claude-code-automation
Version:
π Generic project automation system with anti-compaction protection and recovery capabilities. Automatically detects project type (React, Node.js, Python, Rust, Go, Java) and provides intelligent analysis. Claude Code optimized - run 'welcome' after inst
500 lines (423 loc) β’ 21.2 kB
JavaScript
/**
* Code Automation - Main Entry Point
* Advanced anti-compaction system with perfect recovery
*/
const fs = require('fs').promises;
const path = require('path');
const { program } = require('commander');
// Import all automation modules
const ContextPreservationEngine = require('./context-preservation');
const AutoRecovery = require('./auto-recovery');
const ContextAnalysis = require('./context-analysis');
const LivePreservationEngine = require('./live-preservation-engine');
const PerfectRecoverySystem = require('./perfect-recovery-system');
const AntiTruncationGuard = require('./anti-truncation-guard');
const CompactionRiskAnalyzer = require('./compaction-risk-analyzer');
const DevelopmentSessionTracker = require('./development-session-tracker');
class ClaudeCodeAutomation {
constructor() {
// Read version dynamically from package.json to avoid hardcoding issues
const packageJson = require('../package.json');
this.version = packageJson.version;
this.projectRoot = process.cwd();
this.automationDir = path.join(this.projectRoot, '.automation');
this.docsDir = path.join(this.projectRoot, '.automation', 'state');
}
/**
* Install automation system in current project
*/
async install() {
// Handle global installation case
if (this.isGlobalInstallation()) {
console.log(`β
Code Automation v${this.version} installed globally!`);
this.printGlobalUsageInstructions();
return;
}
console.log(`π Installing Code Automation v${this.version}...`);
try {
// Verify we're in a valid project directory or create package.json
if (!await this.isValidProjectDirectory()) {
console.log('π¦ No package.json found. Creating basic package.json...');
await this.createBasicPackageJson();
}
// Create directory structure
await this.createDirectoryStructure();
// Copy automation files
await this.copyAutomationFiles();
// Setup package.json scripts
await this.setupPackageScripts();
// Create initial configuration
await this.createConfiguration();
// Initialize context preservation
await this.initializePreservation();
console.log(`β
Code Automation v${this.version} installed successfully!`);
this.printUsageInstructions();
} catch (error) {
console.error('β Installation failed:', error.message);
process.exit(1);
}
}
/**
* Create necessary directory structure
*/
async createDirectoryStructure() {
const dirs = [
'.automation',
'.automation/state',
'.automation/recovery',
'.automation/backups'
];
for (const dir of dirs) {
await fs.mkdir(path.join(this.projectRoot, dir), { recursive: true });
}
}
/**
* Copy automation files to project
*/
async copyAutomationFiles() {
const automationFiles = [
'context-preservation.js',
'auto-recovery.js',
'context-analysis.js',
'daily-automation-cycle.js'
];
// Use templates directory for latest fixed versions
const sourceDir = path.join(__dirname, '../templates/automation');
console.log(`π¦ Copying automation files from: ${sourceDir}`);
console.log(`π¦ Target directory: ${this.automationDir}`);
let successCount = 0;
for (const file of automationFiles) {
const source = path.join(sourceDir, file);
const target = path.join(this.automationDir, file);
try {
// Check if source file exists first
await fs.access(source);
const content = await fs.readFile(source, 'utf8');
await fs.writeFile(target, content);
console.log(`β
Copied: ${file}`);
successCount++;
} catch (error) {
console.error(`β Failed to copy ${file}: ${error.message}`);
// If we can't copy files, this is a critical error
if (error.code === 'ENOENT') {
console.error(`π Source file not found: ${source}`);
console.error(`π‘ This suggests a package installation issue.`);
}
}
}
if (successCount === 0) {
throw new Error(`Failed to copy any automation files. Package may be corrupted.`);
} else if (successCount < automationFiles.length) {
console.warn(`β οΈ Warning: Only ${successCount}/${automationFiles.length} files copied successfully.`);
} else {
console.log(`β
All ${successCount} automation files copied successfully.`);
}
}
/**
* Setup package.json scripts
*/
async setupPackageScripts() {
const packagePath = path.join(this.projectRoot, 'package.json');
try {
const packageContent = await fs.readFile(packagePath, 'utf8');
const packageJson = JSON.parse(packageContent);
if (!packageJson.scripts) {
packageJson.scripts = {};
}
// Add automation scripts (hidden directory)
packageJson.scripts['automation:preserve'] = 'node .automation/context-preservation.js';
packageJson.scripts['automation:recover'] = 'node .automation/auto-recovery.js';
packageJson.scripts['automation:analyze'] = 'node .automation/context-analysis.js';
packageJson.scripts['automation:daily'] = 'node .automation/daily-automation-cycle.js';
packageJson.scripts['automation:guard'] = 'node .automation/anti-truncation-guard.js';
await fs.writeFile(packagePath, JSON.stringify(packageJson, null, 2));
} catch (error) {
console.warn('β οΈ Could not update package.json scripts');
}
}
/**
* Create initial configuration
*/
async createConfiguration() {
const config = {
version: '2.0.0',
enabled: true,
features: {
contextPreservation: true,
antiTruncation: true,
livePreservation: true,
perfectRecovery: true,
riskAnalysis: true,
sessionTracking: true
},
settings: {
preservationInterval: 1800000, // 30 minutes
maxBackups: 50,
compressionEnabled: true,
verboseLogging: false
}
};
await fs.writeFile(
path.join(this.automationDir, 'config.json'),
JSON.stringify(config, null, 2)
);
}
/**
* Initialize context preservation (only for project installation)
*/
async initializePreservation() {
// Skip during global installation
if (this.isGlobalInstallation()) {
console.log('βΉοΈ Global installation complete. Use "code-automation install" in your project.');
return;
}
try {
const preservation = new ContextPreservationEngine();
await preservation.preserveCurrentState();
} catch (error) {
// Silently skip - initial preservation is optional during installation
}
}
/**
* Check if this is a global installation context (vs project setup)
*/
isGlobalInstallation() {
// During 'install' command, we're always setting up a project
// This method should check if we're being called during npm install (not user setup)
return false; // Always allow project setup when user runs 'install' command
}
/**
* Check if current directory is a valid project directory
*/
async isValidProjectDirectory() {
try {
// Check for package.json
await fs.access(path.join(this.projectRoot, 'package.json'));
return true;
} catch (error) {
// Check for git repository
try {
await fs.access(path.join(this.projectRoot, '.git'));
return true;
} catch (gitError) {
return false;
}
}
}
/**
* Create basic package.json if it doesn't exist
*/
async createBasicPackageJson() {
const packagePath = path.join(this.projectRoot, 'package.json');
// Check if package.json already exists
try {
await fs.access(packagePath);
console.log('π¦ Found existing package.json');
return; // Don't overwrite existing package.json
} catch (error) {
// File doesn't exist, create it
const projectName = path.basename(this.projectRoot);
const basicPackage = {
"name": projectName,
"version": "1.0.0",
"description": "Project with Code Automation",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
};
await fs.writeFile(packagePath, JSON.stringify(basicPackage, null, 2));
console.log('β
Created basic package.json');
}
}
/**
* Print usage instructions for project installation
*/
printUsageInstructions() {
console.log('\nπ― Quick Start Guide:');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β Basic Commands β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€');
console.log('β npm run automation:preserve - Save current state β');
console.log('β npm run automation:analyze - Check project healthβ');
console.log('β npm run automation:recover - Restore from backup β');
console.log('β npm run automation:daily - Run full cycle β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('\nπ‘οΈ Anti-Compaction Protection:');
console.log('β
Auto-saves every 30 minutes');
console.log('β
Perfect recovery guarantee');
console.log('β
Real-time context monitoring');
console.log('\nπ Next Steps:');
console.log('1. Start protection: npm run automation:preserve');
console.log('2. Continue your work normally');
console.log('3. If context is lost: npm run automation:recover');
console.log('\nπ Files created:');
console.log('β’ scripts/automation/ - Automation scripts');
console.log('β’ docs/state/ - Project backups');
console.log('β’ docs/recovery/ - Recovery instructions');
console.log('\nπ‘ Pro Tip: Run "npm run automation:daily" for maintenance');
}
/**
* Print usage instructions for global installation
*/
printGlobalUsageInstructions() {
console.log('\nπ Global Installation Complete!');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β Setup Your Project β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€');
console.log('β 1. cd your-project β');
console.log('β 2. code-automation install β');
console.log('β 3. npm run automation:preserve β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('\nβ‘ Global Commands Available:');
console.log('β’ code-automation install - Setup current project');
console.log('β’ preserve - Quick context save');
console.log('β’ recover - Emergency recovery');
console.log('β’ analyze - Project health check');
console.log('\nπ― Common Workflows:');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β New Project Setup: β');
console.log('β cd my-new-project β');
console.log('β code-automation install β');
console.log('β β');
console.log('β Existing Project: β');
console.log('β cd existing-project β');
console.log('β preserve β');
console.log('β β');
console.log('β Lost Context? β');
console.log('β recover β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('\nπ§ Need Help?');
console.log('β’ code-automation --help - Show all commands');
console.log('β’ code-automation --version - Check version');
console.log('\nπ‘ Pro Tip: Works with any project type (React, Node.js, Python, etc.)');
}
/**
* Show welcome message if this is likely first use
*/
showWelcomeIfNeeded() {
// Don't show welcome here - it's handled by the binary
}
/**
* Show detailed help information
*/
showDetailedHelp() {
console.log(`\nπ― Code Automation v${this.version} - Complete Guide`);
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('\nπ¦ Installation:');
console.log(' npm install -g claude-code-automation # Global install');
console.log(' npm install claude-code-automation --save-dev # Project install');
console.log('\nπ Quick Setup:');
console.log(' cd your-project');
console.log(' code-automation install # Setup project');
console.log(' npm run automation:preserve # Start protection');
console.log('\nβ‘ Available Commands:');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β Command β Description β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€');
console.log('β code-automation install β Setup current project β');
console.log('β preserve β Save project state β');
console.log('β recover β Restore from backup β');
console.log('β analyze β Check project health β');
console.log('β code-automation help β Show this guide β');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('\nπ― Use Cases:');
console.log('β’ Before long coding sessions');
console.log('β’ When working on complex features');
console.log('β’ After major architectural changes');
console.log('β’ When switching between tasks');
console.log('\nπ‘οΈ What It Protects:');
console.log('β
Project structure and files');
console.log('β
Development progress');
console.log('β
Architecture decisions');
console.log('β
Context and conversations');
console.log('\nπ§ Troubleshooting:');
console.log('β’ Context lost? β recover');
console.log('β’ Need project status? β analyze');
console.log('β’ Setup issues? β code-automation install');
console.log('\nπ Learn More:');
console.log('β’ NPM: https://npmjs.com/package/claude-code-automation');
}
/**
* Command line interface
*/
setupCLI() {
// Show welcome message on first CLI interaction
this.showWelcomeIfNeeded();
program
.name('code-automation')
.description(`Code Automation v${this.version} - Advanced anti-compaction system`)
.version(this.version)
.option('-v, --verbose', 'Enable verbose output')
.option('-q, --quiet', 'Suppress non-essential output');
program
.command('install')
.description('Install automation system in current project')
.action(() => this.install());
program
.command('help')
.description('Show detailed usage instructions')
.action(() => this.showDetailedHelp());
program
.command('preserve')
.description('Preserve current project context')
.action(async () => {
const verboseMode = program.opts().verbose;
if (verboseMode) {
console.log('π Starting context preservation in verbose mode...');
}
const preservation = new ContextPreservationEngine();
await preservation.preserveCurrentState();
if (verboseMode) {
console.log('β
Context preservation completed successfully');
}
});
program
.command('recover')
.description('Recover project from latest backup')
.action(async () => {
const verboseMode = program.opts().verbose;
if (verboseMode) {
console.log('π Starting project recovery in verbose mode...');
}
const recovery = new AutoRecovery();
await recovery.recoverFromLatest();
if (verboseMode) {
console.log('β
Project recovery completed successfully');
}
});
program
.command('analyze')
.description('Analyze current project state')
.action(async () => {
const verboseMode = program.opts().verbose;
if (verboseMode) {
console.log('π Starting project analysis in verbose mode...');
}
const analysis = new ContextAnalysis();
await analysis.analyzeCurrentContext();
if (verboseMode) {
console.log('β
Project analysis completed successfully');
}
});
program
.command('guard')
.description('Start anti-truncation guard')
.action(async () => {
const guard = new AntiTruncationGuard();
await guard.startGuarding();
});
program.parse();
}
}
// Export for use as module
module.exports = ClaudeCodeAutomation;
// Run CLI if called directly
if (require.main === module) {
const automation = new ClaudeCodeAutomation();
automation.setupCLI();
}