UNPKG

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
#!/usr/bin/env node /** * 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(); }