compound-agent 1.0.0
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/CHANGELOG.md +412 -0
- package/LICENSE +21 -0
- package/README.md +331 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +5600 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +971 -0
- package/dist/index.js +1576 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp.d.ts +77 -0
- package/dist/mcp.js +1025 -0
- package/dist/mcp.js.map +1 -0
- package/dist/types--TsW4ZqX.d.ts +2601 -0
- package/package.json +80 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli-utils.ts","../src/memory/embeddings/model.ts","../src/memory/embeddings/nomic.ts","../src/memory/types.ts","../src/memory/storage/jsonl.ts","../src/memory/storage/sqlite/availability.ts","../src/memory/storage/sqlite/schema.ts","../src/memory/storage/sqlite/connection.ts","../src/memory/storage/sqlite/cache.ts","../src/memory/storage/sqlite/sync.ts","../src/memory/storage/sqlite/search.ts","../src/utils.ts","../src/memory/storage/compact.ts","../src/memory/search/vector.ts","../src/memory/search/ranking.ts","../src/compound/clustering.ts","../src/compound/types.ts","../src/compound/io.ts","../src/compound/synthesis.ts","../src/commands/compound.ts","../src/memory/capture/quality.ts","../src/memory/capture/triggers.ts","../src/memory/capture/integration.ts","../src/memory/retrieval/session.ts","../src/memory/retrieval/plan.ts","../src/audit/checks/lessons.ts","../src/rules/types.ts","../src/rules/checks/glob-utils.ts","../src/rules/checks/file-pattern.ts","../src/rules/checks/file-size.ts","../src/rules/checks/script.ts","../src/rules/engine.ts","../src/audit/checks/patterns.ts","../src/audit/checks/rules.ts","../src/audit/engine.ts","../src/audit/types.ts","../src/index.ts","../src/setup/templates.ts","../src/setup/claude-helpers.ts","../src/setup/templates/agents-phase11.ts","../src/setup/templates/agents-review.ts","../src/setup/templates/agents-workflow.ts","../src/setup/templates/agents.ts","../src/setup/templates/commands.ts","../src/setup/templates/skills.ts","../src/setup/primitives.ts","../src/setup/all.ts","../src/cli-error-format.ts","../src/setup/claude.ts","../src/setup/download-model.ts","../src/setup/hooks.ts","../src/setup/init.ts","../src/commands/shared.ts","../src/commands/management-helpers.ts","../src/commands/management-crud.ts","../src/commands/management-invalidation.ts","../src/commands/management-io.ts","../src/commands/management-maintenance.ts","../src/commands/management-prime.ts","../src/commands/audit.ts","../src/commands/rules.ts","../src/commands/test-summary.ts","../src/commands/capture.ts","../src/commands/retrieval.ts","../src/commands/index.ts","../src/cli.ts"],"names":["getLlama","join","require","dirname","createHash","mtime","readFile","mkdir","lines","appendFile","z","program","DEFAULT_LIMIT","SeveritySchema","statSync","readFileSync","existsSync","createRequire","homedir","writeFile","rename","content","result","modelPath","size","chalk","execSync","mkdirSync","formatSource"],"mappings":";;;;;;;;;;;;;;;AAYO,SAAS,YAAY,KAAA,EAAuB;AACjD,EAAA,IAAI,KAAA,KAAU,GAAG,OAAO,KAAA;AACxB,EAAA,IAAI,KAAA,GAAQ,IAAA,EAAM,OAAO,CAAA,EAAG,KAAK,CAAA,EAAA,CAAA;AACjC,EAAA,MAAM,KAAK,KAAA,GAAQ,IAAA;AACnB,EAAA,IAAI,KAAK,IAAA,EAAM,OAAO,GAAG,EAAA,CAAG,OAAA,CAAQ,CAAC,CAAC,CAAA,GAAA,CAAA;AACtC,EAAA,MAAM,KAAK,EAAA,GAAK,IAAA;AAChB,EAAA,OAAO,CAAA,EAAG,EAAA,CAAG,OAAA,CAAQ,CAAC,CAAC,CAAA,GAAA,CAAA;AACzB;AAUO,SAAS,UAAA,CAAW,OAAe,IAAA,EAAsB;AAC9D,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,KAAA,EAAO,EAAE,CAAA;AACjC,EAAA,IAAI,MAAA,CAAO,KAAA,CAAM,MAAM,CAAA,IAAK,UAAU,CAAA,EAAG;AACvC,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,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vB,EAAA,IAAI;AACF,IAAA,OAAA,EAAQ;AAAA,EACV,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAIA,OAAA,CAAQ,EAAA,CAAG,UAAU,MAAM;AACzB,EAAA,OAAA,EAAQ;AACR,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA;AACD,OAAA,CAAQ,EAAA,CAAG,WAAW,MAAM;AAC1B,EAAA,OAAA,EAAQ;AACR,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA;AAMD,IAAM,OAAA,GAAU,IAAI,OAAA,EAAQ;AAG5B,OAAA,CACG,OAAO,eAAA,EAAiB,sBAAsB,CAAA,CAC9C,MAAA,CAAO,eAAe,+BAA+B,CAAA;AAExD,OAAA,CACG,KAAK,IAAI,CAAA,CACT,YAAY,0DAA0D,CAAA,CACtE,QAAQ,OAAO,CAAA;AAMlB,uBAAA,CAAwB,OAAO,CAAA;AAC/B,yBAAA,CAA0B,OAAO,CAAA;AACjC,0BAAA,CAA2B,OAAO,CAAA;AAClC,qBAAA,CAAsB,OAAO,CAAA;AAC7B,wBAAA,CAAyB,OAAO,CAAA;AAMhC,OAAA,CAAQ,KAAA,EAAM","file":"cli.js","sourcesContent":["/**\n * CLI utility functions.\n *\n * Pure functions extracted from cli.ts for testability.\n */\n\n/**\n * Format bytes to human-readable string.\n *\n * @param bytes - Number of bytes\n * @returns Formatted string (e.g., \"1.5 KB\", \"2.0 MB\")\n */\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n if (bytes < 1024) return `${bytes} B`;\n const kb = bytes / 1024;\n if (kb < 1024) return `${kb.toFixed(1)} KB`;\n const mb = kb / 1024;\n return `${mb.toFixed(1)} MB`;\n}\n\n/**\n * Parse limit option and validate it's a positive integer.\n *\n * @param value - String value from command option\n * @param name - Option name for error message\n * @returns Parsed integer\n * @throws Error if value is not a valid positive integer\n */\nexport function parseLimit(value: string, name: string): number {\n const parsed = parseInt(value, 10);\n if (Number.isNaN(parsed) || parsed <= 0) {\n throw new Error(`Invalid ${name}: must be a positive integer`);\n }\n return parsed;\n}\n\n/**\n * Get repository root from environment variable or current directory.\n *\n * @returns Repository root path for lesson storage\n */\nexport function getRepoRoot(): string {\n return process.env['COMPOUND_AGENT_ROOT'] ?? process.cwd();\n}\n","/**\n * Embedding model resolution using node-llama-cpp's built-in resolver.\n *\n * Uses resolveModelFile for automatic download and caching.\n * Model is stored in ~/.node-llama-cpp/models/ by default.\n */\n\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { getLlama, resolveModelFile } from 'node-llama-cpp';\n\n/**\n * HuggingFace URI for EmbeddingGemma-300M (Q4_0 quantization).\n *\n * - Size: ~278MB\n * - Dimensions: 768 (default), supports MRL truncation to 512/256/128\n * - Context: 2048 tokens\n */\nexport const MODEL_URI = 'hf:ggml-org/embeddinggemma-300M-qat-q4_0-GGUF/embeddinggemma-300M-qat-Q4_0.gguf';\n\n/**\n * Expected model filename after download.\n * node-llama-cpp uses format: hf_{org}_{filename}\n */\nexport const MODEL_FILENAME = 'hf_ggml-org_embeddinggemma-300M-qat-Q4_0.gguf';\n\n/** Default model directory used by node-llama-cpp */\nconst DEFAULT_MODEL_DIR = join(homedir(), '.node-llama-cpp', 'models');\n\n/** Cached usability result (per-process) */\nlet cachedUsability: UsabilityResult | null = null;\n\n/**\n * Check if the embedding model is available locally.\n *\n * @returns true if model file exists\n */\nexport function isModelAvailable(): boolean {\n return existsSync(join(DEFAULT_MODEL_DIR, MODEL_FILENAME));\n}\n\n/**\n * Result of checking if the model is usable at runtime.\n *\n * A discriminated union where `usable` determines which fields are present:\n * - usable=true: Model can initialize and create embedding context\n * - usable=false: Model cannot be used, with reason and actionable fix\n */\nexport type UsabilityResult =\n | { usable: true; reason?: undefined; action?: undefined }\n | { usable: false; reason: string; action: string };\n\n/**\n * Check if the embedding model is usable at runtime.\n *\n * Goes beyond file existence to verify the model can actually initialize:\n * 1. Checks if model file exists (fast fail)\n * 2. Attempts to load llama runtime\n * 3. Attempts to load model\n * 4. Attempts to create embedding context\n * 5. Cleans up all resources after check\n *\n * @returns UsabilityResult with usable status and actionable error if failed\n */\nexport async function isModelUsable(): Promise<UsabilityResult> {\n // Return cached result if available (avoids double initialization)\n if (cachedUsability !== null) {\n return cachedUsability;\n }\n\n // Fast fail if model file doesn't exist\n if (!isModelAvailable()) {\n cachedUsability = {\n usable: false,\n reason: 'Embedding model file not found',\n action: 'Run: npx ca download-model',\n };\n return cachedUsability;\n }\n\n // Attempt runtime initialization\n let llama = null;\n let model = null;\n let context = null;\n\n try {\n const modelPath = join(DEFAULT_MODEL_DIR, MODEL_FILENAME);\n\n // Step 1: Get llama runtime\n llama = await getLlama();\n\n // Step 2: Load model\n model = await llama.loadModel({ modelPath });\n\n // Step 3: Create embedding context\n context = await model.createEmbeddingContext();\n\n // Success - cache and return\n cachedUsability = { usable: true };\n return cachedUsability;\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Unknown error';\n cachedUsability = {\n usable: false,\n reason: `Embedding model runtime initialization failed: ${message}`,\n action: 'Check system compatibility or reinstall: npx ca download-model',\n };\n return cachedUsability;\n } finally {\n // Clean up resources in reverse order\n if (context) {\n try {\n context.dispose();\n } catch {\n // Ignore cleanup errors\n }\n }\n // Note: model and llama don't have explicit dispose methods in node-llama-cpp\n // The GC will handle them when references are released\n }\n}\n\n/**\n * Clear the cached usability result.\n *\n * Primarily for testing purposes. Clears the cached result so the next\n * call to isModelUsable() will perform a fresh check.\n */\nexport function clearUsabilityCache(): void {\n cachedUsability = null;\n}\n\n/**\n * Resolve the embedding model path, downloading if necessary.\n *\n * Uses node-llama-cpp's resolveModelFile for automatic download with progress.\n *\n * @param options - Optional configuration\n * @param options.cli - Show download progress in console (default: true)\n * @returns Path to the resolved model file\n *\n * @example\n * ```typescript\n * const modelPath = await resolveModel();\n * const llama = await getLlama();\n * const model = await llama.loadModel({ modelPath });\n * ```\n */\nexport async function resolveModel(options: { cli?: boolean } = {}): Promise<string> {\n const { cli = true } = options;\n return resolveModelFile(MODEL_URI, { cli });\n}\n","/**\n * Text embedding via node-llama-cpp with EmbeddingGemma model\n *\n * **Resource lifecycle:**\n * - Model is loaded lazily on first embedding call (~150MB in memory)\n * - Once loaded, the model remains in memory until `unloadEmbedding()` is called\n * - Loading is slow (~1-3s); keeping loaded improves subsequent call performance\n *\n * **Memory usage:**\n * - Embedding model: ~150MB RAM when loaded\n * - Embeddings themselves: ~3KB per embedding (768 dimensions x 4 bytes)\n *\n * @see {@link unloadEmbedding} for releasing memory\n * @see {@link getEmbedding} for the lazy-loading mechanism\n */\n\nimport type { Llama, LlamaModel } from 'node-llama-cpp';\nimport { getLlama, LlamaEmbeddingContext } from 'node-llama-cpp';\n\nimport { isModelAvailable, resolveModel } from './model.js';\n\n/** Singleton embedding context */\nlet embeddingContext: LlamaEmbeddingContext | null = null;\n/** Pending initialization promise (prevents concurrent duplicate loads) */\nlet pendingInit: Promise<LlamaEmbeddingContext> | null = null;\n/** Native resource refs for proper cleanup */\nlet llamaInstance: Llama | null = null;\nlet modelInstance: LlamaModel | null = null;\n\n/**\n * Get the LlamaEmbeddingContext instance for generating embeddings.\n *\n * **Lazy loading behavior:**\n * - First call loads the embedding model (~150MB) into memory\n * - Loading takes ~1-3 seconds depending on hardware\n * - Subsequent calls return the cached instance immediately\n * - Downloads model automatically if not present\n *\n * **Resource lifecycle:**\n * - Once loaded, model stays in memory until `unloadEmbedding()` is called\n * - For CLI commands: typically load once, use, then unload on exit\n * - For long-running processes: keep loaded for performance\n *\n * @returns The singleton embedding context\n * @throws Error if model download fails\n *\n * @example\n * ```typescript\n * // Direct usage (prefer embedText for simple cases)\n * const ctx = await getEmbedding();\n * const result = await ctx.getEmbeddingFor('some text');\n *\n * // Ensure cleanup\n * process.on('exit', () => unloadEmbedding());\n * ```\n *\n * @see {@link embedText} for simpler text-to-vector conversion\n * @see {@link unloadEmbedding} for releasing memory\n */\nexport async function getEmbedding(): Promise<LlamaEmbeddingContext> {\n if (embeddingContext) return embeddingContext;\n if (pendingInit) return pendingInit;\n\n pendingInit = (async () => {\n try {\n const modelPath = await resolveModel({ cli: true });\n llamaInstance = await getLlama();\n modelInstance = await llamaInstance.loadModel({ modelPath });\n embeddingContext = await modelInstance.createEmbeddingContext();\n return embeddingContext;\n } catch (err) {\n pendingInit = null; // Allow retry on failure\n throw err;\n }\n })();\n\n return pendingInit;\n}\n\n/**\n * Unload the embedding context to free memory (~150MB).\n *\n * **Resource lifecycle:**\n * - Disposes the underlying LlamaEmbeddingContext\n * - Releases ~150MB of RAM used by the model\n * - After unloading, subsequent embedding calls will reload the model\n *\n * **When to call:**\n * - At the end of CLI commands to ensure clean process exit\n * - In memory-constrained environments after batch processing\n * - Before process exit in graceful shutdown handlers\n * - When switching to a different model (if supported in future)\n *\n * **Best practices:**\n * - For single-operation scripts: call before exit\n * - For daemon/server processes: call in shutdown handler\n * - Not needed between embedding calls in the same process\n *\n * @example\n * ```typescript\n * // CLI command pattern\n * try {\n * const embedding = await embedText('some text');\n * // ... use embedding\n * } finally {\n * unloadEmbedding();\n * closeDb();\n * }\n *\n * // Graceful shutdown pattern\n * process.on('SIGTERM', () => {\n * unloadEmbedding();\n * closeDb();\n * process.exit(0);\n * });\n * ```\n *\n * @see {@link getEmbedding} for loading the model\n * @see {@link closeDb} for database cleanup (often used together)\n */\nexport function unloadEmbedding(): void {\n if (embeddingContext) {\n embeddingContext.dispose();\n embeddingContext = null;\n }\n if (modelInstance) {\n modelInstance.dispose().catch(() => {});\n modelInstance = null;\n }\n if (llamaInstance) {\n llamaInstance.dispose().catch(() => {});\n llamaInstance = null;\n }\n pendingInit = null;\n}\n\n/**\n * Embed a single text string into a vector.\n *\n * **Lazy loading:** First call loads the embedding model (~150MB, ~1-3s).\n * Subsequent calls use the cached model and complete in milliseconds.\n *\n * @param text - The text to embed\n * @returns A 768-dimensional vector (number[])\n * @throws Error if model download fails\n *\n * @example\n * ```typescript\n * const vector = await embedText('TypeScript error handling');\n * console.log(vector.length); // 768\n *\n * // Remember to clean up when done\n * unloadEmbedding();\n * ```\n *\n * @see {@link embedTexts} for batch embedding\n * @see {@link unloadEmbedding} for releasing memory\n */\nexport async function embedText(text: string): Promise<number[]> {\n const ctx = await getEmbedding();\n const result = await ctx.getEmbeddingFor(text);\n return Array.from(result.vector);\n}\n\n/**\n * Embed multiple texts into vectors.\n *\n * **Lazy loading:** First call loads the embedding model (~150MB, ~1-3s).\n * Subsequent calls use the cached model.\n *\n * **Performance:** More efficient than calling `embedText` in a loop\n * when processing multiple texts, as model loading happens only once.\n *\n * @param texts - Array of texts to embed\n * @returns Array of 768-dimensional vectors, same order as input\n * @throws Error if model download fails\n *\n * @example\n * ```typescript\n * const texts = ['first text', 'second text'];\n * const vectors = await embedTexts(texts);\n * console.log(vectors.length); // 2\n * console.log(vectors[0].length); // 768\n *\n * // Remember to clean up when done\n * unloadEmbedding();\n * ```\n *\n * @see {@link embedText} for single text embedding\n * @see {@link unloadEmbedding} for releasing memory\n */\nexport async function embedTexts(texts: string[]): Promise<number[][]> {\n if (texts.length === 0) return [];\n\n const ctx = await getEmbedding();\n const results: number[][] = [];\n\n for (const text of texts) {\n const result = await ctx.getEmbeddingFor(text);\n results.push(Array.from(result.vector));\n }\n\n return results;\n}\n\n// Re-export isModelAvailable for test utilities\nexport { isModelAvailable };\n","/**\n * Memory item type definitions using Zod schemas.\n *\n * Supports 4 memory item types via discriminated union:\n * - lesson: Knowledge learned from mistakes\n * - solution: Problem-resolution pairs\n * - pattern: Code pattern transformations (bad -> good)\n * - preference: User workflow preferences\n *\n * Deletion model:\n * - Set `deleted: true` and `deletedAt` on an item to mark it deleted\n * - LegacyTombstoneSchema handles backward-compat reads of old\n * minimal tombstone records { id, deleted: true, deletedAt }\n * - LegacyLessonSchema handles old quick/full type records\n */\n\nimport { createHash } from 'node:crypto';\nimport { z } from 'zod';\n\n// Source of lesson capture\nexport const SourceSchema = z.enum([\n 'user_correction',\n 'self_correction',\n 'test_failure',\n 'manual',\n]);\n\n// Context about when lesson was learned\nexport const ContextSchema = z.object({\n tool: z.string(),\n intent: z.string(),\n});\n\n// Code pattern (bad -> good)\nexport const PatternSchema = z.object({\n bad: z.string(),\n good: z.string(),\n});\n\n// Citation for lesson provenance tracking\nexport const CitationSchema = z.object({\n file: z.string().min(1), // Source file path (required, non-empty)\n line: z.number().int().positive().optional(), // Line number (optional, must be positive)\n commit: z.string().optional(), // Git commit hash (optional)\n});\n\n// Severity levels for lessons\nexport const SeveritySchema = z.enum(['high', 'medium', 'low']);\n\n// Compaction levels for age-based validity\nexport const CompactionLevelSchema = z.union([\n z.literal(0), // Active\n z.literal(1), // Flagged (>90 days)\n z.literal(2), // Archived\n]);\n\n/** @deprecated Use MemoryItemTypeSchema instead. Kept for parsing old JSONL records. */\nexport const LessonTypeSchema = z.enum(['quick', 'full']);\n\n/** Memory item type enum: lesson, solution, pattern, preference. */\nexport const MemoryItemTypeSchema = z.enum(['lesson', 'solution', 'pattern', 'preference']);\n\n// ---------------------------------------------------------------------------\n// Base fields shared by all memory item types\n// ---------------------------------------------------------------------------\n\nconst baseFields = {\n // Core identity (required)\n id: z.string(),\n trigger: z.string(),\n insight: z.string(),\n\n // Metadata (required)\n tags: z.array(z.string()),\n source: SourceSchema,\n context: ContextSchema,\n created: z.string(), // ISO8601\n confirmed: z.boolean(),\n\n // Relationships (required, can be empty arrays)\n supersedes: z.array(z.string()),\n related: z.array(z.string()),\n\n // Extended fields (optional)\n evidence: z.string().optional(),\n severity: SeveritySchema.optional(),\n\n // Lifecycle fields (optional)\n deleted: z.boolean().optional(),\n deletedAt: z.string().optional(),\n retrievalCount: z.number().optional(),\n\n // Provenance tracking (optional)\n citation: CitationSchema.optional(),\n\n // Age-based validity fields (optional)\n compactionLevel: CompactionLevelSchema.optional(),\n compactedAt: z.string().optional(),\n lastRetrieved: z.string().optional(),\n\n // Invalidation fields (optional)\n invalidatedAt: z.string().optional(),\n invalidationReason: z.string().optional(),\n} as const;\n\n// ---------------------------------------------------------------------------\n// Type-specific schemas\n// ---------------------------------------------------------------------------\n\n/**\n * Lesson memory item schema.\n * Replaces the old quick/full distinction with a single 'lesson' type.\n * Pattern field is optional for lessons.\n */\nexport const LessonItemSchema = z.object({\n ...baseFields,\n type: z.literal('lesson'),\n pattern: PatternSchema.optional(),\n});\n\n/**\n * Solution memory item schema.\n * Uses trigger as \"problem\" and insight as \"resolution\".\n * Pattern field is optional.\n */\nexport const SolutionItemSchema = z.object({\n ...baseFields,\n type: z.literal('solution'),\n pattern: PatternSchema.optional(),\n});\n\n/**\n * Pattern memory item schema.\n * Pattern field is REQUIRED (bad -> good code transformation).\n */\nexport const PatternItemSchema = z.object({\n ...baseFields,\n type: z.literal('pattern'),\n pattern: PatternSchema,\n});\n\n/**\n * Preference memory item schema.\n * Captures user workflow preferences.\n * Pattern field is optional.\n */\nexport const PreferenceItemSchema = z.object({\n ...baseFields,\n type: z.literal('preference'),\n pattern: PatternSchema.optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Discriminated union of all memory item types\n// ---------------------------------------------------------------------------\n\n/**\n * Unified memory item schema (discriminated union on 'type' field).\n * Accepts: lesson, solution, pattern, preference.\n */\nexport const MemoryItemSchema = z.discriminatedUnion('type', [\n LessonItemSchema,\n SolutionItemSchema,\n PatternItemSchema,\n PreferenceItemSchema,\n]);\n\n// ---------------------------------------------------------------------------\n// Backward compatibility\n// ---------------------------------------------------------------------------\n\n/**\n * Legacy lesson schema for reading old JSONL records with type: 'quick' | 'full'.\n * Use this only for parsing existing data files; new records use MemoryItemSchema.\n */\nexport const LegacyLessonSchema = z.object({\n ...baseFields,\n type: LessonTypeSchema,\n pattern: PatternSchema.optional(),\n});\n\n/**\n * LessonSchema - now equivalent to LessonItemSchema.\n *\n * For backward compatibility, existing code that imports LessonSchema\n * continues to work. The type field is now z.literal('lesson').\n *\n * To parse old quick/full records, use LegacyLessonSchema.\n */\nexport const LessonSchema = LessonItemSchema;\n\n/**\n * Legacy tombstone format for backward-compatible reads.\n * Old JSONL files may contain minimal { id, deleted, deletedAt } records.\n */\nexport const LegacyTombstoneSchema = z.object({\n id: z.string(),\n deleted: z.literal(true),\n deletedAt: z.string(), // ISO8601\n});\n\n/**\n * LessonRecord schema - union for reading JSONL files.\n *\n * Accepts:\n * 1. Any new memory item type (lesson, solution, pattern, preference)\n * 2. A legacy lesson (type: 'quick' | 'full')\n * 3. A legacy tombstone (minimal: { id, deleted: true, deletedAt })\n */\nexport const LessonRecordSchema = z.union([\n MemoryItemSchema,\n LegacyLessonSchema,\n LegacyTombstoneSchema,\n]);\n\n/**\n * MemoryItemRecord schema - alias for LessonRecordSchema.\n * Parses all memory item types plus legacy formats.\n */\nexport const MemoryItemRecordSchema = LessonRecordSchema;\n\n// ---------------------------------------------------------------------------\n// Type exports\n// ---------------------------------------------------------------------------\n\nexport type Lesson = z.infer<typeof LessonSchema>;\n/** @deprecated Use MemoryItemType instead. */\nexport type LessonType = z.infer<typeof LessonTypeSchema>;\nexport type LessonRecord = z.infer<typeof LessonRecordSchema>;\nexport type Source = z.infer<typeof SourceSchema>;\nexport type Severity = z.infer<typeof SeveritySchema>;\nexport type Context = z.infer<typeof ContextSchema>;\nexport type Pattern = z.infer<typeof PatternSchema>;\nexport type Citation = z.infer<typeof CitationSchema>;\nexport type CompactionLevel = z.infer<typeof CompactionLevelSchema>;\n\n/** Unified memory item type (discriminated union). */\nexport type MemoryItem = z.infer<typeof MemoryItemSchema>;\n/** Memory item type enum: 'lesson' | 'solution' | 'pattern' | 'preference'. */\nexport type MemoryItemType = z.infer<typeof MemoryItemTypeSchema>;\n/** Solution memory item. */\nexport type Solution = z.infer<typeof SolutionItemSchema>;\n/** Pattern memory item (not to be confused with Pattern = {bad, good}). */\nexport type PatternItem = z.infer<typeof PatternItemSchema>;\n/** Preference memory item. */\nexport type Preference = z.infer<typeof PreferenceItemSchema>;\n/** Record type for reading JSONL files (all types + legacy). */\nexport type MemoryItemRecord = z.infer<typeof MemoryItemRecordSchema>;\n\n// ---------------------------------------------------------------------------\n// ID generation\n// ---------------------------------------------------------------------------\n\n/** Prefix mapping for memory item types. */\nconst TYPE_PREFIXES: Record<MemoryItemType, string> = {\n lesson: 'L',\n solution: 'S',\n pattern: 'P',\n preference: 'R',\n};\n\n/**\n * Generate deterministic memory item ID from insight text.\n * Format: {prefix} + 8 hex characters from SHA-256 hash.\n *\n * @param insight - The insight text to hash\n * @param type - Memory item type (default: 'lesson' for backward compat)\n * @returns ID string like L1a2b3c4d, S1a2b3c4d, P1a2b3c4d, or R1a2b3c4d\n */\nexport function generateId(insight: string, type?: MemoryItemType): string {\n const prefix = TYPE_PREFIXES[type ?? 'lesson'];\n const hash = createHash('sha256').update(insight).digest('hex');\n return `${prefix}${hash.slice(0, 8)}`;\n}\n","/**\n * JSONL storage layer for memory items\n *\n * Append-only storage with last-write-wins deduplication.\n * Source of truth - git trackable.\n *\n * Primary API:\n * appendMemoryItem() - Append any memory item type\n * readMemoryItems() - Read all non-deleted memory items\n *\n * Backward-compatible API:\n * appendLesson() - Append a lesson (delegates to appendMemoryItem)\n * readLessons() - Read lesson-type items only\n *\n * Deletion: append the item with `deleted: true` and `deletedAt`.\n * Read path also accepts old minimal tombstone records for backward compat.\n * Legacy type:'quick'/'full' records are converted to type:'lesson' on read.\n */\n\nimport { appendFile, mkdir, readFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n MemoryItemRecordSchema,\n type Lesson,\n type LessonRecord,\n type MemoryItem,\n} from '../types.js';\n\n/** Relative path to lessons file from repo root */\nexport const LESSONS_PATH = '.claude/lessons/index.jsonl';\n\n/** Options for reading memory items */\nexport interface ReadLessonsOptions {\n /** If true, throw on first parse error. Default: false (skip errors) */\n strict?: boolean;\n /** Callback for each parse error in non-strict mode */\n onParseError?: (error: ParseError) => void;\n}\n\n/** Parse error details */\nexport interface ParseError {\n /** 1-based line number */\n line: number;\n /** Error message */\n message: string;\n /** Original error */\n cause: unknown;\n}\n\n/** Result of reading lessons (backward-compat) */\nexport interface ReadLessonsResult {\n /** Successfully parsed lessons */\n lessons: Lesson[];\n /** Number of lines skipped due to errors */\n skippedCount: number;\n}\n\n/** Result of reading memory items */\nexport interface ReadMemoryItemsResult {\n /** Successfully parsed memory items */\n items: MemoryItem[];\n /** Number of lines skipped due to errors */\n skippedCount: number;\n}\n\n\n/**\n * Append a memory item to the JSONL file.\n * Creates directory structure if missing.\n * Primary write function for all memory item types.\n *\n * @param repoRoot - Repository root directory\n * @param item - Memory item to append (any type: lesson, solution, pattern, preference)\n */\nexport async function appendMemoryItem(repoRoot: string, item: MemoryItem): Promise<void> {\n const filePath = join(repoRoot, LESSONS_PATH);\n await mkdir(dirname(filePath), { recursive: true });\n\n const line = JSON.stringify(item) + '\\n';\n await appendFile(filePath, line, 'utf-8');\n}\n\n/**\n * Append a lesson to the JSONL file.\n * Backward-compatible wrapper around appendMemoryItem.\n *\n * @param repoRoot - Repository root directory\n * @param lesson - Lesson to append\n */\nexport async function appendLesson(repoRoot: string, lesson: Lesson): Promise<void> {\n return appendMemoryItem(repoRoot, lesson);\n}\n\n/**\n * Parse and validate a single JSON line.\n *\n * Accepts:\n * - New memory item types (lesson, solution, pattern, preference)\n * - Legacy lessons (type: 'quick' | 'full')\n * - Canonical tombstones ({ id, deleted: true, deletedAt })\n * - Legacy tombstones (full record with deleted:true)\n *\n * @returns Parsed record or null if invalid\n */\nfunction parseJsonLine(\n line: string,\n lineNumber: number,\n strict: boolean,\n onParseError?: (error: ParseError) => void\n): LessonRecord | null {\n // Try to parse JSON\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (err) {\n const parseError: ParseError = {\n line: lineNumber,\n message: `Invalid JSON: ${(err as Error).message}`,\n cause: err,\n };\n if (strict) {\n throw new Error(`Parse error on line ${lineNumber}: ${parseError.message}`);\n }\n onParseError?.(parseError);\n return null;\n }\n\n // Validate against MemoryItemRecordSchema (accepts all types + legacy)\n const result = MemoryItemRecordSchema.safeParse(parsed);\n if (!result.success) {\n const parseError: ParseError = {\n line: lineNumber,\n message: `Schema validation failed: ${result.error.message}`,\n cause: result.error,\n };\n if (strict) {\n throw new Error(`Parse error on line ${lineNumber}: ${parseError.message}`);\n }\n onParseError?.(parseError);\n return null;\n }\n\n return result.data;\n}\n\n/**\n * Convert a parsed record to a MemoryItem.\n * Legacy type:'quick'/'full' records are converted to type:'lesson'.\n * Returns null for tombstone-only records (no MemoryItem data).\n */\nfunction toMemoryItem(record: LessonRecord): MemoryItem | null {\n // Tombstone records that are minimal (no type field) cannot be converted\n if (record.deleted === true) {\n return null;\n }\n\n // Legacy type conversion: quick/full -> lesson\n if (record.type === 'quick' || record.type === 'full') {\n return { ...record, type: 'lesson' } as MemoryItem;\n }\n\n // Already a valid MemoryItem type\n return record as MemoryItem;\n}\n\n/**\n * Read all non-deleted memory items from the JSONL file.\n * Primary read function for the unified memory API.\n *\n * Applies last-write-wins deduplication by ID.\n * Converts legacy type:'quick'/'full' to type:'lesson'.\n *\n * Handles tombstone formats:\n * - Canonical: { id, deleted: true, deletedAt }\n * - Legacy: Full record with deleted:true field\n *\n * @param repoRoot - Repository root directory\n * @param options - Optional settings for error handling\n * @returns Result with items array and count of skipped lines\n */\nexport async function readMemoryItems(\n repoRoot: string,\n options: ReadLessonsOptions = {}\n): Promise<ReadMemoryItemsResult> {\n const { strict = false, onParseError } = options;\n const filePath = join(repoRoot, LESSONS_PATH);\n\n let content: string;\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { items: [], skippedCount: 0 };\n }\n throw err;\n }\n\n const items = new Map<string, MemoryItem>();\n let skippedCount = 0;\n\n const lines = content.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i]!.trim();\n if (!trimmed) continue;\n\n const record = parseJsonLine(trimmed, i + 1, strict, onParseError);\n if (!record) {\n skippedCount++;\n continue;\n }\n\n // Check if record is a tombstone (canonical or legacy)\n if (record.deleted === true) {\n items.delete(record.id);\n } else {\n const item = toMemoryItem(record);\n if (item) {\n items.set(record.id, item);\n }\n }\n }\n\n return { items: Array.from(items.values()), skippedCount };\n}\n\n/**\n * Read all non-deleted lessons from the JSONL file.\n * Backward-compatible wrapper that filters to lesson-type items only.\n *\n * @param repoRoot - Repository root directory\n * @param options - Optional settings for error handling\n * @returns Result with lessons array and count of skipped lines\n */\nexport async function readLessons(\n repoRoot: string,\n options: ReadLessonsOptions = {}\n): Promise<ReadLessonsResult> {\n const result = await readMemoryItems(repoRoot, options);\n\n // Filter to lesson-type items only\n const lessons = result.items.filter((item): item is Lesson => item.type === 'lesson');\n\n return { lessons, skippedCount: result.skippedCount };\n}\n","/**\n * SQLite availability check.\n *\n * Verifies that better-sqlite3 can be loaded. If it cannot, an error\n * is thrown -- there is no silent fallback to JSONL-only mode.\n */\n\nimport { createRequire } from 'node:module';\nimport type { Database as DatabaseType } from 'better-sqlite3';\n\n// Create require function for ESM compatibility\nconst require = createRequire(import.meta.url);\n\n/** Cached availability state */\nlet checked = false;\nlet DatabaseConstructor: (new (path: string) => DatabaseType) | null = null;\n\n/**\n * Ensure SQLite (better-sqlite3) is loadable.\n * Throws a clear error if the native module cannot be loaded.\n */\nexport function ensureSqliteAvailable(): void {\n if (checked) return;\n\n try {\n const module = require('better-sqlite3');\n const Constructor = module.default || module;\n const testDb = new Constructor(':memory:');\n testDb.close();\n DatabaseConstructor = Constructor;\n checked = true;\n } catch (cause) {\n throw new Error(\n 'better-sqlite3 failed to load.\\n' +\n 'If using pnpm, add to your project\\'s package.json:\\n' +\n ' \"pnpm\": { \"onlyBuiltDependencies\": [\"better-sqlite3\"] }\\n' +\n 'Then run: pnpm install && pnpm rebuild better-sqlite3\\n' +\n 'For npm/yarn, run: npm rebuild better-sqlite3',\n { cause }\n );\n }\n}\n\n/**\n * Get the SQLite Database constructor.\n * @returns Database constructor (never null -- throws if unavailable)\n */\nexport function getDatabaseConstructor(): new (path: string) => DatabaseType {\n ensureSqliteAvailable();\n return DatabaseConstructor!;\n}\n","/**\n * SQLite schema definition for lessons database.\n *\n * The SQLite database is a rebuildable cache (JSONL is source of truth).\n * When SCHEMA_VERSION changes, the DB file is deleted and recreated.\n */\n\nimport type { Database as DatabaseType } from 'better-sqlite3';\n\n/**\n * Schema version for the SQLite cache.\n * Bump this when making incompatible schema changes.\n * The connection module auto-rebuilds when the DB version is older.\n */\nexport const SCHEMA_VERSION = 3;\n\n/** SQL schema for lessons database with FTS5 full-text search */\nconst SCHEMA_SQL = `\n CREATE TABLE IF NOT EXISTS lessons (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL,\n trigger TEXT NOT NULL,\n insight TEXT NOT NULL,\n evidence TEXT,\n severity TEXT,\n tags TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n context TEXT NOT NULL DEFAULT '{}',\n supersedes TEXT NOT NULL DEFAULT '[]',\n related TEXT NOT NULL DEFAULT '[]',\n created TEXT NOT NULL,\n confirmed INTEGER NOT NULL DEFAULT 0,\n deleted INTEGER NOT NULL DEFAULT 0,\n retrieval_count INTEGER NOT NULL DEFAULT 0,\n last_retrieved TEXT,\n embedding BLOB,\n content_hash TEXT,\n invalidated_at TEXT,\n invalidation_reason TEXT,\n citation_file TEXT,\n citation_line INTEGER,\n citation_commit TEXT,\n compaction_level INTEGER DEFAULT 0,\n compacted_at TEXT,\n pattern_bad TEXT,\n pattern_good TEXT\n );\n\n CREATE VIRTUAL TABLE IF NOT EXISTS lessons_fts USING fts5(\n id, trigger, insight, tags, pattern_bad, pattern_good,\n content='lessons', content_rowid='rowid'\n );\n\n CREATE TRIGGER IF NOT EXISTS lessons_ai AFTER INSERT ON lessons BEGIN\n INSERT INTO lessons_fts(rowid, id, trigger, insight, tags, pattern_bad, pattern_good)\n VALUES (new.rowid, new.id, new.trigger, new.insight, new.tags, new.pattern_bad, new.pattern_good);\n END;\n\n CREATE TRIGGER IF NOT EXISTS lessons_ad AFTER DELETE ON lessons BEGIN\n INSERT INTO lessons_fts(lessons_fts, rowid, id, trigger, insight, tags, pattern_bad, pattern_good)\n VALUES ('delete', old.rowid, old.id, old.trigger, old.insight, old.tags, old.pattern_bad, old.pattern_good);\n END;\n\n CREATE TRIGGER IF NOT EXISTS lessons_au AFTER UPDATE ON lessons BEGIN\n INSERT INTO lessons_fts(lessons_fts, rowid, id, trigger, insight, tags, pattern_bad, pattern_good)\n VALUES ('delete', old.rowid, old.id, old.trigger, old.insight, old.tags, old.pattern_bad, old.pattern_good);\n INSERT INTO lessons_fts(rowid, id, trigger, insight, tags, pattern_bad, pattern_good)\n VALUES (new.rowid, new.id, new.trigger, new.insight, new.tags, new.pattern_bad, new.pattern_good);\n END;\n\n CREATE INDEX IF NOT EXISTS idx_lessons_created ON lessons(created);\n CREATE INDEX IF NOT EXISTS idx_lessons_confirmed ON lessons(confirmed);\n CREATE INDEX IF NOT EXISTS idx_lessons_severity ON lessons(severity);\n CREATE INDEX IF NOT EXISTS idx_lessons_type ON lessons(type);\n\n CREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n`;\n\n/**\n * Create the database schema and set the version pragma.\n * @param database - SQLite database instance\n */\nexport function createSchema(database: DatabaseType): void {\n database.exec(SCHEMA_SQL);\n database.pragma(`user_version = ${SCHEMA_VERSION}`);\n}\n","/**\n * SQLite database connection management.\n */\n\nimport { mkdirSync, unlinkSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { Database as DatabaseType } from 'better-sqlite3';\n\nimport type { DbOptions } from './types.js';\nimport { getDatabaseConstructor } from './availability.js';\nimport { createSchema, SCHEMA_VERSION } from './schema.js';\n\n/** Relative path to database file from repo root */\nexport const DB_PATH = '.claude/.cache/lessons.sqlite';\n\n/** Database connections keyed by resolved DB path */\nconst dbMap = new Map<string, DatabaseType>();\n/** Last opened DB path for backward-compat getDb() */\nlet lastDbPath: string | null = null;\n\n/**\n * Check if the database has the expected schema version.\n * @param database - SQLite database instance\n * @returns true if the version matches SCHEMA_VERSION\n */\nfunction hasExpectedVersion(database: DatabaseType): boolean {\n const row = database.pragma('user_version', { simple: true }) as number;\n return row === SCHEMA_VERSION;\n}\n\n/**\n * Open the SQLite database connection.\n * If the database has an older schema version, it is deleted and recreated.\n * Throws if better-sqlite3 cannot be loaded.\n * @param repoRoot - Absolute path to repository root\n * @param options - Database options (e.g., inMemory for testing)\n * @returns Database instance\n */\nexport function openDb(repoRoot: string, options: DbOptions = {}): DatabaseType {\n const { inMemory = false } = options;\n\n // In-memory DBs are keyed by repoRoot so different repos stay isolated\n const key = inMemory ? `:memory:${repoRoot}` : join(repoRoot, DB_PATH);\n\n const cached = dbMap.get(key);\n if (cached) {\n lastDbPath = key;\n return cached;\n }\n\n const Database = getDatabaseConstructor();\n let database: DatabaseType;\n\n if (inMemory) {\n database = new Database(':memory:');\n } else {\n const dir = dirname(key);\n mkdirSync(dir, { recursive: true });\n database = new Database(key);\n\n if (!hasExpectedVersion(database)) {\n database.close();\n unlinkSync(key);\n database = new Database(key);\n }\n\n database.pragma('journal_mode = WAL');\n }\n\n createSchema(database);\n dbMap.set(key, database);\n lastDbPath = key;\n return database;\n}\n\n/**\n * Close the SQLite database connection.\n */\nexport function closeDb(): void {\n for (const database of dbMap.values()) {\n database.close();\n }\n dbMap.clear();\n lastDbPath = null;\n}\n\n/**\n * Get the current database instance (for internal use).\n * @deprecated Prefer openDb(repoRoot) for explicit repo-scoped access.\n * @returns Current database instance or null\n */\nexport function getDb(): DatabaseType | null {\n if (!lastDbPath) return null;\n return dbMap.get(lastDbPath) ?? null;\n}\n","/**\n * Embedding cache operations for SQLite storage.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Database as DatabaseType } from 'better-sqlite3';\n\nimport type { CachedEmbeddingData } from './types.js';\nimport { openDb } from './connection.js';\n\n/**\n * Compute content hash for a lesson's trigger and insight.\n * Used to detect content changes for embedding cache invalidation.\n * @param trigger - The lesson trigger text\n * @param insight - The lesson insight text\n * @returns SHA-256 hash of the combined content\n */\nexport function contentHash(trigger: string, insight: string): string {\n return createHash('sha256').update(`${trigger} ${insight}`).digest('hex');\n}\n\n/**\n * Get cached embedding for a lesson.\n * @param repoRoot - Absolute path to repository root\n * @param lessonId - ID of the lesson\n * @param expectedHash - Optional content hash to validate cache freshness\n * @returns Embedding array or null if not cached\n */\nexport function getCachedEmbedding(\n repoRoot: string,\n lessonId: string,\n expectedHash?: string\n): number[] | null {\n const database = openDb(repoRoot);\n\n const row = database\n .prepare('SELECT embedding, content_hash FROM lessons WHERE id = ?')\n .get(lessonId) as { embedding: Buffer | null; content_hash: string | null } | undefined;\n\n if (!row || !row.embedding || !row.content_hash) {\n return null;\n }\n\n if (expectedHash && row.content_hash !== expectedHash) {\n return null;\n }\n\n const float32 = new Float32Array(\n row.embedding.buffer,\n row.embedding.byteOffset,\n row.embedding.byteLength / 4\n );\n return Array.from(float32);\n}\n\n/**\n * Cache embedding for a lesson in SQLite.\n *\n * Uses UPDATE-only (not INSERT) — the row must already exist in the\n * lessons table. If the row hasn't been synced from JSONL yet, the\n * write is a silent no-op and the embedding will be recomputed on\n * next access. This is by-design: the cache is an optional\n * optimization, not the source of truth.\n *\n * @param repoRoot - Absolute path to repository root\n * @param lessonId - ID of the lesson\n * @param embedding - Embedding vector (Float32Array or number array)\n * @param hash - Content hash for cache validation\n */\nexport function setCachedEmbedding(\n repoRoot: string,\n lessonId: string,\n embedding: Float32Array | number[],\n hash: string\n): void {\n const database = openDb(repoRoot);\n\n const float32 = embedding instanceof Float32Array ? embedding : new Float32Array(embedding);\n const buffer = Buffer.from(float32.buffer, float32.byteOffset, float32.byteLength);\n\n database\n .prepare('UPDATE lessons SET embedding = ?, content_hash = ? WHERE id = ?')\n .run(buffer, hash, lessonId);\n}\n\n/**\n * Collect all cached embeddings from the database.\n * Used during index rebuild to preserve valid caches.\n * @param database - SQLite database instance\n * @returns Map of lesson ID to cached embedding data\n */\nexport function collectCachedEmbeddings(database: DatabaseType): Map<string, CachedEmbeddingData> {\n const cache = new Map<string, CachedEmbeddingData>();\n const rows = database\n .prepare('SELECT id, embedding, content_hash FROM lessons WHERE embedding IS NOT NULL')\n .all() as Array<{ id: string; embedding: Buffer; content_hash: string | null }>;\n\n for (const row of rows) {\n if (row.embedding && row.content_hash) {\n cache.set(row.id, { embedding: row.embedding, contentHash: row.content_hash });\n }\n }\n return cache;\n}\n","/**\n * SQLite index synchronization with JSONL source of truth.\n */\n\nimport { statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Database as DatabaseType } from 'better-sqlite3';\n\nimport type { MemoryItem } from '../../types.js';\nimport { LESSONS_PATH, readMemoryItems } from '../jsonl.js';\n\nimport type { SyncOptions } from './types.js';\nimport { openDb } from './connection.js';\nimport { collectCachedEmbeddings, contentHash } from './cache.js';\n\n/** SQL for inserting a lesson record */\nconst INSERT_LESSON_SQL = `\n INSERT INTO lessons (id, type, trigger, insight, evidence, severity, tags, source, context, supersedes, related, created, confirmed, deleted, retrieval_count, last_retrieved, embedding, content_hash, invalidated_at, invalidation_reason, citation_file, citation_line, citation_commit, compaction_level, compacted_at, pattern_bad, pattern_good)\n VALUES (@id, @type, @trigger, @insight, @evidence, @severity, @tags, @source, @context, @supersedes, @related, @created, @confirmed, @deleted, @retrieval_count, @last_retrieved, @embedding, @content_hash, @invalidated_at, @invalidation_reason, @citation_file, @citation_line, @citation_commit, @compaction_level, @compacted_at, @pattern_bad, @pattern_good)\n`;\n\n/**\n * Get the modification time of the JSONL file.\n * @param repoRoot - Absolute path to repository root\n * @returns Modification time in milliseconds or null if file doesn't exist\n */\nfunction getJsonlMtime(repoRoot: string): number | null {\n const jsonlPath = join(repoRoot, LESSONS_PATH);\n try {\n const stat = statSync(jsonlPath);\n return stat.mtimeMs;\n } catch {\n return null;\n }\n}\n\n/**\n * Get the last sync modification time from metadata.\n * @param database - SQLite database instance\n * @returns Last sync mtime or null if not set\n */\nfunction getLastSyncMtime(database: DatabaseType): number | null {\n const row = database\n .prepare('SELECT value FROM metadata WHERE key = ?')\n .get('last_sync_mtime') as { value: string } | undefined;\n return row ? parseFloat(row.value) : null;\n}\n\n/**\n * Set the last sync modification time in metadata.\n * @param database - SQLite database instance\n * @param mtime - Modification time to store\n */\nfunction setLastSyncMtime(database: DatabaseType, mtime: number): void {\n database\n .prepare('INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)')\n .run('last_sync_mtime', mtime.toString());\n}\n\n/**\n * Rebuild the SQLite index from JSONL source of truth.\n * Preserves cached embeddings when item content hasn't changed.\n * @param repoRoot - Absolute path to repository root\n */\nexport async function rebuildIndex(repoRoot: string): Promise<void> {\n const database = openDb(repoRoot);\n\n const { items } = await readMemoryItems(repoRoot);\n const cachedEmbeddings = collectCachedEmbeddings(database);\n database.exec('DELETE FROM lessons');\n\n if (items.length === 0) {\n const mtime = getJsonlMtime(repoRoot);\n if (mtime !== null) {\n setLastSyncMtime(database, mtime);\n }\n return;\n }\n\n const insert = database.prepare(INSERT_LESSON_SQL);\n const insertMany = database.transaction((memoryItems: MemoryItem[]) => {\n for (const item of memoryItems) {\n const newHash = contentHash(item.trigger, item.insight);\n const cached = cachedEmbeddings.get(item.id);\n const hasValidCache = cached && cached.contentHash === newHash;\n\n insert.run({\n id: item.id,\n type: item.type,\n trigger: item.trigger,\n insight: item.insight,\n evidence: item.evidence ?? null,\n severity: item.severity ?? null,\n tags: item.tags.join(','),\n source: item.source,\n context: JSON.stringify(item.context),\n supersedes: JSON.stringify(item.supersedes),\n related: JSON.stringify(item.related),\n created: item.created,\n confirmed: item.confirmed ? 1 : 0,\n deleted: item.deleted ? 1 : 0,\n retrieval_count: item.retrievalCount ?? 0,\n last_retrieved: item.lastRetrieved ?? null,\n embedding: hasValidCache ? cached.embedding : null,\n content_hash: hasValidCache ? cached.contentHash : null,\n invalidated_at: item.invalidatedAt ?? null,\n invalidation_reason: item.invalidationReason ?? null,\n citation_file: item.citation?.file ?? null,\n citation_line: item.citation?.line ?? null,\n citation_commit: item.citation?.commit ?? null,\n compaction_level: item.compactionLevel ?? 0,\n compacted_at: item.compactedAt ?? null,\n pattern_bad: item.pattern?.bad ?? null,\n pattern_good: item.pattern?.good ?? null,\n });\n }\n });\n\n insertMany(items);\n\n const mtime = getJsonlMtime(repoRoot);\n if (mtime !== null) {\n setLastSyncMtime(database, mtime);\n }\n}\n\n/**\n * Sync SQLite index if JSONL has changed.\n * @param repoRoot - Absolute path to repository root\n * @param options - Sync options\n * @returns true if sync was performed, false otherwise\n */\nexport async function syncIfNeeded(\n repoRoot: string,\n options: SyncOptions = {}\n): Promise<boolean> {\n const { force = false } = options;\n const jsonlMtime = getJsonlMtime(repoRoot);\n if (jsonlMtime === null && !force) {\n return false;\n }\n\n const database = openDb(repoRoot);\n\n const lastSyncMtime = getLastSyncMtime(database);\n const needsRebuild = force || lastSyncMtime === null || (jsonlMtime !== null && jsonlMtime > lastSyncMtime);\n\n if (needsRebuild) {\n await rebuildIndex(repoRoot);\n return true;\n }\n\n return false;\n}\n","/**\n * SQLite search operations using FTS5 full-text search.\n */\n\nimport { MemoryItemSchema } from '../../types.js';\nimport type { MemoryItem, MemoryItemType } from '../../types.js';\n\nimport type { MemoryItemRow, RetrievalStat } from './types.js';\nimport { openDb } from './connection.js';\n\n/**\n * Convert a database row to a MemoryItem object.\n * @param row - Database row\n * @returns MemoryItem object\n */\nfunction rowToMemoryItem(row: MemoryItemRow): MemoryItem | null {\n const item = {\n id: row.id,\n type: row.type,\n trigger: row.trigger,\n insight: row.insight,\n tags: row.tags ? row.tags.split(',').filter(Boolean) : [],\n source: row.source,\n context: JSON.parse(row.context),\n supersedes: JSON.parse(row.supersedes),\n related: JSON.parse(row.related),\n created: row.created,\n confirmed: row.confirmed === 1,\n } as Record<string, unknown>;\n\n if (row.evidence !== null) item.evidence = row.evidence;\n if (row.severity !== null) item.severity = row.severity;\n if (row.deleted === 1) item.deleted = true;\n if (row.retrieval_count > 0) item.retrievalCount = row.retrieval_count;\n if (row.invalidated_at !== null) item.invalidatedAt = row.invalidated_at;\n if (row.invalidation_reason !== null) item.invalidationReason = row.invalidation_reason;\n if (row.citation_file !== null) {\n item.citation = {\n file: row.citation_file,\n ...(row.citation_line !== null && { line: row.citation_line }),\n ...(row.citation_commit !== null && { commit: row.citation_commit }),\n };\n }\n if (row.compaction_level !== null && row.compaction_level !== 0) {\n item.compactionLevel = row.compaction_level;\n }\n if (row.compacted_at !== null) item.compactedAt = row.compacted_at;\n if (row.last_retrieved !== null) item.lastRetrieved = row.last_retrieved;\n if (row.pattern_bad !== null && row.pattern_good !== null) {\n item.pattern = { bad: row.pattern_bad, good: row.pattern_good };\n }\n\n const result = MemoryItemSchema.safeParse(item);\n if (!result.success) return null;\n return result.data;\n}\n\n\n/** FTS5 operator tokens to remove */\nconst FTS_OPERATORS = new Set(['AND', 'OR', 'NOT', 'NEAR']);\n\n/**\n * Sanitize a query string for safe use with FTS5 MATCH.\n * Strips special FTS5 syntax characters and operators.\n * @param query - Raw user query\n * @returns Sanitized query safe for FTS5\n */\nexport function sanitizeFtsQuery(query: string): string {\n // Strip FTS5 special chars: \" * ^ - +\n const stripped = query.replace(/[\"*^+-]/g, '');\n // Tokenize by whitespace, remove FTS operators, filter empty\n const tokens = stripped\n .split(/\\s+/)\n .filter((t) => t.length > 0 && !FTS_OPERATORS.has(t));\n return tokens.join(' ');\n}\n\n/**\n * Increment retrieval count for lessons.\n * @param repoRoot - Absolute path to repository root\n * @param lessonIds - IDs of retrieved lessons\n */\nexport function incrementRetrievalCount(repoRoot: string, lessonIds: string[]): void {\n if (lessonIds.length === 0) return;\n\n const database = openDb(repoRoot);\n\n const now = new Date().toISOString();\n\n const update = database.prepare(`\n UPDATE lessons\n SET retrieval_count = retrieval_count + 1,\n last_retrieved = ?\n WHERE id = ?\n `);\n\n const updateMany = database.transaction((ids: string[]) => {\n for (const id of ids) {\n update.run(now, id);\n }\n });\n\n updateMany(lessonIds);\n}\n\n/**\n * Search lessons using FTS5 full-text search.\n * @param repoRoot - Absolute path to repository root\n * @param query - FTS5 query string\n * @param limit - Maximum number of results\n * @param typeFilter - Optional memory item type to filter by\n * @returns Matching lessons\n */\nexport async function searchKeyword(\n repoRoot: string,\n query: string,\n limit: number,\n typeFilter?: MemoryItemType\n): Promise<MemoryItem[]> {\n const database = openDb(repoRoot);\n\n const countResult = database.prepare('SELECT COUNT(*) as cnt FROM lessons').get() as {\n cnt: number;\n };\n if (countResult.cnt === 0) return [];\n\n const sanitized = sanitizeFtsQuery(query);\n if (sanitized === '') return [];\n\n try {\n if (typeFilter) {\n const rows = database\n .prepare(\n `\n SELECT l.*\n FROM lessons l\n JOIN lessons_fts fts ON l.rowid = fts.rowid\n WHERE lessons_fts MATCH ?\n AND l.invalidated_at IS NULL\n AND l.type = ?\n LIMIT ?\n `\n )\n .all(sanitized, typeFilter, limit) as MemoryItemRow[];\n return rows.map(rowToMemoryItem).filter((x): x is MemoryItem => x !== null);\n }\n\n const rows = database\n .prepare(\n `\n SELECT l.*\n FROM lessons l\n JOIN lessons_fts fts ON l.rowid = fts.rowid\n WHERE lessons_fts MATCH ?\n AND l.invalidated_at IS NULL\n LIMIT ?\n `\n )\n .all(sanitized, limit) as MemoryItemRow[];\n\n return rows.map(rowToMemoryItem).filter((x): x is MemoryItem => x !== null);\n } catch (err) {\n // Log for debugging — sanitization should prevent most FTS5 errors,\n // but real issues (e.g. DB corruption) should not be fully silent\n const message = err instanceof Error ? err.message : 'Unknown FTS5 error';\n console.error(`[compound-agent] search error: ${message}`);\n return [];\n }\n}\n\n/**\n * Get retrieval statistics for all lessons.\n * @param repoRoot - Absolute path to repository root\n * @returns Array of retrieval statistics\n */\nexport function getRetrievalStats(repoRoot: string): RetrievalStat[] {\n const database = openDb(repoRoot);\n\n const rows = database\n .prepare('SELECT id, retrieval_count, last_retrieved FROM lessons')\n .all() as Array<{ id: string; retrieval_count: number; last_retrieved: string | null }>;\n\n return rows.map((row) => ({\n id: row.id,\n count: row.retrieval_count,\n lastRetrieved: row.last_retrieved,\n }));\n}\n","/**\n * Shared utility functions for the Learning Agent.\n */\n\n/** Milliseconds per day for time calculations */\nexport const MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Calculate the age of a lesson in days from its created date.\n *\n * @param lesson - Object with a created field (ISO8601 string)\n * @returns Age in days (integer, rounded down)\n */\nexport function getLessonAgeDays(lesson: { created: string }): number {\n const created = new Date(lesson.created).getTime();\n const now = Date.now();\n return Math.floor((now - created) / MS_PER_DAY);\n}\n","/**\n * Compaction and auto-archive for lessons\n *\n * Handles:\n * - Archiving old lessons (>90 days with 0 retrievals)\n * - Removing tombstones through JSONL rewrite\n * - Tracking compaction thresholds\n */\n\nimport { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\nimport { MemoryItemSchema } from '../types.js';\nimport type { MemoryItem } from '../types.js';\nimport { getLessonAgeDays } from '../../utils.js';\n\nimport { LESSONS_PATH, readMemoryItems } from './jsonl.js';\n\n/** Relative path to archive directory from repo root */\nexport const ARCHIVE_DIR = '.claude/lessons/archive';\n\n/** Number of tombstones that triggers automatic compaction */\nexport const TOMBSTONE_THRESHOLD = 100;\n\n/** Age threshold for archiving (in days) */\nexport const ARCHIVE_AGE_DAYS = 90;\n\n/** Month offset for JavaScript's 0-indexed months */\nconst MONTH_INDEX_OFFSET = 1;\n\n/** Padding length for month in archive filename (e.g., \"01\" not \"1\") */\nconst MONTH_PAD_LENGTH = 2;\n\n/**\n * Result of a compaction operation\n */\nexport interface CompactResult {\n /** Number of lessons moved to archive */\n archived: number;\n /** Number of tombstones removed */\n tombstonesRemoved: number;\n /** Number of lessons remaining in index.jsonl */\n lessonsRemaining: number;\n /** Number of records dropped due to invalid schema */\n droppedInvalid: number;\n}\n\n/**\n * Generate archive file path for a given date.\n * Format: .claude/lessons/archive/YYYY-MM.jsonl\n */\nexport function getArchivePath(repoRoot: string, date: Date): string {\n const year = date.getFullYear();\n const month = String(date.getMonth() + MONTH_INDEX_OFFSET).padStart(MONTH_PAD_LENGTH, '0');\n return join(repoRoot, ARCHIVE_DIR, `${year}-${month}.jsonl`);\n}\n\n/**\n * Parse raw JSONL lines from the lessons file.\n * Returns all lines (including invalid ones) as parsed objects or null.\n */\nasync function parseRawJsonlLines(\n repoRoot: string\n): Promise<Array<{ line: string; parsed: Record<string, unknown> | null }>> {\n const filePath = join(repoRoot, LESSONS_PATH);\n let content: string;\n try {\n content = await readFile(filePath, 'utf-8');\n } catch {\n return [];\n }\n\n const results: Array<{ line: string; parsed: Record<string, unknown> | null }> = [];\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n results.push({ line: trimmed, parsed });\n } catch {\n results.push({ line: trimmed, parsed: null });\n }\n }\n return results;\n}\n\n/**\n * Count the number of tombstones (deleted: true records) in the JSONL file.\n */\nexport async function countTombstones(repoRoot: string): Promise<number> {\n const lines = await parseRawJsonlLines(repoRoot);\n let count = 0;\n for (const { parsed } of lines) {\n if (parsed && parsed['deleted'] === true) {\n count++;\n }\n }\n return count;\n}\n\n/**\n * Check if compaction is needed based on tombstone count.\n */\nexport async function needsCompaction(repoRoot: string): Promise<boolean> {\n const count = await countTombstones(repoRoot);\n return count >= TOMBSTONE_THRESHOLD;\n}\n\n/**\n * Rewrite the JSONL file without tombstones.\n * Applies last-write-wins deduplication.\n */\nexport async function rewriteWithoutTombstones(repoRoot: string): Promise<number> {\n const filePath = join(repoRoot, LESSONS_PATH);\n const tempPath = filePath + '.tmp';\n\n // Read deduplicated lessons (already handles last-write-wins)\n const { items } = await readMemoryItems(repoRoot);\n\n // Count tombstones before rewrite\n const tombstoneCount = await countTombstones(repoRoot);\n\n // Ensure directory exists\n await mkdir(dirname(filePath), { recursive: true });\n\n // Write clean lessons to temp file\n const lines = items.map((item) => JSON.stringify(item) + '\\n');\n await writeFile(tempPath, lines.join(''), 'utf-8');\n\n // Atomic rename\n await rename(tempPath, filePath);\n\n return tombstoneCount;\n}\n\n/**\n * Determine if a lesson should be archived based on age and retrieval count.\n * Lessons are archived if older than ARCHIVE_AGE_DAYS and never retrieved.\n *\n * @param lesson - The lesson to evaluate\n * @returns true if lesson should be archived\n */\nfunction shouldArchive(lesson: MemoryItem): boolean {\n const ageDays = getLessonAgeDays(lesson);\n\n // Archive if: older than threshold AND never retrieved\n return ageDays > ARCHIVE_AGE_DAYS && (lesson.retrievalCount === undefined || lesson.retrievalCount === 0);\n}\n\n/**\n * Archive old lessons that haven't been retrieved.\n * Moves lessons >90 days old with 0 retrievals to archive files.\n * Returns the number of lessons archived.\n */\nexport async function archiveOldLessons(repoRoot: string): Promise<number> {\n const { items } = await readMemoryItems(repoRoot);\n\n const toArchive: MemoryItem[] = [];\n const toKeep: MemoryItem[] = [];\n\n for (const item of items) {\n if (shouldArchive(item)) {\n toArchive.push(item);\n } else {\n toKeep.push(item);\n }\n }\n\n if (toArchive.length === 0) {\n return 0;\n }\n\n // Group lessons by archive file (YYYY-MM)\n const archiveGroups = new Map<string, MemoryItem[]>();\n for (const lesson of toArchive) {\n const created = new Date(lesson.created);\n const archivePath = getArchivePath(repoRoot, created);\n const group = archiveGroups.get(archivePath) ?? [];\n group.push(lesson);\n archiveGroups.set(archivePath, group);\n }\n\n // Create archive directory\n const archiveDir = join(repoRoot, ARCHIVE_DIR);\n await mkdir(archiveDir, { recursive: true });\n\n // Append to archive files\n for (const [archivePath, archiveLessons] of archiveGroups) {\n const lines = archiveLessons.map((l) => JSON.stringify(l) + '\\n').join('');\n await appendFile(archivePath, lines, 'utf-8');\n }\n\n // Rewrite main file without archived lessons\n const filePath = join(repoRoot, LESSONS_PATH);\n const tempPath = filePath + '.tmp';\n await mkdir(dirname(filePath), { recursive: true });\n\n const lines = toKeep.map((lesson) => JSON.stringify(lesson) + '\\n');\n await writeFile(tempPath, lines.join(''), 'utf-8');\n await rename(tempPath, filePath);\n\n return toArchive.length;\n}\n\n/**\n * Run full compaction: archive old lessons and remove tombstones.\n *\n * Reads the JSONL file exactly once, computes all operations in-memory,\n * then writes archive files and atomically replaces the main file.\n */\nexport async function compact(repoRoot: string): Promise<CompactResult> {\n const filePath = join(repoRoot, LESSONS_PATH);\n\n // 1. Read file ONCE\n let content: string;\n try {\n content = await readFile(filePath, 'utf-8');\n } catch {\n return { archived: 0, tombstonesRemoved: 0, lessonsRemaining: 0, droppedInvalid: 0 };\n }\n\n // 2. Parse all records in-memory with last-write-wins dedup\n const lessonMap = new Map<string, MemoryItem>();\n let tombstoneCount = 0;\n let droppedCount = 0;\n\n for (const rawLine of content.split('\\n')) {\n const trimmed = rawLine.trim();\n if (!trimmed) continue;\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n if (parsed['deleted'] === true) {\n lessonMap.delete(parsed['id'] as string);\n tombstoneCount++;\n } else {\n const result = MemoryItemSchema.safeParse(parsed);\n if (result.success) {\n lessonMap.set(result.data.id, result.data);\n } else {\n droppedCount++;\n }\n }\n }\n\n // 3. Split into archivable and kept\n const toArchive: MemoryItem[] = [];\n const toKeep: MemoryItem[] = [];\n\n for (const lesson of lessonMap.values()) {\n if (shouldArchive(lesson)) {\n toArchive.push(lesson);\n } else {\n toKeep.push(lesson);\n }\n }\n\n // 4. Write archive files\n if (toArchive.length > 0) {\n const archiveGroups = new Map<string, MemoryItem[]>();\n for (const lesson of toArchive) {\n const created = new Date(lesson.created);\n const archivePath = getArchivePath(repoRoot, created);\n const group = archiveGroups.get(archivePath) ?? [];\n group.push(lesson);\n archiveGroups.set(archivePath, group);\n }\n\n const archiveDir = join(repoRoot, ARCHIVE_DIR);\n await mkdir(archiveDir, { recursive: true });\n\n for (const [archivePath, archiveLessons] of archiveGroups) {\n const lines = archiveLessons.map((l) => JSON.stringify(l) + '\\n').join('');\n await appendFile(archivePath, lines, 'utf-8');\n }\n }\n\n // 5. Atomic write of main JSONL with only kept lessons\n await mkdir(dirname(filePath), { recursive: true });\n const tempPath = filePath + '.tmp';\n const lines = toKeep.map((lesson) => JSON.stringify(lesson) + '\\n');\n await writeFile(tempPath, lines.join(''), 'utf-8');\n await rename(tempPath, filePath);\n\n return {\n archived: toArchive.length,\n tombstonesRemoved: tombstoneCount,\n lessonsRemaining: toKeep.length,\n droppedInvalid: droppedCount,\n };\n}\n","/**\n * Vector search with cosine similarity\n *\n * Embeds query text and ranks lessons by semantic similarity.\n * Uses SQLite cache to avoid recomputing embeddings.\n */\n\nimport { readCctPatterns, type CctPattern } from '../../compound/index.js';\nimport { embedText } from '../embeddings/index.js';\nimport { contentHash, getCachedEmbedding, readMemoryItems, setCachedEmbedding } from '../storage/index.js';\nimport type { MemoryItem } from '../types.js';\n\n/**\n * Calculate cosine similarity between two vectors.\n * Returns value between -1 (opposite) and 1 (identical).\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n throw new Error('Vectors must have same length');\n }\n\n let dotProduct = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n dotProduct += a[i]! * b[i]!;\n normA += a[i]! * a[i]!;\n normB += b[i]! * b[i]!;\n }\n\n const magnitude = Math.sqrt(normA) * Math.sqrt(normB);\n if (magnitude === 0) return 0;\n\n return dotProduct / magnitude;\n}\n\n/**\n * Memory item with similarity score.\n * The `lesson` field holds any MemoryItem type (not just Lesson).\n * Field name kept for backward compatibility.\n */\nexport interface ScoredLesson {\n lesson: MemoryItem;\n score: number;\n}\n\n/** Alias for ScoredLesson for unified memory API consumers. */\nexport type ScoredMemoryItem = ScoredLesson;\n\n/** Options for vector search */\nexport interface SearchVectorOptions {\n /** Maximum number of results to return (default: 10) */\n limit?: number;\n}\n\n/** Default number of results to return */\nconst DEFAULT_LIMIT = 10;\n\n/**\n * Search lessons by vector similarity to query text.\n * Returns top N lessons sorted by similarity score (descending).\n * Uses embedding cache to avoid recomputing embeddings.\n */\n/**\n * Convert a CctPattern to a MemoryItem-like shape for search results.\n */\nfunction cctToMemoryItem(pattern: CctPattern): MemoryItem {\n return {\n id: pattern.id,\n type: 'lesson',\n trigger: pattern.name,\n insight: pattern.description,\n tags: [],\n source: 'manual',\n context: { tool: 'compound', intent: 'synthesis' },\n created: pattern.created,\n confirmed: true,\n supersedes: [],\n related: pattern.sourceIds,\n };\n}\n\nexport async function searchVector(\n repoRoot: string,\n query: string,\n options?: SearchVectorOptions\n): Promise<ScoredLesson[]> {\n const limit = options?.limit ?? DEFAULT_LIMIT;\n // Read all memory items (all types)\n const { items } = await readMemoryItems(repoRoot);\n\n // Read CCT patterns if available\n let cctPatterns: CctPattern[] = [];\n try {\n cctPatterns = await readCctPatterns(repoRoot);\n } catch {\n // File doesn't exist or is unreadable — proceed without CCT patterns\n }\n\n if (items.length === 0 && cctPatterns.length === 0) return [];\n\n // Embed the query\n const queryVector = await embedText(query);\n\n // Score each item, skipping invalidated ones\n const scored: ScoredLesson[] = [];\n for (const item of items) {\n // Skip invalidated items\n if (item.invalidatedAt) continue;\n\n try {\n const itemText = `${item.trigger} ${item.insight}`;\n const hash = contentHash(item.trigger, item.insight);\n\n // Try cache first\n let itemVector = getCachedEmbedding(repoRoot, item.id, hash);\n\n if (!itemVector) {\n // Cache miss - compute and store\n itemVector = await embedText(itemText);\n setCachedEmbedding(repoRoot, item.id, itemVector, hash);\n }\n\n const score = cosineSimilarity(queryVector, itemVector);\n scored.push({ lesson: item, score });\n } catch {\n // Skip items that fail embedding — return partial results\n continue;\n }\n }\n\n // Score CCT patterns\n for (const pattern of cctPatterns) {\n try {\n const text = `${pattern.name} ${pattern.description}`;\n const vec = await embedText(text);\n const score = cosineSimilarity(queryVector, vec);\n scored.push({ lesson: cctToMemoryItem(pattern), score });\n } catch {\n continue;\n }\n }\n\n // Sort by score descending and take top N\n scored.sort((a, b) => b.score - a.score);\n return scored.slice(0, limit);\n}\n","/**\n * Multi-factor memory item ranking system\n *\n * Combines vector similarity with semantic boosts:\n * - Severity: high=1.5, medium=1.0, low=0.8\n * - Recency: 1.2 for items ≤30 days old\n * - Confirmation: 1.3 for confirmed items\n */\n\nimport type { MemoryItem } from '../types.js';\nimport { getLessonAgeDays } from '../../utils.js';\n\nimport type { ScoredLesson } from './vector.js';\n\n/** Lesson/memory item with final ranked score */\nexport interface RankedLesson extends ScoredLesson {\n finalScore?: number;\n}\n\n/** Alias for RankedLesson for unified memory API consumers. */\nexport type RankedMemoryItem = RankedLesson;\n\nconst RECENCY_THRESHOLD_DAYS = 30;\nconst HIGH_SEVERITY_BOOST = 1.5;\nconst MEDIUM_SEVERITY_BOOST = 1.0;\nconst LOW_SEVERITY_BOOST = 0.8;\nconst RECENCY_BOOST = 1.2;\nconst CONFIRMATION_BOOST = 1.3;\n\n/**\n * Maximum combined boost multiplier.\n *\n * Without clamping, the max boost is 1.5 * 1.2 * 1.3 = 2.34x, which lets\n * a 0.4 similarity item outrank a 0.9 similarity item. With a 1.8 cap,\n * an item needs at least ~0.53 similarity with all boosts to beat a 0.95\n * unboosted match, keeping semantic relevance as the primary ranking signal.\n */\nconst MAX_COMBINED_BOOST = 1.8;\n\n/**\n * Calculate severity boost based on item severity.\n * Items without severity get 1.0 (medium boost).\n */\nexport function severityBoost(item: MemoryItem): number {\n switch (item.severity) {\n case 'high':\n return HIGH_SEVERITY_BOOST;\n case 'medium':\n return MEDIUM_SEVERITY_BOOST;\n case 'low':\n return LOW_SEVERITY_BOOST;\n default:\n return MEDIUM_SEVERITY_BOOST;\n }\n}\n\n/**\n * Calculate recency boost based on item age.\n * Items ≤30 days old get 1.2, older get 1.0.\n */\nexport function recencyBoost(item: MemoryItem): number {\n const ageDays = getLessonAgeDays(item);\n return ageDays <= RECENCY_THRESHOLD_DAYS ? RECENCY_BOOST : 1.0;\n}\n\n/**\n * Calculate confirmation boost.\n * Confirmed items get 1.3, unconfirmed get 1.0.\n */\nexport function confirmationBoost(item: MemoryItem): number {\n return item.confirmed ? CONFIRMATION_BOOST : 1.0;\n}\n\n/**\n * Calculate combined score for a memory item.\n * score = vectorSimilarity * min(severity * recency * confirmation, MAX_COMBINED_BOOST)\n */\nexport function calculateScore(item: MemoryItem, vectorSimilarity: number): number {\n const boost = Math.min(\n severityBoost(item) * recencyBoost(item) * confirmationBoost(item),\n MAX_COMBINED_BOOST,\n );\n return vectorSimilarity * boost;\n}\n\n/**\n * Rank lessons by combined score.\n * Returns new array sorted by finalScore descending.\n *\n * Works with ScoredLesson[] (backward compat, uses .lesson field).\n * For ScoredMemoryItem[], use the .item field — same underlying data.\n */\nexport function rankLessons(lessons: ScoredLesson[]): RankedLesson[] {\n return lessons\n .map((scored) => ({\n ...scored,\n finalScore: calculateScore(scored.lesson, scored.score),\n }))\n .sort((a, b) => (b.finalScore ?? 0) - (a.finalScore ?? 0));\n}\n\n/**\n * Rank memory items by combined score.\n * Primary API for unified memory types. Uses .item field.\n * Returns new array sorted by finalScore descending.\n */\nexport const rankMemoryItems = rankLessons;\n","/**\n * Clustering module for grouping similar memory items.\n *\n * Uses single-linkage agglomerative clustering with cosine similarity.\n */\n\nimport { cosineSimilarity } from '../memory/search/index.js';\nimport type { MemoryItem } from '../memory/index.js';\nimport type { ClusterResult } from './types.js';\n\n/** Default similarity threshold for clustering */\nconst DEFAULT_THRESHOLD = 0.75;\n\n/**\n * Build a pairwise cosine similarity matrix from embedding vectors.\n *\n * @param embeddings - Array of embedding vectors\n * @returns NxN similarity matrix\n */\nexport function buildSimilarityMatrix(embeddings: number[][]): number[][] {\n const n = embeddings.length;\n const matrix: number[][] = Array.from({ length: n }, () => new Array<number>(n).fill(0));\n\n for (let i = 0; i < n; i++) {\n matrix[i]![i] = 1.0;\n for (let j = i + 1; j < n; j++) {\n const sim = cosineSimilarity(embeddings[i]!, embeddings[j]!);\n matrix[i]![j] = sim;\n matrix[j]![i] = sim;\n }\n }\n\n return matrix;\n}\n\n/**\n * Cluster memory items by embedding similarity using single-linkage\n * agglomerative clustering.\n *\n * @param items - Memory items to cluster\n * @param embeddings - Embedding vectors (same order as items)\n * @param threshold - Minimum similarity to merge clusters (default: 0.75)\n * @returns Clusters of similar items and noise (unclustered items)\n */\nexport function clusterBySimilarity(\n items: MemoryItem[],\n embeddings: number[][],\n threshold: number = DEFAULT_THRESHOLD\n): ClusterResult {\n const n = items.length;\n if (n === 0) return { clusters: [], noise: [] };\n\n const matrix = buildSimilarityMatrix(embeddings);\n\n // Union-Find for single-linkage clustering\n const parent = Array.from({ length: n }, (_, i) => i);\n\n function find(x: number): number {\n while (parent[x] !== x) {\n parent[x] = parent[parent[x]!]!; // path compression\n x = parent[x]!;\n }\n return x;\n }\n\n function union(a: number, b: number): void {\n const rootA = find(a);\n const rootB = find(b);\n if (rootA !== rootB) parent[rootA] = rootB;\n }\n\n // Merge pairs above threshold\n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n if (matrix[i]![j]! >= threshold) {\n union(i, j);\n }\n }\n }\n\n // Group items by their root\n const groups = new Map<number, MemoryItem[]>();\n for (let i = 0; i < n; i++) {\n const root = find(i);\n let group = groups.get(root);\n if (!group) {\n group = [];\n groups.set(root, group);\n }\n group.push(items[i]!);\n }\n\n const clusters = Array.from(groups.values());\n return { clusters, noise: [] };\n}\n","/**\n * Types for the compounding module.\n *\n * CctPattern represents a cross-cutting pattern synthesized\n * from multiple similar lessons.\n */\n\nimport { createHash } from 'node:crypto';\nimport { z } from 'zod';\n\nimport type { MemoryItem } from '../memory/index.js';\n\n/** Relative path to CCT patterns file from repo root */\nexport const CCT_PATTERNS_PATH = '.claude/lessons/cct-patterns.jsonl';\n\n/** Schema for a cross-cutting pattern */\nexport const CctPatternSchema = z.object({\n id: z.string().regex(/^CCT-[a-f0-9]{8}$/),\n name: z.string().min(1),\n description: z.string().min(1),\n frequency: z.number().int().positive(),\n testable: z.boolean(),\n testApproach: z.string().optional(),\n sourceIds: z.array(z.string()).min(1),\n created: z.string(), // ISO8601\n});\n\n/** Inferred type from CctPatternSchema */\nexport type CctPattern = z.infer<typeof CctPatternSchema>;\n\n/** Result from clustering operation */\nexport interface ClusterResult {\n /** Groups of similar items */\n clusters: MemoryItem[][];\n /** Items that didn't fit any cluster */\n noise: MemoryItem[];\n}\n\n/**\n * Generate a CCT pattern ID from a cluster ID string.\n * Format: \"CCT-\" + first 8 hex chars of SHA-256 hash.\n */\nexport function generateCctId(input: string): string {\n const hash = createHash('sha256').update(input).digest('hex');\n return `CCT-${hash.slice(0, 8)}`;\n}\n","/**\n * I/O module for CctPattern persistence.\n *\n * Append-only JSONL storage, following the same pattern as\n * src/memory/storage/jsonl.ts.\n */\n\nimport { appendFile, mkdir, readFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\nimport { CCT_PATTERNS_PATH, CctPatternSchema, type CctPattern } from './types.js';\n\n/**\n * Read all CCT patterns from the JSONL file.\n *\n * @param repoRoot - Repository root directory\n * @returns Array of CctPattern objects\n */\nexport async function readCctPatterns(repoRoot: string): Promise<CctPattern[]> {\n const filePath = join(repoRoot, CCT_PATTERNS_PATH);\n\n let content: string;\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw err;\n }\n\n const patterns: CctPattern[] = [];\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n const parsed = JSON.parse(trimmed) as unknown;\n const result = CctPatternSchema.safeParse(parsed);\n if (result.success) {\n patterns.push(result.data);\n }\n }\n\n return patterns;\n}\n\n/**\n * Append CCT patterns to the JSONL file (append-only).\n *\n * @param repoRoot - Repository root directory\n * @param patterns - Patterns to append\n */\nexport async function writeCctPatterns(repoRoot: string, patterns: CctPattern[]): Promise<void> {\n const filePath = join(repoRoot, CCT_PATTERNS_PATH);\n await mkdir(dirname(filePath), { recursive: true });\n\n const lines = patterns.map((p) => JSON.stringify(p) + '\\n').join('');\n await appendFile(filePath, lines, 'utf-8');\n}\n","/**\n * Synthesis module for extracting cross-cutting patterns from clusters.\n *\n * Takes a cluster of similar memory items and produces a CctPattern\n * summarizing the common theme.\n */\n\nimport type { MemoryItem } from '../memory/index.js';\nimport { generateCctId, type CctPattern } from './types.js';\n\n/**\n * Synthesize a CctPattern from a cluster of similar memory items.\n *\n * @param cluster - Group of similar memory items\n * @param clusterId - Identifier for this cluster (used for ID generation)\n * @returns A CctPattern summarizing the cluster\n */\nexport function synthesizePattern(cluster: MemoryItem[], clusterId: string): CctPattern {\n const id = generateCctId(clusterId);\n const frequency = cluster.length;\n const sourceIds = cluster.map((item) => item.id);\n\n // Collect all tags with frequency counts\n const tagCounts = new Map<string, number>();\n for (const item of cluster) {\n for (const tag of item.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) ?? 0) + 1);\n }\n }\n\n // Sort tags by frequency (descending)\n const sortedTags = [...tagCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([tag]) => tag);\n\n // Build name from top tags or first insight\n const name = sortedTags.length > 0\n ? sortedTags.slice(0, 3).join(', ')\n : cluster[0]!.insight.slice(0, 50);\n\n // Build description from all insights\n const description = cluster.map((item) => item.insight).join('; ');\n\n // Determine testability: true if any item has high severity or evidence\n const hasHighSeverity = cluster.some(\n (item) => 'severity' in item && item.severity === 'high'\n );\n const hasEvidence = cluster.some(\n (item) => 'evidence' in item && item.evidence\n );\n const testable = hasHighSeverity || hasEvidence;\n\n // Generate test approach when testable\n const testApproach = testable\n ? `Verify pattern: ${name}. Check ${frequency} related lesson(s).`\n : undefined;\n\n return {\n id,\n name,\n description,\n frequency,\n testable,\n ...(testApproach !== undefined && { testApproach }),\n sourceIds,\n created: new Date().toISOString(),\n };\n}\n","/**\n * Compound command: synthesize CCT patterns from lessons.\n *\n * Reads all memory items, clusters them by embedding similarity,\n * and writes synthesized cross-cutting patterns to cct-patterns.jsonl.\n */\n\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { clusterBySimilarity, synthesizePattern, writeCctPatterns } from '../compound/index.js';\nimport { embedText } from '../memory/embeddings/index.js';\nimport { readMemoryItems } from '../memory/storage/index.js';\n\n/**\n * Register compound commands on the program.\n */\nexport function registerCompoundCommands(program: Command): void {\n program\n .command('compound')\n .description('Synthesize cross-cutting patterns from lessons')\n .action(async () => {\n const repoRoot = getRepoRoot();\n\n // Read all memory items\n const { items } = await readMemoryItems(repoRoot);\n if (items.length === 0) {\n console.log('Synthesized 0 patterns from 0 lessons.');\n return;\n }\n\n // Compute embeddings for all items\n const embeddings: number[][] = [];\n for (const item of items) {\n const text = `${item.trigger} ${item.insight}`;\n const vec = await embedText(text);\n embeddings.push(Array.isArray(vec) ? vec : Array.from(vec));\n }\n\n // Cluster by similarity\n const { clusters } = clusterBySimilarity(items, embeddings);\n\n // Filter clusters with 2+ items (single-item clusters are noise)\n const multiClusters = clusters.filter((c) => c.length >= 2);\n\n // Synthesize patterns from clusters\n const patterns = multiClusters.map((cluster) => {\n const clusterId = cluster.map((item) => item.id).join('-');\n return synthesizePattern(cluster, clusterId);\n });\n\n // Write patterns to file\n if (patterns.length > 0) {\n await writeCctPatterns(repoRoot, patterns);\n }\n\n const lessonCount = items.length;\n console.log(`Synthesized ${patterns.length} pattern(s) from ${lessonCount} lessons.`);\n });\n}\n","/**\n * Quality filters for lesson capture\n *\n * Filters to ensure lessons are:\n * - Novel (not duplicate)\n * - Specific (not vague)\n *\n * Actionability check is available but not part of the capture gate.\n * Strategy: capture aggressively, prune later.\n */\n\nimport { searchKeyword, syncIfNeeded } from '../storage/index.js';\nimport type { MemoryItem } from '../types.js';\n\n/** Default similarity threshold for duplicate detection */\nconst DEFAULT_SIMILARITY_THRESHOLD = 0.8;\n\n/** Result of novelty check */\nexport interface NoveltyResult {\n novel: boolean;\n reason?: string;\n existingId?: string;\n}\n\n/** Options for novelty check */\nexport interface NoveltyOptions {\n threshold?: number;\n}\n\n/**\n * Check if an insight is novel (not a duplicate of existing lessons).\n * Uses keyword search to find potentially similar lessons.\n */\nexport async function isNovel(\n repoRoot: string,\n insight: string,\n options: NoveltyOptions = {}\n): Promise<NoveltyResult> {\n const threshold = options.threshold ?? DEFAULT_SIMILARITY_THRESHOLD;\n\n // Sync index if JSONL has changed\n await syncIfNeeded(repoRoot);\n\n // Extract key words for search (take first 3 significant words)\n const words = insight\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, '')\n .split(/\\s+/)\n .filter((w) => w.length > 3)\n .slice(0, 3);\n\n if (words.length === 0) {\n return { novel: true };\n }\n\n // Search for each word and collect results\n const searchQuery = words.join(' OR ');\n const results = await searchKeyword(repoRoot, searchQuery, 10);\n\n if (results.length === 0) {\n return { novel: true };\n }\n\n return checkSimilarity(insight, results, threshold);\n}\n\n/**\n * Check similarity between insight and existing lessons using Jaccard similarity.\n */\nfunction checkSimilarity(\n insight: string,\n lessons: MemoryItem[],\n threshold: number\n): NoveltyResult {\n const insightWords = new Set(insight.toLowerCase().split(/\\s+/));\n\n for (const lesson of lessons) {\n const lessonWords = new Set(lesson.insight.toLowerCase().split(/\\s+/));\n\n // Calculate Jaccard similarity\n const intersection = [...insightWords].filter((w) => lessonWords.has(w)).length;\n const union = new Set([...insightWords, ...lessonWords]).size;\n const similarity = union > 0 ? intersection / union : 0;\n\n if (similarity >= threshold) {\n return {\n novel: false,\n reason: `Found similar existing lesson: \"${lesson.insight.slice(0, 50)}...\"`,\n existingId: lesson.id,\n };\n }\n }\n\n return { novel: true };\n}\n\n/** Minimum word count for a specific insight */\nconst MIN_WORD_COUNT = 4;\n\n/** Vague patterns that indicate non-specific advice */\nconst VAGUE_PATTERNS = [\n /\\bwrite better\\b/i,\n /\\bbe careful\\b/i,\n /\\bremember to\\b/i,\n /\\bmake sure\\b/i,\n /\\btry to\\b/i,\n /\\bdouble check\\b/i,\n];\n\n/** Generic \"always/never\" phrases (short, lacking specificity) */\nconst GENERIC_IMPERATIVE_PATTERN = /^(always|never)\\s+\\w+(\\s+\\w+){0,2}$/i;\n\n/** Result of specificity check */\nexport interface SpecificityResult {\n specific: boolean;\n reason?: string;\n}\n\n/**\n * Check if an insight is specific enough to be useful.\n * Rejects vague, generic advice that doesn't provide actionable guidance.\n */\nexport function isSpecific(insight: string): SpecificityResult {\n // Check minimum length first\n const words = insight.trim().split(/\\s+/).filter((w) => w.length > 0);\n if (words.length < MIN_WORD_COUNT) {\n return { specific: false, reason: 'Insight is too short to be actionable' };\n }\n\n // Check for vague patterns\n for (const pattern of VAGUE_PATTERNS) {\n if (pattern.test(insight)) {\n return { specific: false, reason: 'Insight matches a vague pattern' };\n }\n }\n\n // Check for generic \"Always X\" or \"Never X\" phrases\n if (GENERIC_IMPERATIVE_PATTERN.test(insight)) {\n return { specific: false, reason: 'Insight matches a vague pattern' };\n }\n\n return { specific: true };\n}\n\n/** Action word patterns that indicate actionable guidance */\nconst ACTION_PATTERNS = [\n /\\buse\\s+.+\\s+instead\\s+of\\b/i, // \"use X instead of Y\"\n /\\bprefer\\s+.+\\s+(over|to)\\b/i, // \"prefer X over Y\" or \"prefer X to Y\"\n /\\balways\\s+.+\\s+when\\b/i, // \"always X when Y\"\n /\\bnever\\s+.+\\s+without\\b/i, // \"never X without Y\"\n /\\bavoid\\s+(using\\s+)?\\w+/i, // \"avoid X\" or \"avoid using X\"\n /\\bcheck\\s+.+\\s+before\\b/i, // \"check X before Y\"\n /^(run|use|add|remove|install|update|configure|set|enable|disable)\\s+/i, // Imperative commands at start\n];\n\n/** Result of actionability check */\nexport interface ActionabilityResult {\n actionable: boolean;\n reason?: string;\n}\n\n/**\n * Check if an insight contains actionable guidance.\n * Returns false for pure observations or questions.\n */\nexport function isActionable(insight: string): ActionabilityResult {\n // Check for action patterns\n for (const pattern of ACTION_PATTERNS) {\n if (pattern.test(insight)) {\n return { actionable: true };\n }\n }\n\n return { actionable: false, reason: 'Insight lacks clear action guidance' };\n}\n\n/** Result of combined quality check */\nexport interface ProposeResult {\n shouldPropose: boolean;\n reason?: string;\n}\n\n/**\n * Combined quality check for lesson proposals.\n * Returns true only if insight is novel AND specific.\n * Actionability gate removed: capture aggressively, prune later.\n */\nexport async function shouldPropose(\n repoRoot: string,\n insight: string\n): Promise<ProposeResult> {\n // Check specificity first (fast, no DB)\n const specificResult = isSpecific(insight);\n if (!specificResult.specific) {\n return { shouldPropose: false, reason: specificResult.reason };\n }\n\n // Check novelty (requires DB lookup)\n const noveltyResult = await isNovel(repoRoot, insight);\n if (!noveltyResult.novel) {\n return { shouldPropose: false, reason: noveltyResult.reason };\n }\n\n return { shouldPropose: true };\n}\n","/**\n * Trigger detection for automatic memory capture\n *\n * Detects patterns that indicate potential learning opportunities:\n * - User corrections\n * - Self-corrections\n * - Test failures\n *\n * Also infers memory item type from insight text:\n * - pattern: \"use X instead of Y\", \"prefer X over Y\"\n * - solution: \"when X, do Y\", \"if X then Y\", \"to fix X\"\n * - preference: \"always X\", \"never X\"\n * - lesson: default for unclassified insights\n */\n\nimport type { Context, MemoryItemType } from '../types.js';\n\n/** Signal data for correction detection */\nexport interface CorrectionSignal {\n messages: string[];\n context: Context;\n}\n\n/** Detected correction result */\nexport interface DetectedCorrection {\n trigger: string;\n correctionMessage: string;\n context: Context;\n}\n\n/** User correction patterns */\nconst USER_CORRECTION_PATTERNS = [\n /\\bno\\b[,.]?\\s/i, // \"no, ...\" or \"no ...\"\n /\\bwrong\\b/i, // \"wrong\"\n /\\bactually\\b/i, // \"actually...\"\n /\\bnot that\\b/i, // \"not that\"\n /\\bi meant\\b/i, // \"I meant\"\n];\n\n/**\n * Detect user correction signals in conversation.\n *\n * Looks for patterns that indicate the user is correcting Claude's\n * understanding or actions.\n *\n * @param signals - Messages and context to analyze\n * @returns Detected correction or null if none found\n */\nexport function detectUserCorrection(signals: CorrectionSignal): DetectedCorrection | null {\n const { messages, context } = signals;\n\n if (messages.length < 2) {\n return null;\n }\n\n // Check later messages for correction patterns\n for (let i = 1; i < messages.length; i++) {\n const message = messages[i];\n if (!message) continue;\n\n for (const pattern of USER_CORRECTION_PATTERNS) {\n if (pattern.test(message)) {\n return {\n trigger: `User correction during ${context.intent}`,\n correctionMessage: message,\n context,\n };\n }\n }\n }\n\n return null;\n}\n\n/** Edit history entry */\nexport interface EditEntry {\n file: string;\n success: boolean;\n timestamp: number;\n}\n\n/** Edit history for self-correction detection */\nexport interface EditHistory {\n edits: EditEntry[];\n}\n\n/** Detected self-correction */\nexport interface DetectedSelfCorrection {\n file: string;\n trigger: string;\n}\n\n/**\n * Detect self-correction patterns in edit history.\n *\n * Looks for edit→fail→re-edit patterns on the same file,\n * which indicate Claude had to correct its own work.\n *\n * @param history - Edit history to analyze\n * @returns Detected self-correction or null if none found\n */\nexport function detectSelfCorrection(history: EditHistory): DetectedSelfCorrection | null {\n const { edits } = history;\n\n if (edits.length < 3) {\n return null;\n }\n\n // Look for edit→fail→re-edit pattern on same file\n for (let i = 0; i <= edits.length - 3; i++) {\n const first = edits[i];\n const second = edits[i + 1];\n const third = edits[i + 2];\n\n if (!first || !second || !third) continue;\n\n // Pattern: success → fail → success on same file\n if (\n first.file === second.file &&\n second.file === third.file &&\n first.success &&\n !second.success &&\n third.success\n ) {\n return {\n file: first.file,\n trigger: `Self-correction on ${first.file}`,\n };\n }\n }\n\n return null;\n}\n\n/** Test result for failure detection */\nexport interface TestResult {\n passed: boolean;\n output: string;\n testFile: string;\n}\n\n/** Detected test failure */\nexport interface DetectedTestFailure {\n testFile: string;\n errorOutput: string;\n trigger: string;\n}\n\n/**\n * Detect test failure patterns.\n *\n * When tests fail, this creates a potential learning opportunity\n * if the failure is later fixed.\n *\n * @param testResult - Test result to analyze\n * @returns Detected test failure or null if tests passed\n */\nexport function detectTestFailure(testResult: TestResult): DetectedTestFailure | null {\n if (testResult.passed) {\n return null;\n }\n\n // Extract first meaningful error line for trigger\n const lines = testResult.output.split('\\n').filter((line) => line.trim().length > 0);\n const errorLine = lines.find((line) => /error|fail|assert/i.test(line)) ?? lines[0] ?? '';\n\n return {\n testFile: testResult.testFile,\n errorOutput: testResult.output,\n trigger: `Test failure in ${testResult.testFile}: ${errorLine.slice(0, 100)}`,\n };\n}\n\n/** Patterns indicating a code pattern (bad -> good transformation) */\nconst PATTERN_INDICATORS = [\n /\\buse\\s+.+\\s+instead\\s+of\\b/i,\n /\\bprefer\\s+.+\\s+(over|to)\\b/i,\n];\n\n/** Patterns indicating a solution (problem -> resolution) */\nconst SOLUTION_INDICATORS = [\n /\\bwhen\\s+.+,\\s/i,\n /\\bif\\s+.+\\bthen\\b/i,\n /\\bif\\s+.+,\\s/i,\n /\\bto\\s+fix\\b/i,\n];\n\n/** Patterns indicating a preference (user workflow choice) */\nconst PREFERENCE_INDICATORS = [\n /\\balways\\s+/i,\n /\\bnever\\s+/i,\n];\n\n/**\n * Infer the memory item type from insight text.\n *\n * Rules (checked in priority order):\n * - \"use X instead of Y\" / \"prefer X over Y\" → pattern\n * - \"when X, do Y\" / \"if X then Y\" / \"to fix X\" → solution\n * - \"always X\" / \"never X\" → preference\n * - Default → lesson\n *\n * @param insight - The insight text to classify\n * @returns The inferred memory item type\n */\nexport function inferMemoryItemType(insight: string): MemoryItemType {\n for (const pattern of PATTERN_INDICATORS) {\n if (pattern.test(insight)) return 'pattern';\n }\n\n for (const pattern of SOLUTION_INDICATORS) {\n if (pattern.test(insight)) return 'solution';\n }\n\n for (const pattern of PREFERENCE_INDICATORS) {\n if (pattern.test(insight)) return 'preference';\n }\n\n return 'lesson';\n}\n","/**\n * Trigger detection integration\n *\n * Orchestrates detection -> quality filter -> memory item proposal flow.\n * Infers memory item type from insight content.\n * Provides a high-level API for CLI and hooks.\n */\n\nimport * as fs from 'node:fs/promises';\n\nimport { z } from 'zod';\n\nimport { ContextSchema } from '../types.js';\nimport type { MemoryItemType, Source } from '../types.js';\nimport { shouldPropose } from './quality.js';\nimport {\n detectUserCorrection,\n detectSelfCorrection,\n detectTestFailure,\n inferMemoryItemType,\n} from './triggers.js';\nimport type {\n CorrectionSignal,\n EditHistory,\n TestResult,\n} from './triggers.js';\n\n/** Detection input types */\nexport type DetectionType = 'user' | 'self' | 'test';\n\n/** Input for user correction detection */\nexport interface UserDetectionInput {\n type: 'user';\n data: CorrectionSignal;\n}\n\n/** Input for self correction detection */\nexport interface SelfDetectionInput {\n type: 'self';\n data: EditHistory;\n}\n\n/** Input for test failure detection */\nexport interface TestDetectionInput {\n type: 'test';\n data: TestResult;\n}\n\n/** Union type for all detection inputs */\nexport type DetectionInput = UserDetectionInput | SelfDetectionInput | TestDetectionInput;\n\n/** Result of successful detection */\nexport interface DetectionResult {\n trigger: string;\n source: Source;\n proposedInsight: string;\n memoryItemType: MemoryItemType;\n}\n\n/**\n * Detect triggers and propose lessons.\n *\n * Runs the appropriate detector based on input type, then filters\n * through quality checks. Returns a proposal if detection passes\n * all quality filters.\n *\n * @param repoRoot - Repository root path\n * @param input - Detection input with type and data\n * @returns Detection result with proposed insight, or null\n */\nexport async function detectAndPropose(\n repoRoot: string,\n input: DetectionInput\n): Promise<DetectionResult | null> {\n const detected = runDetector(input);\n if (!detected) {\n return null;\n }\n\n const { trigger, source, proposedInsight } = detected;\n\n // Run quality filters on proposed insight\n const quality = await shouldPropose(repoRoot, proposedInsight);\n if (!quality.shouldPropose) {\n return null;\n }\n\n // Infer memory item type from insight content\n const memoryItemType = inferMemoryItemType(proposedInsight);\n\n return { trigger, source, proposedInsight, memoryItemType };\n}\n\n/** Internal detection result before quality filtering */\ninterface RawDetection {\n trigger: string;\n source: Source;\n proposedInsight: string;\n}\n\n/**\n * Run the appropriate detector based on input type.\n */\nfunction runDetector(input: DetectionInput): RawDetection | null {\n switch (input.type) {\n case 'user':\n return detectUserCorrectionFlow(input.data);\n case 'self':\n return detectSelfCorrectionFlow(input.data);\n case 'test':\n return detectTestFailureFlow(input.data);\n }\n}\n\n/**\n * Detect user correction and extract insight.\n */\nfunction detectUserCorrectionFlow(data: CorrectionSignal): RawDetection | null {\n const result = detectUserCorrection(data);\n if (!result) {\n return null;\n }\n\n return {\n trigger: result.trigger,\n source: 'user_correction',\n proposedInsight: result.correctionMessage,\n };\n}\n\n/**\n * Detect self correction and extract insight.\n */\nfunction detectSelfCorrectionFlow(data: EditHistory): RawDetection | null {\n const result = detectSelfCorrection(data);\n if (!result) {\n return null;\n }\n\n return {\n trigger: result.trigger,\n source: 'self_correction',\n // Self-corrections need context to form useful insights\n proposedInsight: `Check ${result.file} for common errors before editing`,\n };\n}\n\n/**\n * Detect test failure and extract insight.\n */\nfunction detectTestFailureFlow(data: TestResult): RawDetection | null {\n const result = detectTestFailure(data);\n if (!result) {\n return null;\n }\n\n return {\n trigger: result.trigger,\n source: 'test_failure',\n proposedInsight: result.errorOutput,\n };\n}\n\n/** Zod schema for CorrectionSignal */\nconst CorrectionSignalSchema = z.object({\n messages: z.array(z.string()),\n context: ContextSchema,\n});\n\n/** Zod schema for EditEntry */\nconst EditEntrySchema = z.object({\n file: z.string(),\n success: z.boolean(),\n timestamp: z.number(),\n});\n\n/** Zod schema for EditHistory */\nconst EditHistorySchema = z.object({\n edits: z.array(EditEntrySchema),\n});\n\n/** Zod schema for TestResult */\nconst TestResultSchema = z.object({\n passed: z.boolean(),\n output: z.string(),\n testFile: z.string(),\n});\n\n/** Zod discriminated union for DetectionInput */\nconst DetectionInputSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('user'), data: CorrectionSignalSchema }),\n z.object({ type: z.literal('self'), data: EditHistorySchema }),\n z.object({ type: z.literal('test'), data: TestResultSchema }),\n]);\n\n/**\n * Parse detection input from a JSON file.\n *\n * @param filePath - Path to JSON input file\n * @returns Parsed detection input\n * @throws ZodError if file content doesn't match expected schema\n */\nexport async function parseInputFile(filePath: string): Promise<DetectionInput> {\n const content = await fs.readFile(filePath, 'utf-8');\n const data: unknown = JSON.parse(content);\n return DetectionInputSchema.parse(data);\n}\n","/**\n * Session-start lesson retrieval\n *\n * Loads high-severity lessons at the start of a session.\n * No vector search - just filter by severity and recency.\n */\n\nimport { incrementRetrievalCount, readMemoryItems } from '../storage/index.js';\nimport type { MemoryItem, Severity } from '../types.js';\n\n/** Default number of lessons to load at session start */\nconst DEFAULT_LIMIT = 5;\n\n/** A memory item with severity field present */\ntype LessonWithSeverity = MemoryItem & { severity: Severity };\n\n/**\n * Type guard to check if a memory item has severity set\n */\nfunction hasSeverity(item: MemoryItem): item is MemoryItem & { severity: Severity } {\n return item.severity !== undefined;\n}\n\n/**\n * Load high-severity lessons for session start.\n *\n * Returns confirmed, high-severity lessons sorted by recency.\n * These are the most important lessons to surface at the start\n * of a coding session.\n *\n * @param repoRoot - Repository root directory\n * @param limit - Maximum number of lessons to return (default: 5)\n * @returns Array of high-severity lessons, most recent first\n */\nexport async function loadSessionLessons(\n repoRoot: string,\n limit: number = DEFAULT_LIMIT\n): Promise<LessonWithSeverity[]> {\n const { items } = await readMemoryItems(repoRoot);\n\n // Filter for high-severity, confirmed items of any type (excluding invalidated)\n const highSeverityLessons = items.filter(\n (item): item is MemoryItem & { severity: Severity } =>\n hasSeverity(item) &&\n item.severity === 'high' &&\n item.confirmed &&\n !item.invalidatedAt\n );\n\n // Sort by recency (most recent first)\n highSeverityLessons.sort((a, b) => {\n const dateA = new Date(a.created).getTime();\n const dateB = new Date(b.created).getTime();\n return dateB - dateA;\n });\n\n // Return top N and track surfaced lessons as retrieved.\n const topLessons = highSeverityLessons.slice(0, limit);\n if (topLessons.length > 0) {\n incrementRetrievalCount(repoRoot, topLessons.map((lesson) => lesson.id));\n }\n\n return topLessons;\n}\n\n/**\n * @deprecated Use loadSessionMemory. Backward-compat alias.\n */\nexport const loadSessionMemory = loadSessionLessons;\n","/**\n * Plan-time lesson retrieval\n *\n * Retrieves relevant lessons when planning an implementation.\n * Uses vector search to find semantically similar lessons.\n */\n\nimport { rankLessons, searchVector, type RankedLesson, type ScoredLesson } from '../search/index.js';\nimport { incrementRetrievalCount } from '../storage/index.js';\n\n/** Default number of lessons to retrieve */\nconst DEFAULT_LIMIT = 5;\n\n/** Result of plan-time retrieval */\nexport interface PlanRetrievalResult {\n lessons: RankedLesson[];\n message: string;\n}\n\n/**\n * Retrieve relevant lessons for a plan.\n *\n * Uses vector search to find semantically similar lessons,\n * then applies ranking boosts for severity, recency, and confirmation.\n *\n * Hard-fails if embeddings are unavailable (propagates error from embedText).\n *\n * @param repoRoot - Repository root directory\n * @param planText - The plan text to search against\n * @param limit - Maximum number of lessons to return (default: 5)\n * @returns Ranked lessons and formatted message\n */\nexport async function retrieveForPlan(\n repoRoot: string,\n planText: string,\n limit: number = DEFAULT_LIMIT\n): Promise<PlanRetrievalResult> {\n // Get lessons by vector similarity (will throw if embeddings unavailable)\n const scored = await searchVector(repoRoot, planText, { limit: limit * 2 });\n\n // Apply ranking boosts\n const ranked = rankLessons(scored);\n\n // Take top N after ranking\n const topLessons = ranked.slice(0, limit);\n\n // Track actual plan-time retrieval usage only for surfaced lessons.\n if (topLessons.length > 0) {\n incrementRetrievalCount(repoRoot, topLessons.map((item) => item.lesson.id));\n }\n\n // Format the Lessons Check message\n const message = formatLessonsCheck(topLessons);\n\n return { lessons: topLessons, message };\n}\n\n/**\n * Format a \"Lessons Check\" message for display.\n *\n * This message is intended to be shown at plan-time to remind\n * the developer of relevant lessons before implementation.\n *\n * @param lessons - Ranked lessons to include in the message\n * @returns Formatted message string\n */\nexport function formatLessonsCheck(lessons: ScoredLesson[]): string {\n const header = 'Lessons Check\\n' + '─'.repeat(40);\n\n if (lessons.length === 0) {\n return `${header}\\nNo relevant lessons found for this plan.`;\n }\n\n const lessonLines = lessons.map((l, i) => {\n const bullet = `${i + 1}.`;\n const insight = l.lesson.insight;\n return `${bullet} ${insight}`;\n });\n\n return `${header}\\n${lessonLines.join('\\n')}`;\n}\n\n/**\n * @deprecated Use formatMemoryCheck. Backward-compat alias.\n */\nexport const formatMemoryCheck = formatLessonsCheck;\n","/**\n * Lessons audit check.\n *\n * Surfaces high-severity lessons as info-level findings.\n */\n\nimport { LESSONS_PATH, readMemoryItems } from '../../memory/storage/index.js';\nimport type { AuditCheckResult } from '../types.js';\n\n/**\n * Check for high-severity lessons and return as info findings.\n *\n * @param repoRoot - Repository root directory\n * @returns Audit check result with findings and filesChecked\n */\nexport async function checkLessons(repoRoot: string): Promise<AuditCheckResult> {\n const { items } = await readMemoryItems(repoRoot);\n const findings: AuditCheckResult['findings'] = [];\n\n for (const item of items) {\n if (item.severity === 'high') {\n findings.push({\n file: '',\n issue: `High-severity lesson: ${item.insight}`,\n severity: 'info',\n relatedLessonId: item.id,\n source: 'lesson',\n });\n }\n }\n\n const filesChecked = items.length > 0 ? [LESSONS_PATH] : [];\n return { findings, filesChecked };\n}\n","/**\n * Zod schemas for rule configuration.\n *\n * Rules are defined in .claude/rules.json and describe mechanical checks\n * that can be run against a codebase.\n */\n\nimport { z } from 'zod';\n\n/** Rule severity levels. */\nexport const SeveritySchema = z.enum(['error', 'warning', 'info']);\n\n/** File-pattern check: regex match on files matching a glob. */\nexport const FilePatternCheckSchema = z.object({\n type: z.literal('file-pattern'),\n glob: z.string(),\n pattern: z.string(),\n mustMatch: z.boolean().optional(),\n});\n\n/** File-size check: line count limit on files matching a glob. */\nexport const FileSizeCheckSchema = z.object({\n type: z.literal('file-size'),\n glob: z.string(),\n maxLines: z.number().int().positive(),\n});\n\n/** Script check: run a shell command and check exit code. */\nexport const ScriptCheckSchema = z.object({\n type: z.literal('script'),\n command: z.string(),\n expectExitCode: z.number().int().optional(),\n});\n\n/** Discriminated union of all check types. */\nexport const RuleCheckSchema = z.discriminatedUnion('type', [\n FilePatternCheckSchema,\n FileSizeCheckSchema,\n ScriptCheckSchema,\n]);\n\n/** A single rule definition. */\nexport const RuleSchema = z.object({\n id: z.string().min(1),\n description: z.string(),\n severity: SeveritySchema,\n check: RuleCheckSchema,\n remediation: z.string(),\n});\n\n/** Top-level rule configuration file schema. */\nexport const RuleConfigSchema = z.object({\n rules: z.array(RuleSchema),\n});\n\n// Type exports\nexport type Severity = z.infer<typeof SeveritySchema>;\nexport type FilePatternCheck = z.infer<typeof FilePatternCheckSchema>;\nexport type FileSizeCheck = z.infer<typeof FileSizeCheckSchema>;\nexport type ScriptCheck = z.infer<typeof ScriptCheckSchema>;\nexport type RuleCheck = z.infer<typeof RuleCheckSchema>;\nexport type Rule = z.infer<typeof RuleSchema>;\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n","/**\n * Simple glob-like file finder using Node.js built-in fs.\n *\n * Supports basic glob patterns: **, *, and extension matching.\n * No external dependencies required.\n */\n\nimport { readdirSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\n\n/**\n * Convert a simple glob pattern to a regex.\n * Supports: ** (any path), * (any segment), .ext matching.\n *\n * @param glob - Glob pattern (e.g., \"**\\/*.ts\", \"src/*.js\")\n * @returns RegExp that matches the pattern\n */\nexport function globToRegex(glob: string): RegExp {\n const pattern = glob\n .replace(/\\./g, '\\\\.') // escape dots\n .replace(/\\*\\*\\//g, '(.+/)?') // ** matches any directory depth\n .replace(/\\*/g, '[^/]*'); // * matches within a single segment\n return new RegExp(`^${pattern}$`);\n}\n\n/**\n * Find files in baseDir matching a glob pattern.\n *\n * @param baseDir - Root directory to search from\n * @param glob - Glob pattern to match\n * @returns Array of relative file paths matching the pattern\n */\nexport function findFiles(baseDir: string, glob: string): string[] {\n const regex = globToRegex(glob);\n const results: string[] = [];\n\n function walk(dir: string): void {\n const entries = readdirSync(dir);\n for (const entry of entries) {\n // Skip hidden directories and node_modules\n if (entry.startsWith('.') || entry === 'node_modules') continue;\n\n const fullPath = join(dir, entry);\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n walk(fullPath);\n } else {\n const relPath = relative(baseDir, fullPath);\n if (regex.test(relPath)) {\n results.push(relPath);\n }\n }\n }\n }\n\n walk(baseDir);\n return results.sort();\n}\n","/**\n * File-pattern rule check implementation.\n *\n * Scans files matching a glob for a regex pattern.\n * By default, matches are violations. With mustMatch=true,\n * files missing the pattern are violations.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport type { FilePatternCheck } from '../types.js';\nimport type { Violation } from '../engine.js';\n\nimport { findFiles } from './glob-utils.js';\n\n/**\n * Run a file-pattern check against files in baseDir.\n *\n * @param baseDir - Root directory to search from\n * @param check - The file-pattern check configuration\n * @returns Array of violations found\n */\nexport function runFilePatternCheck(\n baseDir: string,\n check: FilePatternCheck,\n): Violation[] {\n const files = findFiles(baseDir, check.glob);\n const regex = new RegExp(check.pattern);\n const violations: Violation[] = [];\n\n for (const file of files) {\n const fullPath = join(baseDir, file);\n const content = readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n if (check.mustMatch) {\n const found = lines.some((line) => regex.test(line));\n if (!found) {\n violations.push({\n file,\n message: `Pattern ${check.pattern} missing from file`,\n });\n }\n } else {\n for (let i = 0; i < lines.length; i++) {\n if (regex.test(lines[i]!)) {\n violations.push({\n file,\n line: i + 1,\n message: `Pattern ${check.pattern} matched`,\n });\n }\n }\n }\n }\n\n return violations;\n}\n","/**\n * File-size rule check implementation.\n *\n * Checks that files matching a glob do not exceed a line count limit.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport type { FileSizeCheck } from '../types.js';\nimport type { Violation } from '../engine.js';\n\nimport { findFiles } from './glob-utils.js';\n\n/**\n * Run a file-size check against files in baseDir.\n *\n * @param baseDir - Root directory to search from\n * @param check - The file-size check configuration\n * @returns Array of violations found\n */\nexport function runFileSizeCheck(\n baseDir: string,\n check: FileSizeCheck,\n): Violation[] {\n const files = findFiles(baseDir, check.glob);\n const violations: Violation[] = [];\n\n for (const file of files) {\n const content = readFileSync(join(baseDir, file), 'utf-8');\n // Count non-empty trailing: split and filter trailing empty from final newline\n const lineCount = content === '' ? 0 : content.split('\\n').filter((_, i, arr) => i < arr.length - 1 || arr[i] !== '').length;\n\n if (lineCount > check.maxLines) {\n violations.push({\n file,\n message: `File has ${lineCount} lines, exceeds limit of ${check.maxLines}`,\n });\n }\n }\n\n return violations;\n}\n","/**\n * Script rule check implementation.\n *\n * Runs a shell command and checks the exit code.\n */\n\nimport { execSync } from 'node:child_process';\n\nimport type { ScriptCheck } from '../types.js';\nimport type { Violation } from '../engine.js';\n\n/**\n * Run a script check by executing a shell command.\n *\n * @param check - The script check configuration\n * @returns Array of violations (empty if command exits with expected code)\n */\nexport function runScriptCheck(check: ScriptCheck, baseDir?: string): Violation[] {\n const expectedCode = check.expectExitCode ?? 0;\n\n try {\n execSync(check.command, { stdio: ['pipe', 'pipe', 'pipe'], cwd: baseDir });\n // Exit code 0\n if (expectedCode !== 0) {\n return [{ message: `Script exited with exit code 0, expected ${expectedCode}` }];\n }\n return [];\n } catch (err: unknown) {\n const exitCode = (err as { status?: number }).status ?? 1;\n if (exitCode === expectedCode) {\n return [];\n }\n const stderr = ((err as { stderr?: Buffer }).stderr ?? Buffer.alloc(0))\n .toString('utf-8')\n .trim();\n const msg = stderr\n ? `Script exited with exit code ${exitCode} (expected ${expectedCode}): ${stderr}`\n : `Script exited with exit code ${exitCode} (expected ${expectedCode})`;\n return [{ message: msg }];\n }\n}\n","/**\n * Rule engine: loads config, runs checks, formats output.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { RuleConfigSchema } from './types.js';\nimport type { Rule, RuleConfig } from './types.js';\n\nimport { runFilePatternCheck } from './checks/file-pattern.js';\nimport { runFileSizeCheck } from './checks/file-size.js';\nimport { runScriptCheck } from './checks/script.js';\n\n/** A single violation found by a rule check. */\nexport interface Violation {\n file?: string;\n line?: number;\n message: string;\n}\n\n/** Result of running a single rule. */\nexport interface RuleResult {\n rule: Rule;\n violations: Violation[];\n passed: boolean;\n}\n\n/** Severity label mapping for output formatting. */\nconst SEVERITY_LABELS: Record<string, string> = {\n error: 'ERROR',\n warning: 'WARN',\n info: 'INFO',\n};\n\n/**\n * Load rule configuration from .claude/rules.json.\n *\n * @param baseDir - Repository root directory\n * @returns Parsed rule configuration (empty rules if no config file)\n * @throws On invalid JSON or schema validation failure\n */\nexport function loadRuleConfig(baseDir: string): RuleConfig {\n const configPath = join(baseDir, '.claude', 'rules.json');\n if (!existsSync(configPath)) {\n return { rules: [] };\n }\n\n const raw = readFileSync(configPath, 'utf-8');\n const json: unknown = JSON.parse(raw);\n return RuleConfigSchema.parse(json);\n}\n\n/**\n * Run all rules against the codebase.\n *\n * @param baseDir - Repository root directory\n * @param rules - Array of rules to check\n * @returns Array of results, one per rule\n */\nexport function runRules(baseDir: string, rules: Rule[]): RuleResult[] {\n return rules.map((rule) => {\n try {\n const violations = runCheck(baseDir, rule);\n return { rule, violations, passed: violations.length === 0 };\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Rule check failed';\n return { rule, violations: [{ message: `Rule check error: ${message}` }], passed: false };\n }\n });\n}\n\n/**\n * Format a single violation as an agent-legible line.\n *\n * Format: SEVERITY [rules] rule-id: file:line -- remediation\n *\n * @param rule - The rule that was violated\n * @param violation - The specific violation\n * @returns Formatted single-line string\n */\nexport function formatViolation(rule: Rule, violation: Violation): string {\n const label = SEVERITY_LABELS[rule.severity] ?? 'INFO';\n const location = violation.file\n ? violation.line\n ? `${violation.file}:${violation.line}`\n : violation.file\n : '';\n const locationPart = location ? ` ${location} --` : '';\n const messagePart = violation.message ? ` ${violation.message} --` : '';\n return `${label} [rules] ${rule.id}:${locationPart}${messagePart} ${rule.remediation}`;\n}\n\n/** Dispatch a rule check to the appropriate handler. */\nfunction runCheck(baseDir: string, rule: Rule): Violation[] {\n switch (rule.check.type) {\n case 'file-pattern':\n return runFilePatternCheck(baseDir, rule.check);\n case 'file-size':\n return runFileSizeCheck(baseDir, rule.check);\n case 'script':\n return runScriptCheck(rule.check, baseDir);\n }\n}\n","/**\n * Patterns audit check.\n *\n * Searches source files for known bad patterns from memory items.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { readMemoryItems } from '../../memory/storage/index.js';\nimport { findFiles } from '../../rules/index.js';\nimport type { AuditCheckResult } from '../types.js';\n\n/**\n * Check for bad patterns in source files.\n *\n * @param repoRoot - Repository root directory\n * @returns Audit check result with findings and filesChecked\n */\nexport async function checkPatterns(repoRoot: string): Promise<AuditCheckResult> {\n const { items } = await readMemoryItems(repoRoot);\n\n // Filter items that have pattern.bad defined\n const patterned = items.filter((item) => item.pattern?.bad);\n if (patterned.length === 0) {\n return { findings: [], filesChecked: [] };\n }\n\n // Find source files to scan\n const sourceFiles = findFiles(repoRoot, '**/*.ts');\n const findings: AuditCheckResult['findings'] = [];\n\n for (const item of patterned) {\n const bad = item.pattern!.bad;\n for (const relPath of sourceFiles) {\n const content = readFileSync(join(repoRoot, relPath), 'utf-8');\n if (content.includes(bad)) {\n findings.push({\n file: relPath,\n issue: `Bad pattern found: \"${bad}\" (${item.insight})`,\n severity: 'warning',\n relatedLessonId: item.id,\n suggestedFix: item.pattern!.good ? `Use: ${item.pattern!.good}` : undefined,\n source: 'pattern',\n });\n }\n }\n }\n\n return { findings, filesChecked: sourceFiles };\n}\n","/**\n * Rules audit check.\n *\n * Wraps loadRuleConfig + runRules and converts violations to AuditFinding format.\n */\n\nimport { loadRuleConfig, runRules } from '../../rules/index.js';\nimport type { AuditCheckResult } from '../types.js';\n\n/**\n * Check rules and return findings with files checked.\n *\n * @param repoRoot - Repository root directory\n * @returns Audit check result with findings and filesChecked\n */\nexport function checkRules(repoRoot: string): AuditCheckResult {\n let config;\n try {\n config = loadRuleConfig(repoRoot);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to load rules config';\n return {\n findings: [{\n file: '.claude/rules.json',\n issue: `Invalid rules configuration: ${message}`,\n severity: 'error',\n source: 'rule',\n }],\n filesChecked: [],\n };\n }\n\n if (config.rules.length === 0) {\n return { findings: [], filesChecked: [] };\n }\n\n const results = runRules(repoRoot, config.rules);\n const findings: AuditCheckResult['findings'] = [];\n const filesCheckedSet = new Set<string>();\n\n for (const result of results) {\n for (const violation of result.violations) {\n if (violation.file) {\n filesCheckedSet.add(violation.file);\n }\n findings.push({\n file: violation.file ?? '',\n issue: violation.message,\n severity: result.rule.severity,\n suggestedFix: result.rule.remediation,\n source: 'rule',\n });\n }\n }\n\n return { findings, filesChecked: [...filesCheckedSet] };\n}\n","/**\n * Audit engine: orchestrates checks and builds report.\n */\n\nimport { checkLessons } from './checks/lessons.js';\nimport { checkPatterns } from './checks/patterns.js';\nimport { checkRules } from './checks/rules.js';\nimport type { AuditCheckResult, AuditFinding, AuditOptions, AuditReport } from './types.js';\n\n/**\n * Run audit checks and build a report.\n *\n * @param repoRoot - Repository root directory\n * @param options - Toggle individual checks (all enabled by default)\n * @returns Complete audit report with findings and summary\n */\nexport async function runAudit(\n repoRoot: string,\n options: AuditOptions = {}\n): Promise<AuditReport> {\n const { includeRules = true, includePatterns = true, includeLessons = true } = options;\n\n const findings: AuditFinding[] = [];\n const allCheckedFiles = new Set<string>();\n\n function collect(result: AuditCheckResult): void {\n findings.push(...result.findings);\n for (const f of result.filesChecked) {\n allCheckedFiles.add(f);\n }\n }\n\n if (includeRules) {\n collect(checkRules(repoRoot));\n }\n\n if (includePatterns) {\n collect(await checkPatterns(repoRoot));\n }\n\n if (includeLessons) {\n collect(await checkLessons(repoRoot));\n }\n\n const errors = findings.filter((f) => f.severity === 'error').length;\n const warnings = findings.filter((f) => f.severity === 'warning').length;\n const infos = findings.filter((f) => f.severity === 'info').length;\n\n return {\n findings,\n summary: { errors, warnings, infos, filesChecked: allCheckedFiles.size },\n timestamp: new Date().toISOString(),\n };\n}\n","/**\n * Audit module types and Zod schemas.\n */\n\nimport { z } from 'zod';\n\n/** Schema for a single audit finding. */\nexport const AuditFindingSchema = z.object({\n file: z.string(),\n issue: z.string(),\n severity: z.enum(['error', 'warning', 'info']),\n relatedLessonId: z.string().optional(),\n suggestedFix: z.string().optional(),\n source: z.enum(['rule', 'pattern', 'lesson']),\n});\n\n/** Schema for the audit summary. */\nexport const AuditSummarySchema = z.object({\n errors: z.number(),\n warnings: z.number(),\n infos: z.number(),\n filesChecked: z.number(),\n});\n\n/** Schema for a complete audit report. */\nexport const AuditReportSchema = z.object({\n findings: z.array(AuditFindingSchema),\n summary: AuditSummarySchema,\n timestamp: z.string(),\n});\n\nexport type AuditFinding = z.infer<typeof AuditFindingSchema>;\nexport type AuditSummary = z.infer<typeof AuditSummarySchema>;\nexport type AuditReport = z.infer<typeof AuditReportSchema>;\n\n/** Return type for individual audit check functions. */\nexport interface AuditCheckResult {\n findings: AuditFinding[];\n filesChecked: string[];\n}\n\n/** Options to toggle individual audit checks. */\nexport interface AuditOptions {\n includeRules?: boolean;\n includePatterns?: boolean;\n includeLessons?: boolean;\n}\n","/**\n * Compound Agent - Repository-scoped learning system for Claude Code\n *\n * This package helps Claude Code learn from mistakes and avoid repeating them.\n * It captures lessons during coding sessions and retrieves relevant lessons\n * when planning new work.\n *\n * ## Quick Start\n *\n * ```typescript\n * import { appendLesson, retrieveForPlan, loadSessionLessons } from 'compound-agent';\n *\n * // At session start, load high-severity lessons\n * const criticalLessons = await loadSessionLessons(repoRoot);\n *\n * // When planning, retrieve relevant lessons\n * const { lessons, message } = await retrieveForPlan(repoRoot, planText);\n *\n * // When capturing a lesson\n * await appendLesson(repoRoot, lesson);\n * ```\n *\n * ## Setup\n *\n * Run `npx ca init` in your project root to configure hooks and AGENTS.md.\n *\n * ## Resource Management\n *\n * This library manages two heavyweight resources that require cleanup:\n *\n * ### SQLite Database\n * - **Acquired:** Lazily on first database operation (search, rebuild, etc.)\n * - **Memory:** Minimal (~few KB for connection, index cached by OS)\n * - **Cleanup:** Call `closeDb()` before process exit\n *\n * ### Embedding Model\n * - **Acquired:** Lazily on first embedding call (embedText, embedTexts, searchVector)\n * - **Memory:** ~150MB RAM for the EmbeddingGemma model\n * - **Cleanup:** Call `unloadEmbedding()` before process exit\n *\n * ### Recommended Cleanup Pattern\n *\n * ```typescript\n * import { closeDb, unloadEmbedding } from 'compound-agent';\n *\n * // For CLI commands - use try/finally\n * async function main() {\n * try {\n * // ... your code that uses compound-agent\n * } finally {\n * unloadEmbedding();\n * closeDb();\n * }\n * }\n *\n * // For long-running processes - use shutdown handlers\n * process.on('SIGTERM', () => {\n * unloadEmbedding();\n * closeDb();\n * process.exit(0);\n * });\n * process.on('SIGINT', () => {\n * unloadEmbedding();\n * closeDb();\n * process.exit(0);\n * });\n * ```\n *\n * **Note:** Failing to clean up will not corrupt data, but may cause:\n * - Memory leaks in long-running processes\n * - Unclean process exits (warnings in some environments)\n *\n * @see {@link closeDb} for database cleanup\n * @see {@link unloadEmbedding} for embedding model cleanup\n * @module compound-agent\n */\n\nimport { createRequire } from 'node:module';\n\nconst _require = createRequire(import.meta.url);\nconst _pkg = _require('../package.json') as { version: string };\n\n/** Package version, read from package.json. */\nexport const VERSION: string = _pkg.version;\n\n// Storage API (JSONL source of truth + SQLite index)\nexport {\n appendLesson,\n appendMemoryItem,\n closeDb,\n DB_PATH,\n LESSONS_PATH,\n readLessons,\n readMemoryItems,\n rebuildIndex,\n searchKeyword,\n} from './memory/storage/index.js';\nexport type { ParseError, ReadLessonsOptions, ReadLessonsResult, ReadMemoryItemsResult } from './memory/storage/index.js';\n\n// Embeddings API\nexport {\n embedText,\n embedTexts,\n getEmbedding,\n isModelAvailable,\n isModelUsable,\n MODEL_FILENAME,\n MODEL_URI,\n resolveModel,\n unloadEmbedding,\n} from './memory/embeddings/index.js';\nexport type { UsabilityResult } from './memory/embeddings/index.js';\n\n// Search API (vector similarity + ranking)\nexport {\n calculateScore,\n confirmationBoost,\n cosineSimilarity,\n rankLessons,\n rankMemoryItems,\n recencyBoost,\n searchVector,\n severityBoost,\n} from './memory/search/index.js';\nexport type { RankedLesson, RankedMemoryItem, ScoredLesson, ScoredMemoryItem, SearchVectorOptions } from './memory/search/index.js';\n\n// Capture API (quality filters + trigger detection)\nexport {\n detectSelfCorrection,\n detectTestFailure,\n detectUserCorrection,\n isActionable,\n isNovel,\n isSpecific,\n shouldPropose,\n} from './memory/capture/index.js';\nexport type {\n ActionabilityResult,\n CorrectionSignal,\n DetectedCorrection,\n DetectedSelfCorrection,\n DetectedTestFailure,\n EditEntry,\n EditHistory,\n NoveltyOptions,\n NoveltyResult,\n ProposeResult,\n SpecificityResult,\n TestResult,\n} from './memory/capture/index.js';\n\n// Retrieval API (session + plan time)\nexport { formatLessonsCheck, formatMemoryCheck, loadSessionLessons, loadSessionMemory, retrieveForPlan } from './memory/retrieval/index.js';\nexport type { PlanRetrievalResult } from './memory/retrieval/index.js';\n\n// Context recovery API (for MCP server integration)\nexport { getPrimeContext } from './commands/index.js';\n\n// Audit API\nexport { runAudit, AuditFindingSchema, AuditReportSchema } from './audit/index.js';\nexport type { AuditFinding, AuditReport, AuditOptions } from './audit/index.js';\n\n// Compound API (clustering, synthesis, pattern I/O)\nexport {\n buildSimilarityMatrix,\n CCT_PATTERNS_PATH,\n CctPatternSchema,\n clusterBySimilarity,\n readCctPatterns,\n synthesizePattern,\n writeCctPatterns,\n} from './compound/index.js';\nexport type { CctPattern, ClusterResult } from './compound/index.js';\n\n// Types and schemas\nexport {\n generateId,\n LegacyLessonSchema,\n LegacyTombstoneSchema,\n LessonItemSchema,\n LessonRecordSchema,\n LessonSchema,\n LessonTypeSchema,\n MemoryItemRecordSchema,\n MemoryItemSchema,\n MemoryItemTypeSchema,\n PatternItemSchema,\n PreferenceItemSchema,\n SolutionItemSchema,\n} from './memory/types.js';\nexport type {\n Context,\n Lesson,\n LessonRecord,\n LessonType,\n MemoryItem,\n MemoryItemRecord,\n MemoryItemType,\n PatternItem,\n Preference,\n Severity,\n Solution,\n Source,\n} from './memory/types.js';\n","/**\n * Templates and constants for setup commands.\n */\n\nimport { VERSION } from '../index.js';\n\n// ============================================================================\n// Hooks Constants\n// ============================================================================\n\n/** Pre-commit hook reminder message */\nexport const PRE_COMMIT_MESSAGE = `\n╔══════════════════════════════════════════════════════════════╗\n║ LESSON CAPTURE CHECKPOINT ║\n╠══════════════════════════════════════════════════════════════╣\n║ STOP. Before this commit, take a moment to reflect: ║\n║ ║\n║ [ ] Did I learn something relevant during this session? ║\n║ [ ] Is there anything worth remembering for next time? ║\n║ ║\n║ If so, consider capturing a lesson: ║\n║ npx ca learn \"<insight>\" --trigger \"<what happened>\" ║\n╚══════════════════════════════════════════════════════════════╝`;\n\n/** Pre-commit hook shell script template */\nexport const PRE_COMMIT_HOOK_TEMPLATE = `#!/bin/sh\n# Compound Agent pre-commit hook\n# Reminds Claude to consider capturing lessons before commits\n\nnpx ca hooks run pre-commit\n`;\n\n/** Marker comment to identify our hook */\nexport const HOOK_MARKER = '# Compound Agent pre-commit hook';\n\n/** Block to insert into existing hooks */\nexport const COMPOUND_AGENT_HOOK_BLOCK = `\n# Compound Agent pre-commit hook (appended)\nnpx ca hooks run pre-commit\n`;\n\n// ============================================================================\n// Claude Code Hooks Configuration\n// ============================================================================\n\n/** Markers to identify our hook in Claude Code settings (current and legacy) */\nexport const CLAUDE_HOOK_MARKERS = [\n 'ca prime',\n 'ca load-session',\n 'compound-agent load-session',\n 'ca hooks run user-prompt',\n 'ca hooks run post-tool-failure',\n 'ca hooks run post-tool-success',\n];\n\n/** Claude Code SessionStart hook configuration (v0.2.4: uses prime for trust language) */\nexport const CLAUDE_HOOK_CONFIG = {\n matcher: '',\n hooks: [\n {\n type: 'command',\n command: 'npx ca prime 2>/dev/null || true',\n },\n ],\n};\n\n/** Claude Code PreCompact hook configuration */\nexport const CLAUDE_PRECOMPACT_HOOK_CONFIG = {\n matcher: '',\n hooks: [\n {\n type: 'command',\n command: 'npx ca prime 2>/dev/null || true',\n },\n ],\n};\n\n/** Claude Code UserPromptSubmit hook configuration */\nexport const CLAUDE_USER_PROMPT_HOOK_CONFIG = {\n matcher: '',\n hooks: [\n {\n type: 'command',\n command: 'npx ca hooks run user-prompt 2>/dev/null || true',\n },\n ],\n};\n\n/** Claude Code PostToolUseFailure hook configuration */\nexport const CLAUDE_POST_TOOL_FAILURE_HOOK_CONFIG = {\n matcher: 'Bash|Edit|Write',\n hooks: [\n {\n type: 'command',\n command: 'npx ca hooks run post-tool-failure 2>/dev/null || true',\n },\n ],\n};\n\n/** Claude Code PostToolUse hook configuration (for success reset) */\nexport const CLAUDE_POST_TOOL_SUCCESS_HOOK_CONFIG = {\n matcher: 'Bash|Edit|Write',\n hooks: [\n {\n type: 'command',\n command: 'npx ca hooks run post-tool-success 2>/dev/null || true',\n },\n ],\n};\n\n// Note: PreCommit is NOT a valid Claude Code hook type.\n// The remind-capture functionality is handled by git pre-commit hooks instead.\n// See installPreCommitHook() in hooks.ts for git hook installation.\n\n/** MCP server configuration for Claude Code settings */\nexport const MCP_SERVER_CONFIG = {\n 'compound-agent': {\n command: 'npx',\n args: ['compound-agent-mcp'],\n },\n};\n\n// ============================================================================\n// Init Command Constants\n// ============================================================================\n\n/** Section header to check for idempotency */\nexport const COMPOUND_AGENT_SECTION_HEADER = '## Compound Agent Integration';\n\n// ============================================================================\n// CLAUDE.md Reference Constants (lfy)\n// ============================================================================\n\n/** Start marker for CLAUDE.md reference section */\nexport const CLAUDE_REF_START_MARKER = '<!-- compound-agent:claude-ref:start -->';\n\n/** End marker for CLAUDE.md reference section */\nexport const CLAUDE_REF_END_MARKER = '<!-- compound-agent:claude-ref:end -->';\n\n/** Reference content to add to CLAUDE.md */\nexport const CLAUDE_MD_REFERENCE = `\n${CLAUDE_REF_START_MARKER}\n## Compound Agent\nSee AGENTS.md for lesson capture workflow.\n${CLAUDE_REF_END_MARKER}\n`;\n\n// ============================================================================\n// AGENTS.md Section Markers (e2r)\n// ============================================================================\n\n/** Start marker for AGENTS.md Learning Agent section */\nexport const AGENTS_SECTION_START_MARKER = '<!-- compound-agent:start -->';\n\n/** End marker for AGENTS.md Learning Agent section */\nexport const AGENTS_SECTION_END_MARKER = '<!-- compound-agent:end -->';\n\n/** Template content for AGENTS.md */\nexport const AGENTS_MD_TEMPLATE = `\n${AGENTS_SECTION_START_MARKER}\n## Compound Agent Integration\n\nThis project uses compound-agent for session memory via **MCP tools** (preferred).\n\n### MCP Tools (ALWAYS USE THESE)\n\n**You MUST use MCP tools, NOT CLI commands:**\n\n| Tool | Purpose |\n|------|---------|\n| \\`memory_search\\` | Search lessons - use BEFORE architectural decisions |\n| \\`memory_capture\\` | Capture lessons - use AFTER corrections or discoveries |\n\n### Mandatory Recall\n\nYou MUST call \\`memory_search\\` BEFORE:\n- Architectural decisions or complex planning\n- Patterns you've implemented before in this repo\n- After user corrections (\"actually...\", \"wrong\", \"use X instead\")\n\n**NEVER skip memory_search for complex decisions.** Past mistakes will repeat.\n\n### Capture Protocol\n\nCall \\`memory_capture\\` AFTER:\n- User corrects you\n- Test fail → fix → pass cycles\n- You discover project-specific knowledge\n\n**Workflow**: Search BEFORE deciding, capture AFTER learning.\n\n### Quality Gate\n\nBefore capturing, verify the lesson is:\n- **Novel** - Not already stored\n- **Specific** - Clear guidance\n- **Actionable** (preferred) - Obvious what to do\n\n### Never Edit JSONL Directly\n\n**WARNING: NEVER edit .claude/lessons/index.jsonl directly.**\n\nThe JSONL file requires proper ID generation, schema validation, and SQLite sync.\nUse \\`memory_capture\\` MCP tool or CLI (\\`npx ca learn\\`) - never manual edits.\n\n### CLI (fallback only)\n\nCLI commands are for manual/terminal use when MCP is unavailable:\n\\`npx ca search \"query\"\\`, \\`npx ca learn \"insight\"\\`, \\`npx ca list\\`\n\nSee [documentation](https://github.com/Nathandela/compound_agent) for more details.\n${AGENTS_SECTION_END_MARKER}\n`;\n\n// ============================================================================\n// Slash Commands (8lp, 6nw)\n// ============================================================================\n\n/** Slash command templates for .claude/commands/ */\nexport const SLASH_COMMANDS: Record<string, string> = {\n 'learn.md': `Capture a lesson from this session.\n\nUsage: /learn <insight>\n\nExamples:\n- /learn \"Always use Polars for large CSV files\"\n- /learn \"API requires X-Request-ID header\"\n\n\\`\\`\\`bash\nnpx ca learn \"$ARGUMENTS\"\n\\`\\`\\`\n`,\n 'search.md': `Search lessons for relevant context.\n\nUsage: /search <query>\n\nExamples:\n- /search \"API authentication\"\n- /search \"data processing patterns\"\n\n\\`\\`\\`bash\nnpx ca search \"$ARGUMENTS\"\n\\`\\`\\`\n\nNote: You can also use the \\`memory_search\\` MCP tool directly.\n`,\n 'list.md': `Show all stored lessons.\n\n\\`\\`\\`bash\nnpx ca list\n\\`\\`\\`\n`,\n 'prime.md': `Load compound-agent workflow context after compaction or context loss.\n\n\\`\\`\\`bash\nnpx ca prime\n\\`\\`\\`\n`,\n 'show.md': `Show details of a specific lesson.\n\nUsage: /show <lesson-id>\n\n\\`\\`\\`bash\nnpx ca show \"$ARGUMENTS\"\n\\`\\`\\`\n`,\n 'wrong.md': `Mark a lesson as incorrect or invalid.\n\nUsage: /wrong <lesson-id>\n\n\\`\\`\\`bash\nnpx ca wrong \"$ARGUMENTS\"\n\\`\\`\\`\n`,\n 'stats.md': `Show compound-agent database statistics and health.\n\n\\`\\`\\`bash\nnpx ca stats\n\\`\\`\\`\n`,\n};\n\n// ============================================================================\n// Plugin Configuration (ctv)\n// ============================================================================\n\n/** Plugin manifest for .claude/plugin.json */\nexport const PLUGIN_MANIFEST = {\n name: 'compound-agent',\n description: 'Session memory for Claude Code - capture and retrieve lessons',\n version: VERSION,\n author: {\n name: 'Nathan Delacrétaz',\n url: 'https://github.com/Nathandela',\n },\n repository: 'https://github.com/Nathandela/compound_agent',\n license: 'MIT',\n hooks: {\n SessionStart: [\n {\n matcher: '',\n hooks: [\n { type: 'command', command: 'npx ca prime 2>/dev/null || true' },\n ],\n },\n ],\n PreCompact: [\n {\n matcher: '',\n hooks: [{ type: 'command', command: 'npx ca prime 2>/dev/null || true' }],\n },\n ],\n UserPromptSubmit: [\n {\n matcher: '',\n hooks: [{ type: 'command', command: 'npx ca hooks run user-prompt 2>/dev/null || true' }],\n },\n ],\n PostToolUseFailure: [\n {\n matcher: 'Bash|Edit|Write',\n hooks: [{ type: 'command', command: 'npx ca hooks run post-tool-failure 2>/dev/null || true' }],\n },\n ],\n PostToolUse: [\n {\n matcher: 'Bash|Edit|Write',\n hooks: [{ type: 'command', command: 'npx ca hooks run post-tool-success 2>/dev/null || true' }],\n },\n ],\n // Note: PreCommit is handled by git hooks, not Claude Code hooks\n },\n};\n","/**\n * Claude Code settings helpers.\n *\n * Functions for reading, writing, and manipulating Claude Code settings.json.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport {\n AGENTS_SECTION_END_MARKER,\n AGENTS_SECTION_START_MARKER,\n CLAUDE_HOOK_CONFIG,\n CLAUDE_HOOK_MARKERS,\n CLAUDE_POST_TOOL_FAILURE_HOOK_CONFIG,\n CLAUDE_POST_TOOL_SUCCESS_HOOK_CONFIG,\n CLAUDE_PRECOMPACT_HOOK_CONFIG,\n CLAUDE_REF_END_MARKER,\n CLAUDE_REF_START_MARKER,\n CLAUDE_USER_PROMPT_HOOK_CONFIG,\n MCP_SERVER_CONFIG,\n} from './templates.js';\nimport type { ClaudeHooksResult } from './types.js';\n\n/**\n * Get the path to Claude Code settings file.\n *\n * @param global - If true, return global path (~/.claude/settings.json).\n * If false (default), return project-local path (.claude/settings.json).\n */\nexport function getClaudeSettingsPath(global: boolean): string {\n if (global) {\n return join(homedir(), '.claude', 'settings.json');\n }\n const repoRoot = getRepoRoot();\n return join(repoRoot, '.claude', 'settings.json');\n}\n\n/**\n * Read and parse Claude Code settings.\n */\nexport async function readClaudeSettings(settingsPath: string): Promise<Record<string, unknown>> {\n if (!existsSync(settingsPath)) {\n return {};\n }\n const content = await readFile(settingsPath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Check if our hook is already installed.\n * Checks for both current (ca) and legacy (compound-agent) markers in any hook type.\n */\nexport function hasClaudeHook(settings: Record<string, unknown>): boolean {\n const hooks = settings.hooks as Record<string, unknown[]> | undefined;\n if (!hooks) return false;\n\n // Check all hook types we manage\n const hookTypes = ['SessionStart', 'PreCompact', 'UserPromptSubmit', 'PostToolUseFailure', 'PostToolUse'];\n\n return hookTypes.some((hookType) => {\n const hookArray = hooks[hookType];\n if (!hookArray) return false;\n\n return hookArray.some((entry) => {\n const hookEntry = entry as { hooks?: Array<{ command?: string }> };\n return hookEntry.hooks?.some((h) =>\n CLAUDE_HOOK_MARKERS.some((marker) => h.command?.includes(marker))\n );\n });\n });\n}\n\n/**\n * Add our hook to SessionStart array.\n */\nexport function addCompoundAgentHook(settings: Record<string, unknown>): void {\n if (!settings.hooks) {\n settings.hooks = {};\n }\n const hooks = settings.hooks as Record<string, unknown[]>;\n if (!hooks.SessionStart) {\n hooks.SessionStart = [];\n }\n hooks.SessionStart.push(CLAUDE_HOOK_CONFIG);\n}\n\n/**\n * Add all hooks: SessionStart, PreCompact, UserPromptSubmit, PostToolUseFailure, PostToolUse.\n * Note: PreCommit is handled by git hooks, not Claude Code hooks.\n */\nexport function addAllCompoundAgentHooks(settings: Record<string, unknown>): void {\n if (!settings.hooks) {\n settings.hooks = {};\n }\n const hooks = settings.hooks as Record<string, unknown[]>;\n\n // SessionStart - prime context\n if (!hooks.SessionStart) {\n hooks.SessionStart = [];\n }\n if (!hasHookType(hooks.SessionStart, 'ca prime')) {\n hooks.SessionStart.push(CLAUDE_HOOK_CONFIG);\n }\n\n // PreCompact - re-inject prime before compaction\n if (!hooks.PreCompact) {\n hooks.PreCompact = [];\n }\n if (!hasHookType(hooks.PreCompact, 'ca prime')) {\n hooks.PreCompact.push(CLAUDE_PRECOMPACT_HOOK_CONFIG);\n }\n\n // UserPromptSubmit - gentle lesson tool reminders\n if (!hooks.UserPromptSubmit) {\n hooks.UserPromptSubmit = [];\n }\n if (!hasHookType(hooks.UserPromptSubmit, 'ca hooks run user-prompt')) {\n hooks.UserPromptSubmit.push(CLAUDE_USER_PROMPT_HOOK_CONFIG);\n }\n\n // PostToolUseFailure - smart failure detection\n if (!hooks.PostToolUseFailure) {\n hooks.PostToolUseFailure = [];\n }\n if (!hasHookType(hooks.PostToolUseFailure, 'ca hooks run post-tool-failure')) {\n hooks.PostToolUseFailure.push(CLAUDE_POST_TOOL_FAILURE_HOOK_CONFIG);\n }\n\n // PostToolUse - reset failure state on success\n if (!hooks.PostToolUse) {\n hooks.PostToolUse = [];\n }\n if (!hasHookType(hooks.PostToolUse, 'ca hooks run post-tool-success')) {\n hooks.PostToolUse.push(CLAUDE_POST_TOOL_SUCCESS_HOOK_CONFIG);\n }\n\n // Note: remind-capture functionality is handled by git pre-commit hooks\n // (see installPreCommitHook in hooks.ts), not Claude Code hooks\n}\n\n/**\n * Check if a hook type already has a command containing the marker.\n */\nfunction hasHookType(hookArray: unknown[], marker: string): boolean {\n return hookArray.some((entry) => {\n const hookEntry = entry as { hooks?: Array<{ command?: string }> };\n return hookEntry.hooks?.some((h) => h.command?.includes(marker));\n });\n}\n\n// ============================================================================\n// MCP Configuration (.mcp.json - project scope)\n// ============================================================================\n\n/**\n * Get the path to .mcp.json (project-scope MCP config).\n * This is the correct location for MCP servers per Claude Code docs.\n */\nexport function getMcpJsonPath(repoRoot?: string): string {\n const root = repoRoot ?? getRepoRoot();\n return join(root, '.mcp.json');\n}\n\n/**\n * Read and parse .mcp.json.\n */\nexport async function readMcpJson(mcpPath: string): Promise<Record<string, unknown>> {\n if (!existsSync(mcpPath)) {\n return {};\n }\n const content = await readFile(mcpPath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Write .mcp.json atomically.\n */\nexport async function writeMcpJson(mcpPath: string, config: Record<string, unknown>): Promise<void> {\n const tempPath = mcpPath + '.tmp';\n await writeFile(tempPath, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n await rename(tempPath, mcpPath);\n}\n\n/**\n * Add MCP server configuration to .mcp.json.\n * Returns true if added, false if already exists.\n */\nexport async function addMcpServerToMcpJson(repoRoot?: string): Promise<boolean> {\n const mcpPath = getMcpJsonPath(repoRoot);\n const config = await readMcpJson(mcpPath);\n\n if (!config.mcpServers) {\n config.mcpServers = {};\n }\n const mcpServers = config.mcpServers as Record<string, unknown>;\n\n if (mcpServers['compound-agent']) {\n return false; // Already configured\n }\n\n Object.assign(mcpServers, MCP_SERVER_CONFIG);\n await writeMcpJson(mcpPath, config);\n return true;\n}\n\n/**\n * Check if MCP server is configured in .mcp.json.\n */\nexport async function hasMcpServerInMcpJson(repoRoot?: string): Promise<boolean> {\n const mcpPath = getMcpJsonPath(repoRoot);\n const config = await readMcpJson(mcpPath);\n const mcpServers = config.mcpServers as Record<string, unknown> | undefined;\n return !!mcpServers?.['compound-agent'];\n}\n\n/**\n * Remove MCP server from .mcp.json.\n */\nexport async function removeMcpServerFromMcpJson(repoRoot?: string): Promise<boolean> {\n const mcpPath = getMcpJsonPath(repoRoot);\n const config = await readMcpJson(mcpPath);\n const mcpServers = config.mcpServers as Record<string, unknown> | undefined;\n\n if (!mcpServers?.['compound-agent']) {\n return false;\n }\n\n delete mcpServers['compound-agent'];\n await writeMcpJson(mcpPath, config);\n return true;\n}\n\n// Legacy functions for backwards compatibility (settings.json)\n// These are deprecated - use the McpJson functions above\n\n/**\n * @deprecated Use addMcpServerToMcpJson instead\n */\nexport function addMcpServer(settings: Record<string, unknown>): boolean {\n if (!settings.mcpServers) {\n settings.mcpServers = {};\n }\n const mcpServers = settings.mcpServers as Record<string, unknown>;\n\n if (mcpServers['compound-agent']) {\n return false; // Already configured\n }\n\n Object.assign(mcpServers, MCP_SERVER_CONFIG);\n return true;\n}\n\n/**\n * @deprecated Use hasMcpServerInMcpJson instead\n */\nexport function hasMcpServer(settings: Record<string, unknown>): boolean {\n const mcpServers = settings.mcpServers as Record<string, unknown> | undefined;\n return !!mcpServers?.['compound-agent'];\n}\n\n/**\n * @deprecated Use removeMcpServerFromMcpJson instead\n */\nexport function removeMcpServer(settings: Record<string, unknown>): boolean {\n const mcpServers = settings.mcpServers as Record<string, unknown> | undefined;\n if (!mcpServers?.['compound-agent']) {\n return false;\n }\n delete mcpServers['compound-agent'];\n return true;\n}\n\n/**\n * Remove our hooks from all hook arrays.\n * Removes both current (ca) and legacy (compound-agent) hooks from all hook types.\n */\nexport function removeCompoundAgentHook(settings: Record<string, unknown>): boolean {\n const hooks = settings.hooks as Record<string, unknown[]> | undefined;\n if (!hooks) return false;\n\n let anyRemoved = false;\n\n // Hook types we manage\n const hookTypes = ['SessionStart', 'PreCompact', 'UserPromptSubmit', 'PostToolUseFailure', 'PostToolUse'];\n\n for (const hookType of hookTypes) {\n if (!hooks[hookType]) continue;\n\n const originalLength = hooks[hookType].length;\n hooks[hookType] = hooks[hookType].filter((entry) => {\n const hookEntry = entry as { hooks?: Array<{ command?: string }> };\n return !hookEntry.hooks?.some((h) =>\n CLAUDE_HOOK_MARKERS.some((marker) => h.command?.includes(marker))\n );\n });\n\n if (hooks[hookType].length < originalLength) {\n anyRemoved = true;\n }\n }\n\n return anyRemoved;\n}\n\n/**\n * Write Claude Code settings atomically.\n */\nexport async function writeClaudeSettings(settingsPath: string, settings: Record<string, unknown>): Promise<void> {\n const dir = dirname(settingsPath);\n await mkdir(dir, { recursive: true });\n\n // Write to temp file, then rename (atomic)\n const tempPath = settingsPath + '.tmp';\n await writeFile(tempPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n await rename(tempPath, settingsPath);\n}\n\n/**\n * Install Claude hooks for init command.\n * Handles errors gracefully - returns error info instead of throwing.\n * @param repoRoot - Repository root path\n * @returns Result indicating success/failure\n */\nexport async function installClaudeHooksForInit(repoRoot: string): Promise<ClaudeHooksResult> {\n const settingsPath = join(repoRoot, '.claude', 'settings.json');\n\n let settings: Record<string, unknown>;\n try {\n settings = await readClaudeSettings(settingsPath);\n } catch {\n return { installed: false, action: 'error', error: 'Failed to parse settings.json' };\n }\n\n if (hasClaudeHook(settings)) {\n return { installed: true, action: 'already_installed' };\n }\n\n try {\n addCompoundAgentHook(settings);\n await writeClaudeSettings(settingsPath, settings);\n return { installed: true, action: 'installed' };\n } catch (err) {\n return { installed: false, action: 'error', error: String(err) };\n }\n}\n\n// ============================================================================\n// AGENTS.md and CLAUDE.md Cleanup (e2r)\n// ============================================================================\n\n/**\n * Remove Learning Agent section from AGENTS.md.\n * Uses markers to find and remove the section.\n *\n * @param repoRoot - Repository root path\n * @returns true if section was removed, false if not found\n */\nexport async function removeAgentsSection(repoRoot: string): Promise<boolean> {\n const agentsPath = join(repoRoot, 'AGENTS.md');\n\n if (!existsSync(agentsPath)) {\n return false;\n }\n\n const content = await readFile(agentsPath, 'utf-8');\n const startIdx = content.indexOf(AGENTS_SECTION_START_MARKER);\n const endIdx = content.indexOf(AGENTS_SECTION_END_MARKER);\n\n if (startIdx === -1 || endIdx === -1) {\n return false;\n }\n\n // Remove from start marker to end marker (inclusive)\n const before = content.slice(0, startIdx);\n const after = content.slice(endIdx + AGENTS_SECTION_END_MARKER.length);\n\n // Clean up: remove trailing newlines from before, keep single newline separation\n const newContent = (before.trimEnd() + after).trim();\n\n // Only write if file would not be empty\n if (newContent.length > 0) {\n await writeFile(agentsPath, newContent + '\\n', 'utf-8');\n } else {\n // File would be empty - could optionally delete it\n await writeFile(agentsPath, '', 'utf-8');\n }\n\n return true;\n}\n\n/**\n * Remove Learning Agent reference from CLAUDE.md.\n * Uses markers to find and remove the reference section.\n *\n * @param repoRoot - Repository root path\n * @returns true if reference was removed, false if not found\n */\nexport async function removeClaudeMdReference(repoRoot: string): Promise<boolean> {\n const claudeMdPath = join(repoRoot, '.claude', 'CLAUDE.md');\n\n if (!existsSync(claudeMdPath)) {\n return false;\n }\n\n const content = await readFile(claudeMdPath, 'utf-8');\n const startIdx = content.indexOf(CLAUDE_REF_START_MARKER);\n const endIdx = content.indexOf(CLAUDE_REF_END_MARKER);\n\n if (startIdx === -1 || endIdx === -1) {\n return false;\n }\n\n // Remove from start marker to end marker (inclusive)\n const before = content.slice(0, startIdx);\n const after = content.slice(endIdx + CLAUDE_REF_END_MARKER.length);\n\n // Clean up: remove trailing newlines from before, keep single newline separation\n const newContent = (before.trimEnd() + after).trim();\n\n // Only write if file would not be empty\n if (newContent.length > 0) {\n await writeFile(claudeMdPath, newContent + '\\n', 'utf-8');\n } else {\n await writeFile(claudeMdPath, '', 'utf-8');\n }\n\n return true;\n}\n","/**\n * Phase 11 agent templates: intelligent compounding and audit.\n *\n * These templates extend the core agent set with agents for:\n * - Pattern synthesis from accumulated lessons\n * - Codebase auditing against known mistakes\n * - CCT injection into the TDD pipeline\n * - Drift detection against constraints\n * - Documentation freshness checking\n */\n\nexport const PHASE11_AGENT_TEMPLATES: Record<string, string> = {\n 'compounding.md': `---\nname: Compounding Agent\ndescription: Clusters similar lessons and synthesizes testable patterns\nmodel: sonnet\n---\n\n# Compounding Agent\n\n## Role\nCluster similar lessons from memory and synthesize them into testable CCT (Compound Corrective Test) patterns. Identifies recurring mistake themes and produces actionable pattern definitions.\n\n## Instructions\n1. Read existing lessons from \\`.claude/lessons/index.jsonl\\`\n2. Use \\`memory_search\\` with broad queries to find related items\n3. Cluster lessons by similarity (same root cause, same domain, same mistake type)\n4. For each cluster with 2+ items, synthesize a CCT pattern:\n - Pattern name and trigger condition\n - What tests should exist to prevent recurrence\n - Confidence level based on cluster size\n5. Write patterns to \\`.claude/lessons/cct-patterns.jsonl\\`\n6. Skip singleton lessons (not enough signal to form a pattern)\n\n## Tools Available\n- Read, Bash, Grep, Glob for file access\n- \\`memory_search\\` for finding related lessons\n\n## Output Format\n- **Patterns written**: Count and file path\n- **Clusters found**: Summary of each cluster\n- **Singletons skipped**: Count of unclustered lessons\n`,\n\n 'audit.md': `---\nname: Audit Agent\ndescription: Deep semantic analysis of codebase against rules, patterns, and lessons\nmodel: sonnet\n---\n\n# Audit Agent\n\n## Role\nPerform deep semantic analysis of the codebase against project rules, established patterns, and stored lessons. Identifies violations, drift, and improvement opportunities.\n\n## Instructions\n1. Run \\`npx ca audit --json\\` to get structured audit findings\n2. Interpret each finding's severity and context\n3. Cross-reference findings with \\`memory_search\\` for known exceptions or decisions\n4. For each finding, suggest a specific fix or explain why it can be ignored\n5. Group findings by category (security, architecture, testing, conventions)\n6. Prioritize by impact: data loss risks first, then correctness, then style\n\n## Tools Available\n- Read, Bash, Grep, Glob for codebase analysis\n- \\`memory_search\\` for historical context on findings\n\n## Output Format\n- **CRITICAL**: Must fix immediately (security, data loss)\n- **WARNING**: Should fix soon (correctness, architecture drift)\n- **INFO**: Improvement suggestion (conventions, style)\n`,\n\n 'doc-gardener.md': `---\nname: Doc Gardener\ndescription: Audits project documentation for freshness, accuracy, and completeness\nmodel: sonnet\n---\n\n# Doc Gardener\n\n## Role\nAudit project documentation for freshness, accuracy, and completeness. Identify stale docs, missing references, and broken links. Ensure docs/INDEX.md accurately reflects the documentation tree.\n\n## Instructions\n1. Read \\`docs/INDEX.md\\` to get the documentation map\n2. Use Glob to find all \\`.md\\` files under \\`docs/\\`\n3. Cross-reference: every doc in INDEX should exist on disk, every doc on disk should be in INDEX\n4. For each doc, check:\n - Does it reference files/functions that still exist? (use Grep)\n - Does it describe the current behavior? (compare with source)\n - Is the last-modified date reasonable?\n5. Flag issues and create beads issues for stale docs: \\`bd create --title=\"Update stale doc: X\" --type=task\\`\n\n## Tools Available\n- Glob, Grep, Read for documentation analysis\n- Bash for \\`bd create\\` to file issues\n\n## Output Format\nPer document:\n- **STALE**: References outdated code or behavior\n- **MISSING**: Referenced in INDEX but file not found\n- **SUPERSEDED**: Content duplicated or replaced elsewhere\n- **OK**: Current and accurate\n`,\n\n 'cct-subagent.md': `---\nname: CCT Subagent\ndescription: Injects mistake-derived test requirements into the TDD pipeline\nmodel: sonnet\n---\n\n# CCT Subagent\n\n## Role\nInject mistake-derived test requirements into the TDD pipeline. Runs between invariant-designer and test-first-enforcer to ensure past mistakes generate preventive tests.\n\n## Pipeline Position\ninvariant-designer -> **CCT Subagent** -> test-first-enforcer\n\n## Instructions\n1. Read CCT patterns from \\`.claude/lessons/cct-patterns.jsonl\\`\n2. Read the current task description and changed files\n3. Match patterns against the current task:\n - Compare task domain, file paths, and error categories\n - Check if the pattern's trigger condition applies\n4. For each matching pattern, output a test requirement:\n - What the test should verify\n - Why it matters (link to historical mistakes)\n - Priority (REQUIRED vs SUGGESTED)\n5. Pass requirements to test-first-enforcer for inclusion\n\n## Tools Available\n- Read, Grep for pattern and task analysis\n- \\`memory_search\\` for additional context\n\n## Output Format\nPer match:\n- **REQUIRED TEST**: Must be written (high-confidence pattern match)\n- **SUGGESTED TEST**: Should consider (partial match)\n- **NO MATCH**: Pattern does not apply to current task\n`,\n\n 'drift-detector.md': `---\nname: Drift Detector\ndescription: Checks implementation for drift from established constraints\nmodel: sonnet\n---\n\n# Drift Detector\n\n## Role\nDetect drift between implementation and established constraints (invariants, ADRs, architectural decisions). Runs between module-boundary-reviewer and implementation-reviewer as a final consistency check.\n\n## Pipeline Position\nmodule-boundary-reviewer -> **Drift Detector** -> implementation-reviewer\n\n## Instructions\n1. Run \\`npx ca audit --json\\` for automated constraint checking\n2. Read invariants from \\`docs/invariants/\\` if present\n3. Read relevant ADRs from \\`docs/adr/\\` if present\n4. Compare the current implementation against each constraint:\n - Are module boundaries respected?\n - Do data flows match documented architecture?\n - Are naming conventions consistent?\n5. Use \\`memory_search\\` for past architectural decisions that may apply\n6. Report any deviation, even if the implementation \"works\"\n\n## Tools Available\n- Bash for running \\`ca audit\\`\n- Read, Grep for constraint and code analysis\n- \\`memory_search\\` for historical decisions\n\n## Output Format\n- **DRIFT**: Implementation violates a documented constraint\n- **RISK**: Implementation is borderline; may drift further\n- **CLEAR**: Implementation aligns with all constraints\n`,\n};\n","/**\n * Review agent templates for the /compound:review phase.\n *\n * 5 specialized reviewers + 2 research agents that run during\n * planning and review phases.\n */\n\nexport const REVIEW_AGENT_TEMPLATES: Record<string, string> = {\n 'repo-analyst.md': `---\nname: Repo Analyst\ndescription: Analyzes repository structure, conventions, and patterns\nmodel: sonnet\n---\n\n# Repo Analyst\n\n## Role\nAnalyze the repository to understand its structure, coding conventions, tech stack, and established patterns. Provides context for planning and decision-making.\n\n## When to Use\n- Before planning new features or refactors\n- When you need to understand how the codebase is organized\n- When identifying conventions to follow\n\n## Instructions\n1. Read the project root for config files (package.json, tsconfig, etc.)\n2. Map the directory structure (src/, tests/, docs/)\n3. Identify the tech stack and dependencies\n4. Note coding conventions (naming, file organization, patterns)\n5. Check for existing documentation (README, CONTRIBUTING, CLAUDE.md)\n6. Summarize findings concisely\n\n## Tools Available\n- Glob, Grep, Read for codebase exploration\n- Bash for running build/test commands to understand the setup\n\n## Output Format\nReturn a structured summary:\n- **Stack**: Language, framework, key dependencies\n- **Structure**: Directory layout and module organization\n- **Conventions**: Naming, patterns, style\n- **Entry points**: Main files, CLI, API surface\n`,\n\n 'memory-analyst.md': `---\nname: Memory Analyst\ndescription: Searches and retrieves relevant memory items for context\nmodel: sonnet\n---\n\n# Memory Analyst\n\n## Role\nSearch compound-agent memory to find relevant lessons, patterns, and decisions from past sessions. Injects historical knowledge into the current workflow.\n\n## When to Use\n- Before architectural decisions\n- When encountering a problem that may have been solved before\n- When a user correction suggests stored knowledge exists\n- At session start to load relevant context\n\n## Instructions\n1. Identify the key topics from the current task\n2. Use \\`memory_search\\` MCP tool with relevant queries\n3. Search with multiple query variations for coverage\n4. Filter results by relevance and recency\n5. Summarize applicable lessons concisely\n\n## Tools Available\n- \\`memory_search\\` MCP tool (primary)\n- \\`npx ca search\\` CLI (fallback)\n\n## Output Format\nReturn a list of relevant memory items:\n- **Item ID**: For reference\n- **Summary**: What was learned\n- **Applicability**: How it relates to the current task\n`,\n\n 'security-reviewer.md': `---\nname: Security Reviewer\ndescription: Reviews code for security vulnerabilities\nmodel: sonnet\n---\n\n# Security Reviewer\n\n## Role\nReview code changes for security vulnerabilities including OWASP top 10, injection attacks, authentication issues, and data exposure risks.\n\n## When to Use\n- Before merging code that handles user input\n- When implementing authentication or authorization\n- When working with external APIs or databases\n- For any code that processes untrusted data\n\n## Instructions\n1. Read the changed files completely\n2. Check for injection vulnerabilities (SQL, command, XSS)\n3. Verify input validation and sanitization\n4. Review authentication and authorization logic\n5. Check for hardcoded secrets or credentials\n6. Verify error messages do not leak sensitive info\n7. Check dependency versions for known CVEs\n\n## Collaboration\n- Share cross-cutting findings via direct message: security issues impacting architecture go to architecture-reviewer; secrets in test fixtures go to test-coverage-reviewer.\n\n## Tools Available\n- Read, Grep for code analysis\n- Bash for running security linters if available\n\n## Output Format\nReturn findings as:\n- **CRITICAL**: Must fix before merge\n- **WARNING**: Should fix, potential risk\n- **INFO**: Best practice suggestion\n`,\n\n 'architecture-reviewer.md': `---\nname: Architecture Reviewer\ndescription: Reviews code for architectural compliance and design integrity\nmodel: sonnet\n---\n\n# Architecture Reviewer\n\n## Role\nReview code for architectural consistency, pattern compliance, module boundary integrity, and adherence to established project conventions.\n\n## When to Use\n- When adding new modules or significant features\n- When refactoring existing architecture\n- When changes cross module boundaries\n\n## Instructions\n1. Read CLAUDE.md and project docs for established patterns\n2. Review the changed code against those patterns\n3. Check module boundaries are respected (no circular deps)\n4. Verify public API surface is minimal\n5. Ensure new code follows existing conventions\n6. Check that dependencies flow in the correct direction\n\n## Collaboration\n- Share cross-cutting findings via direct message: architecture issues with performance implications go to performance-reviewer; structural violations creating security risks go to security-reviewer.\n\n## Tools Available\n- Read, Grep, Glob for codebase analysis\n- \\`memory_search\\` for past architectural decisions\n\n## Output Format\n- **VIOLATION**: Breaks established architecture\n- **DRIFT**: Inconsistent with conventions but functional\n- **SUGGESTION**: Improvement opportunity\n`,\n\n 'performance-reviewer.md': `---\nname: Performance Reviewer\ndescription: Reviews code for performance issues and resource usage\nmodel: sonnet\n---\n\n# Performance Reviewer\n\n## Role\nReview code for performance bottlenecks, algorithmic complexity issues, unnecessary resource consumption, and scalability concerns.\n\n## When to Use\n- When implementing data processing or search logic\n- When working with I/O-heavy operations\n- When changes affect hot paths or startup time\n\n## Instructions\n1. Read the changed code and identify hot paths\n2. Check algorithmic complexity (avoid O(n^2) where O(n) works)\n3. Look for unnecessary allocations or copies\n4. Verify I/O operations are batched where possible\n5. Check for missing indexes on database queries\n6. Verify resources are properly closed/released\n\n## Collaboration\n- Share cross-cutting findings via direct message: performance issues needing test coverage go to test-coverage-reviewer; performance fixes requiring architectural changes go to architecture-reviewer.\n\n## Tools Available\n- Read, Grep for code analysis\n- Bash for running benchmarks if available\n\n## Output Format\n- **BOTTLENECK**: Measurable performance issue\n- **CONCERN**: Potential issue at scale\n- **OK**: No issues found\n`,\n\n 'test-coverage-reviewer.md': `---\nname: Test Coverage Reviewer\ndescription: Reviews test quality, assertions, and edge case coverage\nmodel: sonnet\n---\n\n# Test Coverage Reviewer\n\n## Role\nReview tests for meaningful assertions, edge case coverage, and absence of cargo-cult patterns. Ensures tests actually verify behavior, not just run without errors.\n\n## When to Use\n- After writing or modifying tests\n- During code review\n- When test suite passes but confidence is low\n\n## Instructions\n1. Read each test file completely\n2. Verify every test has meaningful assertions (not just \\`expect(true)\\`)\n3. Check that tests would fail if the implementation is wrong\n4. Look for missing edge cases (empty input, nulls, boundaries)\n5. Verify no mocked business logic (vi.mock on the thing being tested)\n6. Check test names describe expected behavior\n7. Ensure property-based tests exist for pure functions\n\n## Collaboration\n- Share cross-cutting findings via direct message: cargo-cult tests hiding security issues go to security-reviewer; unnecessary test complexity goes to simplicity-reviewer.\n\n## Tools Available\n- Read, Grep for test analysis\n- Bash for running tests with coverage\n\n## Output Format\n- **CARGO-CULT**: Test passes regardless of implementation\n- **GAP**: Missing edge case or scenario\n- **WEAK**: Assertion exists but is insufficient\n- **GOOD**: Test is meaningful and complete\n`,\n\n 'simplicity-reviewer.md': `---\nname: Simplicity Reviewer\ndescription: Reviews code for unnecessary complexity and over-engineering\nmodel: sonnet\n---\n\n# Simplicity Reviewer\n\n## Role\nReview code for unnecessary complexity, over-engineering, premature abstraction, and YAGNI violations. Champion the simplest solution that works.\n\n## When to Use\n- When implementations feel heavy or complex\n- When abstractions are introduced\n- When \"future-proofing\" is mentioned\n\n## Instructions\n1. Read the changed code and its context\n2. Ask: \"Could this be simpler while still correct?\"\n3. Flag premature abstractions (used in only one place)\n4. Flag unnecessary indirection or wrapper layers\n5. Flag feature flags or config for single-use cases\n6. Verify no \"just in case\" code exists\n\n## Collaboration\n- Share cross-cutting findings via direct message: over-engineering obscuring security concerns goes to security-reviewer; premature abstractions creating wrong module boundaries goes to architecture-reviewer.\n\n## Tools Available\n- Read, Grep for code analysis\n\n## Output Format\n- **OVER-ENGINEERED**: Simpler solution exists\n- **YAGNI**: Feature not needed yet\n- **OK**: Appropriate complexity for the task\n`,\n};\n","/**\n * Workflow agent templates for the /compound:compound and /compound:work phases.\n *\n * 4 compound-phase analysts + 2 TDD work agents.\n */\n\nexport const WORKFLOW_AGENT_TEMPLATES: Record<string, string> = {\n 'context-analyzer.md': `---\nname: Context Analyzer\ndescription: Analyzes completed work to identify what was done and learned\nmodel: sonnet\n---\n\n# Context Analyzer\n\n## Role\nAnalyze the current session's work context: what was accomplished, what problems arose, what corrections were made, and what knowledge was gained. Examine git diff output, git log history, and test output to build a complete picture.\n\n## Instructions\n1. Run \\`git diff\\` and \\`git log\\` to review recent changes\n2. Check test results and test output for failures or regressions\n3. Review plan context to understand what was intended\n4. Use \\`memory_search\\` to check existing knowledge for relevant context\n5. Identify problems encountered and how they were solved\n6. Note any user corrections or redirections\n7. Summarize the work context for lesson extraction\n\n## Collaboration\n- Share findings with lesson-extractor via direct message so it can extract actionable lessons from the context.\n- Pass results to other compound agents as needed.\n\n## Output Format\n- **Completed**: What was accomplished\n- **Problems**: Issues encountered and resolutions\n- **Corrections**: User feedback that changed approach\n- **Patterns**: Recurring themes or techniques\n`,\n\n 'lesson-extractor.md': `---\nname: Lesson Extractor\ndescription: Extracts actionable lessons from work context\nmodel: sonnet\n---\n\n# Lesson Extractor\n\n## Role\nExtract actionable, specific lessons from analyzed work context. Identify corrections, mistakes, and discoveries. Transform observations into structured knowledge that prevents future mistakes.\n\n## Instructions\n1. Review the context analysis output\n2. Look for mistake patterns, correction moments, and surprises\n3. Discover insights from how problems were solved\n4. Use \\`memory_search\\` to check for duplicate lessons\n5. For each problem/correction, ask: \"What should be done differently next time?\"\n6. Filter out lessons that are too generic or obvious\n7. Each lesson must be specific; prefer actionable guidance when possible\n\n## Collaboration\n- Share findings with pattern-matcher and solution-writer via direct message so they can classify and store the lessons.\n- Collaborate with context-analyzer to clarify ambiguous findings.\n\n## Output Format\nPer lesson:\n- **Insight**: The actionable directive\n- **Trigger**: When this lesson applies\n- **Context**: Why this matters\n`,\n\n 'pattern-matcher.md': `---\nname: Pattern Matcher\ndescription: Matches lessons against existing memory to avoid duplicates\nmodel: sonnet\n---\n\n# Pattern Matcher\n\n## Role\nCompare extracted lessons against existing memory items to prevent duplicates, find connections, and identify lessons that strengthen existing knowledge.\n\n## Instructions\n1. Take the list of extracted lessons\n2. For each lesson, search existing memory with \\`memory_search\\`\n3. Classify each lesson:\n - **New**: No similar existing item\n - **Duplicate**: Already captured\n - **Reinforcement**: Strengthens existing item\n - **Contradiction**: Conflicts with existing item\n4. Only recommend storing New lessons\n5. Flag Contradictions for user review\n\n## Collaboration\n- Share classifications with solution-writer via direct message so it knows which lessons to store.\n- Pass results to the team for review.\n\n## Output Format\nPer lesson:\n- **Classification**: New / Duplicate / Reinforcement / Contradiction\n- **Match**: ID of matching item if applicable\n- **Recommendation**: Store / Skip / Review\n`,\n\n 'solution-writer.md': `---\nname: Solution Writer\ndescription: Writes final memory items in correct schema format\nmodel: sonnet\n---\n\n# Solution Writer\n\n## Role\nTransform approved lessons into properly formatted memory items that follow the compound-agent schema. Apply quality filters before storage.\n\n## Instructions\n1. Take approved lessons from pattern-matcher\n2. For each lesson, format as a memory item:\n - Clear, imperative insight statement\n - Specific trigger condition\n - Appropriate type classification\n3. Apply quality filters:\n - Is it novel? (not already stored)\n - Is it specific? (not vague advice)\n4. Assign severity: high (data loss/security/contradictions), medium (workflow/patterns), low (style/optimizations)\n5. Set supersedes or related links when the lesson updates existing knowledge\n6. Store via \\`memory_capture\\` MCP tool\n\n## Collaboration\n- Share findings with other agents via direct message to communicate storage outcomes.\n- Collaborate with pattern-matcher on borderline classifications.\n\n## Output Format\n- **Stored**: List of captured items with IDs\n- **Rejected**: Items that failed quality filters, with reasons\n`,\n\n 'test-writer.md': `---\nname: Test Writer\ndescription: Writes failing tests before implementation exists\nmodel: sonnet\n---\n\n# Test Writer\n\n## Role\nWrite comprehensive failing tests that define expected behavior before any implementation exists. Follow strict TDD -- tests must fail for the right reason.\n\n## Modes\n\n### Sequential Mode\nWrite the complete test suite covering happy path, edge cases, and error cases. Hand off the full suite to the implementer. Use this when the task is well-scoped with clear requirements.\n\n### Iterative Mode\nWrite interface and contract tests first, defining the public API surface. Share with the implementer. After the implementer responds with API details or feedback, write edge case tests. Continue the ping-pong cycle until coverage is complete. Use this for complex or ambiguous tasks.\n\n## Instructions\n1. Understand the requirements (read spec, issue, or task description)\n2. Identify the public API surface to test\n3. Write tests that call the real (not-yet-existing) functions\n4. Include:\n - Happy path tests\n - Edge cases (empty input, boundaries, nulls)\n - Error cases (invalid input, failure modes)\n5. Use clear test names describing expected behavior\n6. Run tests to verify they fail for the RIGHT reason (missing implementation, not syntax errors)\n7. Do NOT mock the thing being tested\n\n## Memory Integration\nCall \\`memory_search\\` with the task description before writing tests. Look for known patterns, edge cases, and past mistakes relevant to the feature area.\n\n## Tools Available\n- Read, Grep for understanding existing code\n- Write, Edit for creating test files\n- Bash for running tests\n- \\`memory_search\\` for relevant context\n\n## Output Format\n- Test file path\n- Number of tests written\n- Confirmation that tests fail correctly\n`,\n\n 'implementer.md': `---\nname: Implementer\ndescription: Implements minimal code to pass failing tests\nmodel: sonnet\n---\n\n# Implementer\n\n## Role\nWrite the minimum code necessary to make failing tests pass. Follow the TDD green phase -- NEVER modify test files, only write implementation code.\n\n## Modes\n\n### Sequential Mode\nReceive the full test suite from the test-writer. Implement all tests in order, one at a time. Run tests after each change to confirm progress.\n\n### Iterative Mode\nReceive interface and contract tests from the test-writer. Implement the core API. Communicate back to the test-writer with API details, design decisions, or feedback. Receive edge case tests. Implement remaining behavior. Continue the cycle until all tests pass.\n\n## Instructions\n1. Run the failing tests to understand what is expected\n2. Read the test file to understand the API contract\n3. Write the simplest implementation that passes each test\n4. Work one test at a time (run after each change)\n5. NEVER modify the test files to make them pass\n6. If a test seems wrong, stop and report it -- do not change it\n7. After all tests pass, look for obvious refactoring opportunities\n\n## Memory Integration\nCall \\`memory_search\\` with the task description for known patterns, solutions, and implementation approaches relevant to the feature area.\n\n## Tools Available\n- Read, Write, Edit for implementation\n- Bash for running tests\n- \\`memory_search\\` for relevant patterns\n\n## Output Format\n- Implementation file path\n- Tests passing: X/Y\n- Any concerns about test correctness\n`,\n};\n","/**\n * Agent definition templates for .claude/agents/compound/.\n * Each entry is a markdown file that Claude Code discovers as a spawnable agent.\n *\n * Templates are split across multiple files to stay within the 400-line limit:\n * - agents-review.ts: Research + review agents (7 templates)\n * - agents-workflow.ts: Compound phase + TDD work agents (6 templates)\n * - agents-phase11.ts: Phase 11 intelligent compounding agents (5 templates)\n */\n\nimport { PHASE11_AGENT_TEMPLATES } from './agents-phase11.js';\nimport { REVIEW_AGENT_TEMPLATES } from './agents-review.js';\nimport { WORKFLOW_AGENT_TEMPLATES } from './agents-workflow.js';\n\nexport const AGENT_TEMPLATES: Record<string, string> = {\n ...REVIEW_AGENT_TEMPLATES,\n ...WORKFLOW_AGENT_TEMPLATES,\n ...PHASE11_AGENT_TEMPLATES,\n};\n","/**\n * Workflow slash command templates for .claude/commands/compound/.\n */\n\nexport const WORKFLOW_COMMANDS: Record<string, string> = {\n 'brainstorm.md': `$ARGUMENTS\n\n# Brainstorm\n\n## Purpose\nExplore requirements through collaborative dialogue before committing to a plan.\n\n## Workflow\n1. Parse the topic from \\`$ARGUMENTS\\`. If empty, ask the user what to brainstorm.\n2. Call \\`memory_search\\` with the topic to surface relevant past lessons. Display retrieved items and incorporate them into exploration.\n3. Spawn Explore subagents to research existing context:\n - **docs-explorer**: scan \\`docs/\\` for architecture docs, specs, research, standards, anti-patterns, and existing ADRs in \\`docs/decisions/\\`\n - **code-explorer**: quick codebase research on areas relevant to the brainstorm\n4. Use \\`AskUserQuestion\\` to clarify scope, constraints, and preferences through structured dialogue.\n5. Explore edge cases and failure modes.\n6. Propose 2-3 alternative approaches with tradeoffs.\n7. Run \\`bd ready\\` to check if related tasks already exist.\n8. Output a clear problem definition, chosen approach, and open questions.\n9. Create a beads epic from conclusions:\n \\`\\`\\`bash\n bd create --title=\"<epic title>\" --type=feature --description=\"<problem definition + approach + scope>\"\n \\`\\`\\`\n10. For each significant decision, auto-create an ADR in \\`docs/decisions/\\`:\n - Scan \\`docs/decisions/\\` for the highest existing number, increment by 1\n - Write \\`docs/decisions/NNN-<kebab-title>.md\\` using this template:\n \\`\\`\\`markdown\n # NNN. <Title>\n Status: accepted\n Date: <YYYY-MM-DD>\n\n ## Context\n <What prompted this decision>\n\n ## Decision\n <What was decided and why>\n\n ## Consequences\n <What follows from this decision>\n \\`\\`\\`\n\n## Memory Integration\n- Call \\`memory_search\\` at the start to avoid repeating past mistakes.\n- If the brainstorm surfaces new insights, note them for later capture.\n\n## Docs Integration\n- Spawn a docs-explorer subagent to scan \\`docs/\\` for relevant architecture docs, research, standards, and existing ADRs.\n- Review existing ADRs in \\`docs/decisions/\\` for prior decisions that constrain the current brainstorm.\n- Auto-create ADR files for significant architectural decisions made during brainstorm.\n\n## Beads Integration\n- Run \\`bd ready\\` to check for existing related work.\n- Create a beads epic from brainstorm conclusions with \\`bd create --type=feature\\`.\n- If the brainstorm identifies sub-tasks, suggest creating them with \\`bd create\\`.\n`,\n\n 'plan.md': `$ARGUMENTS\n\n# Plan\n\n## Purpose\nCreate a structured implementation plan enriched by semantic memory and existing documentation, with concrete tasks and dependencies.\n\n## Workflow\n1. Parse the goal from \\`$ARGUMENTS\\`. If empty, ask the user what to plan.\n2. Check for brainstorm output: run \\`bd list\\` to find a related brainstorm epic. If one exists, read its description for decisions and open questions.\n3. Call \\`memory_search\\` with the goal to retrieve relevant past lessons. Display retrieved memory items and incorporate them into planning context.\n4. Spawn research agent team:\n - **Docs Analyst** (\\`docs-analyst\\`): scan \\`docs/\\` for specs, standards, anti-patterns, and ADRs in \\`docs/decisions/\\` that constrain the plan\n - **Repo Analyst** (\\`repo-analyst\\`): explore codebase patterns, conventions, and architecture\n - **Memory Analyst** (\\`memory-analyst\\`): deep dive into related memory items with multiple search queries\n5. Synthesize research findings from all agents into a coherent plan. Flag any conflicts between ADRs and proposed approach.\n6. Use \\`AskUserQuestion\\` to resolve ambiguities: unclear requirements, conflicting ADRs, or priority trade-offs that need user input before decomposing.\n7. Break the goal into concrete, ordered tasks with clear acceptance criteria.\n8. Create beads issues and map dependencies:\n \\`\\`\\`bash\n bd create --title=\"<task>\" --type=task --priority=<1-4>\n bd dep add <dependent-task> <blocking-task>\n \\`\\`\\`\n9. Output the plan as a structured list with task IDs and dependency graph.\n\n## Memory Integration\n- Call \\`memory_search\\` before planning to learn from past approaches.\n- Search for architectural patterns relevant to the goal.\n- Incorporate retrieved lessons into task descriptions as context.\n\n## Docs Integration\n- Spawn a docs-analyst subagent to scan \\`docs/\\` for relevant specs, standards, research, and existing ADRs.\n- Check \\`docs/decisions/\\` for prior ADRs that constrain or inform the plan.\n- If the plan contradicts an existing ADR, flag the conflict for the user.\n\n## Beads Integration\n- Create one \\`bd\\` issue per task with \\`bd create\\`.\n- Set priority (1=critical, 4=low) based on dependency order.\n- Map dependencies with \\`bd dep add <dependent> <blocker>\\`.\n- Each task should include acceptance criteria in its description.\n`,\n\n 'work.md': `$ARGUMENTS\n\n# Work\n\n## Purpose\nExecute implementation by delegating to an agent team. The lead coordinates and does not code directly.\n\n## Workflow\n1. Parse task from \\`$ARGUMENTS\\`. If empty, run \\`bd ready\\` to find available tasks.\n2. Mark task in progress: \\`bd update <id> --status=in_progress\\`.\n3. Call \\`memory_search\\` with the task description to retrieve relevant lessons. Run \\`memory_search\\` per agent/subtask so each gets targeted context.\n4. Assess complexity to determine team strategy.\n5. For non-trivial tasks, spawn a **test-analyst** agent before any code is written. The test-analyst:\n - Analyzes the task requirements and acceptance criteria\n - Identifies happy paths, edge cases, failure modes, boundary conditions, and invariants\n - Produces a structured **test plan** (not code) listing concrete test cases to cover\n - The test-writer then implements this plan as actual test code\n6. Execute based on assessed complexity:\n - If **trivial** (config changes, typos, one-line fixes): handle directly with a single agent. No TDD pair needed. Proceed to verification and close.\n - If **simple** (well-scoped feature or bug fix): sequential TDD — **test-analyst** produces test plan, then **test-writer** implements failing tests, then **implementer** makes them pass.\n - If **complex** (cross-cutting or ambiguous scope): iterative TDD — **test-analyst** produces test plan, then **test-writer** and **implementer** alternate in ping-pong cycles until done.\n7. When agents work on overlapping areas, they communicate directly to coordinate and avoid conflicts.\n8. Lead coordinates the cycle: review agent outputs, resolve conflicts, verify tests pass. Do not write code directly.\n9. If blocked by ambiguity or conflicting agent outputs, use \\`AskUserQuestion\\` to get user direction before proceeding.\n10. Commit incrementally as tests pass — do not batch all commits to the end.\n11. Run the full test suite to check for regressions.\n12. Close the task: \\`bd close <id>\\`.\n\n## Verification Gate\nBefore marking work complete, run the 8-step TDD verification pipeline:\n1. /invariant-designer → 2. /cct-subagent → 3. /test-first-enforcer → 4. /property-test-generator → 5. /anti-cargo-cult-reviewer → 6. /module-boundary-reviewer → 7. /drift-detector → 8. /implementation-reviewer\n\n## Memory Integration\n- Call \\`memory_search\\` per delegated subtask with the subtask's specific description, not one shared query.\n- Each agent receives memory items tailored to their assigned task.\n- After corrections or discoveries, call \\`memory_capture\\` to record them.\n\n## Beads Integration\n- Start with \\`bd ready\\` to pick work.\n- Update status with \\`bd update <id> --status=in_progress\\`.\n- Close with \\`bd close <id>\\` when all tests pass.\n`,\n\n 'review.md': `$ARGUMENTS\n\n# Review\n\n## Purpose\nMulti-agent code review with severity classification and a mandatory \\`/implementation-reviewer\\` gate.\n\n## Workflow\n1. Run quality gates first: \\`pnpm test && pnpm lint\\` to catch easy failures before the full review.\n2. Identify what to review from \\`$ARGUMENTS\\` or recent changes (\\`git diff\\`).\n3. Call \\`memory_search\\` with the changed areas to surface relevant past lessons.\n4. Spawn the reviewer agent team in parallel — one agent per perspective:\n - **security-reviewer**: injection risks, auth issues, data exposure\n - **architecture-reviewer**: module boundaries, coupling, cohesion, API design\n - **performance-reviewer**: unnecessary allocations, N+1 queries, blocking calls\n - **test-coverage-reviewer**: missing edge cases, cargo-cult tests, mocked business logic\n - **simplicity-reviewer**: over-engineering, dead code, unnecessary abstractions\n - **docs-reviewer**: documentation alignment, ADR compliance, undocumented public APIs\n - **consistency-reviewer**: naming conventions, code patterns, style consistency with existing codebase\n - **error-handling-reviewer**: error messages quality, resilience, logging, observability\n - **edge-case-reviewer**: boundary conditions, off-by-one, nil/undefined, empty inputs, type coercion traps\n - **pattern-matcher**: search \\`memory_search\\` for recurring issues — if a finding matches a known pattern, auto-reinforce its severity via \\`memory_capture\\`\n - **cct-reviewer**: check code against CCT patterns in \\`.claude/lessons/cct-patterns.jsonl\\` for known Claude mistakes from past sessions\n5. Reviewers communicate findings with each other via direct messages so cross-cutting issues (e.g., a security fix that impacts performance) are identified early.\n6. Collect all findings and classify by severity:\n - **P1** (critical): security vulnerabilities, data loss, correctness bugs — P1 findings block completion\n - **P2** (important): architectural violations, significant performance issues\n - **P3** (minor): style nits, small improvements, non-urgent suggestions\n7. Synthesize and prioritize findings — deduplicate overlapping reports, consolidate related items, and rank by severity before creating issues.\n8. Use \\`AskUserQuestion\\` when severity classification is ambiguous (e.g., a finding could be P1 or P2) or when the fix approach has multiple valid options.\n9. For P1 and P2 findings, create beads issues:\n \\`\\`\\`bash\n bd create --title=\"P1: <finding>\" --type=bug --priority=1\n \\`\\`\\`\n10. Submit to **\\`/implementation-reviewer\\`** as the mandatory gate — it has final authority on whether the review passes. All P1 findings must be resolved before approval.\n11. Output a review summary with pass/fail per perspective and severity breakdown.\n\n## Memory Integration\n- Call \\`memory_search\\` at the start for known issues in the changed areas.\n- **pattern-matcher** auto-reinforces: when a review finding matches an existing memory item, call \\`memory_capture\\` to increase its severity (recurring issues become higher priority).\n- **cct-reviewer** reads \\`.claude/lessons/cct-patterns.jsonl\\` for known Claude failure patterns.\n- After the review, call \\`memory_capture\\` with \\`type=solution\\` to store the review report for future sessions.\n\n## Docs Integration\n- **docs-reviewer** checks that code changes align with \\`docs/\\` content and existing ADRs.\n- Flags if a public API was added without documentation.\n- Flags if code contradicts an existing ADR in \\`docs/decisions/\\`.\n\n## Beads Integration\n- Create \\`bd\\` issues for P1 and P2 findings with \\`bd create\\`.\n- Reference the reviewed code in issue descriptions.\n- Close related issues with \\`bd close\\` when findings are resolved.\n`,\n\n 'compound.md': `$ARGUMENTS\n\n# Compound\n\n## Purpose\nMulti-agent analysis to capture high-quality lessons from completed work into the memory system and update project documentation.\n\n## Workflow\n1. Parse what was done from \\`$ARGUMENTS\\` or recent git history (\\`git diff\\`, \\`git log\\`).\n2. Call \\`memory_search\\` with the topic to check what is already known (avoid duplicates).\n3. Spawn the compound analysis team in parallel:\n - **context-analyzer**: summarize what happened (git diff, test results, plan context)\n - **lesson-extractor**: identify mistakes, corrections, and discoveries\n - **docs-reviewer**: scan \\`docs/\\` for docs that need updating based on what changed, and check if any ADR in \\`docs/decisions/\\` should be deprecated or superseded\n - **pattern-matcher**: match against existing memory, classify New/Duplicate/Reinforcement/Contradiction\n - **solution-writer**: formulate structured items typed as lesson, solution, pattern, or preference\n - **compounding**: synthesize accumulated lessons into CCT patterns for test reuse\n4. Agents pass results to each other via direct messages so downstream agents build on upstream findings.\n5. Apply quality filter on each candidate item:\n - **Novel**: skip if >0.85 similarity to existing memory\n - **Specific**: reject vague or generic advice\n6. Classify severity for each approved item:\n - **High**: data loss risk, security implications, contradicts established patterns\n - **Medium**: workflow changes, pattern corrections, tooling preferences\n - **Low**: style preferences, minor optimizations, reinforcements\n7. For approved items, store via \\`memory_capture\\` with supersedes/related linking to connect with existing memory.\n8. After storing new items, delegate to the **compounding** subagent to run compounding synthesis:\n - Read all lessons from \\`.claude/lessons/index.jsonl\\`\n - Cluster by embedding similarity (threshold 0.75)\n - Synthesize CCT patterns from clusters of 2+ items\n - Write patterns to \\`.claude/lessons/cct-patterns.jsonl\\`\n - Skip if fewer than 5 total lessons exist (not enough signal)\n9. If the docs-reviewer found outdated docs or ADRs, update them. For superseded ADRs, set status to \\`deprecated\\` and reference the new ADR.\n10. Use \\`AskUserQuestion\\` to confirm high-severity items with the user before storing; medium/low items are auto-stored.\n11. Run \\`bd ready\\` to check for related issues; \\`bd close\\` any resolved by captured knowledge.\n12. Output a summary of captured items, skipped items, and docs updated.\n\n## Docs Integration\n- Spawn a docs-reviewer subagent to check if \\`docs/\\` content needs updating after the cycle.\n- Check \\`docs/decisions/\\` for ADRs that may be outdated or contradicted by the work done.\n- Update ADR status to \\`deprecated\\` if a decision was reversed, with a reference to the new ADR.\n\n## Beads Integration\n- Check \\`bd ready\\` for related open issues.\n- Close resolved issues with \\`bd close\\`.\n`,\n\n 'lfg.md': `$ARGUMENTS\n\n# LFG (Full Cycle)\n\n## Purpose\nChain all phases: brainstorm, plan, work, review, compound. End-to-end delivery.\n\n## Workflow\n1. **Brainstorm phase**: Explore the goal from \\`$ARGUMENTS\\`.\n - Call \\`memory_search\\` with the goal.\n - Spawn docs-explorer to scan \\`docs/\\` for relevant context and existing ADRs.\n - Ask clarifying questions via \\`AskUserQuestion\\`, explore alternatives.\n - Auto-create ADRs for significant decisions in \\`docs/decisions/\\`.\n - Create a beads epic from conclusions with \\`bd create --type=feature\\`.\n\n2. **Plan phase**: Structure the work.\n - Check for brainstorm epic via \\`bd list\\`.\n - Spawn docs-analyst to check specs, standards, and ADRs that constrain the plan.\n - Break into tasks with dependencies and acceptance criteria.\n - Create beads issues with \\`bd create\\` and map dependencies with \\`bd dep add\\`.\n\n3. **Work phase**: Implement with adaptive TDD.\n - Assess complexity (trivial/simple/complex) to choose team strategy.\n - For non-trivial tasks: test-analyst produces test plan, then test-writer and implementer execute.\n - Call \\`memory_search\\` per subtask; \\`memory_capture\\` after corrections.\n - Commit incrementally. Close tasks as they complete.\n - Run verification gate before marking complete.\n\n4. **Review phase**: 11-agent review with severity classification.\n - Run quality gates first: \\`pnpm test && pnpm lint\\`.\n - Core (security, architecture, performance, test-coverage, simplicity), quality (docs, consistency, error-handling), intelligence (edge-case, pattern-matcher, cct-reviewer).\n - Classify findings as P1 (critical/blocking), P2 (important), P3 (minor).\n - P1 findings must be fixed before proceeding — they block completion.\n - Submit to \\`/implementation-reviewer\\` as the mandatory gate before moving on.\n - Create beads issues for P1/P2 findings.\n\n5. **Compound phase**: Capture learnings.\n - Spawn 6-agent analysis team: context-analyzer, lesson-extractor, docs-reviewer, pattern-matcher, solution-writer, compounding.\n - Search first with \\`memory_search\\` to avoid duplicates. Apply quality filters (novelty + specificity).\n - Store novel insights via \\`memory_capture\\` with supersedes/related links.\n - Update outdated docs and deprecate superseded ADRs.\n - Use \\`AskUserQuestion\\` to confirm high-severity items before storing.\n\n## Phase Control\n- **Skip phases**: Parse \\`$ARGUMENTS\\` for \"from <phase>\" (e.g., \"from plan\"). Skip all phases before the named one.\n- **Progress**: Announce the current phase before starting it (e.g., \"[Phase 2/5] Plan\").\n- **Retry**: If a phase fails, report the failure and ask the user whether to retry, skip, or abort.\n- **Resume**: After interruption, check \\`bd list --status=in_progress\\` to find where work stopped and resume from that phase.\n\n## Stop Conditions\n- Stop if brainstorm reveals the goal is unclear (ask user).\n- Stop if any test phase produces failures that cannot be resolved.\n- Stop if review finds critical security issues.\n\n## Memory Integration\n- \\`memory_search\\` is called in brainstorm, work, and compound phases.\n- \\`memory_capture\\` is called in work and compound phases.\n`,\n};\n","/**\n * Phase skill SKILL.md templates for compound workflow phases.\n * Written to .claude/skills/compound/<phase>/SKILL.md during setup.\n */\n\nexport const PHASE_SKILLS: Record<string, string> = {\n brainstorm: `---\nname: Brainstorm\ndescription: Divergent-then-convergent thinking to explore solution space\n---\n\n# Brainstorm Skill\n\n## Overview\nExplore the problem space before committing to a solution. This phase produces a structured brainstorm document with decisions, open questions, and a beads epic for handoff to planning.\n\n## Methodology\n1. Ask \"why\" before \"how\" -- understand the real problem\n2. Search memory with \\`memory_search\\` for similar past features and known constraints\n3. Spawn Explore subagents: docs-explorer for \\`docs/\\` (architecture, specs, research, standards, existing ADRs) and code-explorer for relevant codebase areas\n4. Use \\`AskUserQuestion\\` to clarify scope, constraints, and preferences\n5. Divergent phase: generate multiple approaches without filtering\n6. Identify constraints and non-functional requirements (performance, security, etc.)\n7. Convergent phase: evaluate approaches against constraints\n8. Document decisions with rationale, list open questions, and create a beads epic\n9. Auto-create ADR files in \\`docs/decisions/\\` for significant decisions (lightweight: Status, Context, Decision, Consequences)\n\n## Memory Integration\n- Call \\`memory_search\\` with relevant keywords before generating approaches\n- Look for past architectural decisions, pitfalls, and preferences\n- If the problem domain matches past work, review those lessons first\n\n## Docs Integration\n- Spawn docs-explorer to scan \\`docs/\\` for relevant architecture docs, research, and standards\n- Review existing ADRs in \\`docs/decisions/\\` -- prior decisions may constrain the brainstorm\n- Auto-create ADR for each significant decision made during convergence\n\n## Common Pitfalls\n- Jumping to the first solution without exploring alternatives\n- Ignoring non-functional requirements (scalability, maintainability)\n- Not searching memory for similar past features\n- Not checking existing docs and ADRs for prior decisions\n- Over-scoping: trying to solve everything at once\n- Skipping the \"why\" and diving into \"how\"\n- Not creating a beads epic from conclusions (losing brainstorm output)\n\n## Quality Criteria\n- Multiple approaches were considered (at least 2-3)\n- Constraints and requirements are explicitly listed\n- Memory was searched for relevant context\n- Existing docs and ADRs were reviewed for prior decisions\n- User was engaged via \\`AskUserQuestion\\` for clarification\n- A clear decision was made with documented rationale\n- ADRs created for significant architectural decisions\n- Open questions are captured for the plan phase\n- A beads epic was created from conclusions via \\`bd create\\`\n`,\n\n plan: `---\nname: Plan\ndescription: Decompose work into small testable tasks with clear dependencies\n---\n\n# Plan Skill\n\n## Overview\nCreate a concrete implementation plan by decomposing work into small, testable tasks with dependencies and acceptance criteria.\n\n## Methodology\n1. Review brainstorm output for decisions and open questions\n2. Search memory with \\`memory_search\\` for architectural patterns and past mistakes\n3. Spawn research agent team: docs-analyst for \\`docs/\\` (specs, standards, ADRs), repo-analyst for codebase, memory-analyst for deep memory search\n4. Synthesize research findings into a coherent approach. Flag conflicts between ADRs and proposed plan.\n5. Use \\`AskUserQuestion\\` to resolve ambiguities, conflicting constraints, or priority trade-offs before decomposing\n6. Decompose into tasks small enough to verify individually\n7. Define acceptance criteria for each task\n8. Map dependencies between tasks\n9. Create beads issues: \\`bd create --title=\"...\" --type=task\\`\n\n## Memory Integration\n- Call \\`memory_search\\` for patterns related to the feature area\n- Look for past planning mistakes (missing dependencies, unclear criteria)\n- Check for preferred architectural patterns in this codebase\n\n## Docs Integration\n- Spawn docs-analyst to scan \\`docs/\\` for relevant specs, standards, and research\n- Check \\`docs/decisions/\\` for existing ADRs that constrain or inform the plan\n- If the plan contradicts an ADR, flag it for the user before proceeding\n\n## Common Pitfalls\n- Creating too many fine-grained tasks (aim for 3-7 per feature)\n- Unclear acceptance criteria (\"make it work\" is not a criterion)\n- Missing dependencies between tasks\n- Not checking memory for past architectural decisions\n- Not reviewing existing ADRs and docs for constraints\n- Planning implementation details too early (stay at task level)\n\n## Quality Criteria\n- Each task has clear acceptance criteria\n- Dependencies are mapped and no circular dependencies exist\n- Tasks are ordered so each can be verified independently\n- Memory was searched for relevant patterns and past mistakes\n- Existing docs and ADRs were checked for constraints\n- Ambiguities resolved via \\`AskUserQuestion\\` before decomposing\n- Complexity estimates are realistic (no \"should be quick\")\n`,\n\n work: `---\nname: Work\ndescription: Team-based TDD execution with adaptive complexity and agent delegation\n---\n\n# Work Skill\n\n## Overview\nExecute implementation through an agent team using adaptive TDD. The lead coordinates and delegates -- agents write code.\n\n## Methodology\n1. Pick a task from \\`bd ready\\` or \\`$ARGUMENTS\\`\n2. Search memory with \\`memory_search\\` per agent/subtask for targeted context\n3. Assess complexity (see below) and choose team strategy\n4. For non-trivial tasks, spawn **test-analyst** first to produce a structured test plan (happy paths, edge cases, failure modes, boundary conditions, invariants) -- no code, just a checklist of what to test\n5. Execute based on complexity:\n - If trivial: single agent handles directly, no TDD ceremony. Skip to step 8.\n - If simple: **Analyze** — test-analyst produces test plan, then **Red** — test-writer implements failing tests from the plan, then **Green** — implementer makes them pass.\n - If complex: **Analyze** — test-analyst produces test plan, then **Red/Green ping-pong** — test-writer and implementer alternate in cycles.\n6. When agents work on overlapping areas, they communicate directly to coordinate\n7. **Refactor**: Review agent output, request cleanup if needed\n8. Commit incrementally as tests pass — do not batch all commits to the end\n9. Capture lessons with \\`memory_capture\\` after corrections or discoveries\n\n## Team Structure\nAdaptive TDD model based on task complexity:\n- **Trivial**: Single agent handles the change directly, no TDD ceremony\n- **Simple**: test-analyst → test-writer → implementer (sequential)\n- **Complex**: test-analyst → test-writer/implementer ping-pong (iterative)\n\n## Complexity Assessment\n- **Trivial**: Config changes, typos, renaming, one-line fixes. No new behavior.\n- **Simple**: Well-scoped feature or bug fix. Clear inputs/outputs. One module affected.\n- **Complex**: Cross-module changes, architectural decisions, ambiguous requirements.\n\n## Agent Delegation\nThe lead coordinates but does not write code:\n- Spawn **test-analyst** first for non-trivial tasks -- it produces the test plan that test-writer implements\n- Spawn agents with task context, relevant memory items, and the test plan\n- Review agent outputs for correctness and consistency\n- Resolve conflicts between test expectations and implementation\n- Use \\`AskUserQuestion\\` when blocked by ambiguity or conflicting agent outputs -- get user direction before proceeding\n\n## Memory Integration\n- Call \\`memory_search\\` per delegated subtask with the subtask's specific description\n- Each agent receives memory items tailored to their assigned task, not a shared blob\n- Call \\`memory_capture\\` after corrections or novel discoveries\n\n## Verification Gate\nBefore marking work complete, run the 8-step TDD verification pipeline:\n1. /invariant-designer → 2. /cct-subagent → 3. /test-first-enforcer → 4. /property-test-generator → 5. /anti-cargo-cult-reviewer → 6. /module-boundary-reviewer → 7. /drift-detector → 8. /implementation-reviewer\n\n## Beads Lifecycle\n- \\`bd ready\\` to find available tasks\n- \\`bd update <id> --status=in_progress\\` when starting\n- \\`bd close <id>\\` when all tests pass\n\n## Common Pitfalls\n- Lead writing code instead of delegating to agents\n- Skipping complexity assessment and always using full TDD for trivial changes\n- Letting test-writer improvise without a test-analyst plan (vibes-based testing)\n- Not injecting memory context into agent prompts\n- Modifying tests to make them pass instead of fixing implementation\n- Not running the full test suite after agent work completes\n\n## Quality Criteria\n- Complexity was assessed before choosing team strategy\n- Test-analyst produced a test plan before test-writer started (non-trivial tasks)\n- Tests existed before implementation code\n- Agents received relevant memory context\n- Lead coordinated without writing implementation code\n- Incremental commits made as tests pass\n- All tests pass after refactoring\n- Task lifecycle tracked via beads (\\`bd\\`)\n`,\n\n review: `---\nname: Review\ndescription: Multi-agent review with parallel specialized reviewers and severity classification\n---\n\n# Review Skill\n\n## Overview\nPerform thorough code review by spawning specialized reviewers in parallel, consolidating findings with severity classification (P1/P2/P3), and gating completion on implementation-reviewer approval.\n\n## Methodology\n1. Run quality gates first: \\`pnpm test && pnpm lint\\`\n2. Search memory with \\`memory_search\\` for known patterns and recurring issues\n3. Spawn 11 specialized reviewer agents in parallel:\n - **Core**: security, architecture, performance, test-coverage, simplicity\n - **Quality**: docs-reviewer, consistency-reviewer, error-handling-reviewer\n - **Intelligence**: edge-case-reviewer, pattern-matcher (memory-backed), cct-reviewer (CCT patterns)\n4. Reviewers communicate findings to each other via direct messages\n5. Collect, consolidate, and deduplicate all findings\n6. Classify by severity: P1 (critical/blocking), P2 (important), P3 (minor)\n7. Use \\`AskUserQuestion\\` when severity is ambiguous or fix has multiple valid options\n8. Create beads issues for P1 findings: \\`bd create --title=\"P1: ...\"\\`\n9. Fix all P1 findings before proceeding\n10. Run \\`/implementation-reviewer\\` as mandatory gate\n11. Capture novel findings with \\`memory_capture\\`; pattern-matcher auto-reinforces recurring issues\n\n## Memory Integration\n- Call \\`memory_search\\` before review for known recurring issues\n- **pattern-matcher** auto-reinforces: recurring findings get severity increased via \\`memory_capture\\`\n- **cct-reviewer** reads CCT patterns for known Claude failure patterns\n- Capture the review report via \\`memory_capture\\` with \\`type=solution\\`\n\n## Docs Integration\n- **docs-reviewer** checks code/docs alignment and ADR compliance\n- Flags undocumented public APIs and ADR violations\n\n## Common Pitfalls\n- Ignoring reviewer feedback because \"it works\"\n- Not running all 11 reviewer perspectives (skipping dimensions)\n- Treating all findings as equal priority (classify P1/P2/P3 first)\n- Not creating beads issues for deferred fixes\n- Skipping quality gates before review\n- Bypassing the implementation-reviewer gate\n- Not checking CCT patterns for known Claude mistakes\n\n## Quality Criteria\n- All quality gates pass (\\`pnpm test\\`, lint)\n- All 11 reviewer perspectives were applied in parallel\n- Findings are classified P1/P2/P3 and deduplicated\n- pattern-matcher checked memory and reinforced recurring issues\n- cct-reviewer checked against known Claude failure patterns\n- docs-reviewer confirmed docs/ADR alignment\n- All P1 findings fixed before \\`/implementation-reviewer\\` approval\n- \\`/implementation-reviewer\\` approved as mandatory gate\n`,\n\n compound: `---\nname: Compound\ndescription: Reflect on the cycle and capture high-quality lessons for future sessions\n---\n\n# Compound Skill\n\n## Overview\nExtract and store lessons learned during the cycle, and update project documentation. This is what makes the system compound -- each session leaves the next one better equipped.\n\n## Methodology\n1. Review what happened during this cycle (git diff, test results, plan context)\n2. Spawn the compound analysis team in parallel:\n - context-analyzer: gathers cycle context (diffs, test output)\n - lesson-extractor: identifies corrections, surprises, discoveries\n - docs-reviewer: scans \\`docs/\\` for outdated content and ADRs that need updating\n - pattern-matcher: checks \\`memory_search\\` for duplicates and related items\n - solution-writer: drafts final memory items\n - compounding: synthesizes accumulated lessons into CCT patterns\n3. Agents pass results through the pipeline and share findings with each other\n4. Apply quality filters: novelty check (>0.85 similarity = skip), specificity check\n5. Classify each item by type: lesson, solution, pattern, or preference\n6. Classify severity: high (data loss/security/contradictions), medium (workflow/patterns), low (style/optimizations)\n7. Store via \\`memory_capture\\` with supersedes/related links where applicable\n8. Delegate to the \\`compounding\\` subagent to run synthesis: cluster accumulated lessons by similarity and write CCT patterns to \\`.claude/lessons/cct-patterns.jsonl\\`\n9. Update outdated docs and deprecate superseded ADRs (set status to \\`deprecated\\`)\n10. Use \\`AskUserQuestion\\` to confirm high-severity items with the user before storing; medium/low items are auto-stored\n\n## Docs Integration\n- Spawn docs-reviewer to check if \\`docs/\\` content is outdated after the cycle\n- Check \\`docs/decisions/\\` for ADRs contradicted by the work done\n- Set ADR status to \\`deprecated\\` if a decision was reversed, referencing the new ADR\n\n## Common Pitfalls\n- Not spawning the analysis team (analyzing solo misses cross-cutting patterns)\n- Capturing without checking for duplicates via \\`memory_search\\`\n- Skipping supersedes/related linking when an item updates prior knowledge\n- Not checking if docs or ADRs need updating after the cycle\n- Requiring user confirmation for every item (only high-severity needs it)\n- Not classifying items by type (lesson/solution/pattern/preference)\n- Capturing vague lessons (\"be careful with X\") -- be specific and concrete\n\n## Quality Criteria\n- Analysis team was spawned and agents coordinated via pipeline\n- Quality filters applied (novelty + specificity)\n- Duplicates checked via \\`memory_search\\` before capture\n- Items classified by type (lesson/solution/pattern/preference)\n- Supersedes/related links set where applicable\n- Outdated docs and ADRs were updated or deprecated\n- User confirmed high-severity items\n- Beads checked for related issues (\\`bd\\`)\n- Each item gives clear, concrete guidance for future sessions\n`,\n};\n","/**\n * Shared primitives for setup commands.\n * Used by both init.ts and setup-all.ts to avoid duplication.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport {\n AGENTS_MD_TEMPLATE,\n CLAUDE_MD_REFERENCE,\n CLAUDE_REF_START_MARKER,\n COMPOUND_AGENT_SECTION_HEADER,\n PLUGIN_MANIFEST,\n SLASH_COMMANDS,\n} from './templates.js';\nimport { AGENT_TEMPLATES, WORKFLOW_COMMANDS, PHASE_SKILLS } from './templates/index.js';\n\n/** Marker prepended to generated files for --update detection. */\nexport const GENERATED_MARKER = '<!-- generated by compound-agent -->\\n';\n\n/**\n * Check if AGENTS.md already has the Compound Agent section.\n */\nexport function hasCompoundAgentSection(content: string): boolean {\n return content.includes(COMPOUND_AGENT_SECTION_HEADER);\n}\n\n/**\n * Check if CLAUDE.md already has the Compound Agent reference.\n */\nexport function hasClaudeMdReference(content: string): boolean {\n return content.includes('Compound Agent') || content.includes(CLAUDE_REF_START_MARKER);\n}\n\n/**\n * Create or update AGENTS.md with Compound Agent section.\n */\nexport async function updateAgentsMd(repoRoot: string): Promise<boolean> {\n const agentsPath = join(repoRoot, 'AGENTS.md');\n let content = '';\n let existed = false;\n\n if (existsSync(agentsPath)) {\n content = await readFile(agentsPath, 'utf-8');\n existed = true;\n if (hasCompoundAgentSection(content)) {\n return false; // Already has section, no update needed\n }\n }\n\n // Append the template\n const newContent = existed ? content.trimEnd() + '\\n' + AGENTS_MD_TEMPLATE : AGENTS_MD_TEMPLATE.trim() + '\\n';\n await writeFile(agentsPath, newContent, 'utf-8');\n return true;\n}\n\n/**\n * Ensure CLAUDE.md has a reference to AGENTS.md for Compound Agent workflow.\n * Creates CLAUDE.md if it doesn't exist, appends reference if not present.\n * Uses markers for clean uninstall support.\n */\nexport async function ensureClaudeMdReference(repoRoot: string): Promise<boolean> {\n const claudeMdPath = join(repoRoot, '.claude', 'CLAUDE.md');\n\n // Ensure .claude directory exists\n await mkdir(join(repoRoot, '.claude'), { recursive: true });\n\n if (!existsSync(claudeMdPath)) {\n // Create new CLAUDE.md with reference\n const content = `# Project Instructions\n${CLAUDE_MD_REFERENCE}`;\n await writeFile(claudeMdPath, content, 'utf-8');\n return true;\n }\n\n // File exists - check if reference is already present\n const content = await readFile(claudeMdPath, 'utf-8');\n if (hasClaudeMdReference(content)) {\n return false; // Already has reference\n }\n\n // Append reference\n const newContent = content.trimEnd() + '\\n' + CLAUDE_MD_REFERENCE;\n await writeFile(claudeMdPath, newContent, 'utf-8');\n return true;\n}\n\n/**\n * Create plugin.json in .claude/ directory.\n * Idempotent: does not overwrite existing file.\n *\n * @returns true if plugin.json was created\n */\nexport async function createPluginManifest(repoRoot: string): Promise<boolean> {\n const pluginPath = join(repoRoot, '.claude', 'plugin.json');\n\n // Ensure .claude directory exists\n await mkdir(join(repoRoot, '.claude'), { recursive: true });\n\n if (existsSync(pluginPath)) {\n return false; // Already exists\n }\n\n await writeFile(pluginPath, JSON.stringify(PLUGIN_MANIFEST, null, 2) + '\\n', 'utf-8');\n return true;\n}\n\n/**\n * Create slash commands in .claude/commands/ directory.\n * Idempotent: does not overwrite existing files.\n *\n * @returns true if any commands were created\n */\nexport async function createSlashCommands(repoRoot: string): Promise<boolean> {\n const commandsDir = join(repoRoot, '.claude', 'commands');\n await mkdir(commandsDir, { recursive: true });\n\n let created = false;\n\n for (const [filename, content] of Object.entries(SLASH_COMMANDS)) {\n const filePath = join(commandsDir, filename);\n if (!existsSync(filePath)) {\n await writeFile(filePath, content, 'utf-8');\n created = true;\n }\n }\n\n return created;\n}\n\n/**\n * Install agent templates to .claude/agents/compound/.\n * Idempotent: does not overwrite existing files.\n *\n * @returns true if any agent templates were created\n */\nexport async function installAgentTemplates(repoRoot: string): Promise<boolean> {\n const agentsDir = join(repoRoot, '.claude', 'agents', 'compound');\n await mkdir(agentsDir, { recursive: true });\n\n let created = false;\n for (const [filename, content] of Object.entries(AGENT_TEMPLATES)) {\n const filePath = join(agentsDir, filename);\n if (!existsSync(filePath)) {\n await writeFile(filePath, GENERATED_MARKER + content, 'utf-8');\n created = true;\n }\n }\n return created;\n}\n\n/**\n * Install workflow commands to .claude/commands/compound/.\n * Idempotent: does not overwrite existing files.\n *\n * @returns true if any workflow commands were created\n */\nexport async function installWorkflowCommands(repoRoot: string): Promise<boolean> {\n const commandsDir = join(repoRoot, '.claude', 'commands', 'compound');\n await mkdir(commandsDir, { recursive: true });\n\n let created = false;\n for (const [filename, content] of Object.entries(WORKFLOW_COMMANDS)) {\n const filePath = join(commandsDir, filename);\n if (!existsSync(filePath)) {\n await writeFile(filePath, GENERATED_MARKER + content, 'utf-8');\n created = true;\n }\n }\n return created;\n}\n\n/**\n * Install phase skill templates to .claude/skills/compound/<phase>/SKILL.md.\n * Idempotent: does not overwrite existing files.\n *\n * @returns true if any skill templates were created\n */\nexport async function installPhaseSkills(repoRoot: string): Promise<boolean> {\n let created = false;\n for (const [phase, content] of Object.entries(PHASE_SKILLS)) {\n const skillDir = join(repoRoot, '.claude', 'skills', 'compound', phase);\n await mkdir(skillDir, { recursive: true });\n const filePath = join(skillDir, 'SKILL.md');\n if (!existsSync(filePath)) {\n await writeFile(filePath, GENERATED_MARKER + content, 'utf-8');\n created = true;\n }\n }\n return created;\n}\n","/**\n * One-shot setup command - Configure everything for compound-agent.\n *\n * Combines: init + Claude hooks + MCP server + optionally model download.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { isModelAvailable, resolveModel } from '../memory/embeddings/index.js';\nimport { LESSONS_PATH } from '../memory/storage/index.js';\nimport { out } from '../commands/index.js';\nimport {\n addAllCompoundAgentHooks,\n addMcpServerToMcpJson,\n getClaudeSettingsPath,\n hasClaudeHook,\n hasMcpServerInMcpJson,\n readClaudeSettings,\n removeAgentsSection,\n removeClaudeMdReference,\n removeCompoundAgentHook,\n removeMcpServerFromMcpJson,\n writeClaudeSettings,\n} from './claude-helpers.js';\nimport {\n createPluginManifest,\n createSlashCommands,\n ensureClaudeMdReference,\n GENERATED_MARKER,\n installAgentTemplates,\n installPhaseSkills,\n installWorkflowCommands,\n updateAgentsMd,\n} from './primitives.js';\nimport { SLASH_COMMANDS } from './templates.js';\nimport { AGENT_TEMPLATES, WORKFLOW_COMMANDS, PHASE_SKILLS } from './templates/index.js';\n\n/** Result of one-shot setup */\ninterface SetupResult {\n lessonsDir: string;\n agentsMd: boolean;\n hooks: boolean;\n mcpServer: boolean;\n model: 'downloaded' | 'already_exists' | 'failed' | 'skipped';\n}\n\n/**\n * Ensure lessons directory and index file exist.\n */\nasync function ensureLessonsDirectory(repoRoot: string): Promise<string> {\n const lessonsDir = dirname(join(repoRoot, LESSONS_PATH));\n await mkdir(lessonsDir, { recursive: true });\n\n const indexPath = join(repoRoot, LESSONS_PATH);\n if (!existsSync(indexPath)) {\n await writeFile(indexPath, '', 'utf-8');\n }\n\n return lessonsDir;\n}\n\n/**\n * Configure Claude Code settings: hooks in settings.json, MCP in .mcp.json.\n * Per Claude Code docs, hooks go in .claude/settings.json, MCP goes in .mcp.json.\n */\nasync function configureClaudeSettings(repoRoot: string): Promise<{ hooks: boolean; mcpServer: boolean }> {\n // 1. Configure hooks in .claude/settings.json\n const settingsPath = getClaudeSettingsPath(false);\n let settings: Record<string, unknown>;\n try {\n settings = await readClaudeSettings(settingsPath);\n } catch {\n settings = {};\n }\n\n const hadHooks = hasClaudeHook(settings);\n addAllCompoundAgentHooks(settings);\n await writeClaudeSettings(settingsPath, settings);\n\n // 2. Configure MCP in .mcp.json (project scope, shareable)\n const hadMcp = await hasMcpServerInMcpJson(repoRoot);\n const mcpAdded = await addMcpServerToMcpJson(repoRoot);\n\n return {\n hooks: !hadHooks,\n mcpServer: mcpAdded && !hadMcp,\n };\n}\n\n/**\n * Run one-shot setup.\n */\nexport async function runSetup(options: { skipModel?: boolean }): Promise<SetupResult> {\n const repoRoot = getRepoRoot();\n\n // 1. Initialize lessons directory\n const lessonsDir = await ensureLessonsDirectory(repoRoot);\n\n // 2. Update AGENTS.md\n const agentsMdUpdated = await updateAgentsMd(repoRoot);\n\n // 3. Ensure CLAUDE.md reference\n await ensureClaudeMdReference(repoRoot);\n\n // 4. Create plugin manifest\n await createPluginManifest(repoRoot);\n\n // 5. Create slash commands\n await createSlashCommands(repoRoot);\n\n // 5b. Install agent templates\n await installAgentTemplates(repoRoot);\n\n // 5c. Install workflow commands\n await installWorkflowCommands(repoRoot);\n\n // 5d. Install phase skills\n await installPhaseSkills(repoRoot);\n\n // 6. Configure Claude settings (hooks in settings.json, MCP in .mcp.json)\n const { hooks, mcpServer } = await configureClaudeSettings(repoRoot);\n\n // 7. Download model (unless skipped)\n let modelStatus: 'downloaded' | 'already_exists' | 'failed' | 'skipped' = 'skipped';\n if (!options.skipModel) {\n try {\n const alreadyExisted = isModelAvailable();\n if (!alreadyExisted) {\n await resolveModel({ cli: false });\n modelStatus = 'downloaded';\n } else {\n modelStatus = 'already_exists';\n }\n } catch {\n modelStatus = 'failed';\n }\n }\n\n return {\n lessonsDir,\n agentsMd: agentsMdUpdated,\n hooks,\n mcpServer,\n model: modelStatus,\n };\n}\n\n/**\n * Remove all generated files and configuration.\n * NEVER removes .claude/lessons/ (user data).\n */\nexport async function runUninstall(repoRoot: string, dryRun: boolean): Promise<string[]> {\n const actions: string[] = [];\n\n // Remove generated directories\n const dirsToRemove = [\n join(repoRoot, '.claude', 'agents', 'compound'),\n join(repoRoot, '.claude', 'commands', 'compound'),\n join(repoRoot, '.claude', 'skills', 'compound'),\n ];\n for (const dir of dirsToRemove) {\n if (existsSync(dir)) {\n if (!dryRun) await rm(dir, { recursive: true, force: true });\n actions.push(`Removed ${dir}`);\n }\n }\n\n // Remove base slash commands\n for (const filename of Object.keys(SLASH_COMMANDS)) {\n const filePath = join(repoRoot, '.claude', 'commands', filename);\n if (existsSync(filePath)) {\n if (!dryRun) await rm(filePath);\n actions.push(`Removed ${filePath}`);\n }\n }\n\n // Remove plugin.json\n const pluginPath = join(repoRoot, '.claude', 'plugin.json');\n if (existsSync(pluginPath)) {\n if (!dryRun) await rm(pluginPath);\n actions.push(`Removed ${pluginPath}`);\n }\n\n // Remove hooks from settings.json\n const settingsPath = getClaudeSettingsPath(false);\n try {\n const settings = await readClaudeSettings(settingsPath);\n if (hasClaudeHook(settings)) {\n if (!dryRun) {\n removeCompoundAgentHook(settings);\n await writeClaudeSettings(settingsPath, settings);\n }\n actions.push('Removed compound-agent hooks from settings.json');\n }\n } catch {\n // settings.json may not exist\n }\n\n // Remove MCP server from .mcp.json\n if (await hasMcpServerInMcpJson(repoRoot)) {\n if (!dryRun) await removeMcpServerFromMcpJson(repoRoot);\n actions.push('Removed compound-agent from .mcp.json');\n }\n\n // Remove AGENTS.md section\n if (!dryRun) {\n const removed = await removeAgentsSection(repoRoot);\n if (removed) actions.push('Removed compound-agent section from AGENTS.md');\n } else {\n const agentsPath = join(repoRoot, 'AGENTS.md');\n if (existsSync(agentsPath)) {\n const content = await readFile(agentsPath, 'utf-8');\n if (content.includes('compound-agent:start')) {\n actions.push('Removed compound-agent section from AGENTS.md');\n }\n }\n }\n\n // Remove CLAUDE.md reference\n if (!dryRun) {\n const removed = await removeClaudeMdReference(repoRoot);\n if (removed) actions.push('Removed compound-agent reference from CLAUDE.md');\n } else {\n const claudeMdPath = join(repoRoot, '.claude', 'CLAUDE.md');\n if (existsSync(claudeMdPath)) {\n const content = await readFile(claudeMdPath, 'utf-8');\n if (content.includes('compound-agent:claude-ref:start')) {\n actions.push('Removed compound-agent reference from CLAUDE.md');\n }\n }\n }\n\n return actions;\n}\n\n/**\n * Update generated files with latest templates.\n * Files with GENERATED_MARKER are overwritten, user-customized files are skipped.\n */\nexport async function runUpdate(repoRoot: string, dryRun: boolean): Promise<{ updated: number; added: number; skipped: number }> {\n let updated = 0;\n let added = 0;\n let skipped = 0;\n\n async function processFile(filePath: string, content: string): Promise<void> {\n const markedContent = GENERATED_MARKER + content;\n if (!existsSync(filePath)) {\n if (!dryRun) {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, markedContent, 'utf-8');\n }\n added++;\n } else {\n const existing = await readFile(filePath, 'utf-8');\n if (existing.startsWith(GENERATED_MARKER)) {\n if (existing !== markedContent) {\n if (!dryRun) await writeFile(filePath, markedContent, 'utf-8');\n updated++;\n }\n } else {\n skipped++;\n }\n }\n }\n\n for (const [filename, content] of Object.entries(AGENT_TEMPLATES)) {\n await processFile(join(repoRoot, '.claude', 'agents', 'compound', filename), content);\n }\n for (const [filename, content] of Object.entries(WORKFLOW_COMMANDS)) {\n await processFile(join(repoRoot, '.claude', 'commands', 'compound', filename), content);\n }\n for (const [phase, content] of Object.entries(PHASE_SKILLS)) {\n await processFile(join(repoRoot, '.claude', 'skills', 'compound', phase, 'SKILL.md'), content);\n }\n\n return { updated, added, skipped };\n}\n\n/**\n * Show installation status.\n */\nexport async function runStatus(repoRoot: string): Promise<void> {\n const agentsDir = join(repoRoot, '.claude', 'agents', 'compound');\n const commandsDir = join(repoRoot, '.claude', 'commands', 'compound');\n const skillsDir = join(repoRoot, '.claude', 'skills', 'compound');\n const pluginPath = join(repoRoot, '.claude', 'plugin.json');\n\n console.log('Compound Agent Status:');\n console.log(` Agent templates: ${existsSync(agentsDir) ? 'installed' : 'not installed'}`);\n console.log(` Workflow commands: ${existsSync(commandsDir) ? 'installed' : 'not installed'}`);\n console.log(` Phase skills: ${existsSync(skillsDir) ? 'installed' : 'not installed'}`);\n console.log(` Plugin manifest: ${existsSync(pluginPath) ? 'installed' : 'not installed'}`);\n\n const settingsPath = getClaudeSettingsPath(false);\n let hooksInstalled = false;\n try {\n const settings = await readClaudeSettings(settingsPath);\n hooksInstalled = hasClaudeHook(settings);\n } catch {\n // No settings\n }\n console.log(` Hooks: ${hooksInstalled ? 'installed' : 'not installed'}`);\n\n const mcpInstalled = await hasMcpServerInMcpJson(repoRoot);\n console.log(` MCP server: ${mcpInstalled ? 'installed' : 'not installed'}`);\n}\n\n/**\n * Register the one-shot setup action as the default subcommand of setup.\n * Using a default subcommand prevents its options (--uninstall, --dry-run)\n * from being consumed by the parent when other subcommands like \"claude\"\n * define the same flags.\n */\nexport function registerSetupAllCommand(setupCommand: Command): void {\n setupCommand.description('One-shot setup: init + hooks + MCP server + model');\n\n setupCommand\n .command('all', { isDefault: true })\n .description('Run full setup (default)')\n .option('--skip-model', 'Skip embedding model download')\n .option('--uninstall', 'Remove all generated files and configuration')\n .option('--update', 'Regenerate files (preserves user customizations)')\n .option('--status', 'Show installation status')\n .option('--dry-run', 'Show what would change without changing')\n .action(async (options: {\n skipModel?: boolean;\n uninstall?: boolean;\n update?: boolean;\n status?: boolean;\n dryRun?: boolean;\n }) => {\n const repoRoot = getRepoRoot();\n const dryRun = options.dryRun ?? false;\n\n if (options.uninstall) {\n const prefix = dryRun ? '[dry-run] Would have: ' : '';\n const actions = await runUninstall(repoRoot, dryRun);\n if (actions.length === 0) {\n console.log('Nothing to uninstall.');\n } else {\n for (const action of actions) {\n console.log(` ${prefix}${action}`);\n }\n out.success(dryRun ? 'Dry run complete (no changes made)' : 'Uninstall complete');\n }\n return;\n }\n\n if (options.update) {\n const result = await runUpdate(repoRoot, dryRun);\n const prefix = dryRun ? '[dry-run] ' : '';\n if (result.updated === 0 && result.added === 0) {\n console.log(`${prefix}All generated files are up to date.`);\n } else {\n if (result.updated > 0) console.log(` ${prefix}Updated: ${result.updated} file(s)`);\n if (result.added > 0) console.log(` ${prefix}Added: ${result.added} file(s)`);\n }\n if (result.skipped > 0) console.log(` Skipped: ${result.skipped} user-customized file(s)`);\n return;\n }\n\n if (options.status) {\n await runStatus(repoRoot);\n return;\n }\n\n // Default: full setup\n const result = await runSetup({ skipModel: options.skipModel });\n\n out.success('Compound agent setup complete');\n console.log(` Lessons directory: ${result.lessonsDir}`);\n console.log(` AGENTS.md: ${result.agentsMd ? 'Updated' : 'Already configured'}`);\n console.log(` Claude hooks: ${result.hooks ? 'Installed' : 'Already configured'}`);\n console.log(` MCP server: ${result.mcpServer ? 'Registered in .mcp.json' : 'Already configured'}`);\n switch (result.model) {\n case 'skipped':\n console.log(' Model: Skipped (--skip-model)');\n break;\n case 'downloaded':\n console.log(' Model: Downloaded');\n break;\n case 'already_exists':\n console.log(' Model: Already exists');\n break;\n case 'failed':\n console.log(' Model: Download failed (run `ca download-model` manually)');\n break;\n }\n console.log('');\n console.log('Next steps:');\n console.log(' 1. Restart Claude Code to load MCP tools');\n console.log(' 2. Use `memory_search` and `memory_capture` tools');\n });\n}\n","/**\n * Standardized CLI error/warning/info format helpers.\n *\n * Format:\n * ERROR [command] CODE: message — remediation\n * WARN [command] CODE: message — suggestion\n * INFO [command]: message\n */\n\n/**\n * Format an error message with command, code, message, and remediation.\n *\n * @param command - CLI command name (e.g., \"search\", \"learn\")\n * @param code - Error code (e.g., \"INVALID_LIMIT\", \"FILE_NOT_FOUND\")\n * @param message - Human-readable error description\n * @param remediation - How to fix the error\n * @returns Formatted error string\n */\nexport function formatError(command: string, code: string, message: string, remediation: string): string {\n return `ERROR [${command}] ${code}: ${message} \\u2014 ${remediation}`;\n}\n\n/**\n * Format a warning message with command, code, message, and optional suggestion.\n *\n * @param command - CLI command name\n * @param code - Warning code\n * @param message - Human-readable warning description\n * @param suggestion - Optional suggestion for resolution\n * @returns Formatted warning string\n */\nexport function formatWarn(command: string, code: string, message: string, suggestion?: string): string {\n const base = `WARN [${command}] ${code}: ${message}`;\n return suggestion ? `${base} \\u2014 ${suggestion}` : base;\n}\n\n/**\n * Format an informational message with command and message.\n *\n * @param command - CLI command name\n * @param message - Human-readable info message\n * @returns Formatted info string\n */\nexport function formatInfo(command: string, message: string): string {\n return `INFO [${command}]: ${message}`;\n}\n","/**\n * Setup Claude command - Configure Claude Code SessionStart hooks.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { formatError } from '../cli-error-format.js';\nimport { out } from '../commands/index.js';\nimport { getRepoRoot } from '../cli-utils.js';\nimport {\n addCompoundAgentHook,\n getClaudeSettingsPath,\n getMcpJsonPath,\n hasClaudeHook,\n hasMcpServerInMcpJson,\n readClaudeSettings,\n removeAgentsSection,\n removeClaudeMdReference,\n removeCompoundAgentHook,\n removeMcpServerFromMcpJson,\n writeClaudeSettings,\n} from './claude-helpers.js';\n\n/** Status check result */\ninterface StatusResult {\n settingsFile: string;\n mcpFile: string;\n exists: boolean;\n validJson: boolean;\n hookInstalled: boolean;\n mcpInstalled: boolean;\n slashCommands: {\n learn: boolean;\n search: boolean;\n };\n status: 'connected' | 'partial' | 'disconnected';\n}\n\n// ============================================================================\n// Action helpers\n// ============================================================================\n\nasync function handleStatus(\n alreadyInstalled: boolean,\n displayPath: string,\n settingsPath: string,\n options: { json?: boolean }\n): Promise<void> {\n const repoRoot = getRepoRoot();\n const learnMdPath = join(repoRoot, '.claude', 'commands', 'learn.md');\n const searchMdPath = join(repoRoot, '.claude', 'commands', 'search.md');\n const mcpPath = getMcpJsonPath(repoRoot);\n\n const learnExists = existsSync(learnMdPath);\n const searchExists = existsSync(searchMdPath);\n const mcpExists = existsSync(mcpPath);\n const mcpInstalled = mcpExists && await hasMcpServerInMcpJson(repoRoot);\n\n let status: 'connected' | 'partial' | 'disconnected';\n if (alreadyInstalled && mcpInstalled && learnExists && searchExists) {\n status = 'connected';\n } else if (alreadyInstalled || mcpInstalled || learnExists || searchExists) {\n status = 'partial';\n } else {\n status = 'disconnected';\n }\n\n const result: StatusResult = {\n settingsFile: displayPath,\n mcpFile: '.mcp.json',\n exists: existsSync(settingsPath),\n validJson: true,\n hookInstalled: alreadyInstalled,\n mcpInstalled,\n slashCommands: { learn: learnExists, search: searchExists },\n status,\n };\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log('Claude Code Integration Status');\n console.log('\\u2500'.repeat(40));\n console.log('');\n console.log(`Hooks file: ${displayPath}`);\n console.log(` ${result.exists ? '[ok]' : '[missing]'} File exists`);\n console.log(` ${result.validJson ? '[ok]' : '[error]'} Valid JSON`);\n console.log(` ${result.hookInstalled ? '[ok]' : '[warn]'} SessionStart hook installed`);\n console.log('');\n console.log('MCP config: .mcp.json');\n console.log(` ${mcpExists ? '[ok]' : '[missing]'} File exists`);\n console.log(` ${mcpInstalled ? '[ok]' : '[warn]'} compound-agent MCP server`);\n console.log('');\n console.log('Slash commands:');\n console.log(` ${learnExists ? '[ok]' : '[warn]'} /learn command`);\n console.log(` ${searchExists ? '[ok]' : '[warn]'} /search command`);\n console.log('');\n\n if (status === 'connected') {\n out.success('All checks passed. Integration is connected.');\n } else if (status === 'partial') {\n out.warn('Partial setup detected.');\n console.log('');\n console.log(\"Run 'npx ca setup' to complete setup.\");\n } else {\n out.error('Not connected.');\n console.log('');\n console.log(\"Run 'npx ca setup' to set up Compound Agent.\");\n }\n}\n\nasync function handleUninstall(\n settings: Record<string, unknown>,\n settingsPath: string,\n alreadyInstalled: boolean,\n displayPath: string,\n options: { global?: boolean; dryRun?: boolean; json?: boolean }\n): Promise<void> {\n const repoRoot = getRepoRoot();\n\n if (options.dryRun) {\n if (options.json) {\n console.log(JSON.stringify({ dryRun: true, wouldRemove: alreadyInstalled, location: displayPath }));\n } else {\n if (alreadyInstalled) {\n console.log(`Would remove compound-agent hooks from ${displayPath}`);\n } else {\n console.log('No compound-agent hooks to remove');\n }\n }\n return;\n }\n\n const removedHook = removeCompoundAgentHook(settings);\n if (removedHook) {\n await writeClaudeSettings(settingsPath, settings);\n }\n\n const removedMcp = await removeMcpServerFromMcpJson(repoRoot);\n const removedAgents = await removeAgentsSection(repoRoot);\n const removedClaudeMd = await removeClaudeMdReference(repoRoot);\n\n const anyRemoved = removedHook || removedMcp || removedAgents || removedClaudeMd;\n\n if (anyRemoved) {\n if (options.json) {\n console.log(JSON.stringify({\n installed: false,\n location: displayPath,\n action: 'removed',\n mcpRemoved: removedMcp,\n agentsMdRemoved: removedAgents,\n claudeMdRemoved: removedClaudeMd,\n }));\n } else {\n out.success('Compound agent removed');\n if (removedHook) console.log(` Hooks: ${displayPath}`);\n if (removedMcp) console.log(' MCP: .mcp.json');\n if (removedAgents) console.log(' AGENTS.md: Compound Agent section removed');\n if (removedClaudeMd) console.log(' CLAUDE.md: Compound Agent reference removed');\n }\n } else {\n if (options.json) {\n console.log(JSON.stringify({ installed: false, location: displayPath, action: 'unchanged' }));\n } else {\n out.info('No compound agent hooks to remove');\n if (options.global) {\n console.log(' Hint: Try without --global to check project settings.');\n } else {\n console.log(' Hint: Try with --global flag to check global settings.');\n }\n }\n }\n}\n\nasync function handleInstall(\n settings: Record<string, unknown>,\n settingsPath: string,\n alreadyInstalled: boolean,\n displayPath: string,\n options: { global?: boolean; dryRun?: boolean; json?: boolean }\n): Promise<void> {\n if (options.dryRun) {\n if (options.json) {\n console.log(JSON.stringify({ dryRun: true, wouldInstall: !alreadyInstalled, location: displayPath }));\n } else {\n if (alreadyInstalled) {\n console.log('Compound agent hooks already installed');\n } else {\n console.log(`Would install compound-agent hooks to ${displayPath}`);\n }\n }\n return;\n }\n\n if (alreadyInstalled) {\n if (options.json) {\n console.log(JSON.stringify({\n installed: true,\n location: displayPath,\n hooks: ['SessionStart'],\n action: 'unchanged',\n }));\n } else {\n out.info('Compound agent hooks already installed');\n console.log(` Location: ${displayPath}`);\n }\n return;\n }\n\n const fileExists = existsSync(settingsPath);\n addCompoundAgentHook(settings);\n await writeClaudeSettings(settingsPath, settings);\n\n if (options.json) {\n console.log(JSON.stringify({\n installed: true,\n location: displayPath,\n hooks: ['SessionStart'],\n action: fileExists ? 'updated' : 'created',\n }));\n } else {\n out.success(options.global ? 'Claude Code hooks installed (global)' : 'Claude Code hooks installed (project-level)');\n console.log(` Location: ${displayPath}`);\n console.log(' Hook: SessionStart (startup|resume|compact)');\n console.log('');\n console.log('Lessons will be loaded automatically at session start.');\n if (!options.global) {\n console.log('');\n console.log('Note: Project hooks override global hooks.');\n }\n }\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register the claude subcommand on an existing setup command.\n */\nexport function registerClaudeSubcommand(setupCommand: Command): void {\n setupCommand\n .command('claude')\n .description('Install Claude Code SessionStart hooks')\n .option('--global', 'Install to global ~/.claude/ instead of project')\n .option('--uninstall', 'Remove compound-agent hooks')\n .option('--status', 'Check status of Claude Code integration')\n .option('--dry-run', 'Show what would change without writing')\n .option('--json', 'Output as JSON')\n .action(async (options: { global?: boolean; uninstall?: boolean; status?: boolean; dryRun?: boolean; json?: boolean }) => {\n const settingsPath = getClaudeSettingsPath(options.global ?? false);\n const displayPath = options.global ? '~/.claude/settings.json' : '.claude/settings.json';\n\n let settings: Record<string, unknown>;\n try {\n settings = await readClaudeSettings(settingsPath);\n } catch {\n if (options.json) {\n console.log(JSON.stringify({ error: 'Failed to parse settings file' }));\n } else {\n console.error(formatError('setup', 'PARSE_ERROR', 'Failed to parse settings file', 'Check if JSON is valid'));\n }\n process.exit(1);\n }\n\n const alreadyInstalled = hasClaudeHook(settings);\n\n if (options.status) {\n await handleStatus(alreadyInstalled, displayPath, settingsPath, options);\n } else if (options.uninstall) {\n await handleUninstall(settings, settingsPath, alreadyInstalled, displayPath, options);\n } else {\n await handleInstall(settings, settingsPath, alreadyInstalled, displayPath, options);\n }\n });\n}\n","/**\n * Download-model command - Download the embedding model for semantic search.\n */\n\nimport { statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { formatBytes } from '../cli-utils.js';\nimport { isModelAvailable, MODEL_FILENAME, resolveModel } from '../memory/embeddings/index.js';\n\n/**\n * Register the download-model command on the program.\n */\nexport function registerDownloadModelCommand(program: Command): void {\n program\n .command('download-model')\n .description('Download the embedding model for semantic search')\n .option('--json', 'Output as JSON')\n .action(async (options: { json?: boolean }) => {\n const alreadyExisted = isModelAvailable();\n\n if (alreadyExisted) {\n // Model already exists - get path and size\n const modelPath = join(homedir(), '.node-llama-cpp', 'models', MODEL_FILENAME);\n const size = statSync(modelPath).size;\n\n if (options.json) {\n console.log(JSON.stringify({ success: true, path: modelPath, size, alreadyExisted: true }));\n } else {\n console.log('Model already exists.');\n console.log(`Path: ${modelPath}`);\n console.log(`Size: ${formatBytes(size)}`);\n }\n return;\n }\n\n // Download the model\n if (!options.json) {\n console.log('Downloading embedding model...');\n }\n\n const modelPath = await resolveModel({ cli: !options.json });\n const size = statSync(modelPath).size;\n\n if (options.json) {\n console.log(JSON.stringify({ success: true, path: modelPath, size, alreadyExisted: false }));\n } else {\n console.log(`\\nModel downloaded successfully!`);\n console.log(`Path: ${modelPath}`);\n console.log(`Size: ${formatBytes(size)}`);\n }\n });\n}\n","/**\n * Hooks command - Git hooks management.\n */\n\nimport { chmodSync, existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { formatError } from '../cli-error-format.js';\nimport {\n HOOK_MARKER,\n COMPOUND_AGENT_HOOK_BLOCK,\n PRE_COMMIT_HOOK_TEMPLATE,\n PRE_COMMIT_MESSAGE,\n} from './templates.js';\n\n/** Make hook file executable (mode 0o755) */\nconst HOOK_FILE_MODE = 0o755;\n\n/**\n * Result of pre-commit hook installation.\n * Discriminated union for clear status messages.\n */\nexport type HookInstallResult =\n | { status: 'installed' }\n | { status: 'already_installed' }\n | { status: 'not_git_repo' }\n | { status: 'appended' };\n\n// ============================================================================\n// UserPromptSubmit Hook: Gentle memory tool reminders\n// ============================================================================\n\n/** Patterns that suggest user is correcting Claude */\nconst CORRECTION_PATTERNS = [\n /\\bactually\\b/i,\n /\\bno[,.]?\\s/i,\n /\\bwrong\\b/i,\n /\\bthat'?s not right\\b/i,\n /\\bthat'?s incorrect\\b/i,\n /\\buse .+ instead\\b/i,\n /\\bi told you\\b/i,\n /\\bi already said\\b/i,\n /\\bnot like that\\b/i,\n /\\byou forgot\\b/i,\n /\\byou missed\\b/i,\n /\\bstop\\s*(,\\s*)?(doing|using|that)\\b/i,\n /\\bwait\\s*(,\\s*)?(that|no|wrong)\\b/i,\n];\n\n/** High-confidence planning patterns (single match sufficient) */\nconst HIGH_CONFIDENCE_PLANNING = [\n /\\bdecide\\b/i,\n /\\bchoose\\b/i,\n /\\bpick\\b/i,\n /\\bwhich approach\\b/i,\n /\\bwhat do you think\\b/i,\n /\\bshould we\\b/i,\n /\\bwould you\\b/i,\n /\\bhow should\\b/i,\n /\\bwhat'?s the best\\b/i,\n /\\badd feature\\b/i,\n /\\bset up\\b/i,\n];\n\n/** Low-confidence planning patterns (need 2+ matches) */\nconst LOW_CONFIDENCE_PLANNING = [\n /\\bimplement\\b/i,\n /\\bbuild\\b/i,\n /\\bcreate\\b/i,\n /\\brefactor\\b/i,\n /\\bfix\\b/i,\n /\\bwrite\\b/i,\n /\\bdevelop\\b/i,\n];\n\n/** Reminder messages */\nconst CORRECTION_REMINDER =\n 'Remember: You have memory tools available - memory_capture to save insights, memory_search to find past solutions.';\n\nconst PLANNING_REMINDER =\n 'If you\\'re uncertain or hesitant, remember your memory tools: memory_search may have relevant context from past sessions.';\n\n/** Check if prompt matches correction patterns */\nexport function detectCorrection(prompt: string): boolean {\n return CORRECTION_PATTERNS.some((pattern) => pattern.test(prompt));\n}\n\n/** Check if prompt matches planning patterns */\nexport function detectPlanning(prompt: string): boolean {\n if (HIGH_CONFIDENCE_PLANNING.some((pattern) => pattern.test(prompt))) {\n return true;\n }\n const lowMatches = LOW_CONFIDENCE_PLANNING.filter((pattern) => pattern.test(prompt));\n return lowMatches.length >= 2;\n}\n\n/**\n * UserPromptSubmit hook output format.\n * Claude Code expects this structure for additionalContext injection.\n */\nexport interface UserPromptHookOutput {\n hookSpecificOutput?: {\n hookEventName: 'UserPromptSubmit';\n additionalContext?: string;\n };\n}\n\n/**\n * Process a user prompt and determine if a reminder should be injected.\n *\n * @param prompt - The user's message text\n * @returns Hook output with optional additionalContext\n */\nexport function processUserPrompt(prompt: string): UserPromptHookOutput {\n // Priority: corrections first, then planning\n if (detectCorrection(prompt)) {\n return {\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: CORRECTION_REMINDER,\n },\n };\n }\n\n if (detectPlanning(prompt)) {\n return {\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: PLANNING_REMINDER,\n },\n };\n }\n\n // No reminder needed\n return {};\n}\n\n// ============================================================================\n// PostToolUseFailure Hook: In-memory failure tracking with memory tip\n// ============================================================================\n\n/** Threshold constants */\nconst SAME_TARGET_THRESHOLD = 2;\nconst TOTAL_FAILURE_THRESHOLD = 3;\n\n/** In-memory failure counters */\nlet failureCount = 0;\nlet lastFailedTarget: string | null = null;\nlet sameTargetCount = 0;\n\n/** Tip message for failures */\nconst FAILURE_TIP = 'Tip: Multiple failures detected. memory_search may have solutions for similar issues.';\n\n/**\n * PostToolUseFailure hook output format.\n */\nexport interface PostToolFailureHookOutput {\n hookSpecificOutput?: {\n hookEventName: 'PostToolUseFailure';\n additionalContext?: string;\n };\n}\n\n/** Reset failure state (exported for testing) */\nexport function resetFailureState(): void {\n failureCount = 0;\n lastFailedTarget = null;\n sameTargetCount = 0;\n}\n\n/** Extract a failure target from tool name and input */\nfunction getFailureTarget(toolName: string, toolInput: Record<string, unknown>): string | null {\n if (toolName === 'Bash' && typeof toolInput.command === 'string') {\n const trimmed = toolInput.command.trim();\n const firstSpace = trimmed.indexOf(' ');\n return firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace);\n }\n if ((toolName === 'Edit' || toolName === 'Write') && typeof toolInput.file_path === 'string') {\n return toolInput.file_path;\n }\n return null;\n}\n\n/**\n * Process a tool failure and determine if a tip should be shown.\n */\nexport function processToolFailure(\n toolName: string,\n toolInput: Record<string, unknown>\n): PostToolFailureHookOutput {\n failureCount++;\n const target = getFailureTarget(toolName, toolInput);\n if (target !== null && target === lastFailedTarget) {\n sameTargetCount++;\n } else {\n sameTargetCount = 1;\n lastFailedTarget = target;\n }\n const shouldShowTip =\n sameTargetCount >= SAME_TARGET_THRESHOLD ||\n failureCount >= TOTAL_FAILURE_THRESHOLD;\n if (shouldShowTip) {\n resetFailureState();\n return {\n hookSpecificOutput: {\n hookEventName: 'PostToolUseFailure',\n additionalContext: FAILURE_TIP,\n },\n };\n }\n return {};\n}\n\n/**\n * Process a tool success - clear failure state.\n */\nexport function processToolSuccess(): void {\n resetFailureState();\n}\n\n/**\n * Check if a pre-commit hook already exists with our marker.\n */\nfunction hasCompoundAgentHook(content: string): boolean {\n return content.includes(HOOK_MARKER);\n}\n\n/**\n * Get the git hooks directory, respecting core.hooksPath if set.\n */\nasync function getGitHooksDir(repoRoot: string): Promise<string | null> {\n const gitDir = join(repoRoot, '.git');\n\n // Check if .git directory exists\n if (!existsSync(gitDir)) {\n return null;\n }\n\n // Check for core.hooksPath in .git/config\n const configPath = join(gitDir, 'config');\n if (existsSync(configPath)) {\n const config = await readFile(configPath, 'utf-8');\n const match = /hooksPath\\s*=\\s*(.+)$/m.exec(config);\n if (match?.[1]) {\n const hooksPath = match[1].trim();\n // Resolve relative paths from repo root\n return hooksPath.startsWith('/') ? hooksPath : join(repoRoot, hooksPath);\n }\n }\n\n // Default to .git/hooks\n const defaultHooksDir = join(gitDir, 'hooks');\n return existsSync(defaultHooksDir) ? defaultHooksDir : null;\n}\n\n/**\n * Find the line index of the first top-level exit statement in a shell script.\n *\n * Top-level means not inside:\n * - Function definitions (between { and })\n * - Heredocs (between <<EOF and EOF)\n *\n * Returns -1 if no top-level exit found.\n */\nexport function findFirstTopLevelExitLine(lines: string[]): number {\n let insideFunction = 0; // Brace nesting depth\n let heredocDelimiter: string | null = null;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const trimmed = line.trim();\n\n // Check for heredoc end\n if (heredocDelimiter !== null) {\n if (trimmed === heredocDelimiter) {\n heredocDelimiter = null;\n }\n continue;\n }\n\n // Check for heredoc start: <<EOF, <<'EOF', <<\"EOF\", <<-EOF\n const heredocMatch = /<<-?\\s*['\"]?(\\w+)['\"]?/.exec(line);\n if (heredocMatch?.[1]) {\n heredocDelimiter = heredocMatch[1];\n continue;\n }\n\n // Track function braces (simple heuristic)\n // Count opening and closing braces\n for (const char of line) {\n if (char === '{') insideFunction++;\n if (char === '}') insideFunction = Math.max(0, insideFunction - 1);\n }\n\n // Skip if inside function\n if (insideFunction > 0) {\n continue;\n }\n\n // Check for top-level exit: exit followed by number, $var, or $?\n // Pattern: start of line, optional whitespace, exit, space, code, end\n if (/^\\s*exit\\s+(\\d+|\\$\\w+|\\$\\?)\\s*$/.test(trimmed)) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Install pre-commit hook, respecting core.hooksPath and existing hooks.\n *\n * - Respects core.hooksPath when configured\n * - Appends to existing hooks instead of overwriting\n * - Uses marker to ensure idempotency\n *\n * @returns Discriminated union indicating the installation result\n */\nexport async function installPreCommitHook(repoRoot: string): Promise<HookInstallResult> {\n const gitHooksDir = await getGitHooksDir(repoRoot);\n\n // Not a git repo or no hooks directory\n if (!gitHooksDir) {\n return { status: 'not_git_repo' };\n }\n\n // Ensure hooks directory exists\n await mkdir(gitHooksDir, { recursive: true });\n\n const hookPath = join(gitHooksDir, 'pre-commit');\n\n // Check if hook already exists\n if (existsSync(hookPath)) {\n const content = await readFile(hookPath, 'utf-8');\n if (hasCompoundAgentHook(content)) {\n return { status: 'already_installed' };\n }\n\n // Find insertion point: before first top-level exit, or at end\n const lines = content.split('\\n');\n const exitLineIndex = findFirstTopLevelExitLine(lines);\n\n let newContent: string;\n if (exitLineIndex === -1) {\n // No top-level exit found - append to end\n newContent = content.trimEnd() + '\\n' + COMPOUND_AGENT_HOOK_BLOCK;\n } else {\n // Insert before the exit line\n const before = lines.slice(0, exitLineIndex);\n const after = lines.slice(exitLineIndex);\n newContent = before.join('\\n') + COMPOUND_AGENT_HOOK_BLOCK + after.join('\\n');\n }\n\n await writeFile(hookPath, newContent, 'utf-8');\n chmodSync(hookPath, HOOK_FILE_MODE);\n return { status: 'appended' };\n }\n\n // Create new hook file with full template\n await writeFile(hookPath, PRE_COMMIT_HOOK_TEMPLATE, 'utf-8');\n chmodSync(hookPath, HOOK_FILE_MODE);\n\n return { status: 'installed' };\n}\n\n/**\n * Read stdin as a string.\n */\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString('utf-8');\n}\n\n/**\n * Run the UserPromptSubmit hook.\n * Reads JSON from stdin, processes the prompt, outputs hook result.\n */\nasync function runUserPromptHook(): Promise<void> {\n try {\n const input = await readStdin();\n const data = JSON.parse(input) as { prompt?: string };\n\n if (!data.prompt) {\n // No prompt provided, exit silently\n console.log(JSON.stringify({}));\n return;\n }\n\n const result = processUserPrompt(data.prompt);\n console.log(JSON.stringify(result));\n } catch {\n // On any error, exit silently with empty output\n console.log(JSON.stringify({}));\n }\n}\n\n/**\n * Run the PostToolUseFailure hook.\n * Reads JSON from stdin, tracks failure, outputs tip if threshold reached.\n */\nasync function runPostToolFailureHook(): Promise<void> {\n try {\n const input = await readStdin();\n const data = JSON.parse(input) as {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n };\n\n if (!data.tool_name) {\n console.log(JSON.stringify({}));\n return;\n }\n\n const result = processToolFailure(data.tool_name, data.tool_input ?? {});\n console.log(JSON.stringify(result));\n } catch {\n console.log(JSON.stringify({}));\n }\n}\n\n/**\n * Run the PostToolUse hook for success.\n * Reads JSON from stdin, clears failure state.\n */\nasync function runPostToolSuccessHook(): Promise<void> {\n try {\n await readStdin();\n processToolSuccess();\n console.log(JSON.stringify({}));\n } catch {\n console.log(JSON.stringify({}));\n }\n}\n\n/**\n * Register the hooks command on the program.\n */\nexport function registerHooksCommand(program: Command): void {\n const hooksCommand = program.command('hooks').description('Git hooks management');\n\n hooksCommand\n .command('run <hook>')\n .description('Run a hook script (called by git/Claude hooks)')\n .option('--json', 'Output as JSON')\n .action(async (hook: string, options: { json?: boolean }) => {\n if (hook === 'pre-commit') {\n if (options.json) {\n console.log(JSON.stringify({ hook: 'pre-commit', message: PRE_COMMIT_MESSAGE }));\n } else {\n console.log(PRE_COMMIT_MESSAGE);\n }\n } else if (hook === 'user-prompt') {\n // UserPromptSubmit hook - reads from stdin, outputs JSON\n await runUserPromptHook();\n } else if (hook === 'post-tool-failure') {\n // PostToolUseFailure hook - tracks failures, outputs tip if threshold\n await runPostToolFailureHook();\n } else if (hook === 'post-tool-success') {\n // PostToolUse hook - clears failure state on success\n await runPostToolSuccessHook();\n } else {\n if (options.json) {\n console.log(JSON.stringify({ error: `Unknown hook: ${hook}` }));\n } else {\n console.error(formatError('hooks', 'UNKNOWN_HOOK', `Unknown hook: ${hook}`, 'Valid hooks: pre-session, post-tool-failure, post-tool-success'));\n }\n process.exit(1);\n }\n });\n}\n","/**\n * Init command - Initialize compound-agent in a repository.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { LESSONS_PATH } from '../memory/storage/index.js';\nimport { getGlobalOpts, out } from '../commands/index.js';\nimport { installClaudeHooksForInit } from './claude-helpers.js';\nimport { installPreCommitHook, type HookInstallResult } from './hooks.js';\nimport {\n createPluginManifest,\n createSlashCommands,\n ensureClaudeMdReference,\n installAgentTemplates,\n installPhaseSkills,\n installWorkflowCommands,\n updateAgentsMd,\n} from './primitives.js';\nimport type { ClaudeHooksResult } from './types.js';\n\n/**\n * Create the lessons directory structure.\n */\nasync function createLessonsDirectory(repoRoot: string): Promise<void> {\n const lessonsDir = dirname(join(repoRoot, LESSONS_PATH));\n await mkdir(lessonsDir, { recursive: true });\n}\n\n/**\n * Create empty index.jsonl if it doesn't exist.\n */\nasync function createIndexFile(repoRoot: string): Promise<void> {\n const indexPath = join(repoRoot, LESSONS_PATH);\n if (!existsSync(indexPath)) {\n await writeFile(indexPath, '', 'utf-8');\n }\n}\n\n// ============================================================================\n// Action Handler\n// ============================================================================\n\nasync function initAction(\n cmd: Command,\n options: { skipAgents?: boolean; skipHooks?: boolean; skipClaude?: boolean; json?: boolean }\n): Promise<void> {\n const repoRoot = getRepoRoot();\n const { quiet } = getGlobalOpts(cmd);\n\n await createLessonsDirectory(repoRoot);\n await createIndexFile(repoRoot);\n const lessonsDir = dirname(join(repoRoot, LESSONS_PATH));\n\n let agentsMdUpdated = false;\n if (!options.skipAgents) {\n agentsMdUpdated = await updateAgentsMd(repoRoot);\n }\n\n if (!options.skipAgents) {\n await ensureClaudeMdReference(repoRoot);\n }\n\n let slashCommandsCreated = false;\n if (!options.skipAgents) {\n slashCommandsCreated = await createSlashCommands(repoRoot);\n }\n\n if (!options.skipAgents) {\n await createPluginManifest(repoRoot);\n await installAgentTemplates(repoRoot);\n await installWorkflowCommands(repoRoot);\n await installPhaseSkills(repoRoot);\n }\n\n let hookResult: HookInstallResult | null = null;\n if (!options.skipHooks) {\n hookResult = await installPreCommitHook(repoRoot);\n }\n\n let claudeHooksResult: ClaudeHooksResult = { installed: false, action: 'error', error: 'skipped' };\n if (!options.skipClaude) {\n claudeHooksResult = await installClaudeHooksForInit(repoRoot);\n }\n\n if (options.json) {\n const claudeHooksInstalled = claudeHooksResult.action === 'installed';\n const hooksChanged = hookResult?.status === 'installed' || hookResult?.status === 'appended';\n console.log(JSON.stringify({\n initialized: true,\n lessonsDir,\n agentsMd: agentsMdUpdated,\n slashCommands: slashCommandsCreated || !options.skipAgents,\n hooks: hooksChanged,\n hookStatus: hookResult?.status ?? 'skipped',\n claudeHooks: claudeHooksInstalled,\n }));\n return;\n }\n\n if (quiet) return;\n\n out.success('Compound agent initialized');\n console.log(` Lessons directory: ${lessonsDir}`);\n printAgentsMdStatus(agentsMdUpdated, options.skipAgents);\n printSlashCommandsStatus(slashCommandsCreated, options.skipAgents);\n printHookStatus(hookResult, options.skipHooks);\n printClaudeHooksStatus(claudeHooksResult, options.skipClaude);\n}\n\nfunction printAgentsMdStatus(updated: boolean, skipped?: boolean): void {\n if (updated) {\n console.log(' AGENTS.md: Updated with Compound Agent section');\n } else if (skipped) {\n console.log(' AGENTS.md: Skipped (--skip-agents)');\n } else {\n console.log(' AGENTS.md: Already has Compound Agent section');\n }\n}\n\nfunction printSlashCommandsStatus(created: boolean, skipped?: boolean): void {\n if (created) {\n console.log(' Slash commands: Created (/learn, /show, /wrong, /stats)');\n } else if (skipped) {\n console.log(' Slash commands: Skipped (--skip-agents)');\n } else {\n console.log(' Slash commands: Already exist');\n }\n}\n\nfunction printHookStatus(hookResult: HookInstallResult | null, skipped?: boolean): void {\n if (skipped) {\n console.log(' Git hooks: Skipped (--skip-hooks)');\n } else if (hookResult?.status === 'installed') {\n console.log(' Git hooks: Installed');\n } else if (hookResult?.status === 'appended') {\n console.log(' Git hooks: Appended to existing pre-commit hook');\n } else if (hookResult?.status === 'already_installed') {\n console.log(' Git hooks: Already installed');\n } else if (hookResult?.status === 'not_git_repo') {\n console.log(' Git hooks: Skipped (not a git repository)');\n }\n}\n\nfunction printClaudeHooksStatus(result: ClaudeHooksResult, skipped?: boolean): void {\n if (skipped) {\n console.log(' Claude hooks: Skipped (--skip-claude)');\n } else if (result.action === 'installed') {\n console.log(' Claude hooks: Installed to .claude/settings.json');\n } else if (result.action === 'already_installed') {\n console.log(' Claude hooks: Already installed');\n } else if (result.error) {\n console.log(` Claude hooks: Error - ${result.error}`);\n }\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register the init command on the program.\n */\nexport function registerInitCommand(program: Command): void {\n program\n .command('init')\n .description('Initialize compound-agent in this repository')\n .option('--skip-agents', 'Skip AGENTS.md modification')\n .option('--skip-hooks', 'Skip git hooks installation')\n .option('--skip-claude', 'Skip Claude Code hooks installation')\n .option('--json', 'Output result as JSON')\n .action(async function (this: Command, options: { skipAgents?: boolean; skipHooks?: boolean; skipClaude?: boolean; json?: boolean }) {\n await initAction(this, options);\n });\n}\n","/**\n * Shared types, constants, and utilities for CLI commands.\n */\n\nimport chalk from 'chalk';\nimport type { Command } from 'commander';\n\n// Re-export centralized utilities (utils.ts remains in src/ root)\nexport { getLessonAgeDays, MS_PER_DAY } from '../utils.js';\n\n// ============================================================================\n// Output Formatting Helpers\n// ============================================================================\n\n/** Output helper functions for consistent formatting */\nexport const out = {\n success: (msg: string): void => console.log(chalk.green('[ok]'), msg),\n error: (msg: string): void => console.error(chalk.red('[error]'), msg),\n info: (msg: string): void => console.log(chalk.blue('[info]'), msg),\n warn: (msg: string): void => console.log(chalk.yellow('[warn]'), msg),\n};\n\n/** Global options interface */\nexport interface GlobalOpts {\n verbose: boolean;\n quiet: boolean;\n}\n\n/**\n * Get global options from command.\n */\nexport function getGlobalOpts(cmd: Command): GlobalOpts {\n const opts = cmd.optsWithGlobals() as { verbose?: boolean; quiet?: boolean };\n return {\n verbose: opts.verbose ?? false,\n quiet: opts.quiet ?? false,\n };\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Default limit for search results */\nexport const DEFAULT_SEARCH_LIMIT = '10';\n\n/** Default limit for list results */\nexport const DEFAULT_LIST_LIMIT = '20';\n\n/** Default limit for search results */\nexport const DEFAULT_CHECK_PLAN_LIMIT = '5';\n\n/** Threshold for lesson count warning (context pollution prevention) */\nexport const LESSON_COUNT_WARNING_THRESHOLD = 20;\n\n/** Age threshold in days for flagging old lessons */\nexport const AGE_FLAG_THRESHOLD_DAYS = 90;\n\n/** Length of ISO date prefix (YYYY-MM-DD) */\nexport const ISO_DATE_PREFIX_LENGTH = 10;\n\n/** Decimal places for average calculations */\nexport const AVG_DECIMAL_PLACES = 1;\n\n/** Decimal places for relevance scores */\nexport const RELEVANCE_DECIMAL_PLACES = 2;\n\n/** Indentation for JSON pretty-printing */\nexport const JSON_INDENT_SPACES = 2;\n","/**\n * Helper functions for management commands.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { LESSONS_PATH } from '../memory/storage/index.js';\nimport type { MemoryItem } from '../memory/index.js';\n\n/**\n * Format a memory item for human-readable display.\n */\nexport function formatLessonHuman(lesson: MemoryItem): string {\n const lines: string[] = [];\n\n lines.push(`ID: ${lesson.id}`);\n lines.push(`Type: ${lesson.type}`);\n lines.push(`Trigger: ${lesson.trigger}`);\n lines.push(`Insight: ${lesson.insight}`);\n\n if (lesson.evidence) {\n lines.push(`Evidence: ${lesson.evidence}`);\n }\n\n if (lesson.severity) {\n lines.push(`Severity: ${lesson.severity}`);\n }\n\n lines.push(`Tags: ${lesson.tags.length > 0 ? lesson.tags.join(', ') : '(none)'}`);\n lines.push(`Source: ${lesson.source}`);\n\n if (lesson.context) {\n lines.push(`Context: ${lesson.context.tool} - ${lesson.context.intent}`);\n }\n\n lines.push(`Created: ${lesson.created}`);\n lines.push(`Confirmed: ${lesson.confirmed ? 'yes' : 'no'}`);\n\n if (lesson.supersedes && lesson.supersedes.length > 0) {\n lines.push(`Supersedes: ${lesson.supersedes.join(', ')}`);\n }\n\n if (lesson.related && lesson.related.length > 0) {\n lines.push(`Related: ${lesson.related.join(', ')}`);\n }\n\n if (lesson.pattern) {\n lines.push('Pattern:');\n lines.push(` Bad: ${lesson.pattern.bad}`);\n lines.push(` Good: ${lesson.pattern.good}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Check if a lesson ID has been deleted (has a tombstone).\n */\nexport async function wasLessonDeleted(repoRoot: string, id: string): Promise<boolean> {\n const filePath = join(repoRoot, LESSONS_PATH);\n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const record = JSON.parse(trimmed) as { id: string; deleted?: boolean };\n if (record.id === id && record.deleted === true) {\n return true;\n }\n } catch {\n // Skip invalid lines\n }\n }\n } catch {\n // File doesn't exist\n }\n return false;\n}\n","/**\n * CRUD commands: show, update, delete\n *\n * Commands for reading, updating, and deleting lessons.\n */\n\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { appendMemoryItem, readMemoryItems, syncIfNeeded } from '../memory/storage/index.js';\nimport { MemoryItemSchema, SeveritySchema } from '../memory/index.js';\nimport type { MemoryItem, Severity } from '../memory/index.js';\n\nimport { formatError } from '../cli-error-format.js';\n\nimport { out } from './shared.js';\nimport { formatLessonHuman, wasLessonDeleted } from './management-helpers.js';\n\n/** JSON indentation for show output */\nconst SHOW_JSON_INDENT = 2;\n\n// ============================================================================\n// Action Handlers\n// ============================================================================\n\nasync function showAction(id: string, options: { json?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n\n const { items } = await readMemoryItems(repoRoot);\n const item = items.find((i) => i.id === id);\n\n if (!item) {\n const wasDeleted = await wasLessonDeleted(repoRoot, id);\n\n if (options.json) {\n console.log(JSON.stringify({ error: wasDeleted ? `Lesson ${id} not found (deleted)` : `Lesson ${id} not found` }));\n } else {\n const msg = wasDeleted ? `Lesson ${id} not found (deleted)` : `Lesson ${id} not found`;\n console.error(formatError('show', 'NOT_FOUND', msg, 'Use \"ca list\" to see available lessons'));\n }\n process.exit(1);\n }\n\n if (options.json) {\n console.log(JSON.stringify(item, null, SHOW_JSON_INDENT));\n } else {\n console.log(formatLessonHuman(item));\n }\n}\n\ninterface UpdateOptions {\n insight?: string;\n trigger?: string;\n evidence?: string;\n severity?: string;\n tags?: string;\n confirmed?: string;\n json?: boolean;\n}\n\nfunction buildUpdatedItem(item: MemoryItem, options: UpdateOptions): MemoryItem {\n return {\n ...item,\n ...(options.insight !== undefined && { insight: options.insight }),\n ...(options.trigger !== undefined && { trigger: options.trigger }),\n ...(options.evidence !== undefined && { evidence: options.evidence }),\n ...(options.severity !== undefined && { severity: options.severity as Severity }),\n ...(options.tags !== undefined && {\n tags: [...new Set(\n options.tags\n .split(',')\n .map((t) => t.trim())\n .filter((t) => t.length > 0)\n )],\n }),\n ...(options.confirmed !== undefined && { confirmed: options.confirmed === 'true' }),\n };\n}\n\nasync function updateAction(id: string, options: UpdateOptions): Promise<void> {\n const repoRoot = getRepoRoot();\n\n const hasUpdates = options.insight !== undefined\n || options.trigger !== undefined\n || options.evidence !== undefined\n || options.severity !== undefined\n || options.tags !== undefined\n || options.confirmed !== undefined;\n\n if (!hasUpdates) {\n if (options.json) {\n console.log(JSON.stringify({ error: 'No fields to update (specify at least one: --insight, --tags, --severity, ...)' }));\n } else {\n console.error(formatError('update', 'NO_FIELDS', 'No fields to update', 'Specify at least one: --insight, --tags, --severity, ...'));\n }\n process.exit(1);\n }\n\n const { items } = await readMemoryItems(repoRoot);\n const item = items.find((i) => i.id === id);\n\n if (!item) {\n const wasDeleted = await wasLessonDeleted(repoRoot, id);\n if (options.json) {\n console.log(JSON.stringify({ error: wasDeleted ? `Lesson ${id} is deleted` : `Lesson ${id} not found` }));\n } else {\n const msg = wasDeleted ? `Lesson ${id} is deleted` : `Lesson ${id} not found`;\n console.error(formatError('update', 'NOT_FOUND', msg, 'Use \"ca list\" to see available lessons'));\n }\n process.exit(1);\n }\n\n if (options.severity !== undefined) {\n const result = SeveritySchema.safeParse(options.severity);\n if (!result.success) {\n if (options.json) {\n console.log(JSON.stringify({ error: `Invalid severity '${options.severity}' (must be: high, medium, low)` }));\n } else {\n console.error(formatError('update', 'INVALID_SEVERITY', `Invalid severity: \"${options.severity}\"`, 'Use --severity high|medium|low'));\n }\n process.exit(1);\n }\n }\n\n const updatedItem = buildUpdatedItem(item, options);\n\n const validationResult = MemoryItemSchema.safeParse(updatedItem);\n if (!validationResult.success) {\n if (options.json) {\n console.log(JSON.stringify({ error: `Schema validation failed: ${validationResult.error.message}` }));\n } else {\n console.error(formatError('update', 'VALIDATION_FAILED', `Schema validation failed: ${validationResult.error.message}`, 'Check field values and try again'));\n }\n process.exit(1);\n }\n\n await appendMemoryItem(repoRoot, updatedItem);\n await syncIfNeeded(repoRoot);\n\n if (options.json) {\n console.log(JSON.stringify(updatedItem, null, SHOW_JSON_INDENT));\n } else {\n out.success(`Updated lesson ${id}`);\n }\n}\n\nasync function deleteAction(ids: string[], options: { json?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n\n const { items } = await readMemoryItems(repoRoot);\n const itemMap = new Map(items.map((i) => [i.id, i]));\n\n const deleted: string[] = [];\n const warnings: Array<{ id: string; message: string }> = [];\n\n for (const id of ids) {\n const item = itemMap.get(id);\n\n if (!item) {\n const wasDeleted = await wasLessonDeleted(repoRoot, id);\n warnings.push({ id, message: wasDeleted ? 'already deleted' : 'not found' });\n continue;\n }\n\n const deletedItem: MemoryItem = {\n ...item,\n deleted: true,\n deletedAt: new Date().toISOString(),\n };\n\n await appendMemoryItem(repoRoot, deletedItem);\n deleted.push(id);\n }\n\n if (deleted.length > 0) {\n await syncIfNeeded(repoRoot);\n }\n\n if (options.json) {\n console.log(JSON.stringify({ deleted, warnings }));\n } else {\n if (deleted.length > 0) {\n out.success(`Deleted ${deleted.length} lesson(s): ${deleted.join(', ')}`);\n }\n for (const warning of warnings) {\n out.warn(`${warning.id}: ${warning.message}`);\n }\n if (deleted.length === 0 && warnings.length > 0) {\n process.exit(1);\n }\n }\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register CRUD commands on the program.\n */\nexport function registerCrudCommands(program: Command): void {\n program\n .command('show <id>')\n .description('Show details of a specific lesson')\n .option('--json', 'Output as JSON')\n .action(async (id: string, options: { json?: boolean }) => {\n await showAction(id, options);\n });\n\n program\n .command('update <id>')\n .description('Update a lesson')\n .option('--insight <text>', 'Update insight')\n .option('--trigger <text>', 'Update trigger')\n .option('--evidence <text>', 'Update evidence')\n .option('--severity <level>', 'Update severity (low/medium/high)')\n .option('--tags <tags>', 'Update tags (comma-separated)')\n .option('--confirmed <bool>', 'Update confirmed status (true/false)')\n .option('--json', 'Output as JSON')\n .action(async (id: string, options: {\n insight?: string;\n trigger?: string;\n evidence?: string;\n severity?: string;\n tags?: string;\n confirmed?: string;\n json?: boolean;\n }) => {\n await updateAction(id, options);\n });\n\n program\n .command('delete <ids...>')\n .description('Soft delete lessons (creates tombstone)')\n .option('--json', 'Output as JSON')\n .action(async (ids: string[], options: { json?: boolean }) => {\n await deleteAction(ids, options);\n });\n}\n","/**\n * Invalidation commands: wrong, validate\n *\n * Commands for managing lesson validity state.\n */\n\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { appendMemoryItem, readMemoryItems } from '../memory/storage/index.js';\nimport type { MemoryItem } from '../memory/index.js';\n\nimport { formatError } from '../cli-error-format.js';\n\nimport { out } from './shared.js';\n\n/**\n * Register invalidation commands on the program.\n */\nexport function registerInvalidationCommands(program: Command): void {\n /**\n * Wrong command - Mark a lesson as invalid/wrong.\n *\n * Appends an invalidatedAt timestamp and optional reason to the lesson.\n * Invalidated lessons are excluded from retrieval but remain in storage.\n *\n * @example npx ca wrong L12345678\n * @example npx ca wrong L12345678 --reason \"This advice was incorrect\"\n */\n program\n .command('wrong <id>')\n .description('Mark a lesson as invalid/wrong')\n .option('-r, --reason <text>', 'Reason for invalidation')\n .action(async function (this: Command, id: string, options: { reason?: string }) {\n const repoRoot = getRepoRoot();\n\n // Read all lessons\n const { items } = await readMemoryItems(repoRoot);\n\n // Find the lesson\n const lesson = items.find((l) => l.id === id);\n if (!lesson) {\n console.error(formatError('wrong', 'NOT_FOUND', `Lesson not found: ${id}`, 'Use \"ca list\" to see available lessons'));\n process.exit(1);\n }\n\n // Check if already invalidated\n if (lesson.invalidatedAt) {\n out.warn(`Lesson ${id} is already marked as invalid.`);\n return;\n }\n\n // Create updated lesson with invalidation\n const updatedItem: MemoryItem = {\n ...lesson,\n invalidatedAt: new Date().toISOString(),\n ...(options.reason !== undefined && { invalidationReason: options.reason }),\n };\n\n // Append the updated lesson (JSONL append-only pattern)\n await appendMemoryItem(repoRoot, updatedItem);\n out.success(`Lesson ${id} marked as invalid.`);\n if (options.reason) {\n console.log(` Reason: ${options.reason}`);\n }\n });\n\n /**\n * Validate command - Remove invalidation from a lesson.\n *\n * Re-enables a previously invalidated lesson for retrieval.\n *\n * @example npx ca validate L12345678\n */\n program\n .command('validate <id>')\n .description('Re-enable a previously invalidated lesson')\n .action(async function (this: Command, id: string) {\n const repoRoot = getRepoRoot();\n\n // Read all lessons\n const { items } = await readMemoryItems(repoRoot);\n\n // Find the lesson\n const lesson = items.find((l) => l.id === id);\n if (!lesson) {\n console.error(formatError('validate', 'NOT_FOUND', `Lesson not found: ${id}`, 'Use \"ca list\" to see available lessons'));\n process.exit(1);\n }\n\n // Check if not invalidated\n if (!lesson.invalidatedAt) {\n out.info(`Lesson ${id} is not invalidated.`);\n return;\n }\n\n // Remove invalidation fields (keep everything else)\n const updatedItem: MemoryItem = {\n ...lesson,\n invalidatedAt: undefined,\n invalidationReason: undefined,\n };\n\n // Append the updated lesson (JSONL append-only pattern)\n await appendMemoryItem(repoRoot, updatedItem);\n out.success(`Lesson ${id} re-enabled (validated).`);\n });\n}\n","/**\n * I/O commands: export, import\n *\n * Commands for importing and exporting lessons.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { appendMemoryItem, readMemoryItems } from '../memory/storage/index.js';\nimport { MemoryItemSchema } from '../memory/index.js';\nimport type { MemoryItem } from '../memory/index.js';\n\nimport { formatError } from '../cli-error-format.js';\n\nimport { JSON_INDENT_SPACES } from './shared.js';\n\n// ============================================================================\n// Action Handlers\n// ============================================================================\n\nasync function exportAction(options: { since?: string; tags?: string }): Promise<void> {\n const repoRoot = getRepoRoot();\n\n const { items } = await readMemoryItems(repoRoot);\n\n let filtered = items;\n\n if (options.since) {\n const sinceDate = new Date(options.since);\n if (Number.isNaN(sinceDate.getTime())) {\n console.error(formatError('export', 'INVALID_DATE', `Invalid date format: ${options.since}`, 'Use ISO8601 format (e.g., 2024-01-15)'));\n process.exit(1);\n }\n filtered = filtered.filter((item) => new Date(item.created) >= sinceDate);\n }\n\n if (options.tags) {\n const filterTags = options.tags.split(',').map((t) => t.trim());\n filtered = filtered.filter((item) => item.tags.some((tag) => filterTags.includes(tag)));\n }\n\n console.log(JSON.stringify(filtered, null, JSON_INDENT_SPACES));\n}\n\nasync function importAction(file: string): Promise<void> {\n const repoRoot = getRepoRoot();\n\n let content: string;\n try {\n content = await readFile(file, 'utf-8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n console.error(formatError('import', 'FILE_NOT_FOUND', `File not found: ${file}`, 'Check the path and try again'));\n } else {\n console.error(formatError('import', 'READ_ERROR', `Error reading file: ${(err as Error).message}`, 'Check file permissions'));\n }\n process.exit(1);\n }\n\n const { items: existingItems } = await readMemoryItems(repoRoot);\n const existingIds = new Set(existingItems.map((item) => item.id));\n\n const lines = content.split('\\n');\n let imported = 0;\n let skipped = 0;\n let invalid = 0;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n invalid++;\n continue;\n }\n\n const result = MemoryItemSchema.safeParse(parsed);\n if (!result.success) {\n invalid++;\n continue;\n }\n\n const item: MemoryItem = result.data;\n\n if (existingIds.has(item.id)) {\n skipped++;\n continue;\n }\n\n await appendMemoryItem(repoRoot, item);\n existingIds.add(item.id);\n imported++;\n }\n\n const lessonWord = imported === 1 ? 'lesson' : 'lessons';\n const parts: string[] = [];\n if (skipped > 0) parts.push(`${skipped} skipped`);\n if (invalid > 0) parts.push(`${invalid} invalid`);\n\n if (parts.length > 0) {\n console.log(`Imported ${imported} ${lessonWord} (${parts.join(', ')})`);\n } else {\n console.log(`Imported ${imported} ${lessonWord}`);\n }\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register I/O commands on the program.\n */\nexport function registerIOCommands(program: Command): void {\n program\n .command('export')\n .description('Export lessons as JSON to stdout')\n .option('--since <date>', 'Only include lessons created after this date (ISO8601)')\n .option('--tags <tags>', 'Filter by tags (comma-separated, OR logic)')\n .action(async (options: { since?: string; tags?: string }) => {\n await exportAction(options);\n });\n\n program\n .command('import <file>')\n .description('Import lessons from a JSONL file')\n .action(async (file: string) => {\n await importAction(file);\n });\n}\n","/**\n * Maintenance commands: compact, rebuild, stats\n *\n * Commands for database health and maintenance.\n */\n\nimport { statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { formatBytes, getRepoRoot } from '../cli-utils.js';\nimport {\n compact,\n countTombstones,\n DB_PATH,\n getRetrievalStats,\n LESSONS_PATH,\n needsCompaction,\n readMemoryItems,\n rebuildIndex,\n syncIfNeeded,\n TOMBSTONE_THRESHOLD,\n} from '../memory/storage/index.js';\n\nimport {\n AGE_FLAG_THRESHOLD_DAYS,\n AVG_DECIMAL_PLACES,\n getLessonAgeDays,\n LESSON_COUNT_WARNING_THRESHOLD,\n out,\n} from './shared.js';\n\n// ============================================================================\n// Action Handlers\n// ============================================================================\n\nasync function compactAction(options: { force?: boolean; dryRun?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n\n const tombstones = await countTombstones(repoRoot);\n const needs = await needsCompaction(repoRoot);\n\n if (options.dryRun) {\n console.log('Dry run - no changes will be made.\\n');\n console.log(`Tombstones found: ${tombstones}`);\n console.log(`Compaction needed: ${needs ? 'yes' : 'no'}`);\n return;\n }\n\n if (!needs && !options.force) {\n console.log(`Compaction not needed (${tombstones} tombstones, threshold is ${TOMBSTONE_THRESHOLD}).`);\n console.log('Use --force to compact anyway.');\n return;\n }\n\n console.log('Running compaction...');\n const result = await compact(repoRoot);\n\n console.log('\\nCompaction complete:');\n console.log(` Archived: ${result.archived} lesson(s)`);\n console.log(` Tombstones removed: ${result.tombstonesRemoved}`);\n console.log(` Lessons remaining: ${result.lessonsRemaining}`);\n if (result.droppedInvalid > 0) {\n console.log(` Invalid records dropped: ${result.droppedInvalid}`);\n }\n\n await rebuildIndex(repoRoot);\n console.log(' Index rebuilt.');\n}\n\nasync function rebuildAction(options: { force?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n if (options.force) {\n console.log('Forcing index rebuild...');\n await rebuildIndex(repoRoot);\n console.log('Index rebuilt.');\n } else {\n const rebuilt = await syncIfNeeded(repoRoot);\n if (rebuilt) {\n console.log('Index rebuilt (JSONL changed).');\n } else {\n console.log('Index is up to date.');\n }\n }\n}\n\nasync function statsAction(): Promise<void> {\n const repoRoot = getRepoRoot();\n\n await syncIfNeeded(repoRoot);\n\n const { items } = await readMemoryItems(repoRoot);\n const deletedCount = await countTombstones(repoRoot);\n const totalLessons = items.length;\n\n const retrievalStats = getRetrievalStats(repoRoot);\n const totalRetrievals = retrievalStats.reduce((sum, s) => sum + s.count, 0);\n const avgRetrievals = totalLessons > 0 ? (totalRetrievals / totalLessons).toFixed(AVG_DECIMAL_PLACES) : '0.0';\n\n const jsonlPath = join(repoRoot, LESSONS_PATH);\n const dbPath = join(repoRoot, DB_PATH);\n\n let dataSize = 0;\n let indexSize = 0;\n\n try { dataSize = statSync(jsonlPath).size; } catch { /* File doesn't exist */ }\n try { indexSize = statSync(dbPath).size; } catch { /* File doesn't exist */ }\n\n const totalSize = dataSize + indexSize;\n\n let recentCount = 0;\n let mediumCount = 0;\n let oldCount = 0;\n for (const item of items) {\n const ageDays = getLessonAgeDays(item);\n if (ageDays < 30) {\n recentCount++;\n } else if (ageDays <= AGE_FLAG_THRESHOLD_DAYS) {\n mediumCount++;\n } else {\n oldCount++;\n }\n }\n\n const typeCounts: Record<string, number> = {};\n for (const item of items) {\n typeCounts[item.type] = (typeCounts[item.type] ?? 0) + 1;\n }\n\n const deletedInfo = deletedCount > 0 ? ` (${deletedCount} deleted)` : '';\n console.log(`Lessons: ${totalLessons} total${deletedInfo}`);\n\n if (Object.keys(typeCounts).length > 1 || (Object.keys(typeCounts).length === 1 && !typeCounts['lesson'])) {\n const breakdown = Object.entries(typeCounts)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([type, count]) => `${count} ${type}`)\n .join(', ');\n console.log(`Types: ${breakdown}`);\n }\n\n if (totalLessons > LESSON_COUNT_WARNING_THRESHOLD) {\n out.warn(`High lesson count may degrade retrieval quality. Consider running \\`ca compact\\`.`);\n }\n\n if (totalLessons > 0) {\n console.log(`Age: ${recentCount} <30d, ${mediumCount} 30-90d, ${oldCount} >90d`);\n }\n\n console.log(`Retrievals: ${totalRetrievals} total, ${avgRetrievals} avg per lesson`);\n console.log(`Storage: ${formatBytes(totalSize)} (index: ${formatBytes(indexSize)}, data: ${formatBytes(dataSize)})`);\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register maintenance commands on the program.\n */\nexport function registerMaintenanceCommands(program: Command): void {\n program\n .command('compact')\n .description('Compact lessons: archive old lessons and remove tombstones')\n .option('-f, --force', 'Run compaction even if below threshold')\n .option('--dry-run', 'Show what would be done without making changes')\n .action(async (options: { force?: boolean; dryRun?: boolean }) => {\n await compactAction(options);\n });\n\n program\n .command('rebuild')\n .description('Rebuild SQLite index from JSONL')\n .option('-f, --force', 'Force rebuild even if unchanged')\n .action(async (options: { force?: boolean }) => {\n await rebuildAction(options);\n });\n\n program\n .command('stats')\n .description('Show database health and statistics')\n .action(async () => {\n await statsAction();\n });\n}\n","/**\n * Prime command - Context recovery for Claude Code with Beads-style trust language.\n *\n * Generates trust language guidelines combined with high-severity lessons\n * for context recovery after compaction or session restart.\n */\n\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { loadSessionLessons } from '../memory/retrieval/index.js';\nimport type { MemoryItem, Source } from '../memory/index.js';\n\n/**\n * Beads-style trust language template.\n *\n * Uses explicit prohibitions, workflow sequencing, and NEVER/MUST language\n * following Beads conventions for maximum adherence.\n *\n * IMPORTANT: Prioritizes MCP tools over CLI commands.\n */\nconst TRUST_LANGUAGE_TEMPLATE = `# Compound Agent Active\n\n> **Context Recovery**: Run \\`ca prime\\` after compaction, clear, or new session\n\n## MCP Tools (ALWAYS USE THESE)\n\n**You MUST use MCP tools, NOT CLI commands:**\n\n| Tool | Purpose |\n|------|---------|\n| \\`memory_search\\` | Search lessons - call BEFORE architectural decisions |\n| \\`memory_capture\\` | Capture lessons - call AFTER corrections or discoveries |\n\n## Core Constraints\n\n**Default**: Use MCP tools for lesson management\n**Prohibited**: NEVER edit .claude/lessons/ files directly\n\n**Default**: Propose lessons freely after corrections\n**Prohibited**: NEVER propose without quality gate (novel + specific; prefer actionable)\n\n## Retrieval Protocol\n\nYou MUST call \\`memory_search\\` BEFORE:\n- Architectural decisions or complex planning\n- Implementing patterns you've done before in this repo\n\n**NEVER skip memory_search for complex decisions.** Past mistakes will repeat.\n\n## Capture Protocol\n\nCall \\`memory_capture\\` AFTER:\n- User corrects you (\"no\", \"wrong\", \"actually...\")\n- You self-correct after iteration failures\n- Test fails then you fix it\n\n**Quality gate** (must pass before capturing):\n- Novel (not already stored)\n- Specific (clear guidance)\n- Actionable (preferred, not mandatory)\n\n**Workflow**: Search BEFORE deciding, capture AFTER learning.\n\n## CLI (fallback only)\n\nWhen MCP is unavailable: \\`ca search \"query\"\\`, \\`ca learn \"insight\"\\`, \\`ca list\\`\n`;\n\n/**\n * Format lesson source for human-readable display.\n */\nfunction formatSource(source: Source): string {\n switch (source) {\n case 'user_correction':\n return 'user correction';\n case 'self_correction':\n return 'self correction';\n case 'test_failure':\n return 'test failure';\n case 'manual':\n return 'manual';\n default:\n return source;\n }\n}\n\n/**\n * Format a single lesson for the Emergency Recall section.\n *\n * Format: - **{insight}** ({tags})\n * Learned: {date} via {source}\n */\nfunction formatLessonForPrime(lesson: MemoryItem): string {\n const date = lesson.created.slice(0, 10); // YYYY-MM-DD\n const tags = lesson.tags.length > 0 ? ` (${lesson.tags.join(', ')})` : '';\n const source = formatSource(lesson.source);\n return `- **${lesson.insight}**${tags}\\n Learned: ${date} via ${source}`;\n}\n\n/**\n * Generate prime context output for Claude Code.\n *\n * Combines Beads-style trust language guidelines with high-severity lessons\n * for context recovery after compaction or session restart.\n *\n * @param repoRoot - Repository root directory (defaults to getRepoRoot())\n * @returns Formatted markdown string (< 2K tokens)\n */\nexport async function getPrimeContext(repoRoot?: string): Promise<string> {\n const root = repoRoot ?? getRepoRoot();\n\n // Load high-severity lessons (top 5, sorted by recency)\n const lessons = await loadSessionLessons(root, 5);\n\n // Build output: trust language first\n let output = TRUST_LANGUAGE_TEMPLATE;\n\n // Add Emergency Recall section if we have high-severity lessons\n if (lessons.length > 0) {\n const formattedLessons = lessons.map(formatLessonForPrime).join('\\n\\n');\n output += `\n---\n\n# [CRITICAL] Mandatory Recall\n\nCritical lessons from past corrections:\n\n${formattedLessons}\n`;\n }\n\n return output;\n}\n\n/**\n * Register prime command on the program.\n */\nexport function registerPrimeCommand(program: Command): void {\n /**\n * Prime command - Output context recovery for Claude Code.\n *\n * Combines Beads-style trust language guidelines with high-severity lessons.\n * Used after compaction or context loss to remind Claude of the\n * compound-agent workflow, rules, and commands.\n *\n * @example npx ca prime\n */\n program\n .command('prime')\n .description('Output context for Claude Code (guidelines + top lessons)')\n .action(async () => {\n const output = await getPrimeContext();\n console.log(output);\n });\n}\n","/**\n * Audit command: ca audit\n *\n * Runs all audit checks and outputs findings.\n */\n\nimport chalk from 'chalk';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { formatError } from '../cli-error-format.js';\nimport { runAudit } from '../audit/index.js';\nimport type { AuditFinding } from '../audit/index.js';\n\nimport { getGlobalOpts } from './shared.js';\n\nconst JSON_INDENT = 2;\n\n/**\n * Format a single finding as a human-readable line.\n */\nfunction formatFinding(finding: AuditFinding): string {\n const label = finding.severity.toUpperCase();\n const filePart = finding.file ? ` ${finding.file}` : '';\n return `${label} [${finding.source}]${filePart} -- ${finding.issue}`;\n}\n\n/**\n * Register the audit command on the program.\n */\nexport function registerAuditCommands(program: Command): void {\n program\n .command('audit')\n .description('Run audit checks against the codebase')\n .option('--json', 'Output as JSON')\n .option('--no-rules', 'Skip rule checks')\n .option('--no-patterns', 'Skip pattern checks')\n .option('--no-lessons', 'Skip lesson checks')\n .action(async function (this: Command) {\n const repoRoot = getRepoRoot();\n const { quiet } = getGlobalOpts(this);\n const opts = this.opts<{ json?: boolean; rules: boolean; patterns: boolean; lessons: boolean }>();\n\n let report;\n try {\n report = await runAudit(repoRoot, {\n includeRules: opts.rules,\n includePatterns: opts.patterns,\n includeLessons: opts.lessons,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Audit failed';\n console.error(formatError('audit', 'AUDIT_ERROR', msg, 'Check repo configuration'));\n process.exit(1);\n }\n\n if (opts.json) {\n console.log(JSON.stringify(report, null, JSON_INDENT));\n } else {\n for (const finding of report.findings) {\n const line = formatFinding(finding);\n switch (finding.severity) {\n case 'error':\n console.log(chalk.red(line));\n break;\n case 'warning':\n console.log(chalk.yellow(line));\n break;\n default:\n console.log(chalk.blue(line));\n break;\n }\n }\n\n if (!quiet) {\n console.log('');\n console.log(\n `Audit: ${report.findings.length} finding(s), ` +\n `${report.summary.errors} error(s), ` +\n `${report.summary.warnings} warning(s), ` +\n `${report.summary.infos} info(s)`\n );\n }\n }\n\n if (report.summary.errors > 0) {\n process.exit(1);\n }\n });\n}\n","/**\n * Rules command: rules check\n *\n * Runs repository-defined rules from .claude/rules.json and outputs\n * agent-legible violation messages.\n */\n\nimport chalk from 'chalk';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { formatError } from '../cli-error-format.js';\nimport { formatViolation, loadRuleConfig, runRules } from '../rules/index.js';\n\nimport { getGlobalOpts, out } from './shared.js';\n\n/**\n * Register the rules command group on the program.\n */\nexport function registerRulesCommands(program: Command): void {\n const rulesCmd = program\n .command('rules')\n .description('Run repository-defined rule checks');\n\n rulesCmd\n .command('check')\n .description('Check codebase against rules in .claude/rules.json')\n .action(function (this: Command) {\n const repoRoot = getRepoRoot();\n const { quiet } = getGlobalOpts(this);\n\n let config;\n try {\n config = loadRuleConfig(repoRoot);\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Failed to load rules config';\n console.error(formatError('rules', 'CONFIG_ERROR', msg, 'Check .claude/rules.json syntax'));\n process.exit(1);\n }\n\n if (config.rules.length === 0) {\n if (!quiet) {\n out.info('No rules defined. Create .claude/rules.json to add rules.');\n }\n return;\n }\n\n const results = runRules(repoRoot, config.rules);\n\n // Print violations\n for (const result of results) {\n for (const violation of result.violations) {\n const line = formatViolation(result.rule, violation);\n switch (result.rule.severity) {\n case 'error':\n console.log(chalk.red(line));\n break;\n case 'warning':\n console.log(chalk.yellow(line));\n break;\n default:\n console.log(chalk.blue(line));\n break;\n }\n }\n }\n\n // Summary\n const total = results.length;\n const errors = results.filter((r) => !r.passed && r.rule.severity === 'error').length;\n const warnings = results.filter((r) => !r.passed && r.rule.severity === 'warning').length;\n const passed = results.filter((r) => r.passed).length;\n\n console.log('');\n console.log(`Rules: ${total} checked, ${errors} error(s), ${warnings} warning(s), ${passed} passed`);\n\n if (errors > 0) {\n process.exit(1);\n }\n });\n}\n","/**\n * Test summary command: runs tests and outputs a compact summary.\n *\n * Parses Vitest output to extract pass/fail/skip counts, duration,\n * and failing test names + error messages.\n */\n\nimport { execSync } from 'node:child_process';\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A single test failure with name and error message. */\nexport interface TestFailure {\n name: string;\n error: string;\n}\n\n/** Parsed summary of a Vitest run. */\nexport interface TestSummary {\n passed: number;\n failed: number;\n skipped: number;\n total: number;\n duration: string;\n failures: TestFailure[];\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Max lines to capture from a failure body. */\nconst MAX_ERROR_BODY_LINES = 10;\n\n/** Default log file path relative to repo root. */\nconst LOG_REL_PATH = '.claude/.cache/last-test-run.log';\n\n// ============================================================================\n// Parser\n// ============================================================================\n\n/**\n * Parse Vitest output into a structured summary.\n *\n * @param output - Raw Vitest stdout/stderr output\n * @returns Parsed test summary\n */\nexport function parseVitestOutput(output: string): TestSummary {\n const summary: TestSummary = {\n passed: 0,\n failed: 0,\n skipped: 0,\n total: 0,\n duration: 'unknown',\n failures: [],\n };\n\n if (!output.trim()) return summary;\n\n // Parse the summary line: \"Tests 3 failed | 17 passed (20)\" or \"Tests 65 passed (65)\"\n const testsLine = output.match(/Tests\\s+(.+)\\((\\d+)\\)/);\n if (testsLine) {\n summary.total = parseInt(testsLine[2]!, 10);\n const parts = testsLine[1]!;\n\n const failedMatch = parts.match(/(\\d+)\\s+failed/);\n if (failedMatch) summary.failed = parseInt(failedMatch[1]!, 10);\n\n const passedMatch = parts.match(/(\\d+)\\s+passed/);\n if (passedMatch) summary.passed = parseInt(passedMatch[1]!, 10);\n\n const skippedMatch = parts.match(/(\\d+)\\s+skipped/);\n if (skippedMatch) summary.skipped = parseInt(skippedMatch[1]!, 10);\n }\n\n // Parse duration: \"Duration 1.23s\" or \"Duration 142ms\"\n const durationMatch = output.match(/Duration\\s+([\\d.]+(?:ms|s))/);\n if (durationMatch) {\n summary.duration = durationMatch[1]!;\n }\n\n // Parse individual FAIL blocks with multiline body\n const lines = output.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const failMatch = lines[i]!.match(/^ FAIL\\s+(.+?)(?:\\s+\\[.*?\\])?$/);\n if (!failMatch) continue;\n\n const name = failMatch[1]!.trim();\n const bodyLines: string[] = [];\n\n // Collect up to MAX_ERROR_BODY_LINES of the failure body\n for (let j = i + 1; j < lines.length && bodyLines.length < MAX_ERROR_BODY_LINES; j++) {\n const line = lines[j]!;\n // Stop at location lines or section separators\n if (line.trimStart().startsWith('\\u276F') || line.match(/^⎯/)) break;\n // Stop at next FAIL block\n if (line.match(/^ FAIL\\s+/)) break;\n // Skip blank lines at the start\n if (bodyLines.length === 0 && line.trim() === '') continue;\n bodyLines.push(line);\n }\n\n // Trim trailing blank lines\n while (bodyLines.length > 0 && bodyLines[bodyLines.length - 1]!.trim() === '') {\n bodyLines.pop();\n }\n\n if (bodyLines.length === 0) continue;\n\n summary.failures.push({ name, error: bodyLines.join('\\n').trim() });\n }\n\n return summary;\n}\n\n/**\n * Format a TestSummary into a compact string for CLI output.\n *\n * @param summary - Parsed test summary\n * @param logPath - Path to the full log file\n * @returns Formatted summary string\n */\nexport function formatTestSummary(summary: TestSummary, logPath: string): string {\n const lines: string[] = [];\n\n lines.push(\n `TESTS: ${summary.passed} passed, ${summary.failed} failed, ${summary.skipped} skipped (${summary.duration})`\n );\n\n if (summary.failures.length > 0) {\n const first = summary.failures[0]!;\n lines.push(`FAIL ${first.name}`);\n lines.push(` ${first.error}`);\n if (summary.failures.length > 1) {\n lines.push(` ... and ${summary.failures.length - 1} more failure(s)`);\n }\n }\n\n lines.push(`LOG: Full output at ${logPath}`);\n\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register the test-summary command on the program.\n */\nexport function registerTestSummaryCommand(program: Command): void {\n program\n .command('test-summary')\n .description('Run tests and output a compact summary')\n .option('--fast', 'Run pnpm test:fast instead of pnpm test')\n .option('--cmd <command>', 'Custom test command to run')\n .action((options: { fast?: boolean; cmd?: string }) => {\n const repoRoot = getRepoRoot();\n\n // Determine test command\n let testCmd = 'pnpm test';\n if (options.cmd) {\n testCmd = options.cmd;\n } else if (options.fast) {\n testCmd = 'pnpm test:fast';\n }\n\n // Run test command, capture output\n let output: string;\n let exitCode: number;\n try {\n output = execSync(testCmd, {\n cwd: repoRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n // Merge stderr into stdout for Vitest (it writes to both)\n env: { ...process.env, FORCE_COLOR: '0' },\n });\n exitCode = 0;\n } catch (err) {\n const execErr = err as { stdout?: string; stderr?: string; status?: number };\n output = (execErr.stdout ?? '') + '\\n' + (execErr.stderr ?? '');\n exitCode = execErr.status ?? 1;\n }\n\n // Write full output to log file\n const logPath = join(repoRoot, LOG_REL_PATH);\n mkdirSync(dirname(logPath), { recursive: true });\n writeFileSync(logPath, output, 'utf-8');\n\n // Parse and format summary\n const summary = parseVitestOutput(output);\n console.log(formatTestSummary(summary, logPath));\n\n process.exit(exitCode);\n });\n}\n","/**\n * Capture commands: learn, capture, detect\n *\n * Commands for capturing lessons from various sources.\n */\n\nimport type { Command } from 'commander';\n\nimport { getRepoRoot } from '../cli-utils.js';\nimport { detectAndPropose, parseInputFile } from '../memory/capture/index.js';\nimport type { DetectionResult } from '../memory/capture/index.js';\nimport { appendLesson, appendMemoryItem, generateId, MemoryItemTypeSchema, SeveritySchema } from '../memory/index.js';\nimport type { Lesson, MemoryItem, MemoryItemType, Severity } from '../memory/index.js';\n\nimport { formatError } from '../cli-error-format.js';\n\nimport { getGlobalOpts, out } from './shared.js';\n\n// ============================================================================\n// Capture Command Helpers\n// ============================================================================\n\n/** Options for capture command */\ninterface CaptureOptions {\n trigger?: string;\n insight?: string;\n input?: string;\n json?: boolean;\n yes?: boolean;\n}\n\n/** Options for learn command */\ninterface LearnOptions {\n trigger?: string;\n tags: string;\n severity?: string;\n yes?: boolean;\n citation?: string;\n citationCommit?: string;\n type: string;\n patternBad?: string;\n patternGood?: string;\n}\n\n/**\n * Create a lesson from explicit trigger and insight.\n */\nfunction createLessonFromFlags(trigger: string, insight: string, confirmed: boolean): Lesson {\n return {\n id: generateId(insight),\n type: 'lesson',\n trigger,\n insight,\n tags: [],\n source: 'manual',\n context: { tool: 'capture', intent: 'manual capture' },\n created: new Date().toISOString(),\n confirmed,\n supersedes: [],\n related: [],\n };\n}\n\n/**\n * Output lesson in JSON format for capture command.\n */\nfunction outputCaptureJson(lesson: Lesson, saved: boolean): void {\n console.log(JSON.stringify({\n id: lesson.id,\n trigger: lesson.trigger,\n insight: lesson.insight,\n type: lesson.type,\n saved,\n }));\n}\n\n/**\n * Output lesson preview in human-readable format.\n */\nfunction outputCapturePreview(lesson: Lesson): void {\n console.log('Lesson captured:');\n console.log(` ID: ${lesson.id}`);\n console.log(` Trigger: ${lesson.trigger}`);\n console.log(` Insight: ${lesson.insight}`);\n console.log(` Type: ${lesson.type}`);\n console.log(` Tags: ${lesson.tags.length > 0 ? lesson.tags.join(', ') : '(none)'}`);\n console.log('\\nTo save: run with --yes flag, or use memory_capture MCP tool');\n}\n\n/**\n * Create lesson from input file detection result.\n */\nfunction createLessonFromInputFile(result: DetectionResult, confirmed: boolean): Lesson {\n return {\n id: generateId(result.proposedInsight),\n type: 'lesson',\n trigger: result.trigger,\n insight: result.proposedInsight,\n tags: [],\n source: result.source,\n context: { tool: 'capture', intent: 'auto-capture' },\n created: new Date().toISOString(),\n confirmed,\n supersedes: [],\n related: [],\n };\n}\n\n// ============================================================================\n// Command Action Handlers\n// ============================================================================\n\n/**\n * Handle the learn command action.\n */\nasync function handleLearn(cmd: Command, insight: string, options: LearnOptions): Promise<void> {\n const repoRoot = getRepoRoot();\n const { quiet } = getGlobalOpts(cmd);\n\n // Validate --type\n const typeResult = MemoryItemTypeSchema.safeParse(options.type);\n if (!typeResult.success) {\n console.error(formatError('learn', 'INVALID_TYPE', `Invalid type: \"${options.type}\"`, 'Use --type lesson|solution|pattern|preference'));\n process.exit(1);\n }\n const itemType: MemoryItemType = typeResult.data;\n\n // Validate pattern flags when type=pattern\n if (itemType === 'pattern' && (!options.patternBad || !options.patternGood)) {\n console.error(formatError('learn', 'MISSING_PATTERN', 'type=pattern requires --pattern-bad and --pattern-good', 'Use: learn \"insight\" --type pattern --pattern-bad \"old\" --pattern-good \"new\"'));\n process.exit(1);\n }\n\n // Validate severity if provided\n let severity: Severity | undefined;\n if (options.severity !== undefined) {\n const result = SeveritySchema.safeParse(options.severity);\n if (!result.success) {\n console.error(formatError('learn', 'INVALID_SEVERITY', `Invalid severity: \"${options.severity}\"`, 'Use --severity high|medium|low'));\n process.exit(1);\n }\n severity = result.data;\n }\n\n // Parse citation if provided\n let citation: { file: string; line?: number; commit?: string } | undefined;\n if (options.citation) {\n const parts = options.citation.split(':');\n const file = parts[0] ?? '';\n const lineStr = parts[1];\n const line = lineStr ? parseInt(lineStr, 10) : undefined;\n citation = {\n file,\n ...(line && !isNaN(line) && { line }),\n ...(options.citationCommit && { commit: options.citationCommit }),\n };\n }\n\n // Build pattern if provided\n const pattern = options.patternBad && options.patternGood\n ? { bad: options.patternBad, good: options.patternGood }\n : undefined;\n\n const item: MemoryItem = {\n id: generateId(insight, itemType),\n type: itemType,\n trigger: options.trigger ?? 'Manual capture',\n insight,\n tags: options.tags ? options.tags.split(',').map((t) => t.trim()) : [],\n source: 'manual',\n context: { tool: 'cli', intent: 'manual learning' },\n created: new Date().toISOString(),\n confirmed: true,\n supersedes: [],\n related: [],\n ...(severity !== undefined && { severity }),\n ...(citation && { citation }),\n ...(pattern && { pattern }),\n } as MemoryItem;\n\n await appendMemoryItem(repoRoot, item);\n\n const verb = itemType === 'lesson' ? 'Learned' : 'Captured';\n const chalk = await import('chalk');\n out.success(`${verb}: ${insight}`);\n if (!quiet) {\n console.log(`ID: ${chalk.default.dim(item.id)}`);\n if (itemType !== 'lesson') {\n console.log(`Type: ${chalk.default.dim(itemType)}`);\n }\n if (citation) {\n console.log(`Citation: ${chalk.default.dim(citation.file)}${citation.line ? `:${citation.line}` : ''}`);\n }\n }\n}\n\n/**\n * Handle the detect command action.\n */\nasync function handleDetect(options: { input: string; save?: boolean; yes?: boolean; json?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n\n if (options.save && !options.yes) {\n if (options.json) {\n console.log(JSON.stringify({ error: '--save requires --yes flag for confirmation' }));\n } else {\n console.error(formatError('detect', 'MISSING_FLAG', '--save requires --yes', 'Use: detect --input <file> --save --yes'));\n }\n process.exit(1);\n }\n\n let input;\n try {\n input = await parseInputFile(options.input);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to parse input file';\n if (options.json) {\n console.log(JSON.stringify({ error: message, detected: false }));\n } else {\n console.error(formatError('detect', 'INVALID_INPUT', message, 'Check the file is valid JSON matching the expected schema'));\n }\n process.exit(1);\n }\n const result = await detectAndPropose(repoRoot, input);\n\n if (!result) {\n if (options.json) {\n console.log(JSON.stringify({ detected: false }));\n } else {\n console.log('No learning trigger detected.');\n }\n return;\n }\n\n if (options.json) {\n console.log(JSON.stringify({ detected: true, ...result }));\n return;\n }\n\n console.log('Learning trigger detected!');\n console.log(` Trigger: ${result.trigger}`);\n console.log(` Source: ${result.source}`);\n console.log(` Proposed: ${result.proposedInsight}`);\n\n if (options.save && options.yes) {\n const lesson: Lesson = {\n id: generateId(result.proposedInsight),\n type: 'lesson',\n trigger: result.trigger,\n insight: result.proposedInsight,\n tags: [],\n source: result.source,\n context: { tool: 'detect', intent: 'auto-capture' },\n created: new Date().toISOString(),\n confirmed: true,\n supersedes: [],\n related: [],\n };\n\n await appendLesson(repoRoot, lesson);\n console.log(`\\nSaved as lesson: ${lesson.id}`);\n }\n}\n\n/**\n * Handle the capture command action.\n */\nasync function handleCapture(cmd: Command, options: CaptureOptions): Promise<void> {\n const repoRoot = getRepoRoot();\n const { verbose } = getGlobalOpts(cmd);\n let lesson: Lesson | undefined;\n\n if (options.input) {\n let input;\n try {\n input = await parseInputFile(options.input);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to parse input file';\n if (options.json) {\n console.log(JSON.stringify({ error: message, saved: false }));\n } else {\n console.error(formatError('capture', 'INVALID_INPUT', message, 'Check the file is valid JSON matching the expected schema'));\n }\n process.exit(1);\n }\n const result = await detectAndPropose(repoRoot, input);\n if (!result) {\n if (options.json) {\n console.log(JSON.stringify({ detected: false, saved: false }));\n } else {\n console.log('No learning trigger detected.');\n }\n return;\n }\n lesson = createLessonFromInputFile(result, options.yes ?? false);\n } else if (options.trigger && options.insight) {\n lesson = createLessonFromFlags(options.trigger, options.insight, options.yes ?? false);\n } else {\n const msg = 'Provide either --trigger and --insight, or --input file.';\n if (options.json) {\n console.log(JSON.stringify({ error: msg, saved: false }));\n } else {\n console.error(formatError('capture', 'MISSING_OPTIONS', msg, 'Provide --trigger and --insight, or --input'));\n }\n process.exit(1);\n }\n\n if (!options.yes && !process.stdin.isTTY) {\n if (options.json) {\n console.log(JSON.stringify({ error: '--yes required in non-interactive mode', saved: false }));\n } else {\n console.error(formatError('capture', 'NON_INTERACTIVE', '--yes required in non-interactive mode', 'Use: capture --trigger \"...\" --insight \"...\" --yes'));\n }\n process.exit(1);\n }\n\n if (options.json) {\n if (options.yes) await appendLesson(repoRoot, lesson);\n outputCaptureJson(lesson, options.yes ?? false);\n } else if (options.yes) {\n await appendLesson(repoRoot, lesson);\n out.success(`Lesson saved: ${lesson.id}`);\n if (verbose) console.log(` Type: ${lesson.type} | Trigger: ${lesson.trigger}`);\n } else {\n outputCapturePreview(lesson);\n }\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register capture commands (learn, capture, detect) on the program.\n */\nexport function registerCaptureCommands(program: Command): void {\n program\n .command('learn <insight>')\n .description('Capture a new memory item (lesson, solution, pattern, or preference)')\n .option('-t, --trigger <text>', 'What triggered this lesson')\n .option('--tags <tags>', 'Comma-separated tags', '')\n .option('-s, --severity <level>', 'Lesson severity: high, medium, low')\n .option('-y, --yes', 'Skip confirmation')\n .option('--citation <file:line>', 'Source file (optionally with :line number)')\n .option('--citation-commit <hash>', 'Git commit hash for citation')\n .option('--type <type>', 'Memory item type: lesson, solution, pattern, preference', 'lesson')\n .option('--pattern-bad <code>', 'Bad pattern example (required when --type pattern)')\n .option('--pattern-good <code>', 'Good pattern example (required when --type pattern)')\n .action(async function (this: Command, insight: string, options: LearnOptions) {\n await handleLearn(this, insight, options);\n });\n\n program\n .command('detect')\n .description('Detect learning triggers from input')\n .requiredOption('--input <file>', 'Path to JSON input file')\n .option('--save', 'Save proposed lesson (requires --yes)')\n .option('-y, --yes', 'Confirm save (required with --save)')\n .option('--json', 'Output result as JSON')\n .action(async (options: { input: string; save?: boolean; yes?: boolean; json?: boolean }) => {\n await handleDetect(options);\n });\n\n program\n .command('capture')\n .description('Capture a lesson from trigger/insight or input file')\n .option('-t, --trigger <text>', 'What triggered this lesson')\n .option('-i, --insight <text>', 'The insight or lesson learned')\n .option('--input <file>', 'Path to JSON input file (alternative to trigger/insight)')\n .option('--json', 'Output result as JSON')\n .option('-y, --yes', 'Skip confirmation and save immediately')\n .action(async function (this: Command, options: CaptureOptions) {\n await handleCapture(this, options);\n });\n}\n","/**\n * Retrieval commands: search, list, check-plan, load-session\n *\n * Commands for searching and retrieving lessons.\n */\n\nimport chalk from 'chalk';\nimport type { Command } from 'commander';\n\nimport { getRepoRoot, parseLimit } from '../cli-utils.js';\nimport { isModelUsable, loadSessionLessons, retrieveForPlan } from '../index.js';\nimport { incrementRetrievalCount, readLessons, readMemoryItems, searchKeyword, syncIfNeeded } from '../memory/storage/index.js';\nimport type { MemoryItem } from '../memory/index.js';\n\nimport { formatError } from '../cli-error-format.js';\n\nimport {\n AGE_FLAG_THRESHOLD_DAYS,\n DEFAULT_CHECK_PLAN_LIMIT,\n DEFAULT_LIST_LIMIT,\n DEFAULT_SEARCH_LIMIT,\n getGlobalOpts,\n getLessonAgeDays,\n ISO_DATE_PREFIX_LENGTH,\n LESSON_COUNT_WARNING_THRESHOLD,\n out,\n} from './shared.js';\n\nimport type { RankedLesson } from '../memory/search/index.js';\n\n/**\n * Parse numeric limit and exit with user-friendly output on invalid input.\n */\nfunction parseLimitOrExit(rawLimit: string, optionName: string, commandName: string): number {\n try {\n return parseLimit(rawLimit, optionName);\n } catch (err) {\n const message = err instanceof Error ? err.message : `Invalid ${optionName}`;\n console.error(formatError(commandName, 'INVALID_LIMIT', message, `Use --${optionName} with a positive integer`));\n process.exit(1);\n }\n}\n\n// ============================================================================\n// Check-Plan Command Helpers\n// ============================================================================\n\n/**\n * Read plan text from stdin (non-TTY mode).\n */\nasync function readPlanFromStdin(): Promise<string | undefined> {\n const { stdin } = await import('node:process');\n if (!stdin.isTTY) {\n const chunks: Buffer[] = [];\n for await (const chunk of stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString('utf-8').trim();\n }\n return undefined;\n}\n\n/**\n * Output check-plan results in JSON format.\n *\n * Uses rankScore (final boosted score) instead of raw similarity.\n */\nfunction outputCheckPlanJson(lessons: RankedLesson[]): void {\n const jsonOutput = {\n lessons: lessons.map((l) => ({\n id: l.lesson.id,\n insight: l.lesson.insight,\n rankScore: l.finalScore ?? l.score, // Use finalScore if available, fallback to raw score\n source: l.lesson.source,\n })),\n count: lessons.length,\n };\n console.log(JSON.stringify(jsonOutput));\n}\n\n/**\n * Output check-plan results in human-readable format.\n *\n * Omits numeric scores - ordering is sufficient for human consumption.\n */\nfunction outputCheckPlanHuman(lessons: RankedLesson[], quiet: boolean): void {\n console.log('## Lessons Check\\n');\n console.log('Relevant to your plan:\\n');\n\n lessons.forEach((item, i) => {\n const num = i + 1;\n console.log(`${num}. ${chalk.bold(`[${item.lesson.id}]`)} ${item.lesson.insight}`);\n console.log(` - Source: ${item.lesson.source}`);\n console.log();\n });\n\n if (!quiet) {\n console.log('---');\n console.log('Consider these lessons while implementing.');\n }\n}\n\n// ============================================================================\n// Load-Session Command Helpers\n// ============================================================================\n\n/**\n * Format source string for human-readable display.\n * Converts snake_case to space-separated words.\n */\nfunction formatSource(source: string): string {\n return source.replace(/_/g, ' ');\n}\n\n/**\n * Output load-session results in human-readable format.\n * Optimized for Claude's context window - no IDs, clear structure.\n */\nfunction outputSessionLessonsHuman(lessons: MemoryItem[], quiet: boolean): void {\n console.log('## Lessons from Past Sessions\\n');\n console.log('These lessons were captured from previous corrections and should inform your work:\\n');\n\n lessons.forEach((lesson, i) => {\n const num = i + 1;\n const date = lesson.created.slice(0, ISO_DATE_PREFIX_LENGTH);\n const tagsDisplay = lesson.tags.length > 0 ? ` (${lesson.tags.join(', ')})` : '';\n\n console.log(`${num}. **${lesson.insight}**${tagsDisplay}`);\n console.log(` Learned: ${date} via ${formatSource(lesson.source)}`);\n console.log();\n });\n\n if (!quiet) {\n console.log('Consider these lessons when planning and implementing tasks.');\n }\n}\n\n// ============================================================================\n// Action Handlers\n// ============================================================================\n\nasync function searchAction(cmd: Command, query: string, options: { limit: string }): Promise<void> {\n const repoRoot = getRepoRoot();\n const limit = parseLimitOrExit(options.limit, 'limit', 'search');\n const { verbose, quiet } = getGlobalOpts(cmd);\n\n await syncIfNeeded(repoRoot);\n\n let results;\n try {\n results = await searchKeyword(repoRoot, query, limit);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Search failed';\n console.error(formatError('search', 'SEARCH_FAILED', message, 'Check your query syntax'));\n process.exit(1);\n }\n if (results.length > 0) {\n incrementRetrievalCount(repoRoot, results.map((lesson) => lesson.id));\n }\n\n if (results.length === 0) {\n console.log('No lessons match your search. Try a different query or use \"list\" to see all lessons.');\n return;\n }\n\n if (!quiet) {\n out.info(`Found ${results.length} lesson(s):\\n`);\n }\n for (const lesson of results) {\n console.log(`[${chalk.cyan(lesson.id)}] ${lesson.insight}`);\n console.log(` Trigger: ${lesson.trigger}`);\n if (verbose && lesson.context) {\n console.log(` Context: ${lesson.context.tool} - ${lesson.context.intent}`);\n console.log(` Created: ${lesson.created}`);\n }\n if (lesson.tags.length > 0) {\n console.log(` Tags: ${lesson.tags.join(', ')}`);\n }\n console.log();\n }\n}\n\nasync function listAction(cmd: Command, options: { limit: string; invalidated?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n const limit = parseLimitOrExit(options.limit, 'limit', 'list');\n const { verbose, quiet } = getGlobalOpts(cmd);\n\n const { items, skippedCount } = await readMemoryItems(repoRoot);\n\n const filteredItems = options.invalidated\n ? items.filter((i) => i.invalidatedAt)\n : items;\n\n if (filteredItems.length === 0) {\n if (options.invalidated) {\n console.log('No invalidated lessons found.');\n } else {\n console.log('No lessons found. Get started with: learn \"Your first lesson\"');\n }\n if (skippedCount > 0) {\n out.warn(`${skippedCount} corrupted lesson(s) skipped.`);\n }\n return;\n }\n\n const toShow = filteredItems.slice(0, limit);\n\n if (!quiet) {\n const label = options.invalidated ? 'invalidated lesson(s)' : 'item(s)';\n out.info(`Showing ${toShow.length} of ${filteredItems.length} ${label}:\\n`);\n }\n\n for (const item of toShow) {\n const invalidMarker = item.invalidatedAt ? chalk.red('[INVALID] ') : '';\n console.log(`[${chalk.cyan(item.id)}] ${invalidMarker}${item.insight}`);\n if (verbose) {\n console.log(` Type: ${item.type} | Source: ${item.source}`);\n console.log(` Created: ${item.created}`);\n if (item.context) {\n console.log(` Context: ${item.context.tool} - ${item.context.intent}`);\n }\n if (item.invalidatedAt) {\n console.log(` Invalidated: ${item.invalidatedAt}`);\n if (item.invalidationReason) {\n console.log(` Reason: ${item.invalidationReason}`);\n }\n }\n } else {\n console.log(` Type: ${item.type} | Source: ${item.source}`);\n }\n if (item.tags.length > 0) {\n console.log(` Tags: ${item.tags.join(', ')}`);\n }\n console.log();\n }\n\n if (skippedCount > 0) {\n out.warn(`${skippedCount} corrupted lesson(s) skipped.`);\n }\n}\n\nasync function loadSessionAction(cmd: Command, options: { json?: boolean }): Promise<void> {\n const repoRoot = getRepoRoot();\n const { quiet } = getGlobalOpts(cmd);\n const lessons = await loadSessionLessons(repoRoot);\n\n const { lessons: allLessons } = await readLessons(repoRoot);\n const totalCount = allLessons.length;\n\n if (options.json) {\n console.log(JSON.stringify({ lessons, count: lessons.length, totalCount }));\n return;\n }\n\n if (lessons.length === 0) {\n console.log('No high-severity lessons found.');\n return;\n }\n\n outputSessionLessonsHuman(lessons, quiet);\n\n if (totalCount > LESSON_COUNT_WARNING_THRESHOLD) {\n console.log('');\n out.info(`${totalCount} lessons in index. Consider \\`ca compact\\` to reduce context pollution.`);\n }\n\n const oldLessons = lessons.filter((l) => getLessonAgeDays(l) > AGE_FLAG_THRESHOLD_DAYS);\n if (oldLessons.length > 0) {\n console.log('');\n out.warn(`${oldLessons.length} lesson(s) are over ${AGE_FLAG_THRESHOLD_DAYS} days old. Review for continued validity.`);\n }\n}\n\nasync function checkPlanAction(cmd: Command, options: { plan?: string; json?: boolean; limit: string }): Promise<void> {\n const repoRoot = getRepoRoot();\n const limit = parseLimitOrExit(options.limit, 'limit', 'check-plan');\n const { quiet } = getGlobalOpts(cmd);\n\n const planText = options.plan ?? (await readPlanFromStdin());\n\n if (!planText) {\n console.error(formatError('check-plan', 'NO_PLAN', 'No plan provided', 'Use --plan <text> or pipe text to stdin'));\n process.exit(1);\n }\n\n const usability = await isModelUsable();\n if (!usability.usable) {\n if (options.json) {\n console.log(JSON.stringify({\n lessons: [],\n count: 0,\n error: usability.reason,\n action: usability.action,\n }));\n } else {\n console.error(formatError('check-plan', 'MODEL_UNAVAILABLE', usability.reason, usability.action));\n }\n process.exit(1);\n }\n\n try {\n const result = await retrieveForPlan(repoRoot, planText, limit);\n\n if (options.json) {\n outputCheckPlanJson(result.lessons);\n return;\n }\n\n if (result.lessons.length === 0) {\n console.log('No relevant lessons found for this plan.');\n return;\n }\n\n outputCheckPlanHuman(result.lessons, quiet);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Unknown error';\n if (options.json) {\n console.log(JSON.stringify({\n lessons: [],\n count: 0,\n error: message,\n }));\n } else {\n console.error(formatError('check-plan', 'PLAN_CHECK_FAILED', message, 'Check model installation and try again'));\n }\n process.exit(1);\n }\n}\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\n/**\n * Register retrieval commands (search, list, check-plan, load-session) on the program.\n */\nexport function registerRetrievalCommands(program: Command): void {\n program\n .command('search <query>')\n .description('Search lessons by keyword')\n .option('-n, --limit <number>', 'Maximum results', DEFAULT_SEARCH_LIMIT)\n .action(async function (this: Command, query: string, options: { limit: string }) {\n await searchAction(this, query, options);\n });\n\n program\n .command('list')\n .description('List all lessons')\n .option('-n, --limit <number>', 'Maximum results', DEFAULT_LIST_LIMIT)\n .option('--invalidated', 'Show only invalidated lessons')\n .action(async function (this: Command, options: { limit: string; invalidated?: boolean }) {\n await listAction(this, options);\n });\n\n program\n .command('load-session')\n .description('Load high-severity lessons for session context')\n .option('--json', 'Output as JSON')\n .action(async function (this: Command, options: { json?: boolean }) {\n await loadSessionAction(this, options);\n });\n\n program\n .command('check-plan')\n .description('Check plan against relevant lessons')\n .option('--plan <text>', 'Plan text to check')\n .option('--json', 'Output as JSON')\n .option('-n, --limit <number>', 'Maximum results', DEFAULT_CHECK_PLAN_LIMIT)\n .action(async function (this: Command, options: { plan?: string; json?: boolean; limit: string }) {\n await checkPlanAction(this, options);\n });\n}\n","/**\n * Command modules for CLI.\n *\n * Each module exports a registration function that adds commands to the program.\n */\n\nimport type { Command } from 'commander';\n\nimport {\n registerClaudeSubcommand,\n registerDownloadModelCommand,\n registerHooksCommand,\n registerInitCommand,\n registerSetupAllCommand,\n} from '../setup/index.js';\n\nimport { registerCrudCommands } from './management-crud.js';\nimport { registerInvalidationCommands } from './management-invalidation.js';\nimport { registerIOCommands } from './management-io.js';\nimport { registerMaintenanceCommands } from './management-maintenance.js';\nimport { registerPrimeCommand } from './management-prime.js';\nimport { registerAuditCommands } from './audit.js';\nimport { registerRulesCommands } from './rules.js';\nimport { registerTestSummaryCommand } from './test-summary.js';\n\nexport { registerCaptureCommands } from './capture.js';\nexport { registerRetrievalCommands } from './retrieval.js';\n\n// Re-export types and helpers from management modules\nexport { formatLessonHuman, wasLessonDeleted } from './management-helpers.js';\nexport { getPrimeContext } from './management-prime.js';\n\n// Re-export shared utilities for use by cli.ts\nexport { getGlobalOpts, out } from './shared.js';\nexport type { GlobalOpts } from './shared.js';\n\n/**\n * Register all setup commands on the program.\n */\nexport function registerSetupCommands(program: Command): void {\n registerInitCommand(program);\n registerHooksCommand(program);\n\n // Create the main setup command. The \"all\" action is registered as the\n // default subcommand so its options (--uninstall, --dry-run) don't\n // conflict with identically-named options on the \"claude\" subcommand.\n const setupCommand = program.command('setup');\n registerSetupAllCommand(setupCommand);\n\n // Add subcommands to setup\n registerClaudeSubcommand(setupCommand);\n\n registerDownloadModelCommand(program);\n}\n\n/**\n * Register all management commands on the program.\n */\nexport function registerManagementCommands(program: Command): void {\n registerInvalidationCommands(program);\n registerMaintenanceCommands(program);\n registerIOCommands(program);\n registerPrimeCommand(program);\n registerCrudCommands(program);\n registerAuditCommands(program);\n registerRulesCommands(program);\n registerTestSummaryCommand(program);\n}\n","#!/usr/bin/env node\n/**\n * Compound Agent CLI\n *\n * Semantically-intelligent workflow plugin for Claude Code.\n *\n * Commands:\n * Capture: learn, capture, detect\n * Retrieval: search, list, check-plan, load-session\n * Management: wrong, validate, compact, stats, rebuild, export, import, show, update, delete\n * Setup: init, setup claude, hooks, download-model\n */\n\nimport { Command } from 'commander';\n\nimport { registerCompoundCommands } from './commands/compound.js';\nimport {\n registerCaptureCommands,\n registerManagementCommands,\n registerRetrievalCommands,\n registerSetupCommands,\n} from './commands/index.js';\nimport { VERSION } from './index.js';\nimport { closeDb } from './memory/storage/index.js';\n\n// ============================================================================\n// Resource Cleanup\n// ============================================================================\n\n/**\n * Cleanup function to release database resources.\n * Safe to call even if database was never opened.\n *\n * Note: We only close the SQLite database here. The embedding model\n * (node-llama-cpp) handles its own cleanup and calling unloadEmbedding()\n * during signal handlers can cause issues with the native addon.\n */\nfunction cleanup(): void {\n try {\n closeDb();\n } catch {\n // Ignore errors - database may never have been opened\n }\n}\n\n// Register cleanup for interrupt signals only (not 'exit')\n// The 'exit' handler can interfere with normal process shutdown\nprocess.on('SIGINT', () => {\n cleanup();\n process.exit(0);\n});\nprocess.on('SIGTERM', () => {\n cleanup();\n process.exit(0);\n});\n\n// ============================================================================\n// Program Setup\n// ============================================================================\n\nconst program = new Command();\n\n// Add global options\nprogram\n .option('-v, --verbose', 'Show detailed output')\n .option('-q, --quiet', 'Suppress non-essential output');\n\nprogram\n .name('ca')\n .description('Semantically-intelligent workflow plugin for Claude Code')\n .version(VERSION);\n\n// ============================================================================\n// Register Command Modules\n// ============================================================================\n\nregisterCaptureCommands(program);\nregisterRetrievalCommands(program);\nregisterManagementCommands(program);\nregisterSetupCommands(program);\nregisterCompoundCommands(program);\n\n// ============================================================================\n// Parse and Execute\n// ============================================================================\n\nprogram.parse();\n"]}
|