@triedotdev/mcp 1.0.140 → 1.0.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -7
- package/dist/{chunk-GXF6JOCN.js → chunk-4PAAGLKO.js} +7 -7
- package/dist/{chunk-OQ4A3RDY.js → chunk-N2EDZTKG.js} +6 -359
- package/dist/chunk-N2EDZTKG.js.map +1 -0
- package/dist/{chunk-75ADWWUF.js → chunk-T6PS3MXJ.js} +2 -2
- package/dist/{chunk-AF2APASP.js → chunk-V7AY2EJO.js} +4 -4
- package/dist/{chunk-UOSTOLU7.js → chunk-WMDFK7LI.js} +365 -10
- package/dist/chunk-WMDFK7LI.js.map +1 -0
- package/dist/{chunk-4O2KRHK4.js → chunk-Y2LYDCJD.js} +19 -19
- package/dist/cli/main.js +669 -441
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +9 -9
- package/dist/{codebase-index-5SEOESWM.js → codebase-index-FMIULFZQ.js} +3 -3
- package/dist/{fast-analyzer-AYLZB5TW.js → fast-analyzer-MWKCDRGD.js} +5 -5
- package/dist/{goal-validator-HNXXUCPW.js → goal-validator-DA3JQ6JN.js} +2 -2
- package/dist/index.js +91 -31
- package/dist/index.js.map +1 -1
- package/dist/{trie-agent-M6PHM6UD.js → trie-agent-6A7YBNTQ.js} +6 -6
- package/package.json +1 -1
- package/dist/chunk-OQ4A3RDY.js.map +0 -1
- package/dist/chunk-UOSTOLU7.js.map +0 -1
- /package/dist/{chunk-GXF6JOCN.js.map → chunk-4PAAGLKO.js.map} +0 -0
- /package/dist/{chunk-75ADWWUF.js.map → chunk-T6PS3MXJ.js.map} +0 -0
- /package/dist/{chunk-AF2APASP.js.map → chunk-V7AY2EJO.js.map} +0 -0
- /package/dist/{chunk-4O2KRHK4.js.map → chunk-Y2LYDCJD.js.map} +0 -0
- /package/dist/{codebase-index-5SEOESWM.js.map → codebase-index-FMIULFZQ.js.map} +0 -0
- /package/dist/{fast-analyzer-AYLZB5TW.js.map → fast-analyzer-MWKCDRGD.js.map} +0 -0
- /package/dist/{goal-validator-HNXXUCPW.js.map → goal-validator-DA3JQ6JN.js.map} +0 -0
- /package/dist/{trie-agent-M6PHM6UD.js.map → trie-agent-6A7YBNTQ.js.map} +0 -0
package/dist/cli/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/main.ts","../../src/hooks/install.ts","../../src/hooks/templates.ts","../../src/cli/init.ts","../../src/cli/memory.ts","../../src/cli/check.ts","../../src/cli/pre-push.ts","../../src/cli/auto-fix.ts","../../src/utils/auto-fix-apply.ts","../../src/cli/goal.ts","../../src/cli/tell.ts","../../src/cli/reconcile.ts","../../src/cli/quiet.ts","../../src/cli/ci.ts","../../src/cli/audit.ts","../../src/cli/linear.ts","../../src/cli/gotcha.ts","../../src/cli/learn.ts","../../src/cli/patterns.ts","../../src/patterns/saved-patterns.ts","../../src/cli/sync.ts","../../src/cli/hooks.ts","../../src/cli/ledger.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Trie Agent CLI\n * \n * Main command-line interface for Trie Agent.\n * Provides help, setup, and routes to specific tools.\n * \n * Usage:\n * trie-agent [command] [options]\n */\n\nimport { resolve, join, dirname } from 'path';\nimport { readFileSync, realpathSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport pc from 'picocolors';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { loadProjectInfo, initProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { handleInitCommand } from './init.js';\nimport { handleMemoryCommand } from './memory.js';\nimport { handleCheckpointCommand } from './checkpoint.js';\nimport { handleCheckCommand } from './check.js';\nimport { handlePrePushCommand } from './pre-push.js';\nimport { handleAutoFixCommand } from './auto-fix.js';\nimport { handleGoalCommand, handleHypothesisCommand } from './goal.js';\nimport { handleTellCommand } from './tell.js';\nimport { handleReconcileCommand } from './reconcile.js';\nimport { handleQuietCommand } from './quiet.js';\nimport { handleCISetupCommand } from './ci.js';\nimport { handleAuditCommand } from './audit.js';\nimport { handleLinearCommand } from './linear.js';\nimport { handleGotchaCommand } from './gotcha.js';\nimport { handleLearnCommand } from './learn.js';\nimport { handlePatternsCommand } from './patterns.js';\nimport { createSyncCommand } from './sync.js';\nimport { createLedgerCommand } from './ledger.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { loadContextState } from '../utils/context-state.js';\nimport { getMemoryStats } from '../memory/issue-store.js';\n\n// ES module __dirname equivalent\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst DEFAULT_VERSION = '0.0.0';\n\nfunction getCliVersion(): string {\n try {\n const pkgPath = resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n return typeof pkg.version === 'string' && pkg.version.trim()\n ? pkg.version.trim()\n : DEFAULT_VERSION;\n } catch {\n return DEFAULT_VERSION;\n }\n}\n\n/**\n * Show TRIE ASCII art banner\n */\nfunction showBanner(): void {\n console.log(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗ \n ██║ ██╔══██╗██║██╔══╝ \n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n \n Your decision ledger that travels\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n`);\n}\n\n/**\n * Show the main help message\n */\nfunction showHelp(): void {\n showBanner();\n console.log(`Version: ${getCliVersion()}\n\nUSAGE:\n trie <command> [options]\n\nCOMMANDS:\n init Initialize Trie in your project\n scan Scan codebase once and exit\n watch Start watching (nudges as you code)\n Use screen/tmux to run in background\n check Run risk check before pushing\n \n tell \"<incident>\" Report an incident (\"users can't log in\")\n learn Train Trie from git history or feedback (alias: train)\n ok Mark current pattern as good (alias: learn ok)\n bad Mark current pattern as bad (alias: learn bad)\n quiet Snooze nudges for 1 hour\n \n checkpoint Save work context to .trie/ (aliases: cp, save)\n linear sync Sync active tickets from Linear\n gotcha Predict problems with current changes (alias: predict)\n reconcile Reconcile context graph from JSON backup\n\n audit View security audit logs\n memory Search and manage issue memory\n patterns Save, validate, and share patterns across projects\n status Quick health check (project health + memory stats)\n project View/manage project info (.trie/PROJECT.md)\n setup Configure API key and environment\n \n ci Generate GitHub Actions workflow with memory caching\n \n help Show this help message\n version Show version information\n\nEXAMPLES:\n trie init # Initialize Trie in your project\n trie watch # Start watching (nudges as you code)\n trie watch # Run in background: screen -S trie-watch\n trie scan # Scan your codebase now\n \n trie tell \"users couldn't log in\" # Report an incident\n trie ok # Mark current pattern as good\n trie bad # Mark current pattern as bad\n trie quiet # Snooze nudges for 1 hour\n \n trie linear sync # Sync active tickets from Linear\n trie learn # Scan history for precedents\n trie gotcha # Predict for current changes\n \n trie check # Risk check before pushing\n\n trie memory search \"SQL injection\"\n trie memory stats # View memory statistics\n trie status # Quick health check (project + memory)\n trie ci # Generate CI workflow with memory caching\n\nMCP TOOLS (use via Cursor/Claude Desktop):\n trie_linear_sync Sync active tickets from Linear\n trie_scan Scan with decision ledger\n trie_fix Generate high-confidence fix prompts\n trie_explain Explain code, issues, or changes\n trie_watch Watch mode for autonomous reporting\n\n`);\n}\n\n/**\n * Show setup instructions\n */\nfunction showSetup(): void {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Trie Agent Setup ║\n╚══════════════════════════════════════════════════════════════════╝\n\nSTEP 1: API Keys\n─────────────────────────────────────\nTrie can work offline, but performs best with these keys:\n\n1. ANTHROPIC_API_KEY (Required for AI analysis)\n Get it: https://console.anthropic.com/\n\n2. LINEAR_API_KEY (Required for JIT defect prediction)\n Get it: https://linear.app/settings/api\n\nSet them in your environment (~/.zshrc) or MCP config:\n export ANTHROPIC_API_KEY=sk-ant-...\n export LINEAR_API_KEY=lin_api_...\n\nSTEP 2: Configure for your AI tool\n─────────────────────────────────────\n\nFor CLAUDE CODE:\n claude mcp add Trie -- npx @triedotdev/mcp\n\nFor CURSOR (~/.cursor/mcp.json):\n{\n \"mcpServers\": {\n \"Trie\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@triedotdev/mcp\"],\n \"env\": {\n \"ANTHROPIC_API_KEY\": \"your-key-here\",\n \"LINEAR_API_KEY\": \"your-key-here\"\n }\n }\n }\n}\n\nSTEP 3: Start scanning!\n─────────────────────────────────────\nAsk your AI assistant: \"Scan this with Trie\" or \"Use trie_scan\"\n`);\n}\n\n/**\n * Show version\n */\nfunction showVersion(): void {\n showBanner();\n console.error(`v${getCliVersion()}`);\n}\n\n/**\n * Handle status command - quick health check\n */\nexport async function handleStatusCommand(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n \n try {\n // Load context state for last scan and memory stats\n const state = await loadContextState();\n const memoryStats = await getMemoryStats(workDir);\n \n console.log('\\n╔══════════════════════════════════════════════════════════════════╗');\n console.log('║ PROJECT STATUS ║');\n console.log('╚══════════════════════════════════════════════════════════════════╝\\n');\n \n // Last Scan Info\n if (state.lastScan) {\n const lastScanDate = new Date(state.lastScan.timestamp);\n const daysAgo = Math.floor((Date.now() - lastScanDate.getTime()) / (1000 * 60 * 60 * 24));\n console.log(`\\n${pc.bold('Last Scan:')} ${lastScanDate.toLocaleDateString()} (${daysAgo === 0 ? 'today' : daysAgo === 1 ? 'yesterday' : `${daysAgo} days ago`})`);\n console.log(pc.dim(` Files scanned: ${state.lastScan.filesScanned}`));\n console.log(pc.dim(` Issues found: ${state.lastScan.issues.total} (${state.lastScan.issues.critical} critical, ${state.lastScan.issues.serious} serious)`));\n } else {\n console.log(`\\n${pc.bold('Last Scan:')} Never ${pc.dim('(run `trie scan` to get started)')}`);\n }\n \n // Memory Stats Summary\n console.log(`\\n${pc.bold('Memory Stats:')}`);\n console.log(pc.dim(` Active Issues: ${memoryStats.activeIssues}`));\n console.log(pc.dim(` Resolved: ${memoryStats.resolvedCount}`));\n console.log(pc.dim(` Total (all-time): ${memoryStats.totalIssues}`));\n const cap = memoryStats.capacityInfo;\n const capIndicator = cap.isAtCap ? pc.red('○') : cap.percentFull >= 80 ? pc.yellow('◉') : pc.green('●');\n console.log(` ${capIndicator} Memory Usage: ${pc.bold(cap.percentFull + '%')} ${pc.dim(`(${cap.current}/${cap.max})`)}`);\n \n if (memoryStats.activeIssues > 0) {\n console.log(`\\n ${pc.bold('Active Issues by Severity:')}`);\n const severityOrder = ['critical', 'serious', 'moderate', 'low', 'info'];\n for (const severity of severityOrder) {\n const count = memoryStats.activeIssuesBySeverity[severity] || 0;\n if (count > 0) {\n console.log(pc.dim(` ${severity}: ${count}`));\n }\n }\n } else if (memoryStats.totalIssues > 0) {\n console.log(`\\n ${pc.green('●')} All issues have been resolved`);\n }\n \n // Capacity warning\n if (cap.isAtCap) {\n console.log(`\\n${pc.yellow('⬢ Warning:')} Memory at capacity - consider running: ${pc.bold('trie memory purge smart')}`);\n } else if (cap.percentFull >= 80) {\n console.log(`\\n${pc.yellow('⬢ Notice:')} Memory usage high - consider running: ${pc.bold('trie memory purge smart')}`);\n }\n \n console.log(`\\n${pc.bold('Quick Commands:')}`);\n console.log(pc.dim(' trie scan - Scan codebase now'));\n console.log(pc.dim(' trie memory stats - Detailed memory statistics'));\n console.log(pc.dim(' trie project - View project information'));\n console.log('');\n \n } catch (error) {\n console.error('Error loading status:', error);\n process.exit(1);\n }\n}\n\n/**\n * Handle project command\n */\nasync function handleProject(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n\n if (subcommand === 'init') {\n const result = await initProjectInfo(workDir);\n if (result.created) {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ PROJECT.md Created ║\n╚══════════════════════════════════════════════════════════════════╝\n\n${pc.bold('Path:')} ${result.path}\n\nA template has been created with sections for:\n • Project Overview\n • Technology Stack\n • Architecture\n • Coding Conventions\n • Environment\n • Team\n • Compliance\n • AI Instructions\n\nNext steps:\n 1. Edit the file to add your project details\n 2. The info will be available via trie://project resource\n 3. AI assistants will use this context automatically\n`);\n } else {\n console.log(`PROJECT.md already exists at: ${result.path}`);\n console.log('Use \"trie project\" to view it.');\n }\n return;\n }\n\n if (subcommand === 'edit') {\n const editor = process.env.EDITOR || process.env.VISUAL || 'nano';\n const projectPath = join(getTrieDirectory(workDir), 'PROJECT.md');\n \n if (!projectInfoExists(workDir)) {\n console.log('No PROJECT.md found. Creating one first...');\n await initProjectInfo(workDir);\n }\n \n const { spawn } = await import('child_process');\n const child = spawn(editor, [projectPath], { stdio: 'inherit' });\n child.on('close', (code) => {\n process.exit(code || 0);\n });\n return;\n }\n\n // Default: show project info\n if (!projectInfoExists(workDir)) {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Project Information ║\n╚══════════════════════════════════════════════════════════════════╝\n\n${pc.bold('No PROJECT.md found in this project.')}\n\nCOMMANDS:\n trie project init Create PROJECT.md from template\n trie project edit Open PROJECT.md in $EDITOR\n trie project View PROJECT.md contents\n\nWHAT IS PROJECT.MD?\nPROJECT.md stores important project context for AI assistants:\n • Project description and purpose\n • Technology stack and frameworks\n • Architecture decisions\n • Coding conventions\n • Environment info (URLs, endpoints)\n • Team ownership\n • Compliance requirements\n • Special instructions for AI\n\nThis info is available via trie://project MCP resource.\n`);\n return;\n }\n\n const content = await loadProjectInfo(workDir);\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Project Information ║\n╚══════════════════════════════════════════════════════════════════╝\n\n${pc.bold('Path:')} ${join(getTrieDirectory(workDir), 'PROJECT.md')}\n\n${'-'.repeat(68)}\n`);\n console.log(content);\n}\n\n/**\n * Run scan command\n */\nasync function runScan(args: string[]): Promise<void> {\n // Forward to watch daemon with --once flag\n const { spawn } = await import('child_process');\n \n // Determine daemon path - works for both source (tsx) and built (node) execution\n let daemonPath: string;\n if (__filename.endsWith('.ts')) {\n // Running from source with tsx\n daemonPath = resolve(__dirname, 'yolo-daemon.ts');\n } else {\n // Running from built dist\n daemonPath = resolve(__dirname, 'yolo-daemon.js');\n }\n \n const daemonArgs = ['--once', ...args];\n \n // Use tsx for .ts files, node for .js files\n const executor = daemonPath.endsWith('.ts') ? 'npx' : 'node';\n const execArgs = daemonPath.endsWith('.ts') \n ? ['tsx', daemonPath, ...daemonArgs]\n : [daemonPath, ...daemonArgs];\n \n const child = spawn(executor, execArgs, {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code) => {\n process.exit(code || 0);\n });\n}\n\n/**\n * Run watch command\n */\nasync function runWatch(args: string[]): Promise<void> {\n const { spawn } = await import('child_process');\n \n // Determine daemon path - works for both source (tsx) and built (node) execution\n let daemonPath: string;\n if (__filename.endsWith('.ts')) {\n daemonPath = resolve(__dirname, 'yolo-daemon.ts');\n } else {\n daemonPath = resolve(__dirname, 'yolo-daemon.js');\n }\n \n // Use tsx for .ts files, node for .js files\n const executor = daemonPath.endsWith('.ts') ? 'npx' : 'node';\n const execArgs = daemonPath.endsWith('.ts') \n ? ['tsx', daemonPath, ...args]\n : [daemonPath, ...args];\n \n const child = spawn(executor, execArgs, {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code) => {\n process.exit(code || 0);\n });\n}\n\n/**\n * Main entry point\n */\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n const command = args[0]?.toLowerCase();\n const restArgs = args.slice(1);\n\n // No command or help flag\n if (!command || command === 'help' || command === '--help' || command === '-h') {\n showHelp();\n process.exit(0);\n }\n\n const initRequired = !['init', 'version', '--version', '-v'].includes(command);\n if (initRequired) {\n const workDir = getWorkingDirectory(undefined, true);\n if (!isTrieInitialized(workDir)) {\n console.error('Trie is not initialized for this project.');\n console.error('Run `trie init` first.');\n process.exit(1);\n }\n }\n\n switch (command) {\n case 'setup':\n case 'config':\n case 'configure':\n showSetup();\n break;\n\n case 'init':\n case 'bootstrap':\n handleInitCommand(restArgs);\n break;\n\n case 'memory':\n case 'mem':\n handleMemoryCommand(restArgs);\n break;\n\n case 'status':\n case 'stats':\n await handleStatusCommand();\n break;\n\n case 'checkpoint':\n case 'cp':\n case 'save':\n handleCheckpointCommand(restArgs);\n break;\n\n case 'project':\n case 'info':\n case 'project-info':\n handleProject(restArgs);\n break;\n\n case 'audit':\n handleAuditCommand(restArgs);\n break;\n\n case 'version':\n case '--version':\n case '-v':\n showVersion();\n break;\n\n case 'scan':\n runScan(restArgs);\n break;\n\n case 'watch':\n runWatch(restArgs);\n break;\n\n case 'check':\n handleCheckCommand(restArgs);\n break;\n\n case 'pre-push':\n handlePrePushCommand(restArgs);\n break;\n\n case 'fix':\n case 'auto-fix':\n case 'autofix':\n handleAutoFixCommand(restArgs);\n break;\n\n case 'goal':\n case 'goals':\n handleGoalCommand(restArgs);\n break;\n\n case 'hypothesis':\n case 'hypo':\n case 'hypotheses':\n handleHypothesisCommand(restArgs);\n break;\n\n case 'tell':\n handleTellCommand(restArgs);\n break;\n\n case 'reconcile':\n handleReconcileCommand(restArgs);\n break;\n\n case 'learn':\n case 'train':\n handleLearnCommand(restArgs);\n break;\n\n case 'ok':\n case 'thumbs-up':\n handleLearnCommand(['ok', ...restArgs]);\n break;\n\n case 'bad':\n case 'thumbs-down':\n handleLearnCommand(['bad', ...restArgs]);\n break;\n\n case 'quiet':\n case 'snooze':\n handleQuietCommand();\n break;\n\n case 'ci':\n case 'ci-setup':\n handleCISetupCommand(restArgs);\n break;\n\n case 'linear':\n handleLinearCommand(restArgs);\n break;\n\n case 'gotcha':\n case 'predict':\n handleGotchaCommand();\n break;\n\n case 'patterns':\n case 'pattern':\n handlePatternsCommand(restArgs);\n break;\n\n case 'sync':\n {\n const syncCommand = createSyncCommand();\n syncCommand.parse(['node', 'trie', 'sync', ...restArgs], { from: 'user' });\n }\n break;\n\n case 'ledger':\n {\n const ledgerCommand = createLedgerCommand();\n ledgerCommand.parse(['node', 'trie', 'ledger', ...restArgs], { from: 'user' });\n }\n break;\n\n default:\n // Check if it looks like a flag (pass to watch daemon)\n if (command.startsWith('-')) {\n // Treat as watch-daemon args\n const { spawn } = require('child_process');\n const daemonPath = resolve(__dirname, 'yolo-daemon.js');\n \n const child = spawn('node', [daemonPath, ...args], {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code: number) => {\n process.exit(code || 0);\n });\n } else {\n console.error(`Unknown command: ${command}`);\n console.error(`Run 'trie help' for usage information.`);\n process.exit(1);\n }\n }\n}\n\n// Check if this module is the entry point\n// We use realpathSync to resolve symlinks (npm bin creates symlinks)\nconst isEntryPoint = (() => {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n // Use imported realpathSync instead of dynamic require\n const realEntry = realpathSync(entry);\n const realThis = fileURLToPath(import.meta.url);\n return realEntry === realThis;\n } catch {\n // Fallback: check if we're being run directly (not imported in tests)\n // Tests use vitest which sets specific env vars\n return !process.env.VITEST && !process.env.VITEST_WORKER_ID;\n }\n})();\n\nif (isEntryPoint) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { postCommitTemplate, preCommitTemplate, prePushTemplate } from './templates.js';\n\ntype HookName = 'pre-commit' | 'post-commit' | 'pre-push';\n\nconst HOOK_BUILDERS: Record<HookName, () => string> = {\n 'pre-commit': preCommitTemplate,\n 'post-commit': postCommitTemplate,\n 'pre-push': prePushTemplate\n};\n\nfunction hookPath(repoPath: string, name: HookName): string {\n return path.join(repoPath, '.git', 'hooks', name);\n}\n\nfunction ensureHookDir(repoPath: string): void {\n const dir = path.join(repoPath, '.git', 'hooks');\n fs.mkdirSync(dir, { recursive: true });\n}\n\nfunction appendHookFile(targetPath: string, content: string): void {\n if (fs.existsSync(targetPath)) {\n const existing = fs.readFileSync(targetPath, 'utf8');\n if (existing.includes('# Trie pre-commit hook') || existing.includes('# Trie post-commit hook')) {\n return;\n }\n fs.appendFileSync(targetPath, `\\n# --- Added by Trie ---\\n${content}`);\n } else {\n fs.writeFileSync(targetPath, content, { mode: 0o755 });\n }\n fs.chmodSync(targetPath, 0o755);\n}\n\nexport function installGitHooks(projectPath: string): string[] {\n const gitDir = path.join(projectPath, '.git');\n if (!fs.existsSync(gitDir)) {\n return [];\n }\n\n ensureHookDir(projectPath);\n\n const installed: string[] = [];\n (Object.keys(HOOK_BUILDERS) as HookName[]).forEach((name) => {\n const content = HOOK_BUILDERS[name]();\n const target = hookPath(projectPath, name);\n appendHookFile(target, content);\n installed.push(name);\n });\n\n return installed;\n}\n","const PATH_FIX = 'export PATH=\"/usr/local/bin:/opt/homebrew/bin:$PATH\"\\n';\n\nfunction hookHeader(): string {\n return '#!/bin/sh\\n' + PATH_FIX + '\\n';\n}\n\nfunction trieCommand(name: string): string {\n return `\nTRIE_BIN=\"$(command -v trie || command -v trie-agent || true)\"\nif [ -n \"$TRIE_BIN\" ]; then\n \"$TRIE_BIN\" ${name} || true\nelse\n echo \"Trie not available; skipping ${name} hook.\"\nfi\n`;\n}\n\n/**\n * Pre-push hook command that can block on critical issues\n * Supports bypass via TRIE_BYPASS=1 environment variable\n */\nfunction prePushCommand(): string {\n return `\nTRIE_BIN=\"$(command -v trie || command -v trie-agent || true)\"\nif [ -n \"$TRIE_BIN\" ]; then\n # Check for bypass\n if [ \"$TRIE_BYPASS\" = \"1\" ] || [ \"$TRIE_BYPASS\" = \"true\" ]; then\n echo \"Trie push blocking bypassed (TRIE_BYPASS=1)\"\n \"$TRIE_BIN\" pre-push --bypassed || true\n exit 0\n fi\n \n # Run pre-push check with blocking enabled\n \"$TRIE_BIN\" pre-push --block\n EXIT_CODE=$?\n \n if [ $EXIT_CODE -eq 0 ]; then\n exit 0\n elif [ $EXIT_CODE -eq 2 ]; then\n # Exit code 2 = blocked but bypassable\n echo \"\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n echo \"Push blocked by Trie due to critical issues.\"\n echo \"\"\n echo \"To bypass (not recommended):\"\n echo \" TRIE_BYPASS=1 git push\"\n echo \" OR: git push --no-verify\"\n echo \"\"\n echo \"To fix issues first:\"\n echo \" trie fix\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n exit 1\n else\n # Other errors - don't block\n exit 0\n fi\nelse\n echo \"Trie not available; skipping pre-push hook.\"\nfi\n`;\n}\n\nexport function preCommitTemplate(): string {\n return (\n hookHeader() +\n '# Trie pre-commit hook\\n' +\n trieCommand('pre-commit')\n ).trim() + '\\n';\n}\n\nexport function postCommitTemplate(): string {\n return (\n hookHeader() +\n '# Trie post-commit hook\\n' +\n trieCommand('post-commit')\n ).trim() + '\\n';\n}\n\nexport function prePushTemplate(): string {\n return (\n hookHeader() +\n '# Trie pre-push hook with blocking support\\n' +\n '# Bypass with: TRIE_BYPASS=1 git push\\n' +\n prePushCommand()\n ).trim() + '\\n';\n}\n","/**\n * CLI Init Command\n * \n * Initialize bootstrap files for a new project.\n */\n\nimport { initializeBootstrapFiles, needsBootstrap, completeBootstrap } from '../bootstrap/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getSkillCategories } from '../bootstrap/stack-detector.js';\nimport { installGitHooks } from '../hooks/install.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nfunction ensureGitignore(workDir: string): void {\n const target = path.join(workDir, '.gitignore');\n const entries = ['.trie/context.db', '.trie/context.json', '.trie/*.db', 'trie-reports/'];\n let content = '';\n if (fs.existsSync(target)) {\n content = fs.readFileSync(target, 'utf8');\n }\n const missing = entries.filter((e) => !content.includes(e));\n if (missing.length > 0) {\n const updated = content.trimEnd() + '\\n' + missing.join('\\n') + '\\n';\n fs.writeFileSync(target, updated);\n }\n}\n\nexport async function handleInitCommand(args: string[]): Promise<void> {\n try {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n\n if (subcommand === 'complete') {\n const result = await completeBootstrap(workDir);\n if (result) {\n console.log('Bootstrap completed. BOOTSTRAP.md has been deleted.');\n } else {\n console.log('No BOOTSTRAP.md file found.');\n }\n return;\n }\n\n if (subcommand === 'status') {\n const needs = needsBootstrap(workDir);\n if (needs) {\n console.log('Bootstrap pending: .trie/BOOTSTRAP.md exists');\n console.log('Run \"trie init complete\" after finishing setup.');\n } else {\n console.log('Bootstrap complete: No pending setup.');\n }\n return;\n }\n\n const force = args.includes('--force') || args.includes('-f');\n const skipBootstrap = args.includes('--skip-bootstrap');\n\n console.log(`\n╔════════════════════════════════════════════════╗\n║ ║\n║ ████████╗██████╗ ██╗███████╗ ║\n║ ╚══██╔══╝██╔══██╗██║██╔════╝ ║\n║ ██║ ██████╔╝██║█████╗ ║\n║ ██║ ██╔══██╗██║██╔══╝ ║\n║ ██║ ██║ ██║██║███████╗ ║\n║ ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝ ║\n║ ║\n║ Your code quality agent and skills registry ║\n║ ║\n╚════════════════════════════════════════════════╝\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n\n`);\n\n const result = await initializeBootstrapFiles({\n workDir,\n force,\n skipBootstrap,\n });\n\n // Check if this is a re-init (all files already exist)\n const isReInit = result.created.length === 0 && result.skipped.length > 0;\n\n if (isReInit && !force) {\n console.log('Trie is already initialized in this project.\\n');\n console.log('Your files:');\n for (const file of result.skipped) {\n console.log(` ✓ .trie/${file}`);\n }\n console.log('\\nTo reset and recreate files: trie init --force');\n } else {\n if (result.created.length > 0) {\n console.log('Created files:');\n for (const file of result.created) {\n console.log(` + .trie/${file}`);\n }\n }\n\n if (result.skipped.length > 0 && !force) {\n console.log('\\nSkipped (already exist):');\n for (const file of result.skipped) {\n console.log(` - .trie/${file}`);\n }\n }\n }\n\n console.log('\\nDetected Stack:');\n if (result.stack.framework) console.log(` Framework: ${result.stack.framework}`);\n if (result.stack.language) console.log(` Language: ${result.stack.language}`);\n if (result.stack.database) console.log(` Database: ${result.stack.database}`);\n if (result.stack.auth) console.log(` Auth: ${result.stack.auth}`);\n if (result.stack.packageManager) console.log(` Package Manager: ${result.stack.packageManager}`);\n\n if (result.stack.suggestedSkills.length > 0) {\n // Limit to top 5 most relevant skills to avoid overwhelming output\n const topSkills = result.stack.suggestedSkills.slice(0, 5);\n console.log('\\nSuggested Skills (based on your stack):');\n for (const skill of topSkills) {\n console.log(` trie skills add ${skill}`);\n }\n if (result.stack.suggestedSkills.length > 5) {\n console.log(` ... and ${result.stack.suggestedSkills.length - 5} more: trie skills suggest`);\n }\n }\n\n // Show category exploration options\n const categories = getSkillCategories();\n const topCategories = categories.slice(0, 5);\n console.log('\\nExplore skill categories:');\n for (const cat of topCategories) {\n console.log(` trie skills list ${cat.name.padEnd(15)} # ${cat.count} skills`);\n }\n console.log(` trie skills list categories # see all ${categories.length} categories`);\n \n console.log('\\nBrowse all skills: https://skills.sh');\n\n console.log(`\nQuick Start:\n 1. trie scan # Analyze your codebase now\n 2. trie watch # Start watching (nudges as you code)\n 3. trie tell \"what broke\" # Teach Trie about past incidents\n\nTrie is now active via git hooks (pre-commit, pre-push).\nFor real-time nudges while coding, run \"trie watch\" in a terminal.\n\nCustomize Later:\n - .trie/PROJECT.md — Describe your project for better context\n - .trie/RULES.md — Define coding standards Trie should enforce\n\nRun \"trie help\" to see all available commands.\n`);\n\n const hooks = installGitHooks(workDir);\n if (hooks.length > 0) {\n console.log('\\nGit hooks installed:');\n for (const hook of hooks) {\n console.log(` .git/hooks/${hook}`);\n }\n } else {\n console.log('\\nGit hooks not installed (no .git directory found).');\n }\n\n ensureGitignore(workDir);\n if (!process.env.ANTHROPIC_API_KEY) {\n console.log(`\nNote: Running in pattern-only mode. For AI-powered analysis, set your API key:\n\n This session only:\n export ANTHROPIC_API_KEY=sk-ant-...\n\n Persist in shell config (~/.zshrc or ~/.bashrc):\n echo 'export ANTHROPIC_API_KEY=sk-ant-...' >> ~/.zshrc\n source ~/.zshrc\n\n Or add to your MCP config for Cursor/Claude Code (see README).`);\n }\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","/**\n * CLI Memory Command\n * \n * Search and manage issue memory.\n */\n\nimport {\n searchIssues,\n getMemoryStats,\n getRecentIssues,\n getDailyLogs,\n markIssueResolved,\n purgeIssues,\n} from '../memory/issue-store.js';\nimport {\n findCrossProjectPatterns,\n listTrackedProjects,\n getGlobalMemoryStats,\n updateGlobalMemoryMd,\n searchGlobalPatterns,\n} from '../memory/global-memory.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function handleMemoryCommand(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n const restArgs = args.slice(1);\n\n switch (subcommand) {\n case 'search':\n await handleSearch(restArgs);\n break;\n case 'stats':\n await handleStats();\n break;\n case 'recent':\n await handleRecent(restArgs);\n break;\n case 'logs':\n await handleLogs();\n break;\n case 'resolve':\n await handleResolve(restArgs);\n break;\n case 'purge':\n await handlePurge(restArgs);\n break;\n case 'global':\n await handleGlobal(restArgs);\n break;\n default:\n showHelp();\n }\n}\n\nasync function handleSearch(args: string[]): Promise<void> {\n const query = args.join(' ');\n \n if (!query) {\n console.log('Usage: trie memory search <query>');\n console.log('Example: trie memory search \"SQL injection\"');\n return;\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n const results = await searchIssues(query, { workDir, limit: 10 });\n\n if (results.length === 0) {\n console.log(`No issues found matching \"${query}\"`);\n return;\n }\n\n console.log(`Found ${results.length} issue(s) matching \"${query}\":\\n`);\n\n for (const result of results) {\n const i = result.issue;\n const status = i.resolved ? '[RESOLVED]' : '';\n console.log(`[${i.severity.toUpperCase()}] ${status} ${i.issue.slice(0, 80)}`);\n console.log(` File: ${i.file}${i.line ? `:${i.line}` : ''}`);\n console.log(` Agent: ${i.agent} | Score: ${(result.score * 100).toFixed(0)}%`);\n console.log(` Date: ${new Date(i.timestamp).toLocaleDateString()}`);\n console.log('');\n }\n}\n\nasync function handleStats(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n const stats = await getMemoryStats(workDir);\n const globalStats = await getGlobalMemoryStats();\n\n console.log('Local Issue Memory Stats:');\n console.log(` Active Issues: ${stats.activeIssues}`);\n console.log(` Resolved: ${stats.resolvedCount}`);\n console.log(` Total (all-time): ${stats.totalIssues}`);\n \n // Capacity info\n const cap = stats.capacityInfo;\n if (cap.isAtCap) {\n console.log('\\n⚠️ CAPACITY WARNING');\n console.log(` Memory is at maximum capacity (${cap.current}/${cap.max}, ${cap.percentFull}%)`);\n console.log(' New repeats are deduplicated. Older issues are compacted into summaries, and if still over cap the oldest/lowest-value issues are pruned.');\n console.log('\\n To free up space:');\n console.log(' trie memory purge smart - Remove resolved & old low-priority (recommended)');\n console.log(' trie memory purge resolved - Remove all resolved issues');\n console.log(' trie memory purge old - Remove issues older than 90 days');\n console.log(' trie memory purge all - Clear all issues (keeps summaries)');\n } else if (cap.percentFull >= 80) {\n console.log(`\\nℹ️ Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`);\n console.log(' Consider running: trie memory purge smart');\n } else {\n console.log(` Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`);\n }\n \n // Deduplication stats\n if (stats.deduplicationStats.duplicatesAvoided > 0) {\n console.log('\\n Deduplication:');\n console.log(` Unique Patterns: ${stats.deduplicationStats.uniquePatterns}`);\n console.log(` Duplicates Avoided: ${stats.deduplicationStats.duplicatesAvoided}`);\n }\n \n if (stats.oldestIssue) {\n console.log(`\\n Date Range: ${stats.oldestIssue.split('T')[0]} to ${stats.newestIssue?.split('T')[0]}`);\n }\n\n console.log('\\n Active Issues by Severity:');\n const severityOrder = ['critical', 'serious', 'moderate', 'low', 'info'];\n let hasActiveIssues = false;\n for (const severity of severityOrder) {\n const activeCount = stats.activeIssuesBySeverity[severity] || 0;\n const totalCount = stats.issuesBySeverity[severity] || 0;\n if (totalCount > 0) {\n hasActiveIssues = hasActiveIssues || activeCount > 0;\n console.log(` ${severity}: ${activeCount} active (${totalCount} all-time)`);\n }\n }\n if (!hasActiveIssues && stats.totalIssues > 0) {\n console.log(' ✅ All issues have been resolved!');\n }\n\n console.log('\\n By Agent:');\n const sortedAgents = Object.entries(stats.issuesByAgent).sort((a, b) => b[1] - a[1]);\n for (const [agent, count] of sortedAgents.slice(0, 10)) {\n console.log(` ${agent}: ${count}`);\n }\n\n console.log('\\nGlobal Cross-Project Stats:');\n console.log(` Tracked Projects: ${globalStats.trackedProjects}`);\n console.log(` Total Patterns: ${globalStats.totalPatterns}`);\n console.log(` Cross-Project Patterns: ${globalStats.crossProjectPatterns}`);\n console.log(` Fixed Patterns: ${globalStats.fixedPatterns}`);\n}\n\nasync function handleRecent(args: string[]): Promise<void> {\n const limit = parseInt(args[0] || '10', 10);\n const workDir = getWorkingDirectory(undefined, true);\n const issues = await getRecentIssues({ workDir, limit });\n\n if (issues.length === 0) {\n console.log('No recent issues found.');\n return;\n }\n\n console.log(`Recent Issues (last 7 days):\\n`);\n\n for (const i of issues) {\n const status = i.resolved ? '[RESOLVED]' : '';\n console.log(`[${i.severity.toUpperCase()}] ${status} ${i.issue.slice(0, 70)}`);\n console.log(` ${i.file}${i.line ? `:${i.line}` : ''} | ${i.agent}`);\n console.log('');\n }\n}\n\nasync function handleLogs(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n const logs = await getDailyLogs(workDir);\n\n if (logs.length === 0) {\n console.log('No daily logs found.');\n return;\n }\n\n console.log('Daily Logs (.trie/memory/):\\n');\n for (const log of logs.slice(0, 14)) {\n console.log(` ${log}`);\n }\n\n if (logs.length > 14) {\n console.log(` ... and ${logs.length - 14} more`);\n }\n}\n\nasync function handleResolve(args: string[]): Promise<void> {\n const issueId = args[0];\n \n if (!issueId) {\n console.log('Usage: trie memory resolve <issue-id>');\n return;\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n const result = await markIssueResolved(issueId, workDir);\n\n if (result) {\n console.log(`Issue ${issueId} marked as resolved.`);\n } else {\n console.log(`Issue ${issueId} not found.`);\n }\n}\n\nasync function handleGlobal(args: string[]): Promise<void> {\n const action = args[0]?.toLowerCase();\n\n if (action === 'patterns') {\n const patterns = await findCrossProjectPatterns(2);\n \n if (patterns.length === 0) {\n console.log('No cross-project patterns found yet.');\n console.log('Patterns appear when the same issue is detected in multiple projects.');\n return;\n }\n\n console.log(`Cross-Project Patterns (${patterns.length}):\\n`);\n \n for (const p of patterns.slice(0, 10)) {\n console.log(`[${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`);\n console.log(` Occurrences: ${p.occurrences} across ${p.projects.length} projects`);\n console.log(` Agent: ${p.agent}`);\n if (p.fixApplied) {\n console.log(` Fixed in: ${p.fixApplied.project}`);\n }\n console.log('');\n }\n return;\n }\n\n if (action === 'projects') {\n const projects = await listTrackedProjects();\n \n if (projects.length === 0) {\n console.log('No projects tracked yet.');\n return;\n }\n\n console.log(`Tracked Projects (${projects.length}):\\n`);\n console.log('| Project | Last Scan | Issues |');\n console.log('|---------|-----------|--------|');\n \n for (const p of projects) {\n console.log(`| ${p.name.slice(0, 20)} | ${p.lastScan.split('T')[0]} | ${p.totalIssues} |`);\n }\n return;\n }\n\n if (action === 'search') {\n const query = args.slice(1).join(' ');\n if (!query) {\n console.log('Usage: trie memory global search <query>');\n return;\n }\n\n const patterns = await searchGlobalPatterns(query, { limit: 10 });\n \n if (patterns.length === 0) {\n console.log(`No global patterns found matching \"${query}\"`);\n return;\n }\n\n console.log(`Global patterns matching \"${query}\":\\n`);\n for (const p of patterns) {\n console.log(`[${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`);\n console.log(` Projects: ${p.projects.slice(0, 3).join(', ')}`);\n console.log('');\n }\n return;\n }\n\n if (action === 'update') {\n await updateGlobalMemoryMd();\n console.log('Updated ~/.trie/memory/GLOBAL_MEMORY.md');\n return;\n }\n\n console.log(`\nGlobal Memory Commands:\n trie memory global patterns Show cross-project patterns\n trie memory global projects Show tracked projects\n trie memory global search <q> Search global patterns\n trie memory global update Update GLOBAL_MEMORY.md\n`);\n}\n\nasync function handlePurge(args: string[]): Promise<void> {\n const strategy = (args[0]?.toLowerCase() as 'smart' | 'resolved' | 'old' | 'all') || 'smart';\n const validStrategies = ['smart', 'resolved', 'old', 'all'];\n \n if (!validStrategies.includes(strategy)) {\n console.log('Invalid purge strategy. Use: smart, resolved, old, or all');\n console.log('\\nUsage:');\n console.log(' trie memory purge smart - Remove resolved & old low-priority (recommended)');\n console.log(' trie memory purge resolved - Remove all resolved issues');\n console.log(' trie memory purge old [days] - Remove issues older than N days (default 90)');\n console.log(' trie memory purge all - Clear all issues (keeps summaries)');\n return;\n }\n\n const daysOld = strategy === 'old' ? parseInt(args[1] || '90', 10) : undefined;\n \n // Confirm destructive actions\n if (strategy === 'all') {\n console.log('⚠️ WARNING: This will clear ALL issues from active memory.');\n console.log('Historical summaries will be preserved, but individual issues will be removed.');\n console.log('\\nTo confirm, run: trie memory purge all --confirm');\n \n if (!args.includes('--confirm')) {\n return;\n }\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n console.log(`\\nPurging issues with strategy: ${strategy}...`);\n \n const options: { workDir: string; daysOld?: number } = { workDir };\n if (daysOld !== undefined) {\n options.daysOld = daysOld;\n }\n \n const result = await purgeIssues(strategy, options);\n\n console.log(`\\n✅ Purge Complete`);\n console.log(` Strategy: ${result.strategy}`);\n console.log(` Removed: ${result.removed} issues`);\n console.log(` Remaining: ${result.remaining} issues`);\n\n switch (strategy) {\n case 'smart':\n console.log('\\nWhat was removed:');\n console.log(' • Resolved issues older than 30 days');\n console.log(' • Low-priority issues (info/low) older than 30 days');\n console.log('\\nWhat was kept:');\n console.log(' • All critical and high severity issues');\n console.log(' • All unresolved issues');\n console.log(' • All issues from the last 30 days');\n break;\n case 'resolved':\n console.log('\\nRemoved all resolved issues.');\n console.log('Kept all unresolved issues.');\n break;\n case 'old':\n console.log(`\\nRemoved all issues older than ${daysOld} days.`);\n console.log('Kept all recent issues.');\n break;\n case 'all':\n console.log('\\nCleared all issues from active memory.');\n console.log('Historical summaries preserved in .trie/memory/compacted-summaries.json');\n break;\n }\n \n console.log('\\nRun \"trie memory stats\" to see updated memory usage.');\n}\n\nfunction showHelp(): void {\n console.log(`\nMemory - Search and manage issue memory\n\nCommands:\n trie memory search <query> Search issues by keyword\n trie memory stats Show memory statistics\n trie memory recent [limit] Show recent issues\n trie memory logs List daily log files\n trie memory resolve <id> Mark issue as resolved\n trie memory purge <strategy> Free up memory space\n trie memory global <action> Cross-project memory\n\nPurge Strategies:\n smart Remove resolved & old low-priority issues (recommended)\n resolved Remove all resolved issues\n old [N] Remove issues older than N days (default 90)\n all Clear all issues (keeps historical summaries)\n\nExamples:\n trie memory search \"SQL injection\"\n trie memory recent 20\n trie memory purge smart\n trie memory global patterns\n`);\n}\n","import { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\ninterface CheckOptions {\n mode: 'quick' | 'full' | 'offline';\n files?: string[];\n}\n\nfunction parseArgs(args: string[]): CheckOptions {\n let mode: CheckOptions['mode'] = 'full';\n const filesFlag = args.find((a) => a.startsWith('--files='));\n const parsedFiles = filesFlag ? filesFlag.replace('--files=', '').split(',').map((f) => f.trim()).filter(Boolean) : [];\n\n if (args.includes('--quick') || args.includes('-q')) mode = 'quick';\n if (args.includes('--offline')) mode = 'offline';\n if (args.includes('--full')) mode = 'full';\n\n const result: CheckOptions = { mode };\n if (parsedFiles.length > 0) result.files = parsedFiles;\n return result;\n}\n\nfunction printResult(result: any) {\n console.log(`\\nRisk: ${result.original.riskLevel.toUpperCase()} (${result.original.shouldBlock ? 'block' : 'allow'})`);\n console.log(`Explanation: ${result.original.explanation}`);\n console.log(`Recommendation: ${result.original.recommendation}`);\n\n if (result.original.files?.length) {\n console.log('\\nHigh-risk files:');\n for (const file of result.original.files.filter((f: any) => ['high', 'critical'].includes(f.level))) {\n console.log(` - ${file.file}: ${file.reasons.join('; ')}`);\n }\n }\n\n console.log('\\nPlain-English summary:');\n console.log(` Summary: ${result.summary}`);\n console.log(` What I found: ${result.whatIFound}`);\n console.log(` How bad: ${result.howBad}`);\n console.log(` What to do: ${result.whatToDo}`);\n}\n\nexport async function handleCheckCommand(args: string[]): Promise<void> {\n try {\n const options = parseArgs(args);\n const projectPath = getWorkingDirectory(undefined, true);\n\n let files = options.files;\n if (!files || files.length === 0) {\n const perception = await perceiveCurrentChanges(projectPath);\n files = perception.diffSummary.files.map((f) => f.filePath);\n if (files.length === 0) {\n console.log('No changes detected. Provide files with --files=path1,path2 or make a change first.');\n return;\n }\n }\n\n const runAgents = options.mode === 'full';\n const reasoning = await reasonAboutChangesHumanReadable(projectPath, files, {\n runAgents,\n scanContext: {\n config: { timeoutMs: options.mode === 'quick' ? 15000 : 60000 }\n }\n });\n\n printResult(reasoning);\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","/**\n * Pre-push Command Handler\n * \n * Runs before git push with blocking support for critical issues.\n * \n * Exit codes:\n * - 0: Push allowed\n * - 1: Push blocked (fatal error)\n * - 2: Push blocked due to critical issues (bypassable)\n */\n\nimport { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { \n getAutonomyConfig, \n shouldBlockPush,\n recordBypass,\n trackIssueOccurrence \n} from '../utils/autonomy-config.js';\nimport pc from 'picocolors';\n\ninterface PrePushOptions {\n block: boolean;\n bypassed: boolean;\n quick: boolean;\n}\n\nfunction parseArgs(args: string[]): PrePushOptions {\n return {\n block: args.includes('--block'),\n bypassed: args.includes('--bypassed'),\n quick: args.includes('--quick') || args.includes('-q'),\n };\n}\n\nexport async function handlePrePushCommand(args: string[]): Promise<void> {\n const options = parseArgs(args);\n const projectPath = getWorkingDirectory(undefined, true);\n \n try {\n // Load autonomy config\n const autonomyConfig = await getAutonomyConfig(projectPath);\n \n // If bypassed, log and allow\n if (options.bypassed) {\n console.error(pc.yellow('Pre-push check bypassed by user'));\n \n // Log the bypass for audit trail\n if (autonomyConfig.pushBlocking.logBypasses) {\n await recordBypass(\n projectPath,\n 'git-push',\n undefined,\n 'pre-push-bypass',\n 'env',\n 'User set TRIE_BYPASS=1'\n );\n }\n \n process.exit(0);\n }\n \n // Get changed files\n const perception = await perceiveCurrentChanges(projectPath);\n const files = perception.diffSummary.files.map((f) => f.filePath);\n \n if (files.length === 0) {\n console.error(pc.green('✓ No changes to check'));\n process.exit(0);\n }\n \n console.error(pc.cyan(`\\n🔍 Checking ${files.length} file(s) before push...\\n`));\n \n // Run quick analysis\n const reasoning = await reasonAboutChangesHumanReadable(projectPath, files, {\n runAgents: !options.quick,\n scanContext: {\n config: { timeoutMs: options.quick ? 15000 : 30000 }\n }\n });\n \n // Check if we should block\n if (options.block && autonomyConfig.pushBlocking.enabled) {\n // Collect issues for blocking check\n const issues = collectIssuesForBlocking(reasoning);\n \n // Track occurrences for progressive escalation\n for (const issue of issues) {\n await trackIssueOccurrence(\n projectPath,\n issue.file,\n issue.line,\n issue.severity,\n autonomyConfig\n );\n }\n \n const blockResult = shouldBlockPush(issues, autonomyConfig);\n \n if (blockResult.blocked) {\n // Print blocking message\n console.error('');\n console.error(pc.red('━'.repeat(60)));\n console.error(pc.bold(pc.red('PUSH BLOCKED')));\n console.error(pc.red('━'.repeat(60)));\n console.error('');\n console.error(pc.yellow(`Found ${blockResult.blockingIssues.length} blocking issue(s):`));\n console.error('');\n \n // Show top blocking issues\n for (const issue of blockResult.blockingIssues.slice(0, 5)) {\n const icon = issue.severity === 'critical' ? '[!]' : '[!]';\n console.error(` ${icon} ${pc.dim(issue.file)}${issue.line ? `:${issue.line}` : ''}`);\n console.error(` ${issue.issue.slice(0, 80)}${issue.issue.length > 80 ? '...' : ''}`);\n }\n \n if (blockResult.blockingIssues.length > 5) {\n console.error(` ... and ${blockResult.blockingIssues.length - 5} more`);\n }\n \n console.error('');\n console.error(pc.dim('─'.repeat(60)));\n \n if (blockResult.bypassInstructions) {\n console.error('');\n console.error(pc.yellow('To bypass (not recommended):'));\n for (const line of blockResult.bypassInstructions.split('\\n')) {\n console.error(pc.dim(line));\n }\n }\n \n console.error('');\n console.error(pc.cyan('To fix issues:'));\n console.error(pc.dim(' trie fix # Auto-fix trivial issues'));\n console.error(pc.dim(' trie scan # See all issues'));\n console.error('');\n \n // Exit with code 2 to indicate bypassable block\n process.exit(2);\n } else if (blockResult.bypassed) {\n console.error(pc.yellow(`Bypassed: ${blockResult.blockingIssues.length} issue(s) ignored`));\n }\n }\n \n // Print summary\n const riskLevel = reasoning.original?.riskLevel || 'low';\n const riskColor = riskLevel === 'critical' ? pc.red : \n riskLevel === 'high' ? pc.yellow : \n riskLevel === 'medium' ? pc.blue : pc.green;\n \n console.error('');\n console.error(riskColor(`Risk: ${riskLevel.toUpperCase()}`));\n console.error(pc.dim(reasoning.summary || 'No significant risks detected'));\n console.error('');\n \n // Allow push\n process.exit(0);\n \n } catch (error) {\n // On error, don't block the push\n const friendly = formatFriendlyError(error);\n console.error(pc.yellow(`Pre-push check error: ${friendly.userMessage}`));\n console.error(pc.dim('Allowing push to continue.'));\n process.exit(0);\n }\n}\n\n/**\n * Collect issues from reasoning result for blocking check\n */\nfunction collectIssuesForBlocking(reasoning: any): Array<{\n file: string;\n line?: number;\n severity: string;\n issue: string;\n}> {\n const issues: Array<{ file: string; line?: number; severity: string; issue: string }> = [];\n \n // Extract from original reasoning\n if (reasoning.original?.files) {\n for (const file of reasoning.original.files) {\n if (file.level === 'critical' || file.level === 'high') {\n issues.push({\n file: file.file,\n severity: file.level === 'critical' ? 'critical' : 'serious',\n issue: file.reasons?.join('; ') || 'High-risk file',\n });\n }\n }\n }\n \n // Extract from scan results if available\n if (reasoning.scanResults?.issues) {\n for (const issue of reasoning.scanResults.issues) {\n if (issue.severity === 'critical' || issue.severity === 'serious') {\n issues.push({\n file: issue.file,\n line: issue.line,\n severity: issue.severity,\n issue: issue.issue,\n });\n }\n }\n }\n \n return issues;\n}\n","/**\n * Auto-Fix with Human-in-the-Loop\n * \n * Applies fixes to code issues with user confirmation.\n * Supports batch fixing and individual review.\n */\n\nimport { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { createInterface } from 'readline';\nimport pc from 'picocolors';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getAutonomyConfig, shouldAutoFix } from '../utils/autonomy-config.js';\nimport { applyAutoFix } from '../utils/auto-fix-apply.js';\nimport type { AutoFixAction } from '../types/autonomy.js';\nimport type { Issue } from '../types/index.js';\n\n// ============================================================================\n// Fix Detection\n// ============================================================================\n\n/**\n * Detect auto-fixable issues and generate fix actions\n */\nexport function detectAutoFixes(issues: Issue[]): AutoFixAction[] {\n const fixes: AutoFixAction[] = [];\n \n for (const issue of issues) {\n const fix = generateFixForIssue(issue);\n if (fix) {\n fixes.push(fix);\n }\n }\n \n return fixes;\n}\n\n/**\n * Generate a fix action for an issue\n */\nfunction generateFixForIssue(issue: Issue): AutoFixAction | null {\n // Only generate fixes for issues with line numbers\n if (!issue.line) return null;\n \n // Console.log removal\n if (issue.issue.toLowerCase().includes('console.log') || \n issue.issue.toLowerCase().includes('console log')) {\n return {\n id: `fix-${issue.id}`,\n file: issue.file,\n line: issue.line,\n original: '', // Will be filled when reading file\n fixed: '', // Will be deletion\n type: 'remove-console-log',\n category: 'trivial',\n description: 'Remove console.log statement',\n confidence: 0.95,\n };\n }\n \n // Debugger removal\n if (issue.issue.toLowerCase().includes('debugger')) {\n return {\n id: `fix-${issue.id}`,\n file: issue.file,\n line: issue.line,\n original: '',\n fixed: '',\n type: 'remove-debugger',\n category: 'trivial',\n description: 'Remove debugger statement',\n confidence: 0.98,\n };\n }\n \n // Additional fix types can be implemented here:\n // - Remove unused imports\n // - Add missing await\n // - Fix typos\n \n return null;\n}\n\n// ============================================================================\n// User Interaction\n// ============================================================================\n\n/**\n * Prompt user for confirmation\n */\nasync function promptUser(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n \n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.toLowerCase().trim());\n });\n });\n}\n\n/**\n * Display a fix preview\n */\nfunction displayFixPreview(fix: AutoFixAction, index: number, total: number): void {\n console.error('');\n console.error(pc.cyan(`━━━ Fix ${index + 1}/${total} ━━━`));\n console.error(pc.dim(`File: ${fix.file}${fix.line ? `:${fix.line}` : ''}`));\n console.error(pc.dim(`Type: ${fix.type}`));\n console.error(pc.yellow(`Description: ${fix.description}`));\n console.error('');\n \n if (fix.original) {\n console.error(pc.red('- ' + fix.original));\n }\n if (fix.fixed) {\n console.error(pc.green('+ ' + fix.fixed));\n } else if (fix.original) {\n console.error(pc.dim(' (line will be removed)'));\n }\n console.error('');\n}\n\n// ============================================================================\n// Fix Application\n// ============================================================================\n\n/**\n * Load actual line content for fixes\n */\nasync function loadFixContent(fixes: AutoFixAction[]): Promise<AutoFixAction[]> {\n const enrichedFixes: AutoFixAction[] = [];\n \n for (const fix of fixes) {\n if (!fix.line || !existsSync(fix.file)) {\n continue;\n }\n \n try {\n const content = await readFile(fix.file, 'utf-8');\n const lines = content.split('\\n');\n const originalLine = lines[fix.line - 1];\n \n if (originalLine) {\n enrichedFixes.push({\n ...fix,\n original: originalLine,\n });\n }\n } catch {\n // Skip files we can't read\n }\n }\n \n return enrichedFixes;\n}\n\n// ============================================================================\n// Main Command Handler\n// ============================================================================\n\n/**\n * Handle the auto-fix command with human-in-the-loop\n */\nexport async function handleAutoFixCommand(args: string[], issues?: Issue[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const config = await getAutonomyConfig(projectPath);\n \n // Check if auto-fix is enabled\n if (!config.autoFix.enabled) {\n console.error(pc.yellow('Auto-fix is disabled in config.'));\n console.error(pc.dim('Enable it with: trie config set autoFix.enabled true'));\n return;\n }\n \n // Parse args\n const dryRun = args.includes('--dry-run');\n const skipConfirm = args.includes('--yes') || args.includes('-y');\n \n // If no issues provided, we'd need to run a scan first\n if (!issues || issues.length === 0) {\n console.error(pc.yellow('No issues provided. Run a scan first:'));\n console.error(pc.dim(' trie scan --fix'));\n return;\n }\n \n // Detect auto-fixable issues\n let fixes = detectAutoFixes(issues);\n \n if (fixes.length === 0) {\n console.error(pc.green('✓ No auto-fixable issues found.'));\n return;\n }\n \n // Filter by config\n fixes = fixes.filter(fix => shouldAutoFix(fix, config));\n \n if (fixes.length === 0) {\n console.error(pc.yellow('Found fixable issues but they are not in allowed categories.'));\n console.error(pc.dim('Allowed categories: ' + config.autoFix.categories.join(', ')));\n return;\n }\n \n // Load actual line content\n fixes = await loadFixContent(fixes);\n \n if (fixes.length === 0) {\n console.error(pc.yellow('Could not load fix content from files.'));\n return;\n }\n \n // Summary\n console.error('');\n console.error(pc.cyan('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));\n console.error(pc.bold('Auto-Fix: Human-in-the-Loop'));\n console.error(pc.cyan('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));\n console.error('');\n console.error(`Found ${pc.bold(fixes.length.toString())} auto-fixable issues:`);\n \n // Group by category\n const byCategory = new Map<string, number>();\n for (const fix of fixes) {\n byCategory.set(fix.category, (byCategory.get(fix.category) || 0) + 1);\n }\n for (const [cat, count] of byCategory) {\n console.error(` • ${cat}: ${count}`);\n }\n console.error('');\n \n if (dryRun) {\n console.error(pc.yellow('[DRY RUN] No changes will be made.'));\n console.error('');\n \n for (let i = 0; i < fixes.length; i++) {\n displayFixPreview(fixes[i]!, i, fixes.length);\n }\n return;\n }\n \n // Always ask for confirmation (human-in-the-loop)\n if (config.autoFix.askFirst && !skipConfirm) {\n console.error(pc.yellow('Trie will ask before applying each fix.'));\n console.error('');\n \n const response = await promptUser(\n `Apply all ${fixes.length} fixes? (y)es / (n)o / (r)eview each: `\n );\n \n if (response === 'n' || response === 'no') {\n console.error(pc.dim('Cancelled.'));\n return;\n }\n \n if (response === 'r' || response === 'review') {\n // Review each fix individually\n let applied = 0;\n let skipped = 0;\n \n for (let i = 0; i < fixes.length; i++) {\n const fix = fixes[i]!;\n displayFixPreview(fix, i, fixes.length);\n \n const answer = await promptUser('Apply this fix? (y/n/q): ');\n \n if (answer === 'q' || answer === 'quit') {\n console.error(pc.dim('Stopped.'));\n break;\n }\n \n if (answer === 'y' || answer === 'yes') {\n const success = await applyAutoFix(fix);\n if (success) {\n console.error(pc.green(`✓ Applied fix to ${fix.file}:${fix.line}`));\n applied++;\n } else {\n console.error(pc.red(`✗ Failed to apply fix`));\n }\n } else {\n console.error(pc.dim('Skipped.'));\n skipped++;\n }\n }\n \n console.error('');\n console.error(pc.cyan('━━━ Summary ━━━'));\n console.error(`Applied: ${pc.green(applied.toString())}`);\n console.error(`Skipped: ${pc.dim(skipped.toString())}`);\n return;\n }\n }\n \n // Apply all fixes\n console.error('');\n console.error(pc.cyan('Applying fixes...'));\n console.error('');\n \n let applied = 0;\n let failed = 0;\n \n for (const fix of fixes) {\n const success = await applyAutoFix(fix);\n if (success) {\n console.error(pc.green(`✓ Applied fix to ${fix.file}:${fix.line}`));\n applied++;\n } else {\n console.error(pc.red(`✗ Failed to apply fix to ${fix.file}:${fix.line}`));\n failed++;\n }\n }\n \n console.error('');\n console.error(pc.cyan('━━━ Complete ━━━'));\n console.error(`Applied: ${pc.green(applied.toString())}`);\n if (failed > 0) {\n console.error(`Failed: ${pc.red(failed.toString())}`);\n }\n}\n\n/**\n * Interactive fix prompt for dashboard\n * Returns true if user wants to fix, false otherwise\n */\nexport async function promptForAutoFix(\n fixes: AutoFixAction[],\n config: { askFirst: boolean }\n): Promise<'all' | 'review' | 'none'> {\n if (fixes.length === 0) return 'none';\n \n console.error('');\n console.error(pc.cyan(`Found ${fixes.length} auto-fixable issues.`));\n \n if (!config.askFirst) {\n return 'all';\n }\n \n const response = await promptUser(\n 'Fix them? (y)es all / (r)eview / (n)o: '\n );\n \n if (response === 'y' || response === 'yes') return 'all';\n if (response === 'r' || response === 'review') return 'review';\n return 'none';\n}\n","/**\n * Auto-Fix Apply - Apply auto-fix actions to files\n * \n * Extracted from auto-fix.ts for reuse by watch mode and other tools\n */\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport type { AutoFixAction } from '../types/autonomy.js';\n\n/**\n * Apply a single fix to a file\n * Returns true if successful, false otherwise\n */\nexport async function applyAutoFix(fix: AutoFixAction): Promise<boolean> {\n try {\n if (!existsSync(fix.file)) {\n return false;\n }\n \n const content = await readFile(fix.file, 'utf-8');\n const lines = content.split('\\n');\n \n if (fix.line === undefined || fix.line < 1 || fix.line > lines.length) {\n return false;\n }\n \n const lineIndex = fix.line - 1;\n \n // Apply the fix based on type\n let newContent: string;\n \n if (fix.type === 'remove-console-log' || \n fix.type === 'remove-debugger' ||\n fix.fixed === '') {\n // Remove the entire line\n lines.splice(lineIndex, 1);\n newContent = lines.join('\\n');\n } else if (fix.type === 'remove-emoji') {\n // Remove emojis from the line\n const emojiPattern = /[\\u{1F300}-\\u{1F9FF}\\u{2600}-\\u{26FF}\\u{2700}-\\u{27BF}]/gu;\n lines[lineIndex] = lines[lineIndex]!.replace(emojiPattern, '');\n newContent = lines.join('\\n');\n } else if (fix.fixed) {\n // Replace the line\n lines[lineIndex] = fix.fixed;\n newContent = lines.join('\\n');\n } else {\n return false;\n }\n \n // Write the file\n await writeFile(fix.file, newContent);\n \n return true;\n \n } catch {\n return false;\n }\n}\n\n/**\n * Apply multiple fixes to files\n * Returns the number of successfully applied fixes\n */\nexport async function applyAutoFixes(fixes: AutoFixAction[]): Promise<number> {\n let applied = 0;\n \n for (const fix of fixes) {\n const success = await applyAutoFix(fix);\n if (success) {\n applied++;\n }\n }\n \n return applied;\n}\n","/**\n * Goal & Hypothesis CLI Commands\n * \n * Allows users to manually add goals and hypotheses while still\n * allowing Trie to auto-generate them.\n * \n * Commands:\n * - trie goal add \"Reduce auth issues by 50%\"\n * - trie goal list\n * - trie goal complete <id>\n * - trie hypothesis add \"Mondays have more bugs\"\n * - trie hypothesis list\n */\n\nimport pc from 'picocolors';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getProjectState, type Goal, type Hypothesis } from '../agent/project-state.js';\nimport { measureInitialGoalValue } from '../agent/goal-validator.js';\n\n// ============================================================================\n// Goal Commands\n// ============================================================================\n\nexport async function handleGoalCommand(args: string[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const projectState = getProjectState(projectPath);\n await projectState.load();\n \n const subcommand = args[0];\n const restArgs = args.slice(1);\n \n switch (subcommand) {\n case 'add':\n case 'create':\n await addGoal(projectState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listGoals(projectState);\n break;\n \n case 'complete':\n case 'done':\n await completeGoal(projectState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteGoal(projectState, restArgs[0]);\n break;\n \n default:\n if (subcommand && !subcommand.startsWith('-')) {\n // Treat as goal description shorthand: trie goal \"reduce bugs\"\n await addGoal(projectState, [subcommand, ...restArgs]);\n } else {\n printGoalHelp();\n }\n }\n}\n\nasync function addGoal(projectState: ReturnType<typeof getProjectState>, args: string[]): Promise<void> {\n const description = args.join(' ').replace(/^[\"']|[\"']$/g, '');\n \n if (!description) {\n console.error(pc.red('Please provide a goal description.'));\n console.error(pc.dim('Example: trie goal add \"Reduce auth issues by 50%\"'));\n return;\n }\n \n // Parse optional flags\n const categoryMatch = description.match(/--category[=\\s](\\w+)/);\n const targetMatch = description.match(/--target[=\\s](\\d+)/);\n const deadlineMatch = description.match(/--deadline[=\\s](\\S+)/);\n \n // Clean description of flags\n let cleanDesc = description\n .replace(/--category[=\\s]\\w+/g, '')\n .replace(/--target[=\\s]\\d+/g, '')\n .replace(/--deadline[=\\s]\\S+/g, '')\n .trim();\n \n // Detect goal type and target from description\n const reductionMatch = cleanDesc.match(/reduce.*?(\\d+)%/i);\n const eliminateMatch = cleanDesc.match(/eliminate|remove all|zero/i);\n const streakMatch = cleanDesc.match(/(\\d+)\\s*days?\\s*(streak|in a row|consecutive)/i);\n \n let goalType: Goal['type'] = 'custom';\n let target = 100;\n let metric = 'progress';\n \n if (reductionMatch && reductionMatch[1]) {\n goalType = 'reduction';\n target = parseInt(reductionMatch[1], 10);\n metric = 'reduction_percent';\n } else if (eliminateMatch) {\n goalType = 'reduction';\n target = 100;\n metric = 'elimination';\n } else if (streakMatch && streakMatch[1]) {\n goalType = 'streak';\n target = parseInt(streakMatch[1], 10);\n metric = 'days_streak';\n }\n \n // Override with explicit flags\n if (targetMatch && targetMatch[1]) {\n target = parseInt(targetMatch[1], 10);\n }\n \n const category = (categoryMatch?.[1] as Goal['category']) || detectCategory(cleanDesc);\n \n // Calculate deadline (default: 14 days)\n const deadline = new Date();\n if (deadlineMatch && deadlineMatch[1]) {\n const days = parseInt(deadlineMatch[1], 10);\n deadline.setDate(deadline.getDate() + (isNaN(days) ? 14 : days));\n } else {\n deadline.setDate(deadline.getDate() + 14);\n }\n \n // Measure initial value based on existing issues\n const workDir = getWorkingDirectory(undefined, true);\n const initialValue = await measureInitialGoalValue(cleanDesc, workDir);\n \n const goal: Goal = {\n id: `goal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n description: cleanDesc,\n type: goalType,\n metric,\n target,\n currentValue: initialValue,\n startValue: initialValue,\n status: 'active',\n autoGenerated: false, // User-created\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n deadline: deadline.toISOString(),\n category,\n };\n \n await projectState.addGoal(goal);\n \n console.error('');\n console.error(pc.green('✓ Goal created'));\n console.error('');\n console.error(pc.bold(cleanDesc));\n console.error(pc.dim(`ID: ${goal.id}`));\n console.error(pc.dim(`Type: ${goalType} | Target: ${target} | Category: ${category}`));\n if (initialValue > 0) {\n console.error(pc.dim(`Starting value: ${initialValue} issues found`));\n }\n console.error(pc.dim(`Deadline: ${deadline.toLocaleDateString()}`));\n console.error('');\n console.error(pc.cyan('Progress will be tracked and you\\'ll be notified when you achieve it!'));\n}\n\nasync function listGoals(projectState: ReturnType<typeof getProjectState>): Promise<void> {\n const goals = projectState.getAllGoals();\n \n if (goals.length === 0) {\n console.error(pc.dim('No goals yet.'));\n console.error(pc.dim('Create one: trie goal add \"Reduce auth issues by 50%\"'));\n return;\n }\n \n console.error('');\n console.error(pc.bold('Goals'));\n console.error('');\n \n const active = goals.filter(g => g.status === 'active');\n const achieved = goals.filter(g => g.status === 'achieved');\n const other = goals.filter(g => g.status !== 'active' && g.status !== 'achieved');\n \n if (active.length > 0) {\n console.error(pc.cyan('Active:'));\n for (const goal of active) {\n const progress = calculateGoalProgress(goal);\n const bar = renderProgressBar(progress);\n const source = goal.autoGenerated ? pc.dim('[auto]') : pc.dim('[manual]');\n console.error(` ${bar} ${goal.description} ${source}`);\n console.error(pc.dim(` ID: ${goal.id} | ${progress}% complete`));\n }\n console.error('');\n }\n \n if (achieved.length > 0) {\n console.error(pc.green('Achieved:'));\n for (const goal of achieved) {\n console.error(` [+] ${goal.description}`);\n }\n console.error('');\n }\n \n if (other.length > 0) {\n console.error(pc.dim('Other:'));\n for (const goal of other) {\n const icon = goal.status === 'failed' ? '[X]' : goal.status === 'paused' ? '[P]' : '•';\n console.error(` ${icon} ${goal.description} (${goal.status})`);\n }\n }\n}\n\nasync function completeGoal(projectState: ReturnType<typeof getProjectState>, goalId: string | undefined): Promise<void> {\n if (!goalId) {\n console.error(pc.red('Please provide a goal ID.'));\n console.error(pc.dim('Run \"trie goal list\" to see IDs.'));\n return;\n }\n \n const goals = projectState.getAllGoals();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const goal = goals.find(g => g.id === goalId || g.id.startsWith(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await projectState.updateGoal(goal.id, {\n status: 'achieved',\n currentValue: goal.target,\n achievedAt: new Date().toISOString(),\n });\n \n console.error('');\n console.error(pc.green('Goal achieved!'));\n console.error(pc.bold(goal.description));\n console.error('');\n}\n\nasync function deleteGoal(projectState: ReturnType<typeof getProjectState>, goalId: string | undefined): Promise<void> {\n if (!goalId) {\n console.error(pc.red('Please provide a goal ID.'));\n return;\n }\n \n const goals = projectState.getAllGoals();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const goal = goals.find(g => g.id === goalId || g.id.startsWith(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await projectState.updateGoal(goal.id, { status: 'rejected' });\n console.error(pc.dim(`Removed goal: ${goal.description}`));\n}\n\n/**\n * Calculate goal progress correctly for both increase and reduction goals.\n * For reduction goals (startValue > target): progress = (startValue - currentValue) / (startValue - target)\n * For increase goals (startValue <= target): progress = currentValue / target\n */\nfunction calculateGoalProgress(goal: { startValue?: number | undefined; currentValue: number; target: number }): number {\n if (goal.target <= 0) return 0;\n \n const startValue = goal.startValue ?? goal.currentValue;\n \n // Reduction goal: startValue > target (e.g., reduce from 20 to 10)\n if (startValue > goal.target) {\n const totalReduction = startValue - goal.target;\n // Guard against division by zero when startValue === target\n if (totalReduction === 0) return 100; // Already at target\n const actualReduction = startValue - goal.currentValue;\n return Math.round((actualReduction / totalReduction) * 100);\n }\n \n // Increase goal: progress toward target\n return Math.round((goal.currentValue / goal.target) * 100);\n}\n\nfunction renderProgressBar(percent: number): string {\n const width = 10;\n const clamped = Math.max(0, Math.min(100, percent)); // Clamp to 0-100\n const filled = Math.round((clamped / 100) * width);\n const empty = width - filled;\n return `[${pc.green('█'.repeat(filled))}${pc.gray('░'.repeat(empty))}]`;\n}\n\nfunction detectCategory(description: string): Goal['category'] {\n const lower = description.toLowerCase();\n if (/security|auth|password|token|xss|sql|inject/i.test(lower)) return 'security';\n if (/quality|bug|issue|error|fix/i.test(lower)) return 'quality';\n if (/performance|speed|fast|slow|latency/i.test(lower)) return 'performance';\n if (/coverage|test|spec/i.test(lower)) return 'coverage';\n return 'general';\n}\n\nfunction printGoalHelp(): void {\n console.error('');\n console.error(pc.bold('trie goal - Manage guardian goals'));\n console.error('');\n console.error(pc.cyan('Usage:'));\n console.error(' trie goal add \"Reduce auth issues by 50%\"');\n console.error(' trie goal list');\n console.error(' trie goal complete <id>');\n console.error(' trie goal delete <id>');\n console.error('');\n console.error(pc.cyan('Options for add:'));\n console.error(' --category=security|quality|performance|coverage|general');\n console.error(' --target=<number>');\n console.error(' --deadline=<days>');\n console.error('');\n console.error(pc.cyan('Examples:'));\n console.error(' trie goal add \"Eliminate all critical security issues\"');\n console.error(' trie goal add \"7 days streak of clean builds\"');\n console.error(' trie goal add \"Reduce test flakiness by 80%\" --category=quality');\n console.error('');\n}\n\n// ============================================================================\n// Hypothesis Commands\n// ============================================================================\n\nexport async function handleHypothesisCommand(args: string[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const projectState = getProjectState(projectPath);\n await projectState.load();\n \n const subcommand = args[0];\n const restArgs = args.slice(1);\n \n switch (subcommand) {\n case 'add':\n case 'create':\n await addHypothesis(projectState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listHypotheses(projectState);\n break;\n \n case 'validate':\n await validateHypothesis(projectState, restArgs[0]);\n break;\n \n case 'invalidate':\n await invalidateHypothesis(projectState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteHypothesis(projectState, restArgs[0]);\n break;\n \n default:\n if (subcommand && !subcommand.startsWith('-')) {\n // Treat as hypothesis statement shorthand\n await addHypothesis(projectState, [subcommand, ...restArgs]);\n } else {\n printHypothesisHelp();\n }\n }\n}\n\nasync function addHypothesis(projectState: ReturnType<typeof getProjectState>, args: string[]): Promise<void> {\n const statement = args.join(' ').replace(/^[\"']|[\"']$/g, '');\n \n if (!statement) {\n console.error(pc.red('Please provide a hypothesis statement.'));\n console.error(pc.dim('Example: trie hypothesis add \"Mondays have more bugs than Fridays\"'));\n return;\n }\n \n // Parse optional flags\n const categoryMatch = statement.match(/--category[=\\s](\\w+)/);\n const testMatch = statement.match(/--test[=\\s][\"']([^\"']+)[\"']/);\n \n let cleanStatement = statement\n .replace(/--category[=\\s]\\w+/g, '')\n .replace(/--test[=\\s][\"'][^\"']+[\"']/g, '')\n .trim();\n \n const category = (categoryMatch?.[1] as Hypothesis['category']) || detectHypothesisCategory(cleanStatement);\n const testCriteria = testMatch?.[1] || generateTestCriteria(cleanStatement);\n \n const hypothesis: Hypothesis = {\n id: `hypo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n statement: cleanStatement,\n confidence: 0, // No evidence yet\n status: 'testing',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria,\n category,\n autoGenerated: false,\n };\n \n await projectState.addHypothesis(hypothesis);\n \n console.error('');\n console.error(pc.green('✓ Hypothesis created'));\n console.error('');\n console.error(pc.bold(`\"${cleanStatement}\"`));\n console.error(pc.dim(`ID: ${hypothesis.id}`));\n console.error(pc.dim(`Status: testing | Confidence: untested | Category: ${category}`));\n console.error('');\n console.error(pc.cyan('The agent will collect evidence and update confidence over time.'));\n console.error(pc.dim(`Test criteria: ${testCriteria}`));\n}\n\nasync function listHypotheses(projectState: ReturnType<typeof getProjectState>): Promise<void> {\n const hypotheses = projectState.getAllHypotheses();\n \n if (hypotheses.length === 0) {\n console.error(pc.dim('No hypotheses yet.'));\n console.error(pc.dim('Create one: trie hypothesis add \"Mondays have more bugs\"'));\n return;\n }\n \n console.error('');\n console.error(pc.bold('Hypotheses'));\n console.error('');\n \n const testing = hypotheses.filter(h => h.status === 'testing');\n const validated = hypotheses.filter(h => h.status === 'validated');\n const invalidated = hypotheses.filter(h => h.status === 'invalidated');\n \n if (testing.length > 0) {\n console.error(pc.cyan('Testing:'));\n for (const hypo of testing) {\n const conf = Math.round(hypo.confidence * 100);\n const confColor = conf >= 70 ? pc.green : conf >= 40 ? pc.yellow : pc.red;\n console.error(` [?] \"${hypo.statement}\" ${confColor(`(${conf}% confidence)`)}`);\n console.error(pc.dim(` ID: ${hypo.id} | Evidence: ${hypo.evidence.length} points`));\n }\n console.error('');\n }\n \n if (validated.length > 0) {\n console.error(pc.green('Validated:'));\n for (const hypo of validated) {\n console.error(` [+] \"${hypo.statement}\" (${Math.round(hypo.confidence * 100)}%)`);\n }\n console.error('');\n }\n \n if (invalidated.length > 0) {\n console.error(pc.red('Invalidated:'));\n for (const hypo of invalidated) {\n console.error(` [X] \"${hypo.statement}\"`);\n }\n }\n}\n\nasync function validateHypothesis(projectState: ReturnType<typeof getProjectState>, hypoId: string | undefined): Promise<void> {\n if (!hypoId) {\n console.error(pc.red('Please provide a hypothesis ID.'));\n return;\n }\n \n const hypotheses = projectState.getAllHypotheses();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.startsWith(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await projectState.updateHypothesis(hypo.id, {\n status: 'validated',\n confidence: 0.9,\n validatedAt: new Date().toISOString(),\n });\n \n console.error(pc.green(`Hypothesis validated: \"${hypo.statement}\"`));\n}\n\nasync function invalidateHypothesis(projectState: ReturnType<typeof getProjectState>, hypoId: string | undefined): Promise<void> {\n if (!hypoId) {\n console.error(pc.red('Please provide a hypothesis ID.'));\n return;\n }\n \n const hypotheses = projectState.getAllHypotheses();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.startsWith(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await projectState.updateHypothesis(hypo.id, {\n status: 'invalidated',\n confidence: 0.1,\n });\n \n console.error(pc.red(`Hypothesis invalidated: \"${hypo.statement}\"`));\n}\n\nasync function deleteHypothesis(projectState: ReturnType<typeof getProjectState>, hypoId: string | undefined): Promise<void> {\n if (!hypoId) {\n console.error(pc.red('Please provide a hypothesis ID.'));\n return;\n }\n \n const hypotheses = projectState.getAllHypotheses();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.startsWith(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await projectState.updateHypothesis(hypo.id, { status: 'retired' });\n console.error(pc.dim(`Removed hypothesis: \"${hypo.statement}\"`));\n}\n\nfunction detectHypothesisCategory(statement: string): Hypothesis['category'] {\n const lower = statement.toLowerCase();\n if (/monday|friday|weekend|morning|night|time|day|hour/i.test(lower)) return 'timing';\n if (/pattern|recurring|always|never|consistently/i.test(lower)) return 'pattern';\n if (/team|developer|engineer|review/i.test(lower)) return 'team';\n if (/code|file|function|class|module|refactor/i.test(lower)) return 'code';\n return 'general';\n}\n\nfunction generateTestCriteria(statement: string): string {\n const lower = statement.toLowerCase();\n \n if (lower.includes('monday')) {\n return 'Compare Monday issue counts to weekly average';\n }\n if (lower.includes('friday')) {\n return 'Compare Friday issue introduction rate to other days';\n }\n if (lower.includes('more bug') || lower.includes('more issue')) {\n return 'Compare issue counts between conditions over time';\n }\n if (lower.includes('causes') || lower.includes('leads to')) {\n return 'Track correlation between trigger and outcome events';\n }\n \n return 'Collect supporting and contradicting evidence from scans';\n}\n\nfunction printHypothesisHelp(): void {\n console.error('');\n console.error(pc.bold('trie hypothesis - Manage project hypotheses'));\n console.error('');\n console.error(pc.cyan('Usage:'));\n console.error(' trie hypothesis add \"Mondays have more bugs than Fridays\"');\n console.error(' trie hypothesis list');\n console.error(' trie hypothesis validate <id>');\n console.error(' trie hypothesis invalidate <id>');\n console.error(' trie hypothesis delete <id>');\n console.error('');\n console.error(pc.cyan('Options for add:'));\n console.error(' --category=timing|pattern|team|code|general');\n console.error(' --test=\"<test criteria>\"');\n console.error('');\n console.error(pc.cyan('Examples:'));\n console.error(' trie hypothesis add \"Code reviews reduce bug rate\"');\n console.error(' trie hypothesis add \"Auth module has highest churn\"');\n console.error(' trie hypothesis add \"Deploy Fridays cause weekend incidents\"');\n console.error('');\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData } from '../context/nodes.js';\nimport { exportToJson } from '../context/sync.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport type { RiskLevel } from '../types/index.js';\n\nfunction escalateRisk(level: RiskLevel): RiskLevel {\n if (level === 'low') return 'medium';\n if (level === 'medium') return 'high';\n if (level === 'high') return 'critical';\n return 'critical';\n}\n\nfunction extractFilePathsFromDescription(description: string): string[] {\n const matches = description.match(/[\\\\w./_-]+\\\\.(ts|tsx|js|jsx|mjs|cjs)/gi);\n if (!matches) return [];\n const unique = new Set<string>();\n matches.forEach((m) => unique.add(m.replace(/^\\.\\/+/, '')));\n return Array.from(unique);\n}\n\nexport async function handleTellCommand(args: string[]): Promise<void> {\n try {\n const projectPath = getWorkingDirectory(undefined, true);\n const description = args.join(' ').trim();\n if (!description) {\n console.log('Usage: trie tell \"<incident description>\"');\n return;\n }\n\n const graph = new ContextGraph(projectPath);\n const now = new Date().toISOString();\n const change = (await graph.getRecentChanges(1))[0];\n\n const incident = await graph.addNode('incident', {\n description,\n severity: 'major',\n affectedUsers: null,\n duration: null,\n timestamp: now,\n resolved: false,\n resolution: null,\n fixChangeId: change?.id ?? null,\n reportedVia: 'manual'\n });\n\n const linkedFiles = new Set<string>();\n\n if (change) {\n await graph.addEdge(change.id, incident.id, 'leadTo');\n await graph.addEdge(incident.id, change.id, 'causedBy');\n\n for (const filePath of change.data.files) {\n linkedFiles.add(filePath);\n const fileNode = await graph.getNode('file', path.resolve(projectPath, filePath));\n if (fileNode) {\n const data = fileNode.data as FileNodeData;\n await graph.updateNode('file', fileNode.id, {\n incidentCount: (data.incidentCount ?? 0) + 1,\n riskLevel: escalateRisk(data.riskLevel)\n });\n }\n }\n }\n\n // Also extract file paths from the incident description\n const mentionedFiles = extractFilePathsFromDescription(description);\n mentionedFiles.forEach((f) => linkedFiles.add(f));\n\n // Update trie-backed incident index for O(m) lookups\n const incidentIndex = new IncidentIndex(graph, projectPath);\n incidentIndex.addIncidentToTrie(incident, Array.from(linkedFiles));\n\n await exportToJson(graph);\n\n console.log('Incident recorded.');\n if (change) {\n console.log(`Linked to change: ${change.id}`);\n } else {\n console.log('No recent change found; incident recorded without linkage.');\n }\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { importFromJson } from '../context/sync.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport path from 'node:path';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nasync function removeOrphanEdges(graph: ContextGraph): Promise<number> {\n const nodes = await graph.listNodes();\n const nodeIds = new Set(nodes.map((n) => n.id));\n const edges = await graph.listEdges();\n let removed = 0;\n\n for (const edge of edges) {\n if (!nodeIds.has(edge.from_id) || !nodeIds.has(edge.to_id)) {\n await graph.deleteEdge(edge.id);\n removed++;\n }\n }\n\n return removed;\n}\n\nexport async function handleReconcileCommand(args: string[]): Promise<void> {\n try {\n const projectPath = getWorkingDirectory(undefined, true);\n const source = args.find((a) => a.startsWith('--from='))?.replace('--from=', '') ??\n path.join(getTrieDirectory(projectPath), 'context.json');\n\n const graph = new ContextGraph(projectPath);\n await importFromJson(graph, '', source);\n\n const removed = await removeOrphanEdges(graph);\n console.log(`Reconciled context from ${source}. Removed ${removed} orphaned edges.`);\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\n\nexport async function handleQuietCommand(): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const quietPath = path.join(getTrieDirectory(projectPath), 'quiet.json');\n\n const until = new Date(Date.now() + 60 * 60 * 1000).toISOString(); // 1 hour\n const payload = { until };\n\n try {\n const dir = path.dirname(quietPath);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(quietPath, JSON.stringify(payload, null, 2));\n console.log('🔕 Nudges snoozed for 1 hour.');\n } catch (error) {\n console.error('Failed to set quiet mode:', error);\n }\n}\n","/**\n * CI/CD Setup Command\n * \n * Generates GitHub Actions workflow with memory caching\n * for cross-run learning and pattern recognition.\n */\n\nimport { writeFileSync, existsSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport pc from 'picocolors';\n\nconst WORKFLOW_TEMPLATE = `# Trie Security Scan with Memory Persistence\n# Generated by: trie ci\n# \n# This workflow scans your code and caches Trie's memory\n# across runs for cross-run learning and pattern recognition.\n\nname: Trie Security Scan\n\non:\n push:\n branches: [main, master, develop]\n pull_request:\n branches: [main, master]\n\njobs:\n security-scan:\n runs-on: ubuntu-latest\n permissions:\n security-events: write\n pull-requests: write\n contents: read\n\n steps:\n - name: Checkout\n uses: actions/checkout@v4\n\n # Restore Trie memory from previous runs\n # This enables cross-run learning and pattern recognition\n - name: Restore Trie Memory\n uses: actions/cache@v4\n with:\n path: |\n .trie/memory\n .trie/context\n .trie/summaries\n key: trie-memory-\\${{ github.repository }}-\\${{ github.ref_name }}\n restore-keys: |\n trie-memory-\\${{ github.repository }}-\n trie-memory-\n\n - name: Setup Node.js\n uses: actions/setup-node@v4\n with:\n node-version: '20'\n\n - name: Install Trie\n run: npm install -g @triedotdev/mcp\n\n - name: Run Security Scan\n run: |\n trie scan --format sarif --output trie-results.sarif\n env:\n ANTHROPIC_API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n\n - name: Upload SARIF Results\n uses: github/codeql-action/upload-sarif@v3\n if: always()\n with:\n sarif_file: trie-results.sarif\n continue-on-error: true\n\n # Memory is automatically saved by cache action on job completion\n`;\n\nconst WORKFLOW_MINIMAL = `# Trie Security Scan (Minimal)\n# Generated by: trie ci --minimal\n\nname: Trie Scan\n\non: [push, pull_request]\n\njobs:\n scan:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n \n # Cache Trie memory for cross-run learning\n - uses: actions/cache@v4\n with:\n path: .trie/memory\n key: trie-memory-\\${{ github.repository }}\n \n - run: npm install -g @triedotdev/mcp\n - run: trie scan\n env:\n ANTHROPIC_API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n`;\n\nexport function handleCISetupCommand(args: string[]): void {\n const workDir = getWorkingDirectory(undefined, true);\n const workflowsDir = join(workDir, '.github', 'workflows');\n const workflowPath = join(workflowsDir, 'trie-scan.yml');\n \n // Parse args\n const isMinimal = args.includes('--minimal') || args.includes('-m');\n const isDryRun = args.includes('--dry-run') || args.includes('-n');\n const showHelp = args.includes('--help') || args.includes('-h');\n \n if (showHelp) {\n console.log(`\n${pc.bold('trie ci')} - Generate GitHub Actions workflow with memory caching\n\n${pc.bold('USAGE:')}\n trie ci [options]\n\n${pc.bold('OPTIONS:')}\n --minimal, -m Generate minimal workflow (simpler, fewer features)\n --dry-run, -n Preview workflow without creating files\n --help, -h Show this help\n\n${pc.bold('WHAT IT DOES:')}\n Creates .github/workflows/trie-scan.yml that:\n \n 1. ${pc.green('Caches Trie memory')} - Patterns and fixes persist across runs\n 2. ${pc.green('Enables learning')} - Trie remembers issues from previous PRs\n 3. ${pc.green('Tracks patterns')} - Detects recurring issues across your codebase\n 4. ${pc.green('SARIF upload')} - Results appear in GitHub Security tab\n\n${pc.bold('MEMORY BENEFITS:')}\n • \"This issue was introduced 3 PRs ago\"\n • \"Similar issue was fixed in PR #42\"\n • \"This pattern keeps recurring in auth code\"\n • Trend tracking: improving, stable, or declining\n\n${pc.bold('EXAMPLES:')}\n trie ci # Generate full workflow\n trie ci --minimal # Generate simple workflow\n trie ci --dry-run # Preview without writing\n\n${pc.bold('REQUIRED SECRETS:')}\n ANTHROPIC_API_KEY Your Anthropic API key (add in GitHub repo settings)\n`);\n return;\n }\n \n const template = isMinimal ? WORKFLOW_MINIMAL : WORKFLOW_TEMPLATE;\n \n if (isDryRun) {\n console.log(pc.bold('\\nWorkflow Preview:\\n'));\n console.log(pc.dim('─'.repeat(60)));\n console.log(template);\n console.log(pc.dim('─'.repeat(60)));\n console.log(pc.dim('\\nRun without --dry-run to create the file.'));\n return;\n }\n \n // Check if workflow already exists\n if (existsSync(workflowPath)) {\n console.log(pc.yellow('Workflow already exists: .github/workflows/trie-scan.yml'));\n console.log(pc.dim(' Run with --dry-run to preview what would be written.'));\n console.log(pc.dim(' Delete the existing file to regenerate.'));\n return;\n }\n \n // Create directories if needed\n if (!existsSync(workflowsDir)) {\n mkdirSync(workflowsDir, { recursive: true });\n }\n \n // Write workflow\n writeFileSync(workflowPath, template);\n \n console.log(pc.green('✓') + ' Created .github/workflows/trie-scan.yml');\n console.log('');\n console.log(pc.bold('Next steps:'));\n console.log('');\n console.log(' 1. Add your Anthropic API key to GitHub Secrets:');\n console.log(pc.dim(' Settings → Secrets → Actions → New repository secret'));\n console.log(pc.dim(' Name: ANTHROPIC_API_KEY'));\n console.log('');\n console.log(' 2. Commit and push:');\n console.log(pc.dim(' git add .github/workflows/trie-scan.yml'));\n console.log(pc.dim(' git commit -m \"Add Trie security scan with memory\"'));\n console.log(pc.dim(' git push'));\n console.log('');\n console.log(pc.bold('Memory caching benefits:'));\n console.log(pc.dim(' • Trie learns from past scans'));\n console.log(pc.dim(' • Tracks issue trends over time'));\n console.log(pc.dim(' • Remembers when issues were introduced'));\n console.log(pc.dim(' • Recognizes recurring patterns'));\n}\n","/**\n * Audit CLI Command Handler\n * \n * View security audit logs for skill operations\n */\n\nimport { getRecentAuditLogs, getSkillAuditLogs, getAuditStatistics, formatAuditLog } from '../skills/audit-logger.js';\n\nexport async function handleAuditCommand(args: string[]): Promise<void> {\n const [cmd, ...rest] = args;\n\n switch (cmd) {\n case 'logs':\n case 'list': {\n const limit = rest[0] ? parseInt(rest[0], 10) : 20;\n const logs = await getRecentAuditLogs(limit);\n \n if (logs.length === 0) {\n console.log('\\nNo audit logs found.');\n console.log('Audit logs are created when skills are executed during scans.\\n');\n return;\n }\n \n console.log(`\\nRecent Skill Executions (last ${logs.length}):\\n`);\n \n for (const log of logs) {\n console.log(formatAuditLog(log));\n console.log('');\n }\n \n break;\n }\n \n case 'skill': {\n if (!rest[0]) {\n console.log('Usage: trie audit skill <skill-name>');\n console.log('');\n console.log('View audit logs for a specific skill.');\n return;\n }\n \n const skillName = rest[0];\n const logs = await getSkillAuditLogs(skillName);\n \n if (logs.length === 0) {\n console.log(`\\nNo audit logs found for skill: ${skillName}\\n`);\n return;\n }\n \n console.log(`\\nAudit Logs for ${skillName} (${logs.length} executions):\\n`);\n \n for (const log of logs) {\n console.log(formatAuditLog(log));\n console.log('');\n }\n \n break;\n }\n \n case 'stats':\n case 'statistics': {\n const stats = await getAuditStatistics();\n \n console.log('\\n📊 Audit Statistics\\n');\n console.log(`Total executions: ${stats.totalExecutions}`);\n console.log(` ✅ Successful: ${stats.successfulExecutions}`);\n console.log(` ❌ Failed: ${stats.failedExecutions}`);\n console.log('');\n console.log(`Unique skills executed: ${stats.uniqueSkills}`);\n console.log('');\n console.log(`Commands executed: ${stats.totalCommands}`);\n if (stats.blockedCommands > 0) {\n console.log(` ⚠️ Blocked: ${stats.blockedCommands}`);\n }\n console.log('');\n console.log(`Network calls: ${stats.totalNetworkCalls}`);\n if (stats.blockedNetworkCalls > 0) {\n console.log(` ⚠️ Blocked: ${stats.blockedNetworkCalls}`);\n }\n console.log('');\n \n if (stats.blockedCommands > 0 || stats.blockedNetworkCalls > 0) {\n console.log('⚠️ Some operations were blocked by security policies.');\n console.log('Run \"trie audit logs\" to see details.\\n');\n }\n \n break;\n }\n \n default: {\n console.log(`\nAudit - View security audit logs\n\nTrie logs all skill operations for security auditing. View what\nskills have executed, what commands they ran, and any blocked operations.\n\nCommands:\n trie audit logs [count] Show recent audit logs (default: 20)\n trie audit skill <name> Show logs for a specific skill\n trie audit stats Show audit statistics\n\nExamples:\n trie audit logs 50 Show last 50 executions\n trie audit skill security Show all executions of security skill\n trie audit stats View overall statistics\n\nAudit logs are stored in .trie/audit/ and include:\n • Skill name and source\n • Commands executed\n • Network calls made\n • Files accessed/modified\n • Any blocked operations\n `);\n }\n }\n}\n","import { loadConfig, saveConfig } from '../config/loader.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { LinearIngester } from '../ingest/linear-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function handleLinearCommand(args: string[]): Promise<void> {\n try {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n\n if (subcommand === 'auth') {\n const apiKey = args[1];\n if (!apiKey) {\n console.log('Usage: trie linear auth <your-linear-api-key>');\n return;\n }\n\n const config = await loadConfig();\n if (!config.apiKeys) {\n config.apiKeys = {};\n }\n (config.apiKeys as any).linear = apiKey;\n\n await saveConfig(config);\n console.log('Linear API key saved successfully.');\n return;\n }\n\n if (subcommand === 'sync') {\n const graph = new ContextGraph(workDir);\n const ingester = new LinearIngester(workDir, graph);\n \n console.log('Syncing Linear tickets...');\n await ingester.syncTickets();\n console.log('Linear tickets synced successfully.');\n return;\n }\n\n console.log('Usage:');\n console.log(' trie linear auth <api-key> Save Linear API key');\n console.log(' trie linear sync Sync active tickets');\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { GotchaPredictor } from '../agent/gotcha-predictor.js';\nimport { getStorage } from '../storage/tiered-storage.js';\nimport type { Gotcha } from '../types/signal.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { getStagedChanges, getUncommittedChanges } from '../agent/git.js';\nimport picocolors from 'picocolors';\n\nexport async function handleGotchaCommand(): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const predictor = new GotchaPredictor(workDir, graph);\n\n // Default: predict for current changes\n console.log('Analyzing current changes for \"gotchas\"...');\n \n const staged = await getStagedChanges(workDir);\n const uncommitted = await getUncommittedChanges(workDir);\n const allChanges = [...staged, ...uncommitted].map(c => c.path);\n const uniqueFiles = Array.from(new Set(allChanges));\n\n if (uniqueFiles.length === 0) {\n console.log('No changes detected to analyze.');\n return;\n }\n\n const gotchas = await predictor.predictGotchas(uniqueFiles);\n\n if (gotchas.length === 0) {\n console.log(picocolors.green('✓ No \"gotchas\" predicted for your current changes.'));\n return;\n }\n\n console.log(picocolors.yellow(`\\nFound ${gotchas.length} potential \"gotchas\":\\n`));\n\n // Store gotchas in ledger for Ledger view\n const storage = getStorage(workDir);\n await storage.initialize();\n const primaryFile = uniqueFiles[0];\n for (const gotcha of gotchas) {\n const ledgerGotcha: Gotcha = {\n id: gotcha.id,\n message: gotcha.message,\n confidence: gotcha.confidence,\n riskLevel: gotcha.riskLevel,\n recommendation: gotcha.recommendation,\n ...(primaryFile && { file: primaryFile }),\n timestamp: new Date().toISOString(),\n ...(gotcha.precedentId && { precedentId: gotcha.precedentId }),\n tags: gotcha.evidence.matchingPatterns,\n evidence: gotcha.evidence,\n resolved: false,\n };\n await storage.storeGotcha(ledgerGotcha);\n }\n\n for (const gotcha of gotchas) {\n const color = gotcha.riskLevel === 'critical' ? picocolors.red : \n gotcha.riskLevel === 'high' ? picocolors.yellow : \n picocolors.blue;\n\n console.log(color(`[${gotcha.riskLevel.toUpperCase()}] ${gotcha.message}`));\n \n const explanation = await predictor.synthesizeGotchaExplanation(gotcha);\n if (explanation !== gotcha.message) {\n console.log(picocolors.dim(` ${explanation}`));\n }\n\n console.log(picocolors.cyan(` 💡 Recommendation: ${gotcha.recommendation}`));\n console.log('');\n }\n\n console.log(picocolors.dim(`Stored ${gotchas.length} gotcha(s) in Ledger. View in: trie watch → Ledger tab`));\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { LearningEngine } from '../agent/learning-engine.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { getStagedChanges } from '../agent/git.js';\nimport picocolors from 'picocolors';\n\nexport async function handleLearnCommand(args: string[]): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const engine = new LearningEngine(workDir);\n\n const firstArg = args[0]?.toLowerCase();\n\n // 1. trie learn ok [note]\n if (firstArg === 'ok' || firstArg === 'good') {\n const note = args.slice(1).join(' ');\n const staged = await getStagedChanges(workDir);\n const files = staged.map(s => s.path);\n \n await engine.learn({ \n manualFeedback: { helpful: true, files, note } \n });\n \n console.log(picocolors.green('👍 Learned that this pattern is good.'));\n if (files.length > 0) {\n console.log(picocolors.dim(` Linked to: ${files.join(', ')}`));\n }\n return;\n }\n\n // 2. trie learn bad [note]\n if (firstArg === 'bad' || firstArg === 'wrong') {\n const note = args.slice(1).join(' ');\n const staged = await getStagedChanges(workDir);\n const files = staged.map(s => s.path);\n\n await engine.learn({ \n manualFeedback: { helpful: false, files, note } \n });\n\n console.log(picocolors.yellow('👎 Learned that this pattern is problematic.'));\n if (files.length > 0) {\n console.log(picocolors.dim(` Linked to: ${files.join(', ')}`));\n }\n return;\n }\n\n // 3. trie learn (default: implicit scan)\n console.log(picocolors.cyan('Scanning history for implicit failure signals (reverts/fixes)...'));\n const results = await engine.learn({ limit: 50 });\n const implicit = results.find(r => r.source === 'git-history');\n \n console.log(picocolors.green(`✓ Learned ${implicit?.learned ?? 0} new cases from your git history.`));\n console.log(picocolors.dim(' Trie will now use these precedents to predict future gotchas.'));\n\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","/**\n * Pattern Management CLI\n * \n * Smart pattern saving that captures:\n * A) File structure/architecture patterns\n * B) Code patterns/fixes that worked\n * C) Detection patterns (scout rules)\n */\n\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { readFile, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { basename } from 'path';\nimport picocolors from 'picocolors';\nimport {\n createSavedPattern,\n loadSavedPatterns,\n savePatternToProject,\n savePatternsToProject,\n type SavedPattern,\n} from '../patterns/saved-patterns.js';\n\nexport type { SavedPattern };\n\nexport async function handlePatternsCommand(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n \n try {\n switch (subcommand) {\n case 'save':\n await handleSavePattern(args.slice(1), workDir);\n break;\n case 'list':\n await handleListPatterns(args.slice(1), workDir);\n break;\n case 'export':\n await handleExportPatterns(args.slice(1), workDir);\n break;\n case 'import':\n await handleImportPatterns(args.slice(1), workDir);\n break;\n case 'validate':\n await handleValidatePattern(args.slice(1), workDir);\n break;\n default:\n showPatternsHelp();\n }\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(picocolors.red(`Error: ${friendly.userMessage}`));\n process.exit(1);\n }\n}\n\nasync function handleSavePattern(args: string[], workDir: string): Promise<void> {\n const target = args[0]; // file path, code pattern, or scout name\n const note = args.slice(1).join(' ') || undefined;\n \n if (!target) {\n console.error(picocolors.red('Usage: trie patterns save <target> [note]'));\n console.log(picocolors.dim('\\nExamples:'));\n console.log(' trie patterns save \"path/to/file.ts\" \"Short note about why it worked\"');\n console.log(' trie patterns save \"path/*\" \"Folder structure that worked well\"');\n console.log(' trie patterns save security \"Scout that caught issues early\"');\n process.exit(1);\n }\n \n const savedPattern = await createSavedPattern(target, note, workDir);\n \n // Save to project's saved patterns\n await savePatternToProject(savedPattern, workDir);\n \n console.log(picocolors.green(`✓ Pattern saved: ${target}`));\n if (note) {\n console.log(picocolors.dim(` Note: ${note}`));\n }\n console.log(picocolors.dim(` Type: ${savedPattern.type}`));\n console.log(picocolors.dim(` Export with: trie patterns export`));\n}\n\nasync function handleListPatterns(args: string[], workDir: string): Promise<void> {\n const filter = args[0]?.toLowerCase();\n const patterns = await loadSavedPatterns(workDir);\n \n let filtered = patterns;\n if (filter === 'validated' || filter === 'saved') {\n filtered = patterns.filter(p => filter === 'validated' ? p.validated : true);\n }\n \n if (filtered.length === 0) {\n console.log(picocolors.yellow('No saved patterns found.'));\n console.log(picocolors.dim('Save patterns with: trie patterns save <target> [note]'));\n return;\n }\n \n console.log(picocolors.bold(`\\n📋 Saved Patterns (${filtered.length})\\n`));\n \n for (const pattern of filtered) {\n const typeEmoji = {\n 'file-structure': '📁',\n 'code-pattern': '💻',\n 'detection-rule': '🔍',\n }[pattern.type] || '📌';\n \n console.log(`${typeEmoji} ${picocolors.bold(pattern.name)}`);\n console.log(` Type: ${pattern.type}`);\n if (pattern.description) {\n console.log(` ${picocolors.dim(pattern.description)}`);\n }\n if (pattern.validated) {\n console.log(` ${picocolors.green('✓ Validated')}`);\n if (pattern.validationNotes) {\n console.log(` ${picocolors.dim(pattern.validationNotes)}`);\n }\n }\n console.log(` Projects: ${pattern.projects.join(', ')}`);\n console.log('');\n }\n}\n\nasync function handleExportPatterns(args: string[], workDir: string): Promise<void> {\n const outputPath = args[0] || 'trie-patterns.json';\n const filter = args[1]?.toLowerCase();\n \n let patterns = await loadSavedPatterns(workDir);\n \n if (filter === 'validated' || filter === 'saved') {\n patterns = patterns.filter(p => filter === 'validated' ? p.validated : true);\n }\n \n if (patterns.length === 0) {\n console.error(picocolors.yellow('No patterns to export.'));\n return;\n }\n \n const exportData = {\n version: '1.0',\n exportedAt: new Date().toISOString(),\n exportedFrom: basename(workDir),\n patterns,\n };\n \n await writeFile(outputPath, JSON.stringify(exportData, null, 2));\n \n console.log(picocolors.green(`✓ Exported ${patterns.length} patterns to ${outputPath}`));\n console.log(picocolors.dim(` Import to another project with: trie patterns import ${outputPath}`));\n}\n\nasync function handleImportPatterns(args: string[], workDir: string): Promise<void> {\n const inputPath = args[0];\n \n if (!inputPath) {\n console.error(picocolors.red('Usage: trie patterns import <path-to-patterns.json>'));\n process.exit(1);\n }\n \n if (!existsSync(inputPath)) {\n console.error(picocolors.red(`File not found: ${inputPath}`));\n process.exit(1);\n }\n \n const content = await readFile(inputPath, 'utf-8');\n const importData = JSON.parse(content);\n \n if (!importData.patterns || !Array.isArray(importData.patterns)) {\n console.error(picocolors.red('Invalid pattern file format.'));\n process.exit(1);\n }\n \n const existingPatterns = await loadSavedPatterns(workDir);\n const projectName = basename(workDir);\n let imported = 0;\n let skipped = 0;\n \n for (const pattern of importData.patterns) {\n const existing = existingPatterns.find(p => p.id === pattern.id);\n if (existing) {\n // Update existing pattern\n if (!existing.projects.includes(projectName)) {\n existing.projects.push(projectName);\n }\n existing.occurrences++;\n skipped++;\n } else {\n // Add new pattern\n const newPattern: SavedPattern = {\n ...pattern,\n projects: [...pattern.projects, projectName],\n savedBy: importData.exportedFrom || 'unknown',\n };\n existingPatterns.push(newPattern);\n imported++;\n }\n }\n \n await savePatternsToProject(existingPatterns, workDir);\n \n console.log(picocolors.green(`✓ Imported ${imported} new patterns`));\n if (skipped > 0) {\n console.log(picocolors.dim(` Updated ${skipped} existing patterns`));\n }\n console.log(picocolors.dim(` Total patterns: ${existingPatterns.length}`));\n}\n\nasync function handleValidatePattern(args: string[], workDir: string): Promise<void> {\n const patternId = args[0];\n const note = args.slice(1).join(' ') || 'Validated - worked well';\n \n if (!patternId) {\n console.error(picocolors.red('Usage: trie patterns validate <pattern-id> [note]'));\n process.exit(1);\n }\n \n const patterns = await loadSavedPatterns(workDir);\n const pattern = patterns.find(p => p.id === patternId || p.name === patternId);\n \n if (!pattern) {\n console.error(picocolors.red(`Pattern not found: ${patternId}`));\n console.log(picocolors.dim('List patterns with: trie patterns list'));\n process.exit(1);\n }\n \n pattern.validated = true;\n pattern.validationNotes = note;\n \n await savePatternsToProject(patterns, workDir);\n \n console.log(picocolors.green(`✓ Pattern validated: ${pattern.name}`));\n console.log(picocolors.dim(` Note: ${note}`));\n}\n\nfunction showPatternsHelp(): void {\n console.log(`\n${picocolors.bold('Pattern Management')}\n\nSave, validate, and share patterns that worked well across projects.\n\n${picocolors.bold('Commands:')}\n trie patterns save <target> [note] Save a pattern (file, code, or scout)\n trie patterns list [--validated] List saved patterns\n trie patterns export [file] [--validated] Export patterns to JSON\n trie patterns import <file> Import patterns from JSON\n trie patterns validate <id> [note] Mark pattern as validated\n\n${picocolors.bold('Examples:')}\n # Save a file structure pattern\n trie patterns save \"path/*\" \"This folder structure worked well\"\n\n # Save a code pattern\n trie patterns save path/to/file.ts \"This error handling prevented bugs\"\n\n # Save a detection rule\n trie patterns save security \"This scout caught issues early\"\n\n # Validate a pattern\n trie patterns validate pattern-abc123 \"Worked great in production\"\n\n # Export validated patterns\n trie patterns export patterns.json --validated\n\n # Import to another project\n cd ../another-project\n trie patterns import ../source-project/patterns.json\n\n${picocolors.dim('Patterns are saved in .trie/saved-patterns.json')}\n`);\n}\n","/**\n * Saved Patterns\n *\n * Unified pattern storage for:\n * - File structure patterns (architecture decisions)\n * - Code patterns (specific fixes/approaches)\n * - Detection rules (scout preferences)\n */\n\nimport { createHash } from 'crypto';\nimport { readFile, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename } from 'path';\nimport type { Issue } from '../types/index.js';\nimport { searchIssues } from '../memory/issue-store.js';\nimport { getTrieDirectory } from '../utils/workspace.js';\n\nexport type SavedPatternType = 'file-structure' | 'code-pattern' | 'detection-rule';\n\nexport interface SavedPattern {\n id: string;\n type: SavedPatternType;\n name: string;\n description: string;\n\n filePatterns?: string[];\n architecture?: {\n structure: string;\n rationale: string;\n };\n\n codePattern?: {\n pattern: string;\n fix: string;\n context: string;\n };\n\n detectionRule?: {\n agent: string;\n rule: string;\n severity: string;\n };\n\n validated: boolean;\n validationNotes?: string;\n projects: string[];\n occurrences: number;\n savedAt: string;\n savedBy: string;\n}\n\nexport async function loadSavedPatterns(workDir: string): Promise<SavedPattern[]> {\n const patternsPath = join(getTrieDirectory(workDir), 'saved-patterns.json');\n\n try {\n if (existsSync(patternsPath)) {\n const content = await readFile(patternsPath, 'utf-8');\n return JSON.parse(content);\n }\n } catch {\n // File doesn't exist or invalid - return empty\n }\n\n return [];\n}\n\nexport async function savePatternsToProject(patterns: SavedPattern[], workDir: string): Promise<void> {\n const { mkdir } = await import('fs/promises');\n const patternsPath = join(getTrieDirectory(workDir), 'saved-patterns.json');\n\n await mkdir(getTrieDirectory(workDir), { recursive: true });\n await writeFile(patternsPath, JSON.stringify(patterns, null, 2));\n}\n\nexport async function savePatternToProject(pattern: SavedPattern, workDir: string): Promise<void> {\n const patterns = await loadSavedPatterns(workDir);\n const existing = patterns.findIndex(p => p.id === pattern.id);\n\n if (existing >= 0) {\n patterns[existing] = {\n ...patterns[existing]!,\n ...pattern,\n occurrences: patterns[existing]!.occurrences + 1,\n };\n } else {\n patterns.push(pattern);\n }\n\n await savePatternsToProject(patterns, workDir);\n}\n\nexport function detectPatternType(target: string, workDir: string): SavedPatternType {\n const scoutNames = [\n 'security', 'legal', 'accessibility', 'bug-finding',\n 'architecture', 'types', 'clean', 'devops', 'performance',\n 'ux', 'design', 'production-ready', 'agent-smith'\n ];\n\n if (scoutNames.includes(target.toLowerCase())) {\n return 'detection-rule';\n }\n\n const fullPath = join(workDir, target);\n if (\n existsSync(fullPath) ||\n target.includes('/') ||\n target.includes('*') ||\n target.endsWith('.ts') ||\n target.endsWith('.js')\n ) {\n return 'file-structure';\n }\n\n return 'code-pattern';\n}\n\nexport function generatePatternId(target: string, type: SavedPatternType): string {\n const hash = createHash('sha256')\n .update(`${type}:${target}`)\n .digest('hex')\n .slice(0, 12);\n return `${type}-${hash}`;\n}\n\nexport function getDetectionRuleAgents(patterns: SavedPattern[]): string[] {\n return patterns\n .filter(p => p.type === 'detection-rule')\n .map(p => p.detectionRule?.agent || p.name)\n .filter(Boolean);\n}\n\nexport async function createSavedPattern(\n target: string,\n note: string | undefined,\n workDir: string\n): Promise<SavedPattern> {\n const projectName = basename(workDir);\n const patternType = detectPatternType(target, workDir);\n\n const savedPattern: SavedPattern = {\n id: generatePatternId(target, patternType),\n type: patternType,\n name: target,\n description: note || `Pattern saved from ${projectName}`,\n validated: false,\n projects: [projectName],\n occurrences: 1,\n savedAt: new Date().toISOString(),\n savedBy: projectName,\n };\n\n if (patternType === 'file-structure') {\n savedPattern.filePatterns = [target];\n savedPattern.architecture = {\n structure: `Files matching ${target}`,\n rationale: note || 'File structure pattern that worked well',\n };\n } else if (patternType === 'code-pattern') {\n const issues = await searchIssues(target, { limit: 5 });\n if (issues.length > 0) {\n const latestIssue = issues[0];\n savedPattern.codePattern = {\n pattern: latestIssue?.issue.issue || target,\n fix: latestIssue?.issue.fix || 'Review and apply similar fix',\n context: note || 'Code pattern that worked well',\n };\n } else {\n savedPattern.codePattern = {\n pattern: target,\n fix: 'Review and apply similar fix',\n context: note || 'Code pattern that worked well',\n };\n }\n } else if (patternType === 'detection-rule') {\n savedPattern.detectionRule = {\n agent: target,\n rule: `Detection rules from ${target} scout`,\n severity: 'moderate',\n };\n }\n\n return savedPattern;\n}\n\nexport async function buildSavedPatternIssues(\n patterns: SavedPattern[],\n files: string[],\n readFileContent: (filePath: string) => Promise<string>\n): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const pattern of patterns) {\n if (pattern.type === 'detection-rule') continue;\n\n const targetFiles = filterFilesForPattern(files, pattern);\n if (targetFiles.length === 0) continue;\n\n if (pattern.type === 'file-structure') {\n for (const file of targetFiles) {\n issues.push(createPatternIssue(pattern, file, undefined));\n }\n continue;\n }\n\n if (pattern.type === 'code-pattern' && pattern.codePattern) {\n for (const file of targetFiles) {\n const content = await readFileContent(file);\n const match = findPatternMatch(content, pattern.codePattern.pattern);\n if (match) {\n issues.push(createPatternIssue(pattern, file, match.line));\n }\n }\n }\n }\n\n return issues;\n}\n\nfunction filterFilesForPattern(files: string[], pattern: SavedPattern): string[] {\n if (pattern.type === 'file-structure' && pattern.filePatterns) {\n return files.filter(file => pattern.filePatterns!.some(p => matchesFilePattern(file, p)));\n }\n if (pattern.type === 'code-pattern') {\n return files;\n }\n return [];\n}\n\nfunction matchesFilePattern(filePath: string, pattern: string): boolean {\n const normalized = filePath.replace(/\\\\/g, '/');\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '___DOUBLESTAR___')\n .replace(/\\*/g, '[^/]*')\n .replace(/___DOUBLESTAR___/g, '.*');\n const regex = new RegExp(`^${escaped}$`, 'i');\n return regex.test(normalized) || normalized.includes(pattern.replace(/\\*+/g, ''));\n}\n\nfunction findPatternMatch(content: string, pattern: string): { line: number } | null {\n try {\n const regex = new RegExp(pattern, 'i');\n const match = regex.exec(content);\n if (!match || match.index === undefined) return null;\n const line = getLineNumber(content, match.index);\n return { line };\n } catch {\n const index = content.toLowerCase().indexOf(pattern.toLowerCase());\n if (index === -1) return null;\n const line = getLineNumber(content, index);\n return { line };\n }\n}\n\nfunction getLineNumber(content: string, index: number): number {\n return content.slice(0, index).split('\\n').length;\n}\n\nfunction createPatternIssue(pattern: SavedPattern, file: string, line?: number): Issue {\n const description = pattern.description || `Saved pattern: ${pattern.name}`;\n const fix = pattern.codePattern?.fix || 'Apply the saved pattern from your other project.';\n const issue: Issue = {\n id: `saved-${pattern.id}-${hashFile(file)}`,\n severity: 'low',\n issue: `Saved pattern suggestion: ${description}`,\n fix,\n file,\n confidence: 0.6,\n autoFixable: false,\n agent: 'saved-patterns',\n category: 'pattern-sharing',\n };\n if (line !== undefined) {\n issue.line = line;\n }\n return issue;\n}\n\nfunction hashFile(file: string): string {\n return createHash('sha256').update(file).digest('hex').slice(0, 8);\n}\n","import pc from 'picocolors';\nimport { Command } from 'commander';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport {\n initializeSharedLedger,\n syncLedgerFromShared,\n pushLedgerToShared,\n getLedgerSyncStatus,\n migrateLegacyLedger,\n detectLegacyLedger\n} from '../memory/ledger.js';\nimport { installGitHooks, checkGitHooks } from './hooks.js';\n\nexport function createSyncCommand(): Command {\n const sync = new Command('sync')\n .description('Sync ledger with shared storage');\n\n sync.command('init')\n .description('Initialize shared ledger storage')\n .action(async () => {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n console.log(`Initializing shared ledger in ${workDir}...`);\n\n await initializeSharedLedger();\n console.log(pc.green('✓ Shared ledger initialized successfully'));\n } catch (error) {\n console.error(pc.red('Failed to initialize shared ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('pull')\n .description('Pull updates from shared ledger')\n .action(async () => {\n try {\n console.log('Syncing from shared ledger...');\n\n // Check for legacy ledger and migrate if needed\n const hasLegacy = await detectLegacyLedger();\n if (hasLegacy) {\n console.log('Detected legacy ledger, migrating...');\n await migrateLegacyLedger();\n }\n\n const result = await syncLedgerFromShared();\n\n console.log(pc.green('✓ Sync completed'));\n console.log(`Merged ${result.stats.mergedBlocks} blocks`);\n\n if (result.conflicts.length > 0) {\n console.log(pc.yellow(`⚠ ${result.conflicts.length} conflicts detected`));\n console.log('Run \"trie sync status\" to see details');\n }\n\n if (result.stats.duplicatesRemoved > 0) {\n console.log(`Removed ${result.stats.duplicatesRemoved} duplicate entries`);\n }\n } catch (error) {\n console.error(pc.red('Failed to sync from shared ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('push')\n .description('Push local changes to shared ledger')\n .action(async () => {\n try {\n console.log('Pushing to shared ledger...');\n\n // Check for legacy ledger and migrate if needed\n const hasLegacy = await detectLegacyLedger();\n if (hasLegacy) {\n console.log('Detected legacy ledger, migrating...');\n await migrateLegacyLedger();\n }\n\n await pushLedgerToShared();\n console.log(pc.green('✓ Push completed'));\n } catch (error) {\n console.error(pc.red('Failed to push to shared ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('status')\n .description('Show ledger sync status')\n .action(async () => {\n try {\n const status = await getLedgerSyncStatus();\n\n console.log(pc.bold('Ledger Sync Status\\n'));\n\n if (!status.isInitialized) {\n console.log(pc.yellow('⚠ Shared ledger not initialized. Run \"trie sync init\" first.'));\n return;\n }\n\n if (status.hasLegacyLedger) {\n console.log(pc.yellow('⚠ Legacy ledger detected. Run \"trie sync pull\" to migrate.'));\n }\n\n console.log(`Local blocks: ${pc.cyan(status.localBlocks.toString())}`);\n console.log(`Shared blocks: ${pc.cyan(status.sharedBlocks.toString())}`);\n\n if (status.syncState) {\n const lastSync = new Date(status.syncState.lastSyncTimestamp);\n console.log(`Last sync: ${pc.dim(lastSync.toLocaleString())}`);\n\n if (status.conflicts > 0) {\n console.log(pc.yellow(`Conflicts: ${status.conflicts}`));\n console.log('\\nConflicts:');\n for (const conflict of status.syncState.conflicts) {\n console.log(` • ${conflict.type}: ${conflict.description}`);\n }\n } else {\n console.log(pc.green('✓ No conflicts'));\n }\n }\n\n if (status.manifest) {\n console.log(`\\nTotal entries: ${pc.cyan(status.manifest.totalEntries.toString())}`);\n console.log(`Compression: ${status.manifest.compressionConfig.enabled ? pc.green('enabled') : pc.red('disabled')}`);\n }\n } catch (error) {\n console.error(pc.red('Failed to get sync status:'), error);\n process.exit(1);\n }\n });\n\n sync.command('migrate')\n .description('Migrate legacy ledger to new format')\n .action(async () => {\n try {\n const hasLegacy = await detectLegacyLedger();\n\n if (!hasLegacy) {\n console.log(pc.yellow('No legacy ledger found to migrate'));\n return;\n }\n\n console.log('Migrating legacy ledger...');\n const success = await migrateLegacyLedger();\n\n if (success) {\n console.log(pc.green('✓ Migration completed successfully'));\n } else {\n console.log(pc.red('Migration failed'));\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to migrate legacy ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('hooks')\n .description('Manage git hooks for automatic sync')\n .option('--install', 'Install git hooks')\n .option('--status', 'Check git hooks status')\n .action(async (options) => {\n try {\n if (options.install) {\n await installGitHooks();\n return;\n }\n\n // Default to status check\n const status = await checkGitHooks();\n\n if (!status.isGitRepo) {\n console.log(pc.yellow('Not a git repository'));\n return;\n }\n\n console.log(pc.bold('Git Hooks Status\\n'));\n console.log(`Pre-push hook: ${status.prePushInstalled ? pc.green('✓ installed') : pc.red('✗ not installed')}`);\n console.log(`Post-merge hook: ${status.postMergeInstalled ? pc.green('✓ installed') : pc.red('✗ not installed')}`);\n\n if (!status.prePushInstalled || !status.postMergeInstalled) {\n console.log(`\\n${pc.yellow('💡 Tip:')} Run ${pc.bold('trie sync hooks --install')} to install missing hooks`);\n }\n } catch (error) {\n console.error(pc.red('Failed to manage git hooks:'), error);\n process.exit(1);\n }\n });\n\n return sync;\n}","import { writeFile, mkdir, chmod } from 'fs/promises';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport pc from 'picocolors';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { isGitRepo } from '../agent/git.js';\n\n/**\n * Install git hooks for automatic ledger sync\n */\nexport async function installGitHooks(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n\n const isRepo = await isGitRepo(workDir);\n if (!isRepo) {\n console.log(pc.yellow('⚠ Not a git repository. Git hooks not installed.'));\n return;\n }\n\n const hooksDir = join(workDir, '.git', 'hooks');\n\n if (!existsSync(hooksDir)) {\n await mkdir(hooksDir, { recursive: true });\n }\n\n // Pre-push hook: sync ledger to shared storage\n const prePushHook = `#!/bin/sh\n# Auto-sync ledger to shared storage before push\n\n# Only run if trie is initialized\nif [ ! -d \".trie\" ]; then\n exit 0\nfi\n\n# Check if trie command is available\nif ! command -v trie >/dev/null 2>&1; then\n echo \"Warning: trie command not found, skipping ledger sync\"\n exit 0\nfi\n\n# Sync ledger to shared storage\necho \"Syncing ledger to shared storage...\"\ntrie sync push 2>/dev/null || true\n\nexit 0\n`;\n\n // Post-merge hook: sync ledger from shared storage\n const postMergeHook = `#!/bin/sh\n# Auto-sync ledger from shared storage after merge\n\n# Only run if trie is initialized\nif [ ! -d \".trie\" ]; then\n exit 0\nfi\n\n# Check if trie command is available\nif ! command -v trie >/dev/null 2>&1; then\n exit 0\nfi\n\n# Sync ledger from shared storage\necho \"Syncing ledger from shared storage...\"\ntrie sync pull 2>/dev/null || true\n\nexit 0\n`;\n\n const prePushPath = join(hooksDir, 'pre-push');\n const postMergePath = join(hooksDir, 'post-merge');\n\n // Install hooks\n await writeFile(prePushPath, prePushHook);\n await writeFile(postMergePath, postMergeHook);\n\n // Make hooks executable\n await chmod(prePushPath, 0o755);\n await chmod(postMergePath, 0o755);\n\n console.log(pc.green('✓ Git hooks installed successfully'));\n console.log(pc.dim(' pre-push: Syncs ledger to shared storage'));\n console.log(pc.dim(' post-merge: Syncs ledger from shared storage'));\n}\n\n/**\n * Check if git hooks are installed\n */\nexport async function checkGitHooks(): Promise<{\n isGitRepo: boolean;\n prePushInstalled: boolean;\n postMergeInstalled: boolean;\n}> {\n const workDir = getWorkingDirectory(undefined, true);\n\n const isRepo = await isGitRepo(workDir);\n if (!isRepo) {\n return {\n isGitRepo: false,\n prePushInstalled: false,\n postMergeInstalled: false\n };\n }\n\n const hooksDir = join(workDir, '.git', 'hooks');\n const prePushPath = join(hooksDir, 'pre-push');\n const postMergePath = join(hooksDir, 'post-merge');\n\n return {\n isGitRepo: true,\n prePushInstalled: existsSync(prePushPath),\n postMergeInstalled: existsSync(postMergePath)\n };\n}","import pc from 'picocolors';\nimport { Command } from 'commander';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport {\n verifyLedger,\n getLedgerBlocks,\n getLedgerSyncStatus,\n compressOldBlocks,\n getStorageStats,\n shouldCompress,\n deleteBlocks,\n deleteAllBlocks\n} from '../memory/ledger.js';\n\nexport function createLedgerCommand(): Command {\n const ledger = new Command('ledger')\n .description('Manage and inspect the ledger');\n\n ledger.command('verify')\n .description('Verify ledger chain integrity')\n .action(async () => {\n try {\n console.log('Verifying ledger chain...');\n\n const result = await verifyLedger();\n\n if (result.valid) {\n console.log(pc.green('✓ Ledger chain is valid'));\n } else {\n console.log(pc.red(`✗ Ledger chain is invalid: ${result.error}`));\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to verify ledger:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('history')\n .description('Show ledger history with author attribution')\n .option('-l, --limit <number>', 'Number of blocks to show', '10')\n .action(async (options) => {\n try {\n const limit = parseInt(options.limit, 10);\n const blocks = await getLedgerBlocks();\n\n if (blocks.length === 0) {\n console.log('No ledger blocks found');\n return;\n }\n\n console.log(pc.bold(`Ledger History (last ${Math.min(limit, blocks.length)} blocks)\\n`));\n\n const recentBlocks = blocks.slice(-limit).reverse();\n\n for (const block of recentBlocks) {\n const syncableBlock = block as any;\n console.log(pc.bold(pc.cyan(`Block ${block.date}`)));\n\n if (syncableBlock.author) {\n console.log(`Author: ${pc.dim(syncableBlock.author)}`);\n }\n\n if (syncableBlock.gitCommit) {\n console.log(`Git: ${pc.dim(syncableBlock.gitCommit.slice(0, 8))}`);\n }\n\n console.log(`Entries: ${block.entries.length}`);\n console.log(`Hash: ${pc.dim(block.blockHash.slice(0, 16))}...`);\n\n if (block.entries.length > 0) {\n console.log('Issues:');\n for (const entry of block.entries) {\n console.log(` • ${entry.severity} - ${entry.file} (${entry.agent})`);\n }\n }\n\n console.log('');\n }\n } catch (error) {\n console.error(pc.red('Failed to show ledger history:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('stats')\n .description('Show ledger statistics')\n .action(async () => {\n try {\n const status = await getLedgerSyncStatus();\n const blocks = await getLedgerBlocks();\n\n console.log(pc.bold('Ledger Statistics\\n'));\n\n console.log(`Total blocks: ${pc.cyan(blocks.length.toString())}`);\n\n if (status.manifest) {\n console.log(`Total entries: ${pc.cyan(status.manifest.totalEntries.toString())}`);\n console.log(`Active blocks: ${pc.cyan(status.manifest.activeBlocks.length.toString())}`);\n console.log(`Archived blocks: ${pc.cyan(status.manifest.archivedBlocks.length.toString())}`);\n\n if (status.manifest.compressionConfig.enabled) {\n const hotSize = Math.round(status.manifest.compressionConfig.maxHotStorageSize / 1024 / 1024);\n console.log(`Hot storage limit: ${pc.cyan(`${hotSize}MB`)}`);\n console.log(`Archive after: ${pc.cyan(`${status.manifest.compressionConfig.archiveAfterDays} days`)}`);\n }\n }\n\n // Calculate date range\n if (blocks.length > 0) {\n const firstBlock = blocks[0];\n const lastBlock = blocks[blocks.length - 1];\n console.log(`Date range: ${pc.dim(`${firstBlock.date} to ${lastBlock.date}`)}`);\n }\n\n // Author statistics\n const authorCounts = new Map<string, number>();\n for (const block of blocks) {\n const syncableBlock = block as any;\n if (syncableBlock.author) {\n authorCounts.set(syncableBlock.author, (authorCounts.get(syncableBlock.author) || 0) + 1);\n }\n }\n\n if (authorCounts.size > 0) {\n console.log('\\nBlocks by author:');\n const sortedAuthors = Array.from(authorCounts.entries())\n .sort((a, b) => b[1] - a[1]);\n\n for (const [author, count] of sortedAuthors.slice(0, 10)) {\n console.log(` ${author}: ${pc.cyan(count.toString())}`);\n }\n }\n\n // Severity statistics\n const severityCounts = new Map<string, number>();\n for (const block of blocks) {\n for (const entry of block.entries) {\n severityCounts.set(entry.severity, (severityCounts.get(entry.severity) || 0) + 1);\n }\n }\n\n if (severityCounts.size > 0) {\n console.log('\\nIssues by severity:');\n const severityOrder = ['critical', 'high', 'medium', 'low', 'info'];\n\n for (const severity of severityOrder) {\n const count = severityCounts.get(severity);\n if (count) {\n const color = severity === 'critical' ? pc.red :\n severity === 'high' ? pc.yellow :\n severity === 'medium' ? pc.blue : pc.gray;\n console.log(` ${color(severity)}: ${pc.cyan(count.toString())}`);\n }\n }\n }\n } catch (error) {\n console.error(pc.red('Failed to show ledger stats:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('diff')\n .description('Compare local and shared ledger state')\n .action(async () => {\n try {\n const status = await getLedgerSyncStatus();\n\n console.log(pc.bold('Ledger Diff\\n'));\n\n if (!status.isInitialized) {\n console.log(pc.yellow('Shared ledger not initialized'));\n return;\n }\n\n console.log(`Local blocks: ${pc.cyan(status.localBlocks.toString())}`);\n console.log(`Shared blocks: ${pc.cyan(status.sharedBlocks.toString())}`);\n\n const diff = status.sharedBlocks - status.localBlocks;\n if (diff > 0) {\n console.log(pc.green(`↓ ${diff} blocks available to pull`));\n } else if (diff < 0) {\n console.log(pc.blue(`↑ ${-diff} local blocks not yet pushed`));\n } else {\n console.log(pc.green('✓ Local and shared ledgers are in sync'));\n }\n\n if (status.conflicts > 0) {\n console.log(pc.red(`⚠ ${status.conflicts} conflicts detected`));\n }\n } catch (error) {\n console.error(pc.red('Failed to diff ledgers:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('compress')\n .description('Manually compress and archive old blocks')\n .action(async () => {\n try {\n const shouldRun = await shouldCompress();\n\n if (!shouldRun) {\n console.log('No compression needed at this time');\n return;\n }\n\n console.log('Compressing old ledger blocks...');\n const result = await compressOldBlocks();\n\n if (result.archived > 0) {\n console.log(pc.green(`✓ Compressed ${result.archived} blocks`));\n console.log(`Space saved: ${result.sizeReduction}%`);\n } else {\n console.log('No blocks were archived');\n }\n } catch (error) {\n console.error(pc.red('Failed to compress blocks:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('storage')\n .description('Show detailed storage statistics')\n .action(async () => {\n try {\n const stats = await getStorageStats();\n\n console.log(pc.bold('Ledger Storage Statistics\\n'));\n\n console.log(pc.bold('Block Storage:'));\n console.log(` Active blocks: ${pc.cyan(stats.activeBlocks.toString())}`);\n console.log(` Archived blocks: ${pc.cyan(stats.archivedBlocks.toString())}`);\n\n console.log(pc.bold('\\nStorage Usage:'));\n const activeMB = (stats.activeSize / 1024 / 1024).toFixed(2);\n const archivedMB = (stats.archivedSize / 1024 / 1024).toFixed(2);\n const totalMB = (Number(activeMB) + Number(archivedMB)).toFixed(2);\n\n console.log(` Active storage: ${pc.cyan(`${activeMB} MB`)}`);\n console.log(` Archived storage: ${pc.cyan(`${archivedMB} MB`)}`);\n console.log(` Total storage: ${pc.bold(pc.cyan(`${totalMB} MB`))}`);\n\n if (stats.compressionRatio > 0) {\n console.log(` Compression ratio: ${pc.green(`${stats.compressionRatio}%`)}`);\n }\n\n console.log(pc.bold('\\nData:'));\n console.log(` Total entries: ${pc.cyan(stats.totalEntries.toString())}`);\n\n const needsCompression = await shouldCompress();\n if (needsCompression) {\n console.log(`\\n${pc.yellow('💡 Tip:')} Run ${pc.bold('trie ledger compress')} to archive old blocks`);\n }\n } catch (error) {\n console.error(pc.red('Failed to get storage stats:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('delete')\n .description('Delete specific blocks from the ledger (PERMANENT)')\n .argument('<dates...>', 'Block dates to delete (YYYY-MM-DD format)')\n .option('--confirm', 'Confirm the permanent deletion')\n .action(async (dates: string[], options) => {\n try {\n // Validate date formats\n const datePattern = /^\\d{4}-\\d{2}-\\d{2}$/;\n const invalidDates = dates.filter(date => !datePattern.test(date));\n\n if (invalidDates.length > 0) {\n console.error(pc.red('Invalid date format(s):'), invalidDates.join(', '));\n console.error('Please use YYYY-MM-DD format');\n process.exit(1);\n }\n\n if (!options.confirm) {\n console.log(pc.bold(pc.red('⚠️ DANGER: PERMANENT DELETION')));\n console.log('');\n console.log(`You are about to permanently delete ${dates.length} block(s):`);\n for (const date of dates) {\n console.log(` • ${pc.cyan(date)}`);\n }\n console.log('');\n console.log(pc.red('This operation cannot be undone and will permanently remove'));\n console.log(pc.red('all issues and data from these blocks.'));\n console.log('');\n console.log(`To proceed, add the ${pc.bold('--confirm')} flag:`);\n console.log(` ${pc.dim('trie ledger delete ' + dates.join(' ') + ' --confirm')}`);\n return;\n }\n\n console.log(pc.yellow('🗑️ Deleting blocks...'));\n\n const result = await deleteBlocks(dates, undefined, true);\n\n if (result.success) {\n console.log(pc.green(`✓ Successfully deleted ${result.deletedBlocks} block(s)`));\n if (result.warning) {\n console.log(pc.yellow(`⚠️ ${result.warning}`));\n }\n } else {\n console.error(pc.red('✗ Deletion failed:'), result.error);\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to delete blocks:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('clear')\n .description('Delete ALL blocks from the ledger (PERMANENT)')\n .option('--confirm', 'Confirm the permanent deletion of all blocks')\n .action(async (options) => {\n try {\n if (!options.confirm) {\n console.log(pc.bold(pc.red('🚨 DANGER: COMPLETE LEDGER DELETION')));\n console.log('');\n console.log(pc.red('You are about to permanently delete ALL blocks in the ledger.'));\n console.log(pc.red('This will completely erase the entire ledger history.'));\n console.log('');\n console.log(pc.red('This operation cannot be undone and will permanently remove'));\n console.log(pc.red('ALL issues and historical data.'));\n console.log('');\n console.log(`To proceed, add the ${pc.bold('--confirm')} flag:`);\n console.log(` ${pc.dim('trie ledger clear --confirm')}`);\n return;\n }\n\n // Double confirmation for clear all\n console.log(pc.yellow('🗑️ Clearing entire ledger...'));\n\n const result = await deleteAllBlocks(undefined, true);\n\n if (result.success) {\n console.log(pc.green(`✓ Successfully deleted ${result.deletedBlocks} block(s)`));\n if (result.warning) {\n console.log(pc.yellow(`⚠️ ${result.warning}`));\n }\n } else {\n console.error(pc.red('✗ Clear operation failed:'), result.error);\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to clear ledger:'), error);\n process.exit(1);\n }\n });\n\n return ledger;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,SAAS,QAAAA,OAAM,eAAe;AACvC,SAAS,cAAc,oBAAoB;AAC3C,SAAS,qBAAqB;AAC9B,OAAOC,SAAQ;;;ACdf,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACDjB,IAAM,WAAW;AAEjB,SAAS,aAAqB;AAC5B,SAAO,gBAAgB,WAAW;AACpC;AAEA,SAAS,YAAY,MAAsB;AACzC,SAAO;AAAA;AAAA;AAAA,gBAGO,IAAI;AAAA;AAAA,uCAEmB,IAAI;AAAA;AAAA;AAG3C;AAMA,SAAS,iBAAyB;AAChC,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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,KAAK;AACpC,UAAM,WAAW,cAAc,YAAY,GAAG;AAC9C,WAAO,cAAc;AAAA,EACvB,QAAQ;AAGN,WAAO,CAAC,QAAQ,IAAI,UAAU,CAAC,QAAQ,IAAI;AAAA,EAC7C;AACF,GAAG;AAEH,IAAI,cAAc;AAChB,OAAK,EAAE,MAAM,WAAS;AACpB,YAAQ,MAAM,UAAU,KAAK;AAC7B,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["join","pc","fs","path","result","parseArgs","readFile","existsSync","pc","resolve","pc","existsSync","readFile","applied","pc","pc","path","path","path","path","fs","path","path","fs","existsSync","pc","showHelp","existsSync","picocolors","readFile","writeFile","existsSync","basename","picocolors","readFile","writeFile","existsSync","join","join","existsSync","readFile","mkdir","writeFile","picocolors","basename","writeFile","existsSync","readFile","pc","writeFile","join","existsSync","pc","installGitHooks","pc","join","existsSync","writeFile","pc","installGitHooks","pc","Command","Command","pc","__filename","__dirname","showHelp","pc","join"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/main.ts","../../src/hooks/install.ts","../../src/hooks/templates.ts","../../src/cli/init.ts","../../src/cli/memory.ts","../../src/cli/check.ts","../../src/cli/pre-push.ts","../../src/cli/hooks.ts","../../src/cli/setup.ts","../../src/cli/auto-fix.ts","../../src/utils/auto-fix-apply.ts","../../src/cli/goal.ts","../../src/cli/tell.ts","../../src/cli/reconcile.ts","../../src/cli/quiet.ts","../../src/cli/ci.ts","../../src/cli/audit.ts","../../src/cli/linear.ts","../../src/cli/gotcha.ts","../../src/cli/learn.ts","../../src/cli/patterns.ts","../../src/patterns/saved-patterns.ts","../../src/cli/sync.ts","../../src/cli/ledger.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Trie Agent CLI\n * \n * Main command-line interface for Trie Agent.\n * Provides help, setup, and routes to specific tools.\n * \n * Usage:\n * trie-agent [command] [options]\n */\n\nimport { resolve, join, dirname } from 'path';\nimport { readFileSync, realpathSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport pc from 'picocolors';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { loadProjectInfo, initProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { handleInitCommand } from './init.js';\nimport { handleMemoryCommand } from './memory.js';\nimport { handleCheckpointCommand } from './checkpoint.js';\nimport { handleCheckCommand } from './check.js';\nimport { handlePrePushCommand } from './pre-push.js';\nimport { handlePreCommitCommand, handlePostCommitCommand } from './hooks.js';\nimport { handleSetupCommand } from './setup.js';\nimport { handleAutoFixCommand } from './auto-fix.js';\nimport { handleGoalCommand, handleHypothesisCommand } from './goal.js';\nimport { handleTellCommand } from './tell.js';\nimport { handleReconcileCommand } from './reconcile.js';\nimport { handleQuietCommand } from './quiet.js';\nimport { handleCISetupCommand } from './ci.js';\nimport { handleAuditCommand } from './audit.js';\nimport { handleLinearCommand } from './linear.js';\nimport { handleGotchaCommand } from './gotcha.js';\nimport { handleLearnCommand } from './learn.js';\nimport { handlePatternsCommand } from './patterns.js';\nimport { createSyncCommand } from './sync.js';\nimport { createLedgerCommand } from './ledger.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { loadContextState } from '../utils/context-state.js';\nimport { getMemoryStats } from '../memory/issue-store.js';\n\n// ES module __dirname equivalent\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst DEFAULT_VERSION = '0.0.0';\n\nfunction getCliVersion(): string {\n try {\n const pkgPath = resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n return typeof pkg.version === 'string' && pkg.version.trim()\n ? pkg.version.trim()\n : DEFAULT_VERSION;\n } catch {\n return DEFAULT_VERSION;\n }\n}\n\n/**\n * Show TRIE ASCII art banner\n */\nfunction showBanner(): void {\n console.log(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗ \n ██║ ██╔══██╗██║██╔══╝ \n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n \n Your decision ledger that travels\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n`);\n}\n\n/**\n * Show the main help message\n */\nfunction showHelp(): void {\n showBanner();\n console.log(`Version: ${getCliVersion()}\n\nUSAGE:\n trie <command> [options]\n\nCOMMANDS:\n init Initialize Trie in your project\n scan Scan codebase once and exit\n watch Start watching (nudges as you code)\n Use screen/tmux to run in background\n check Run risk check before pushing\n \n tell \"<incident>\" Report an incident (\"users can't log in\")\n learn Train Trie from git history or feedback (alias: train)\n ok Mark current pattern as good (alias: learn ok)\n bad Mark current pattern as bad (alias: learn bad)\n quiet Snooze nudges for 1 hour\n \n checkpoint Save work context to .trie/ (aliases: cp, save)\n linear sync Sync active tickets from Linear\n gotcha Predict problems with current changes (alias: predict)\n reconcile Reconcile context graph from JSON backup\n\n audit View security audit logs\n memory Search and manage issue memory\n patterns Save, validate, and share patterns across projects\n status Quick health check (project health + memory stats)\n project View/manage project info (.trie/PROJECT.md)\n setup Configure API key and environment\n \n ci Generate GitHub Actions workflow with memory caching\n \n help Show this help message\n version Show version information\n\nEXAMPLES:\n trie init # Initialize Trie in your project\n trie watch # Start watching (nudges as you code)\n trie watch # Run in background: screen -S trie-watch\n trie scan # Scan your codebase now\n \n trie tell \"users couldn't log in\" # Report an incident\n trie ok # Mark current pattern as good\n trie bad # Mark current pattern as bad\n trie quiet # Snooze nudges for 1 hour\n \n trie linear sync # Sync active tickets from Linear\n trie learn # Scan history for precedents\n trie gotcha # Predict for current changes\n \n trie check # Risk check before pushing\n\n trie memory search \"SQL injection\"\n trie memory stats # View memory statistics\n trie status # Quick health check (project + memory)\n trie ci # Generate CI workflow with memory caching\n\nMCP TOOLS (use via Cursor/Claude Desktop):\n trie_linear_sync Sync active tickets from Linear\n trie_scan Scan with decision ledger\n trie_fix Generate high-confidence fix prompts\n trie_explain Explain code, issues, or changes\n trie_watch Watch mode for autonomous reporting\n\n`);\n}\n\n\n/**\n * Show version\n */\nfunction showVersion(): void {\n showBanner();\n console.error(`v${getCliVersion()}`);\n}\n\n/**\n * Handle status command - quick health check\n */\nexport async function handleStatusCommand(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n \n try {\n // Load context state for last scan and memory stats\n const state = await loadContextState();\n const memoryStats = await getMemoryStats(workDir);\n \n console.log('\\n╔══════════════════════════════════════════════════════════════════╗');\n console.log('║ PROJECT STATUS ║');\n console.log('╚══════════════════════════════════════════════════════════════════╝\\n');\n \n // Last Scan Info\n if (state.lastScan) {\n const lastScanDate = new Date(state.lastScan.timestamp);\n const daysAgo = Math.floor((Date.now() - lastScanDate.getTime()) / (1000 * 60 * 60 * 24));\n console.log(`\\n${pc.bold('Last Scan:')} ${lastScanDate.toLocaleDateString()} (${daysAgo === 0 ? 'today' : daysAgo === 1 ? 'yesterday' : `${daysAgo} days ago`})`);\n console.log(pc.dim(` Files scanned: ${state.lastScan.filesScanned}`));\n console.log(pc.dim(` Issues found: ${state.lastScan.issues.total} (${state.lastScan.issues.critical} critical, ${state.lastScan.issues.serious} serious)`));\n } else {\n console.log(`\\n${pc.bold('Last Scan:')} Never ${pc.dim('(run `trie scan` to get started)')}`);\n }\n \n // Memory Stats Summary\n console.log(`\\n${pc.bold('Memory Stats:')}`);\n console.log(pc.dim(` Active Issues: ${memoryStats.activeIssues}`));\n console.log(pc.dim(` Resolved: ${memoryStats.resolvedCount}`));\n console.log(pc.dim(` Total (all-time): ${memoryStats.totalIssues}`));\n const cap = memoryStats.capacityInfo;\n const capIndicator = cap.isAtCap ? pc.red('○') : cap.percentFull >= 80 ? pc.yellow('◉') : pc.green('●');\n console.log(` ${capIndicator} Memory Usage: ${pc.bold(cap.percentFull + '%')} ${pc.dim(`(${cap.current}/${cap.max})`)}`);\n \n if (memoryStats.activeIssues > 0) {\n console.log(`\\n ${pc.bold('Active Issues by Severity:')}`);\n const severityOrder = ['critical', 'serious', 'moderate', 'low', 'info'];\n for (const severity of severityOrder) {\n const count = memoryStats.activeIssuesBySeverity[severity] || 0;\n if (count > 0) {\n console.log(pc.dim(` ${severity}: ${count}`));\n }\n }\n } else if (memoryStats.totalIssues > 0) {\n console.log(`\\n ${pc.green('●')} All issues have been resolved`);\n }\n \n // Capacity warning\n if (cap.isAtCap) {\n console.log(`\\n${pc.yellow('⬢ Warning:')} Memory at capacity - consider running: ${pc.bold('trie memory purge smart')}`);\n } else if (cap.percentFull >= 80) {\n console.log(`\\n${pc.yellow('⬢ Notice:')} Memory usage high - consider running: ${pc.bold('trie memory purge smart')}`);\n }\n \n console.log(`\\n${pc.bold('Quick Commands:')}`);\n console.log(pc.dim(' trie scan - Scan codebase now'));\n console.log(pc.dim(' trie memory stats - Detailed memory statistics'));\n console.log(pc.dim(' trie project - View project information'));\n console.log('');\n \n } catch (error) {\n console.error('Error loading status:', error);\n process.exit(1);\n }\n}\n\n/**\n * Handle project command\n */\nasync function handleProject(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n\n if (subcommand === 'init') {\n const result = await initProjectInfo(workDir);\n if (result.created) {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ PROJECT.md Created ║\n╚══════════════════════════════════════════════════════════════════╝\n\n${pc.bold('Path:')} ${result.path}\n\nA template has been created with sections for:\n • Project Overview\n • Technology Stack\n • Architecture\n • Coding Conventions\n • Environment\n • Team\n • Compliance\n • AI Instructions\n\nNext steps:\n 1. Edit the file to add your project details\n 2. The info will be available via trie://project resource\n 3. AI assistants will use this context automatically\n`);\n } else {\n console.log(`PROJECT.md already exists at: ${result.path}`);\n console.log('Use \"trie project\" to view it.');\n }\n return;\n }\n\n if (subcommand === 'edit') {\n const editor = process.env.EDITOR || process.env.VISUAL || 'nano';\n const projectPath = join(getTrieDirectory(workDir), 'PROJECT.md');\n \n if (!projectInfoExists(workDir)) {\n console.log('No PROJECT.md found. Creating one first...');\n await initProjectInfo(workDir);\n }\n \n const { spawn } = await import('child_process');\n const child = spawn(editor, [projectPath], { stdio: 'inherit' });\n child.on('close', (code) => {\n process.exit(code || 0);\n });\n return;\n }\n\n // Default: show project info\n if (!projectInfoExists(workDir)) {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Project Information ║\n╚══════════════════════════════════════════════════════════════════╝\n\n${pc.bold('No PROJECT.md found in this project.')}\n\nCOMMANDS:\n trie project init Create PROJECT.md from template\n trie project edit Open PROJECT.md in $EDITOR\n trie project View PROJECT.md contents\n\nWHAT IS PROJECT.MD?\nPROJECT.md stores important project context for AI assistants:\n • Project description and purpose\n • Technology stack and frameworks\n • Architecture decisions\n • Coding conventions\n • Environment info (URLs, endpoints)\n • Team ownership\n • Compliance requirements\n • Special instructions for AI\n\nThis info is available via trie://project MCP resource.\n`);\n return;\n }\n\n const content = await loadProjectInfo(workDir);\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Project Information ║\n╚══════════════════════════════════════════════════════════════════╝\n\n${pc.bold('Path:')} ${join(getTrieDirectory(workDir), 'PROJECT.md')}\n\n${'-'.repeat(68)}\n`);\n console.log(content);\n}\n\n/**\n * Run scan command\n */\nasync function runScan(args: string[]): Promise<void> {\n // Forward to watch daemon with --once flag\n const { spawn } = await import('child_process');\n \n // Determine daemon path - works for both source (tsx) and built (node) execution\n let daemonPath: string;\n if (__filename.endsWith('.ts')) {\n // Running from source with tsx\n daemonPath = resolve(__dirname, 'yolo-daemon.ts');\n } else {\n // Running from built dist\n daemonPath = resolve(__dirname, 'yolo-daemon.js');\n }\n \n const daemonArgs = ['--once', ...args];\n \n // Use tsx for .ts files, node for .js files\n const executor = daemonPath.endsWith('.ts') ? 'npx' : 'node';\n const execArgs = daemonPath.endsWith('.ts') \n ? ['tsx', daemonPath, ...daemonArgs]\n : [daemonPath, ...daemonArgs];\n \n const child = spawn(executor, execArgs, {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code) => {\n process.exit(code || 0);\n });\n}\n\n/**\n * Run watch command\n */\nasync function runWatch(args: string[]): Promise<void> {\n const { spawn } = await import('child_process');\n \n // Determine daemon path - works for both source (tsx) and built (node) execution\n let daemonPath: string;\n if (__filename.endsWith('.ts')) {\n daemonPath = resolve(__dirname, 'yolo-daemon.ts');\n } else {\n daemonPath = resolve(__dirname, 'yolo-daemon.js');\n }\n \n // Use tsx for .ts files, node for .js files\n const executor = daemonPath.endsWith('.ts') ? 'npx' : 'node';\n const execArgs = daemonPath.endsWith('.ts') \n ? ['tsx', daemonPath, ...args]\n : [daemonPath, ...args];\n \n const child = spawn(executor, execArgs, {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code) => {\n process.exit(code || 0);\n });\n}\n\n/**\n * Main entry point\n */\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n const command = args[0]?.toLowerCase();\n const restArgs = args.slice(1);\n\n // No command or help flag\n if (!command || command === 'help' || command === '--help' || command === '-h') {\n showHelp();\n process.exit(0);\n }\n\n const initRequired = !['init', 'version', '--version', '-v'].includes(command);\n if (initRequired) {\n const workDir = getWorkingDirectory(undefined, true);\n if (!isTrieInitialized(workDir)) {\n console.error('Trie is not initialized for this project.');\n console.error('Run `trie init` first.');\n process.exit(1);\n }\n }\n\n switch (command) {\n case 'setup':\n case 'config':\n case 'configure':\n await handleSetupCommand(restArgs);\n break;\n\n case 'init':\n case 'bootstrap':\n handleInitCommand(restArgs);\n break;\n\n case 'memory':\n case 'mem':\n handleMemoryCommand(restArgs);\n break;\n\n case 'status':\n case 'stats':\n await handleStatusCommand();\n break;\n\n case 'checkpoint':\n case 'cp':\n case 'save':\n handleCheckpointCommand(restArgs);\n break;\n\n case 'project':\n case 'info':\n case 'project-info':\n handleProject(restArgs);\n break;\n\n case 'audit':\n handleAuditCommand(restArgs);\n break;\n\n case 'version':\n case '--version':\n case '-v':\n showVersion();\n break;\n\n case 'scan':\n runScan(restArgs);\n break;\n\n case 'watch':\n runWatch(restArgs);\n break;\n\n case 'check':\n handleCheckCommand(restArgs);\n break;\n\n case 'pre-push':\n handlePrePushCommand(restArgs);\n break;\n\n case 'pre-commit':\n handlePreCommitCommand(restArgs);\n break;\n\n case 'post-commit':\n handlePostCommitCommand(restArgs);\n break;\n\n case 'fix':\n case 'auto-fix':\n case 'autofix':\n handleAutoFixCommand(restArgs);\n break;\n\n case 'goal':\n case 'goals':\n handleGoalCommand(restArgs);\n break;\n\n case 'hypothesis':\n case 'hypo':\n case 'hypotheses':\n handleHypothesisCommand(restArgs);\n break;\n\n case 'tell':\n handleTellCommand(restArgs);\n break;\n\n case 'reconcile':\n handleReconcileCommand(restArgs);\n break;\n\n case 'learn':\n case 'train':\n handleLearnCommand(restArgs);\n break;\n\n case 'ok':\n case 'thumbs-up':\n handleLearnCommand(['ok', ...restArgs]);\n break;\n\n case 'bad':\n case 'thumbs-down':\n handleLearnCommand(['bad', ...restArgs]);\n break;\n\n case 'quiet':\n case 'snooze':\n handleQuietCommand();\n break;\n\n case 'ci':\n case 'ci-setup':\n handleCISetupCommand(restArgs);\n break;\n\n case 'linear':\n handleLinearCommand(restArgs);\n break;\n\n case 'gotcha':\n case 'predict':\n handleGotchaCommand();\n break;\n\n case 'patterns':\n case 'pattern':\n handlePatternsCommand(restArgs);\n break;\n\n case 'sync':\n {\n const syncCommand = createSyncCommand();\n syncCommand.parse(['node', 'trie', 'sync', ...restArgs], { from: 'user' });\n }\n break;\n\n case 'ledger':\n {\n const ledgerCommand = createLedgerCommand();\n ledgerCommand.parse(['node', 'trie', 'ledger', ...restArgs], { from: 'user' });\n }\n break;\n\n default:\n // Check if it looks like a flag (pass to watch daemon)\n if (command.startsWith('-')) {\n // Treat as watch-daemon args\n const { spawn } = require('child_process');\n const daemonPath = resolve(__dirname, 'yolo-daemon.js');\n \n const child = spawn('node', [daemonPath, ...args], {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code: number) => {\n process.exit(code || 0);\n });\n } else {\n console.error(`Unknown command: ${command}`);\n console.error(`Run 'trie help' for usage information.`);\n process.exit(1);\n }\n }\n}\n\n// Check if this module is the entry point\n// We use realpathSync to resolve symlinks (npm bin creates symlinks)\nconst isEntryPoint = (() => {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n // Use imported realpathSync instead of dynamic require\n const realEntry = realpathSync(entry);\n const realThis = fileURLToPath(import.meta.url);\n return realEntry === realThis;\n } catch {\n // Fallback: check if we're being run directly (not imported in tests)\n // Tests use vitest which sets specific env vars\n return !process.env.VITEST && !process.env.VITEST_WORKER_ID;\n }\n})();\n\nif (isEntryPoint) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { postCommitTemplate, preCommitTemplate, prePushTemplate } from './templates.js';\n\ntype HookName = 'pre-commit' | 'post-commit' | 'pre-push';\n\nconst HOOK_BUILDERS: Record<HookName, () => string> = {\n 'pre-commit': preCommitTemplate,\n 'post-commit': postCommitTemplate,\n 'pre-push': prePushTemplate\n};\n\nfunction hookPath(repoPath: string, name: HookName): string {\n return path.join(repoPath, '.git', 'hooks', name);\n}\n\nfunction ensureHookDir(repoPath: string): void {\n const dir = path.join(repoPath, '.git', 'hooks');\n fs.mkdirSync(dir, { recursive: true });\n}\n\nfunction appendHookFile(targetPath: string, content: string): void {\n if (fs.existsSync(targetPath)) {\n const existing = fs.readFileSync(targetPath, 'utf8');\n if (existing.includes('# Trie pre-commit hook') || existing.includes('# Trie post-commit hook')) {\n return;\n }\n fs.appendFileSync(targetPath, `\\n# --- Added by Trie ---\\n${content}`);\n } else {\n fs.writeFileSync(targetPath, content, { mode: 0o755 });\n }\n fs.chmodSync(targetPath, 0o755);\n}\n\nexport function installGitHooks(projectPath: string): string[] {\n const gitDir = path.join(projectPath, '.git');\n if (!fs.existsSync(gitDir)) {\n return [];\n }\n\n ensureHookDir(projectPath);\n\n const installed: string[] = [];\n (Object.keys(HOOK_BUILDERS) as HookName[]).forEach((name) => {\n const content = HOOK_BUILDERS[name]();\n const target = hookPath(projectPath, name);\n appendHookFile(target, content);\n installed.push(name);\n });\n\n return installed;\n}\n","const PATH_FIX = 'export PATH=\"/usr/local/bin:/opt/homebrew/bin:$PATH\"\\n';\n\nfunction hookHeader(): string {\n return '#!/bin/sh\\n' + PATH_FIX + '\\n';\n}\n\nfunction trieCommand(name: string): string {\n return `\nTRIE_BIN=\"$(command -v trie || command -v trie-agent || true)\"\nif [ -n \"$TRIE_BIN\" ]; then\n \"$TRIE_BIN\" ${name} || true\nelse\n echo \"Trie not available; skipping ${name} hook.\"\nfi\n`;\n}\n\n/**\n * Pre-push hook command that can block on critical issues\n * Supports bypass via TRIE_BYPASS=1 environment variable\n */\nfunction prePushCommand(): string {\n return `\nTRIE_BIN=\"$(command -v trie || command -v trie-agent || true)\"\nif [ -n \"$TRIE_BIN\" ]; then\n # Check for bypass\n if [ \"$TRIE_BYPASS\" = \"1\" ] || [ \"$TRIE_BYPASS\" = \"true\" ]; then\n echo \"Trie push blocking bypassed (TRIE_BYPASS=1)\"\n \"$TRIE_BIN\" pre-push --bypassed || true\n exit 0\n fi\n \n # Run pre-push check with blocking enabled\n \"$TRIE_BIN\" pre-push --block\n EXIT_CODE=$?\n \n if [ $EXIT_CODE -eq 0 ]; then\n exit 0\n elif [ $EXIT_CODE -eq 2 ]; then\n # Exit code 2 = blocked but bypassable\n echo \"\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n echo \"Push blocked by Trie due to critical issues.\"\n echo \"\"\n echo \"To bypass (not recommended):\"\n echo \" TRIE_BYPASS=1 git push\"\n echo \" OR: git push --no-verify\"\n echo \"\"\n echo \"To fix issues first:\"\n echo \" trie fix\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n exit 1\n else\n # Other errors - don't block\n exit 0\n fi\nelse\n echo \"Trie not available; skipping pre-push hook.\"\nfi\n`;\n}\n\nexport function preCommitTemplate(): string {\n return (\n hookHeader() +\n '# Trie pre-commit hook\\n' +\n trieCommand('pre-commit')\n ).trim() + '\\n';\n}\n\nexport function postCommitTemplate(): string {\n return (\n hookHeader() +\n '# Trie post-commit hook\\n' +\n trieCommand('post-commit')\n ).trim() + '\\n';\n}\n\nexport function prePushTemplate(): string {\n return (\n hookHeader() +\n '# Trie pre-push hook with blocking support\\n' +\n '# Bypass with: TRIE_BYPASS=1 git push\\n' +\n prePushCommand()\n ).trim() + '\\n';\n}\n","/**\n * CLI Init Command\n * \n * Initialize bootstrap files for a new project.\n */\n\nimport { initializeBootstrapFiles, needsBootstrap, completeBootstrap } from '../bootstrap/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getSkillCategories } from '../bootstrap/stack-detector.js';\nimport { installGitHooks } from '../hooks/install.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nfunction ensureGitignore(workDir: string): void {\n const target = path.join(workDir, '.gitignore');\n const entries = ['.trie/context.db', '.trie/context.json', '.trie/*.db', 'trie-reports/'];\n let content = '';\n if (fs.existsSync(target)) {\n content = fs.readFileSync(target, 'utf8');\n }\n const missing = entries.filter((e) => !content.includes(e));\n if (missing.length > 0) {\n const updated = content.trimEnd() + '\\n' + missing.join('\\n') + '\\n';\n fs.writeFileSync(target, updated);\n }\n}\n\nexport async function handleInitCommand(args: string[]): Promise<void> {\n try {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n\n if (subcommand === 'complete') {\n const result = await completeBootstrap(workDir);\n if (result) {\n console.log('Bootstrap completed. BOOTSTRAP.md has been deleted.');\n } else {\n console.log('No BOOTSTRAP.md file found.');\n }\n return;\n }\n\n if (subcommand === 'status') {\n const needs = needsBootstrap(workDir);\n if (needs) {\n console.log('Bootstrap pending: .trie/BOOTSTRAP.md exists');\n console.log('Run \"trie init complete\" after finishing setup.');\n } else {\n console.log('Bootstrap complete: No pending setup.');\n }\n return;\n }\n\n const force = args.includes('--force') || args.includes('-f');\n const skipBootstrap = args.includes('--skip-bootstrap');\n\n console.log(`\n╔════════════════════════════════════════════════╗\n║ ║\n║ ████████╗██████╗ ██╗███████╗ ║\n║ ╚══██╔══╝██╔══██╗██║██╔════╝ ║\n║ ██║ ██████╔╝██║█████╗ ║\n║ ██║ ██╔══██╗██║██╔══╝ ║\n║ ██║ ██║ ██║██║███████╗ ║\n║ ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝ ║\n║ ║\n║ Your code quality agent and skills registry ║\n║ ║\n╚════════════════════════════════════════════════╝\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n\n`);\n\n const result = await initializeBootstrapFiles({\n workDir,\n force,\n skipBootstrap,\n });\n\n // Check if this is a re-init (all files already exist)\n const isReInit = result.created.length === 0 && result.skipped.length > 0;\n\n if (isReInit && !force) {\n console.log('Trie is already initialized in this project.\\n');\n console.log('Your files:');\n for (const file of result.skipped) {\n console.log(` ✓ .trie/${file}`);\n }\n console.log('\\nTo reset and recreate files: trie init --force');\n } else {\n if (result.created.length > 0) {\n console.log('Created files:');\n for (const file of result.created) {\n console.log(` + .trie/${file}`);\n }\n }\n\n if (result.skipped.length > 0 && !force) {\n console.log('\\nSkipped (already exist):');\n for (const file of result.skipped) {\n console.log(` - .trie/${file}`);\n }\n }\n }\n\n console.log('\\nDetected Stack:');\n if (result.stack.framework) console.log(` Framework: ${result.stack.framework}`);\n if (result.stack.language) console.log(` Language: ${result.stack.language}`);\n if (result.stack.database) console.log(` Database: ${result.stack.database}`);\n if (result.stack.auth) console.log(` Auth: ${result.stack.auth}`);\n if (result.stack.packageManager) console.log(` Package Manager: ${result.stack.packageManager}`);\n\n if (result.stack.suggestedSkills.length > 0) {\n // Limit to top 5 most relevant skills to avoid overwhelming output\n const topSkills = result.stack.suggestedSkills.slice(0, 5);\n console.log('\\nSuggested Skills (based on your stack):');\n for (const skill of topSkills) {\n console.log(` trie skills add ${skill}`);\n }\n if (result.stack.suggestedSkills.length > 5) {\n console.log(` ... and ${result.stack.suggestedSkills.length - 5} more: trie skills suggest`);\n }\n }\n\n // Show category exploration options\n const categories = getSkillCategories();\n const topCategories = categories.slice(0, 5);\n console.log('\\nExplore skill categories:');\n for (const cat of topCategories) {\n console.log(` trie skills list ${cat.name.padEnd(15)} # ${cat.count} skills`);\n }\n console.log(` trie skills list categories # see all ${categories.length} categories`);\n \n console.log('\\nBrowse all skills: https://skills.sh');\n\n console.log(`\nQuick Start:\n 1. trie scan # Analyze your codebase now\n 2. trie watch # Start watching (nudges as you code)\n 3. trie tell \"what broke\" # Teach Trie about past incidents\n\nTrie is now active via git hooks (pre-commit, pre-push).\nFor real-time nudges while coding, run \"trie watch\" in a terminal.\n\nCustomize Later:\n - .trie/PROJECT.md — Describe your project for better context\n - .trie/RULES.md — Define coding standards Trie should enforce\n\nRun \"trie help\" to see all available commands.\n`);\n\n const hooks = installGitHooks(workDir);\n if (hooks.length > 0) {\n console.log('\\nGit hooks installed:');\n for (const hook of hooks) {\n console.log(` .git/hooks/${hook}`);\n }\n } else {\n console.log('\\nGit hooks not installed (no .git directory found).');\n }\n\n ensureGitignore(workDir);\n if (!process.env.ANTHROPIC_API_KEY) {\n console.log(`\nNote: Running in pattern-only mode. For AI-powered analysis, set your API key:\n\n This session only:\n export ANTHROPIC_API_KEY=sk-ant-...\n\n Persist in shell config (~/.zshrc or ~/.bashrc):\n echo 'export ANTHROPIC_API_KEY=sk-ant-...' >> ~/.zshrc\n source ~/.zshrc\n\n Or add to your MCP config for Cursor/Claude Code (see README).`);\n }\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","/**\n * CLI Memory Command\n * \n * Search and manage issue memory.\n */\n\nimport {\n searchIssues,\n getMemoryStats,\n getRecentIssues,\n getDailyLogs,\n markIssueResolved,\n purgeIssues,\n} from '../memory/issue-store.js';\nimport {\n findCrossProjectPatterns,\n listTrackedProjects,\n getGlobalMemoryStats,\n updateGlobalMemoryMd,\n searchGlobalPatterns,\n} from '../memory/global-memory.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function handleMemoryCommand(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n const restArgs = args.slice(1);\n\n switch (subcommand) {\n case 'search':\n await handleSearch(restArgs);\n break;\n case 'stats':\n await handleStats();\n break;\n case 'recent':\n await handleRecent(restArgs);\n break;\n case 'logs':\n await handleLogs();\n break;\n case 'resolve':\n await handleResolve(restArgs);\n break;\n case 'purge':\n await handlePurge(restArgs);\n break;\n case 'global':\n await handleGlobal(restArgs);\n break;\n default:\n showHelp();\n }\n}\n\nasync function handleSearch(args: string[]): Promise<void> {\n const query = args.join(' ');\n \n if (!query) {\n console.log('Usage: trie memory search <query>');\n console.log('Example: trie memory search \"SQL injection\"');\n return;\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n const results = await searchIssues(query, { workDir, limit: 10 });\n\n if (results.length === 0) {\n console.log(`No issues found matching \"${query}\"`);\n return;\n }\n\n console.log(`Found ${results.length} issue(s) matching \"${query}\":\\n`);\n\n for (const result of results) {\n const i = result.issue;\n const status = i.resolved ? '[RESOLVED]' : '';\n console.log(`[${i.severity.toUpperCase()}] ${status} ${i.issue.slice(0, 80)}`);\n console.log(` File: ${i.file}${i.line ? `:${i.line}` : ''}`);\n console.log(` Agent: ${i.agent} | Score: ${(result.score * 100).toFixed(0)}%`);\n console.log(` Date: ${new Date(i.timestamp).toLocaleDateString()}`);\n console.log('');\n }\n}\n\nasync function handleStats(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n const stats = await getMemoryStats(workDir);\n const globalStats = await getGlobalMemoryStats();\n\n console.log('Local Issue Memory Stats:');\n console.log(` Active Issues: ${stats.activeIssues}`);\n console.log(` Resolved: ${stats.resolvedCount}`);\n console.log(` Total (all-time): ${stats.totalIssues}`);\n \n // Capacity info\n const cap = stats.capacityInfo;\n if (cap.isAtCap) {\n console.log('\\n⚠️ CAPACITY WARNING');\n console.log(` Memory is at maximum capacity (${cap.current}/${cap.max}, ${cap.percentFull}%)`);\n console.log(' New repeats are deduplicated. Older issues are compacted into summaries, and if still over cap the oldest/lowest-value issues are pruned.');\n console.log('\\n To free up space:');\n console.log(' trie memory purge smart - Remove resolved & old low-priority (recommended)');\n console.log(' trie memory purge resolved - Remove all resolved issues');\n console.log(' trie memory purge old - Remove issues older than 90 days');\n console.log(' trie memory purge all - Clear all issues (keeps summaries)');\n } else if (cap.percentFull >= 80) {\n console.log(`\\nℹ️ Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`);\n console.log(' Consider running: trie memory purge smart');\n } else {\n console.log(` Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`);\n }\n \n // Deduplication stats\n if (stats.deduplicationStats.duplicatesAvoided > 0) {\n console.log('\\n Deduplication:');\n console.log(` Unique Patterns: ${stats.deduplicationStats.uniquePatterns}`);\n console.log(` Duplicates Avoided: ${stats.deduplicationStats.duplicatesAvoided}`);\n }\n \n if (stats.oldestIssue) {\n console.log(`\\n Date Range: ${stats.oldestIssue.split('T')[0]} to ${stats.newestIssue?.split('T')[0]}`);\n }\n\n console.log('\\n Active Issues by Severity:');\n const severityOrder = ['critical', 'serious', 'moderate', 'low', 'info'];\n let hasActiveIssues = false;\n for (const severity of severityOrder) {\n const activeCount = stats.activeIssuesBySeverity[severity] || 0;\n const totalCount = stats.issuesBySeverity[severity] || 0;\n if (totalCount > 0) {\n hasActiveIssues = hasActiveIssues || activeCount > 0;\n console.log(` ${severity}: ${activeCount} active (${totalCount} all-time)`);\n }\n }\n if (!hasActiveIssues && stats.totalIssues > 0) {\n console.log(' ✅ All issues have been resolved!');\n }\n\n console.log('\\n By Agent:');\n const sortedAgents = Object.entries(stats.issuesByAgent).sort((a, b) => b[1] - a[1]);\n for (const [agent, count] of sortedAgents.slice(0, 10)) {\n console.log(` ${agent}: ${count}`);\n }\n\n console.log('\\nGlobal Cross-Project Stats:');\n console.log(` Tracked Projects: ${globalStats.trackedProjects}`);\n console.log(` Total Patterns: ${globalStats.totalPatterns}`);\n console.log(` Cross-Project Patterns: ${globalStats.crossProjectPatterns}`);\n console.log(` Fixed Patterns: ${globalStats.fixedPatterns}`);\n}\n\nasync function handleRecent(args: string[]): Promise<void> {\n const limit = parseInt(args[0] || '10', 10);\n const workDir = getWorkingDirectory(undefined, true);\n const issues = await getRecentIssues({ workDir, limit });\n\n if (issues.length === 0) {\n console.log('No recent issues found.');\n return;\n }\n\n console.log(`Recent Issues (last 7 days):\\n`);\n\n for (const i of issues) {\n const status = i.resolved ? '[RESOLVED]' : '';\n console.log(`[${i.severity.toUpperCase()}] ${status} ${i.issue.slice(0, 70)}`);\n console.log(` ${i.file}${i.line ? `:${i.line}` : ''} | ${i.agent}`);\n console.log('');\n }\n}\n\nasync function handleLogs(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n const logs = await getDailyLogs(workDir);\n\n if (logs.length === 0) {\n console.log('No daily logs found.');\n return;\n }\n\n console.log('Daily Logs (.trie/memory/):\\n');\n for (const log of logs.slice(0, 14)) {\n console.log(` ${log}`);\n }\n\n if (logs.length > 14) {\n console.log(` ... and ${logs.length - 14} more`);\n }\n}\n\nasync function handleResolve(args: string[]): Promise<void> {\n const issueId = args[0];\n \n if (!issueId) {\n console.log('Usage: trie memory resolve <issue-id>');\n return;\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n const result = await markIssueResolved(issueId, workDir);\n\n if (result) {\n console.log(`Issue ${issueId} marked as resolved.`);\n } else {\n console.log(`Issue ${issueId} not found.`);\n }\n}\n\nasync function handleGlobal(args: string[]): Promise<void> {\n const action = args[0]?.toLowerCase();\n\n if (action === 'patterns') {\n const patterns = await findCrossProjectPatterns(2);\n \n if (patterns.length === 0) {\n console.log('No cross-project patterns found yet.');\n console.log('Patterns appear when the same issue is detected in multiple projects.');\n return;\n }\n\n console.log(`Cross-Project Patterns (${patterns.length}):\\n`);\n \n for (const p of patterns.slice(0, 10)) {\n console.log(`[${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`);\n console.log(` Occurrences: ${p.occurrences} across ${p.projects.length} projects`);\n console.log(` Agent: ${p.agent}`);\n if (p.fixApplied) {\n console.log(` Fixed in: ${p.fixApplied.project}`);\n }\n console.log('');\n }\n return;\n }\n\n if (action === 'projects') {\n const projects = await listTrackedProjects();\n \n if (projects.length === 0) {\n console.log('No projects tracked yet.');\n return;\n }\n\n console.log(`Tracked Projects (${projects.length}):\\n`);\n console.log('| Project | Last Scan | Issues |');\n console.log('|---------|-----------|--------|');\n \n for (const p of projects) {\n console.log(`| ${p.name.slice(0, 20)} | ${p.lastScan.split('T')[0]} | ${p.totalIssues} |`);\n }\n return;\n }\n\n if (action === 'search') {\n const query = args.slice(1).join(' ');\n if (!query) {\n console.log('Usage: trie memory global search <query>');\n return;\n }\n\n const patterns = await searchGlobalPatterns(query, { limit: 10 });\n \n if (patterns.length === 0) {\n console.log(`No global patterns found matching \"${query}\"`);\n return;\n }\n\n console.log(`Global patterns matching \"${query}\":\\n`);\n for (const p of patterns) {\n console.log(`[${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`);\n console.log(` Projects: ${p.projects.slice(0, 3).join(', ')}`);\n console.log('');\n }\n return;\n }\n\n if (action === 'update') {\n await updateGlobalMemoryMd();\n console.log('Updated ~/.trie/memory/GLOBAL_MEMORY.md');\n return;\n }\n\n console.log(`\nGlobal Memory Commands:\n trie memory global patterns Show cross-project patterns\n trie memory global projects Show tracked projects\n trie memory global search <q> Search global patterns\n trie memory global update Update GLOBAL_MEMORY.md\n`);\n}\n\nasync function handlePurge(args: string[]): Promise<void> {\n const strategy = (args[0]?.toLowerCase() as 'smart' | 'resolved' | 'old' | 'all') || 'smart';\n const validStrategies = ['smart', 'resolved', 'old', 'all'];\n \n if (!validStrategies.includes(strategy)) {\n console.log('Invalid purge strategy. Use: smart, resolved, old, or all');\n console.log('\\nUsage:');\n console.log(' trie memory purge smart - Remove resolved & old low-priority (recommended)');\n console.log(' trie memory purge resolved - Remove all resolved issues');\n console.log(' trie memory purge old [days] - Remove issues older than N days (default 90)');\n console.log(' trie memory purge all - Clear all issues (keeps summaries)');\n return;\n }\n\n const daysOld = strategy === 'old' ? parseInt(args[1] || '90', 10) : undefined;\n \n // Confirm destructive actions\n if (strategy === 'all') {\n console.log('⚠️ WARNING: This will clear ALL issues from active memory.');\n console.log('Historical summaries will be preserved, but individual issues will be removed.');\n console.log('\\nTo confirm, run: trie memory purge all --confirm');\n \n if (!args.includes('--confirm')) {\n return;\n }\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n console.log(`\\nPurging issues with strategy: ${strategy}...`);\n \n const options: { workDir: string; daysOld?: number } = { workDir };\n if (daysOld !== undefined) {\n options.daysOld = daysOld;\n }\n \n const result = await purgeIssues(strategy, options);\n\n console.log(`\\n✅ Purge Complete`);\n console.log(` Strategy: ${result.strategy}`);\n console.log(` Removed: ${result.removed} issues`);\n console.log(` Remaining: ${result.remaining} issues`);\n\n switch (strategy) {\n case 'smart':\n console.log('\\nWhat was removed:');\n console.log(' • Resolved issues older than 30 days');\n console.log(' • Low-priority issues (info/low) older than 30 days');\n console.log('\\nWhat was kept:');\n console.log(' • All critical and high severity issues');\n console.log(' • All unresolved issues');\n console.log(' • All issues from the last 30 days');\n break;\n case 'resolved':\n console.log('\\nRemoved all resolved issues.');\n console.log('Kept all unresolved issues.');\n break;\n case 'old':\n console.log(`\\nRemoved all issues older than ${daysOld} days.`);\n console.log('Kept all recent issues.');\n break;\n case 'all':\n console.log('\\nCleared all issues from active memory.');\n console.log('Historical summaries preserved in .trie/memory/compacted-summaries.json');\n break;\n }\n \n console.log('\\nRun \"trie memory stats\" to see updated memory usage.');\n}\n\nfunction showHelp(): void {\n console.log(`\nMemory - Search and manage issue memory\n\nCommands:\n trie memory search <query> Search issues by keyword\n trie memory stats Show memory statistics\n trie memory recent [limit] Show recent issues\n trie memory logs List daily log files\n trie memory resolve <id> Mark issue as resolved\n trie memory purge <strategy> Free up memory space\n trie memory global <action> Cross-project memory\n\nPurge Strategies:\n smart Remove resolved & old low-priority issues (recommended)\n resolved Remove all resolved issues\n old [N] Remove issues older than N days (default 90)\n all Clear all issues (keeps historical summaries)\n\nExamples:\n trie memory search \"SQL injection\"\n trie memory recent 20\n trie memory purge smart\n trie memory global patterns\n`);\n}\n","import { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\ninterface CheckOptions {\n mode: 'quick' | 'full' | 'offline';\n files?: string[];\n}\n\nfunction parseArgs(args: string[]): CheckOptions {\n let mode: CheckOptions['mode'] = 'full';\n const filesFlag = args.find((a) => a.startsWith('--files='));\n const parsedFiles = filesFlag ? filesFlag.replace('--files=', '').split(',').map((f) => f.trim()).filter(Boolean) : [];\n\n if (args.includes('--quick') || args.includes('-q')) mode = 'quick';\n if (args.includes('--offline')) mode = 'offline';\n if (args.includes('--full')) mode = 'full';\n\n const result: CheckOptions = { mode };\n if (parsedFiles.length > 0) result.files = parsedFiles;\n return result;\n}\n\nfunction printResult(result: any) {\n console.log(`\\nRisk: ${result.original.riskLevel.toUpperCase()} (${result.original.shouldBlock ? 'block' : 'allow'})`);\n console.log(`Explanation: ${result.original.explanation}`);\n console.log(`Recommendation: ${result.original.recommendation}`);\n\n if (result.original.files?.length) {\n console.log('\\nHigh-risk files:');\n for (const file of result.original.files.filter((f: any) => ['high', 'critical'].includes(f.level))) {\n console.log(` - ${file.file}: ${file.reasons.join('; ')}`);\n }\n }\n\n console.log('\\nPlain-English summary:');\n console.log(` Summary: ${result.summary}`);\n console.log(` What I found: ${result.whatIFound}`);\n console.log(` How bad: ${result.howBad}`);\n console.log(` What to do: ${result.whatToDo}`);\n}\n\nexport async function handleCheckCommand(args: string[]): Promise<void> {\n try {\n const options = parseArgs(args);\n const projectPath = getWorkingDirectory(undefined, true);\n\n let files = options.files;\n if (!files || files.length === 0) {\n const perception = await perceiveCurrentChanges(projectPath);\n files = perception.diffSummary.files.map((f) => f.filePath);\n if (files.length === 0) {\n console.log('No changes detected. Provide files with --files=path1,path2 or make a change first.');\n return;\n }\n }\n\n const runAgents = options.mode === 'full';\n const reasoning = await reasonAboutChangesHumanReadable(projectPath, files, {\n runAgents,\n scanContext: {\n config: { timeoutMs: options.mode === 'quick' ? 15000 : 60000 }\n }\n });\n\n printResult(reasoning);\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","/**\n * Pre-push Command Handler\n * \n * Runs before git push with blocking support for critical issues.\n * \n * Exit codes:\n * - 0: Push allowed\n * - 1: Push blocked (fatal error)\n * - 2: Push blocked due to critical issues (bypassable)\n */\n\nimport { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { \n getAutonomyConfig, \n shouldBlockPush,\n recordBypass,\n trackIssueOccurrence \n} from '../utils/autonomy-config.js';\nimport pc from 'picocolors';\n\ninterface PrePushOptions {\n block: boolean;\n bypassed: boolean;\n quick: boolean;\n}\n\nfunction parseArgs(args: string[]): PrePushOptions {\n return {\n block: args.includes('--block'),\n bypassed: args.includes('--bypassed'),\n quick: args.includes('--quick') || args.includes('-q'),\n };\n}\n\nexport async function handlePrePushCommand(args: string[]): Promise<void> {\n const options = parseArgs(args);\n const projectPath = getWorkingDirectory(undefined, true);\n \n try {\n // Load autonomy config\n const autonomyConfig = await getAutonomyConfig(projectPath);\n \n // If bypassed, log and allow\n if (options.bypassed) {\n console.error(pc.yellow('Pre-push check bypassed by user'));\n \n // Log the bypass for audit trail\n if (autonomyConfig.pushBlocking.logBypasses) {\n await recordBypass(\n projectPath,\n 'git-push',\n undefined,\n 'pre-push-bypass',\n 'env',\n 'User set TRIE_BYPASS=1'\n );\n }\n \n process.exit(0);\n }\n \n // Get changed files\n const perception = await perceiveCurrentChanges(projectPath);\n const files = perception.diffSummary.files.map((f) => f.filePath);\n \n if (files.length === 0) {\n console.error(pc.green('✓ No changes to check'));\n process.exit(0);\n }\n \n console.error(pc.cyan(`\\n🔍 Checking ${files.length} file(s) before push...\\n`));\n \n // Run quick analysis\n const reasoning = await reasonAboutChangesHumanReadable(projectPath, files, {\n runAgents: !options.quick,\n scanContext: {\n config: { timeoutMs: options.quick ? 15000 : 30000 }\n }\n });\n \n // Check if we should block\n if (options.block && autonomyConfig.pushBlocking.enabled) {\n // Collect issues for blocking check\n const issues = collectIssuesForBlocking(reasoning);\n \n // Track occurrences for progressive escalation\n for (const issue of issues) {\n await trackIssueOccurrence(\n projectPath,\n issue.file,\n issue.line,\n issue.severity,\n autonomyConfig\n );\n }\n \n const blockResult = shouldBlockPush(issues, autonomyConfig);\n \n if (blockResult.blocked) {\n // Print blocking message\n console.error('');\n console.error(pc.red('━'.repeat(60)));\n console.error(pc.bold(pc.red('PUSH BLOCKED')));\n console.error(pc.red('━'.repeat(60)));\n console.error('');\n console.error(pc.yellow(`Found ${blockResult.blockingIssues.length} blocking issue(s):`));\n console.error('');\n \n // Show top blocking issues\n for (const issue of blockResult.blockingIssues.slice(0, 5)) {\n const icon = issue.severity === 'critical' ? '[!]' : '[!]';\n console.error(` ${icon} ${pc.dim(issue.file)}${issue.line ? `:${issue.line}` : ''}`);\n console.error(` ${issue.issue.slice(0, 80)}${issue.issue.length > 80 ? '...' : ''}`);\n }\n \n if (blockResult.blockingIssues.length > 5) {\n console.error(` ... and ${blockResult.blockingIssues.length - 5} more`);\n }\n \n console.error('');\n console.error(pc.dim('─'.repeat(60)));\n \n if (blockResult.bypassInstructions) {\n console.error('');\n console.error(pc.yellow('To bypass (not recommended):'));\n for (const line of blockResult.bypassInstructions.split('\\n')) {\n console.error(pc.dim(line));\n }\n }\n \n console.error('');\n console.error(pc.cyan('To fix issues:'));\n console.error(pc.dim(' trie fix # Auto-fix trivial issues'));\n console.error(pc.dim(' trie scan # See all issues'));\n console.error('');\n \n // Exit with code 2 to indicate bypassable block\n process.exit(2);\n } else if (blockResult.bypassed) {\n console.error(pc.yellow(`Bypassed: ${blockResult.blockingIssues.length} issue(s) ignored`));\n }\n }\n \n // Print summary\n const riskLevel = reasoning.original?.riskLevel || 'low';\n const riskColor = riskLevel === 'critical' ? pc.red : \n riskLevel === 'high' ? pc.yellow : \n riskLevel === 'medium' ? pc.blue : pc.green;\n \n console.error('');\n console.error(riskColor(`Risk: ${riskLevel.toUpperCase()}`));\n console.error(pc.dim(reasoning.summary || 'No significant risks detected'));\n console.error('');\n \n // Allow push\n process.exit(0);\n \n } catch (error) {\n // On error, don't block the push\n const friendly = formatFriendlyError(error);\n console.error(pc.yellow(`Pre-push check error: ${friendly.userMessage}`));\n console.error(pc.dim('Allowing push to continue.'));\n process.exit(0);\n }\n}\n\n/**\n * Collect issues from reasoning result for blocking check\n */\nfunction collectIssuesForBlocking(reasoning: any): Array<{\n file: string;\n line?: number;\n severity: string;\n issue: string;\n}> {\n const issues: Array<{ file: string; line?: number; severity: string; issue: string }> = [];\n \n // Extract from original reasoning\n if (reasoning.original?.files) {\n for (const file of reasoning.original.files) {\n if (file.level === 'critical' || file.level === 'high') {\n issues.push({\n file: file.file,\n severity: file.level === 'critical' ? 'critical' : 'serious',\n issue: file.reasons?.join('; ') || 'High-risk file',\n });\n }\n }\n }\n \n // Extract from scan results if available\n if (reasoning.scanResults?.issues) {\n for (const issue of reasoning.scanResults.issues) {\n if (issue.severity === 'critical' || issue.severity === 'serious') {\n issues.push({\n file: issue.file,\n line: issue.line,\n severity: issue.severity,\n issue: issue.issue,\n });\n }\n }\n }\n \n return issues;\n}\n","import { writeFile, mkdir, chmod } from 'fs/promises';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport pc from 'picocolors';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { isGitRepo } from '../agent/git.js';\nimport { resolve, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\n/**\n * Install git hooks for automatic ledger sync\n */\nexport async function installGitHooks(): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n\n const isRepo = await isGitRepo(workDir);\n if (!isRepo) {\n console.log(pc.yellow('⚠ Not a git repository. Git hooks not installed.'));\n return;\n }\n\n const hooksDir = join(workDir, '.git', 'hooks');\n\n if (!existsSync(hooksDir)) {\n await mkdir(hooksDir, { recursive: true });\n }\n\n // Pre-push hook: sync ledger to shared storage\n const prePushHook = `#!/bin/sh\n# Auto-sync ledger to shared storage before push\n\n# Only run if trie is initialized\nif [ ! -d \".trie\" ]; then\n exit 0\nfi\n\n# Check if trie command is available\nif ! command -v trie >/dev/null 2>&1; then\n echo \"Warning: trie command not found, skipping ledger sync\"\n exit 0\nfi\n\n# Sync ledger to shared storage\necho \"Syncing ledger to shared storage...\"\ntrie sync push 2>/dev/null || true\n\nexit 0\n`;\n\n // Post-merge hook: sync ledger from shared storage\n const postMergeHook = `#!/bin/sh\n# Auto-sync ledger from shared storage after merge\n\n# Only run if trie is initialized\nif [ ! -d \".trie\" ]; then\n exit 0\nfi\n\n# Check if trie command is available\nif ! command -v trie >/dev/null 2>&1; then\n exit 0\nfi\n\n# Sync ledger from shared storage\necho \"Syncing ledger from shared storage...\"\ntrie sync pull 2>/dev/null || true\n\nexit 0\n`;\n\n const prePushPath = join(hooksDir, 'pre-push');\n const postMergePath = join(hooksDir, 'post-merge');\n\n // Install hooks\n await writeFile(prePushPath, prePushHook);\n await writeFile(postMergePath, postMergeHook);\n\n // Make hooks executable\n await chmod(prePushPath, 0o755);\n await chmod(postMergePath, 0o755);\n\n console.log(pc.green('✓ Git hooks installed successfully'));\n console.log(pc.dim(' pre-push: Syncs ledger to shared storage'));\n console.log(pc.dim(' post-merge: Syncs ledger from shared storage'));\n}\n\n/**\n * Check if git hooks are installed\n */\nexport async function checkGitHooks(): Promise<{\n isGitRepo: boolean;\n prePushInstalled: boolean;\n postMergeInstalled: boolean;\n}> {\n const workDir = getWorkingDirectory(undefined, true);\n\n const isRepo = await isGitRepo(workDir);\n if (!isRepo) {\n return {\n isGitRepo: false,\n prePushInstalled: false,\n postMergeInstalled: false\n };\n }\n\n const hooksDir = join(workDir, '.git', 'hooks');\n const prePushPath = join(hooksDir, 'pre-push');\n const postMergePath = join(hooksDir, 'post-merge');\n\n return {\n isGitRepo: true,\n prePushInstalled: existsSync(prePushPath),\n postMergeInstalled: existsSync(postMergePath)\n };\n}\n\n// ES module __dirname equivalent\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Handle pre-commit hook command\n */\nexport async function handlePreCommitCommand(_args: string[]): Promise<void> {\n console.log(pc.cyan('🔍 Running pre-commit hook...'));\n\n try {\n // Run a quick scan on staged files only\n const { spawn } = await import('child_process');\n\n // Determine daemon path\n let daemonPath: string;\n if (__filename.endsWith('.ts')) {\n daemonPath = resolve(__dirname, 'yolo-daemon.ts');\n } else {\n daemonPath = resolve(__dirname, 'yolo-daemon.js');\n }\n\n const daemonArgs = ['--once', '--staged-only', '--fail-on', 'critical'];\n\n // Use tsx for .ts files, node for .js files\n const executor = daemonPath.endsWith('.ts') ? 'npx' : 'node';\n const execArgs = daemonPath.endsWith('.ts')\n ? ['tsx', daemonPath, ...daemonArgs]\n : [daemonPath, ...daemonArgs];\n\n const child = spawn(executor, execArgs, {\n stdio: 'inherit',\n env: process.env\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n console.log(pc.green('✓ Pre-commit hook completed successfully'));\n } else {\n console.log(pc.red('✗ Pre-commit hook found critical issues'));\n console.log(pc.dim(' Commit blocked. Fix issues and try again.'));\n }\n process.exit(code || 0);\n });\n } catch (error) {\n console.error(pc.red('Error in pre-commit hook:'), error);\n // Don't block commit on hook errors\n process.exit(0);\n }\n}\n\n/**\n * Handle post-commit hook command\n */\nexport async function handlePostCommitCommand(_args: string[]): Promise<void> {\n console.log(pc.cyan('📝 Running post-commit hook...'));\n\n try {\n // Update context graph after commit\n const workDir = getWorkingDirectory(undefined, true);\n\n // Quick context update - don't block if it fails\n const { spawn } = await import('child_process');\n\n // Update context graph\n const updateProcess = spawn('node', [\n '-e',\n `\n const { updateContextAfterCommit } = require('./context.js');\n updateContextAfterCommit('${workDir}').catch(console.error);\n `\n ], {\n stdio: 'pipe',\n env: process.env\n });\n\n updateProcess.on('close', (code) => {\n if (code === 0) {\n console.log(pc.green('✓ Post-commit hook completed - context updated'));\n } else {\n console.log(pc.yellow('⚠ Post-commit hook completed with warnings'));\n }\n });\n\n // Don't wait for completion, let it run in background\n updateProcess.unref();\n\n } catch (error) {\n console.error(pc.yellow('Warning in post-commit hook:'), error);\n // Never block after commit\n }\n}","import pc from 'picocolors';\nimport { loadConfig, saveConfig } from '../config/loader.js';\nimport { SlackIntegration } from '../integrations/slack.js';\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { getTrieDirectory, getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Show setup instructions or configure integrations\n */\nexport async function handleSetupCommand(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n\n if (subcommand === 'slack') {\n await setupSlackIntegration(args.slice(1));\n return;\n }\n\n if (subcommand === 'test-slack') {\n await testSlackIntegration();\n return;\n }\n\n // Show general setup instructions\n showSetup();\n}\n\n/**\n * Setup Slack integration\n */\nasync function setupSlackIntegration(args: string[]): Promise<void> {\n const webhookUrl = args[0];\n\n if (!webhookUrl) {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Slack Integration Setup ║\n╚══════════════════════════════════════════════════════════════════╝\n\nSTEP 1: Create a Slack Webhook\n${pc.dim('─────────────────────────────────────')}\n1. Go to https://api.slack.com/apps\n2. Click \"Create New App\" > \"From scratch\"\n3. Name your app (e.g. \"Trie Security Bot\")\n4. Choose your workspace\n5. Go to \"Incoming Webhooks\" in the sidebar\n6. Toggle \"Activate Incoming Webhooks\" to On\n7. Click \"Add New Webhook to Workspace\"\n8. Choose a channel (e.g. #security, #alerts)\n9. Copy the webhook URL\n\nSTEP 2: Configure Trie\n${pc.dim('─────────────────────────────────────')}\nRun: trie setup slack <webhook-url> [channel]\n\nEXAMPLES:\n trie setup slack https://hooks.slack.com/services/T.../B.../... #security\n trie setup slack https://hooks.slack.com/services/T.../B.../...\n\nSTEP 3: Test the Integration\n${pc.dim('─────────────────────────────────────')}\nRun: trie setup test-slack\n\nWHAT TRIE SENDS TO SLACK:\n• Decision extractions from incidents\n• Active blockers and risk predictions\n• Daily/weekly team summaries\n• Critical security findings\n• Auto-escalation notifications\n`);\n return;\n }\n\n const channel = args[1];\n\n try {\n // Validate webhook URL\n if (!webhookUrl.startsWith('https://hooks.slack.com/services/')) {\n console.error(pc.red('Error:'), 'Invalid Slack webhook URL format');\n console.error('Expected: https://hooks.slack.com/services/...');\n process.exit(1);\n }\n\n // Load current config\n const config = await loadConfig();\n\n // Update config with Slack integration\n const updatedConfig = {\n ...config,\n integrations: {\n ...config.integrations,\n slack: {\n enabled: true,\n webhook: webhookUrl,\n channel: channel || undefined,\n },\n },\n };\n\n // Save updated config\n await saveConfig(updatedConfig);\n\n console.log(pc.green('✓'), 'Slack integration configured successfully!');\n if (channel) {\n console.log(pc.dim(` Channel: ${channel}`));\n }\n console.log(pc.dim(` Webhook: ${webhookUrl.substring(0, 50)}...`));\n\n console.log(`\n${pc.bold('Next steps:')}\n1. Test the integration: ${pc.cyan('trie setup test-slack')}\n2. Configure auto-escalation (optional):\n ${pc.dim('Add to .trie/config.json:')}\n ${pc.dim(`{\n \"autoEscalation\": {\n \"enabled\": true,\n \"webhookUrl\": \"${webhookUrl}\",\n \"quietHours\": { \"start\": \"21:00\", \"end\": \"08:00\" }\n }\n }`)}\n3. Notifications will be sent for:\n • Critical security issues\n • Team assignments and escalations\n • Daily/weekly summaries\n`);\n } catch (error) {\n console.error(pc.red('Error configuring Slack integration:'), error);\n process.exit(1);\n }\n}\n\n/**\n * Test Slack integration\n */\nasync function testSlackIntegration(): Promise<void> {\n try {\n const config = await loadConfig();\n\n if (!config.integrations?.slack?.enabled || !config.integrations.slack.webhook) {\n console.error(pc.red('Error:'), 'Slack integration not configured');\n console.error('Run:', pc.cyan('trie setup slack <webhook-url>'));\n process.exit(1);\n }\n\n console.log(pc.cyan('🔍'), 'Testing Slack integration...');\n\n const slack = new SlackIntegration({\n webhookUrl: config.integrations.slack.webhook,\n channel: config.integrations.slack.channel,\n });\n\n const success = await slack.testConnection();\n\n if (success) {\n console.log(pc.green('✓'), 'Slack integration test successful!');\n console.log(pc.dim(' Check your Slack channel for the test message'));\n } else {\n console.log(pc.red('✗'), 'Slack integration test failed');\n console.log(pc.dim(' Check your webhook URL and network connection'));\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Error testing Slack integration:'), error);\n process.exit(1);\n }\n}\n\n/**\n * Show general setup instructions\n */\nfunction showSetup(): void {\n const config = getCurrentConfig();\n const hasSlack = config?.integrations?.slack?.enabled;\n const hasGitHub = config?.apiKeys?.github;\n const hasLinear = config?.apiKeys?.linear;\n\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ Trie Agent Setup ║\n╚══════════════════════════════════════════════════════════════════╝\n\nSTEP 1: API Keys\n${pc.dim('─────────────────────────────────────')}\nTrie can work offline, but performs best with these keys:\n\n1. ANTHROPIC_API_KEY (Required for AI analysis)\n Get it: https://console.anthropic.com/\n\n2. LINEAR_API_KEY (Required for JIT defect prediction)\n Get it: https://linear.app/settings/api\n\n3. GITHUB_TOKEN (Optional for GitHub integration)\n Get it: https://github.com/settings/tokens\n\nSet them in your environment (~/.zshrc) or .trie/config.json:\n export ANTHROPIC_API_KEY=sk-ant-...\n export LINEAR_API_KEY=lin_api_...\n export GITHUB_TOKEN=ghp_...\n\nSTEP 2: Team Integrations\n${pc.dim('─────────────────────────────────────')}\n${hasSlack ? pc.green('✓') : pc.red('✗')} Slack: ${hasSlack ? 'Configured' : 'trie setup slack <webhook>'}\n${hasGitHub ? pc.green('✓') : pc.red('✗')} GitHub: ${hasGitHub ? 'Configured' : 'Set GITHUB_TOKEN'}\n${hasLinear ? pc.green('✓') : pc.red('✗')} Linear: ${hasLinear ? 'Configured' : 'Set LINEAR_API_KEY'}\n\nSLACK SETUP:\n trie setup slack # Show Slack setup guide\n trie setup slack <webhook> [channel] # Configure Slack webhook\n trie setup test-slack # Test Slack integration\n\nSTEP 3: Configure for your AI tool\n${pc.dim('─────────────────────────────────────')}\n\nFor CLAUDE CODE:\n claude mcp add Trie -- npx @triedotdev/mcp\n\nFor CURSOR (~/.cursor/mcp.json):\n{\n \"mcpServers\": {\n \"Trie\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@triedotdev/mcp\"],\n \"env\": {\n \"ANTHROPIC_API_KEY\": \"your-key-here\",\n \"LINEAR_API_KEY\": \"your-key-here\"\n }\n }\n }\n}\n\nSTEP 4: Start scanning!\n${pc.dim('─────────────────────────────────────')}\nAsk your AI assistant: \"Scan this with Trie\" or \"Use trie_scan\"\n`);\n}\n\n/**\n * Get current config for status display\n */\nfunction getCurrentConfig(): any {\n try {\n const configPath = join(getTrieDirectory(getWorkingDirectory(undefined, true)), 'config.json');\n if (existsSync(configPath)) {\n return JSON.parse(readFileSync(configPath, 'utf-8'));\n }\n } catch {\n // Config file check failed\n }\n return null;\n}","/**\n * Auto-Fix with Human-in-the-Loop\n * \n * Applies fixes to code issues with user confirmation.\n * Supports batch fixing and individual review.\n */\n\nimport { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { createInterface } from 'readline';\nimport pc from 'picocolors';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getAutonomyConfig, shouldAutoFix } from '../utils/autonomy-config.js';\nimport { applyAutoFix } from '../utils/auto-fix-apply.js';\nimport type { AutoFixAction } from '../types/autonomy.js';\nimport type { Issue } from '../types/index.js';\n\n// ============================================================================\n// Fix Detection\n// ============================================================================\n\n/**\n * Detect auto-fixable issues and generate fix actions\n */\nexport function detectAutoFixes(issues: Issue[]): AutoFixAction[] {\n const fixes: AutoFixAction[] = [];\n \n for (const issue of issues) {\n const fix = generateFixForIssue(issue);\n if (fix) {\n fixes.push(fix);\n }\n }\n \n return fixes;\n}\n\n/**\n * Generate a fix action for an issue\n */\nfunction generateFixForIssue(issue: Issue): AutoFixAction | null {\n // Only generate fixes for issues with line numbers\n if (!issue.line) return null;\n \n // Console.log removal\n if (issue.issue.toLowerCase().includes('console.log') || \n issue.issue.toLowerCase().includes('console log')) {\n return {\n id: `fix-${issue.id}`,\n file: issue.file,\n line: issue.line,\n original: '', // Will be filled when reading file\n fixed: '', // Will be deletion\n type: 'remove-console-log',\n category: 'trivial',\n description: 'Remove console.log statement',\n confidence: 0.95,\n };\n }\n \n // Debugger removal\n if (issue.issue.toLowerCase().includes('debugger')) {\n return {\n id: `fix-${issue.id}`,\n file: issue.file,\n line: issue.line,\n original: '',\n fixed: '',\n type: 'remove-debugger',\n category: 'trivial',\n description: 'Remove debugger statement',\n confidence: 0.98,\n };\n }\n \n // Additional fix types can be implemented here:\n // - Remove unused imports\n // - Add missing await\n // - Fix typos\n \n return null;\n}\n\n// ============================================================================\n// User Interaction\n// ============================================================================\n\n/**\n * Prompt user for confirmation\n */\nasync function promptUser(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n \n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.toLowerCase().trim());\n });\n });\n}\n\n/**\n * Display a fix preview\n */\nfunction displayFixPreview(fix: AutoFixAction, index: number, total: number): void {\n console.error('');\n console.error(pc.cyan(`━━━ Fix ${index + 1}/${total} ━━━`));\n console.error(pc.dim(`File: ${fix.file}${fix.line ? `:${fix.line}` : ''}`));\n console.error(pc.dim(`Type: ${fix.type}`));\n console.error(pc.yellow(`Description: ${fix.description}`));\n console.error('');\n \n if (fix.original) {\n console.error(pc.red('- ' + fix.original));\n }\n if (fix.fixed) {\n console.error(pc.green('+ ' + fix.fixed));\n } else if (fix.original) {\n console.error(pc.dim(' (line will be removed)'));\n }\n console.error('');\n}\n\n// ============================================================================\n// Fix Application\n// ============================================================================\n\n/**\n * Load actual line content for fixes\n */\nasync function loadFixContent(fixes: AutoFixAction[]): Promise<AutoFixAction[]> {\n const enrichedFixes: AutoFixAction[] = [];\n \n for (const fix of fixes) {\n if (!fix.line || !existsSync(fix.file)) {\n continue;\n }\n \n try {\n const content = await readFile(fix.file, 'utf-8');\n const lines = content.split('\\n');\n const originalLine = lines[fix.line - 1];\n \n if (originalLine) {\n enrichedFixes.push({\n ...fix,\n original: originalLine,\n });\n }\n } catch {\n // Skip files we can't read\n }\n }\n \n return enrichedFixes;\n}\n\n// ============================================================================\n// Main Command Handler\n// ============================================================================\n\n/**\n * Handle the auto-fix command with human-in-the-loop\n */\nexport async function handleAutoFixCommand(args: string[], issues?: Issue[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const config = await getAutonomyConfig(projectPath);\n \n // Check if auto-fix is enabled\n if (!config.autoFix.enabled) {\n console.error(pc.yellow('Auto-fix is disabled in config.'));\n console.error(pc.dim('Enable it with: trie config set autoFix.enabled true'));\n return;\n }\n \n // Parse args\n const dryRun = args.includes('--dry-run');\n const skipConfirm = args.includes('--yes') || args.includes('-y');\n \n // If no issues provided, we'd need to run a scan first\n if (!issues || issues.length === 0) {\n console.error(pc.yellow('No issues provided. Run a scan first:'));\n console.error(pc.dim(' trie scan --fix'));\n return;\n }\n \n // Detect auto-fixable issues\n let fixes = detectAutoFixes(issues);\n \n if (fixes.length === 0) {\n console.error(pc.green('✓ No auto-fixable issues found.'));\n return;\n }\n \n // Filter by config\n fixes = fixes.filter(fix => shouldAutoFix(fix, config));\n \n if (fixes.length === 0) {\n console.error(pc.yellow('Found fixable issues but they are not in allowed categories.'));\n console.error(pc.dim('Allowed categories: ' + config.autoFix.categories.join(', ')));\n return;\n }\n \n // Load actual line content\n fixes = await loadFixContent(fixes);\n \n if (fixes.length === 0) {\n console.error(pc.yellow('Could not load fix content from files.'));\n return;\n }\n \n // Summary\n console.error('');\n console.error(pc.cyan('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));\n console.error(pc.bold('Auto-Fix: Human-in-the-Loop'));\n console.error(pc.cyan('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));\n console.error('');\n console.error(`Found ${pc.bold(fixes.length.toString())} auto-fixable issues:`);\n \n // Group by category\n const byCategory = new Map<string, number>();\n for (const fix of fixes) {\n byCategory.set(fix.category, (byCategory.get(fix.category) || 0) + 1);\n }\n for (const [cat, count] of byCategory) {\n console.error(` • ${cat}: ${count}`);\n }\n console.error('');\n \n if (dryRun) {\n console.error(pc.yellow('[DRY RUN] No changes will be made.'));\n console.error('');\n \n for (let i = 0; i < fixes.length; i++) {\n displayFixPreview(fixes[i]!, i, fixes.length);\n }\n return;\n }\n \n // Always ask for confirmation (human-in-the-loop)\n if (config.autoFix.askFirst && !skipConfirm) {\n console.error(pc.yellow('Trie will ask before applying each fix.'));\n console.error('');\n \n const response = await promptUser(\n `Apply all ${fixes.length} fixes? (y)es / (n)o / (r)eview each: `\n );\n \n if (response === 'n' || response === 'no') {\n console.error(pc.dim('Cancelled.'));\n return;\n }\n \n if (response === 'r' || response === 'review') {\n // Review each fix individually\n let applied = 0;\n let skipped = 0;\n \n for (let i = 0; i < fixes.length; i++) {\n const fix = fixes[i]!;\n displayFixPreview(fix, i, fixes.length);\n \n const answer = await promptUser('Apply this fix? (y/n/q): ');\n \n if (answer === 'q' || answer === 'quit') {\n console.error(pc.dim('Stopped.'));\n break;\n }\n \n if (answer === 'y' || answer === 'yes') {\n const success = await applyAutoFix(fix);\n if (success) {\n console.error(pc.green(`✓ Applied fix to ${fix.file}:${fix.line}`));\n applied++;\n } else {\n console.error(pc.red(`✗ Failed to apply fix`));\n }\n } else {\n console.error(pc.dim('Skipped.'));\n skipped++;\n }\n }\n \n console.error('');\n console.error(pc.cyan('━━━ Summary ━━━'));\n console.error(`Applied: ${pc.green(applied.toString())}`);\n console.error(`Skipped: ${pc.dim(skipped.toString())}`);\n return;\n }\n }\n \n // Apply all fixes\n console.error('');\n console.error(pc.cyan('Applying fixes...'));\n console.error('');\n \n let applied = 0;\n let failed = 0;\n \n for (const fix of fixes) {\n const success = await applyAutoFix(fix);\n if (success) {\n console.error(pc.green(`✓ Applied fix to ${fix.file}:${fix.line}`));\n applied++;\n } else {\n console.error(pc.red(`✗ Failed to apply fix to ${fix.file}:${fix.line}`));\n failed++;\n }\n }\n \n console.error('');\n console.error(pc.cyan('━━━ Complete ━━━'));\n console.error(`Applied: ${pc.green(applied.toString())}`);\n if (failed > 0) {\n console.error(`Failed: ${pc.red(failed.toString())}`);\n }\n}\n\n/**\n * Interactive fix prompt for dashboard\n * Returns true if user wants to fix, false otherwise\n */\nexport async function promptForAutoFix(\n fixes: AutoFixAction[],\n config: { askFirst: boolean }\n): Promise<'all' | 'review' | 'none'> {\n if (fixes.length === 0) return 'none';\n \n console.error('');\n console.error(pc.cyan(`Found ${fixes.length} auto-fixable issues.`));\n \n if (!config.askFirst) {\n return 'all';\n }\n \n const response = await promptUser(\n 'Fix them? (y)es all / (r)eview / (n)o: '\n );\n \n if (response === 'y' || response === 'yes') return 'all';\n if (response === 'r' || response === 'review') return 'review';\n return 'none';\n}\n","/**\n * Auto-Fix Apply - Apply auto-fix actions to files\n * \n * Extracted from auto-fix.ts for reuse by watch mode and other tools\n */\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport type { AutoFixAction } from '../types/autonomy.js';\n\n/**\n * Apply a single fix to a file\n * Returns true if successful, false otherwise\n */\nexport async function applyAutoFix(fix: AutoFixAction): Promise<boolean> {\n try {\n if (!existsSync(fix.file)) {\n return false;\n }\n \n const content = await readFile(fix.file, 'utf-8');\n const lines = content.split('\\n');\n \n if (fix.line === undefined || fix.line < 1 || fix.line > lines.length) {\n return false;\n }\n \n const lineIndex = fix.line - 1;\n \n // Apply the fix based on type\n let newContent: string;\n \n if (fix.type === 'remove-console-log' || \n fix.type === 'remove-debugger' ||\n fix.fixed === '') {\n // Remove the entire line\n lines.splice(lineIndex, 1);\n newContent = lines.join('\\n');\n } else if (fix.type === 'remove-emoji') {\n // Remove emojis from the line\n const emojiPattern = /[\\u{1F300}-\\u{1F9FF}\\u{2600}-\\u{26FF}\\u{2700}-\\u{27BF}]/gu;\n lines[lineIndex] = lines[lineIndex]!.replace(emojiPattern, '');\n newContent = lines.join('\\n');\n } else if (fix.fixed) {\n // Replace the line\n lines[lineIndex] = fix.fixed;\n newContent = lines.join('\\n');\n } else {\n return false;\n }\n \n // Write the file\n await writeFile(fix.file, newContent);\n \n return true;\n \n } catch {\n return false;\n }\n}\n\n/**\n * Apply multiple fixes to files\n * Returns the number of successfully applied fixes\n */\nexport async function applyAutoFixes(fixes: AutoFixAction[]): Promise<number> {\n let applied = 0;\n \n for (const fix of fixes) {\n const success = await applyAutoFix(fix);\n if (success) {\n applied++;\n }\n }\n \n return applied;\n}\n","/**\n * Goal & Hypothesis CLI Commands\n * \n * Allows users to manually add goals and hypotheses while still\n * allowing Trie to auto-generate them.\n * \n * Commands:\n * - trie goal add \"Reduce auth issues by 50%\"\n * - trie goal list\n * - trie goal complete <id>\n * - trie hypothesis add \"Mondays have more bugs\"\n * - trie hypothesis list\n */\n\nimport pc from 'picocolors';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getProjectState, type Goal, type Hypothesis } from '../agent/project-state.js';\nimport { measureInitialGoalValue } from '../agent/goal-validator.js';\n\n// ============================================================================\n// Goal Commands\n// ============================================================================\n\nexport async function handleGoalCommand(args: string[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const projectState = getProjectState(projectPath);\n await projectState.load();\n \n const subcommand = args[0];\n const restArgs = args.slice(1);\n \n switch (subcommand) {\n case 'add':\n case 'create':\n await addGoal(projectState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listGoals(projectState);\n break;\n \n case 'complete':\n case 'done':\n await completeGoal(projectState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteGoal(projectState, restArgs[0]);\n break;\n \n default:\n if (subcommand && !subcommand.startsWith('-')) {\n // Treat as goal description shorthand: trie goal \"reduce bugs\"\n await addGoal(projectState, [subcommand, ...restArgs]);\n } else {\n printGoalHelp();\n }\n }\n}\n\nasync function addGoal(projectState: ReturnType<typeof getProjectState>, args: string[]): Promise<void> {\n const description = args.join(' ').replace(/^[\"']|[\"']$/g, '');\n \n if (!description) {\n console.error(pc.red('Please provide a goal description.'));\n console.error(pc.dim('Example: trie goal add \"Reduce auth issues by 50%\"'));\n return;\n }\n \n // Parse optional flags\n const categoryMatch = description.match(/--category[=\\s](\\w+)/);\n const targetMatch = description.match(/--target[=\\s](\\d+)/);\n const deadlineMatch = description.match(/--deadline[=\\s](\\S+)/);\n \n // Clean description of flags\n let cleanDesc = description\n .replace(/--category[=\\s]\\w+/g, '')\n .replace(/--target[=\\s]\\d+/g, '')\n .replace(/--deadline[=\\s]\\S+/g, '')\n .trim();\n \n // Detect goal type and target from description\n const reductionMatch = cleanDesc.match(/reduce.*?(\\d+)%/i);\n const eliminateMatch = cleanDesc.match(/eliminate|remove all|zero/i);\n const streakMatch = cleanDesc.match(/(\\d+)\\s*days?\\s*(streak|in a row|consecutive)/i);\n \n let goalType: Goal['type'] = 'custom';\n let target = 100;\n let metric = 'progress';\n \n if (reductionMatch && reductionMatch[1]) {\n goalType = 'reduction';\n target = parseInt(reductionMatch[1], 10);\n metric = 'reduction_percent';\n } else if (eliminateMatch) {\n goalType = 'reduction';\n target = 100;\n metric = 'elimination';\n } else if (streakMatch && streakMatch[1]) {\n goalType = 'streak';\n target = parseInt(streakMatch[1], 10);\n metric = 'days_streak';\n }\n \n // Override with explicit flags\n if (targetMatch && targetMatch[1]) {\n target = parseInt(targetMatch[1], 10);\n }\n \n const category = (categoryMatch?.[1] as Goal['category']) || detectCategory(cleanDesc);\n \n // Calculate deadline (default: 14 days)\n const deadline = new Date();\n if (deadlineMatch && deadlineMatch[1]) {\n const days = parseInt(deadlineMatch[1], 10);\n deadline.setDate(deadline.getDate() + (isNaN(days) ? 14 : days));\n } else {\n deadline.setDate(deadline.getDate() + 14);\n }\n \n // Measure initial value based on existing issues\n const workDir = getWorkingDirectory(undefined, true);\n const initialValue = await measureInitialGoalValue(cleanDesc, workDir);\n \n const goal: Goal = {\n id: `goal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n description: cleanDesc,\n type: goalType,\n metric,\n target,\n currentValue: initialValue,\n startValue: initialValue,\n status: 'active',\n autoGenerated: false, // User-created\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n deadline: deadline.toISOString(),\n category,\n };\n \n await projectState.addGoal(goal);\n \n console.error('');\n console.error(pc.green('✓ Goal created'));\n console.error('');\n console.error(pc.bold(cleanDesc));\n console.error(pc.dim(`ID: ${goal.id}`));\n console.error(pc.dim(`Type: ${goalType} | Target: ${target} | Category: ${category}`));\n if (initialValue > 0) {\n console.error(pc.dim(`Starting value: ${initialValue} issues found`));\n }\n console.error(pc.dim(`Deadline: ${deadline.toLocaleDateString()}`));\n console.error('');\n console.error(pc.cyan('Progress will be tracked and you\\'ll be notified when you achieve it!'));\n}\n\nasync function listGoals(projectState: ReturnType<typeof getProjectState>): Promise<void> {\n const goals = projectState.getAllGoals();\n \n if (goals.length === 0) {\n console.error(pc.dim('No goals yet.'));\n console.error(pc.dim('Create one: trie goal add \"Reduce auth issues by 50%\"'));\n return;\n }\n \n console.error('');\n console.error(pc.bold('Goals'));\n console.error('');\n \n const active = goals.filter(g => g.status === 'active');\n const achieved = goals.filter(g => g.status === 'achieved');\n const other = goals.filter(g => g.status !== 'active' && g.status !== 'achieved');\n \n if (active.length > 0) {\n console.error(pc.cyan('Active:'));\n for (const goal of active) {\n const progress = calculateGoalProgress(goal);\n const bar = renderProgressBar(progress);\n const source = goal.autoGenerated ? pc.dim('[auto]') : pc.dim('[manual]');\n console.error(` ${bar} ${goal.description} ${source}`);\n console.error(pc.dim(` ID: ${goal.id} | ${progress}% complete`));\n }\n console.error('');\n }\n \n if (achieved.length > 0) {\n console.error(pc.green('Achieved:'));\n for (const goal of achieved) {\n console.error(` [+] ${goal.description}`);\n }\n console.error('');\n }\n \n if (other.length > 0) {\n console.error(pc.dim('Other:'));\n for (const goal of other) {\n const icon = goal.status === 'failed' ? '[X]' : goal.status === 'paused' ? '[P]' : '•';\n console.error(` ${icon} ${goal.description} (${goal.status})`);\n }\n }\n}\n\nasync function completeGoal(projectState: ReturnType<typeof getProjectState>, goalId: string | undefined): Promise<void> {\n if (!goalId) {\n console.error(pc.red('Please provide a goal ID.'));\n console.error(pc.dim('Run \"trie goal list\" to see IDs.'));\n return;\n }\n \n const goals = projectState.getAllGoals();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const goal = goals.find(g => g.id === goalId || g.id.startsWith(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await projectState.updateGoal(goal.id, {\n status: 'achieved',\n currentValue: goal.target,\n achievedAt: new Date().toISOString(),\n });\n \n console.error('');\n console.error(pc.green('Goal achieved!'));\n console.error(pc.bold(goal.description));\n console.error('');\n}\n\nasync function deleteGoal(projectState: ReturnType<typeof getProjectState>, goalId: string | undefined): Promise<void> {\n if (!goalId) {\n console.error(pc.red('Please provide a goal ID.'));\n return;\n }\n \n const goals = projectState.getAllGoals();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const goal = goals.find(g => g.id === goalId || g.id.startsWith(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await projectState.updateGoal(goal.id, { status: 'rejected' });\n console.error(pc.dim(`Removed goal: ${goal.description}`));\n}\n\n/**\n * Calculate goal progress correctly for both increase and reduction goals.\n * For reduction goals (startValue > target): progress = (startValue - currentValue) / (startValue - target)\n * For increase goals (startValue <= target): progress = currentValue / target\n */\nfunction calculateGoalProgress(goal: { startValue?: number | undefined; currentValue: number; target: number }): number {\n if (goal.target <= 0) return 0;\n \n const startValue = goal.startValue ?? goal.currentValue;\n \n // Reduction goal: startValue > target (e.g., reduce from 20 to 10)\n if (startValue > goal.target) {\n const totalReduction = startValue - goal.target;\n // Guard against division by zero when startValue === target\n if (totalReduction === 0) return 100; // Already at target\n const actualReduction = startValue - goal.currentValue;\n return Math.round((actualReduction / totalReduction) * 100);\n }\n \n // Increase goal: progress toward target\n return Math.round((goal.currentValue / goal.target) * 100);\n}\n\nfunction renderProgressBar(percent: number): string {\n const width = 10;\n const clamped = Math.max(0, Math.min(100, percent)); // Clamp to 0-100\n const filled = Math.round((clamped / 100) * width);\n const empty = width - filled;\n return `[${pc.green('█'.repeat(filled))}${pc.gray('░'.repeat(empty))}]`;\n}\n\nfunction detectCategory(description: string): Goal['category'] {\n const lower = description.toLowerCase();\n if (/security|auth|password|token|xss|sql|inject/i.test(lower)) return 'security';\n if (/quality|bug|issue|error|fix/i.test(lower)) return 'quality';\n if (/performance|speed|fast|slow|latency/i.test(lower)) return 'performance';\n if (/coverage|test|spec/i.test(lower)) return 'coverage';\n return 'general';\n}\n\nfunction printGoalHelp(): void {\n console.error('');\n console.error(pc.bold('trie goal - Manage guardian goals'));\n console.error('');\n console.error(pc.cyan('Usage:'));\n console.error(' trie goal add \"Reduce auth issues by 50%\"');\n console.error(' trie goal list');\n console.error(' trie goal complete <id>');\n console.error(' trie goal delete <id>');\n console.error('');\n console.error(pc.cyan('Options for add:'));\n console.error(' --category=security|quality|performance|coverage|general');\n console.error(' --target=<number>');\n console.error(' --deadline=<days>');\n console.error('');\n console.error(pc.cyan('Examples:'));\n console.error(' trie goal add \"Eliminate all critical security issues\"');\n console.error(' trie goal add \"7 days streak of clean builds\"');\n console.error(' trie goal add \"Reduce test flakiness by 80%\" --category=quality');\n console.error('');\n}\n\n// ============================================================================\n// Hypothesis Commands\n// ============================================================================\n\nexport async function handleHypothesisCommand(args: string[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const projectState = getProjectState(projectPath);\n await projectState.load();\n \n const subcommand = args[0];\n const restArgs = args.slice(1);\n \n switch (subcommand) {\n case 'add':\n case 'create':\n await addHypothesis(projectState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listHypotheses(projectState);\n break;\n \n case 'validate':\n await validateHypothesis(projectState, restArgs[0]);\n break;\n \n case 'invalidate':\n await invalidateHypothesis(projectState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteHypothesis(projectState, restArgs[0]);\n break;\n \n default:\n if (subcommand && !subcommand.startsWith('-')) {\n // Treat as hypothesis statement shorthand\n await addHypothesis(projectState, [subcommand, ...restArgs]);\n } else {\n printHypothesisHelp();\n }\n }\n}\n\nasync function addHypothesis(projectState: ReturnType<typeof getProjectState>, args: string[]): Promise<void> {\n const statement = args.join(' ').replace(/^[\"']|[\"']$/g, '');\n \n if (!statement) {\n console.error(pc.red('Please provide a hypothesis statement.'));\n console.error(pc.dim('Example: trie hypothesis add \"Mondays have more bugs than Fridays\"'));\n return;\n }\n \n // Parse optional flags\n const categoryMatch = statement.match(/--category[=\\s](\\w+)/);\n const testMatch = statement.match(/--test[=\\s][\"']([^\"']+)[\"']/);\n \n let cleanStatement = statement\n .replace(/--category[=\\s]\\w+/g, '')\n .replace(/--test[=\\s][\"'][^\"']+[\"']/g, '')\n .trim();\n \n const category = (categoryMatch?.[1] as Hypothesis['category']) || detectHypothesisCategory(cleanStatement);\n const testCriteria = testMatch?.[1] || generateTestCriteria(cleanStatement);\n \n const hypothesis: Hypothesis = {\n id: `hypo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n statement: cleanStatement,\n confidence: 0, // No evidence yet\n status: 'testing',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria,\n category,\n autoGenerated: false,\n };\n \n await projectState.addHypothesis(hypothesis);\n \n console.error('');\n console.error(pc.green('✓ Hypothesis created'));\n console.error('');\n console.error(pc.bold(`\"${cleanStatement}\"`));\n console.error(pc.dim(`ID: ${hypothesis.id}`));\n console.error(pc.dim(`Status: testing | Confidence: untested | Category: ${category}`));\n console.error('');\n console.error(pc.cyan('The agent will collect evidence and update confidence over time.'));\n console.error(pc.dim(`Test criteria: ${testCriteria}`));\n}\n\nasync function listHypotheses(projectState: ReturnType<typeof getProjectState>): Promise<void> {\n const hypotheses = projectState.getAllHypotheses();\n \n if (hypotheses.length === 0) {\n console.error(pc.dim('No hypotheses yet.'));\n console.error(pc.dim('Create one: trie hypothesis add \"Mondays have more bugs\"'));\n return;\n }\n \n console.error('');\n console.error(pc.bold('Hypotheses'));\n console.error('');\n \n const testing = hypotheses.filter(h => h.status === 'testing');\n const validated = hypotheses.filter(h => h.status === 'validated');\n const invalidated = hypotheses.filter(h => h.status === 'invalidated');\n \n if (testing.length > 0) {\n console.error(pc.cyan('Testing:'));\n for (const hypo of testing) {\n const conf = Math.round(hypo.confidence * 100);\n const confColor = conf >= 70 ? pc.green : conf >= 40 ? pc.yellow : pc.red;\n console.error(` [?] \"${hypo.statement}\" ${confColor(`(${conf}% confidence)`)}`);\n console.error(pc.dim(` ID: ${hypo.id} | Evidence: ${hypo.evidence.length} points`));\n }\n console.error('');\n }\n \n if (validated.length > 0) {\n console.error(pc.green('Validated:'));\n for (const hypo of validated) {\n console.error(` [+] \"${hypo.statement}\" (${Math.round(hypo.confidence * 100)}%)`);\n }\n console.error('');\n }\n \n if (invalidated.length > 0) {\n console.error(pc.red('Invalidated:'));\n for (const hypo of invalidated) {\n console.error(` [X] \"${hypo.statement}\"`);\n }\n }\n}\n\nasync function validateHypothesis(projectState: ReturnType<typeof getProjectState>, hypoId: string | undefined): Promise<void> {\n if (!hypoId) {\n console.error(pc.red('Please provide a hypothesis ID.'));\n return;\n }\n \n const hypotheses = projectState.getAllHypotheses();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.startsWith(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await projectState.updateHypothesis(hypo.id, {\n status: 'validated',\n confidence: 0.9,\n validatedAt: new Date().toISOString(),\n });\n \n console.error(pc.green(`Hypothesis validated: \"${hypo.statement}\"`));\n}\n\nasync function invalidateHypothesis(projectState: ReturnType<typeof getProjectState>, hypoId: string | undefined): Promise<void> {\n if (!hypoId) {\n console.error(pc.red('Please provide a hypothesis ID.'));\n return;\n }\n \n const hypotheses = projectState.getAllHypotheses();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.startsWith(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await projectState.updateHypothesis(hypo.id, {\n status: 'invalidated',\n confidence: 0.1,\n });\n \n console.error(pc.red(`Hypothesis invalidated: \"${hypo.statement}\"`));\n}\n\nasync function deleteHypothesis(projectState: ReturnType<typeof getProjectState>, hypoId: string | undefined): Promise<void> {\n if (!hypoId) {\n console.error(pc.red('Please provide a hypothesis ID.'));\n return;\n }\n \n const hypotheses = projectState.getAllHypotheses();\n // Match exact ID or ID prefix (startsWith is safer than includes to avoid false positives)\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.startsWith(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await projectState.updateHypothesis(hypo.id, { status: 'retired' });\n console.error(pc.dim(`Removed hypothesis: \"${hypo.statement}\"`));\n}\n\nfunction detectHypothesisCategory(statement: string): Hypothesis['category'] {\n const lower = statement.toLowerCase();\n if (/monday|friday|weekend|morning|night|time|day|hour/i.test(lower)) return 'timing';\n if (/pattern|recurring|always|never|consistently/i.test(lower)) return 'pattern';\n if (/team|developer|engineer|review/i.test(lower)) return 'team';\n if (/code|file|function|class|module|refactor/i.test(lower)) return 'code';\n return 'general';\n}\n\nfunction generateTestCriteria(statement: string): string {\n const lower = statement.toLowerCase();\n \n if (lower.includes('monday')) {\n return 'Compare Monday issue counts to weekly average';\n }\n if (lower.includes('friday')) {\n return 'Compare Friday issue introduction rate to other days';\n }\n if (lower.includes('more bug') || lower.includes('more issue')) {\n return 'Compare issue counts between conditions over time';\n }\n if (lower.includes('causes') || lower.includes('leads to')) {\n return 'Track correlation between trigger and outcome events';\n }\n \n return 'Collect supporting and contradicting evidence from scans';\n}\n\nfunction printHypothesisHelp(): void {\n console.error('');\n console.error(pc.bold('trie hypothesis - Manage project hypotheses'));\n console.error('');\n console.error(pc.cyan('Usage:'));\n console.error(' trie hypothesis add \"Mondays have more bugs than Fridays\"');\n console.error(' trie hypothesis list');\n console.error(' trie hypothesis validate <id>');\n console.error(' trie hypothesis invalidate <id>');\n console.error(' trie hypothesis delete <id>');\n console.error('');\n console.error(pc.cyan('Options for add:'));\n console.error(' --category=timing|pattern|team|code|general');\n console.error(' --test=\"<test criteria>\"');\n console.error('');\n console.error(pc.cyan('Examples:'));\n console.error(' trie hypothesis add \"Code reviews reduce bug rate\"');\n console.error(' trie hypothesis add \"Auth module has highest churn\"');\n console.error(' trie hypothesis add \"Deploy Fridays cause weekend incidents\"');\n console.error('');\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData } from '../context/nodes.js';\nimport { exportToJson } from '../context/sync.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport type { RiskLevel } from '../types/index.js';\n\nfunction escalateRisk(level: RiskLevel): RiskLevel {\n if (level === 'low') return 'medium';\n if (level === 'medium') return 'high';\n if (level === 'high') return 'critical';\n return 'critical';\n}\n\nfunction extractFilePathsFromDescription(description: string): string[] {\n const matches = description.match(/[\\\\w./_-]+\\\\.(ts|tsx|js|jsx|mjs|cjs)/gi);\n if (!matches) return [];\n const unique = new Set<string>();\n matches.forEach((m) => unique.add(m.replace(/^\\.\\/+/, '')));\n return Array.from(unique);\n}\n\nexport async function handleTellCommand(args: string[]): Promise<void> {\n try {\n const projectPath = getWorkingDirectory(undefined, true);\n const description = args.join(' ').trim();\n if (!description) {\n console.log('Usage: trie tell \"<incident description>\"');\n return;\n }\n\n const graph = new ContextGraph(projectPath);\n const now = new Date().toISOString();\n const change = (await graph.getRecentChanges(1))[0];\n\n const incident = await graph.addNode('incident', {\n description,\n severity: 'major',\n affectedUsers: null,\n duration: null,\n timestamp: now,\n resolved: false,\n resolution: null,\n fixChangeId: change?.id ?? null,\n reportedVia: 'manual'\n });\n\n const linkedFiles = new Set<string>();\n\n if (change) {\n await graph.addEdge(change.id, incident.id, 'leadTo');\n await graph.addEdge(incident.id, change.id, 'causedBy');\n\n for (const filePath of change.data.files) {\n linkedFiles.add(filePath);\n const fileNode = await graph.getNode('file', path.resolve(projectPath, filePath));\n if (fileNode) {\n const data = fileNode.data as FileNodeData;\n await graph.updateNode('file', fileNode.id, {\n incidentCount: (data.incidentCount ?? 0) + 1,\n riskLevel: escalateRisk(data.riskLevel)\n });\n }\n }\n }\n\n // Also extract file paths from the incident description\n const mentionedFiles = extractFilePathsFromDescription(description);\n mentionedFiles.forEach((f) => linkedFiles.add(f));\n\n // Update trie-backed incident index for O(m) lookups\n const incidentIndex = new IncidentIndex(graph, projectPath);\n incidentIndex.addIncidentToTrie(incident, Array.from(linkedFiles));\n\n await exportToJson(graph);\n\n console.log('Incident recorded.');\n if (change) {\n console.log(`Linked to change: ${change.id}`);\n } else {\n console.log('No recent change found; incident recorded without linkage.');\n }\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { importFromJson } from '../context/sync.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport path from 'node:path';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nasync function removeOrphanEdges(graph: ContextGraph): Promise<number> {\n const nodes = await graph.listNodes();\n const nodeIds = new Set(nodes.map((n) => n.id));\n const edges = await graph.listEdges();\n let removed = 0;\n\n for (const edge of edges) {\n if (!nodeIds.has(edge.from_id) || !nodeIds.has(edge.to_id)) {\n await graph.deleteEdge(edge.id);\n removed++;\n }\n }\n\n return removed;\n}\n\nexport async function handleReconcileCommand(args: string[]): Promise<void> {\n try {\n const projectPath = getWorkingDirectory(undefined, true);\n const source = args.find((a) => a.startsWith('--from='))?.replace('--from=', '') ??\n path.join(getTrieDirectory(projectPath), 'context.json');\n\n const graph = new ContextGraph(projectPath);\n await importFromJson(graph, '', source);\n\n const removed = await removeOrphanEdges(graph);\n console.log(`Reconciled context from ${source}. Removed ${removed} orphaned edges.`);\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\n\nexport async function handleQuietCommand(): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const quietPath = path.join(getTrieDirectory(projectPath), 'quiet.json');\n\n const until = new Date(Date.now() + 60 * 60 * 1000).toISOString(); // 1 hour\n const payload = { until };\n\n try {\n const dir = path.dirname(quietPath);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(quietPath, JSON.stringify(payload, null, 2));\n console.log('🔕 Nudges snoozed for 1 hour.');\n } catch (error) {\n console.error('Failed to set quiet mode:', error);\n }\n}\n","/**\n * CI/CD Setup Command\n * \n * Generates GitHub Actions workflow with memory caching\n * for cross-run learning and pattern recognition.\n */\n\nimport { writeFileSync, existsSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport pc from 'picocolors';\n\nconst WORKFLOW_TEMPLATE = `# Trie Security Scan with Memory Persistence\n# Generated by: trie ci\n# \n# This workflow scans your code and caches Trie's memory\n# across runs for cross-run learning and pattern recognition.\n\nname: Trie Security Scan\n\non:\n push:\n branches: [main, master, develop]\n pull_request:\n branches: [main, master]\n\njobs:\n security-scan:\n runs-on: ubuntu-latest\n permissions:\n security-events: write\n pull-requests: write\n contents: read\n\n steps:\n - name: Checkout\n uses: actions/checkout@v4\n\n # Restore Trie memory from previous runs\n # This enables cross-run learning and pattern recognition\n - name: Restore Trie Memory\n uses: actions/cache@v4\n with:\n path: |\n .trie/memory\n .trie/context\n .trie/summaries\n key: trie-memory-\\${{ github.repository }}-\\${{ github.ref_name }}\n restore-keys: |\n trie-memory-\\${{ github.repository }}-\n trie-memory-\n\n - name: Setup Node.js\n uses: actions/setup-node@v4\n with:\n node-version: '20'\n\n - name: Install Trie\n run: npm install -g @triedotdev/mcp\n\n - name: Run Security Scan\n run: |\n trie scan --format sarif --output trie-results.sarif\n env:\n ANTHROPIC_API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n\n - name: Upload SARIF Results\n uses: github/codeql-action/upload-sarif@v3\n if: always()\n with:\n sarif_file: trie-results.sarif\n continue-on-error: true\n\n # Memory is automatically saved by cache action on job completion\n`;\n\nconst WORKFLOW_MINIMAL = `# Trie Security Scan (Minimal)\n# Generated by: trie ci --minimal\n\nname: Trie Scan\n\non: [push, pull_request]\n\njobs:\n scan:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n \n # Cache Trie memory for cross-run learning\n - uses: actions/cache@v4\n with:\n path: .trie/memory\n key: trie-memory-\\${{ github.repository }}\n \n - run: npm install -g @triedotdev/mcp\n - run: trie scan\n env:\n ANTHROPIC_API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n`;\n\nexport function handleCISetupCommand(args: string[]): void {\n const workDir = getWorkingDirectory(undefined, true);\n const workflowsDir = join(workDir, '.github', 'workflows');\n const workflowPath = join(workflowsDir, 'trie-scan.yml');\n \n // Parse args\n const isMinimal = args.includes('--minimal') || args.includes('-m');\n const isDryRun = args.includes('--dry-run') || args.includes('-n');\n const showHelp = args.includes('--help') || args.includes('-h');\n \n if (showHelp) {\n console.log(`\n${pc.bold('trie ci')} - Generate GitHub Actions workflow with memory caching\n\n${pc.bold('USAGE:')}\n trie ci [options]\n\n${pc.bold('OPTIONS:')}\n --minimal, -m Generate minimal workflow (simpler, fewer features)\n --dry-run, -n Preview workflow without creating files\n --help, -h Show this help\n\n${pc.bold('WHAT IT DOES:')}\n Creates .github/workflows/trie-scan.yml that:\n \n 1. ${pc.green('Caches Trie memory')} - Patterns and fixes persist across runs\n 2. ${pc.green('Enables learning')} - Trie remembers issues from previous PRs\n 3. ${pc.green('Tracks patterns')} - Detects recurring issues across your codebase\n 4. ${pc.green('SARIF upload')} - Results appear in GitHub Security tab\n\n${pc.bold('MEMORY BENEFITS:')}\n • \"This issue was introduced 3 PRs ago\"\n • \"Similar issue was fixed in PR #42\"\n • \"This pattern keeps recurring in auth code\"\n • Trend tracking: improving, stable, or declining\n\n${pc.bold('EXAMPLES:')}\n trie ci # Generate full workflow\n trie ci --minimal # Generate simple workflow\n trie ci --dry-run # Preview without writing\n\n${pc.bold('REQUIRED SECRETS:')}\n ANTHROPIC_API_KEY Your Anthropic API key (add in GitHub repo settings)\n`);\n return;\n }\n \n const template = isMinimal ? WORKFLOW_MINIMAL : WORKFLOW_TEMPLATE;\n \n if (isDryRun) {\n console.log(pc.bold('\\nWorkflow Preview:\\n'));\n console.log(pc.dim('─'.repeat(60)));\n console.log(template);\n console.log(pc.dim('─'.repeat(60)));\n console.log(pc.dim('\\nRun without --dry-run to create the file.'));\n return;\n }\n \n // Check if workflow already exists\n if (existsSync(workflowPath)) {\n console.log(pc.yellow('Workflow already exists: .github/workflows/trie-scan.yml'));\n console.log(pc.dim(' Run with --dry-run to preview what would be written.'));\n console.log(pc.dim(' Delete the existing file to regenerate.'));\n return;\n }\n \n // Create directories if needed\n if (!existsSync(workflowsDir)) {\n mkdirSync(workflowsDir, { recursive: true });\n }\n \n // Write workflow\n writeFileSync(workflowPath, template);\n \n console.log(pc.green('✓') + ' Created .github/workflows/trie-scan.yml');\n console.log('');\n console.log(pc.bold('Next steps:'));\n console.log('');\n console.log(' 1. Add your Anthropic API key to GitHub Secrets:');\n console.log(pc.dim(' Settings → Secrets → Actions → New repository secret'));\n console.log(pc.dim(' Name: ANTHROPIC_API_KEY'));\n console.log('');\n console.log(' 2. Commit and push:');\n console.log(pc.dim(' git add .github/workflows/trie-scan.yml'));\n console.log(pc.dim(' git commit -m \"Add Trie security scan with memory\"'));\n console.log(pc.dim(' git push'));\n console.log('');\n console.log(pc.bold('Memory caching benefits:'));\n console.log(pc.dim(' • Trie learns from past scans'));\n console.log(pc.dim(' • Tracks issue trends over time'));\n console.log(pc.dim(' • Remembers when issues were introduced'));\n console.log(pc.dim(' • Recognizes recurring patterns'));\n}\n","/**\n * Audit CLI Command Handler\n * \n * View security audit logs for skill operations\n */\n\nimport { getRecentAuditLogs, getSkillAuditLogs, getAuditStatistics, formatAuditLog } from '../skills/audit-logger.js';\n\nexport async function handleAuditCommand(args: string[]): Promise<void> {\n const [cmd, ...rest] = args;\n\n switch (cmd) {\n case 'logs':\n case 'list': {\n const limit = rest[0] ? parseInt(rest[0], 10) : 20;\n const logs = await getRecentAuditLogs(limit);\n \n if (logs.length === 0) {\n console.log('\\nNo audit logs found.');\n console.log('Audit logs are created when skills are executed during scans.\\n');\n return;\n }\n \n console.log(`\\nRecent Skill Executions (last ${logs.length}):\\n`);\n \n for (const log of logs) {\n console.log(formatAuditLog(log));\n console.log('');\n }\n \n break;\n }\n \n case 'skill': {\n if (!rest[0]) {\n console.log('Usage: trie audit skill <skill-name>');\n console.log('');\n console.log('View audit logs for a specific skill.');\n return;\n }\n \n const skillName = rest[0];\n const logs = await getSkillAuditLogs(skillName);\n \n if (logs.length === 0) {\n console.log(`\\nNo audit logs found for skill: ${skillName}\\n`);\n return;\n }\n \n console.log(`\\nAudit Logs for ${skillName} (${logs.length} executions):\\n`);\n \n for (const log of logs) {\n console.log(formatAuditLog(log));\n console.log('');\n }\n \n break;\n }\n \n case 'stats':\n case 'statistics': {\n const stats = await getAuditStatistics();\n \n console.log('\\n📊 Audit Statistics\\n');\n console.log(`Total executions: ${stats.totalExecutions}`);\n console.log(` ✅ Successful: ${stats.successfulExecutions}`);\n console.log(` ❌ Failed: ${stats.failedExecutions}`);\n console.log('');\n console.log(`Unique skills executed: ${stats.uniqueSkills}`);\n console.log('');\n console.log(`Commands executed: ${stats.totalCommands}`);\n if (stats.blockedCommands > 0) {\n console.log(` ⚠️ Blocked: ${stats.blockedCommands}`);\n }\n console.log('');\n console.log(`Network calls: ${stats.totalNetworkCalls}`);\n if (stats.blockedNetworkCalls > 0) {\n console.log(` ⚠️ Blocked: ${stats.blockedNetworkCalls}`);\n }\n console.log('');\n \n if (stats.blockedCommands > 0 || stats.blockedNetworkCalls > 0) {\n console.log('⚠️ Some operations were blocked by security policies.');\n console.log('Run \"trie audit logs\" to see details.\\n');\n }\n \n break;\n }\n \n default: {\n console.log(`\nAudit - View security audit logs\n\nTrie logs all skill operations for security auditing. View what\nskills have executed, what commands they ran, and any blocked operations.\n\nCommands:\n trie audit logs [count] Show recent audit logs (default: 20)\n trie audit skill <name> Show logs for a specific skill\n trie audit stats Show audit statistics\n\nExamples:\n trie audit logs 50 Show last 50 executions\n trie audit skill security Show all executions of security skill\n trie audit stats View overall statistics\n\nAudit logs are stored in .trie/audit/ and include:\n • Skill name and source\n • Commands executed\n • Network calls made\n • Files accessed/modified\n • Any blocked operations\n `);\n }\n }\n}\n","import { loadConfig, saveConfig } from '../config/loader.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { LinearIngester } from '../ingest/linear-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function handleLinearCommand(args: string[]): Promise<void> {\n try {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n\n if (subcommand === 'auth') {\n const apiKey = args[1];\n if (!apiKey) {\n console.log('Usage: trie linear auth <your-linear-api-key>');\n return;\n }\n\n const config = await loadConfig();\n if (!config.apiKeys) {\n config.apiKeys = {};\n }\n (config.apiKeys as any).linear = apiKey;\n\n await saveConfig(config);\n console.log('Linear API key saved successfully.');\n return;\n }\n\n if (subcommand === 'sync') {\n const graph = new ContextGraph(workDir);\n const ingester = new LinearIngester(workDir, graph);\n \n console.log('Syncing Linear tickets...');\n await ingester.syncTickets();\n console.log('Linear tickets synced successfully.');\n return;\n }\n\n console.log('Usage:');\n console.log(' trie linear auth <api-key> Save Linear API key');\n console.log(' trie linear sync Sync active tickets');\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { GotchaPredictor } from '../agent/gotcha-predictor.js';\nimport { getStorage } from '../storage/tiered-storage.js';\nimport type { Gotcha } from '../types/signal.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { getStagedChanges, getUncommittedChanges } from '../agent/git.js';\nimport picocolors from 'picocolors';\n\nexport async function handleGotchaCommand(): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const predictor = new GotchaPredictor(workDir, graph);\n\n // Default: predict for current changes\n console.log('Analyzing current changes for \"gotchas\"...');\n \n const staged = await getStagedChanges(workDir);\n const uncommitted = await getUncommittedChanges(workDir);\n const allChanges = [...staged, ...uncommitted].map(c => c.path);\n const uniqueFiles = Array.from(new Set(allChanges));\n\n if (uniqueFiles.length === 0) {\n console.log('No changes detected to analyze.');\n return;\n }\n\n const gotchas = await predictor.predictGotchas(uniqueFiles);\n\n if (gotchas.length === 0) {\n console.log(picocolors.green('✓ No \"gotchas\" predicted for your current changes.'));\n return;\n }\n\n console.log(picocolors.yellow(`\\nFound ${gotchas.length} potential \"gotchas\":\\n`));\n\n // Store gotchas in ledger for Ledger view\n const storage = getStorage(workDir);\n await storage.initialize();\n const primaryFile = uniqueFiles[0];\n for (const gotcha of gotchas) {\n const ledgerGotcha: Gotcha = {\n id: gotcha.id,\n message: gotcha.message,\n confidence: gotcha.confidence,\n riskLevel: gotcha.riskLevel,\n recommendation: gotcha.recommendation,\n ...(primaryFile && { file: primaryFile }),\n timestamp: new Date().toISOString(),\n ...(gotcha.precedentId && { precedentId: gotcha.precedentId }),\n tags: gotcha.evidence.matchingPatterns,\n evidence: gotcha.evidence,\n resolved: false,\n };\n await storage.storeGotcha(ledgerGotcha);\n }\n\n for (const gotcha of gotchas) {\n const color = gotcha.riskLevel === 'critical' ? picocolors.red : \n gotcha.riskLevel === 'high' ? picocolors.yellow : \n picocolors.blue;\n\n console.log(color(`[${gotcha.riskLevel.toUpperCase()}] ${gotcha.message}`));\n \n const explanation = await predictor.synthesizeGotchaExplanation(gotcha);\n if (explanation !== gotcha.message) {\n console.log(picocolors.dim(` ${explanation}`));\n }\n\n console.log(picocolors.cyan(` 💡 Recommendation: ${gotcha.recommendation}`));\n console.log('');\n }\n\n console.log(picocolors.dim(`Stored ${gotchas.length} gotcha(s) in Ledger. View in: trie watch → Ledger tab`));\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { LearningEngine } from '../agent/learning-engine.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { getStagedChanges } from '../agent/git.js';\nimport picocolors from 'picocolors';\n\nexport async function handleLearnCommand(args: string[]): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const engine = new LearningEngine(workDir);\n\n const firstArg = args[0]?.toLowerCase();\n\n // 1. trie learn ok [note]\n if (firstArg === 'ok' || firstArg === 'good') {\n const note = args.slice(1).join(' ');\n const staged = await getStagedChanges(workDir);\n const files = staged.map(s => s.path);\n \n await engine.learn({ \n manualFeedback: { helpful: true, files, note } \n });\n \n console.log(picocolors.green('👍 Learned that this pattern is good.'));\n if (files.length > 0) {\n console.log(picocolors.dim(` Linked to: ${files.join(', ')}`));\n }\n return;\n }\n\n // 2. trie learn bad [note]\n if (firstArg === 'bad' || firstArg === 'wrong') {\n const note = args.slice(1).join(' ');\n const staged = await getStagedChanges(workDir);\n const files = staged.map(s => s.path);\n\n await engine.learn({ \n manualFeedback: { helpful: false, files, note } \n });\n\n console.log(picocolors.yellow('👎 Learned that this pattern is problematic.'));\n if (files.length > 0) {\n console.log(picocolors.dim(` Linked to: ${files.join(', ')}`));\n }\n return;\n }\n\n // 3. trie learn (default: implicit scan)\n console.log(picocolors.cyan('Scanning history for implicit failure signals (reverts/fixes)...'));\n const results = await engine.learn({ limit: 50 });\n const implicit = results.find(r => r.source === 'git-history');\n \n console.log(picocolors.green(`✓ Learned ${implicit?.learned ?? 0} new cases from your git history.`));\n console.log(picocolors.dim(' Trie will now use these precedents to predict future gotchas.'));\n\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","/**\n * Pattern Management CLI\n * \n * Smart pattern saving that captures:\n * A) File structure/architecture patterns\n * B) Code patterns/fixes that worked\n * C) Detection patterns (scout rules)\n */\n\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { readFile, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { basename } from 'path';\nimport picocolors from 'picocolors';\nimport {\n createSavedPattern,\n loadSavedPatterns,\n savePatternToProject,\n savePatternsToProject,\n type SavedPattern,\n} from '../patterns/saved-patterns.js';\n\nexport type { SavedPattern };\n\nexport async function handlePatternsCommand(args: string[]): Promise<void> {\n const subcommand = args[0]?.toLowerCase();\n const workDir = getWorkingDirectory(undefined, true);\n \n try {\n switch (subcommand) {\n case 'save':\n await handleSavePattern(args.slice(1), workDir);\n break;\n case 'list':\n await handleListPatterns(args.slice(1), workDir);\n break;\n case 'export':\n await handleExportPatterns(args.slice(1), workDir);\n break;\n case 'import':\n await handleImportPatterns(args.slice(1), workDir);\n break;\n case 'validate':\n await handleValidatePattern(args.slice(1), workDir);\n break;\n default:\n showPatternsHelp();\n }\n } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(picocolors.red(`Error: ${friendly.userMessage}`));\n process.exit(1);\n }\n}\n\nasync function handleSavePattern(args: string[], workDir: string): Promise<void> {\n const target = args[0]; // file path, code pattern, or scout name\n const note = args.slice(1).join(' ') || undefined;\n \n if (!target) {\n console.error(picocolors.red('Usage: trie patterns save <target> [note]'));\n console.log(picocolors.dim('\\nExamples:'));\n console.log(' trie patterns save \"path/to/file.ts\" \"Short note about why it worked\"');\n console.log(' trie patterns save \"path/*\" \"Folder structure that worked well\"');\n console.log(' trie patterns save security \"Scout that caught issues early\"');\n process.exit(1);\n }\n \n const savedPattern = await createSavedPattern(target, note, workDir);\n \n // Save to project's saved patterns\n await savePatternToProject(savedPattern, workDir);\n \n console.log(picocolors.green(`✓ Pattern saved: ${target}`));\n if (note) {\n console.log(picocolors.dim(` Note: ${note}`));\n }\n console.log(picocolors.dim(` Type: ${savedPattern.type}`));\n console.log(picocolors.dim(` Export with: trie patterns export`));\n}\n\nasync function handleListPatterns(args: string[], workDir: string): Promise<void> {\n const filter = args[0]?.toLowerCase();\n const patterns = await loadSavedPatterns(workDir);\n \n let filtered = patterns;\n if (filter === 'validated' || filter === 'saved') {\n filtered = patterns.filter(p => filter === 'validated' ? p.validated : true);\n }\n \n if (filtered.length === 0) {\n console.log(picocolors.yellow('No saved patterns found.'));\n console.log(picocolors.dim('Save patterns with: trie patterns save <target> [note]'));\n return;\n }\n \n console.log(picocolors.bold(`\\n📋 Saved Patterns (${filtered.length})\\n`));\n \n for (const pattern of filtered) {\n const typeEmoji = {\n 'file-structure': '📁',\n 'code-pattern': '💻',\n 'detection-rule': '🔍',\n }[pattern.type] || '📌';\n \n console.log(`${typeEmoji} ${picocolors.bold(pattern.name)}`);\n console.log(` Type: ${pattern.type}`);\n if (pattern.description) {\n console.log(` ${picocolors.dim(pattern.description)}`);\n }\n if (pattern.validated) {\n console.log(` ${picocolors.green('✓ Validated')}`);\n if (pattern.validationNotes) {\n console.log(` ${picocolors.dim(pattern.validationNotes)}`);\n }\n }\n console.log(` Projects: ${pattern.projects.join(', ')}`);\n console.log('');\n }\n}\n\nasync function handleExportPatterns(args: string[], workDir: string): Promise<void> {\n const outputPath = args[0] || 'trie-patterns.json';\n const filter = args[1]?.toLowerCase();\n \n let patterns = await loadSavedPatterns(workDir);\n \n if (filter === 'validated' || filter === 'saved') {\n patterns = patterns.filter(p => filter === 'validated' ? p.validated : true);\n }\n \n if (patterns.length === 0) {\n console.error(picocolors.yellow('No patterns to export.'));\n return;\n }\n \n const exportData = {\n version: '1.0',\n exportedAt: new Date().toISOString(),\n exportedFrom: basename(workDir),\n patterns,\n };\n \n await writeFile(outputPath, JSON.stringify(exportData, null, 2));\n \n console.log(picocolors.green(`✓ Exported ${patterns.length} patterns to ${outputPath}`));\n console.log(picocolors.dim(` Import to another project with: trie patterns import ${outputPath}`));\n}\n\nasync function handleImportPatterns(args: string[], workDir: string): Promise<void> {\n const inputPath = args[0];\n \n if (!inputPath) {\n console.error(picocolors.red('Usage: trie patterns import <path-to-patterns.json>'));\n process.exit(1);\n }\n \n if (!existsSync(inputPath)) {\n console.error(picocolors.red(`File not found: ${inputPath}`));\n process.exit(1);\n }\n \n const content = await readFile(inputPath, 'utf-8');\n const importData = JSON.parse(content);\n \n if (!importData.patterns || !Array.isArray(importData.patterns)) {\n console.error(picocolors.red('Invalid pattern file format.'));\n process.exit(1);\n }\n \n const existingPatterns = await loadSavedPatterns(workDir);\n const projectName = basename(workDir);\n let imported = 0;\n let skipped = 0;\n \n for (const pattern of importData.patterns) {\n const existing = existingPatterns.find(p => p.id === pattern.id);\n if (existing) {\n // Update existing pattern\n if (!existing.projects.includes(projectName)) {\n existing.projects.push(projectName);\n }\n existing.occurrences++;\n skipped++;\n } else {\n // Add new pattern\n const newPattern: SavedPattern = {\n ...pattern,\n projects: [...pattern.projects, projectName],\n savedBy: importData.exportedFrom || 'unknown',\n };\n existingPatterns.push(newPattern);\n imported++;\n }\n }\n \n await savePatternsToProject(existingPatterns, workDir);\n \n console.log(picocolors.green(`✓ Imported ${imported} new patterns`));\n if (skipped > 0) {\n console.log(picocolors.dim(` Updated ${skipped} existing patterns`));\n }\n console.log(picocolors.dim(` Total patterns: ${existingPatterns.length}`));\n}\n\nasync function handleValidatePattern(args: string[], workDir: string): Promise<void> {\n const patternId = args[0];\n const note = args.slice(1).join(' ') || 'Validated - worked well';\n \n if (!patternId) {\n console.error(picocolors.red('Usage: trie patterns validate <pattern-id> [note]'));\n process.exit(1);\n }\n \n const patterns = await loadSavedPatterns(workDir);\n const pattern = patterns.find(p => p.id === patternId || p.name === patternId);\n \n if (!pattern) {\n console.error(picocolors.red(`Pattern not found: ${patternId}`));\n console.log(picocolors.dim('List patterns with: trie patterns list'));\n process.exit(1);\n }\n \n pattern.validated = true;\n pattern.validationNotes = note;\n \n await savePatternsToProject(patterns, workDir);\n \n console.log(picocolors.green(`✓ Pattern validated: ${pattern.name}`));\n console.log(picocolors.dim(` Note: ${note}`));\n}\n\nfunction showPatternsHelp(): void {\n console.log(`\n${picocolors.bold('Pattern Management')}\n\nSave, validate, and share patterns that worked well across projects.\n\n${picocolors.bold('Commands:')}\n trie patterns save <target> [note] Save a pattern (file, code, or scout)\n trie patterns list [--validated] List saved patterns\n trie patterns export [file] [--validated] Export patterns to JSON\n trie patterns import <file> Import patterns from JSON\n trie patterns validate <id> [note] Mark pattern as validated\n\n${picocolors.bold('Examples:')}\n # Save a file structure pattern\n trie patterns save \"path/*\" \"This folder structure worked well\"\n\n # Save a code pattern\n trie patterns save path/to/file.ts \"This error handling prevented bugs\"\n\n # Save a detection rule\n trie patterns save security \"This scout caught issues early\"\n\n # Validate a pattern\n trie patterns validate pattern-abc123 \"Worked great in production\"\n\n # Export validated patterns\n trie patterns export patterns.json --validated\n\n # Import to another project\n cd ../another-project\n trie patterns import ../source-project/patterns.json\n\n${picocolors.dim('Patterns are saved in .trie/saved-patterns.json')}\n`);\n}\n","/**\n * Saved Patterns\n *\n * Unified pattern storage for:\n * - File structure patterns (architecture decisions)\n * - Code patterns (specific fixes/approaches)\n * - Detection rules (scout preferences)\n */\n\nimport { createHash } from 'crypto';\nimport { readFile, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename } from 'path';\nimport type { Issue } from '../types/index.js';\nimport { searchIssues } from '../memory/issue-store.js';\nimport { getTrieDirectory } from '../utils/workspace.js';\n\nexport type SavedPatternType = 'file-structure' | 'code-pattern' | 'detection-rule';\n\nexport interface SavedPattern {\n id: string;\n type: SavedPatternType;\n name: string;\n description: string;\n\n filePatterns?: string[];\n architecture?: {\n structure: string;\n rationale: string;\n };\n\n codePattern?: {\n pattern: string;\n fix: string;\n context: string;\n };\n\n detectionRule?: {\n agent: string;\n rule: string;\n severity: string;\n };\n\n validated: boolean;\n validationNotes?: string;\n projects: string[];\n occurrences: number;\n savedAt: string;\n savedBy: string;\n}\n\nexport async function loadSavedPatterns(workDir: string): Promise<SavedPattern[]> {\n const patternsPath = join(getTrieDirectory(workDir), 'saved-patterns.json');\n\n try {\n if (existsSync(patternsPath)) {\n const content = await readFile(patternsPath, 'utf-8');\n return JSON.parse(content);\n }\n } catch {\n // File doesn't exist or invalid - return empty\n }\n\n return [];\n}\n\nexport async function savePatternsToProject(patterns: SavedPattern[], workDir: string): Promise<void> {\n const { mkdir } = await import('fs/promises');\n const patternsPath = join(getTrieDirectory(workDir), 'saved-patterns.json');\n\n await mkdir(getTrieDirectory(workDir), { recursive: true });\n await writeFile(patternsPath, JSON.stringify(patterns, null, 2));\n}\n\nexport async function savePatternToProject(pattern: SavedPattern, workDir: string): Promise<void> {\n const patterns = await loadSavedPatterns(workDir);\n const existing = patterns.findIndex(p => p.id === pattern.id);\n\n if (existing >= 0) {\n patterns[existing] = {\n ...patterns[existing]!,\n ...pattern,\n occurrences: patterns[existing]!.occurrences + 1,\n };\n } else {\n patterns.push(pattern);\n }\n\n await savePatternsToProject(patterns, workDir);\n}\n\nexport function detectPatternType(target: string, workDir: string): SavedPatternType {\n const scoutNames = [\n 'security', 'legal', 'accessibility', 'bug-finding',\n 'architecture', 'types', 'clean', 'devops', 'performance',\n 'ux', 'design', 'production-ready', 'agent-smith'\n ];\n\n if (scoutNames.includes(target.toLowerCase())) {\n return 'detection-rule';\n }\n\n const fullPath = join(workDir, target);\n if (\n existsSync(fullPath) ||\n target.includes('/') ||\n target.includes('*') ||\n target.endsWith('.ts') ||\n target.endsWith('.js')\n ) {\n return 'file-structure';\n }\n\n return 'code-pattern';\n}\n\nexport function generatePatternId(target: string, type: SavedPatternType): string {\n const hash = createHash('sha256')\n .update(`${type}:${target}`)\n .digest('hex')\n .slice(0, 12);\n return `${type}-${hash}`;\n}\n\nexport function getDetectionRuleAgents(patterns: SavedPattern[]): string[] {\n return patterns\n .filter(p => p.type === 'detection-rule')\n .map(p => p.detectionRule?.agent || p.name)\n .filter(Boolean);\n}\n\nexport async function createSavedPattern(\n target: string,\n note: string | undefined,\n workDir: string\n): Promise<SavedPattern> {\n const projectName = basename(workDir);\n const patternType = detectPatternType(target, workDir);\n\n const savedPattern: SavedPattern = {\n id: generatePatternId(target, patternType),\n type: patternType,\n name: target,\n description: note || `Pattern saved from ${projectName}`,\n validated: false,\n projects: [projectName],\n occurrences: 1,\n savedAt: new Date().toISOString(),\n savedBy: projectName,\n };\n\n if (patternType === 'file-structure') {\n savedPattern.filePatterns = [target];\n savedPattern.architecture = {\n structure: `Files matching ${target}`,\n rationale: note || 'File structure pattern that worked well',\n };\n } else if (patternType === 'code-pattern') {\n const issues = await searchIssues(target, { limit: 5 });\n if (issues.length > 0) {\n const latestIssue = issues[0];\n savedPattern.codePattern = {\n pattern: latestIssue?.issue.issue || target,\n fix: latestIssue?.issue.fix || 'Review and apply similar fix',\n context: note || 'Code pattern that worked well',\n };\n } else {\n savedPattern.codePattern = {\n pattern: target,\n fix: 'Review and apply similar fix',\n context: note || 'Code pattern that worked well',\n };\n }\n } else if (patternType === 'detection-rule') {\n savedPattern.detectionRule = {\n agent: target,\n rule: `Detection rules from ${target} scout`,\n severity: 'moderate',\n };\n }\n\n return savedPattern;\n}\n\nexport async function buildSavedPatternIssues(\n patterns: SavedPattern[],\n files: string[],\n readFileContent: (filePath: string) => Promise<string>\n): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const pattern of patterns) {\n if (pattern.type === 'detection-rule') continue;\n\n const targetFiles = filterFilesForPattern(files, pattern);\n if (targetFiles.length === 0) continue;\n\n if (pattern.type === 'file-structure') {\n for (const file of targetFiles) {\n issues.push(createPatternIssue(pattern, file, undefined));\n }\n continue;\n }\n\n if (pattern.type === 'code-pattern' && pattern.codePattern) {\n for (const file of targetFiles) {\n const content = await readFileContent(file);\n const match = findPatternMatch(content, pattern.codePattern.pattern);\n if (match) {\n issues.push(createPatternIssue(pattern, file, match.line));\n }\n }\n }\n }\n\n return issues;\n}\n\nfunction filterFilesForPattern(files: string[], pattern: SavedPattern): string[] {\n if (pattern.type === 'file-structure' && pattern.filePatterns) {\n return files.filter(file => pattern.filePatterns!.some(p => matchesFilePattern(file, p)));\n }\n if (pattern.type === 'code-pattern') {\n return files;\n }\n return [];\n}\n\nfunction matchesFilePattern(filePath: string, pattern: string): boolean {\n const normalized = filePath.replace(/\\\\/g, '/');\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '___DOUBLESTAR___')\n .replace(/\\*/g, '[^/]*')\n .replace(/___DOUBLESTAR___/g, '.*');\n const regex = new RegExp(`^${escaped}$`, 'i');\n return regex.test(normalized) || normalized.includes(pattern.replace(/\\*+/g, ''));\n}\n\nfunction findPatternMatch(content: string, pattern: string): { line: number } | null {\n try {\n const regex = new RegExp(pattern, 'i');\n const match = regex.exec(content);\n if (!match || match.index === undefined) return null;\n const line = getLineNumber(content, match.index);\n return { line };\n } catch {\n const index = content.toLowerCase().indexOf(pattern.toLowerCase());\n if (index === -1) return null;\n const line = getLineNumber(content, index);\n return { line };\n }\n}\n\nfunction getLineNumber(content: string, index: number): number {\n return content.slice(0, index).split('\\n').length;\n}\n\nfunction createPatternIssue(pattern: SavedPattern, file: string, line?: number): Issue {\n const description = pattern.description || `Saved pattern: ${pattern.name}`;\n const fix = pattern.codePattern?.fix || 'Apply the saved pattern from your other project.';\n const issue: Issue = {\n id: `saved-${pattern.id}-${hashFile(file)}`,\n severity: 'low',\n issue: `Saved pattern suggestion: ${description}`,\n fix,\n file,\n confidence: 0.6,\n autoFixable: false,\n agent: 'saved-patterns',\n category: 'pattern-sharing',\n };\n if (line !== undefined) {\n issue.line = line;\n }\n return issue;\n}\n\nfunction hashFile(file: string): string {\n return createHash('sha256').update(file).digest('hex').slice(0, 8);\n}\n","import pc from 'picocolors';\nimport { Command } from 'commander';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport {\n initializeSharedLedger,\n syncLedgerFromShared,\n pushLedgerToShared,\n getLedgerSyncStatus,\n migrateLegacyLedger,\n detectLegacyLedger\n} from '../memory/ledger.js';\nimport { installGitHooks, checkGitHooks } from './hooks.js';\n\nexport function createSyncCommand(): Command {\n const sync = new Command('sync')\n .description('Sync ledger with shared storage');\n\n sync.command('init')\n .description('Initialize shared ledger storage')\n .action(async () => {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n console.log(`Initializing shared ledger in ${workDir}...`);\n\n await initializeSharedLedger();\n console.log(pc.green('✓ Shared ledger initialized successfully'));\n } catch (error) {\n console.error(pc.red('Failed to initialize shared ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('pull')\n .description('Pull updates from shared ledger')\n .action(async () => {\n try {\n console.log('Syncing from shared ledger...');\n\n // Check for legacy ledger and migrate if needed\n const hasLegacy = await detectLegacyLedger();\n if (hasLegacy) {\n console.log('Detected legacy ledger, migrating...');\n await migrateLegacyLedger();\n }\n\n const result = await syncLedgerFromShared();\n\n console.log(pc.green('✓ Sync completed'));\n console.log(`Merged ${result.stats.mergedBlocks} blocks`);\n\n if (result.conflicts.length > 0) {\n console.log(pc.yellow(`⚠ ${result.conflicts.length} conflicts detected`));\n console.log('Run \"trie sync status\" to see details');\n }\n\n if (result.stats.duplicatesRemoved > 0) {\n console.log(`Removed ${result.stats.duplicatesRemoved} duplicate entries`);\n }\n } catch (error) {\n console.error(pc.red('Failed to sync from shared ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('push')\n .description('Push local changes to shared ledger')\n .action(async () => {\n try {\n console.log('Pushing to shared ledger...');\n\n // Check for legacy ledger and migrate if needed\n const hasLegacy = await detectLegacyLedger();\n if (hasLegacy) {\n console.log('Detected legacy ledger, migrating...');\n await migrateLegacyLedger();\n }\n\n await pushLedgerToShared();\n console.log(pc.green('✓ Push completed'));\n } catch (error) {\n console.error(pc.red('Failed to push to shared ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('status')\n .description('Show ledger sync status')\n .action(async () => {\n try {\n const status = await getLedgerSyncStatus();\n\n console.log(pc.bold('Ledger Sync Status\\n'));\n\n if (!status.isInitialized) {\n console.log(pc.yellow('⚠ Shared ledger not initialized. Run \"trie sync init\" first.'));\n return;\n }\n\n if (status.hasLegacyLedger) {\n console.log(pc.yellow('⚠ Legacy ledger detected. Run \"trie sync pull\" to migrate.'));\n }\n\n console.log(`Local blocks: ${pc.cyan(status.localBlocks.toString())}`);\n console.log(`Shared blocks: ${pc.cyan(status.sharedBlocks.toString())}`);\n\n if (status.syncState) {\n const lastSync = new Date(status.syncState.lastSyncTimestamp);\n console.log(`Last sync: ${pc.dim(lastSync.toLocaleString())}`);\n\n if (status.conflicts > 0) {\n console.log(pc.yellow(`Conflicts: ${status.conflicts}`));\n console.log('\\nConflicts:');\n for (const conflict of status.syncState.conflicts) {\n console.log(` • ${conflict.type}: ${conflict.description}`);\n }\n } else {\n console.log(pc.green('✓ No conflicts'));\n }\n }\n\n if (status.manifest) {\n console.log(`\\nTotal entries: ${pc.cyan(status.manifest.totalEntries.toString())}`);\n console.log(`Compression: ${status.manifest.compressionConfig.enabled ? pc.green('enabled') : pc.red('disabled')}`);\n }\n } catch (error) {\n console.error(pc.red('Failed to get sync status:'), error);\n process.exit(1);\n }\n });\n\n sync.command('migrate')\n .description('Migrate legacy ledger to new format')\n .action(async () => {\n try {\n const hasLegacy = await detectLegacyLedger();\n\n if (!hasLegacy) {\n console.log(pc.yellow('No legacy ledger found to migrate'));\n return;\n }\n\n console.log('Migrating legacy ledger...');\n const success = await migrateLegacyLedger();\n\n if (success) {\n console.log(pc.green('✓ Migration completed successfully'));\n } else {\n console.log(pc.red('Migration failed'));\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to migrate legacy ledger:'), error);\n process.exit(1);\n }\n });\n\n sync.command('hooks')\n .description('Manage git hooks for automatic sync')\n .option('--install', 'Install git hooks')\n .option('--status', 'Check git hooks status')\n .action(async (options) => {\n try {\n if (options.install) {\n await installGitHooks();\n return;\n }\n\n // Default to status check\n const status = await checkGitHooks();\n\n if (!status.isGitRepo) {\n console.log(pc.yellow('Not a git repository'));\n return;\n }\n\n console.log(pc.bold('Git Hooks Status\\n'));\n console.log(`Pre-push hook: ${status.prePushInstalled ? pc.green('✓ installed') : pc.red('✗ not installed')}`);\n console.log(`Post-merge hook: ${status.postMergeInstalled ? pc.green('✓ installed') : pc.red('✗ not installed')}`);\n\n if (!status.prePushInstalled || !status.postMergeInstalled) {\n console.log(`\\n${pc.yellow('💡 Tip:')} Run ${pc.bold('trie sync hooks --install')} to install missing hooks`);\n }\n } catch (error) {\n console.error(pc.red('Failed to manage git hooks:'), error);\n process.exit(1);\n }\n });\n\n return sync;\n}","import pc from 'picocolors';\nimport { Command } from 'commander';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport {\n verifyLedger,\n getLedgerBlocks,\n getLedgerSyncStatus,\n compressOldBlocks,\n getStorageStats,\n shouldCompress,\n deleteBlocks,\n deleteAllBlocks\n} from '../memory/ledger.js';\n\nexport function createLedgerCommand(): Command {\n const ledger = new Command('ledger')\n .description('Manage and inspect the ledger');\n\n ledger.command('verify')\n .description('Verify ledger chain integrity')\n .action(async () => {\n try {\n console.log('Verifying ledger chain...');\n\n const result = await verifyLedger();\n\n if (result.valid) {\n console.log(pc.green('✓ Ledger chain is valid'));\n } else {\n console.log(pc.red(`✗ Ledger chain is invalid: ${result.error}`));\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to verify ledger:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('history')\n .description('Show ledger history with author attribution')\n .option('-l, --limit <number>', 'Number of blocks to show', '10')\n .action(async (options) => {\n try {\n const limit = parseInt(options.limit, 10);\n const blocks = await getLedgerBlocks();\n\n if (blocks.length === 0) {\n console.log('No ledger blocks found');\n return;\n }\n\n console.log(pc.bold(`Ledger History (last ${Math.min(limit, blocks.length)} blocks)\\n`));\n\n const recentBlocks = blocks.slice(-limit).reverse();\n\n for (const block of recentBlocks) {\n const syncableBlock = block as any;\n console.log(pc.bold(pc.cyan(`Block ${block.date}`)));\n\n if (syncableBlock.author) {\n console.log(`Author: ${pc.dim(syncableBlock.author)}`);\n }\n\n if (syncableBlock.gitCommit) {\n console.log(`Git: ${pc.dim(syncableBlock.gitCommit.slice(0, 8))}`);\n }\n\n console.log(`Entries: ${block.entries.length}`);\n console.log(`Hash: ${pc.dim(block.blockHash.slice(0, 16))}...`);\n\n if (block.entries.length > 0) {\n console.log('Issues:');\n for (const entry of block.entries) {\n console.log(` • ${entry.severity} - ${entry.file} (${entry.agent})`);\n }\n }\n\n console.log('');\n }\n } catch (error) {\n console.error(pc.red('Failed to show ledger history:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('stats')\n .description('Show ledger statistics')\n .action(async () => {\n try {\n const status = await getLedgerSyncStatus();\n const blocks = await getLedgerBlocks();\n\n console.log(pc.bold('Ledger Statistics\\n'));\n\n console.log(`Total blocks: ${pc.cyan(blocks.length.toString())}`);\n\n if (status.manifest) {\n console.log(`Total entries: ${pc.cyan(status.manifest.totalEntries.toString())}`);\n console.log(`Active blocks: ${pc.cyan(status.manifest.activeBlocks.length.toString())}`);\n console.log(`Archived blocks: ${pc.cyan(status.manifest.archivedBlocks.length.toString())}`);\n\n if (status.manifest.compressionConfig.enabled) {\n const hotSize = Math.round(status.manifest.compressionConfig.maxHotStorageSize / 1024 / 1024);\n console.log(`Hot storage limit: ${pc.cyan(`${hotSize}MB`)}`);\n console.log(`Archive after: ${pc.cyan(`${status.manifest.compressionConfig.archiveAfterDays} days`)}`);\n }\n }\n\n // Calculate date range\n if (blocks.length > 0) {\n const firstBlock = blocks[0];\n const lastBlock = blocks[blocks.length - 1];\n console.log(`Date range: ${pc.dim(`${firstBlock.date} to ${lastBlock.date}`)}`);\n }\n\n // Author statistics\n const authorCounts = new Map<string, number>();\n for (const block of blocks) {\n const syncableBlock = block as any;\n if (syncableBlock.author) {\n authorCounts.set(syncableBlock.author, (authorCounts.get(syncableBlock.author) || 0) + 1);\n }\n }\n\n if (authorCounts.size > 0) {\n console.log('\\nBlocks by author:');\n const sortedAuthors = Array.from(authorCounts.entries())\n .sort((a, b) => b[1] - a[1]);\n\n for (const [author, count] of sortedAuthors.slice(0, 10)) {\n console.log(` ${author}: ${pc.cyan(count.toString())}`);\n }\n }\n\n // Severity statistics\n const severityCounts = new Map<string, number>();\n for (const block of blocks) {\n for (const entry of block.entries) {\n severityCounts.set(entry.severity, (severityCounts.get(entry.severity) || 0) + 1);\n }\n }\n\n if (severityCounts.size > 0) {\n console.log('\\nIssues by severity:');\n const severityOrder = ['critical', 'high', 'medium', 'low', 'info'];\n\n for (const severity of severityOrder) {\n const count = severityCounts.get(severity);\n if (count) {\n const color = severity === 'critical' ? pc.red :\n severity === 'high' ? pc.yellow :\n severity === 'medium' ? pc.blue : pc.gray;\n console.log(` ${color(severity)}: ${pc.cyan(count.toString())}`);\n }\n }\n }\n } catch (error) {\n console.error(pc.red('Failed to show ledger stats:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('diff')\n .description('Compare local and shared ledger state')\n .action(async () => {\n try {\n const status = await getLedgerSyncStatus();\n\n console.log(pc.bold('Ledger Diff\\n'));\n\n if (!status.isInitialized) {\n console.log(pc.yellow('Shared ledger not initialized'));\n return;\n }\n\n console.log(`Local blocks: ${pc.cyan(status.localBlocks.toString())}`);\n console.log(`Shared blocks: ${pc.cyan(status.sharedBlocks.toString())}`);\n\n const diff = status.sharedBlocks - status.localBlocks;\n if (diff > 0) {\n console.log(pc.green(`↓ ${diff} blocks available to pull`));\n } else if (diff < 0) {\n console.log(pc.blue(`↑ ${-diff} local blocks not yet pushed`));\n } else {\n console.log(pc.green('✓ Local and shared ledgers are in sync'));\n }\n\n if (status.conflicts > 0) {\n console.log(pc.red(`⚠ ${status.conflicts} conflicts detected`));\n }\n } catch (error) {\n console.error(pc.red('Failed to diff ledgers:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('compress')\n .description('Manually compress and archive old blocks')\n .action(async () => {\n try {\n const shouldRun = await shouldCompress();\n\n if (!shouldRun) {\n console.log('No compression needed at this time');\n return;\n }\n\n console.log('Compressing old ledger blocks...');\n const result = await compressOldBlocks();\n\n if (result.archived > 0) {\n console.log(pc.green(`✓ Compressed ${result.archived} blocks`));\n console.log(`Space saved: ${result.sizeReduction}%`);\n } else {\n console.log('No blocks were archived');\n }\n } catch (error) {\n console.error(pc.red('Failed to compress blocks:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('storage')\n .description('Show detailed storage statistics')\n .action(async () => {\n try {\n const stats = await getStorageStats();\n\n console.log(pc.bold('Ledger Storage Statistics\\n'));\n\n console.log(pc.bold('Block Storage:'));\n console.log(` Active blocks: ${pc.cyan(stats.activeBlocks.toString())}`);\n console.log(` Archived blocks: ${pc.cyan(stats.archivedBlocks.toString())}`);\n\n console.log(pc.bold('\\nStorage Usage:'));\n const activeMB = (stats.activeSize / 1024 / 1024).toFixed(2);\n const archivedMB = (stats.archivedSize / 1024 / 1024).toFixed(2);\n const totalMB = (Number(activeMB) + Number(archivedMB)).toFixed(2);\n\n console.log(` Active storage: ${pc.cyan(`${activeMB} MB`)}`);\n console.log(` Archived storage: ${pc.cyan(`${archivedMB} MB`)}`);\n console.log(` Total storage: ${pc.bold(pc.cyan(`${totalMB} MB`))}`);\n\n if (stats.compressionRatio > 0) {\n console.log(` Compression ratio: ${pc.green(`${stats.compressionRatio}%`)}`);\n }\n\n console.log(pc.bold('\\nData:'));\n console.log(` Total entries: ${pc.cyan(stats.totalEntries.toString())}`);\n\n const needsCompression = await shouldCompress();\n if (needsCompression) {\n console.log(`\\n${pc.yellow('💡 Tip:')} Run ${pc.bold('trie ledger compress')} to archive old blocks`);\n }\n } catch (error) {\n console.error(pc.red('Failed to get storage stats:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('delete')\n .description('Delete specific blocks from the ledger (PERMANENT)')\n .argument('<dates...>', 'Block dates to delete (YYYY-MM-DD format)')\n .option('--confirm', 'Confirm the permanent deletion')\n .action(async (dates: string[], options) => {\n try {\n // Validate date formats\n const datePattern = /^\\d{4}-\\d{2}-\\d{2}$/;\n const invalidDates = dates.filter(date => !datePattern.test(date));\n\n if (invalidDates.length > 0) {\n console.error(pc.red('Invalid date format(s):'), invalidDates.join(', '));\n console.error('Please use YYYY-MM-DD format');\n process.exit(1);\n }\n\n if (!options.confirm) {\n console.log(pc.bold(pc.red('⚠️ DANGER: PERMANENT DELETION')));\n console.log('');\n console.log(`You are about to permanently delete ${dates.length} block(s):`);\n for (const date of dates) {\n console.log(` • ${pc.cyan(date)}`);\n }\n console.log('');\n console.log(pc.red('This operation cannot be undone and will permanently remove'));\n console.log(pc.red('all issues and data from these blocks.'));\n console.log('');\n console.log(`To proceed, add the ${pc.bold('--confirm')} flag:`);\n console.log(` ${pc.dim('trie ledger delete ' + dates.join(' ') + ' --confirm')}`);\n return;\n }\n\n console.log(pc.yellow('🗑️ Deleting blocks...'));\n\n const result = await deleteBlocks(dates, undefined, true);\n\n if (result.success) {\n console.log(pc.green(`✓ Successfully deleted ${result.deletedBlocks} block(s)`));\n if (result.warning) {\n console.log(pc.yellow(`⚠️ ${result.warning}`));\n }\n } else {\n console.error(pc.red('✗ Deletion failed:'), result.error);\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to delete blocks:'), error);\n process.exit(1);\n }\n });\n\n ledger.command('clear')\n .description('Delete ALL blocks from the ledger (PERMANENT)')\n .option('--confirm', 'Confirm the permanent deletion of all blocks')\n .action(async (options) => {\n try {\n if (!options.confirm) {\n console.log(pc.bold(pc.red('🚨 DANGER: COMPLETE LEDGER DELETION')));\n console.log('');\n console.log(pc.red('You are about to permanently delete ALL blocks in the ledger.'));\n console.log(pc.red('This will completely erase the entire ledger history.'));\n console.log('');\n console.log(pc.red('This operation cannot be undone and will permanently remove'));\n console.log(pc.red('ALL issues and historical data.'));\n console.log('');\n console.log(`To proceed, add the ${pc.bold('--confirm')} flag:`);\n console.log(` ${pc.dim('trie ledger clear --confirm')}`);\n return;\n }\n\n // Double confirmation for clear all\n console.log(pc.yellow('🗑️ Clearing entire ledger...'));\n\n const result = await deleteAllBlocks(undefined, true);\n\n if (result.success) {\n console.log(pc.green(`✓ Successfully deleted ${result.deletedBlocks} block(s)`));\n if (result.warning) {\n console.log(pc.yellow(`⚠️ ${result.warning}`));\n }\n } else {\n console.error(pc.red('✗ Clear operation failed:'), result.error);\n process.exit(1);\n }\n } catch (error) {\n console.error(pc.red('Failed to clear ledger:'), error);\n process.exit(1);\n }\n });\n\n return ledger;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,WAAAA,UAAS,QAAAC,OAAM,WAAAC,gBAAe;AACvC,SAAS,gBAAAC,eAAc,oBAAoB;AAC3C,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,SAAQ;;;ACdf,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACDjB,IAAM,WAAW;AAEjB,SAAS,aAAqB;AAC5B,SAAO,gBAAgB,W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Args","pc","installGitHooks","pc","__filename","__dirname","pc","existsSync","join","pc","join","existsSync","readFile","existsSync","pc","writeFile","existsSync","resolve","pc","existsSync","readFile","applied","pc","pc","path","path","path","path","fs","path","path","fs","existsSync","join","pc","join","showHelp","existsSync","picocolors","readFile","writeFile","existsSync","basename","picocolors","readFile","writeFile","existsSync","join","join","existsSync","readFile","mkdir","writeFile","picocolors","basename","writeFile","existsSync","readFile","pc","pc","installGitHooks","pc","Command","Command","pc","__filename","fileURLToPath","__dirname","dirname","resolve","readFileSync","showHelp","pc","join"]}
|