@triedotdev/mcp 1.0.83 → 1.0.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +622 -0
- package/dist/{chunk-W4SQE6F7.js → chunk-4U3DNRUA.js} +4 -4
- package/dist/{chunk-YHQYOD6M.js → chunk-4UVTFL2T.js} +7 -8
- package/dist/{chunk-YHQYOD6M.js.map → chunk-4UVTFL2T.js.map} +1 -1
- package/dist/{chunk-WGECLUDQ.js → chunk-7UPNCM66.js} +111 -23
- package/dist/chunk-7UPNCM66.js.map +1 -0
- package/dist/{chunk-7OVM6KEY.js → chunk-DXBYHIA7.js} +7 -7
- package/dist/{chunk-IDDEVC3M.js → chunk-KERQ4JXR.js} +12 -12
- package/dist/{chunk-IDDEVC3M.js.map → chunk-KERQ4JXR.js.map} +1 -1
- package/dist/{chunk-EWIEXQES.js → chunk-KGVKUMFO.js} +2 -2
- package/dist/{chunk-U5P3O5G5.js → chunk-TDWPEV3N.js} +3 -3
- package/dist/{chunk-B7CLAOEK.js → chunk-THJKXIMJ.js} +5 -4
- package/dist/chunk-THJKXIMJ.js.map +1 -0
- package/dist/{chunk-75J4HQTD.js → chunk-X3E6ISEG.js} +2 -2
- package/dist/{chunk-CGALCUZE.js → chunk-Z6JP2QQU.js} +3 -3
- package/dist/cli/main.js +21 -15
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +9 -9
- package/dist/{goal-manager-NHPEUWFY.js → goal-manager-JTM6MOZG.js} +4 -4
- package/dist/{guardian-agent-GWYDNLWC.js → guardian-agent-RIF7XBFL.js} +7 -7
- package/dist/index.js +18 -18
- package/dist/index.js.map +1 -1
- package/dist/{issue-store-RKJVOKSJ.js → issue-store-AZ3D4LOG.js} +2 -2
- package/dist/workers/agent-worker.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-B7CLAOEK.js.map +0 -1
- package/dist/chunk-WGECLUDQ.js.map +0 -1
- /package/dist/{chunk-W4SQE6F7.js.map → chunk-4U3DNRUA.js.map} +0 -0
- /package/dist/{chunk-7OVM6KEY.js.map → chunk-DXBYHIA7.js.map} +0 -0
- /package/dist/{chunk-EWIEXQES.js.map → chunk-KGVKUMFO.js.map} +0 -0
- /package/dist/{chunk-U5P3O5G5.js.map → chunk-TDWPEV3N.js.map} +0 -0
- /package/dist/{chunk-75J4HQTD.js.map → chunk-X3E6ISEG.js.map} +0 -0
- /package/dist/{chunk-CGALCUZE.js.map → chunk-Z6JP2QQU.js.map} +0 -0
- /package/dist/{goal-manager-NHPEUWFY.js.map → goal-manager-JTM6MOZG.js.map} +0 -0
- /package/dist/{guardian-agent-GWYDNLWC.js.map → guardian-agent-RIF7XBFL.js.map} +0 -0
- /package/dist/{issue-store-RKJVOKSJ.js.map → issue-store-AZ3D4LOG.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/checkpoint.ts","../src/utils/autonomy-config.ts","../src/types/autonomy.ts","../src/agent/perceive.ts","../src/agent/diff-analyzer.ts","../src/agent/risk-scorer.ts","../src/agent/pattern-matcher.ts","../src/agent/reason.ts","../src/bootstrap/files.ts","../src/utils/errors.ts","../src/context/sync.ts","../src/context/incident-index.ts","../src/context/file-trie.ts","../src/agent/confidence.ts","../src/agent/pattern-discovery.ts","../src/agent/learning.ts","../src/guardian/learning-engine.ts","../src/ingest/linear-ingester.ts"],"sourcesContent":["/**\n * Checkpoint CLI\n * \n * Save your work context to .trie/ without running a full scan.\n * Think of it as a quick save - captures what you're working on.\n */\n\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile, readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface Checkpoint {\n id: string;\n timestamp: string;\n message?: string;\n files: string[];\n notes?: string;\n createdBy: 'cli' | 'mcp';\n}\n\nexport interface CheckpointLog {\n checkpoints: Checkpoint[];\n lastCheckpoint?: string;\n}\n\n/**\n * Save a checkpoint\n */\nexport async function saveCheckpoint(options: {\n message?: string;\n files?: string[];\n notes?: string;\n workDir?: string;\n createdBy?: 'cli' | 'mcp';\n}): Promise<Checkpoint> {\n const workDir = options.workDir || getWorkingDirectory(undefined, true);\n const trieDir = join(workDir, '.trie');\n const checkpointPath = join(trieDir, 'checkpoints.json');\n \n await mkdir(trieDir, { recursive: true });\n \n // Load existing checkpoints\n let log: CheckpointLog = { checkpoints: [] };\n try {\n if (existsSync(checkpointPath)) {\n log = JSON.parse(await readFile(checkpointPath, 'utf-8'));\n }\n } catch {\n log = { checkpoints: [] };\n }\n \n // Create new checkpoint\n const checkpoint: Checkpoint = {\n id: `cp-${Date.now().toString(36)}`,\n timestamp: new Date().toISOString(),\n files: options.files || [],\n createdBy: options.createdBy || 'cli',\n };\n if (options.message) checkpoint.message = options.message;\n if (options.notes) checkpoint.notes = options.notes;\n \n // Add to log\n log.checkpoints.push(checkpoint);\n log.lastCheckpoint = checkpoint.id;\n \n // Keep last 50 checkpoints\n if (log.checkpoints.length > 50) {\n log.checkpoints = log.checkpoints.slice(-50);\n }\n \n // Save\n await writeFile(checkpointPath, JSON.stringify(log, null, 2));\n \n // Also update AGENTS.md with checkpoint note\n await updateAgentsMdWithCheckpoint(checkpoint, workDir);\n \n return checkpoint;\n}\n\n/**\n * List checkpoints\n */\nexport async function listCheckpoints(workDir?: string): Promise<Checkpoint[]> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const checkpointPath = join(dir, '.trie', 'checkpoints.json');\n \n try {\n if (existsSync(checkpointPath)) {\n const log: CheckpointLog = JSON.parse(await readFile(checkpointPath, 'utf-8'));\n return log.checkpoints;\n }\n } catch {\n // File doesn't exist or is corrupted\n }\n \n return [];\n}\n\n/**\n * Get the last checkpoint\n */\nexport async function getLastCheckpoint(workDir?: string): Promise<Checkpoint | null> {\n const checkpoints = await listCheckpoints(workDir);\n const last = checkpoints[checkpoints.length - 1];\n return last ?? null;\n}\n\n/**\n * Update AGENTS.md with checkpoint info\n */\nasync function updateAgentsMdWithCheckpoint(checkpoint: Checkpoint, workDir: string): Promise<void> {\n const agentsPath = join(workDir, '.trie', 'AGENTS.md');\n \n let content = '';\n try {\n if (existsSync(agentsPath)) {\n content = await readFile(agentsPath, 'utf-8');\n }\n } catch {\n content = '';\n }\n \n // Find or create checkpoint section\n const checkpointSection = `\n## Last Checkpoint\n\n- **ID:** ${checkpoint.id}\n- **Time:** ${checkpoint.timestamp}\n${checkpoint.message ? `- **Message:** ${checkpoint.message}` : ''}\n${checkpoint.files.length > 0 ? `- **Files:** ${checkpoint.files.length} files` : ''}\n${checkpoint.notes ? `- **Notes:** ${checkpoint.notes}` : ''}\n`;\n \n // Replace existing checkpoint section or append\n const checkpointRegex = /## Last Checkpoint[\\s\\S]*?(?=\\n## |\\n---|\\Z)/;\n if (checkpointRegex.test(content)) {\n content = content.replace(checkpointRegex, checkpointSection.trim());\n } else {\n content = content.trim() + '\\n\\n' + checkpointSection.trim() + '\\n';\n }\n \n await writeFile(agentsPath, content);\n}\n\n/**\n * CLI handler for checkpoint command\n */\nexport async function handleCheckpointCommand(args: string[]): Promise<void> {\n const subcommand = args[0] || 'save';\n \n switch (subcommand) {\n case 'save': {\n // Parse options\n let message: string | undefined;\n let notes: string | undefined;\n const files: string[] = [];\n \n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n if (arg === '-m' || arg === '--message') {\n message = args[++i] ?? '';\n } else if (arg === '-n' || arg === '--notes') {\n notes = args[++i] ?? '';\n } else if (arg === '-f' || arg === '--file') {\n const file = args[++i];\n if (file) files.push(file);\n } else if (arg && !arg.startsWith('-')) {\n // Treat as message if no flag\n message = arg;\n }\n }\n \n const opts: { message?: string; files?: string[]; notes?: string } = { files };\n if (message) opts.message = message;\n if (notes) opts.notes = notes;\n const checkpoint = await saveCheckpoint(opts);\n \n console.log('\\n Checkpoint saved\\n');\n console.log(` ID: ${checkpoint.id}`);\n console.log(` Time: ${checkpoint.timestamp}`);\n if (checkpoint.message) {\n console.log(` Message: ${checkpoint.message}`);\n }\n if (checkpoint.files.length > 0) {\n console.log(` Files: ${checkpoint.files.join(', ')}`);\n }\n console.log('\\n Context saved to .trie/\\n');\n break;\n }\n \n case 'list': {\n const checkpoints = await listCheckpoints();\n \n if (checkpoints.length === 0) {\n console.log('\\n No checkpoints yet. Run `trie checkpoint` to save one.\\n');\n return;\n }\n \n console.log('\\n Checkpoints:\\n');\n for (const cp of checkpoints.slice(-10).reverse()) {\n const date = new Date(cp.timestamp).toLocaleString();\n console.log(` ${cp.id} ${date} ${cp.message || '(no message)'}`);\n }\n console.log('');\n break;\n }\n \n case 'last': {\n const checkpoint = await getLastCheckpoint();\n \n if (!checkpoint) {\n console.log('\\n No checkpoints yet. Run `trie checkpoint` to save one.\\n');\n return;\n }\n \n console.log('\\n Last Checkpoint:\\n');\n console.log(` ID: ${checkpoint.id}`);\n console.log(` Time: ${new Date(checkpoint.timestamp).toLocaleString()}`);\n if (checkpoint.message) {\n console.log(` Message: ${checkpoint.message}`);\n }\n if (checkpoint.notes) {\n console.log(` Notes: ${checkpoint.notes}`);\n }\n if (checkpoint.files.length > 0) {\n console.log(` Files: ${checkpoint.files.join(', ')}`);\n }\n console.log('');\n break;\n }\n \n default:\n console.log(`\n Usage: trie checkpoint [command] [options]\n\n Commands:\n save [message] Save a checkpoint (default)\n list List recent checkpoints\n last Show the last checkpoint\n\n Options:\n -m, --message Checkpoint message\n -n, --notes Additional notes\n -f, --file File to include (can be repeated)\n\n Examples:\n trie checkpoint \"finished auth flow\"\n trie checkpoint save -m \"WIP: payment integration\" -n \"needs testing\"\n trie checkpoint list\n`);\n }\n}\n","/**\n * Autonomy Configuration Loader\n * \n * Loads, saves, and manages autonomy settings from .trie/config.json\n */\n\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport type { \n AutonomyConfig, \n IssueOccurrence,\n AutoFixAction,\n PushBlockResult \n} from '../types/autonomy.js';\nimport { DEFAULT_AUTONOMY_CONFIG } from '../types/autonomy.js';\nimport { createHash } from 'crypto';\n\n// ============================================================================\n// Config Loading/Saving\n// ============================================================================\n\n/**\n * Load autonomy config from .trie/config.json\n */\nexport async function loadAutonomyConfig(projectPath: string): Promise<AutonomyConfig> {\n const configPath = join(projectPath, '.trie', 'config.json');\n \n try {\n if (!existsSync(configPath)) {\n return { ...DEFAULT_AUTONOMY_CONFIG };\n }\n \n const content = await readFile(configPath, 'utf-8');\n const config = JSON.parse(content);\n \n // Merge with defaults to ensure all fields exist\n return mergeWithDefaults(config.autonomy || {});\n } catch (error) {\n console.error('Failed to load autonomy config:', error);\n return { ...DEFAULT_AUTONOMY_CONFIG };\n }\n}\n\n/**\n * Save autonomy config to .trie/config.json\n */\nexport async function saveAutonomyConfig(\n projectPath: string, \n autonomyConfig: Partial<AutonomyConfig>\n): Promise<void> {\n const configPath = join(projectPath, '.trie', 'config.json');\n const trieDir = join(projectPath, '.trie');\n \n try {\n // Ensure .trie directory exists\n if (!existsSync(trieDir)) {\n await mkdir(trieDir, { recursive: true });\n }\n \n // Load existing config\n let fullConfig: Record<string, unknown> = {};\n if (existsSync(configPath)) {\n const content = await readFile(configPath, 'utf-8');\n fullConfig = JSON.parse(content);\n }\n \n // Merge autonomy config\n fullConfig.autonomy = mergeWithDefaults(autonomyConfig);\n \n // Save atomically\n const tempPath = configPath + '.tmp';\n await writeFile(tempPath, JSON.stringify(fullConfig, null, 2));\n await writeFile(configPath, JSON.stringify(fullConfig, null, 2));\n \n } catch (error) {\n console.error('Failed to save autonomy config:', error);\n throw error;\n }\n}\n\n/**\n * Merge partial config with defaults\n */\nfunction mergeWithDefaults(partial: Partial<AutonomyConfig>): AutonomyConfig {\n return {\n level: partial.level ?? DEFAULT_AUTONOMY_CONFIG.level,\n autoCheck: {\n ...DEFAULT_AUTONOMY_CONFIG.autoCheck,\n ...(partial.autoCheck || {}),\n },\n autoFix: {\n ...DEFAULT_AUTONOMY_CONFIG.autoFix,\n ...(partial.autoFix || {}),\n },\n pushBlocking: {\n ...DEFAULT_AUTONOMY_CONFIG.pushBlocking,\n ...(partial.pushBlocking || {}),\n },\n progressiveEscalation: {\n ...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation,\n ...(partial.progressiveEscalation || {}),\n thresholds: {\n ...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation.thresholds,\n ...(partial.progressiveEscalation?.thresholds || {}),\n },\n },\n };\n}\n\n// ============================================================================\n// Issue Occurrence Tracking (for progressive escalation)\n// ============================================================================\n\nconst occurrenceCache = new Map<string, Map<string, IssueOccurrence>>();\n\n/**\n * Get occurrence tracker for a project\n */\nasync function getOccurrences(projectPath: string): Promise<Map<string, IssueOccurrence>> {\n if (occurrenceCache.has(projectPath)) {\n return occurrenceCache.get(projectPath)!;\n }\n \n const occurrencesPath = join(projectPath, '.trie', 'memory', 'occurrences.json');\n const occurrences = new Map<string, IssueOccurrence>();\n \n try {\n if (existsSync(occurrencesPath)) {\n const content = await readFile(occurrencesPath, 'utf-8');\n const data = JSON.parse(content);\n for (const [hash, occ] of Object.entries(data)) {\n occurrences.set(hash, occ as IssueOccurrence);\n }\n }\n } catch {\n // Start fresh\n }\n \n occurrenceCache.set(projectPath, occurrences);\n return occurrences;\n}\n\n/**\n * Save occurrences to disk\n */\nasync function saveOccurrences(projectPath: string): Promise<void> {\n const occurrences = occurrenceCache.get(projectPath);\n if (!occurrences) return;\n \n const occurrencesPath = join(projectPath, '.trie', 'memory', 'occurrences.json');\n const memoryDir = join(projectPath, '.trie', 'memory');\n \n try {\n if (!existsSync(memoryDir)) {\n await mkdir(memoryDir, { recursive: true });\n }\n \n const data: Record<string, IssueOccurrence> = {};\n for (const [hash, occ] of occurrences.entries()) {\n data[hash] = occ;\n }\n \n await writeFile(occurrencesPath, JSON.stringify(data, null, 2));\n } catch (error) {\n console.error('Failed to save occurrences:', error);\n }\n}\n\n/**\n * Create a hash for an issue (for deduplication)\n */\nexport function createIssueHash(file: string, line: number | undefined, issueType: string): string {\n const input = `${file}:${line || 0}:${issueType}`;\n return createHash('md5').update(input).digest('hex').slice(0, 12);\n}\n\n/**\n * Track an issue occurrence\n */\nexport async function trackIssueOccurrence(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string,\n config: AutonomyConfig\n): Promise<IssueOccurrence> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n const now = Date.now();\n \n let occurrence = occurrences.get(hash);\n \n if (occurrence) {\n // Check if within time window\n const windowMs = config.progressiveEscalation.windowMs;\n if (now - occurrence.firstSeen > windowMs) {\n // Reset if outside window\n occurrence = {\n hash,\n firstSeen: now,\n lastSeen: now,\n count: 1,\n escalationLevel: 'suggest',\n notified: false,\n bypassed: false,\n bypassHistory: occurrence.bypassHistory, // Keep bypass history\n };\n } else {\n // Increment within window\n occurrence.lastSeen = now;\n occurrence.count++;\n \n // Update escalation level\n const thresholds = config.progressiveEscalation.thresholds;\n if (occurrence.count >= thresholds.block) {\n occurrence.escalationLevel = 'block';\n } else if (occurrence.count >= thresholds.escalate) {\n occurrence.escalationLevel = 'escalate';\n } else if (occurrence.count >= thresholds.autoCheck) {\n occurrence.escalationLevel = 'autoCheck';\n }\n }\n } else {\n // New occurrence\n occurrence = {\n hash,\n firstSeen: now,\n lastSeen: now,\n count: 1,\n escalationLevel: 'suggest',\n notified: false,\n bypassed: false,\n bypassHistory: [],\n };\n }\n \n occurrences.set(hash, occurrence);\n await saveOccurrences(projectPath);\n \n return occurrence;\n}\n\n/**\n * Get escalation level for an issue\n */\nexport async function getEscalationLevel(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string\n): Promise<IssueOccurrence['escalationLevel']> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n \n const occurrence = occurrences.get(hash);\n return occurrence?.escalationLevel ?? 'suggest';\n}\n\n/**\n * Record a bypass\n */\nexport async function recordBypass(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string,\n method: string,\n reason?: string\n): Promise<void> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n \n const occurrence = occurrences.get(hash);\n if (occurrence) {\n occurrence.bypassed = true;\n occurrence.bypassHistory.push({\n timestamp: Date.now(),\n method,\n ...(reason !== undefined ? { reason } : {}),\n });\n await saveOccurrences(projectPath);\n }\n}\n\n// ============================================================================\n// Auto-fix Helpers\n// ============================================================================\n\n/**\n * Check if a fix should be auto-applied based on config\n */\nexport function shouldAutoFix(\n fix: AutoFixAction,\n config: AutonomyConfig\n): boolean {\n if (!config.autoFix.enabled) {\n return false;\n }\n \n // Check if category is allowed\n const allowedCategories = config.autoFix.categories as string[];\n if (!allowedCategories.includes(fix.category) && \n !allowedCategories.includes('all')) {\n return false;\n }\n \n // Check if specific fix type is allowed\n if (config.autoFix.allowedFixTypes.length > 0 &&\n !config.autoFix.allowedFixTypes.includes(fix.type)) {\n return false;\n }\n \n // Check confidence threshold (require high confidence for auto-fix)\n if (fix.confidence < 0.9) {\n return false;\n }\n \n return true;\n}\n\n/**\n * Group fixes by file for batch application\n */\nexport function groupFixesByFile(fixes: AutoFixAction[]): Map<string, AutoFixAction[]> {\n const grouped = new Map<string, AutoFixAction[]>();\n \n for (const fix of fixes) {\n const existing = grouped.get(fix.file) || [];\n existing.push(fix);\n grouped.set(fix.file, existing);\n }\n \n return grouped;\n}\n\n// ============================================================================\n// Push Blocking Helpers\n// ============================================================================\n\n/**\n * Check if push should be blocked\n */\nexport function shouldBlockPush(\n issues: Array<{ severity: string; file: string; line?: number; issue: string }>,\n config: AutonomyConfig\n): PushBlockResult {\n if (!config.pushBlocking.enabled) {\n return {\n blocked: false,\n blockingIssues: [],\n bypassed: false,\n };\n }\n \n // Find blocking issues\n const blockingIssues = issues.filter(issue => \n config.pushBlocking.blockOn.includes(issue.severity as 'critical' | 'serious' | 'moderate')\n );\n \n if (blockingIssues.length === 0) {\n return {\n blocked: false,\n blockingIssues: [],\n bypassed: false,\n };\n }\n \n // Check for bypass\n const envBypass = process.env.TRIE_BYPASS === '1' || process.env.TRIE_BYPASS === 'true';\n \n if (envBypass && config.pushBlocking.allowBypass) {\n return {\n blocked: false,\n blockingIssues,\n bypassed: true,\n bypassMethod: 'env',\n };\n }\n \n // Build bypass instructions\n const bypassInstructions = buildBypassInstructions(config);\n \n return {\n blocked: true,\n reason: `${blockingIssues.length} ${blockingIssues[0]?.severity || 'critical'} issue(s) must be fixed before pushing`,\n blockingIssues,\n bypassInstructions,\n bypassed: false,\n };\n}\n\n/**\n * Build bypass instructions based on config\n */\nfunction buildBypassInstructions(config: AutonomyConfig): string {\n const instructions: string[] = [];\n \n if (config.pushBlocking.bypassMethods.includes('env')) {\n instructions.push('• Set TRIE_BYPASS=1 to bypass: TRIE_BYPASS=1 git push');\n }\n \n if (config.pushBlocking.bypassMethods.includes('flag')) {\n instructions.push('• Use --no-verify flag: git push --no-verify');\n }\n \n if (config.pushBlocking.bypassMethods.includes('confirm')) {\n instructions.push('• Run: trie bypass --confirm to bypass this push');\n }\n \n return instructions.join('\\n');\n}\n\n// ============================================================================\n// Singleton Config Cache\n// ============================================================================\n\nconst configCache = new Map<string, { config: AutonomyConfig; loadedAt: number }>();\nconst CACHE_TTL = 60000; // 1 minute\n\n/**\n * Get autonomy config with caching\n */\nexport async function getAutonomyConfig(projectPath: string): Promise<AutonomyConfig> {\n const cached = configCache.get(projectPath);\n \n if (cached && Date.now() - cached.loadedAt < CACHE_TTL) {\n return cached.config;\n }\n \n const config = await loadAutonomyConfig(projectPath);\n configCache.set(projectPath, { config, loadedAt: Date.now() });\n \n return config;\n}\n\n/**\n * Clear config cache (for testing or after config changes)\n */\nexport function clearConfigCache(): void {\n configCache.clear();\n occurrenceCache.clear();\n}\n","/**\n * Autonomy Configuration Types\n * \n * Controls how autonomous Trie behaves:\n * - Auto-check: Run full checks when issues detected\n * - Auto-fix: Apply fixes with human confirmation\n * - Push blocking: Block git push on critical issues\n * - Progressive escalation: Escalate based on occurrence count\n */\n\n/**\n * Overall autonomy level\n */\nexport type AutonomyLevel = \n | 'passive' // Only report, never act\n | 'suggest' // Suggest actions, don't execute\n | 'proactive' // Auto-check, ask before fixing\n | 'aggressive'; // Auto-check, auto-fix trivial, block on critical\n\n/**\n * Auto-check configuration\n */\nexport interface AutoCheckConfig {\n /** Enable auto-running full checks */\n enabled: boolean;\n /** Issue count threshold to trigger auto-check */\n threshold: number;\n /** Always trigger on critical issues */\n onCritical: boolean;\n /** Cooldown between auto-checks (ms) */\n cooldownMs: number;\n}\n\n/**\n * Auto-fix configuration\n */\nexport interface AutoFixConfig {\n /** Enable auto-fix suggestions */\n enabled: boolean;\n /** Always ask user before applying fixes (human-in-the-loop) */\n askFirst: boolean;\n /** Categories of fixes to auto-apply */\n categories: ('trivial' | 'safe' | 'moderate' | 'all')[];\n /** Specific fix types to auto-apply */\n allowedFixTypes: string[];\n}\n\n/**\n * Push blocking configuration\n */\nexport interface PushBlockingConfig {\n /** Enable push blocking */\n enabled: boolean;\n /** Allow user to bypass with flag */\n allowBypass: boolean;\n /** Severities that trigger blocking */\n blockOn: ('critical' | 'serious' | 'moderate')[];\n /** Bypass methods */\n bypassMethods: ('env' | 'flag' | 'confirm')[];\n /** Log bypasses for audit */\n logBypasses: boolean;\n}\n\n/**\n * Progressive escalation thresholds\n */\nexport interface ProgressiveEscalationConfig {\n /** Enable progressive escalation */\n enabled: boolean;\n /** Thresholds for different actions */\n thresholds: {\n /** First occurrence: suggest fix */\n suggest: number;\n /** N occurrences: auto-run full check */\n autoCheck: number;\n /** N occurrences: escalate to Slack/email */\n escalate: number;\n /** N occurrences: block until fixed */\n block: number;\n };\n /** Time window for counting occurrences (ms) */\n windowMs: number;\n}\n\n/**\n * Full autonomy configuration\n */\nexport interface AutonomyConfig {\n /** Overall autonomy level (can be overridden by specific settings) */\n level: AutonomyLevel;\n /** Auto-check settings */\n autoCheck: AutoCheckConfig;\n /** Auto-fix settings */\n autoFix: AutoFixConfig;\n /** Push blocking settings */\n pushBlocking: PushBlockingConfig;\n /** Progressive escalation settings */\n progressiveEscalation: ProgressiveEscalationConfig;\n}\n\n/**\n * Default autonomy configuration - proactive but safe\n */\nexport const DEFAULT_AUTONOMY_CONFIG: AutonomyConfig = {\n level: 'proactive',\n autoCheck: {\n enabled: true,\n threshold: 5,\n onCritical: true,\n cooldownMs: 30000, // 30 seconds\n },\n autoFix: {\n enabled: true,\n askFirst: true, // Always ask (human-in-the-loop)\n categories: ['trivial', 'safe'],\n allowedFixTypes: [\n 'remove-console-log',\n 'remove-unused-import',\n 'add-missing-await',\n 'fix-typo',\n ],\n },\n pushBlocking: {\n enabled: true,\n allowBypass: true,\n blockOn: ['critical'],\n bypassMethods: ['env', 'flag', 'confirm'],\n logBypasses: true,\n },\n progressiveEscalation: {\n enabled: true,\n thresholds: {\n suggest: 1,\n autoCheck: 3,\n escalate: 5,\n block: 10,\n },\n windowMs: 24 * 60 * 60 * 1000, // 24 hours\n },\n};\n\n/**\n * Issue occurrence tracking for progressive escalation\n */\nexport interface IssueOccurrence {\n /** Issue hash (file + line + type) */\n hash: string;\n /** First seen timestamp */\n firstSeen: number;\n /** Last seen timestamp */\n lastSeen: number;\n /** Total occurrence count */\n count: number;\n /** Current escalation level */\n escalationLevel: 'suggest' | 'autoCheck' | 'escalate' | 'block';\n /** Whether user has been notified at current level */\n notified: boolean;\n /** Whether issue has been bypassed */\n bypassed: boolean;\n /** Bypass history */\n bypassHistory: Array<{\n timestamp: number;\n method: string;\n reason?: string;\n }>;\n}\n\n/**\n * Auto-fix action\n */\nexport interface AutoFixAction {\n /** Unique ID for this fix */\n id: string;\n /** File to fix */\n file: string;\n /** Line number */\n line?: number;\n /** Original code */\n original: string;\n /** Fixed code */\n fixed: string;\n /** Type of fix */\n type: string;\n /** Category of fix */\n category: 'trivial' | 'safe' | 'moderate' | 'risky';\n /** Description of what the fix does */\n description: string;\n /** Confidence in the fix (0-1) */\n confidence: number;\n}\n\n/**\n * Push block result\n */\nexport interface PushBlockResult {\n /** Whether push is blocked */\n blocked: boolean;\n /** Reason for blocking */\n reason?: string;\n /** Issues causing the block */\n blockingIssues: Array<{\n file: string;\n line?: number;\n severity: string;\n issue: string;\n }>;\n /** Bypass instructions */\n bypassInstructions?: string;\n /** Whether user chose to bypass */\n bypassed: boolean;\n /** Bypass method used */\n bypassMethod?: string;\n}\n","import path from 'node:path';\n\nimport { analyzeDiff, type DiffSummary } from './diff-analyzer.js';\nimport {\n getStagedChanges,\n getUncommittedChanges,\n getWorkingTreeDiff,\n type Change\n} from './git.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNode, FileNodeData } from '../context/nodes.js';\n\nexport interface PerceptionResult {\n staged: Change[];\n unstaged: Change[];\n diffSummary: DiffSummary;\n changeNodeId?: string;\n}\n\nexport async function perceiveCurrentChanges(\n projectPath: string,\n graph?: ContextGraph\n): Promise<PerceptionResult> {\n const ctxGraph = graph ?? new ContextGraph(projectPath);\n\n const [staged, unstaged] = await Promise.all([\n getStagedChanges(projectPath),\n getUncommittedChanges(projectPath)\n ]);\n\n const stagedDiff = await getWorkingTreeDiff(projectPath, true);\n const unstagedDiff = await getWorkingTreeDiff(projectPath, false);\n const combinedDiff = [stagedDiff, unstagedDiff].filter(Boolean).join('\\n');\n const diffSummary = analyzeDiff(combinedDiff);\n\n const filesTouched = new Set<string>();\n staged.forEach((c) => filesTouched.add(c.path));\n unstaged.forEach((c) => filesTouched.add(c.path));\n diffSummary.files.forEach((f) => filesTouched.add(f.filePath));\n\n const changeId = await upsertWorkingChange(ctxGraph, Array.from(filesTouched), projectPath);\n\n const result: PerceptionResult = {\n staged,\n unstaged,\n diffSummary\n };\n if (changeId) result.changeNodeId = changeId;\n return result;\n}\n\nasync function upsertWorkingChange(\n graph: ContextGraph,\n files: string[],\n projectPath: string\n): Promise<string | undefined> {\n if (files.length === 0) return undefined;\n\n const now = new Date().toISOString();\n const change = await graph.addNode('change', {\n commitHash: null,\n files,\n message: 'workspace changes',\n diff: null,\n author: null,\n timestamp: now,\n outcome: 'unknown'\n });\n\n for (const filePath of files) {\n const fileNode = await ensureFileNode(graph, filePath, projectPath);\n await graph.addEdge(change.id, fileNode.id, 'affects');\n }\n\n return change.id;\n}\n\nasync function ensureFileNode(\n graph: ContextGraph,\n filePath: string,\n projectPath: string\n): Promise<FileNode> {\n const normalized = path.resolve(projectPath, filePath);\n const existing = await graph.getNode('file', normalized);\n\n const now = new Date().toISOString();\n if (existing) {\n const data = existing.data as FileNodeData;\n await graph.updateNode('file', existing.id, {\n changeCount: (data.changeCount ?? 0) + 1,\n lastChanged: now\n });\n return (await graph.getNode('file', existing.id)) as FileNode;\n }\n\n const data: FileNodeData = {\n path: filePath,\n extension: path.extname(filePath),\n purpose: '',\n riskLevel: 'medium',\n whyRisky: null,\n changeCount: 1,\n lastChanged: now,\n incidentCount: 0,\n createdAt: now\n };\n\n return (await graph.addNode('file', data)) as FileNode;\n}\n","export interface DiffFileSummary {\n filePath: string;\n added: number;\n removed: number;\n functionsModified: string[];\n riskyPatterns: string[];\n}\n\nexport interface DiffSummary {\n files: DiffFileSummary[];\n totalAdded: number;\n totalRemoved: number;\n riskyFiles: string[];\n}\n\nconst RISKY_PATTERNS = [/auth/i, /token/i, /password/i, /secret/i, /validate/i, /sanitize/i];\n\nexport function analyzeDiff(diff: string): DiffSummary {\n const files: DiffFileSummary[] = [];\n let current: DiffFileSummary | null = null;\n\n const lines = diff.split('\\n');\n\n for (const line of lines) {\n if (line.startsWith('+++ b/')) {\n const filePath = line.replace('+++ b/', '').trim();\n current = {\n filePath,\n added: 0,\n removed: 0,\n functionsModified: [],\n riskyPatterns: []\n };\n files.push(current);\n continue;\n }\n\n if (!current) {\n continue;\n }\n\n if (line.startsWith('@@')) {\n // Capture function names or signatures in hunk headers\n const match = line.match(/@@.*?(function\\s+([\\w$]+)|class\\s+([\\w$]+)|([\\w$]+\\s*\\())/i);\n const fnName = match?.[2] || match?.[3] || match?.[4];\n if (fnName) {\n current.functionsModified.push(fnName.replace('(', '').trim());\n }\n continue;\n }\n\n if (line.startsWith('+') && !line.startsWith('+++')) {\n current.added += 1;\n markRisk(line, current);\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n current.removed += 1;\n markRisk(line, current);\n }\n }\n\n const totalAdded = files.reduce((acc, f) => acc + f.added, 0);\n const totalRemoved = files.reduce((acc, f) => acc + f.removed, 0);\n const riskyFiles = files.filter((f) => f.riskyPatterns.length > 0).map((f) => f.filePath);\n\n return {\n files,\n totalAdded,\n totalRemoved,\n riskyFiles\n };\n}\n\nfunction markRisk(line: string, file: DiffFileSummary): void {\n for (const pattern of RISKY_PATTERNS) {\n if (pattern.test(line)) {\n const label = pattern.toString();\n if (!file.riskyPatterns.includes(label)) {\n file.riskyPatterns.push(label);\n }\n }\n }\n}\n","import path from 'node:path';\n\nimport type { RiskLevel } from '../types/index.js';\nimport type { PatternNode } from '../context/types.js';\nimport type { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData, IncidentNode } from '../context/nodes.js';\n\nexport interface FileRiskResult {\n file: string;\n score: number;\n level: RiskLevel;\n reasons: string[];\n incidents: IncidentNode[];\n matchedPatterns: PatternNode[];\n}\n\nexport interface ChangeRiskResult {\n files: FileRiskResult[];\n overall: RiskLevel;\n score: number;\n shouldEscalate: boolean;\n}\n\nconst BASE_RISK: Record<RiskLevel, number> = {\n low: 10,\n medium: 35,\n high: 65,\n critical: 85\n};\n\nconst SENSITIVE_PATHS: { pattern: RegExp; weight: number; reason: string }[] = [\n { pattern: /auth|login|token|session/i, weight: 20, reason: 'touches authentication' },\n { pattern: /payment|billing|stripe|paypal|checkout/i, weight: 25, reason: 'touches payments' },\n { pattern: /secret|credential|env|config\\/security/i, weight: 15, reason: 'touches secrets/security config' },\n { pattern: /gdpr|privacy|pii|phi/i, weight: 15, reason: 'touches sensitive data' }\n];\n\nfunction levelFromScore(score: number): RiskLevel {\n if (score >= 90) return 'critical';\n if (score >= 65) return 'high';\n if (score >= 40) return 'medium';\n return 'low';\n}\n\nexport async function scoreFile(\n graph: ContextGraph,\n filePath: string,\n matchedPatterns: PatternNode[] = []\n): Promise<FileRiskResult> {\n const reasons: string[] = [];\n const normalized = path.resolve(graph.projectRoot, filePath);\n const node = await graph.getNode('file', normalized);\n const incidents = await graph.getIncidentsForFile(filePath);\n\n let score = 10;\n const data = node?.data as FileNodeData | undefined;\n\n if (data) {\n score = BASE_RISK[data.riskLevel] ?? score;\n reasons.push(`baseline ${data.riskLevel}`);\n\n if (data.incidentCount > 0) {\n const incBoost = Math.min(data.incidentCount * 12, 36);\n score += incBoost;\n reasons.push(`historical incidents (+${incBoost})`);\n }\n\n if (data.changeCount > 5) {\n const changeBoost = Math.min((data.changeCount - 5) * 2, 12);\n score += changeBoost;\n reasons.push(`frequent changes (+${changeBoost})`);\n }\n\n if (data.lastChanged) {\n const lastChanged = new Date(data.lastChanged).getTime();\n const days = (Date.now() - lastChanged) / (1000 * 60 * 60 * 24);\n if (days > 60 && data.incidentCount === 0) {\n score -= 5;\n reasons.push('stable for 60d (-5)');\n }\n }\n }\n\n for (const { pattern, weight, reason } of SENSITIVE_PATHS) {\n if (pattern.test(filePath)) {\n score += weight;\n reasons.push(reason);\n }\n }\n\n if (matchedPatterns.length > 0) {\n const patternBoost = Math.min(\n matchedPatterns.reduce((acc, p) => acc + (p.data.confidence ?? 50) / 10, 0),\n 20\n );\n score += patternBoost;\n reasons.push(`pattern match (+${Math.round(patternBoost)})`);\n }\n\n if (incidents.length > 0) {\n const timestamps = incidents\n .map((i) => new Date(i.data.timestamp).getTime())\n .sort((a, b) => b - a);\n const recent = timestamps[0]!;\n const daysSince = (Date.now() - recent) / (1000 * 60 * 60 * 24);\n if (daysSince > 90) {\n score -= 5;\n reasons.push('no incidents in 90d (-5)');\n } else {\n score += 8;\n reasons.push('recent incident (+8)');\n }\n }\n\n const level = levelFromScore(score);\n return {\n file: filePath,\n score,\n level,\n reasons,\n incidents,\n matchedPatterns\n };\n}\n\nexport async function scoreChangeSet(\n graph: ContextGraph,\n files: string[],\n patternMatches: Record<string, PatternNode[]> = {}\n): Promise<ChangeRiskResult> {\n const fileResults: FileRiskResult[] = [];\n\n for (const file of files) {\n const patterns = patternMatches[file] ?? [];\n fileResults.push(await scoreFile(graph, file, patterns));\n }\n\n // Aggregate: use max file score, but boost if many files touched\n const maxScore = Math.max(...fileResults.map((f) => f.score), 10);\n const spreadBoost = files.length > 5 ? Math.min((files.length - 5) * 2, 10) : 0;\n const overallScore = maxScore + spreadBoost;\n const overall = levelFromScore(overallScore);\n\n const shouldEscalate = overall === 'critical' || overall === 'high';\n\n return {\n files: fileResults,\n overall,\n score: overallScore,\n shouldEscalate\n };\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { PatternNode } from '../context/nodes.js';\n\nexport interface PatternMatch {\n file: string;\n pattern: PatternNode;\n confidence: number;\n isAntiPattern: boolean;\n}\n\nexport async function matchPatternsForFiles(\n graph: ContextGraph,\n files: string[]\n): Promise<{ matches: PatternMatch[]; byFile: Record<string, PatternNode[]> }> {\n const matches: PatternMatch[] = [];\n const byFile: Record<string, PatternNode[]> = {};\n\n for (const file of files) {\n const patterns = await graph.getPatternsForFile(file);\n if (patterns.length === 0) continue;\n\n byFile[file] = patterns;\n\n for (const pattern of patterns) {\n matches.push({\n file,\n pattern,\n confidence: pattern.data.confidence,\n isAntiPattern: pattern.data.isAntiPattern\n });\n }\n }\n\n return { matches, byFile };\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { IncidentNode, PatternNode } from '../context/nodes.js';\nimport type { RiskLevel, AgentResult, CodeContext, ScanContext } from '../types/index.js';\nimport { scoreChangeSet, type ChangeRiskResult, type FileRiskResult } from './risk-scorer.js';\nimport { matchPatternsForFiles } from './pattern-matcher.js';\nimport { Triager } from '../orchestrator/triager.js';\nimport { Executor } from '../orchestrator/executor.js';\n\nexport interface Reasoning {\n riskLevel: RiskLevel;\n shouldBlock: boolean;\n explanation: string;\n relevantIncidents: IncidentNode[];\n matchedPatterns: PatternNode[];\n recommendation: string;\n files: FileRiskResult[];\n agentResults?: AgentResult[];\n}\n\nexport interface ReasonOptions {\n runAgents?: boolean;\n codeContext?: CodeContext;\n scanContext?: Partial<ScanContext>;\n}\n\nfunction buildDefaultCodeContext(): CodeContext {\n return {\n changeType: 'general',\n isNewFeature: false,\n touchesUserData: false,\n touchesAuth: false,\n touchesPayments: false,\n touchesDatabase: false,\n touchesAPI: false,\n touchesUI: false,\n touchesHealthData: false,\n touchesSecurityConfig: false,\n linesChanged: 50,\n filePatterns: [],\n framework: 'unknown',\n language: 'typescript',\n touchesCrypto: false,\n touchesFileSystem: false,\n touchesThirdPartyAPI: false,\n touchesLogging: false,\n touchesErrorHandling: false,\n hasTests: false,\n complexity: 'medium',\n patterns: {\n hasAsyncCode: false,\n hasFormHandling: false,\n hasFileUploads: false,\n hasEmailHandling: false,\n hasRateLimiting: false,\n hasWebSockets: false,\n hasCaching: false,\n hasQueue: false\n }\n };\n}\n\nfunction buildExplanation(result: ChangeRiskResult): string {\n const top = [...result.files].sort((a, b) => b.score - a.score)[0];\n if (!top) return `Risk level ${result.overall} (no files provided)`;\n return `Risk level ${result.overall} because ${top.file} ${top.reasons.join(', ')}`;\n}\n\nfunction buildRecommendation(risk: RiskLevel, hasAntiPattern: boolean): string {\n if (hasAntiPattern || risk === 'critical') {\n return 'Block until reviewed: address anti-patterns and rerun targeted tests.';\n }\n if (risk === 'high') {\n return 'Require senior review and run full test suite before merge.';\n }\n if (risk === 'medium') {\n return 'Proceed with caution; run impacted tests and sanity checks.';\n }\n return 'Low risk; proceed but keep an eye on recent changes.';\n}\n\nexport async function reasonAboutChanges(\n projectPath: string,\n files: string[],\n options: ReasonOptions = {}\n): Promise<Reasoning> {\n const graph = new ContextGraph(projectPath);\n const { matches, byFile } = await matchPatternsForFiles(graph, files);\n const changeRisk = await scoreChangeSet(graph, files, byFile);\n\n const incidents: IncidentNode[] = [];\n for (const file of files) {\n const fileIncidents = await graph.getIncidentsForFile(file);\n incidents.push(...fileIncidents);\n }\n\n const hasAntiPattern = matches.some((m) => m.isAntiPattern);\n const riskLevel: RiskLevel = hasAntiPattern ? 'critical' : changeRisk.overall;\n const shouldBlock = hasAntiPattern || riskLevel === 'critical' || riskLevel === 'high';\n\n const reasoning: Reasoning = {\n riskLevel,\n shouldBlock,\n explanation: buildExplanation(changeRisk),\n relevantIncidents: incidents,\n matchedPatterns: matches.map((m) => m.pattern),\n recommendation: buildRecommendation(riskLevel, hasAntiPattern),\n files: changeRisk.files\n };\n\n if (options.runAgents) {\n const codeContext = options.codeContext ?? buildDefaultCodeContext();\n const triager = new Triager();\n const agents = await triager.selectAgents(codeContext, riskLevel);\n\n if (agents.length > 0) {\n const executor = new Executor();\n const scanContext: ScanContext = {\n workingDir: projectPath,\n ...options.scanContext\n };\n if (codeContext.framework) scanContext.framework = codeContext.framework;\n if (codeContext.language) scanContext.language = codeContext.language;\n\n reasoning.agentResults = await executor.executeAgents(agents, files, scanContext, {\n parallel: true,\n timeoutMs: options.scanContext?.config?.timeoutMs ?? 60000\n });\n } else {\n reasoning.agentResults = [];\n }\n }\n\n return reasoning;\n}\n\n// Convenience wrapper to keep future CLI/MCP integration simple\nexport async function reasonAboutChangesHumanReadable(\n projectPath: string,\n files: string[],\n options: ReasonOptions = {}\n) {\n const reasoning = await reasonAboutChanges(projectPath, files, options);\n const { humanizeReasoning } = await import('../comprehension/index.js');\n return humanizeReasoning(reasoning);\n}\n","/**\n * Bootstrap File System\n * \n * Manages workspace files that inject context at scan start.\n * Files: BOOTSTRAP.md, RULES.md, TEAM.md\n */\n\nimport { readFile, writeFile, unlink, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { detectStack, type DetectedStack } from './stack-detector.js';\n\nexport interface BootstrapFile {\n name: string;\n path: string;\n type: 'user' | 'auto' | 'one-time';\n exists: boolean;\n content?: string;\n}\n\nexport interface BootstrapContext {\n files: BootstrapFile[];\n injectedContent: string;\n needsBootstrap: boolean;\n}\n\ninterface BootstrapFileSpec {\n name: string;\n type: 'user' | 'auto' | 'one-time';\n description: string;\n}\n\nconst BOOTSTRAP_FILES: BootstrapFileSpec[] = [\n { name: 'PROJECT.md', type: 'user', description: 'Project overview and conventions' },\n { name: 'RULES.md', type: 'user', description: 'Coding standards agents enforce' },\n { name: 'TEAM.md', type: 'user', description: 'Team ownership and escalation' },\n { name: 'BOOTSTRAP.md', type: 'one-time', description: 'First-run setup (deleted after)' },\n { name: 'AGENTS.md', type: 'auto', description: 'Auto-generated scan context' },\n];\n\n/**\n * Load bootstrap files and inject into agent context\n */\nexport async function loadBootstrapContext(workDir?: string): Promise<BootstrapContext> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const trieDir = join(projectDir, '.trie');\n const files: BootstrapFile[] = [];\n const contentParts: string[] = [];\n let needsBootstrap = false;\n\n for (const file of BOOTSTRAP_FILES) {\n const filePath = join(trieDir, file.name);\n const exists = existsSync(filePath);\n \n if (file.name === 'BOOTSTRAP.md' && exists) {\n needsBootstrap = true;\n }\n \n let content: string | undefined;\n if (exists) {\n try {\n content = await readFile(filePath, 'utf-8');\n if (content.trim() && file.type !== 'one-time') {\n contentParts.push(`<!-- ${file.name} -->\\n${content}`);\n }\n } catch {\n // Skip files that can't be read\n }\n }\n\n const fileEntry: BootstrapFile = {\n name: file.name,\n path: filePath,\n type: file.type,\n exists,\n };\n if (content) fileEntry.content = content;\n files.push(fileEntry);\n }\n\n return {\n files,\n injectedContent: contentParts.join('\\n\\n---\\n\\n'),\n needsBootstrap,\n };\n}\n\n/**\n * Initialize bootstrap files for a new project\n */\nexport async function initializeBootstrapFiles(options: {\n workDir?: string;\n force?: boolean;\n skipBootstrap?: boolean;\n} = {}): Promise<{ created: string[]; skipped: string[]; stack: DetectedStack }> {\n const projectDir = options.workDir || getWorkingDirectory(undefined, true);\n const trieDir = join(projectDir, '.trie');\n await mkdir(trieDir, { recursive: true });\n\n const created: string[] = [];\n const skipped: string[] = [];\n\n const stack = await detectStack(projectDir);\n\n for (const file of BOOTSTRAP_FILES) {\n const filePath = join(trieDir, file.name);\n const exists = existsSync(filePath);\n\n if (exists && !options.force) {\n skipped.push(file.name);\n continue;\n }\n\n if (file.name === 'BOOTSTRAP.md' && options.skipBootstrap) {\n skipped.push(file.name);\n continue;\n }\n\n if (file.name === 'AGENTS.md') {\n skipped.push(file.name);\n continue;\n }\n\n const template = getFileTemplate(file.name, stack);\n if (template) {\n await writeFile(filePath, template);\n created.push(file.name);\n }\n }\n\n return { created, skipped, stack };\n}\n\n/**\n * Mark bootstrap as complete (delete BOOTSTRAP.md)\n */\nexport async function completeBootstrap(workDir?: string): Promise<boolean> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const bootstrapPath = join(projectDir, '.trie', 'BOOTSTRAP.md');\n\n try {\n await unlink(bootstrapPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if bootstrap is needed (BOOTSTRAP.md exists)\n */\nexport function needsBootstrap(workDir?: string): boolean {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const bootstrapPath = join(projectDir, '.trie', 'BOOTSTRAP.md');\n return existsSync(bootstrapPath);\n}\n\n/**\n * Get rules from RULES.md\n */\nexport async function loadRules(workDir?: string): Promise<string | null> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const rulesPath = join(projectDir, '.trie', 'RULES.md');\n \n try {\n if (existsSync(rulesPath)) {\n return await readFile(rulesPath, 'utf-8');\n }\n } catch {\n // Rules file doesn't exist or can't be read\n }\n \n return null;\n}\n\n/**\n * Get team info from TEAM.md\n */\nexport async function loadTeamInfo(workDir?: string): Promise<string | null> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const teamPath = join(projectDir, '.trie', 'TEAM.md');\n \n try {\n if (existsSync(teamPath)) {\n return await readFile(teamPath, 'utf-8');\n }\n } catch {\n // Team file doesn't exist or can't be read\n }\n \n return null;\n}\n\nfunction getFileTemplate(fileName: string, stack: DetectedStack): string | null {\n switch (fileName) {\n case 'PROJECT.md':\n return getProjectTemplate(stack);\n case 'RULES.md':\n return getRulesTemplate(stack);\n case 'TEAM.md':\n return getTeamTemplate();\n case 'BOOTSTRAP.md':\n return getBootstrapTemplate(stack);\n default:\n return null;\n }\n}\n\nfunction getProjectTemplate(stack: DetectedStack): string {\n const lines: string[] = ['# Project Overview', '', '> Define your project context here. AI assistants read this first.', ''];\n \n lines.push('## Description', '', '[Describe what this project does and who it\\'s for]', '');\n \n lines.push('## Technology Stack', '');\n if (stack.framework) lines.push(`- **Framework:** ${stack.framework}`);\n if (stack.language) lines.push(`- **Language:** ${stack.language}`);\n if (stack.database) lines.push(`- **Database:** ${stack.database}`);\n if (stack.auth) lines.push(`- **Auth:** ${stack.auth}`);\n if (!stack.framework && !stack.language && !stack.database) {\n lines.push('[Add your technology stack]');\n }\n lines.push('');\n \n lines.push('## Architecture', '', '[Key patterns and design decisions]', '');\n lines.push('## Coding Conventions', '', '[Style rules agents should follow]', '');\n lines.push('## AI Instructions', '', 'When working on this project:', '1. [Instruction 1]', '2. [Instruction 2]', '3. [Instruction 3]', '');\n lines.push('---', '', '*Edit this file to provide project context to AI assistants.*');\n \n return lines.join('\\n');\n}\n\nfunction getRulesTemplate(stack: DetectedStack): string {\n const packageManager = stack.packageManager || 'npm';\n \n return `# Project Rules\n\n> These rules are enforced by Trie agents during scans.\n> Violations appear as issues with [RULES] prefix.\n\n## Code Style\n\n1. Use named exports, not default exports\n2. Prefer \\`${packageManager}\\` for package management\n3. Maximum file length: 300 lines\n4. Use TypeScript strict mode\n\n## Testing Requirements\n\n1. Critical paths require unit tests\n2. API endpoints require integration tests\n3. Minimum coverage: 70%\n\n## Security Rules\n\n1. Never log sensitive data (passwords, tokens, PII)\n2. All API routes require authentication\n3. Rate limiting required on public endpoints\n4. SQL queries must use parameterized statements\n\n## Review Requirements\n\n1. All PRs require at least 1 reviewer\n2. Security-sensitive changes require security review\n3. Database migrations require review\n\n---\n\n*Edit this file to define your project's coding standards.*\n`;\n}\n\nfunction getTeamTemplate(): string {\n return `# Team Structure\n\n## Code Ownership\n\n| Area | Owner | Backup | Review Required |\n|------|-------|--------|-----------------|\n| \\`/src/api/\\` | @backend-team | - | 1 approver |\n| \\`/src/ui/\\` | @frontend-team | - | 1 approver |\n| \\`/src/auth/\\` | @security-team | - | Security review |\n\n## Escalation\n\n| Severity | First Contact | Escalate To | SLA |\n|----------|--------------|-------------|-----|\n| Critical | Team lead | CTO | 1 hour |\n| Serious | PR reviewer | Team lead | 4 hours |\n| Moderate | Self-serve | - | 1 day |\n\n## Contacts\n\n- **Security:** [email/slack]\n- **Privacy:** [email/slack]\n- **Emergencies:** [phone/pager]\n\n---\n\n*Edit this file to define your team structure.*\n`;\n}\n\nfunction getBootstrapTemplate(stack: DetectedStack): string {\n const skillCommands = stack.suggestedSkills\n .map(s => `trie skills add ${s}`)\n .join('\\n');\n\n const agentList = stack.suggestedAgents.join(', ');\n\n const lines: string[] = [\n '# Trie Bootstrap Checklist',\n '',\n 'This file guides your first scan setup. **Delete when complete.**',\n '',\n '## Auto-Detected Stack',\n '',\n 'Based on your project, Trie detected:',\n ];\n \n if (stack.framework) lines.push(`- **Framework:** ${stack.framework}`);\n if (stack.language) lines.push(`- **Language:** ${stack.language}`);\n if (stack.database) lines.push(`- **Database:** ${stack.database}`);\n if (stack.auth) lines.push(`- **Auth:** ${stack.auth}`);\n \n lines.push('', '## Recommended Actions', '', '### 1. Skills to Install', 'Based on your stack, consider installing:', '```bash');\n lines.push(skillCommands || '# No specific skills detected - browse https://skills.sh');\n lines.push('```', '', '### 2. Agents to Enable', `Your stack suggests these agents: ${agentList || 'security, privacy, bugs'}`, '');\n lines.push('### 3. Configure Rules', 'Add your coding standards to `.trie/RULES.md`.', '');\n lines.push('### 4. Run First Scan', '```bash', 'trie scan', '```', '');\n lines.push('---', '', '**Delete this file after completing setup.** Run:', '```bash', 'rm .trie/BOOTSTRAP.md', '```');\n \n return lines.join('\\n');\n}\n","export class TrieError extends Error {\n code: string;\n recoverable: boolean;\n userMessage: string;\n\n constructor(message: string, code: string, userMessage: string, recoverable = true) {\n super(message);\n this.code = code;\n this.recoverable = recoverable;\n this.userMessage = userMessage;\n }\n}\n\nexport class GraphError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'GRAPH_ERROR',\n 'Trie had trouble accessing its memory. Try again or re-run trie reconcile.',\n true\n );\n }\n}\n\nexport class GitError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'GIT_ERROR',\n 'Git info is unavailable. Is this a git repo? Commit once, or pass --files to trie check.',\n true\n );\n }\n}\n\nexport class NetworkError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'NETWORK_ERROR',\n 'Network unavailable. Running in offline mode; AI calls skipped.',\n true\n );\n }\n}\n\nexport class MissingAPIKeyError extends TrieError {\n constructor(message = 'Missing ANTHROPIC_API_KEY') {\n super(\n message,\n 'MISSING_API_KEY',\n 'No API key detected. Set ANTHROPIC_API_KEY for AI-powered analysis (deeper issue detection, smarter fixes). Running in pattern-only mode.',\n true\n );\n }\n}\n\nexport function formatFriendlyError(error: unknown): { userMessage: string; code: string } {\n if (error instanceof TrieError) {\n return { userMessage: error.userMessage, code: error.code };\n }\n return {\n userMessage: 'Something went wrong. Try again or run with --offline.',\n code: 'UNKNOWN'\n };\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { ContextGraph } from './graph.js';\nimport type { ContextSnapshot } from './types.js';\n\nconst DEFAULT_JSON_NAME = 'context.json';\n\nexport async function exportToJson(graph: ContextGraph, targetPath?: string): Promise<string> {\n const snapshot = await graph.getSnapshot();\n const json = JSON.stringify(snapshot, null, 2);\n\n const outputPath = targetPath ?? path.join(graph.projectRoot, '.trie', DEFAULT_JSON_NAME);\n await fs.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.writeFile(outputPath, json, 'utf8');\n\n return json;\n}\n\nexport async function importFromJson(\n graph: ContextGraph,\n json: string,\n sourcePath?: string\n): Promise<void> {\n const payload =\n json.trim().length > 0\n ? json\n : await fs.readFile(sourcePath ?? path.join(graph.projectRoot, '.trie', DEFAULT_JSON_NAME), 'utf8');\n\n const snapshot = JSON.parse(payload) as ContextSnapshot;\n await graph.applySnapshot(snapshot);\n}\n","import path from 'node:path';\n\nimport type { IncidentNode } from './nodes.js';\nimport type { ContextGraph } from './graph.js';\nimport { FilePathTrie, type IncidentMetadata } from './file-trie.js';\n\nexport interface IncidentIndexOptions {\n persistPath?: string;\n}\n\nexport class IncidentIndex {\n private readonly graph: ContextGraph;\n private readonly trie: FilePathTrie;\n private readonly projectRoot: string;\n\n constructor(graph: ContextGraph, projectRoot: string, options?: IncidentIndexOptions) {\n this.graph = graph;\n this.projectRoot = projectRoot;\n this.trie = new FilePathTrie(\n options?.persistPath ?? path.join(projectRoot, '.trie', 'incident-trie.json')\n );\n }\n\n static async build(graph: ContextGraph, projectRoot: string, options?: IncidentIndexOptions): Promise<IncidentIndex> {\n const index = new IncidentIndex(graph, projectRoot, options);\n await index.rebuild();\n return index;\n }\n\n async rebuild(): Promise<void> {\n const nodes = await this.graph.listNodes();\n const incidents = nodes.filter((n) => n.type === 'incident') as IncidentNode[];\n\n for (const incident of incidents) {\n const files = await this.getFilesForIncident(incident.id);\n this.addIncidentToTrie(incident, files);\n }\n }\n\n addIncidentToTrie(incident: IncidentNode, files: string[]): void {\n const meta: IncidentMetadata = {\n id: incident.id,\n file: '',\n description: incident.data.description,\n severity: incident.data.severity,\n timestamp: incident.data.timestamp,\n };\n\n for (const file of files) {\n const normalized = this.normalizePath(file);\n this.trie.addIncident(normalized, { ...meta, file: normalized });\n }\n }\n\n getFileTrie(): FilePathTrie {\n return this.trie;\n }\n\n private async getFilesForIncident(incidentId: string): Promise<string[]> {\n const files = new Set<string>();\n const edges = await this.graph.getEdges(incidentId, 'both');\n\n // Traverse connected changes to pull file lists\n for (const edge of edges) {\n if (edge.type === 'causedBy' || edge.type === 'leadTo') {\n // Identify the change node id regardless of direction\n const changeId = edge.type === 'causedBy' ? edge.to_id : edge.from_id;\n const change = await this.graph.getNode('change', changeId);\n if (change?.data && 'files' in change.data && Array.isArray(change.data.files)) {\n (change.data.files as string[]).forEach((f: string) => files.add(f));\n }\n }\n\n // If there are direct file links, capture them as well\n if (edge.type === 'affects') {\n const fileNode =\n (await this.graph.getNode('file', edge.to_id)) ||\n (await this.graph.getNode('file', edge.from_id));\n if (fileNode && typeof (fileNode as any).data?.path === 'string') {\n files.add((fileNode as any).data.path);\n }\n }\n }\n\n return Array.from(files);\n }\n\n private normalizePath(filePath: string): string {\n const absolute = path.isAbsolute(filePath) ? filePath : path.join(this.projectRoot, filePath);\n const relative = path.relative(this.projectRoot, absolute);\n return relative.replace(/\\\\/g, '/');\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { performance } from 'node:perf_hooks';\n\nimport { Trie } from '../trie/trie.js';\n\nexport interface IncidentMetadata {\n id: string;\n file: string;\n description: string;\n severity: 'minor' | 'major' | 'critical' | string;\n timestamp: string;\n}\n\nexport interface HotZone {\n path: string;\n incidentCount: number;\n confidence: number;\n}\n\nfunction normalizePath(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n return normalized.startsWith('./') ? normalized.slice(2) : normalized;\n}\n\nexport class FilePathTrie {\n private trie: Trie<IncidentMetadata[]> = new Trie();\n private persistPath?: string;\n\n constructor(persistPath?: string) {\n if (persistPath) this.persistPath = persistPath;\n if (persistPath && fs.existsSync(persistPath)) {\n try {\n const raw = fs.readFileSync(persistPath, 'utf-8');\n if (raw.trim().length > 0) {\n const json = JSON.parse(raw);\n this.trie = Trie.fromJSON<IncidentMetadata[]>(json);\n }\n } catch {\n this.trie = new Trie();\n }\n }\n }\n\n addIncident(filePath: string, incident: IncidentMetadata): void {\n const key = normalizePath(filePath);\n const existing = this.trie.search(key);\n const incidents = existing.found && Array.isArray(existing.value) ? existing.value : [];\n incidents.push(incident);\n this.trie.insert(key, incidents);\n this.persist();\n }\n\n getIncidents(filePath: string): IncidentMetadata[] {\n const key = normalizePath(filePath);\n const result = this.trie.search(key);\n return result.found && Array.isArray(result.value) ? result.value : [];\n }\n\n getDirectoryIncidents(prefix: string): IncidentMetadata[] {\n const normalizedPrefix = normalizePath(prefix);\n const matches = this.trie.getWithPrefix(normalizedPrefix);\n return matches.flatMap((m) => (Array.isArray(m.value) ? m.value : [])).filter(Boolean);\n }\n\n getHotZones(threshold: number): HotZone[] {\n const matches = this.trie.getWithPrefix('');\n const zones: HotZone[] = [];\n\n for (const match of matches) {\n const incidents = Array.isArray(match.value) ? match.value : [];\n if (incidents.length >= threshold) {\n zones.push({\n path: match.pattern,\n incidentCount: incidents.length,\n confidence: this.calculateConfidence(incidents.length),\n });\n }\n }\n\n return zones.sort((a, b) => b.incidentCount - a.incidentCount);\n }\n\n suggestPaths(partial: string, limit = 5): Array<{ path: string; incidentCount: number }> {\n const normalized = normalizePath(partial);\n const results = this.trie.getWithPrefix(normalized);\n return results\n .map((r) => ({\n path: r.pattern,\n incidentCount: Array.isArray(r.value) ? r.value.length : 0,\n }))\n .sort((a, b) => b.incidentCount - a.incidentCount)\n .slice(0, limit);\n }\n\n timeLookup(path: string): number {\n const start = performance.now();\n this.getIncidents(path);\n return performance.now() - start;\n }\n\n toJSON(): object {\n return this.trie.toJSON();\n }\n\n private calculateConfidence(count: number): number {\n const capped = Math.min(count, 10);\n return Math.round((capped / 10) * 100) / 100; // 0-1 scale\n }\n\n private persist(): void {\n if (!this.persistPath) return;\n try {\n const dir = path.dirname(this.persistPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(this.persistPath, JSON.stringify(this.trie.toJSON()), 'utf-8');\n } catch {\n // Persistence is best-effort; ignore failures\n }\n }\n}\n","/**\n * Lightweight Bayesian-style confidence updater.\n * Treats confidence as probability in [0,1].\n */\n\nexport function bayesianUpdate(prior: number, evidence: number, weight = 1): number {\n const p = clamp(prior);\n const e = clamp(evidence);\n const w = Math.max(0, weight);\n // Blend prior with evidence weighted by w\n const posterior = (p * (1 - w)) + (e * w);\n return clamp(posterior);\n}\n\nexport function adjustConfidence(current: number, outcome: 'positive' | 'negative', step = 0.1): number {\n const delta = outcome === 'positive' ? step : -step;\n return clamp(current + delta);\n}\n\nfunction clamp(value: number): number {\n if (Number.isNaN(value)) return 0.5;\n return Math.min(1, Math.max(0, value));\n}\n","import { IncidentIndex } from '../context/incident-index.js';\nimport type { ContextGraph } from '../context/graph.js';\nimport type { ChangeNode, IncidentNode } from '../context/nodes.js';\n\nexport interface HotPattern {\n type: 'file' | 'directory';\n path: string;\n incidentCount: number;\n confidence: number;\n relatedFiles?: string[];\n}\n\nexport interface CoOccurrencePattern {\n files: [string, string];\n coOccurrences: number;\n confidence: number;\n}\n\nexport class TriePatternDiscovery {\n constructor(\n private graph: ContextGraph,\n private incidentIndex: IncidentIndex\n ) {}\n\n discoverHotPatterns(threshold = 3): HotPattern[] {\n const trie = this.incidentIndex.getFileTrie();\n const hotZones = trie.getHotZones(threshold);\n\n return hotZones.map((zone) => ({\n type: zone.path.endsWith('/') ? 'directory' : 'file',\n path: zone.path,\n incidentCount: zone.incidentCount,\n confidence: zone.confidence,\n relatedFiles: trie.getDirectoryIncidents(zone.path).map((i) => i.file)\n }));\n }\n\n async discoverCoOccurrences(minCount = 3): Promise<CoOccurrencePattern[]> {\n const incidents = await this.getAllIncidents();\n const coOccurrences: Map<string, Map<string, number>> = new Map();\n\n for (const inc of incidents) {\n const files = await this.getFilesForIncident(inc);\n for (let i = 0; i < files.length; i++) {\n for (let j = i + 1; j < files.length; j++) {\n const a = files[i]!;\n const b = files[j]!;\n if (!coOccurrences.has(a)) coOccurrences.set(a, new Map());\n const counts = coOccurrences.get(a)!;\n counts.set(b, (counts.get(b) || 0) + 1);\n }\n }\n }\n\n const patterns: CoOccurrencePattern[] = [];\n for (const [a, map] of coOccurrences.entries()) {\n for (const [b, count] of map.entries()) {\n if (count >= minCount) {\n const denom = Math.min(\n this.incidentIndex.getFileTrie().getIncidents(a).length || 1,\n this.incidentIndex.getFileTrie().getIncidents(b).length || 1\n );\n patterns.push({\n files: [a, b],\n coOccurrences: count,\n confidence: Math.min(1, count / denom)\n });\n }\n }\n }\n\n return patterns.sort((x, y) => y.confidence - x.confidence);\n }\n\n private async getAllIncidents(): Promise<IncidentNode[]> {\n const nodes = await this.graph.listNodes();\n return nodes.filter((n) => n.type === 'incident') as IncidentNode[];\n }\n\n private async getFilesForIncident(incident: IncidentNode): Promise<string[]> {\n const files = new Set<string>();\n const edges = await this.graph.getEdges(incident.id, 'both');\n\n for (const edge of edges) {\n if (edge.type === 'causedBy' || edge.type === 'leadTo') {\n const changeId = edge.type === 'causedBy' ? edge.to_id : edge.from_id;\n const change = await this.graph.getNode('change', changeId) as ChangeNode | null;\n if (change?.data?.files && Array.isArray(change.data.files)) {\n change.data.files.forEach((f: string) => files.add(f));\n }\n }\n }\n\n return Array.from(files).map((f) => f.replace(/\\\\/g, '/'));\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { IncidentNode, PatternNode } from '../context/nodes.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { adjustConfidence } from './confidence.js';\nimport { TriePatternDiscovery } from './pattern-discovery.js';\n\nexport class LearningSystem {\n private incidentIndex: IncidentIndex;\n private discovery: TriePatternDiscovery;\n\n constructor(private graph: ContextGraph, projectPath: string) {\n this.incidentIndex = new IncidentIndex(graph, projectPath);\n this.discovery = new TriePatternDiscovery(graph, this.incidentIndex);\n }\n\n async onWarningHeeded(files: string[]): Promise<void> {\n await this.adjustPatterns(files, 'positive');\n }\n\n async onWarningIgnored(files: string[]): Promise<void> {\n await this.adjustPatterns(files, 'negative');\n }\n\n async onIncidentReported(incidentId: string, files: string[]): Promise<void> {\n const incident = await this.graph.getNode('incident', incidentId);\n if (incident && incident.type === 'incident') {\n this.incidentIndex.addIncidentToTrie(incident as IncidentNode, files);\n }\n await this.discoverAndStorePatterns();\n }\n\n async onFeedback(helpful: boolean, files: string[] = []): Promise<void> {\n await this.adjustPatterns(files, helpful ? 'positive' : 'negative');\n }\n\n private async adjustPatterns(files: string[], outcome: 'positive' | 'negative'): Promise<void> {\n if (!files.length) return;\n for (const file of files) {\n const patterns = await this.graph.getPatternsForFile(file);\n await Promise.all(patterns.map((p) => this.updatePatternConfidence(p, outcome)));\n }\n }\n\n private async updatePatternConfidence(pattern: PatternNode, outcome: 'positive' | 'negative'): Promise<void> {\n const current = pattern.data.confidence ?? 0.5;\n const updated = adjustConfidence(current, outcome, 0.05);\n await this.graph.updateNode('pattern', pattern.id, { confidence: updated, lastSeen: new Date().toISOString() });\n }\n\n private async discoverAndStorePatterns(): Promise<void> {\n const hotPatterns = this.discovery.discoverHotPatterns();\n for (const hot of hotPatterns) {\n await this.graph.addNode('pattern', {\n description: `${hot.type === 'directory' ? 'Directory' : 'File'} hot zone: ${hot.path}`,\n appliesTo: [hot.path],\n confidence: hot.confidence,\n occurrences: hot.incidentCount,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: true,\n source: 'local'\n });\n }\n }\n}\n","import { getRecentCommits, getDiff } from '../agent/git.js';\nimport { storeIssues } from '../memory/issue-store.js';\nimport { scanForVulnerabilities } from '../trie/vulnerability-signatures.js';\nimport { scanForVibeCodeIssues } from '../trie/vibe-code-signatures.js';\nimport type { Issue } from '../types/index.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { LearningSystem } from '../agent/learning.js';\nimport path from 'node:path';\n\nexport interface LearningResult {\n learned: number;\n source: 'git-history' | 'manual-feedback';\n}\n\nexport class LearningEngine {\n private readonly projectPath: string;\n private readonly graph: ContextGraph;\n private readonly learningSystem: LearningSystem;\n\n constructor(projectPath: string, graph?: ContextGraph) {\n this.projectPath = projectPath;\n this.graph = graph || new ContextGraph(projectPath);\n this.learningSystem = new LearningSystem(this.graph, projectPath);\n }\n\n /**\n * Unified learning method: Scans history AND processes manual feedback\n */\n async learn(options: { \n limit?: number; \n manualFeedback?: { helpful: boolean; files: string[]; note?: string } \n } = {}): Promise<LearningResult[]> {\n const results: LearningResult[] = [];\n\n // 1. Implicit Learning from Git History\n if (!options.manualFeedback) {\n const implicitCount = await this.learnFromHistory(options.limit || 20);\n results.push({ learned: implicitCount, source: 'git-history' });\n }\n\n // 2. Manual Feedback Learning\n if (options.manualFeedback) {\n await this.recordManualFeedback(\n options.manualFeedback.helpful, \n options.manualFeedback.files, \n options.manualFeedback.note\n );\n results.push({ learned: options.manualFeedback.files.length || 1, source: 'manual-feedback' });\n }\n\n return results;\n }\n\n /**\n * Scan recent commits for implicit failure signals (reverts, fixes)\n */\n private async learnFromHistory(limit: number = 20): Promise<number> {\n const commits = await getRecentCommits(this.projectPath, limit);\n const issuesToStore: Issue[] = [];\n\n for (const commit of commits) {\n const isRevert = commit.message.toLowerCase().includes('revert') || commit.message.startsWith('Revert \"');\n const isFix = /fix(es|ed)?\\s+#\\d+/i.test(commit.message) || commit.message.toLowerCase().includes('bugfix');\n\n if (isRevert || isFix) {\n const type = isRevert ? 'revert' : 'fix';\n const diff = await getDiff(this.projectPath, commit.hash);\n const files = this.extractFilesFromDiff(diff);\n \n for (const file of files) {\n const learnedIssues = await this.extractIssuesFromDiff(diff, file, type, commit.message);\n issuesToStore.push(...learnedIssues);\n }\n }\n }\n\n if (issuesToStore.length > 0) {\n const result = await storeIssues(issuesToStore, path.basename(this.projectPath), this.projectPath);\n return result.stored;\n }\n\n return 0;\n }\n\n /**\n * Record manual feedback (trie ok/bad) and adjust pattern confidence\n */\n private async recordManualFeedback(helpful: boolean, files: string[], note?: string): Promise<void> {\n const decision = await this.graph.addNode('decision', {\n context: files.length > 0 ? files[0] : 'unspecified',\n decision: helpful ? 'helpful' : 'not helpful',\n reasoning: note ?? null,\n outcome: helpful ? 'good' : 'bad',\n timestamp: new Date().toISOString(),\n });\n\n if (files.length > 0) {\n for (const file of files) {\n const fileNode = await this.graph.getNode('file', file);\n if (fileNode) {\n await this.graph.addEdge(decision.id, fileNode.id, 'affects');\n }\n }\n await this.learningSystem.onFeedback(helpful, files);\n }\n }\n\n private extractFilesFromDiff(diff: string): string[] {\n const files = new Set<string>();\n const lines = diff.split('\\n');\n for (const line of lines) {\n if (line.startsWith('+++ b/')) {\n files.add(line.slice(6));\n }\n }\n return Array.from(files);\n }\n\n private async extractIssuesFromDiff(diff: string, file: string, type: 'revert' | 'fix', message: string): Promise<Issue[]> {\n const issues: Issue[] = [];\n const badLines = this.getBadLinesFromDiff(diff, file, type);\n const content = badLines.join('\\n');\n\n if (!content) return [];\n\n const vulnerabilities = await scanForVulnerabilities(content, file);\n const vibeIssues = await scanForVibeCodeIssues(content, file);\n\n const allMatches = [...vulnerabilities, ...vibeIssues];\n\n for (const match of allMatches) {\n issues.push({\n id: `implicit-${type}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n severity: 'serious',\n issue: `Implicit failure detected via ${type}: ${message}. Linked to pattern: ${match.category}`,\n fix: `Review the ${type} commit and avoid this pattern in ${file}.`,\n file: file,\n confidence: 0.7,\n autoFixable: false,\n agent: 'implicit-learning',\n category: match.category\n });\n }\n\n if (issues.length === 0) {\n issues.push({\n id: `implicit-${type}-${Date.now()}`,\n severity: 'moderate',\n issue: `Historical ${type} detected: ${message}`,\n fix: `Review the changes in ${file} from this commit to avoid regression.`,\n file: file,\n confidence: 0.5,\n autoFixable: false,\n agent: 'implicit-learning'\n });\n }\n\n return issues;\n }\n\n private getBadLinesFromDiff(diff: string, file: string, type: 'revert' | 'fix'): string[] {\n const badLines: string[] = [];\n const lines = diff.split('\\n');\n let inTargetFile = false;\n\n for (const line of lines) {\n if (line.startsWith('+++ b/') || line.startsWith('--- a/')) {\n inTargetFile = line.includes(file);\n continue;\n }\n\n if (!inTargetFile) continue;\n\n if (type === 'fix' && line.startsWith('-') && !line.startsWith('---')) {\n badLines.push(line.slice(1));\n } else if (type === 'revert' && line.startsWith('+') && !line.startsWith('+++')) {\n badLines.push(line.slice(1));\n }\n }\n\n return badLines;\n }\n}\n","import { loadConfig } from '../config/loader.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { LinearTicketNodeData } from '../context/nodes.js';\n\nexport interface LinearTicket {\n id: string;\n identifier: string;\n title: string;\n description: string;\n priority: number;\n status: { name: string };\n assignee?: { name: string };\n labels: { nodes: { name: string }[] };\n createdAt: string;\n updatedAt: string;\n}\n\nexport class LinearIngester {\n private readonly projectPath: string;\n private readonly graph: ContextGraph;\n\n constructor(projectPath: string, graph: ContextGraph) {\n this.projectPath = projectPath;\n this.graph = graph;\n }\n\n async syncTickets(): Promise<void> {\n const apiKey = await this.getApiKey();\n if (!apiKey) {\n console.warn('Linear API key not found. Run \"trie linear auth <key>\" to enable ticket sync.');\n return;\n }\n\n const tickets = await this.fetchActiveTickets(apiKey);\n for (const ticket of tickets) {\n await this.ingestTicket(ticket);\n }\n }\n\n private async getApiKey(): Promise<string | null> {\n const config = await loadConfig();\n return (config.apiKeys as any)?.linear || process.env.LINEAR_API_KEY || null;\n }\n\n private async fetchActiveTickets(apiKey: string): Promise<LinearTicket[]> {\n const query = `\n query {\n issues(filter: { state: { type: { in: [\"started\", \"unstarted\"] } } }) {\n nodes {\n id\n identifier\n title\n description\n priority\n status {\n name\n }\n assignee {\n name\n }\n labels {\n nodes {\n name\n }\n }\n createdAt\n updatedAt\n }\n }\n }\n `;\n\n const response = await fetch('https://api.linear.app/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': apiKey,\n },\n body: JSON.stringify({ query }),\n });\n\n if (!response.ok) {\n throw new Error(`Linear API error: ${response.statusText}`);\n }\n\n const data = (await response.json()) as any;\n return data.data.issues.nodes as LinearTicket[];\n }\n\n private async ingestTicket(ticket: LinearTicket): Promise<void> {\n const labels = ticket.labels.nodes.map(l => l.name);\n const intentVibe = this.extractIntentVibes(ticket.title, ticket.description, labels);\n \n // Attempt to find linked files in description or via labels (heuristic)\n const linkedFiles = this.extractLinkedFiles(ticket.description);\n\n const data: LinearTicketNodeData = {\n ticketId: ticket.identifier,\n title: ticket.title,\n description: ticket.description || '',\n priority: this.mapPriority(ticket.priority),\n labels,\n intentVibe,\n linkedFiles,\n status: ticket.status.name,\n assignee: ticket.assignee?.name || null,\n createdAt: ticket.createdAt,\n updatedAt: ticket.updatedAt,\n };\n\n await this.graph.addNode('linear-ticket', data);\n\n // Link to files if found\n for (const file of linkedFiles) {\n const fileNode = await this.graph.getNode('file', file); // Use ID (path)\n if (fileNode) {\n await this.graph.addEdge(`linear:${ticket.identifier}`, fileNode.id, 'relatedTo');\n }\n }\n }\n\n private extractIntentVibes(title: string, description: string, labels: string[]): string[] {\n const vibes = new Set<string>();\n const text = (title + ' ' + (description || '') + ' ' + labels.join(' ')).toLowerCase();\n\n if (text.includes('performance') || text.includes('slow') || text.includes('optimize')) vibes.add('performance');\n if (text.includes('security') || text.includes('auth') || text.includes('vulnerability')) vibes.add('security');\n if (text.includes('refactor') || text.includes('cleanup') || text.includes('debt')) vibes.add('refactor');\n if (text.includes('feature') || text.includes('new')) vibes.add('feature');\n if (text.includes('bug') || text.includes('fix') || text.includes('broken')) vibes.add('bug');\n if (text.includes('breaking') || text.includes('major change')) vibes.add('breaking-change');\n\n return Array.from(vibes);\n }\n\n private extractLinkedFiles(description: string): string[] {\n if (!description) return [];\n const matches = description.match(/[\\\\w./_-]+\\\\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs)/gi);\n if (!matches) return [];\n return Array.from(new Set(matches.map(m => m.replace(/^\\.\\/+/, ''))));\n }\n\n private mapPriority(priority: number): string {\n switch (priority) {\n case 1: return 'urgent';\n case 2: return 'high';\n case 3: return 'medium';\n case 4: return 'low';\n default: return 'none';\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,WAAW,gBAAgB;AAC3C,SAAS,YAAY;AAoBrB,eAAsB,eAAe,SAMb;AACtB,QAAM,UAAU,QAAQ,WAAW,oBAAoB,QAAW,IAAI;AACtE,QAAM,UAAU,KAAK,SAAS,OAAO;AACrC,QAAM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,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,UAAU,EAAG,OAAM,IAAI,aAAa;AAC/G,QAAI,KAAK,SAAS,UAAU,KAAK,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,eAAe,EAAG,OAAM,IAAI,UAAU;AAC9G,QAAI,KAAK,SAAS,UAAU,KAAK,KAAK,SAAS,SAAS,KAAK,KAAK,SAAS,MAAM,EAAG,OAAM,IAAI,UAAU;AACxG,QAAI,KAAK,SAAS,SAAS,KAAK,KAAK,SAAS,KAAK,EAAG,OAAM,IAAI,SAAS;AACzE,QAAI,KAAK,SAAS,KAAK,KAAK,KAAK,SAAS,KAAK,KAAK,KAAK,SAAS,QAAQ,EAAG,OAAM,IAAI,KAAK;AAC5F,QAAI,KAAK,SAAS,UAAU,KAAK,KAAK,SAAS,cAAc,EAAG,OAAM,IAAI,iBAAiB;AAE3F,WAAO,MAAM,KAAK,KAAK;AAAA,EACzB;AAAA,EAEQ,mBAAmB,aAA+B;AACxD,QAAI,CAAC,YAAa,QAAO,CAAC;AAC1B,UAAM,UAAU,YAAY,MAAM,iDAAiD;AACnF,QAAI,CAAC,QAAS,QAAO,CAAC;AACtB,WAAO,MAAM,KAAK,IAAI,IAAI,QAAQ,IAAI,OAAK,EAAE,QAAQ,UAAU,EAAE,CAAC,CAAC,CAAC;AAAA,EACtE;AAAA,EAEQ,YAAY,UAA0B;AAC5C,YAAQ,UAAU;AAAA,MAChB,KAAK;AAAG,eAAO;AAAA,MACf,KAAK;AAAG,eAAO;AAAA,MACf,KAAK;AAAG,eAAO;AAAA,MACf,KAAK;AAAG,eAAO;AAAA,MACf;AAAS,eAAO;AAAA,IAClB;AAAA,EACF;AACF;","names":["readFile","writeFile","mkdir","existsSync","join","join","existsSync","readFile","join","existsSync","readFile","mkdir","writeFile","data","path","readFile","writeFile","mkdir","existsSync","join","join","needsBootstrap","existsSync","readFile","mkdir","writeFile","path","path","fs","path","fs","path","path","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/checkpoint.ts","../src/utils/autonomy-config.ts","../src/types/autonomy.ts","../src/agent/perceive.ts","../src/agent/diff-analyzer.ts","../src/agent/risk-scorer.ts","../src/agent/pattern-matcher.ts","../src/agent/reason.ts","../src/bootstrap/files.ts","../src/utils/errors.ts","../src/context/sync.ts","../src/context/incident-index.ts","../src/context/file-trie.ts","../src/agent/confidence.ts","../src/agent/pattern-discovery.ts","../src/agent/learning.ts","../src/guardian/learning-engine.ts","../src/ingest/linear-ingester.ts"],"sourcesContent":["/**\n * Checkpoint CLI\n * \n * Save your work context to .trie/ without running a full scan.\n * Think of it as a quick save - captures what you're working on.\n */\n\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile, readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface Checkpoint {\n id: string;\n timestamp: string;\n message?: string;\n files: string[];\n notes?: string;\n createdBy: 'cli' | 'mcp';\n}\n\nexport interface CheckpointLog {\n checkpoints: Checkpoint[];\n lastCheckpoint?: string;\n}\n\n/**\n * Save a checkpoint\n */\nexport async function saveCheckpoint(options: {\n message?: string;\n files?: string[];\n notes?: string;\n workDir?: string;\n createdBy?: 'cli' | 'mcp';\n}): Promise<Checkpoint> {\n const workDir = options.workDir || getWorkingDirectory(undefined, true);\n const trieDir = join(workDir, '.trie');\n const checkpointPath = join(trieDir, 'checkpoints.json');\n \n await mkdir(trieDir, { recursive: true });\n \n // Load existing checkpoints\n let log: CheckpointLog = { checkpoints: [] };\n try {\n if (existsSync(checkpointPath)) {\n log = JSON.parse(await readFile(checkpointPath, 'utf-8'));\n }\n } catch {\n log = { checkpoints: [] };\n }\n \n // Create new checkpoint\n const checkpoint: Checkpoint = {\n id: `cp-${Date.now().toString(36)}`,\n timestamp: new Date().toISOString(),\n files: options.files || [],\n createdBy: options.createdBy || 'cli',\n };\n if (options.message) checkpoint.message = options.message;\n if (options.notes) checkpoint.notes = options.notes;\n \n // Add to log\n log.checkpoints.push(checkpoint);\n log.lastCheckpoint = checkpoint.id;\n \n // Keep last 50 checkpoints\n if (log.checkpoints.length > 50) {\n log.checkpoints = log.checkpoints.slice(-50);\n }\n \n // Save\n await writeFile(checkpointPath, JSON.stringify(log, null, 2));\n \n // Also update AGENTS.md with checkpoint note\n await updateAgentsMdWithCheckpoint(checkpoint, workDir);\n \n return checkpoint;\n}\n\n/**\n * List checkpoints\n */\nexport async function listCheckpoints(workDir?: string): Promise<Checkpoint[]> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const checkpointPath = join(dir, '.trie', 'checkpoints.json');\n \n try {\n if (existsSync(checkpointPath)) {\n const log: CheckpointLog = JSON.parse(await readFile(checkpointPath, 'utf-8'));\n return log.checkpoints;\n }\n } catch {\n // File doesn't exist or is corrupted\n }\n \n return [];\n}\n\n/**\n * Get the last checkpoint\n */\nexport async function getLastCheckpoint(workDir?: string): Promise<Checkpoint | null> {\n const checkpoints = await listCheckpoints(workDir);\n const last = checkpoints[checkpoints.length - 1];\n return last ?? null;\n}\n\n/**\n * Update AGENTS.md with checkpoint info\n */\nasync function updateAgentsMdWithCheckpoint(checkpoint: Checkpoint, workDir: string): Promise<void> {\n const agentsPath = join(workDir, '.trie', 'AGENTS.md');\n \n let content = '';\n try {\n if (existsSync(agentsPath)) {\n content = await readFile(agentsPath, 'utf-8');\n }\n } catch {\n content = '';\n }\n \n // Find or create checkpoint section\n const checkpointSection = `\n## Last Checkpoint\n\n- **ID:** ${checkpoint.id}\n- **Time:** ${checkpoint.timestamp}\n${checkpoint.message ? `- **Message:** ${checkpoint.message}` : ''}\n${checkpoint.files.length > 0 ? `- **Files:** ${checkpoint.files.length} files` : ''}\n${checkpoint.notes ? `- **Notes:** ${checkpoint.notes}` : ''}\n`;\n \n // Replace existing checkpoint section or append\n const checkpointRegex = /## Last Checkpoint[\\s\\S]*?(?=\\n## |\\n---|\\Z)/;\n if (checkpointRegex.test(content)) {\n content = content.replace(checkpointRegex, checkpointSection.trim());\n } else {\n content = content.trim() + '\\n\\n' + checkpointSection.trim() + '\\n';\n }\n \n await writeFile(agentsPath, content);\n}\n\n/**\n * CLI handler for checkpoint command\n */\nexport async function handleCheckpointCommand(args: string[]): Promise<void> {\n const subcommand = args[0] || 'save';\n \n switch (subcommand) {\n case 'save': {\n // Parse options\n let message: string | undefined;\n let notes: string | undefined;\n const files: string[] = [];\n \n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n if (arg === '-m' || arg === '--message') {\n message = args[++i] ?? '';\n } else if (arg === '-n' || arg === '--notes') {\n notes = args[++i] ?? '';\n } else if (arg === '-f' || arg === '--file') {\n const file = args[++i];\n if (file) files.push(file);\n } else if (arg && !arg.startsWith('-')) {\n // Treat as message if no flag\n message = arg;\n }\n }\n \n const opts: { message?: string; files?: string[]; notes?: string } = { files };\n if (message) opts.message = message;\n if (notes) opts.notes = notes;\n const checkpoint = await saveCheckpoint(opts);\n \n console.log('\\n Checkpoint saved\\n');\n console.log(` ID: ${checkpoint.id}`);\n console.log(` Time: ${checkpoint.timestamp}`);\n if (checkpoint.message) {\n console.log(` Message: ${checkpoint.message}`);\n }\n if (checkpoint.files.length > 0) {\n console.log(` Files: ${checkpoint.files.join(', ')}`);\n }\n console.log('\\n Context saved to .trie/\\n');\n break;\n }\n \n case 'list': {\n const checkpoints = await listCheckpoints();\n \n if (checkpoints.length === 0) {\n console.log('\\n No checkpoints yet. Run `trie checkpoint` to save one.\\n');\n return;\n }\n \n console.log('\\n Checkpoints:\\n');\n for (const cp of checkpoints.slice(-10).reverse()) {\n const date = new Date(cp.timestamp).toLocaleString();\n console.log(` ${cp.id} ${date} ${cp.message || '(no message)'}`);\n }\n console.log('');\n break;\n }\n \n case 'last': {\n const checkpoint = await getLastCheckpoint();\n \n if (!checkpoint) {\n console.log('\\n No checkpoints yet. Run `trie checkpoint` to save one.\\n');\n return;\n }\n \n console.log('\\n Last Checkpoint:\\n');\n console.log(` ID: ${checkpoint.id}`);\n console.log(` Time: ${new Date(checkpoint.timestamp).toLocaleString()}`);\n if (checkpoint.message) {\n console.log(` Message: ${checkpoint.message}`);\n }\n if (checkpoint.notes) {\n console.log(` Notes: ${checkpoint.notes}`);\n }\n if (checkpoint.files.length > 0) {\n console.log(` Files: ${checkpoint.files.join(', ')}`);\n }\n console.log('');\n break;\n }\n \n default:\n console.log(`\n Usage: trie checkpoint [command] [options]\n\n Commands:\n save [message] Save a checkpoint (default)\n list List recent checkpoints\n last Show the last checkpoint\n\n Options:\n -m, --message Checkpoint message\n -n, --notes Additional notes\n -f, --file File to include (can be repeated)\n\n Examples:\n trie checkpoint \"finished auth flow\"\n trie checkpoint save -m \"WIP: payment integration\" -n \"needs testing\"\n trie checkpoint list\n`);\n }\n}\n","/**\n * Autonomy Configuration Loader\n * \n * Loads, saves, and manages autonomy settings from .trie/config.json\n */\n\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport type { \n AutonomyConfig, \n IssueOccurrence,\n AutoFixAction,\n PushBlockResult \n} from '../types/autonomy.js';\nimport { DEFAULT_AUTONOMY_CONFIG } from '../types/autonomy.js';\nimport { createHash } from 'crypto';\n\n// ============================================================================\n// Config Loading/Saving\n// ============================================================================\n\n/**\n * Load autonomy config from .trie/config.json\n */\nexport async function loadAutonomyConfig(projectPath: string): Promise<AutonomyConfig> {\n const configPath = join(projectPath, '.trie', 'config.json');\n \n try {\n if (!existsSync(configPath)) {\n return { ...DEFAULT_AUTONOMY_CONFIG };\n }\n \n const content = await readFile(configPath, 'utf-8');\n const config = JSON.parse(content);\n \n // Merge with defaults to ensure all fields exist\n return mergeWithDefaults(config.autonomy || {});\n } catch (error) {\n console.error('Failed to load autonomy config:', error);\n return { ...DEFAULT_AUTONOMY_CONFIG };\n }\n}\n\n/**\n * Save autonomy config to .trie/config.json\n */\nexport async function saveAutonomyConfig(\n projectPath: string, \n autonomyConfig: Partial<AutonomyConfig>\n): Promise<void> {\n const configPath = join(projectPath, '.trie', 'config.json');\n const trieDir = join(projectPath, '.trie');\n \n try {\n // Ensure .trie directory exists\n if (!existsSync(trieDir)) {\n await mkdir(trieDir, { recursive: true });\n }\n \n // Load existing config\n let fullConfig: Record<string, unknown> = {};\n if (existsSync(configPath)) {\n const content = await readFile(configPath, 'utf-8');\n fullConfig = JSON.parse(content);\n }\n \n // Merge autonomy config\n fullConfig.autonomy = mergeWithDefaults(autonomyConfig);\n \n // Save atomically\n const tempPath = configPath + '.tmp';\n await writeFile(tempPath, JSON.stringify(fullConfig, null, 2));\n await writeFile(configPath, JSON.stringify(fullConfig, null, 2));\n \n } catch (error) {\n console.error('Failed to save autonomy config:', error);\n throw error;\n }\n}\n\n/**\n * Merge partial config with defaults\n */\nfunction mergeWithDefaults(partial: Partial<AutonomyConfig>): AutonomyConfig {\n return {\n level: partial.level ?? DEFAULT_AUTONOMY_CONFIG.level,\n autoCheck: {\n ...DEFAULT_AUTONOMY_CONFIG.autoCheck,\n ...(partial.autoCheck || {}),\n },\n autoFix: {\n ...DEFAULT_AUTONOMY_CONFIG.autoFix,\n ...(partial.autoFix || {}),\n },\n pushBlocking: {\n ...DEFAULT_AUTONOMY_CONFIG.pushBlocking,\n ...(partial.pushBlocking || {}),\n },\n progressiveEscalation: {\n ...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation,\n ...(partial.progressiveEscalation || {}),\n thresholds: {\n ...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation.thresholds,\n ...(partial.progressiveEscalation?.thresholds || {}),\n },\n },\n };\n}\n\n// ============================================================================\n// Issue Occurrence Tracking (for progressive escalation)\n// ============================================================================\n\nconst occurrenceCache = new Map<string, Map<string, IssueOccurrence>>();\n\n/**\n * Get occurrence tracker for a project\n */\nasync function getOccurrences(projectPath: string): Promise<Map<string, IssueOccurrence>> {\n if (occurrenceCache.has(projectPath)) {\n return occurrenceCache.get(projectPath)!;\n }\n \n const occurrencesPath = join(projectPath, '.trie', 'memory', 'occurrences.json');\n const occurrences = new Map<string, IssueOccurrence>();\n \n try {\n if (existsSync(occurrencesPath)) {\n const content = await readFile(occurrencesPath, 'utf-8');\n const data = JSON.parse(content);\n for (const [hash, occ] of Object.entries(data)) {\n occurrences.set(hash, occ as IssueOccurrence);\n }\n }\n } catch {\n // Start fresh\n }\n \n occurrenceCache.set(projectPath, occurrences);\n return occurrences;\n}\n\n/**\n * Save occurrences to disk\n */\nasync function saveOccurrences(projectPath: string): Promise<void> {\n const occurrences = occurrenceCache.get(projectPath);\n if (!occurrences) return;\n \n const occurrencesPath = join(projectPath, '.trie', 'memory', 'occurrences.json');\n const memoryDir = join(projectPath, '.trie', 'memory');\n \n try {\n if (!existsSync(memoryDir)) {\n await mkdir(memoryDir, { recursive: true });\n }\n \n const data: Record<string, IssueOccurrence> = {};\n for (const [hash, occ] of occurrences.entries()) {\n data[hash] = occ;\n }\n \n await writeFile(occurrencesPath, JSON.stringify(data, null, 2));\n } catch (error) {\n console.error('Failed to save occurrences:', error);\n }\n}\n\n/**\n * Create a hash for an issue (for deduplication)\n */\nexport function createIssueHash(file: string, line: number | undefined, issueType: string): string {\n const input = `${file}:${line || 0}:${issueType}`;\n return createHash('md5').update(input).digest('hex').slice(0, 12);\n}\n\n/**\n * Track an issue occurrence\n */\nexport async function trackIssueOccurrence(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string,\n config: AutonomyConfig\n): Promise<IssueOccurrence> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n const now = Date.now();\n \n let occurrence = occurrences.get(hash);\n \n if (occurrence) {\n // Check if within time window\n const windowMs = config.progressiveEscalation.windowMs;\n if (now - occurrence.firstSeen > windowMs) {\n // Reset if outside window\n occurrence = {\n hash,\n firstSeen: now,\n lastSeen: now,\n count: 1,\n escalationLevel: 'suggest',\n notified: false,\n bypassed: false,\n bypassHistory: occurrence.bypassHistory, // Keep bypass history\n };\n } else {\n // Increment within window\n occurrence.lastSeen = now;\n occurrence.count++;\n \n // Update escalation level\n const thresholds = config.progressiveEscalation.thresholds;\n if (occurrence.count >= thresholds.block) {\n occurrence.escalationLevel = 'block';\n } else if (occurrence.count >= thresholds.escalate) {\n occurrence.escalationLevel = 'escalate';\n } else if (occurrence.count >= thresholds.autoCheck) {\n occurrence.escalationLevel = 'autoCheck';\n }\n }\n } else {\n // New occurrence\n occurrence = {\n hash,\n firstSeen: now,\n lastSeen: now,\n count: 1,\n escalationLevel: 'suggest',\n notified: false,\n bypassed: false,\n bypassHistory: [],\n };\n }\n \n occurrences.set(hash, occurrence);\n await saveOccurrences(projectPath);\n \n return occurrence;\n}\n\n/**\n * Get escalation level for an issue\n */\nexport async function getEscalationLevel(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string\n): Promise<IssueOccurrence['escalationLevel']> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n \n const occurrence = occurrences.get(hash);\n return occurrence?.escalationLevel ?? 'suggest';\n}\n\n/**\n * Record a bypass\n */\nexport async function recordBypass(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string,\n method: string,\n reason?: string\n): Promise<void> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n \n const occurrence = occurrences.get(hash);\n if (occurrence) {\n occurrence.bypassed = true;\n occurrence.bypassHistory.push({\n timestamp: Date.now(),\n method,\n ...(reason !== undefined ? { reason } : {}),\n });\n await saveOccurrences(projectPath);\n }\n}\n\n// ============================================================================\n// Auto-fix Helpers\n// ============================================================================\n\n/**\n * Check if a fix should be auto-applied based on config\n */\nexport function shouldAutoFix(\n fix: AutoFixAction,\n config: AutonomyConfig\n): boolean {\n if (!config.autoFix.enabled) {\n return false;\n }\n \n // Check if category is allowed\n const allowedCategories = config.autoFix.categories as string[];\n if (!allowedCategories.includes(fix.category) && \n !allowedCategories.includes('all')) {\n return false;\n }\n \n // Check if specific fix type is allowed\n if (config.autoFix.allowedFixTypes.length > 0 &&\n !config.autoFix.allowedFixTypes.includes(fix.type)) {\n return false;\n }\n \n // Check confidence threshold (require high confidence for auto-fix)\n if (fix.confidence < 0.9) {\n return false;\n }\n \n return true;\n}\n\n/**\n * Group fixes by file for batch application\n */\nexport function groupFixesByFile(fixes: AutoFixAction[]): Map<string, AutoFixAction[]> {\n const grouped = new Map<string, AutoFixAction[]>();\n \n for (const fix of fixes) {\n const existing = grouped.get(fix.file) || [];\n existing.push(fix);\n grouped.set(fix.file, existing);\n }\n \n return grouped;\n}\n\n// ============================================================================\n// Push Blocking Helpers\n// ============================================================================\n\n/**\n * Check if push should be blocked\n */\nexport function shouldBlockPush(\n issues: Array<{ severity: string; file: string; line?: number; issue: string }>,\n config: AutonomyConfig\n): PushBlockResult {\n if (!config.pushBlocking.enabled) {\n return {\n blocked: false,\n blockingIssues: [],\n bypassed: false,\n };\n }\n \n // Find blocking issues\n const blockingIssues = issues.filter(issue => \n config.pushBlocking.blockOn.includes(issue.severity as 'critical' | 'serious' | 'moderate')\n );\n \n if (blockingIssues.length === 0) {\n return {\n blocked: false,\n blockingIssues: [],\n bypassed: false,\n };\n }\n \n // Check for bypass\n const envBypass = process.env.TRIE_BYPASS === '1' || process.env.TRIE_BYPASS === 'true';\n \n if (envBypass && config.pushBlocking.allowBypass) {\n return {\n blocked: false,\n blockingIssues,\n bypassed: true,\n bypassMethod: 'env',\n };\n }\n \n // Build bypass instructions\n const bypassInstructions = buildBypassInstructions(config);\n \n return {\n blocked: true,\n reason: `${blockingIssues.length} ${blockingIssues[0]?.severity || 'critical'} issue(s) must be fixed before pushing`,\n blockingIssues,\n bypassInstructions,\n bypassed: false,\n };\n}\n\n/**\n * Build bypass instructions based on config\n */\nfunction buildBypassInstructions(config: AutonomyConfig): string {\n const instructions: string[] = [];\n \n if (config.pushBlocking.bypassMethods.includes('env')) {\n instructions.push('• Set TRIE_BYPASS=1 to bypass: TRIE_BYPASS=1 git push');\n }\n \n if (config.pushBlocking.bypassMethods.includes('flag')) {\n instructions.push('• Use --no-verify flag: git push --no-verify');\n }\n \n if (config.pushBlocking.bypassMethods.includes('confirm')) {\n instructions.push('• Run: trie bypass --confirm to bypass this push');\n }\n \n return instructions.join('\\n');\n}\n\n// ============================================================================\n// Singleton Config Cache\n// ============================================================================\n\nconst configCache = new Map<string, { config: AutonomyConfig; loadedAt: number }>();\nconst CACHE_TTL = 60000; // 1 minute\n\n/**\n * Get autonomy config with caching\n */\nexport async function getAutonomyConfig(projectPath: string): Promise<AutonomyConfig> {\n const cached = configCache.get(projectPath);\n \n if (cached && Date.now() - cached.loadedAt < CACHE_TTL) {\n return cached.config;\n }\n \n const config = await loadAutonomyConfig(projectPath);\n configCache.set(projectPath, { config, loadedAt: Date.now() });\n \n return config;\n}\n\n/**\n * Clear config cache (for testing or after config changes)\n */\nexport function clearConfigCache(): void {\n configCache.clear();\n occurrenceCache.clear();\n}\n","/**\n * Autonomy Configuration Types\n * \n * Controls how autonomous Trie behaves:\n * - Auto-check: Run full checks when issues detected\n * - Auto-fix: Apply fixes with human confirmation\n * - Push blocking: Block git push on critical issues\n * - Progressive escalation: Escalate based on occurrence count\n */\n\n/**\n * Overall autonomy level\n */\nexport type AutonomyLevel = \n | 'passive' // Only report, never act\n | 'suggest' // Suggest actions, don't execute\n | 'proactive' // Auto-check, ask before fixing\n | 'aggressive'; // Auto-check, auto-fix trivial, block on critical\n\n/**\n * Auto-check configuration\n */\nexport interface AutoCheckConfig {\n /** Enable auto-running full checks */\n enabled: boolean;\n /** Issue count threshold to trigger auto-check */\n threshold: number;\n /** Always trigger on critical issues */\n onCritical: boolean;\n /** Cooldown between auto-checks (ms) */\n cooldownMs: number;\n}\n\n/**\n * Auto-fix configuration\n */\nexport interface AutoFixConfig {\n /** Enable auto-fix suggestions */\n enabled: boolean;\n /** Always ask user before applying fixes (human-in-the-loop) */\n askFirst: boolean;\n /** Categories of fixes to auto-apply */\n categories: ('trivial' | 'safe' | 'moderate' | 'all')[];\n /** Specific fix types to auto-apply */\n allowedFixTypes: string[];\n}\n\n/**\n * Push blocking configuration\n */\nexport interface PushBlockingConfig {\n /** Enable push blocking */\n enabled: boolean;\n /** Allow user to bypass with flag */\n allowBypass: boolean;\n /** Severities that trigger blocking */\n blockOn: ('critical' | 'serious' | 'moderate')[];\n /** Bypass methods */\n bypassMethods: ('env' | 'flag' | 'confirm')[];\n /** Log bypasses for audit */\n logBypasses: boolean;\n}\n\n/**\n * Progressive escalation thresholds\n */\nexport interface ProgressiveEscalationConfig {\n /** Enable progressive escalation */\n enabled: boolean;\n /** Thresholds for different actions */\n thresholds: {\n /** First occurrence: suggest fix */\n suggest: number;\n /** N occurrences: auto-run full check */\n autoCheck: number;\n /** N occurrences: escalate to Slack/email */\n escalate: number;\n /** N occurrences: block until fixed */\n block: number;\n };\n /** Time window for counting occurrences (ms) */\n windowMs: number;\n}\n\n/**\n * Full autonomy configuration\n */\nexport interface AutonomyConfig {\n /** Overall autonomy level (can be overridden by specific settings) */\n level: AutonomyLevel;\n /** Auto-check settings */\n autoCheck: AutoCheckConfig;\n /** Auto-fix settings */\n autoFix: AutoFixConfig;\n /** Push blocking settings */\n pushBlocking: PushBlockingConfig;\n /** Progressive escalation settings */\n progressiveEscalation: ProgressiveEscalationConfig;\n}\n\n/**\n * Default autonomy configuration - proactive but safe\n */\nexport const DEFAULT_AUTONOMY_CONFIG: AutonomyConfig = {\n level: 'proactive',\n autoCheck: {\n enabled: true,\n threshold: 5,\n onCritical: true,\n cooldownMs: 30000, // 30 seconds\n },\n autoFix: {\n enabled: true,\n askFirst: true, // Always ask (human-in-the-loop)\n categories: ['trivial', 'safe'],\n allowedFixTypes: [\n 'remove-console-log',\n 'remove-unused-import',\n 'add-missing-await',\n 'fix-typo',\n ],\n },\n pushBlocking: {\n enabled: true,\n allowBypass: true,\n blockOn: ['critical'],\n bypassMethods: ['env', 'flag', 'confirm'],\n logBypasses: true,\n },\n progressiveEscalation: {\n enabled: true,\n thresholds: {\n suggest: 1,\n autoCheck: 3,\n escalate: 5,\n block: 10,\n },\n windowMs: 24 * 60 * 60 * 1000, // 24 hours\n },\n};\n\n/**\n * Issue occurrence tracking for progressive escalation\n */\nexport interface IssueOccurrence {\n /** Issue hash (file + line + type) */\n hash: string;\n /** First seen timestamp */\n firstSeen: number;\n /** Last seen timestamp */\n lastSeen: number;\n /** Total occurrence count */\n count: number;\n /** Current escalation level */\n escalationLevel: 'suggest' | 'autoCheck' | 'escalate' | 'block';\n /** Whether user has been notified at current level */\n notified: boolean;\n /** Whether issue has been bypassed */\n bypassed: boolean;\n /** Bypass history */\n bypassHistory: Array<{\n timestamp: number;\n method: string;\n reason?: string;\n }>;\n}\n\n/**\n * Auto-fix action\n */\nexport interface AutoFixAction {\n /** Unique ID for this fix */\n id: string;\n /** File to fix */\n file: string;\n /** Line number */\n line?: number;\n /** Original code */\n original: string;\n /** Fixed code */\n fixed: string;\n /** Type of fix */\n type: string;\n /** Category of fix */\n category: 'trivial' | 'safe' | 'moderate' | 'risky';\n /** Description of what the fix does */\n description: string;\n /** Confidence in the fix (0-1) */\n confidence: number;\n}\n\n/**\n * Push block result\n */\nexport interface PushBlockResult {\n /** Whether push is blocked */\n blocked: boolean;\n /** Reason for blocking */\n reason?: string;\n /** Issues causing the block */\n blockingIssues: Array<{\n file: string;\n line?: number;\n severity: string;\n issue: string;\n }>;\n /** Bypass instructions */\n bypassInstructions?: string;\n /** Whether user chose to bypass */\n bypassed: boolean;\n /** Bypass method used */\n bypassMethod?: string;\n}\n","import path from 'node:path';\n\nimport { analyzeDiff, type DiffSummary } from './diff-analyzer.js';\nimport {\n getStagedChanges,\n getUncommittedChanges,\n getWorkingTreeDiff,\n type Change\n} from './git.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNode, FileNodeData } from '../context/nodes.js';\n\nexport interface PerceptionResult {\n staged: Change[];\n unstaged: Change[];\n diffSummary: DiffSummary;\n changeNodeId?: string;\n}\n\nexport async function perceiveCurrentChanges(\n projectPath: string,\n graph?: ContextGraph\n): Promise<PerceptionResult> {\n const ctxGraph = graph ?? new ContextGraph(projectPath);\n\n const [staged, unstaged] = await Promise.all([\n getStagedChanges(projectPath),\n getUncommittedChanges(projectPath)\n ]);\n\n const stagedDiff = await getWorkingTreeDiff(projectPath, true);\n const unstagedDiff = await getWorkingTreeDiff(projectPath, false);\n const combinedDiff = [stagedDiff, unstagedDiff].filter(Boolean).join('\\n');\n const diffSummary = analyzeDiff(combinedDiff);\n\n const filesTouched = new Set<string>();\n staged.forEach((c) => filesTouched.add(c.path));\n unstaged.forEach((c) => filesTouched.add(c.path));\n diffSummary.files.forEach((f) => filesTouched.add(f.filePath));\n\n const changeId = await upsertWorkingChange(ctxGraph, Array.from(filesTouched), projectPath);\n\n const result: PerceptionResult = {\n staged,\n unstaged,\n diffSummary\n };\n if (changeId) result.changeNodeId = changeId;\n return result;\n}\n\nasync function upsertWorkingChange(\n graph: ContextGraph,\n files: string[],\n projectPath: string\n): Promise<string | undefined> {\n if (files.length === 0) return undefined;\n\n const now = new Date().toISOString();\n const change = await graph.addNode('change', {\n commitHash: null,\n files,\n message: 'workspace changes',\n diff: null,\n author: null,\n timestamp: now,\n outcome: 'unknown'\n });\n\n for (const filePath of files) {\n const fileNode = await ensureFileNode(graph, filePath, projectPath);\n await graph.addEdge(change.id, fileNode.id, 'affects');\n }\n\n return change.id;\n}\n\nasync function ensureFileNode(\n graph: ContextGraph,\n filePath: string,\n projectPath: string\n): Promise<FileNode> {\n const normalized = path.resolve(projectPath, filePath);\n const existing = await graph.getNode('file', normalized);\n\n const now = new Date().toISOString();\n if (existing) {\n const data = existing.data as FileNodeData;\n await graph.updateNode('file', existing.id, {\n changeCount: (data.changeCount ?? 0) + 1,\n lastChanged: now\n });\n return (await graph.getNode('file', existing.id)) as FileNode;\n }\n\n const data: FileNodeData = {\n path: filePath,\n extension: path.extname(filePath),\n purpose: '',\n riskLevel: 'medium',\n whyRisky: null,\n changeCount: 1,\n lastChanged: now,\n incidentCount: 0,\n createdAt: now\n };\n\n return (await graph.addNode('file', data)) as FileNode;\n}\n","export interface DiffFileSummary {\n filePath: string;\n added: number;\n removed: number;\n functionsModified: string[];\n riskyPatterns: string[];\n}\n\nexport interface DiffSummary {\n files: DiffFileSummary[];\n totalAdded: number;\n totalRemoved: number;\n riskyFiles: string[];\n}\n\nconst RISKY_PATTERNS = [/auth/i, /token/i, /password/i, /secret/i, /validate/i, /sanitize/i];\n\nexport function analyzeDiff(diff: string): DiffSummary {\n const files: DiffFileSummary[] = [];\n let current: DiffFileSummary | null = null;\n\n const lines = diff.split('\\n');\n\n for (const line of lines) {\n if (line.startsWith('+++ b/')) {\n const filePath = line.replace('+++ b/', '').trim();\n current = {\n filePath,\n added: 0,\n removed: 0,\n functionsModified: [],\n riskyPatterns: []\n };\n files.push(current);\n continue;\n }\n\n if (!current) {\n continue;\n }\n\n if (line.startsWith('@@')) {\n // Capture function names or signatures in hunk headers\n const match = line.match(/@@.*?(function\\s+([\\w$]+)|class\\s+([\\w$]+)|([\\w$]+\\s*\\())/i);\n const fnName = match?.[2] || match?.[3] || match?.[4];\n if (fnName) {\n current.functionsModified.push(fnName.replace('(', '').trim());\n }\n continue;\n }\n\n if (line.startsWith('+') && !line.startsWith('+++')) {\n current.added += 1;\n markRisk(line, current);\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n current.removed += 1;\n markRisk(line, current);\n }\n }\n\n const totalAdded = files.reduce((acc, f) => acc + f.added, 0);\n const totalRemoved = files.reduce((acc, f) => acc + f.removed, 0);\n const riskyFiles = files.filter((f) => f.riskyPatterns.length > 0).map((f) => f.filePath);\n\n return {\n files,\n totalAdded,\n totalRemoved,\n riskyFiles\n };\n}\n\nfunction markRisk(line: string, file: DiffFileSummary): void {\n for (const pattern of RISKY_PATTERNS) {\n if (pattern.test(line)) {\n const label = pattern.toString();\n if (!file.riskyPatterns.includes(label)) {\n file.riskyPatterns.push(label);\n }\n }\n }\n}\n","import path from 'node:path';\n\nimport type { RiskLevel } from '../types/index.js';\nimport type { PatternNode } from '../context/types.js';\nimport type { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData, IncidentNode } from '../context/nodes.js';\n\nexport interface FileRiskResult {\n file: string;\n score: number;\n level: RiskLevel;\n reasons: string[];\n incidents: IncidentNode[];\n matchedPatterns: PatternNode[];\n}\n\nexport interface ChangeRiskResult {\n files: FileRiskResult[];\n overall: RiskLevel;\n score: number;\n shouldEscalate: boolean;\n}\n\nconst BASE_RISK: Record<RiskLevel, number> = {\n low: 10,\n medium: 35,\n high: 65,\n critical: 85\n};\n\nconst SENSITIVE_PATHS: { pattern: RegExp; weight: number; reason: string }[] = [\n { pattern: /auth|login|token|session/i, weight: 20, reason: 'touches authentication' },\n { pattern: /payment|billing|stripe|paypal|checkout/i, weight: 25, reason: 'touches payments' },\n { pattern: /secret|credential|env|config\\/security/i, weight: 15, reason: 'touches secrets/security config' },\n { pattern: /gdpr|privacy|pii|phi/i, weight: 15, reason: 'touches sensitive data' }\n];\n\nfunction levelFromScore(score: number): RiskLevel {\n if (score >= 90) return 'critical';\n if (score >= 65) return 'high';\n if (score >= 40) return 'medium';\n return 'low';\n}\n\nexport async function scoreFile(\n graph: ContextGraph,\n filePath: string,\n matchedPatterns: PatternNode[] = []\n): Promise<FileRiskResult> {\n const reasons: string[] = [];\n const normalized = path.resolve(graph.projectRoot, filePath);\n const node = await graph.getNode('file', normalized);\n const incidents = await graph.getIncidentsForFile(filePath);\n\n let score = 10;\n const data = node?.data as FileNodeData | undefined;\n\n if (data) {\n score = BASE_RISK[data.riskLevel] ?? score;\n reasons.push(`baseline ${data.riskLevel}`);\n\n if (data.incidentCount > 0) {\n const incBoost = Math.min(data.incidentCount * 12, 36);\n score += incBoost;\n reasons.push(`historical incidents (+${incBoost})`);\n }\n\n if (data.changeCount > 5) {\n const changeBoost = Math.min((data.changeCount - 5) * 2, 12);\n score += changeBoost;\n reasons.push(`frequent changes (+${changeBoost})`);\n }\n\n if (data.lastChanged) {\n const lastChanged = new Date(data.lastChanged).getTime();\n const days = (Date.now() - lastChanged) / (1000 * 60 * 60 * 24);\n if (days > 60 && data.incidentCount === 0) {\n score -= 5;\n reasons.push('stable for 60d (-5)');\n }\n }\n }\n\n for (const { pattern, weight, reason } of SENSITIVE_PATHS) {\n if (pattern.test(filePath)) {\n score += weight;\n reasons.push(reason);\n }\n }\n\n if (matchedPatterns.length > 0) {\n const patternBoost = Math.min(\n matchedPatterns.reduce((acc, p) => acc + (p.data.confidence ?? 50) / 10, 0),\n 20\n );\n score += patternBoost;\n reasons.push(`pattern match (+${Math.round(patternBoost)})`);\n }\n\n if (incidents.length > 0) {\n const timestamps = incidents\n .map((i) => new Date(i.data.timestamp).getTime())\n .sort((a, b) => b - a);\n const recent = timestamps[0]!;\n const daysSince = (Date.now() - recent) / (1000 * 60 * 60 * 24);\n if (daysSince > 90) {\n score -= 5;\n reasons.push('no incidents in 90d (-5)');\n } else {\n score += 8;\n reasons.push('recent incident (+8)');\n }\n }\n\n const level = levelFromScore(score);\n return {\n file: filePath,\n score,\n level,\n reasons,\n incidents,\n matchedPatterns\n };\n}\n\nexport async function scoreChangeSet(\n graph: ContextGraph,\n files: string[],\n patternMatches: Record<string, PatternNode[]> = {}\n): Promise<ChangeRiskResult> {\n const fileResults: FileRiskResult[] = [];\n\n for (const file of files) {\n const patterns = patternMatches[file] ?? [];\n fileResults.push(await scoreFile(graph, file, patterns));\n }\n\n // Aggregate: use max file score, but boost if many files touched\n const maxScore = Math.max(...fileResults.map((f) => f.score), 10);\n const spreadBoost = files.length > 5 ? Math.min((files.length - 5) * 2, 10) : 0;\n const overallScore = maxScore + spreadBoost;\n const overall = levelFromScore(overallScore);\n\n const shouldEscalate = overall === 'critical' || overall === 'high';\n\n return {\n files: fileResults,\n overall,\n score: overallScore,\n shouldEscalate\n };\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { PatternNode } from '../context/nodes.js';\n\nexport interface PatternMatch {\n file: string;\n pattern: PatternNode;\n confidence: number;\n isAntiPattern: boolean;\n}\n\nexport async function matchPatternsForFiles(\n graph: ContextGraph,\n files: string[]\n): Promise<{ matches: PatternMatch[]; byFile: Record<string, PatternNode[]> }> {\n const matches: PatternMatch[] = [];\n const byFile: Record<string, PatternNode[]> = {};\n\n for (const file of files) {\n const patterns = await graph.getPatternsForFile(file);\n if (patterns.length === 0) continue;\n\n byFile[file] = patterns;\n\n for (const pattern of patterns) {\n matches.push({\n file,\n pattern,\n confidence: pattern.data.confidence,\n isAntiPattern: pattern.data.isAntiPattern\n });\n }\n }\n\n return { matches, byFile };\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { IncidentNode, PatternNode } from '../context/nodes.js';\nimport type { RiskLevel, AgentResult, CodeContext, ScanContext } from '../types/index.js';\nimport { scoreChangeSet, type ChangeRiskResult, type FileRiskResult } from './risk-scorer.js';\nimport { matchPatternsForFiles } from './pattern-matcher.js';\nimport { Triager } from '../orchestrator/triager.js';\nimport { Executor } from '../orchestrator/executor.js';\n\nexport interface Reasoning {\n riskLevel: RiskLevel;\n shouldBlock: boolean;\n explanation: string;\n relevantIncidents: IncidentNode[];\n matchedPatterns: PatternNode[];\n recommendation: string;\n files: FileRiskResult[];\n agentResults?: AgentResult[];\n}\n\nexport interface ReasonOptions {\n runAgents?: boolean;\n codeContext?: CodeContext;\n scanContext?: Partial<ScanContext>;\n}\n\nfunction buildDefaultCodeContext(): CodeContext {\n return {\n changeType: 'general',\n isNewFeature: false,\n touchesUserData: false,\n touchesAuth: false,\n touchesPayments: false,\n touchesDatabase: false,\n touchesAPI: false,\n touchesUI: false,\n touchesHealthData: false,\n touchesSecurityConfig: false,\n linesChanged: 50,\n filePatterns: [],\n framework: 'unknown',\n language: 'typescript',\n touchesCrypto: false,\n touchesFileSystem: false,\n touchesThirdPartyAPI: false,\n touchesLogging: false,\n touchesErrorHandling: false,\n hasTests: false,\n complexity: 'medium',\n patterns: {\n hasAsyncCode: false,\n hasFormHandling: false,\n hasFileUploads: false,\n hasEmailHandling: false,\n hasRateLimiting: false,\n hasWebSockets: false,\n hasCaching: false,\n hasQueue: false\n }\n };\n}\n\nfunction buildExplanation(result: ChangeRiskResult): string {\n const top = [...result.files].sort((a, b) => b.score - a.score)[0];\n if (!top) return `Risk level ${result.overall} (no files provided)`;\n return `Risk level ${result.overall} because ${top.file} ${top.reasons.join(', ')}`;\n}\n\nfunction buildRecommendation(risk: RiskLevel, hasAntiPattern: boolean): string {\n if (hasAntiPattern || risk === 'critical') {\n return 'Block until reviewed: address anti-patterns and rerun targeted tests.';\n }\n if (risk === 'high') {\n return 'Require senior review and run full test suite before merge.';\n }\n if (risk === 'medium') {\n return 'Proceed with caution; run impacted tests and sanity checks.';\n }\n return 'Low risk; proceed but keep an eye on recent changes.';\n}\n\nexport async function reasonAboutChanges(\n projectPath: string,\n files: string[],\n options: ReasonOptions = {}\n): Promise<Reasoning> {\n const graph = new ContextGraph(projectPath);\n const { matches, byFile } = await matchPatternsForFiles(graph, files);\n const changeRisk = await scoreChangeSet(graph, files, byFile);\n\n const incidents: IncidentNode[] = [];\n for (const file of files) {\n const fileIncidents = await graph.getIncidentsForFile(file);\n incidents.push(...fileIncidents);\n }\n\n const hasAntiPattern = matches.some((m) => m.isAntiPattern);\n const riskLevel: RiskLevel = hasAntiPattern ? 'critical' : changeRisk.overall;\n const shouldBlock = hasAntiPattern || riskLevel === 'critical' || riskLevel === 'high';\n\n const reasoning: Reasoning = {\n riskLevel,\n shouldBlock,\n explanation: buildExplanation(changeRisk),\n relevantIncidents: incidents,\n matchedPatterns: matches.map((m) => m.pattern),\n recommendation: buildRecommendation(riskLevel, hasAntiPattern),\n files: changeRisk.files\n };\n\n if (options.runAgents) {\n const codeContext = options.codeContext ?? buildDefaultCodeContext();\n const triager = new Triager();\n const agents = await triager.selectAgents(codeContext, riskLevel);\n\n if (agents.length > 0) {\n const executor = new Executor();\n const scanContext: ScanContext = {\n workingDir: projectPath,\n ...options.scanContext\n };\n if (codeContext.framework) scanContext.framework = codeContext.framework;\n if (codeContext.language) scanContext.language = codeContext.language;\n\n reasoning.agentResults = await executor.executeAgents(agents, files, scanContext, {\n parallel: true,\n timeoutMs: options.scanContext?.config?.timeoutMs ?? 60000\n });\n } else {\n reasoning.agentResults = [];\n }\n }\n\n return reasoning;\n}\n\n// Convenience wrapper to keep future CLI/MCP integration simple\nexport async function reasonAboutChangesHumanReadable(\n projectPath: string,\n files: string[],\n options: ReasonOptions = {}\n) {\n const reasoning = await reasonAboutChanges(projectPath, files, options);\n const { humanizeReasoning } = await import('../comprehension/index.js');\n return humanizeReasoning(reasoning);\n}\n","/**\n * Bootstrap File System\n * \n * Manages workspace files that inject context at scan start.\n * Files: BOOTSTRAP.md, RULES.md, TEAM.md\n */\n\nimport { readFile, writeFile, unlink, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { detectStack, type DetectedStack } from './stack-detector.js';\n\nexport interface BootstrapFile {\n name: string;\n path: string;\n type: 'user' | 'auto' | 'one-time';\n exists: boolean;\n content?: string;\n}\n\nexport interface BootstrapContext {\n files: BootstrapFile[];\n injectedContent: string;\n needsBootstrap: boolean;\n}\n\ninterface BootstrapFileSpec {\n name: string;\n type: 'user' | 'auto' | 'one-time';\n description: string;\n}\n\nconst BOOTSTRAP_FILES: BootstrapFileSpec[] = [\n { name: 'PROJECT.md', type: 'user', description: 'Project overview and conventions' },\n { name: 'RULES.md', type: 'user', description: 'Coding standards agents enforce' },\n { name: 'TEAM.md', type: 'user', description: 'Team ownership and escalation' },\n { name: 'BOOTSTRAP.md', type: 'one-time', description: 'First-run setup (deleted after)' },\n { name: 'AGENTS.md', type: 'auto', description: 'Auto-generated scan context' },\n];\n\n/**\n * Load bootstrap files and inject into agent context\n */\nexport async function loadBootstrapContext(workDir?: string): Promise<BootstrapContext> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const trieDir = join(projectDir, '.trie');\n const files: BootstrapFile[] = [];\n const contentParts: string[] = [];\n let needsBootstrap = false;\n\n for (const file of BOOTSTRAP_FILES) {\n const filePath = join(trieDir, file.name);\n const exists = existsSync(filePath);\n \n if (file.name === 'BOOTSTRAP.md' && exists) {\n needsBootstrap = true;\n }\n \n let content: string | undefined;\n if (exists) {\n try {\n content = await readFile(filePath, 'utf-8');\n if (content.trim() && file.type !== 'one-time') {\n contentParts.push(`<!-- ${file.name} -->\\n${content}`);\n }\n } catch {\n // Skip files that can't be read\n }\n }\n\n const fileEntry: BootstrapFile = {\n name: file.name,\n path: filePath,\n type: file.type,\n exists,\n };\n if (content) fileEntry.content = content;\n files.push(fileEntry);\n }\n\n return {\n files,\n injectedContent: contentParts.join('\\n\\n---\\n\\n'),\n needsBootstrap,\n };\n}\n\n/**\n * Initialize bootstrap files for a new project\n */\nexport async function initializeBootstrapFiles(options: {\n workDir?: string;\n force?: boolean;\n skipBootstrap?: boolean;\n} = {}): Promise<{ created: string[]; skipped: string[]; stack: DetectedStack }> {\n const projectDir = options.workDir || getWorkingDirectory(undefined, true);\n const trieDir = join(projectDir, '.trie');\n await mkdir(trieDir, { recursive: true });\n\n const created: string[] = [];\n const skipped: string[] = [];\n\n const stack = await detectStack(projectDir);\n\n for (const file of BOOTSTRAP_FILES) {\n const filePath = join(trieDir, file.name);\n const exists = existsSync(filePath);\n\n if (exists && !options.force) {\n skipped.push(file.name);\n continue;\n }\n\n if (file.name === 'BOOTSTRAP.md' && options.skipBootstrap) {\n skipped.push(file.name);\n continue;\n }\n\n if (file.name === 'AGENTS.md') {\n skipped.push(file.name);\n continue;\n }\n\n const template = getFileTemplate(file.name, stack);\n if (template) {\n await writeFile(filePath, template);\n created.push(file.name);\n }\n }\n\n return { created, skipped, stack };\n}\n\n/**\n * Mark bootstrap as complete (delete BOOTSTRAP.md)\n */\nexport async function completeBootstrap(workDir?: string): Promise<boolean> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const bootstrapPath = join(projectDir, '.trie', 'BOOTSTRAP.md');\n\n try {\n await unlink(bootstrapPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if bootstrap is needed (BOOTSTRAP.md exists)\n */\nexport function needsBootstrap(workDir?: string): boolean {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const bootstrapPath = join(projectDir, '.trie', 'BOOTSTRAP.md');\n return existsSync(bootstrapPath);\n}\n\n/**\n * Get rules from RULES.md\n */\nexport async function loadRules(workDir?: string): Promise<string | null> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const rulesPath = join(projectDir, '.trie', 'RULES.md');\n \n try {\n if (existsSync(rulesPath)) {\n return await readFile(rulesPath, 'utf-8');\n }\n } catch {\n // Rules file doesn't exist or can't be read\n }\n \n return null;\n}\n\n/**\n * Get team info from TEAM.md\n */\nexport async function loadTeamInfo(workDir?: string): Promise<string | null> {\n const projectDir = workDir || getWorkingDirectory(undefined, true);\n const teamPath = join(projectDir, '.trie', 'TEAM.md');\n \n try {\n if (existsSync(teamPath)) {\n return await readFile(teamPath, 'utf-8');\n }\n } catch {\n // Team file doesn't exist or can't be read\n }\n \n return null;\n}\n\nfunction getFileTemplate(fileName: string, stack: DetectedStack): string | null {\n switch (fileName) {\n case 'PROJECT.md':\n return getProjectTemplate(stack);\n case 'RULES.md':\n return getRulesTemplate(stack);\n case 'TEAM.md':\n return getTeamTemplate();\n case 'BOOTSTRAP.md':\n return getBootstrapTemplate(stack);\n default:\n return null;\n }\n}\n\nfunction getProjectTemplate(stack: DetectedStack): string {\n const lines: string[] = ['# Project Overview', '', '> Define your project context here. AI assistants read this first.', ''];\n \n lines.push('## Description', '', '[Describe what this project does and who it\\'s for]', '');\n \n lines.push('## Technology Stack', '');\n if (stack.framework) lines.push(`- **Framework:** ${stack.framework}`);\n if (stack.language) lines.push(`- **Language:** ${stack.language}`);\n if (stack.database) lines.push(`- **Database:** ${stack.database}`);\n if (stack.auth) lines.push(`- **Auth:** ${stack.auth}`);\n if (!stack.framework && !stack.language && !stack.database) {\n lines.push('[Add your technology stack]');\n }\n lines.push('');\n \n lines.push('## Architecture', '', '[Key patterns and design decisions]', '');\n lines.push('## Coding Conventions', '', '[Style rules agents should follow]', '');\n lines.push('## AI Instructions', '', 'When working on this project:', '1. [Instruction 1]', '2. [Instruction 2]', '3. [Instruction 3]', '');\n lines.push('---', '', '*Edit this file to provide project context to AI assistants.*');\n \n return lines.join('\\n');\n}\n\nfunction getRulesTemplate(stack: DetectedStack): string {\n const packageManager = stack.packageManager || 'npm';\n \n return `# Project Rules\n\n> These rules are enforced by Trie agents during scans.\n> Violations appear as issues with [RULES] prefix.\n\n## Code Style\n\n1. Use named exports, not default exports\n2. Prefer \\`${packageManager}\\` for package management\n3. Maximum file length: 300 lines\n4. Use TypeScript strict mode\n\n## Testing Requirements\n\n1. Critical paths require unit tests\n2. API endpoints require integration tests\n3. Minimum coverage: 70%\n\n## Security Rules\n\n1. Never log sensitive data (passwords, tokens, PII)\n2. All API routes require authentication\n3. Rate limiting required on public endpoints\n4. SQL queries must use parameterized statements\n\n## Review Requirements\n\n1. All PRs require at least 1 reviewer\n2. Security-sensitive changes require security review\n3. Database migrations require review\n\n---\n\n*Edit this file to define your project's coding standards.*\n`;\n}\n\nfunction getTeamTemplate(): string {\n return `# Team Structure\n\n## Code Ownership\n\n| Area | Owner | Backup | Review Required |\n|------|-------|--------|-----------------|\n| \\`/src/api/\\` | @backend-team | - | 1 approver |\n| \\`/src/ui/\\` | @frontend-team | - | 1 approver |\n| \\`/src/auth/\\` | @security-team | - | Security review |\n\n## Escalation\n\n| Severity | First Contact | Escalate To | SLA |\n|----------|--------------|-------------|-----|\n| Critical | Team lead | CTO | 1 hour |\n| Serious | PR reviewer | Team lead | 4 hours |\n| Moderate | Self-serve | - | 1 day |\n\n## Contacts\n\n- **Security:** [email/slack]\n- **Privacy:** [email/slack]\n- **Emergencies:** [phone/pager]\n\n---\n\n*Edit this file to define your team structure.*\n`;\n}\n\nfunction getBootstrapTemplate(stack: DetectedStack): string {\n const skillCommands = stack.suggestedSkills\n .map(s => `trie skills add ${s}`)\n .join('\\n');\n\n const agentList = stack.suggestedAgents.join(', ');\n\n const lines: string[] = [\n '# Trie Bootstrap Checklist',\n '',\n 'This file guides your first scan setup. **Delete when complete.**',\n '',\n '## Auto-Detected Stack',\n '',\n 'Based on your project, Trie detected:',\n ];\n \n if (stack.framework) lines.push(`- **Framework:** ${stack.framework}`);\n if (stack.language) lines.push(`- **Language:** ${stack.language}`);\n if (stack.database) lines.push(`- **Database:** ${stack.database}`);\n if (stack.auth) lines.push(`- **Auth:** ${stack.auth}`);\n \n lines.push('', '## Recommended Actions', '', '### 1. Skills to Install', 'Based on your stack, consider installing:', '```bash');\n lines.push(skillCommands || '# No specific skills detected - browse https://skills.sh');\n lines.push('```', '', '### 2. Agents to Enable', `Your stack suggests these agents: ${agentList || 'security, privacy, bugs'}`, '');\n lines.push('### 3. Configure Rules', 'Add your coding standards to `.trie/RULES.md`.', '');\n lines.push('### 4. Run First Scan', '```bash', 'trie scan', '```', '');\n lines.push('---', '', '**Delete this file after completing setup.** Run:', '```bash', 'rm .trie/BOOTSTRAP.md', '```');\n \n return lines.join('\\n');\n}\n","export class TrieError extends Error {\n code: string;\n recoverable: boolean;\n userMessage: string;\n\n constructor(message: string, code: string, userMessage: string, recoverable = true) {\n super(message);\n this.code = code;\n this.recoverable = recoverable;\n this.userMessage = userMessage;\n }\n}\n\nexport class GraphError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'GRAPH_ERROR',\n 'Trie had trouble accessing its memory. Try again or re-run trie reconcile.',\n true\n );\n }\n}\n\nexport class GitError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'GIT_ERROR',\n 'Git info is unavailable. Is this a git repo? Commit once, or pass --files to trie check.',\n true\n );\n }\n}\n\nexport class NetworkError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'NETWORK_ERROR',\n 'Network unavailable. Running in offline mode; AI calls skipped.',\n true\n );\n }\n}\n\nexport class MissingAPIKeyError extends TrieError {\n constructor(message = 'Missing ANTHROPIC_API_KEY') {\n super(\n message,\n 'MISSING_API_KEY',\n 'No API key detected. Set ANTHROPIC_API_KEY for AI-powered analysis (deeper issue detection, smarter fixes). Running in pattern-only mode.',\n true\n );\n }\n}\n\nexport function formatFriendlyError(error: unknown): { userMessage: string; code: string } {\n if (error instanceof TrieError) {\n return { userMessage: error.userMessage, code: error.code };\n }\n return {\n userMessage: 'Something went wrong. Try again or run with --offline.',\n code: 'UNKNOWN'\n };\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { ContextGraph } from './graph.js';\nimport type { ContextSnapshot } from './types.js';\n\nconst DEFAULT_JSON_NAME = 'context.json';\n\nexport async function exportToJson(graph: ContextGraph, targetPath?: string): Promise<string> {\n const snapshot = await graph.getSnapshot();\n const json = JSON.stringify(snapshot, null, 2);\n\n const outputPath = targetPath ?? path.join(graph.projectRoot, '.trie', DEFAULT_JSON_NAME);\n await fs.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.writeFile(outputPath, json, 'utf8');\n\n return json;\n}\n\nexport async function importFromJson(\n graph: ContextGraph,\n json: string,\n sourcePath?: string\n): Promise<void> {\n const payload =\n json.trim().length > 0\n ? json\n : await fs.readFile(sourcePath ?? path.join(graph.projectRoot, '.trie', DEFAULT_JSON_NAME), 'utf8');\n\n const snapshot = JSON.parse(payload) as ContextSnapshot;\n await graph.applySnapshot(snapshot);\n}\n","import path from 'node:path';\n\nimport type { IncidentNode } from './nodes.js';\nimport type { ContextGraph } from './graph.js';\nimport { FilePathTrie, type IncidentMetadata } from './file-trie.js';\n\nexport interface IncidentIndexOptions {\n persistPath?: string;\n}\n\nexport class IncidentIndex {\n private readonly graph: ContextGraph;\n private readonly trie: FilePathTrie;\n private readonly projectRoot: string;\n\n constructor(graph: ContextGraph, projectRoot: string, options?: IncidentIndexOptions) {\n this.graph = graph;\n this.projectRoot = projectRoot;\n this.trie = new FilePathTrie(\n options?.persistPath ?? path.join(projectRoot, '.trie', 'incident-trie.json')\n );\n }\n\n static async build(graph: ContextGraph, projectRoot: string, options?: IncidentIndexOptions): Promise<IncidentIndex> {\n const index = new IncidentIndex(graph, projectRoot, options);\n await index.rebuild();\n return index;\n }\n\n async rebuild(): Promise<void> {\n const nodes = await this.graph.listNodes();\n const incidents = nodes.filter((n) => n.type === 'incident') as IncidentNode[];\n\n for (const incident of incidents) {\n const files = await this.getFilesForIncident(incident.id);\n this.addIncidentToTrie(incident, files);\n }\n }\n\n addIncidentToTrie(incident: IncidentNode, files: string[]): void {\n const meta: IncidentMetadata = {\n id: incident.id,\n file: '',\n description: incident.data.description,\n severity: incident.data.severity,\n timestamp: incident.data.timestamp,\n };\n\n for (const file of files) {\n const normalized = this.normalizePath(file);\n this.trie.addIncident(normalized, { ...meta, file: normalized });\n }\n }\n\n getFileTrie(): FilePathTrie {\n return this.trie;\n }\n\n private async getFilesForIncident(incidentId: string): Promise<string[]> {\n const files = new Set<string>();\n const edges = await this.graph.getEdges(incidentId, 'both');\n\n // Traverse connected changes to pull file lists\n for (const edge of edges) {\n if (edge.type === 'causedBy' || edge.type === 'leadTo') {\n // Identify the change node id regardless of direction\n const changeId = edge.type === 'causedBy' ? edge.to_id : edge.from_id;\n const change = await this.graph.getNode('change', changeId);\n if (change?.data && 'files' in change.data && Array.isArray(change.data.files)) {\n (change.data.files as string[]).forEach((f: string) => files.add(f));\n }\n }\n\n // If there are direct file links, capture them as well\n if (edge.type === 'affects') {\n const fileNode =\n (await this.graph.getNode('file', edge.to_id)) ||\n (await this.graph.getNode('file', edge.from_id));\n if (fileNode && typeof (fileNode as any).data?.path === 'string') {\n files.add((fileNode as any).data.path);\n }\n }\n }\n\n return Array.from(files);\n }\n\n private normalizePath(filePath: string): string {\n const absolute = path.isAbsolute(filePath) ? filePath : path.join(this.projectRoot, filePath);\n const relative = path.relative(this.projectRoot, absolute);\n return relative.replace(/\\\\/g, '/');\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { performance } from 'node:perf_hooks';\n\nimport { Trie } from '../trie/trie.js';\n\nexport interface IncidentMetadata {\n id: string;\n file: string;\n description: string;\n severity: 'minor' | 'major' | 'critical' | string;\n timestamp: string;\n}\n\nexport interface HotZone {\n path: string;\n incidentCount: number;\n confidence: number;\n}\n\nfunction normalizePath(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n return normalized.startsWith('./') ? normalized.slice(2) : normalized;\n}\n\nexport class FilePathTrie {\n private trie: Trie<IncidentMetadata[]> = new Trie();\n private persistPath?: string;\n\n constructor(persistPath?: string) {\n if (persistPath) this.persistPath = persistPath;\n if (persistPath && fs.existsSync(persistPath)) {\n try {\n const raw = fs.readFileSync(persistPath, 'utf-8');\n if (raw.trim().length > 0) {\n const json = JSON.parse(raw);\n this.trie = Trie.fromJSON<IncidentMetadata[]>(json);\n }\n } catch {\n this.trie = new Trie();\n }\n }\n }\n\n addIncident(filePath: string, incident: IncidentMetadata): void {\n const key = normalizePath(filePath);\n const existing = this.trie.search(key);\n const incidents = existing.found && Array.isArray(existing.value) ? existing.value : [];\n incidents.push(incident);\n this.trie.insert(key, incidents);\n this.persist();\n }\n\n getIncidents(filePath: string): IncidentMetadata[] {\n const key = normalizePath(filePath);\n const result = this.trie.search(key);\n return result.found && Array.isArray(result.value) ? result.value : [];\n }\n\n getDirectoryIncidents(prefix: string): IncidentMetadata[] {\n const normalizedPrefix = normalizePath(prefix);\n const matches = this.trie.getWithPrefix(normalizedPrefix);\n return matches.flatMap((m) => (Array.isArray(m.value) ? m.value : [])).filter(Boolean);\n }\n\n getHotZones(threshold: number): HotZone[] {\n const matches = this.trie.getWithPrefix('');\n const zones: HotZone[] = [];\n\n for (const match of matches) {\n const incidents = Array.isArray(match.value) ? match.value : [];\n if (incidents.length >= threshold) {\n zones.push({\n path: match.pattern,\n incidentCount: incidents.length,\n confidence: this.calculateConfidence(incidents.length),\n });\n }\n }\n\n return zones.sort((a, b) => b.incidentCount - a.incidentCount);\n }\n\n suggestPaths(partial: string, limit = 5): Array<{ path: string; incidentCount: number }> {\n const normalized = normalizePath(partial);\n const results = this.trie.getWithPrefix(normalized);\n return results\n .map((r) => ({\n path: r.pattern,\n incidentCount: Array.isArray(r.value) ? r.value.length : 0,\n }))\n .sort((a, b) => b.incidentCount - a.incidentCount)\n .slice(0, limit);\n }\n\n timeLookup(path: string): number {\n const start = performance.now();\n this.getIncidents(path);\n return performance.now() - start;\n }\n\n toJSON(): object {\n return this.trie.toJSON();\n }\n\n private calculateConfidence(count: number): number {\n const capped = Math.min(count, 10);\n return Math.round((capped / 10) * 100) / 100; // 0-1 scale\n }\n\n private persist(): void {\n if (!this.persistPath) return;\n try {\n const dir = path.dirname(this.persistPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(this.persistPath, JSON.stringify(this.trie.toJSON()), 'utf-8');\n } catch {\n // Persistence is best-effort; ignore failures\n }\n }\n}\n","/**\n * Lightweight Bayesian-style confidence updater.\n * Treats confidence as probability in [0,1].\n */\n\nexport function bayesianUpdate(prior: number, evidence: number, weight = 1): number {\n const p = clamp(prior);\n const e = clamp(evidence);\n const w = Math.max(0, weight);\n // Blend prior with evidence weighted by w\n const posterior = (p * (1 - w)) + (e * w);\n return clamp(posterior);\n}\n\nexport function adjustConfidence(current: number, outcome: 'positive' | 'negative', step = 0.1): number {\n const delta = outcome === 'positive' ? step : -step;\n return clamp(current + delta);\n}\n\nfunction clamp(value: number): number {\n if (Number.isNaN(value)) return 0.5;\n return Math.min(1, Math.max(0, value));\n}\n","import { IncidentIndex } from '../context/incident-index.js';\nimport type { ContextGraph } from '../context/graph.js';\nimport type { ChangeNode, IncidentNode } from '../context/nodes.js';\n\nexport interface HotPattern {\n type: 'file' | 'directory';\n path: string;\n incidentCount: number;\n confidence: number;\n relatedFiles?: string[];\n}\n\nexport interface CoOccurrencePattern {\n files: [string, string];\n coOccurrences: number;\n confidence: number;\n}\n\nexport class TriePatternDiscovery {\n constructor(\n private graph: ContextGraph,\n private incidentIndex: IncidentIndex\n ) {}\n\n discoverHotPatterns(threshold = 3): HotPattern[] {\n const trie = this.incidentIndex.getFileTrie();\n const hotZones = trie.getHotZones(threshold);\n\n return hotZones.map((zone) => ({\n type: zone.path.endsWith('/') ? 'directory' : 'file',\n path: zone.path,\n incidentCount: zone.incidentCount,\n confidence: zone.confidence,\n relatedFiles: trie.getDirectoryIncidents(zone.path).map((i) => i.file)\n }));\n }\n\n async discoverCoOccurrences(minCount = 3): Promise<CoOccurrencePattern[]> {\n const incidents = await this.getAllIncidents();\n const coOccurrences: Map<string, Map<string, number>> = new Map();\n\n for (const inc of incidents) {\n const files = await this.getFilesForIncident(inc);\n for (let i = 0; i < files.length; i++) {\n for (let j = i + 1; j < files.length; j++) {\n const a = files[i]!;\n const b = files[j]!;\n if (!coOccurrences.has(a)) coOccurrences.set(a, new Map());\n const counts = coOccurrences.get(a)!;\n counts.set(b, (counts.get(b) || 0) + 1);\n }\n }\n }\n\n const patterns: CoOccurrencePattern[] = [];\n for (const [a, map] of coOccurrences.entries()) {\n for (const [b, count] of map.entries()) {\n if (count >= minCount) {\n const denom = Math.min(\n this.incidentIndex.getFileTrie().getIncidents(a).length || 1,\n this.incidentIndex.getFileTrie().getIncidents(b).length || 1\n );\n patterns.push({\n files: [a, b],\n coOccurrences: count,\n confidence: Math.min(1, count / denom)\n });\n }\n }\n }\n\n return patterns.sort((x, y) => y.confidence - x.confidence);\n }\n\n private async getAllIncidents(): Promise<IncidentNode[]> {\n const nodes = await this.graph.listNodes();\n return nodes.filter((n) => n.type === 'incident') as IncidentNode[];\n }\n\n private async getFilesForIncident(incident: IncidentNode): Promise<string[]> {\n const files = new Set<string>();\n const edges = await this.graph.getEdges(incident.id, 'both');\n\n for (const edge of edges) {\n if (edge.type === 'causedBy' || edge.type === 'leadTo') {\n const changeId = edge.type === 'causedBy' ? edge.to_id : edge.from_id;\n const change = await this.graph.getNode('change', changeId) as ChangeNode | null;\n if (change?.data?.files && Array.isArray(change.data.files)) {\n change.data.files.forEach((f: string) => files.add(f));\n }\n }\n }\n\n return Array.from(files).map((f) => f.replace(/\\\\/g, '/'));\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { IncidentNode, PatternNode } from '../context/nodes.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { adjustConfidence } from './confidence.js';\nimport { TriePatternDiscovery } from './pattern-discovery.js';\n\nexport class LearningSystem {\n private incidentIndex: IncidentIndex;\n private discovery: TriePatternDiscovery;\n\n constructor(private graph: ContextGraph, projectPath: string) {\n this.incidentIndex = new IncidentIndex(graph, projectPath);\n this.discovery = new TriePatternDiscovery(graph, this.incidentIndex);\n }\n\n async onWarningHeeded(files: string[]): Promise<void> {\n await this.adjustPatterns(files, 'positive');\n }\n\n async onWarningIgnored(files: string[]): Promise<void> {\n await this.adjustPatterns(files, 'negative');\n }\n\n async onIncidentReported(incidentId: string, files: string[]): Promise<void> {\n const incident = await this.graph.getNode('incident', incidentId);\n if (incident && incident.type === 'incident') {\n this.incidentIndex.addIncidentToTrie(incident as IncidentNode, files);\n }\n await this.discoverAndStorePatterns();\n }\n\n async onFeedback(helpful: boolean, files: string[] = []): Promise<void> {\n await this.adjustPatterns(files, helpful ? 'positive' : 'negative');\n }\n\n private async adjustPatterns(files: string[], outcome: 'positive' | 'negative'): Promise<void> {\n if (!files.length) return;\n for (const file of files) {\n const patterns = await this.graph.getPatternsForFile(file);\n await Promise.all(patterns.map((p) => this.updatePatternConfidence(p, outcome)));\n }\n }\n\n private async updatePatternConfidence(pattern: PatternNode, outcome: 'positive' | 'negative'): Promise<void> {\n const current = pattern.data.confidence ?? 0.5;\n const updated = adjustConfidence(current, outcome, 0.05);\n await this.graph.updateNode('pattern', pattern.id, { confidence: updated, lastSeen: new Date().toISOString() });\n }\n\n private async discoverAndStorePatterns(): Promise<void> {\n const hotPatterns = this.discovery.discoverHotPatterns();\n for (const hot of hotPatterns) {\n await this.graph.addNode('pattern', {\n description: `${hot.type === 'directory' ? 'Directory' : 'File'} hot zone: ${hot.path}`,\n appliesTo: [hot.path],\n confidence: hot.confidence,\n occurrences: hot.incidentCount,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: true,\n source: 'local'\n });\n }\n }\n}\n","import { getRecentCommits, getDiff } from '../agent/git.js';\nimport { storeIssues } from '../memory/issue-store.js';\nimport { scanForVulnerabilities } from '../trie/vulnerability-signatures.js';\nimport { scanForVibeCodeIssues } from '../trie/vibe-code-signatures.js';\nimport type { Issue } from '../types/index.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { DecisionNodeData } from '../context/nodes.js';\nimport { LearningSystem } from '../agent/learning.js';\nimport path from 'node:path';\n\nexport interface LearningResult {\n learned: number;\n source: 'git-history' | 'manual-feedback';\n}\n\nexport class LearningEngine {\n private readonly projectPath: string;\n private readonly graph: ContextGraph;\n private readonly learningSystem: LearningSystem;\n\n constructor(projectPath: string, graph?: ContextGraph) {\n this.projectPath = projectPath;\n this.graph = graph || new ContextGraph(projectPath);\n this.learningSystem = new LearningSystem(this.graph, projectPath);\n }\n\n /**\n * Unified learning method: Scans history AND processes manual feedback\n */\n async learn(options: { \n limit?: number; \n manualFeedback?: { helpful: boolean; files: string[]; note?: string } \n } = {}): Promise<LearningResult[]> {\n const results: LearningResult[] = [];\n\n // 1. Implicit Learning from Git History\n if (!options.manualFeedback) {\n const implicitCount = await this.learnFromHistory(options.limit || 20);\n results.push({ learned: implicitCount, source: 'git-history' });\n }\n\n // 2. Manual Feedback Learning\n if (options.manualFeedback) {\n await this.recordManualFeedback(\n options.manualFeedback.helpful, \n options.manualFeedback.files, \n options.manualFeedback.note\n );\n results.push({ learned: options.manualFeedback.files.length || 1, source: 'manual-feedback' });\n }\n\n return results;\n }\n\n /**\n * Scan recent commits for implicit failure signals (reverts, fixes)\n */\n private async learnFromHistory(limit: number = 20): Promise<number> {\n const commits = await getRecentCommits(this.projectPath, limit);\n const issuesToStore: Issue[] = [];\n\n for (const commit of commits) {\n const isRevert = commit.message.toLowerCase().includes('revert') || commit.message.startsWith('Revert \"');\n const isFix = /fix(es|ed)?\\s+#\\d+/i.test(commit.message) || commit.message.toLowerCase().includes('bugfix');\n\n if (isRevert || isFix) {\n const type = isRevert ? 'revert' : 'fix';\n const diff = await getDiff(this.projectPath, commit.hash);\n const files = this.extractFilesFromDiff(diff);\n \n for (const file of files) {\n const learnedIssues = await this.extractIssuesFromDiff(diff, file, type, commit.message);\n issuesToStore.push(...learnedIssues);\n }\n }\n }\n\n if (issuesToStore.length > 0) {\n const result = await storeIssues(issuesToStore, path.basename(this.projectPath), this.projectPath);\n return result.stored;\n }\n\n return 0;\n }\n\n /**\n * Record manual feedback (trie ok/bad) and adjust pattern confidence\n */\n private async recordManualFeedback(helpful: boolean, files: string[], note?: string): Promise<void> {\n const context = files[0] ?? 'unspecified';\n const decision = await this.graph.addNode('decision', {\n context,\n decision: helpful ? 'helpful' : 'not helpful',\n reasoning: note ?? null,\n outcome: helpful ? 'good' : 'bad',\n timestamp: new Date().toISOString(),\n } satisfies DecisionNodeData);\n\n if (files.length > 0) {\n for (const file of files) {\n const fileNode = await this.graph.getNode('file', file);\n if (fileNode) {\n await this.graph.addEdge(decision.id, fileNode.id, 'affects');\n }\n }\n await this.learningSystem.onFeedback(helpful, files);\n }\n }\n\n private extractFilesFromDiff(diff: string): string[] {\n const files = new Set<string>();\n const lines = diff.split('\\n');\n for (const line of lines) {\n if (line.startsWith('+++ b/')) {\n files.add(line.slice(6));\n }\n }\n return Array.from(files);\n }\n\n private async extractIssuesFromDiff(diff: string, file: string, type: 'revert' | 'fix', message: string): Promise<Issue[]> {\n const issues: Issue[] = [];\n const badLines = this.getBadLinesFromDiff(diff, file, type);\n const content = badLines.join('\\n');\n\n if (!content) return [];\n\n const vulnerabilities = await scanForVulnerabilities(content, file);\n const vibeIssues = await scanForVibeCodeIssues(content, file);\n\n const allMatches = [...vulnerabilities, ...vibeIssues];\n\n for (const match of allMatches) {\n issues.push({\n id: `implicit-${type}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n severity: 'serious',\n issue: `Implicit failure detected via ${type}: ${message}. Linked to pattern: ${match.category}`,\n fix: `Review the ${type} commit and avoid this pattern in ${file}.`,\n file: file,\n confidence: 0.7,\n autoFixable: false,\n agent: 'implicit-learning',\n category: match.category\n });\n }\n\n if (issues.length === 0) {\n issues.push({\n id: `implicit-${type}-${Date.now()}`,\n severity: 'moderate',\n issue: `Historical ${type} detected: ${message}`,\n fix: `Review the changes in ${file} from this commit to avoid regression.`,\n file: file,\n confidence: 0.5,\n autoFixable: false,\n agent: 'implicit-learning'\n });\n }\n\n return issues;\n }\n\n private getBadLinesFromDiff(diff: string, file: string, type: 'revert' | 'fix'): string[] {\n const badLines: string[] = [];\n const lines = diff.split('\\n');\n let inTargetFile = false;\n\n for (const line of lines) {\n if (line.startsWith('+++ b/') || line.startsWith('--- a/')) {\n inTargetFile = line.includes(file);\n continue;\n }\n\n if (!inTargetFile) continue;\n\n if (type === 'fix' && line.startsWith('-') && !line.startsWith('---')) {\n badLines.push(line.slice(1));\n } else if (type === 'revert' && line.startsWith('+') && !line.startsWith('+++')) {\n badLines.push(line.slice(1));\n }\n }\n\n return badLines;\n }\n}\n","import { loadConfig } from '../config/loader.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { LinearTicketNodeData } from '../context/nodes.js';\n\nexport interface LinearTicket {\n id: string;\n identifier: string;\n title: string;\n description: string;\n priority: number;\n status: { name: string };\n assignee?: { name: string };\n labels: { nodes: { name: string }[] };\n createdAt: string;\n updatedAt: string;\n}\n\nexport class LinearIngester {\n private readonly graph: ContextGraph;\n\n constructor(_projectPath: string, graph: ContextGraph) {\n this.graph = graph;\n }\n\n async syncTickets(): Promise<void> {\n const apiKey = await this.getApiKey();\n if (!apiKey) {\n console.warn('Linear API key not found. Run \"trie linear auth <key>\" to enable ticket sync.');\n return;\n }\n\n const tickets = await this.fetchActiveTickets(apiKey);\n for (const ticket of tickets) {\n await this.ingestTicket(ticket);\n }\n }\n\n private async getApiKey(): Promise<string | null> {\n const config = await loadConfig();\n return (config.apiKeys as any)?.linear || process.env.LINEAR_API_KEY || null;\n }\n\n private async fetchActiveTickets(apiKey: string): Promise<LinearTicket[]> {\n const query = `\n query {\n issues(filter: { state: { type: { in: [\"started\", \"unstarted\"] } } }) {\n nodes {\n id\n identifier\n title\n description\n priority\n status {\n name\n }\n assignee {\n name\n }\n labels {\n nodes {\n name\n }\n }\n createdAt\n updatedAt\n }\n }\n }\n `;\n\n const response = await fetch('https://api.linear.app/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': apiKey,\n },\n body: JSON.stringify({ query }),\n });\n\n if (!response.ok) {\n throw new Error(`Linear API error: ${response.statusText}`);\n }\n\n const data = (await response.json()) as any;\n return data.data.issues.nodes as LinearTicket[];\n }\n\n private async ingestTicket(ticket: LinearTicket): Promise<void> {\n const labels = ticket.labels.nodes.map(l => l.name);\n const intentVibe = this.extractIntentVibes(ticket.title, ticket.description, labels);\n \n // Attempt to find linked files in description or via labels (heuristic)\n const linkedFiles = this.extractLinkedFiles(ticket.description);\n\n const data: LinearTicketNodeData = {\n ticketId: ticket.identifier,\n title: ticket.title,\n description: ticket.description || '',\n priority: this.mapPriority(ticket.priority),\n labels,\n intentVibe,\n linkedFiles,\n status: ticket.status.name,\n assignee: ticket.assignee?.name || null,\n createdAt: ticket.createdAt,\n updatedAt: ticket.updatedAt,\n };\n\n await this.graph.addNode('linear-ticket', data);\n\n // Link to files if found\n for (const file of linkedFiles) {\n const fileNode = await this.graph.getNode('file', file); // Use ID (path)\n if (fileNode) {\n await this.graph.addEdge(`linear:${ticket.identifier}`, fileNode.id, 'relatedTo');\n }\n }\n }\n\n private extractIntentVibes(title: string, description: string, labels: string[]): string[] {\n const vibes = new Set<string>();\n const text = (title + ' ' + (description || '') + ' ' + labels.join(' ')).toLowerCase();\n\n if (text.includes('performance') || text.includes('slow') || text.includes('optimize')) vibes.add('performance');\n if (text.includes('security') || text.includes('auth') || text.includes('vulnerability')) vibes.add('security');\n if (text.includes('refactor') || text.includes('cleanup') || text.includes('debt')) vibes.add('refactor');\n if (text.includes('feature') || text.includes('new')) vibes.add('feature');\n if (text.includes('bug') || text.includes('fix') || text.includes('broken')) vibes.add('bug');\n if (text.includes('breaking') || text.includes('major change')) vibes.add('breaking-change');\n\n return Array.from(vibes);\n }\n\n private extractLinkedFiles(description: string): string[] {\n if (!description) return [];\n const matches = description.match(/[\\\\w./_-]+\\\\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs)/gi);\n if (!matches) return [];\n return Array.from(new Set(matches.map(m => m.replace(/^\\.\\/+/, ''))));\n }\n\n private mapPriority(priority: number): string {\n switch (priority) {\n case 1: return 'urgent';\n case 2: return 'high';\n case 3: return 'medium';\n case 4: return 'low';\n default: return 'none';\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,WAAW,gBAAgB;AAC3C,SAAS,YAAY;AAoBrB,eAAsB,eAAe,SAMb;AACtB,QAAM,UAAU,QAAQ,WAAW,oBAAoB,QAAW,IAAI;AACtE,QAAM,UAAU,KAAK,SAAS,OAAO;AACrC,QAAM,iBAAiB,KAAK,SAAS,kBAAkB;AAEvD,QAAM,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AAGxC,MAAI,MAAqB,EAAE,aAAa,CAAC,EAAE;AAC3C,MAAI;AACF,QAAI,WAAW,cAAc,GAAG;AAC9B,YAAM,KAAK,MAAM,MAAM,SAAS,gBAAgB,OAAO,CAAC;AAAA,IAC1D;AAAA,EACF,QAAQ;AACN,UAAM,EAAE,aAAa,CAAC,EAAE;AAAA,EAC1B;AAGA,QAAM,aAAyB;AAAA,IAC7B,IAAI,MAAM,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;AAAA,IACjC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IAClC,OAAO,QAAQ,SAAS,CAAC;AAAA,IACzB,WAAW,QAAQ,aAAa;AAAA,EAClC;AACA,MAAI,QAAQ,QAAS,YAAW,UAAU,QAAQ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;AAAA,EAEQ,mBAAmB,aAA+B;AACxD,QAAI,CAAC,YAAa,QAAO,CAAC;AAC1B,UAAM,UAAU,YAAY,MAAM,iDAAiD;AACnF,QAAI,CAAC,QAAS,QAAO,CAAC;AACtB,WAAO,MAAM,KAAK,IAAI,IAAI,QAAQ,IAAI,OAAK,EAAE,QAAQ,UAAU,EAAE,CAAC,CAAC,CAAC;AAAA,EACtE;AAAA,EAEQ,YAAY,UAA0B;AAC5C,YAAQ,UAAU;AAAA,MAChB,KAAK;AAAG,eAAO;AAAA,MACf,KAAK;AAAG,eAAO;AAAA,MACf,KAAK;AAAG,eAAO;AAAA,MACf,KAAK;AAAG,eAAO;AAAA,MACf;AAAS,eAAO;AAAA,IAClB;AAAA,EACF;AACF;","names":["readFile","writeFile","mkdir","existsSync","join","join","existsSync","readFile","join","existsSync","readFile","mkdir","writeFile","data","path","readFile","writeFile","mkdir","existsSync","join","join","needsBootstrap","existsSync","readFile","mkdir","writeFile","path","path","fs","path","fs","path","path","path"]}
|