@triedotdev/mcp 1.0.89 → 1.0.90
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/dist/cli/main.js +9 -2
- package/dist/cli/main.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/main.js
CHANGED
|
@@ -86,7 +86,7 @@ import {
|
|
|
86
86
|
// src/cli/main.ts
|
|
87
87
|
import { resolve, join as join2, dirname } from "path";
|
|
88
88
|
import { existsSync as existsSync4, readFileSync } from "fs";
|
|
89
|
-
import { fileURLToPath
|
|
89
|
+
import { fileURLToPath } from "url";
|
|
90
90
|
|
|
91
91
|
// src/cli/skills.ts
|
|
92
92
|
async function handleSkillsCommand(args) {
|
|
@@ -3022,7 +3022,14 @@ async function main() {
|
|
|
3022
3022
|
var isEntryPoint = (() => {
|
|
3023
3023
|
const entry = process.argv[1];
|
|
3024
3024
|
if (!entry) return false;
|
|
3025
|
-
|
|
3025
|
+
try {
|
|
3026
|
+
const { realpathSync } = __require("fs");
|
|
3027
|
+
const realEntry = realpathSync(entry);
|
|
3028
|
+
const realThis = fileURLToPath(import.meta.url);
|
|
3029
|
+
return realEntry === realThis;
|
|
3030
|
+
} catch {
|
|
3031
|
+
return !process.env.VITEST && !process.env.VITEST_WORKER_ID;
|
|
3032
|
+
}
|
|
3026
3033
|
})();
|
|
3027
3034
|
if (isEntryPoint) {
|
|
3028
3035
|
main().catch((error) => {
|
package/dist/cli/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/main.ts","../../src/cli/skills.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/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"],"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 { existsSync, readFileSync } from 'fs';\nimport { fileURLToPath, pathToFileURL } from 'url';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { loadProjectInfo, initProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { handleSkillsCommand } from './skills.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 { 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 central registry for agents and skills\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 the guardian (watches + 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 skills Manage external skills from skills.sh\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 scouts List all available scouts\n setup Configure API key and environment\n \n agent-smith Run Agent Smith (35 vibe code hunters)\n super-reviewer Run interactive PR review\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 the guardian (watches + nudges)\n trie watch # Run in background: screen -S trie-watch\n trie scan # Scan your codebase now\n trie scan --scouts security,privacy # Scan with specific scouts\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 skills add vercel-labs/agent-skills react-best-practices\n trie memory search \"SQL injection\"\n trie memory stats # View memory statistics\n trie status # Quick health check (project + memory)\n trie agent-smith # 35 vibe code hunters\n trie super-reviewer # Interactive PR review\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 Intelligent scan with scout selection\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 Individual Scouts:\n trie_security Security vulnerabilities\n trie_privacy Privacy & GDPR compliance\n trie_soc2 SOC 2 Type II compliance\n trie_legal Legal compliance\n trie_accessibility WCAG 2.1 accessibility\n trie_architecture Code organization & SOLID\n trie_bugs Bug finding & null safety\n trie_ux UX testing (happy path, edge cases)\n trie_types TypeScript type safety\n trie_devops DevOps & deployment\n trie_clean Clean up AI-generated code\n \n Special Scouts:\n trie_agent_smith 35 vibe code hunters, cross-file detection\n trie_super_reviewer Interactive PR review with cross-examination\n\n Custom Skills:\n trie_create_skill Create skill from PDF/TXT/MD document\n trie_list_skills List all registered skills\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 * List available agents\n */\nfunction listAgents(): void {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ 📋 Available Scouts ║\n╚══════════════════════════════════════════════════════════════════╝\n\nBUILT-IN SCOUTS:\n─────────────────────────────────────\n security Security vulnerabilities, injection risks, auth issues\n privacy GDPR, HIPAA, PII handling, data encryption\n legal GDPR, CCPA, consent patterns, data retention\n accessibility WCAG 2.1 accessibility, keyboard nav, screen readers\n software-architect Code organization, SOLID principles, scalability\n bug-finding Null safety, edge cases, async issues\n user-testing Simulate users: happy path, security tester, confused user\n typecheck Type errors, missing annotations, null checks\n devops Config issues, logging, env vars, deployment\n trie_clean Clean up AI-generated code patterns\n moneybags Estimates dollar cost of bugs (IBM/NIST cost models)\n production-ready Production gate: health checks, scaling, security headers\n\n Custom Skills:\n ─────────────────────────────────────`);\n\n // Check for custom skills\n const skillsDir = join(getTrieDirectory(getWorkingDirectory(undefined, true)), 'agents');\n if (existsSync(skillsDir)) {\n try {\n const { readdirSync } = require('fs');\n const files = readdirSync(skillsDir).filter((f: string) => f.endsWith('.json'));\n \n if (files.length > 0) {\n for (const file of files) {\n const config = JSON.parse(readFileSync(join(skillsDir, file), 'utf-8'));\n console.log(` ${config.name.padEnd(18)} ${config.description || 'Custom skill'}`);\n }\n } else {\n console.log(` (No custom skills found)`);\n }\n } catch {\n console.log(` (No custom skills found)`);\n }\n } else {\n console.log(` (No custom skills found)`);\n }\n\n console.log(`\nCREATE CUSTOM SKILLS:\n─────────────────────────────────────\nYou can create skills from PDF, TXT, or MD documents:\n\n Via MCP: Use trie_create_skill tool\n CLI: trie-create --file book.pdf --name my-skill\n\nThe agent will learn patterns from your document and apply them\nto code reviews. Great for style guides, compliance docs, etc.\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 health score and last scan\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 // Health Score\n const healthEmoji = state.healthScore >= 80 ? '✅' : state.healthScore >= 60 ? '⚠️' : '🔴';\n console.log(`${healthEmoji} Health Score: ${state.healthScore}%`);\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📅 Last Scan: ${lastScanDate.toLocaleDateString()} (${daysAgo === 0 ? 'today' : daysAgo === 1 ? 'yesterday' : `${daysAgo} days ago`})`);\n console.log(` Files scanned: ${state.lastScan.filesScanned}`);\n console.log(` Issues found: ${state.lastScan.issues.total} (${state.lastScan.issues.critical} critical, ${state.lastScan.issues.serious} serious)`);\n } else {\n console.log('\\n📅 Last Scan: Never (run `trie scan` to get started)');\n }\n \n // Memory Stats Summary\n console.log('\\n💾 Memory Stats:');\n console.log(` Total Issues: ${memoryStats.totalIssues}`);\n console.log(` Resolved: ${memoryStats.resolvedCount}`);\n const cap = memoryStats.capacityInfo;\n const capEmoji = cap.isAtCap ? '🔴' : cap.percentFull >= 80 ? '⚠️' : '✅';\n console.log(` ${capEmoji} Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`);\n \n if (memoryStats.totalIssues > 0) {\n console.log('\\n By Severity:');\n const severityOrder = ['critical', 'serious', 'moderate', 'low', 'info'];\n for (const severity of severityOrder) {\n const count = memoryStats.issuesBySeverity[severity] || 0;\n if (count > 0) {\n console.log(` ${severity}: ${count}`);\n }\n }\n }\n \n // Capacity warning\n if (cap.isAtCap) {\n console.log('\\n⚠️ Memory at capacity - consider running: trie memory purge smart');\n } else if (cap.percentFull >= 80) {\n console.log('\\nℹ️ Memory usage high - consider running: trie memory purge smart');\n }\n \n console.log('\\n💡 Quick Commands:');\n console.log(' trie scan - Scan codebase now');\n console.log(' trie memory stats - Detailed memory statistics');\n console.log(' 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\nPath: ${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\nNo 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\nPath: ${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 'scouts':\n case 'agents': // Alias for backward compatibility\n case 'list':\n case 'list-scouts':\n case 'list-agents': // Alias for backward compatibility\n listAgents();\n break;\n\n case 'project':\n case 'info':\n case 'project-info':\n handleProject(restArgs);\n break;\n\n case 'skills':\n case 'skill':\n handleSkillsCommand(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 'agent-smith':\n case 'smith':\n case 'trie_agent_smith':\n // Run agent-smith specifically\n runScan(['--scouts', 'agent-smith', ...restArgs]);\n break;\n\n case 'super-reviewer':\n case 'reviewer':\n case 'trie_super_reviewer':\n // Run super-reviewer specifically\n runScan(['--scouts', 'super-reviewer', ...restArgs]);\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 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\nconst isEntryPoint = (() => {\n const entry = process.argv[1];\n if (!entry) return false;\n return pathToFileURL(entry).href === import.meta.url;\n})();\n\nif (isEntryPoint) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n","/**\n * Skills CLI Command Handler\n * \n * Manages external skills from skills.sh and other GitHub repositories.\n * Skills are reusable capabilities that agents apply during code review.\n */\n\nimport { installSkill, listInstalledSkills, removeSkill } from '../skills/installer.js';\nimport { loadContextState, recordSkillInstalled } from '../utils/context-state.js';\nimport { SKILL_CATEGORIES, getSkillCategories, getSkillsByCategory, detectStack } from '../bootstrap/stack-detector.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function handleSkillsCommand(args: string[]): Promise<void> {\n const [cmd, ...rest] = args;\n\n switch (cmd) {\n case 'add':\n case 'install': {\n if (!rest[0]) {\n console.log('Usage: trie skills add <owner/repo> [skill-name]');\n console.log('');\n console.log('Examples:');\n console.log(' trie skills add vercel-labs/agent-skills react-best-practices');\n console.log(' trie skills add anthropics/skills claude-code-review');\n console.log(' trie skills add myorg/internal-standards');\n return;\n }\n \n console.log(`Installing skill from ${rest[0]}...`);\n const result = await installSkill(rest[0], rest[1]);\n \n if (result.success) {\n await recordSkillInstalled({ name: result.name, source: rest[0] });\n console.log(`Installed: ${result.name}`);\n console.log(`Path: ${result.path}`);\n console.log('');\n console.log('This skill is now a capability the skill-review agent can apply.');\n console.log('Run \"trie scan\" to apply skills to your codebase.');\n } else {\n console.error(`Failed to install: ${result.error}`);\n process.exit(1);\n }\n break;\n }\n \n case 'list':\n case 'ls': {\n const categoryArg = rest[0]?.toLowerCase();\n \n // If a category is specified, show skills in that category\n if (categoryArg) {\n if (categoryArg === 'categories' || categoryArg === 'all') {\n // Show all available categories\n const categories = getSkillCategories();\n console.log('');\n console.log('Available Skill Categories:');\n console.log('');\n for (const cat of categories) {\n console.log(` ${cat.name.padEnd(15)} ${cat.count} skills`);\n }\n console.log('');\n console.log('View skills in a category:');\n console.log(' trie skills list <category>');\n console.log('');\n console.log('Browse all skills: https://skills.sh');\n return;\n }\n \n const categorySkills = getSkillsByCategory(categoryArg);\n if (categorySkills.length === 0) {\n const categories = getSkillCategories();\n console.log(`Unknown category: ${categoryArg}`);\n console.log('');\n console.log('Available categories:');\n for (const cat of categories) {\n console.log(` ${cat.name}`);\n }\n return;\n }\n \n console.log('');\n console.log(`${categoryArg.charAt(0).toUpperCase() + categoryArg.slice(1)} Skills (${categorySkills.length}):`);\n console.log('');\n for (const skill of categorySkills) {\n console.log(` trie skills add ${skill}`);\n }\n console.log('');\n console.log('Install any skill with: trie skills add <source> <name>');\n console.log('Browse all skills: https://skills.sh');\n return;\n }\n \n // No category - show installed skills\n const skills = await listInstalledSkills();\n const state = await loadContextState();\n \n if (skills.length === 0) {\n console.log('');\n console.log('No skills installed.');\n console.log('');\n console.log('Install a skill:');\n console.log(' trie skills add vercel-labs/agent-skills react-best-practices');\n console.log('');\n console.log('Explore skill categories:');\n const categories = getSkillCategories();\n for (const cat of categories.slice(0, 5)) {\n console.log(` trie skills list ${cat.name.padEnd(15)} # ${cat.count} skills`);\n }\n console.log(' trie skills list categories # see all');\n console.log('');\n console.log('Browse all skills: https://skills.sh');\n return;\n }\n \n console.log('');\n console.log(`Installed Skills (${skills.length}):`);\n console.log('');\n \n for (const skill of skills) {\n const record = state.skills?.[skill.name];\n const usage = record ? `applied ${record.timesApplied}x` : 'not yet applied';\n console.log(` ${skill.name} (${usage})`);\n console.log(` ${skill.description}`);\n console.log(` Source: ${skill.installedFrom}`);\n console.log('');\n }\n \n console.log('These skills are applied by the skill-review agent during scans.');\n console.log('');\n console.log('Explore more: trie skills list categories');\n break;\n }\n \n case 'remove':\n case 'rm':\n case 'uninstall': {\n if (!rest[0]) {\n console.log('Usage: trie skills remove <skill-name>');\n return;\n }\n \n const removed = await removeSkill(rest[0]);\n if (removed) {\n console.log(`Removed: ${rest[0]}`);\n } else {\n console.error(`Skill not found: ${rest[0]}`);\n process.exit(1);\n }\n break;\n }\n \n case 'suggest':\n case 'recommended': {\n const workDir = getWorkingDirectory(undefined, true);\n const stack = await detectStack(workDir);\n \n if (stack.suggestedSkills.length === 0) {\n console.log('');\n console.log('No specific skill recommendations for your stack.');\n console.log('');\n console.log('Browse all skills:');\n console.log(' trie skills list categories');\n console.log(' https://skills.sh');\n return;\n }\n \n console.log('');\n console.log('Suggested Skills (based on your stack):');\n console.log('');\n \n if (stack.framework) console.log(` Detected: ${stack.framework}`);\n if (stack.language) console.log(` Language: ${stack.language}`);\n if (stack.database) console.log(` Database: ${stack.database}`);\n console.log('');\n \n for (const skill of stack.suggestedSkills) {\n console.log(` trie skills add ${skill}`);\n }\n \n console.log('');\n console.log('Install any skill with: trie skills add <source> <name>');\n console.log('Browse all skills: https://skills.sh');\n break;\n }\n \n case 'info': {\n if (!rest[0]) {\n console.log('Usage: trie skills info <skill-name>');\n return;\n }\n \n const skills = await listInstalledSkills();\n const skill = skills.find(s => s.name === rest[0]);\n \n if (!skill) {\n console.error(`Skill not found: ${rest[0]}`);\n process.exit(1);\n return;\n }\n \n const state = await loadContextState();\n const record = state.skills?.[skill.name];\n \n console.log('');\n console.log(`Skill: ${skill.name}`);\n console.log(`Description: ${skill.description}`);\n console.log(`Path: ${skill.path}`);\n console.log(`Source: ${skill.installedFrom}`);\n console.log(`Installed: ${new Date(skill.installedAt).toLocaleString()}`);\n \n if (record) {\n console.log(`Times Applied: ${record.timesApplied}`);\n console.log(`Applied By: ${record.appliedBy.join(', ') || 'none'}`);\n if (record.lastApplied) {\n console.log(`Last Applied: ${new Date(record.lastApplied).toLocaleString()}`);\n }\n } else {\n console.log('Times Applied: 0');\n }\n break;\n }\n \n default: {\n const categories = getSkillCategories();\n console.log(`\nSkills - Reusable capabilities from skills.sh\n\nSkills are NOT agents - they are knowledge/instructions that the\nskill-review agent applies during code review.\n\nCommands:\n trie skills suggest Show skills for your stack\n trie skills add <source> [name] Install a skill\n trie skills list List installed skills\n trie skills list <category> Browse skills by category\n trie skills list categories Show all categories\n trie skills info <name> Show skill details\n trie skills remove <name> Uninstall a skill\n\nExamples:\n trie skills add vercel-labs/agent-skills react-best-practices\n trie skills add anthropics/skills frontend-design\n trie skills add expo/skills upgrading-expo\n\nCategories (${categories.length} total, ${Object.values(SKILL_CATEGORIES).flat().length}+ skills):\n ${categories.map(c => `${c.name} (${c.count})`).join(', ')}\n\nHow it works:\n 1. You install skills (capabilities)\n 2. The skill-review agent applies them during 'trie scan'\n 3. Usage is tracked in your project context\n\nBrowse all skills: https://skills.sh\n `);\n }\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 guardian 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 the guardian (watches + nudges as you code)\n 3. trie tell \"what broke\" # Teach Trie about past incidents\n\nThe guardian agent 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(` Total Issues: ${stats.totalIssues}`);\n console.log(` Resolved: ${stats.resolvedCount}`);\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 By Severity:');\n for (const [severity, count] of Object.entries(stats.issuesBySeverity)) {\n console.log(` ${severity}: ${count}`);\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 | Health | 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.healthScore}% | ${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, writeFile } 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 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 // TODO: Add more fix types\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 * Apply a single fix to a file\n */\nasync function applyFix(fix: AutoFixAction): Promise<boolean> {\n try {\n if (!existsSync(fix.file)) {\n console.error(pc.red(`File not found: ${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 console.error(pc.red(`Invalid line number: ${fix.line}`));\n return false;\n }\n \n const lineIndex = fix.line - 1;\n const originalLine = lines[lineIndex];\n \n // Apply the fix based on type\n let newContent: string;\n \n if (fix.type === 'remove-console-log' || fix.type === 'remove-debugger') {\n // Remove the entire line\n lines.splice(lineIndex, 1);\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 console.error(pc.red(`Unknown fix type: ${fix.type}`));\n return false;\n }\n \n // Write the file\n await writeFile(fix.file, newContent);\n \n console.error(pc.green(`✓ Applied fix to ${fix.file}:${fix.line}`));\n if (originalLine) {\n console.error(pc.dim(` Removed: ${originalLine.trim().slice(0, 60)}...`));\n }\n \n return true;\n \n } catch (error) {\n console.error(pc.red(`Failed to apply fix: ${error}`));\n return false;\n }\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 applyFix(fix);\n if (success) applied++;\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 applyFix(fix);\n if (success) {\n applied++;\n } else {\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 * Goal & Hypothesis CLI Commands\n * \n * Allows users to manually add goals and hypotheses while still\n * allowing the guardian 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 { getGuardianState, type Goal, type Hypothesis } from '../guardian/guardian-state.js';\n\n// ============================================================================\n// Goal Commands\n// ============================================================================\n\nexport async function handleGoalCommand(args: string[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(projectPath);\n await guardianState.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(guardianState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listGoals(guardianState);\n break;\n \n case 'complete':\n case 'done':\n await completeGoal(guardianState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteGoal(guardianState, 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(guardianState, [subcommand, ...restArgs]);\n } else {\n printGoalHelp();\n }\n }\n}\n\nasync function addGoal(guardianState: ReturnType<typeof getGuardianState>, 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 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: 0,\n startValue: 0,\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 guardianState.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 console.error(pc.dim(`Deadline: ${deadline.toLocaleDateString()}`));\n console.error('');\n console.error(pc.cyan('The guardian will track progress and celebrate when you achieve it!'));\n}\n\nasync function listGoals(guardianState: ReturnType<typeof getGuardianState>): Promise<void> {\n const goals = guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllGoals();\n const goal = goals.find(g => g.id === goalId || g.id.includes(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllGoals();\n const goal = goals.find(g => g.id === goalId || g.id.includes(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await guardianState.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 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.dim('░'.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 guardianState = getGuardianState(projectPath);\n await guardianState.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(guardianState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listHypotheses(guardianState);\n break;\n \n case 'validate':\n await validateHypothesis(guardianState, restArgs[0]);\n break;\n \n case 'invalidate':\n await invalidateHypothesis(guardianState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteHypothesis(guardianState, restArgs[0]);\n break;\n \n default:\n if (subcommand && !subcommand.startsWith('-')) {\n // Treat as hypothesis statement shorthand\n await addHypothesis(guardianState, [subcommand, ...restArgs]);\n } else {\n printHypothesisHelp();\n }\n }\n}\n\nasync function addHypothesis(guardianState: ReturnType<typeof getGuardianState>, 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.5, // Start neutral\n status: 'testing',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria,\n category,\n };\n \n await guardianState.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: 50% | Category: ${category}`));\n console.error('');\n console.error(pc.cyan('The guardian will collect evidence and update confidence over time.'));\n console.error(pc.dim(`Test criteria: ${testCriteria}`));\n}\n\nasync function listHypotheses(guardianState: ReturnType<typeof getGuardianState>): Promise<void> {\n const hypotheses = guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllHypotheses();\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.includes(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllHypotheses();\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.includes(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllHypotheses();\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.includes(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await guardianState.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 guardian 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 '../guardian/gotcha-predictor.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 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 } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { LearningEngine } from '../guardian/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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,SAAS,QAAAA,OAAM,eAAe;AACvC,SAAS,cAAAC,aAAY,oBAAoB;AACzC,SAAS,eAAe,qBAAqB;;;ACD7C,eAAsB,oBAAoB,MAA+B;AACvE,QAAM,CAAC,KAAK,GAAG,IAAI,IAAI;AAEvB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H,OAAO;AACL,gBAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,gBAAQ,MAAM,wCAAwC;AACtD,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAAA,EACJ;AACF;AAEA,IAAM,gBAAgB,MAAM;AAC1B,QAAM,QAAQ,QAAQ,KAAK,CAAC;AAC5B,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,cAAc,KAAK,EAAE,SAAS,YAAY;AACnD,GAAG;AAEH,IAAI,cAAc;AAChB,OAAK,EAAE,MAAM,WAAS;AACpB,YAAQ,MAAM,UAAU,KAAK;AAC7B,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["join","existsSync","fs","path","result","parseArgs","pc","resolve","pc","applied","pc","pc","path","path","path","path","fs","path","path","fs","existsSync","pc","showHelp","existsSync","picocolors","readFile","writeFile","existsSync","picocolors","picocolors","writeFile","existsSync","readFile","__filename","__dirname","showHelp","join","existsSync"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/main.ts","../../src/cli/skills.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/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"],"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 { existsSync, readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { loadProjectInfo, initProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { handleSkillsCommand } from './skills.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 { 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 central registry for agents and skills\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 the guardian (watches + 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 skills Manage external skills from skills.sh\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 scouts List all available scouts\n setup Configure API key and environment\n \n agent-smith Run Agent Smith (35 vibe code hunters)\n super-reviewer Run interactive PR review\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 the guardian (watches + nudges)\n trie watch # Run in background: screen -S trie-watch\n trie scan # Scan your codebase now\n trie scan --scouts security,privacy # Scan with specific scouts\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 skills add vercel-labs/agent-skills react-best-practices\n trie memory search \"SQL injection\"\n trie memory stats # View memory statistics\n trie status # Quick health check (project + memory)\n trie agent-smith # 35 vibe code hunters\n trie super-reviewer # Interactive PR review\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 Intelligent scan with scout selection\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 Individual Scouts:\n trie_security Security vulnerabilities\n trie_privacy Privacy & GDPR compliance\n trie_soc2 SOC 2 Type II compliance\n trie_legal Legal compliance\n trie_accessibility WCAG 2.1 accessibility\n trie_architecture Code organization & SOLID\n trie_bugs Bug finding & null safety\n trie_ux UX testing (happy path, edge cases)\n trie_types TypeScript type safety\n trie_devops DevOps & deployment\n trie_clean Clean up AI-generated code\n \n Special Scouts:\n trie_agent_smith 35 vibe code hunters, cross-file detection\n trie_super_reviewer Interactive PR review with cross-examination\n\n Custom Skills:\n trie_create_skill Create skill from PDF/TXT/MD document\n trie_list_skills List all registered skills\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 * List available agents\n */\nfunction listAgents(): void {\n console.log(`\n╔══════════════════════════════════════════════════════════════════╗\n║ 📋 Available Scouts ║\n╚══════════════════════════════════════════════════════════════════╝\n\nBUILT-IN SCOUTS:\n─────────────────────────────────────\n security Security vulnerabilities, injection risks, auth issues\n privacy GDPR, HIPAA, PII handling, data encryption\n legal GDPR, CCPA, consent patterns, data retention\n accessibility WCAG 2.1 accessibility, keyboard nav, screen readers\n software-architect Code organization, SOLID principles, scalability\n bug-finding Null safety, edge cases, async issues\n user-testing Simulate users: happy path, security tester, confused user\n typecheck Type errors, missing annotations, null checks\n devops Config issues, logging, env vars, deployment\n trie_clean Clean up AI-generated code patterns\n moneybags Estimates dollar cost of bugs (IBM/NIST cost models)\n production-ready Production gate: health checks, scaling, security headers\n\n Custom Skills:\n ─────────────────────────────────────`);\n\n // Check for custom skills\n const skillsDir = join(getTrieDirectory(getWorkingDirectory(undefined, true)), 'agents');\n if (existsSync(skillsDir)) {\n try {\n const { readdirSync } = require('fs');\n const files = readdirSync(skillsDir).filter((f: string) => f.endsWith('.json'));\n \n if (files.length > 0) {\n for (const file of files) {\n const config = JSON.parse(readFileSync(join(skillsDir, file), 'utf-8'));\n console.log(` ${config.name.padEnd(18)} ${config.description || 'Custom skill'}`);\n }\n } else {\n console.log(` (No custom skills found)`);\n }\n } catch {\n console.log(` (No custom skills found)`);\n }\n } else {\n console.log(` (No custom skills found)`);\n }\n\n console.log(`\nCREATE CUSTOM SKILLS:\n─────────────────────────────────────\nYou can create skills from PDF, TXT, or MD documents:\n\n Via MCP: Use trie_create_skill tool\n CLI: trie-create --file book.pdf --name my-skill\n\nThe agent will learn patterns from your document and apply them\nto code reviews. Great for style guides, compliance docs, etc.\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 health score and last scan\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 // Health Score\n const healthEmoji = state.healthScore >= 80 ? '✅' : state.healthScore >= 60 ? '⚠️' : '🔴';\n console.log(`${healthEmoji} Health Score: ${state.healthScore}%`);\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📅 Last Scan: ${lastScanDate.toLocaleDateString()} (${daysAgo === 0 ? 'today' : daysAgo === 1 ? 'yesterday' : `${daysAgo} days ago`})`);\n console.log(` Files scanned: ${state.lastScan.filesScanned}`);\n console.log(` Issues found: ${state.lastScan.issues.total} (${state.lastScan.issues.critical} critical, ${state.lastScan.issues.serious} serious)`);\n } else {\n console.log('\\n📅 Last Scan: Never (run `trie scan` to get started)');\n }\n \n // Memory Stats Summary\n console.log('\\n💾 Memory Stats:');\n console.log(` Total Issues: ${memoryStats.totalIssues}`);\n console.log(` Resolved: ${memoryStats.resolvedCount}`);\n const cap = memoryStats.capacityInfo;\n const capEmoji = cap.isAtCap ? '🔴' : cap.percentFull >= 80 ? '⚠️' : '✅';\n console.log(` ${capEmoji} Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`);\n \n if (memoryStats.totalIssues > 0) {\n console.log('\\n By Severity:');\n const severityOrder = ['critical', 'serious', 'moderate', 'low', 'info'];\n for (const severity of severityOrder) {\n const count = memoryStats.issuesBySeverity[severity] || 0;\n if (count > 0) {\n console.log(` ${severity}: ${count}`);\n }\n }\n }\n \n // Capacity warning\n if (cap.isAtCap) {\n console.log('\\n⚠️ Memory at capacity - consider running: trie memory purge smart');\n } else if (cap.percentFull >= 80) {\n console.log('\\nℹ️ Memory usage high - consider running: trie memory purge smart');\n }\n \n console.log('\\n💡 Quick Commands:');\n console.log(' trie scan - Scan codebase now');\n console.log(' trie memory stats - Detailed memory statistics');\n console.log(' 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\nPath: ${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\nNo 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\nPath: ${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 'scouts':\n case 'agents': // Alias for backward compatibility\n case 'list':\n case 'list-scouts':\n case 'list-agents': // Alias for backward compatibility\n listAgents();\n break;\n\n case 'project':\n case 'info':\n case 'project-info':\n handleProject(restArgs);\n break;\n\n case 'skills':\n case 'skill':\n handleSkillsCommand(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 'agent-smith':\n case 'smith':\n case 'trie_agent_smith':\n // Run agent-smith specifically\n runScan(['--scouts', 'agent-smith', ...restArgs]);\n break;\n\n case 'super-reviewer':\n case 'reviewer':\n case 'trie_super_reviewer':\n // Run super-reviewer specifically\n runScan(['--scouts', 'super-reviewer', ...restArgs]);\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 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 const { realpathSync } = require('fs');\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","/**\n * Skills CLI Command Handler\n * \n * Manages external skills from skills.sh and other GitHub repositories.\n * Skills are reusable capabilities that agents apply during code review.\n */\n\nimport { installSkill, listInstalledSkills, removeSkill } from '../skills/installer.js';\nimport { loadContextState, recordSkillInstalled } from '../utils/context-state.js';\nimport { SKILL_CATEGORIES, getSkillCategories, getSkillsByCategory, detectStack } from '../bootstrap/stack-detector.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function handleSkillsCommand(args: string[]): Promise<void> {\n const [cmd, ...rest] = args;\n\n switch (cmd) {\n case 'add':\n case 'install': {\n if (!rest[0]) {\n console.log('Usage: trie skills add <owner/repo> [skill-name]');\n console.log('');\n console.log('Examples:');\n console.log(' trie skills add vercel-labs/agent-skills react-best-practices');\n console.log(' trie skills add anthropics/skills claude-code-review');\n console.log(' trie skills add myorg/internal-standards');\n return;\n }\n \n console.log(`Installing skill from ${rest[0]}...`);\n const result = await installSkill(rest[0], rest[1]);\n \n if (result.success) {\n await recordSkillInstalled({ name: result.name, source: rest[0] });\n console.log(`Installed: ${result.name}`);\n console.log(`Path: ${result.path}`);\n console.log('');\n console.log('This skill is now a capability the skill-review agent can apply.');\n console.log('Run \"trie scan\" to apply skills to your codebase.');\n } else {\n console.error(`Failed to install: ${result.error}`);\n process.exit(1);\n }\n break;\n }\n \n case 'list':\n case 'ls': {\n const categoryArg = rest[0]?.toLowerCase();\n \n // If a category is specified, show skills in that category\n if (categoryArg) {\n if (categoryArg === 'categories' || categoryArg === 'all') {\n // Show all available categories\n const categories = getSkillCategories();\n console.log('');\n console.log('Available Skill Categories:');\n console.log('');\n for (const cat of categories) {\n console.log(` ${cat.name.padEnd(15)} ${cat.count} skills`);\n }\n console.log('');\n console.log('View skills in a category:');\n console.log(' trie skills list <category>');\n console.log('');\n console.log('Browse all skills: https://skills.sh');\n return;\n }\n \n const categorySkills = getSkillsByCategory(categoryArg);\n if (categorySkills.length === 0) {\n const categories = getSkillCategories();\n console.log(`Unknown category: ${categoryArg}`);\n console.log('');\n console.log('Available categories:');\n for (const cat of categories) {\n console.log(` ${cat.name}`);\n }\n return;\n }\n \n console.log('');\n console.log(`${categoryArg.charAt(0).toUpperCase() + categoryArg.slice(1)} Skills (${categorySkills.length}):`);\n console.log('');\n for (const skill of categorySkills) {\n console.log(` trie skills add ${skill}`);\n }\n console.log('');\n console.log('Install any skill with: trie skills add <source> <name>');\n console.log('Browse all skills: https://skills.sh');\n return;\n }\n \n // No category - show installed skills\n const skills = await listInstalledSkills();\n const state = await loadContextState();\n \n if (skills.length === 0) {\n console.log('');\n console.log('No skills installed.');\n console.log('');\n console.log('Install a skill:');\n console.log(' trie skills add vercel-labs/agent-skills react-best-practices');\n console.log('');\n console.log('Explore skill categories:');\n const categories = getSkillCategories();\n for (const cat of categories.slice(0, 5)) {\n console.log(` trie skills list ${cat.name.padEnd(15)} # ${cat.count} skills`);\n }\n console.log(' trie skills list categories # see all');\n console.log('');\n console.log('Browse all skills: https://skills.sh');\n return;\n }\n \n console.log('');\n console.log(`Installed Skills (${skills.length}):`);\n console.log('');\n \n for (const skill of skills) {\n const record = state.skills?.[skill.name];\n const usage = record ? `applied ${record.timesApplied}x` : 'not yet applied';\n console.log(` ${skill.name} (${usage})`);\n console.log(` ${skill.description}`);\n console.log(` Source: ${skill.installedFrom}`);\n console.log('');\n }\n \n console.log('These skills are applied by the skill-review agent during scans.');\n console.log('');\n console.log('Explore more: trie skills list categories');\n break;\n }\n \n case 'remove':\n case 'rm':\n case 'uninstall': {\n if (!rest[0]) {\n console.log('Usage: trie skills remove <skill-name>');\n return;\n }\n \n const removed = await removeSkill(rest[0]);\n if (removed) {\n console.log(`Removed: ${rest[0]}`);\n } else {\n console.error(`Skill not found: ${rest[0]}`);\n process.exit(1);\n }\n break;\n }\n \n case 'suggest':\n case 'recommended': {\n const workDir = getWorkingDirectory(undefined, true);\n const stack = await detectStack(workDir);\n \n if (stack.suggestedSkills.length === 0) {\n console.log('');\n console.log('No specific skill recommendations for your stack.');\n console.log('');\n console.log('Browse all skills:');\n console.log(' trie skills list categories');\n console.log(' https://skills.sh');\n return;\n }\n \n console.log('');\n console.log('Suggested Skills (based on your stack):');\n console.log('');\n \n if (stack.framework) console.log(` Detected: ${stack.framework}`);\n if (stack.language) console.log(` Language: ${stack.language}`);\n if (stack.database) console.log(` Database: ${stack.database}`);\n console.log('');\n \n for (const skill of stack.suggestedSkills) {\n console.log(` trie skills add ${skill}`);\n }\n \n console.log('');\n console.log('Install any skill with: trie skills add <source> <name>');\n console.log('Browse all skills: https://skills.sh');\n break;\n }\n \n case 'info': {\n if (!rest[0]) {\n console.log('Usage: trie skills info <skill-name>');\n return;\n }\n \n const skills = await listInstalledSkills();\n const skill = skills.find(s => s.name === rest[0]);\n \n if (!skill) {\n console.error(`Skill not found: ${rest[0]}`);\n process.exit(1);\n return;\n }\n \n const state = await loadContextState();\n const record = state.skills?.[skill.name];\n \n console.log('');\n console.log(`Skill: ${skill.name}`);\n console.log(`Description: ${skill.description}`);\n console.log(`Path: ${skill.path}`);\n console.log(`Source: ${skill.installedFrom}`);\n console.log(`Installed: ${new Date(skill.installedAt).toLocaleString()}`);\n \n if (record) {\n console.log(`Times Applied: ${record.timesApplied}`);\n console.log(`Applied By: ${record.appliedBy.join(', ') || 'none'}`);\n if (record.lastApplied) {\n console.log(`Last Applied: ${new Date(record.lastApplied).toLocaleString()}`);\n }\n } else {\n console.log('Times Applied: 0');\n }\n break;\n }\n \n default: {\n const categories = getSkillCategories();\n console.log(`\nSkills - Reusable capabilities from skills.sh\n\nSkills are NOT agents - they are knowledge/instructions that the\nskill-review agent applies during code review.\n\nCommands:\n trie skills suggest Show skills for your stack\n trie skills add <source> [name] Install a skill\n trie skills list List installed skills\n trie skills list <category> Browse skills by category\n trie skills list categories Show all categories\n trie skills info <name> Show skill details\n trie skills remove <name> Uninstall a skill\n\nExamples:\n trie skills add vercel-labs/agent-skills react-best-practices\n trie skills add anthropics/skills frontend-design\n trie skills add expo/skills upgrading-expo\n\nCategories (${categories.length} total, ${Object.values(SKILL_CATEGORIES).flat().length}+ skills):\n ${categories.map(c => `${c.name} (${c.count})`).join(', ')}\n\nHow it works:\n 1. You install skills (capabilities)\n 2. The skill-review agent applies them during 'trie scan'\n 3. Usage is tracked in your project context\n\nBrowse all skills: https://skills.sh\n `);\n }\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 guardian 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 the guardian (watches + nudges as you code)\n 3. trie tell \"what broke\" # Teach Trie about past incidents\n\nThe guardian agent 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(` Total Issues: ${stats.totalIssues}`);\n console.log(` Resolved: ${stats.resolvedCount}`);\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 By Severity:');\n for (const [severity, count] of Object.entries(stats.issuesBySeverity)) {\n console.log(` ${severity}: ${count}`);\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 | Health | 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.healthScore}% | ${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, writeFile } 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 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 // TODO: Add more fix types\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 * Apply a single fix to a file\n */\nasync function applyFix(fix: AutoFixAction): Promise<boolean> {\n try {\n if (!existsSync(fix.file)) {\n console.error(pc.red(`File not found: ${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 console.error(pc.red(`Invalid line number: ${fix.line}`));\n return false;\n }\n \n const lineIndex = fix.line - 1;\n const originalLine = lines[lineIndex];\n \n // Apply the fix based on type\n let newContent: string;\n \n if (fix.type === 'remove-console-log' || fix.type === 'remove-debugger') {\n // Remove the entire line\n lines.splice(lineIndex, 1);\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 console.error(pc.red(`Unknown fix type: ${fix.type}`));\n return false;\n }\n \n // Write the file\n await writeFile(fix.file, newContent);\n \n console.error(pc.green(`✓ Applied fix to ${fix.file}:${fix.line}`));\n if (originalLine) {\n console.error(pc.dim(` Removed: ${originalLine.trim().slice(0, 60)}...`));\n }\n \n return true;\n \n } catch (error) {\n console.error(pc.red(`Failed to apply fix: ${error}`));\n return false;\n }\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 applyFix(fix);\n if (success) applied++;\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 applyFix(fix);\n if (success) {\n applied++;\n } else {\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 * Goal & Hypothesis CLI Commands\n * \n * Allows users to manually add goals and hypotheses while still\n * allowing the guardian 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 { getGuardianState, type Goal, type Hypothesis } from '../guardian/guardian-state.js';\n\n// ============================================================================\n// Goal Commands\n// ============================================================================\n\nexport async function handleGoalCommand(args: string[]): Promise<void> {\n const projectPath = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(projectPath);\n await guardianState.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(guardianState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listGoals(guardianState);\n break;\n \n case 'complete':\n case 'done':\n await completeGoal(guardianState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteGoal(guardianState, 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(guardianState, [subcommand, ...restArgs]);\n } else {\n printGoalHelp();\n }\n }\n}\n\nasync function addGoal(guardianState: ReturnType<typeof getGuardianState>, 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 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: 0,\n startValue: 0,\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 guardianState.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 console.error(pc.dim(`Deadline: ${deadline.toLocaleDateString()}`));\n console.error('');\n console.error(pc.cyan('The guardian will track progress and celebrate when you achieve it!'));\n}\n\nasync function listGoals(guardianState: ReturnType<typeof getGuardianState>): Promise<void> {\n const goals = guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllGoals();\n const goal = goals.find(g => g.id === goalId || g.id.includes(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllGoals();\n const goal = goals.find(g => g.id === goalId || g.id.includes(goalId));\n \n if (!goal) {\n console.error(pc.red(`Goal not found: ${goalId}`));\n return;\n }\n \n await guardianState.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 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.dim('░'.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 guardianState = getGuardianState(projectPath);\n await guardianState.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(guardianState, restArgs);\n break;\n \n case 'list':\n case 'ls':\n await listHypotheses(guardianState);\n break;\n \n case 'validate':\n await validateHypothesis(guardianState, restArgs[0]);\n break;\n \n case 'invalidate':\n await invalidateHypothesis(guardianState, restArgs[0]);\n break;\n \n case 'delete':\n case 'rm':\n await deleteHypothesis(guardianState, restArgs[0]);\n break;\n \n default:\n if (subcommand && !subcommand.startsWith('-')) {\n // Treat as hypothesis statement shorthand\n await addHypothesis(guardianState, [subcommand, ...restArgs]);\n } else {\n printHypothesisHelp();\n }\n }\n}\n\nasync function addHypothesis(guardianState: ReturnType<typeof getGuardianState>, 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.5, // Start neutral\n status: 'testing',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria,\n category,\n };\n \n await guardianState.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: 50% | Category: ${category}`));\n console.error('');\n console.error(pc.cyan('The guardian will collect evidence and update confidence over time.'));\n console.error(pc.dim(`Test criteria: ${testCriteria}`));\n}\n\nasync function listHypotheses(guardianState: ReturnType<typeof getGuardianState>): Promise<void> {\n const hypotheses = guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllHypotheses();\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.includes(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllHypotheses();\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.includes(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await guardianState.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(guardianState: ReturnType<typeof getGuardianState>, 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 = guardianState.getAllHypotheses();\n const hypo = hypotheses.find(h => h.id === hypoId || h.id.includes(hypoId));\n \n if (!hypo) {\n console.error(pc.red(`Hypothesis not found: ${hypoId}`));\n return;\n }\n \n await guardianState.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 guardian 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 '../guardian/gotcha-predictor.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 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 } catch (error) {\n const friendly = formatFriendlyError(error);\n console.error(friendly.userMessage);\n }\n}\n","import { LearningEngine } from '../guardian/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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,SAAS,QAAAA,OAAM,eAAe;AACvC,SAAS,cAAAC,aAAY,oBAAoB;AACzC,SAAS,qBAAqB;;;ACD9B,eAAsB,oBAAoB,MAA+B;AACvE,QAAM,CAAC,KAAK,GAAG,IAAI,IAAI;AAEvB,UAAQ,KAAK;AAAA,IACX,KAAK;AAAA,IACL,KAAK,WAAW;AACd,UAAI,CAAC,KAAK,CAAC,GAAG;AACZ,gBAAQ,IAAI,kDAAkD;AAC9D,gBAAQ,IAAI,EAAE;AACd,gBA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MAAM;AAC1B,QAAM,QAAQ,QAAQ,KAAK,CAAC;AAC5B,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,UAAM,EAAE,aAAa,IAAI,UAAQ,IAAI;AACrC,UAAM,YAAY,aAAa,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","existsSync","fs","path","result","parseArgs","pc","resolve","pc","applied","pc","pc","path","path","path","path","fs","path","path","fs","existsSync","pc","showHelp","existsSync","picocolors","readFile","writeFile","existsSync","picocolors","picocolors","writeFile","existsSync","readFile","__filename","__dirname","showHelp","join","existsSync"]}
|