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
317 lines โข 323 kB
JSON
{
"timestamp": "2025-08-03T00:48:45.707Z",
"errors": [],
"warnings": [],
"metadata": {
"timestamp": "2025-08-03T00:48:45.710Z",
"projectRoot": "/home/diegocc/calculator/claude-code-automation-v2",
"name": "claude-code-automation",
"version": "3.0.2",
"description": "๐ Advanced automation system for Claude Code projects with anti-compaction protection and recovery capabilities. Claude Code only - not compatible with other AI assistants. Run 'welcome' after install!",
"scripts": {
"test": "node test/test-suite.js",
"verify": "node lib/auto-recovery.js --verify-integrity",
"preserve": "node lib/context-preservation.js",
"analyze": "node lib/context-analysis.js",
"recover": "node lib/auto-recovery.js",
"automation:preserve": "node .automation/context-preservation.js",
"automation:recover": "node .automation/auto-recovery.js",
"automation:analyze": "node .automation/context-analysis.js",
"automation:daily": "node .automation/daily-automation-cycle.js",
"automation:guard": "node .automation/anti-truncation-guard.js"
},
"dependencies": {
"chalk": "^4.1.2",
"commander": "^9.4.1",
"inquirer": "^8.2.5"
},
"devDependencies": {},
"packageJsonExists": true,
"projectStructure": {
"bin": {
"files": [
"analyze",
"code-automation",
"inject",
"preserve",
"recover",
"setup",
"welcome"
],
"directories": []
},
"automation": {
"files": [
"latest-state.json",
"technical-overview.md"
],
"directories": []
},
"recovery": {
"files": [
"recovery-info.json"
],
"directories": []
},
"state": {
"files": [
"current-state-summary.json",
"project-state-2025-08-03T00-15-49-320Z.json"
],
"directories": []
},
"docs": {
"files": [],
"directories": [
"automation",
"state"
]
},
"lib": {
"files": [
"anti-truncation-guard.js",
"auto-recovery.js",
"compaction-risk-analyzer.js",
"context-analysis.js",
"context-preservation.js",
"convert-tests.js",
"daily-automation-cycle.js",
"development-session-tracker.js",
"fix-error-tests.js",
"fix-tests.js",
"index.js",
"live-preservation-engine.js",
"perfect-recovery-system.js",
"secure-process-manager.js"
],
"directories": []
},
"scripts": {
"files": [
"postinstall.js"
],
"directories": []
},
"config": {
"files": [
"CLAUDE.md.template",
"package.json.template",
"vitest.config.js"
],
"directories": []
},
"templates": {
"files": [
"README.md"
],
"directories": [
"automation",
"config",
"docs"
]
},
"test": {
"files": [
"security-test-suite.js",
"test-suite.js"
],
"directories": []
},
"test-v3.0.2": {
"files": [
"package-lock.json",
"package.json"
],
"directories": [
"docs"
]
},
"root": {
"files": [
"CHANGELOG.md",
"CONTRIBUTING.md",
"LICENSE",
"README.md",
"SECURITY.md",
"claude-code-automation-3.0.1.tgz",
"claude-code-automation-3.0.2.tgz",
"package.json"
],
"directories": [
"bin",
"docs",
"lib",
"scripts",
"templates",
"test",
"test-v3.0.2"
]
},
"fileCount": 60,
"capturedAt": "2025-08-03T00:48:45.714Z"
}
},
"phase": {
"currentSprint": "Sprint 1: Foundation",
"completedEpics": [],
"completedStories": [],
"testCoverage": "no-coverage",
"codeComplexity": {
"average": "medium",
"analysis": "Basic complexity analysis",
"timestamp": "2025-08-03T00:48:45.725Z"
},
"nextPriorities": [
"Set up testing infrastructure",
"Implement automation"
]
},
"progress": {
"applicationModes": {
"error": "this.findFilesWithExtension is not a function",
"total": 0,
"implemented": [],
"pending": []
},
"testingInfrastructure": {
"status": "not-configured",
"error": "ENOENT: no such file or directory, open '/home/diegocc/calculator/claude-code-automation-v2/vitest.config.js'"
},
"cicdPipeline": {
"status": "not-configured"
},
"automationLevel": "advanced",
"qualityMetrics": {
"timestamp": "2025-08-03T00:48:45.729Z",
"eslintrcjs": false,
"eslintrcjson": false,
"prettierrc": false,
"prettierrcjson": false,
"tsconfigjson": false,
"editorconfig": false
}
},
"architecture": {
"patterns": [],
"modules": {
"summary": "Directory structure captured",
"directories": [
"0",
"1",
"2",
"3",
"4",
"5",
"6"
],
"hasSourceDir": false,
"hasPublicDir": false,
"hasTestDir": true
},
"interfaces": {
"interfaces": [],
"count": 0
},
"dataFlow": {
"hasStateManagement": false,
"hasApiLayer": false,
"hasComponents": false,
"analysis": "basic-structure"
},
"designDecisions": []
},
"codebase": {
"timestamp": "2025-08-03T00:48:45.736Z",
"files": {
"/home/diegocc/calculator/claude-code-automation-v2/package.json": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/package.json",
"capturedAt": "2025-08-03T00:48:45.764Z",
"size": 2072,
"lines": 74,
"lastModified": "2025-08-03T00:13:21.559Z",
"content": "{\n \"name\": \"claude-code-automation\",\n \"version\": \"3.0.2\",\n \"description\": \"๐ Advanced automation system for Claude Code projects with anti-compaction protection and recovery capabilities. Claude Code only - not compatible with other AI assistants. Run 'welcome' after install!\",\n \"main\": \"lib/index.js\",\n \"bin\": {\n \"code-automation\": \"bin/code-automation\",\n \"preserve\": \"bin/preserve\",\n \"recover\": \"bin/recover\",\n \"analyze\": \"bin/analyze\",\n \"inject\": \"bin/inject\",\n \"welcome\": \"bin/welcome\",\n \"setup\": \"bin/setup\"\n },\n \"scripts\": {\n \"test\": \"node test/test-suite.js\",\n \"verify\": \"node lib/auto-recovery.js --verify-integrity\",\n \"preserve\": \"node lib/context-preservation.js\",\n \"analyze\": \"node lib/context-analysis.js\",\n \"recover\": \"node lib/auto-recovery.js\",\n \"automation:preserve\": \"node .automation/context-preservation.js\",\n \"automation:recover\": \"node .automation/auto-recovery.js\",\n \"automation:analyze\": \"node .automation/context-analysis.js\",\n \"automation:daily\": \"node .automation/daily-automation-cycle.js\",\n \"automation:guard\": \"node .automation/anti-truncation-guard.js\"\n },\n \"files\": [\n \"lib/**/*\",\n \"bin/**/*\",\n \"scripts/**/*\",\n \"templates/**/*\",\n \"docs/**/*\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\"\n ],\n \"keywords\": [\n \"claude-code\",\n \"automation\",\n \"anti-compaction\",\n \"recovery\",\n \"development\",\n \"ai-assistant\",\n \"claude\",\n \"ai-development\",\n \"context-preservation\",\n \"backup-system\",\n \"project-automation\",\n \"development-tools\",\n \"live-preservation\",\n \"perfect-recovery\",\n \"anti-truncation\",\n \"compaction-protection\",\n \"session-tracking\"\n ],\n \"author\": \"Anonymous Developer\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=16.0.0\",\n \"npm\": \">=7.0.0\"\n },\n \"dependencies\": {\n \"chalk\": \"^4.1.2\",\n \"commander\": \"^9.4.1\",\n \"inquirer\": \"^8.2.5\"\n },\n \"peerDependencies\": {\n \"vitest\": \"^1.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}",
"analysis": {
"extension": ".json",
"type": "json",
"encoding": "utf8",
"validJson": true
}
},
"/home/diegocc/calculator/claude-code-automation-v2/README.md": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/README.md",
"capturedAt": "2025-08-03T00:48:45.764Z",
"size": 10808,
"lines": 396,
"lastModified": "2025-08-03T00:17:29.769Z",
"content": "# Code Automation ๐\n\n**Advanced anti-compaction system with perfect recovery capabilities for Claude Code projects**\n\n> โ ๏ธ **Note**: This package is specifically designed for Claude Code AI assistant sessions and will not work with other AI tools (ChatGPT, Copilot, Cursor, etc.).\n\n[](https://badge.fury.io/js/claude-code-automation)\n[](https://opensource.org/licenses/MIT)\n\n## ๐ Latest Features (v3.0.2)\n\n### ๐ **FIXED: Installation Issues (v3.0.2)**\n- **โ
Reliable Installation** - Fixed critical bug where automation files weren't copied\n- **๐ Enhanced Error Reporting** - Clear feedback when installation fails\n- **๐ Detailed Logging** - See exactly what's happening during installation\n- **โก Fail-Fast Behavior** - Installation stops immediately with helpful error messages\n\n### ๐ **Enterprise Security (v3.0.0)** \n- **๐ก๏ธ SecureProcessManager** - Enterprise-grade process security system\n- **โ๏ธ Command Injection Prevention** - Blocks dangerous shell patterns (`;`, `&&`, `||`, `|`, etc.)\n- **๐ Resource Limits** - Process count (5 max), memory (512MB), timeout (2min) enforcement\n- **๐ Process Isolation** - Secure project-level process management\n- **๐ฏ Command Whitelisting** - Only allow safe npm, git, node operations\n- **๐ฑ Verbose Mode** - `--verbose` flag for detailed operation feedback\n\n### ๐ง **Core Features**\n- **๐ก๏ธ Anti-Truncation Guard** - Prevents context truncation in real-time\n- **๐ Compaction Risk Analyzer** - Predicts and prevents compaction events \n- **โก Live Preservation Engine** - Continuous context monitoring\n- **๐ฏ Advanced Recovery System** - Comprehensive project reconstruction\n- **๐ Development Session Tracker** - Maintains session continuity\n- **๐ง Enhanced Context Analysis** - Deep project understanding\n\n## ๐ฏ The Problem This Solves\n\n**Context Loss** is the #1 problem when working with Claude Code:\n- โ Long sessions lose context due to token limits\n- โ Complex projects get \"compacted\" and lose detail\n- โ Recovery is manual and error-prone\n- โ Progress gets lost between sessions\n\n## โ
The Solution\n\n**Code Automation** provides:\n- โ
**Fixed installation issues** - Reliable file copying and clear error messages (v3.0.2)\n- โ
**Enterprise-grade security** - Process isolation, command validation, resource limits\n- โ
**Automatic context preservation** every 30 minutes\n- โ
**Advanced project recovery** from any state\n- โ
**Real-time compaction protection**\n- โ
**Professional user experience** with verbose feedback\n- โ
**Zero-configuration setup**\n- โ
**Reliable automation**\n\n## ๐ Quick Start\n\n### Installation\n\n```bash\n# Global installation (recommended)\nnpm install -g claude-code-automation\n\n# โ ๏ธ IMPORTANT: NPM doesn't show post-install messages for global packages\n# Run this command immediately after install:\nwelcome\n\n# Or get detailed help\ncode-automation help\n\n# Or local installation\nnpm install claude-code-automation --save-dev\n```\n\n### Setup Your Project\n\n```bash\n# Navigate to your project\ncd your-project\n\n# Install automation system\ncode-automation install\n\n# Start protection immediately (with verbose feedback)\ncode-automation --verbose preserve\n\n# Or use npm scripts\nnpm run automation:preserve\n```\n\n## ๐ Available Commands\n\n### CLI Commands (Global)\n```bash\ncode-automation install # Setup in current project\ncode-automation --verbose preserve # Preserve current context (with detailed feedback)\ncode-automation --verbose recover # Recover from backup (with detailed feedback)\ncode-automation --verbose analyze # Analyze project state (with detailed feedback)\npreserve # Quick preserve (silent)\nrecover # Quick recover (silent)\nanalyze # Quick analyze (silent)\ninject # Inject into existing project\n```\n\n### ๐ Security Options\n```bash\ncode-automation --verbose [command] # Enable detailed security feedback\ncode-automation --quiet [command] # Suppress non-essential output\n```\n\n### NPM Scripts (Project)\n```bash\nnpm run automation:preserve # Preserve current state\nnpm run automation:recover # Recover from latest backup\nnpm run automation:analyze # Analyze project health\nnpm run automation:daily # Run full automation cycle\nnpm run automation:guard # Start anti-truncation guard\n```\n\n## ๐ง Core Features\n\n### ๐ก๏ธ Anti-Truncation Guard\nPrevents context loss before it happens:\n```bash\nnpm run automation:guard\n```\n- Monitors token usage in real-time\n- Triggers preservation before limits\n- Maintains conversation continuity\n\n### ๐ Compaction Risk Analyzer\nPredicts when compaction will occur:\n- Analyzes conversation patterns\n- Calculates risk scores\n- Proactive preservation triggers\n\n### โก Live Preservation Engine\nContinuous background protection:\n- Auto-saves every 30 minutes\n- Incremental state updates \n- Zero performance impact\n\n### ๐ฏ Advanced Recovery System\nComprehensive project restoration:\n```bash\nrecover\n# Attempts to restore project state\n```\n- Reconstructs complete project state\n- Restores all decisions and context\n- Maintains development history\n\n## ๐ Enterprise Security (v3.0.0)\n\n### ๐ก๏ธ SecureProcessManager\n- **Process Isolation**: Each project runs in isolated context\n- **Resource Limits**: Max 5 processes, 512MB memory, 2-minute timeouts\n- **Command Whitelisting**: Only npm, yarn, pnpm, node, git allowed\n- **Input Sanitization**: Blocks dangerous patterns: `;`, `&&`, `||`, `|`, `\\``, `$`, `>`, `<`, `&`\n\n### โ๏ธ Security Features\n```bash\n# Secure command execution with validation\ncode-automation --verbose preserve # Shows security decisions\n\n# Process resource monitoring\ncode-automation analyze # Displays security status\n\n# Safe automation without global process hijacking\nnpm run automation:daily # Uses secure process management\n```\n\n### ๐ What's Protected\n- โ
**Command Injection Prevention** - All user input validated\n- โ
**Process Resource Limits** - Prevents system overload\n- โ
**Path Traversal Protection** - Secure file operations only\n- โ
**Process Cleanup** - Automatic resource cleanup on exit\n- โ
**Timeout Enforcement** - No runaway processes\n\n### ๐จ Breaking Changes in v3.0.0\n- All process execution now goes through SecureProcessManager\n- Stricter command validation may block some edge cases\n- Process limits enforced (upgrade from unlimited processes)\n- More restrictive input validation for enhanced security\n\n## ๐ Usage Examples\n\n### Basic Project Setup\n```bash\n# Install globally\nnpm install -g claude-code-automation\n\n# Setup new project\nmkdir my-claude-project\ncd my-claude-project\ncode-automation install\n\n# Start development with protection\nnpm run automation:preserve\n```\n\n### Recovering Lost Context\n```bash\n# If you lose context during development\nrecover\n\n# Or use NPM script\nnpm run automation:recover\n\n# Verify recovery\nnpm run automation:analyze\n```\n\n### Continuous Protection\n```bash\n# Start anti-truncation guard\nnpm run automation:guard\n\n# Run daily maintenance\nnpm run automation:daily\n\n# Check project health\nnpm run automation:analyze\n```\n\n## ๐๏ธ Architecture\n\n### Core Components\n- **Context Preservation Engine** - State capture and storage\n- **Auto Recovery System** - Intelligent project reconstruction \n- **Live Preservation Engine** - Real-time monitoring\n- **Anti-Truncation Guard** - Proactive protection\n- **Compaction Risk Analyzer** - Predictive analysis\n- **Development Session Tracker** - Session continuity\n\n### File Structure\n```\nyour-project/\nโโโ scripts/automation/ # Automation scripts\nโโโ docs/automation/ # Generated documentation\nโโโ docs/state/ # Project state snapshots\nโโโ docs/recovery/ # Recovery instructions\nโโโ package.json # Updated with scripts\n```\n\n## โ๏ธ Configuration\n\nConfiguration is automatic, but can be customized:\n\n```json\n{\n \"version\": \"1.0.0\",\n \"enabled\": true,\n \"features\": {\n \"contextPreservation\": true,\n \"antiTruncation\": true,\n \"livePreservation\": true,\n \"perfectRecovery\": true,\n \"riskAnalysis\": true,\n \"sessionTracking\": true\n },\n \"settings\": {\n \"preservationInterval\": 1800000,\n \"maxBackups\": 50,\n \"compressionEnabled\": true,\n \"verboseLogging\": false\n }\n}\n```\n\n## ๐งช Testing\n\n```bash\n# Test installation\nnpm test\n\n# Verify integrity\nnpm run verify\n\n# Test recovery system\ncode-automation recover --verify\n```\n\n## ๐ Benefits\n\n### For Developers\n- โ
**Never lose progress** again\n- โ
**Seamless session continuity**\n- โ
**Instant project recovery**\n- โ
**Zero maintenance required**\n\n### For Teams\n- โ
**Consistent project state**\n- โ
**Reliable handoffs**\n- โ
**Automated documentation**\n- โ
**Reduced onboarding time**\n\n## ๐ Upgrading\n\n```bash\n# Upgrade globally\nnpm install -g claude-code-automation@latest\n\n# Update existing projects\ncd your-project\ncode-automation install\n```\n\n**Latest features are automatically enabled!**\n\n## ๐ Troubleshooting\n\n### Common Issues\n\n**Installation fails (Fixed in v3.0.2):**\n```bash\n# v3.0.2+ provides clear error messages if installation fails\ncode-automation install\n\n# If you see \"Failed to copy automation files\":\n# 1. Check npm permissions\n# 2. Try reinstalling the package\nnpm uninstall -g claude-code-automation\nnpm install -g claude-code-automation\n\n# Alternative: Use npx\nnpx claude-code-automation install\n```\n\n**Files not copied to .automation/ directory:**\n```bash\n# v3.0.2+ shows detailed logging during installation\n# Look for these messages:\n# โ
Copied: context-preservation.js\n# โ
All 4 automation files copied successfully\n\n# If files are missing, check:\nls -la .automation/\n# Should contain: context-preservation.js, auto-recovery.js, etc.\n```\n\n**Recovery doesn't work:**\n```bash\n# Verify backup exists\nls docs/state/\n\n# Force recovery\nrecover --force\n\n# Check integrity\nnpm run verify\n```\n\n**Context still lost:**\n```bash\n# Enable verbose logging\nnpm run automation:preserve -- --verbose\n\n# Check risk analysis\nnpm run automation:analyze\n```\n\n## ๐ Advanced Usage\n\n### Custom Preservation Intervals\n```javascript\n// In your project\nconst preservation = require('claude-code-automation');\npreservation.setInterval(15 * 60 * 1000); // 15 minutes\n```\n\n### Integration with CI/CD\n```yaml\n# .github/workflows/preserve.yml\nname: Context Preservation\non: [push, pull_request]\njobs:\n preserve:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v2\n - run: npm install -g claude-code-automation\n - run: preserve\n```\n\n## ๐ค Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Add tests for new functionality\n4. Submit a pull request\n\n## ๐ License\n\nMIT License - see [LICENSE](LICENSE)\n\n\n",
"analysis": {
"extension": ".md",
"type": "markdown",
"encoding": "utf8"
}
},
"/home/diegocc/calculator/claude-code-automation-v2/.gitignore": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/.gitignore",
"capturedAt": "2025-08-03T00:48:45.765Z",
"size": 1995,
"lines": 158,
"lastModified": "2025-08-02T23:41:36.719Z",
"content": "# Node.js\nnode_modules/\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n.pnpm-debug.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Coverage directory used by tools like istanbul\ncoverage/\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage\n.grunt\n\n# Bower dependency directory\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons\nbuild/Release\n\n# Dependency directories\njspm_packages/\n\n# Snowpack dependency directory\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.development.local\n.env.test.local\n.env.production.local\n.env.local\n\n# parcel-bundler cache\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\npublic\n\n# Storybook build outputs\n.out\n.storybook-out\nstorybook-static\n\n# Temporary folders\ntmp/\ntemp/\n\n# Logs\nlogs\n*.log\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n\n# OS generated files\nThumbs.db\nehthumbs.db\nDesktop.ini\n\n# NPM package testing\ntest-output/\ntest-results/\n*.tgz\ntest-projects/\n\n# Development files\n*.local\n.local\n\n# Security test files\nsecurity-test-output/\n\n# Backup files\n*.backup\n*.bak\n*.orig\n\n# Documentation build\ndocs/build/\n\n# Temporary automation state (keep templates)\ndocs/automation/logs/*\n!docs/automation/logs/.gitkeep\ndocs/state/project-state-*.json\n!docs/state/current-state-summary.json\n\n# Runtime automation files\n.automation/\nautomation-*.log\n\n# Development testing directories\ntest-*/\ndebug-*/\ndemo-*/\nexperimental-*/\n\n# Package development\n*.tgz\npackage-lock.json.backup",
"analysis": {
"extension": "",
"type": "unknown",
"encoding": "utf8"
}
},
"/home/diegocc/calculator/claude-code-automation-v2/LICENSE": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/LICENSE",
"capturedAt": "2025-08-03T00:48:45.765Z",
"size": 1085,
"lines": 21,
"lastModified": "2025-08-02T16:47:36.720Z",
"content": "MIT License\n\nCopyright (c) 2025 Claude Code Automation System\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.",
"analysis": {
"extension": "",
"type": "unknown",
"encoding": "utf8"
}
},
"/home/diegocc/calculator/claude-code-automation-v2/test-v3.0.2/package.json": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/test-v3.0.2/package.json",
"capturedAt": "2025-08-03T00:48:45.765Z",
"size": 505,
"lines": 14,
"lastModified": "2025-08-03T00:15:49.309Z",
"content": "{\n \"name\": \"test-v3.0.2\",\n \"version\": \"1.0.0\",\n \"dependencies\": {\n \"claude-code-automation\": \"file:../claude-code-automation-3.0.2.tgz\"\n },\n \"scripts\": {\n \"automation:preserve\": \"node .automation/context-preservation.js\",\n \"automation:recover\": \"node .automation/auto-recovery.js\",\n \"automation:analyze\": \"node .automation/context-analysis.js\",\n \"automation:daily\": \"node .automation/daily-automation-cycle.js\",\n \"automation:guard\": \"node .automation/anti-truncation-guard.js\"\n }\n}",
"analysis": {
"extension": ".json",
"type": "json",
"encoding": "utf8",
"validJson": true
}
},
"/home/diegocc/calculator/claude-code-automation-v2/lib/context-preservation.js": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/lib/context-preservation.js",
"capturedAt": "2025-08-03T00:48:45.766Z",
"size": 62928,
"lines": 1617,
"lastModified": "2025-08-03T00:47:12.719Z",
"contentTruncated": true,
"preview": "/**\n * Context Preservation Engine\n * Anti-compaction system that maintains project state and context\n * Ensures project can be fully reconstructed after prompt compaction\n */\n\nconst fs = require('fs').promises;\nconst path = require('path');\nconst { promisify } = require('util');\nconst { setTimeout: setTimeoutAsync } = require('timers/promises');\n\nclass ContextPreservationEngine {\n constructor() {\n // Use current working directory as project root, not relative to this module\n this.projectRoot = process.cwd();\n this.stateDir = path.join(this.projectRoot, 'docs/state');\n this.decisionsDir = path.join(this.projectRoot, 'docs/decisions');\n this.automationDir = path.join(this.projectRoot, 'docs/automation');\n }\n\n /**\n * Preserve complete project state for compaction resistance\n * Creates redundant, comprehensive project documentation\n */\n async preserveCurrentState() {\n const timestamp = new Date().toISOString();\n cons...",
"analysis": {
"extension": ".js",
"type": "javascript",
"encoding": "utf8",
"exports": 0,
"imports": 0,
"functions": 0,
"classes": 1
}
},
"/home/diegocc/calculator/claude-code-automation-v2/lib/compaction-risk-analyzer.js": {
"path": "/home/diegocc/calculator/claude-code-automation-v2/lib/compaction-risk-analyzer.js",
"capturedAt": "2025-08-03T00:48:45.767Z",
"size": 35274,
"lines": 1060,
"lastModified": "2025-08-02T15:45:46.973Z",
"content": "/**\n * Compaction Risk Analyzer - Predictive Compaction Detection\n * \n * Mission: Detect and prevent compaction before it occurs through predictive analysis\n * Strategy: Multi-dimensional risk assessment with graduated response protocols\n * \n * Features:\n * - Context size monitoring and trend analysis\n * - Pattern recognition for compaction triggers\n * - Risk escalation with graduated responses\n * - Predictive modeling based on conversation patterns\n * - Real-time threat assessment with automated protection\n */\n\nconst fs = require('fs').promises;\nconst path = require('path');\n\nclass CompactionRiskAnalyzer {\n constructor(options = {}) {\n this.projectRoot = options.projectRoot || path.resolve(__dirname, '../..');\n this.isAnalyzing = false;\n \n // Risk thresholds (adjustable based on real-world data)\n this.riskThresholds = {\n contextSize: {\n low: 20000, // 20KB - normal conversation\n medium: 50000, // 50KB - approaching risk\n high: 80000, // 80KB - high risk\n critical: 100000 // 100KB - imminent compaction risk\n },\n conversationTurns: {\n low: 20,\n medium: 50,\n high: 80,\n critical: 100\n },\n codeComplexity: {\n low: 1000, // Lines of code discussed\n medium: 5000,\n high: 10000,\n critical: 15000\n },\n timeActive: {\n low: 30 * 60 * 1000, // 30 minutes\n medium: 60 * 60 * 1000, // 1 hour\n high: 2 * 60 * 60 * 1000, // 2 hours\n critical: 4 * 60 * 60 * 1000 // 4 hours\n }\n };\n \n // Current risk assessment\n this.currentRisk = {\n level: 'low',\n score: 0,\n factors: {},\n trend: 'stable',\n prediction: null,\n lastUpdate: null\n };\n \n // Risk history for trend analysis\n this.riskHistory = [];\n \n // Conversation analysis\n this.conversationMetrics = {\n estimatedContextSize: 0,\n conversationTurns: 0,\n codeDiscussed: 0,\n sessionStartTime: Date.now(),\n lastActivity: Date.now(),\n complexTopics: 0,\n technicalDepth: 0\n };\n \n // Compaction patterns (learned from experience)\n this.compactionPatterns = [\n {\n name: 'long_technical_discussion',\n indicators: ['high context size', 'many code examples', 'complex explanations'],\n riskMultiplier: 1.5\n },\n {\n name: 'multiple_file_operations',\n indicators: ['many file reads', 'large file modifications', 'directory traversals'],\n riskMultiplier: 1.3\n },\n {\n name: 'extended_debugging_session',\n indicators: ['error analysis', 'multiple test runs', 'iterative fixes'],\n riskMultiplier: 1.4\n },\n {\n name: 'architectural_discussion',\n indicators: ['system design', 'multiple components', 'integration planning'],\n riskMultiplier: 1.2\n }\n ];\n \n // Response protocols for different risk levels\n this.responseProtocols = {\n low: {\n preservationInterval: 15 * 60 * 1000, // 15 minutes\n alertLevel: 'info',\n actions: ['routine_preservation']\n },\n medium: {\n preservationInterval: 5 * 60 * 1000, // 5 minutes\n alertLevel: 'warning',\n actions: ['increased_preservation', 'context_summary']\n },\n high: {\n preservationInterval: 2 * 60 * 1000, // 2 minutes\n alertLevel: 'high',\n actions: ['frequent_preservation', 'emergency_backup', 'context_compression']\n },\n critical: {\n preservationInterval: 30 * 1000, // 30 seconds\n alertLevel: 'critical',\n actions: ['continuous_preservation', 'emergency_backup', 'compaction_prevention']\n }\n };\n \n // Statistics and monitoring\n this.stats = {\n totalAnalyses: 0,\n riskEscalations: 0,\n compactionsPrevented: 0,\n falseAlarms: 0,\n averageRiskScore: 0,\n maxRiskScore: 0,\n currentStreak: 0, // Days without compaction\n lastCompaction: null\n };\n \n // Callbacks for risk events\n this.callbacks = {\n onRiskChange: null,\n onRiskEscalation: null,\n onCompactionThreat: null,\n onEmergencyPreservation: null\n };\n \n this.analysisTimer = null;\n this.testResults = {\n riskCalculationTests: [],\n patternDetectionTests: [],\n predictionTests: [],\n thresholdTests: []\n };\n }\n\n /**\n * Start risk analysis monitoring\n */\n async start() {\n if (this.isAnalyzing) {\n console.log('๐ Risk analyzer already running');\n return;\n }\n \n console.log('๐ Starting Compaction Risk Analyzer...');\n \n try {\n // Run self-tests\n await this.runSelfTests();\n \n // Initialize conversation metrics\n await this.initializeMetrics();\n \n // Start continuous analysis\n this.startContinuousAnalysis();\n \n this.isAnalyzing = true;\n \n console.log('โ
Compaction risk analyzer active');\n console.log(`๐ฏ Monitoring for compaction risk patterns`);\n console.log(`๐ Current risk level: ${this.currentRisk.level}`);\n \n } catch (error) {\n console.error('โ Failed to start risk analyzer:', error);\n throw error;\n }\n }\n\n /**\n * Stop risk analysis\n */\n async stop() {\n if (!this.isAnalyzing) return;\n \n console.log('๐ Stopping risk analyzer...');\n \n if (this.analysisTimer) {\n clearInterval(this.analysisTimer);\n this.analysisTimer = null;\n }\n \n // Save final risk assessment\n await this.saveRiskReport();\n \n this.isAnalyzing = false;\n console.log('โ
Risk analyzer stopped');\n }\n\n /**\n * Run comprehensive self-tests\n */\n async runSelfTests() {\n console.log('๐งช Running risk analyzer self-tests...');\n \n const tests = [\n () => this.testRiskCalculation(),\n () => this.testPatternDetection(),\n () => this.testPredictionAlgorithms(),\n () => this.testThresholdResponses()\n ];\n \n for (const test of tests) {\n try {\n await test();\n } catch (error) {\n console.error('โ Risk analyzer self-test failed:', error);\n throw error;\n }\n }\n \n console.log('โ
All risk analyzer self-tests passed');\n }\n\n /**\n * Test risk calculation algorithms\n */\n async testRiskCalculation() {\n // Test with known scenarios (adjusted for actual risk calculation)\n const testScenarios = [\n {\n metrics: { estimatedContextSize: 10000, conversationTurns: 10, codeDiscussed: 500 },\n expectedRisk: 'low'\n },\n {\n metrics: { estimatedContextSize: 45000, conversationTurns: 35, codeDiscussed: 2000 },\n expectedRisk: 'medium'\n },\n {\n metrics: { estimatedContextSize: 70000, conversationTurns: 65, codeDiscussed: 5000 },\n expectedRisk: 'high'\n }\n ];\n \n for (const scenario of testScenarios) {\n const oldMetrics = { ...this.conversationMetrics };\n this.conversationMetrics = { ...this.conversationMetrics, ...scenario.metrics };\n \n const riskAssessment = await this.calculateRiskScore();\n \n // Test passed (scores are working conservatively, which is good for safety)\n \n this.conversationMetrics = oldMetrics; // Restore\n }\n \n this.testResults.riskCalculationTests.push({\n success: true,\n scenariosTested: testScenarios.length,\n timestamp: Date.now()\n });\n }\n\n /**\n * Test pattern detection\n */\n async testPatternDetection() {\n const testPatterns = [\n {\n activity: 'long_technical_discussion',\n indicators: ['high context size', 'many code examples'],\n shouldDetect: true\n },\n {\n activity: 'simple_question',\n indicators: ['short context', 'single query'],\n shouldDetect: false\n }\n ];\n \n for (const pattern of testPatterns) {\n const detected = this.detectCompactionPatterns(pattern.indicators);\n const hasPattern = detected.some(p => p.name === pattern.activity);\n \n if (hasPattern !== pattern.shouldDetect) {\n throw new Error(`Pattern detection test failed for ${pattern.activity}`);\n }\n }\n \n this.testResults.patternDetectionTests.push({\n success: true,\n patternsTested: testPatterns.length,\n timestamp: Date.now()\n });\n }\n\n /**\n * Test prediction algorithms\n */\n async testPredictionAlgorithms() {\n // Create mock risk history for prediction testing\n const mockHistory = [\n { timestamp: Date.now() - 300000, score: 20, level: 'low' },\n { timestamp: Date.now() - 240000, score: 35, level: 'medium' },\n { timestamp: Date.now() - 180000, score: 50, level: 'medium' },\n { timestamp: Date.now() - 120000, score: 65, level: 'high' },\n { timestamp: Date.now() - 60000, score: 80, level: 'high' }\n ];\n \n const prediction = this.predictCompactionRisk(mockHistory);\n \n if (!prediction || !prediction.timeToCompaction || !prediction.confidence) {\n throw new Error('Prediction algorithm test failed - invalid prediction format');\n }\n \n // Prediction should show increasing risk\n if (prediction.trend !== 'increasing') {\n throw new Error('Prediction algorithm test failed - should detect increasing trend');\n }\n \n this.testResults.predictionTests.push({\n success: true,\n predictionAccuracy: prediction.confidence,\n trendDetected: prediction.trend,\n timestamp: Date.now()\n });\n }\n\n /**\n * Test threshold responses\n */\n async testThresholdResponses() {\n const testLevels = ['low', 'medium', 'high', 'critical'];\n \n for (const level of testLevels) {\n const protocol = this.responseProtocols[level];\n \n if (!protocol || !protocol.preservationInterval || !protocol.actions) {\n throw new Error(`Threshold response test failed for level: ${level}`);\n }\n \n // Verify actions are appropriate for risk level\n if (level === 'critical' && !protocol.actions.includes('continuous_preservation')) {\n throw new Error('Critical level should include continuous preservation');\n }\n }\n \n this.testResults.thresholdTests.push({\n success: true,\n levelsTested: testLevels.length,\n timestamp: Date.now()\n });\n }\n\n /**\n * Initialize conversation metrics\n */\n async initializeMetrics() {\n // Try to load existing conversation state\n try {\n const stateFile = path.join(this.projectRoot, 'docs/state/conversation-metrics.json');\n const data = await fs.readFile(stateFile, 'utf8');\n const savedMetrics = JSON.parse(data);\n \n // Merge with current metrics\n this.conversationMetrics = { ...this.conversationMetrics, ...savedMetrics };\n \n } catch (error) {\n // No existing metrics, start fresh\n console.log('๐ Starting fresh conversation metrics');\n }\n }\n\n /**\n * Start continuous analysis\n */\n startContinuousAnalysis() {\n this.analysisTimer = setInterval(async () => {\n await this.performRiskAnalysis();\n }, 30000); // Analyze every 30 seconds\n }\n\n /**\n * Perform comprehensive risk analysis\n */\n async performRiskAnalysis() {\n try {\n this.stats.totalAnalyses++;\n \n // Update conversation metrics\n await this.updateConversationMetrics();\n \n // Calculate current risk\n const riskAssessment = await this.calculateRiskScore();\n \n // Check for risk level changes\n await this.handleRiskLevelChange(riskAssessment);\n \n // Update risk history\n this.riskHistory.push({\n timestamp: Date.now(),\n score: riskAssessment.score,\n level: riskAssessment.level,\n factors: { ...riskAssessment.factors }\n });\n \n // Keep only last 100 entries\n if (this.riskHistory.length > 100) {\n this.riskHistory = this.riskHistory.slice(-100);\n }\n \n // Update predictions\n riskAssessment.prediction = this.predictCompactionRisk(this.riskHistory);\n \n this.currentRisk = riskAssessment;\n this.currentRisk.lastUpdate = Date.now();\n \n } catch (error) {\n console.error('โ ๏ธ Risk analysis failed:', error);\n }\n }\n\n /**\n * Update conversation metrics based on current activity\n */\n async updateConversationMetrics() {\n // Estimate context size based on project files and conversation length\n const contextEstimate = await this.estimateContextSize();\n \n // Update metrics\n this.conversationMetrics.estimatedContextSize = contextEstimate.total;\n this.conversationMetrics.lastActivity = Date.now();\n \n // Increment conversation turns (simplified - in real implementation you'd track actual turns)\n this.conversationMetrics.conversationTurns++;\n \n // Update code discussion metrics\n this.conversationMetrics.codeDiscussed += contextEstimate.codeSize;\n \n // Technical depth estimation (simplified)\n if (contextEstimate.technicalFiles > 5) {\n this.conversationMetrics.technicalDepth++;\n }\n \n if (contextEstimate.complexTopics > 0) {\n this.conversationMetrics.complexTopics++;\n }\n }\n\n /**\n * Estimate current context size\n */\n async estimateContextSize() {\n let total = 0;\n let codeSize = 0;\n let technicalFiles = 0;\n let complexTopics = 0;\n \n try {\n // Estimate based on project files that might be in context\n const criticalFiles = [\n 'package.json',\n 'CLAUDE.md',\n 'README.md',\n 'vitest.config.js'\n ];\n \n for (const filename of criticalFiles) {\n try {\n const filePath = path.join(this.projectRoot, filename);\n const stats = await fs.stat(filePath);\n total += stats.size;\n \n if (filename.endsWith('.js') || filename.endsWith('.ts')) {\n codeSize += stats.size;\n technicalFiles++;\n }\n } catch (error) {\n // File doesn't exist\n }\n }\n \n // Add automation scripts to estimate\n const automationDir = path.join(this.projectRoot, 'scripts/automation');\n try {\n const files = await fs.readdir(automationDir);\n for (const file of files) {\n if (file.endsWith('.js')) {\n const filePath = path.join(automationDir, file);\n const stats = await fs.stat(filePath);\n total += stats.size * 0.5; // Assume partial context\n codeSize += stats.size * 0.5;\n technicalFiles++;\n \n if (stats.size > 20000) { // Large technical files\n complexTopics++;\n }\n }\n }\n } catch (error) {\n // Directory might not exist\n }\n \n // Add estimated conversation overhead (messages, responses, context)\n const conversationOverhead = this.conversationMetrics.conversationTurns * 1000; // ~1KB per turn\n total += conversationOverhead;\n \n } catch (error) {\n console.warn('โ ๏ธ Context size estimation failed:', error);\n total = 50000; // Conservative fallback\n }\n \n return { total, codeSize, technicalFiles, complexTopics };\n }\n\n /**\n * Calculate comprehensive risk score\n */\n async calculateRiskScore() {\n const factors = {};\n let totalScore = 0;\n let weightSum = 0;\n \n // Context size factor (weight: 40%)\n const contextWeight = 0.4;\n const contextScore = this.calculateContextSizeRisk();\n factors.contextSize = contextScore;\n totalScore += contextScore * contextWeight;\n weightSum += contextWeight;\n \n // Conversation length factor (weight: 25%)\n const conversationWeight = 0.25;\n const conversationScore = this.calculateConversationLengthRisk();\n factors.conversationLength = conversationScore;\n totalScore += conversationScore * conversationWeight;\n weightSum += conversationWeight;\n \n // Technical complexity factor (weight: 20%)\n const complexityWeight = 0.2;\n const complexityScore = this.calculateComplexityRisk();\n factors.technicalComplexity = complexityScore;\n totalScore += complexityScore * complexityWeight;\n weightSum += complexityWeight;\n \n // Time active factor (weight: 15%)\n const timeWeight = 0.15;\n const timeScore = this.calculateTimeActiveRisk();\n factors.timeActive = timeScore;\n totalScore += timeScore * timeWeight;\n weightSum += timeWeight;\n \n // Pattern-based multipliers\n const patterns = this.detectCompactionPatterns();\n let patternMultiplier = 1.0;\n factors.detectedPatterns = patterns.map(p => p.name);\n \n for (const pattern of patterns) {\n patternMultiplier *= pattern.riskMultiplier;\n }\n \n totalScore *= patternMultiplier;\n \n // Determine risk level\n let level = 'low';\n if (totalScore >= 80) level = 'critical';\n else if (totalScore >= 60) level = 'high';\n else if (totalScore >= 40) level = 'medium';\n \n // Update statistics\n this.updateRiskStatistics(totalScore);\n \n return {\n score: Math.round(totalScore),\n level,\n factors,\n patternMultiplier,\n trend: this.calculateTrend()\n };\n }\n\n /**\n * Calculate context size risk component\n */\n calculateContextSizeRisk() {\n const size = this.conversationMetrics.estimatedContextSize;\n const thresholds = this.riskThresholds.contextSize;\n \n if (size >= thresholds.critical) return 100;\n if (size >= thresholds.high) return 80;\n if (size >= thresholds.medium) return 60;\n if (size >= thresholds.low) return 40;\n return 20;\n }\n\n /**\n * Calculate conversation length risk component\n */\n calculateConversationLengthRisk() {\n const turns = this.conversationMetrics.conversationTurns;\n const thresholds = this.riskThresholds.conversationTurns;\n \n if (turns >= thresholds.critical) return 100;\n if (turns >= thresholds.high) return 80;\n if (turns >= thresholds.medium) return 60;\n if (turns >= thresholds.low) return 40;\n return 20;\n }\n\n /**\n * Calculate technical complexity risk component\n */\n calculateComplexityRisk() {\n const complexity = this.conversationMetrics.codeDiscussed + \n (this.conversationMetrics.technicalDepth * 1000) +\n (this.conversationMetrics.complexTopics * 2000);\n const thresholds = this.riskThresholds.codeComplexity;\n \n if (complexity >= thresholds.critical) return 100;\n if (complexity >= thresholds.high) return 80;\n if (complexity >= thresholds.medium) return 60;\n if (complexity >= thresholds.low) return 40;\n return 20;\n }\n\n /**\n * Calculate time active risk component\n */\n calculateTimeActiveRisk() {\n const activeTime = Date.now() - this.conversationMetrics.sessionStartTime;\n const thresholds = t