@orquentra/codebuddy 0.0.0-stage → 2.4.1

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.
Files changed (82) hide show
  1. package/ARCHITECTURE.md +269 -0
  2. package/CLAUDE_CODEX.md +433 -0
  3. package/LICENSE +21 -0
  4. package/README.md +55 -2
  5. package/WORKFLOW.md +152 -0
  6. package/dist/chunk-3ZELDCR3.js +204 -0
  7. package/dist/chunk-3ZELDCR3.js.map +1 -0
  8. package/dist/chunk-5OWZVZSO.js +476 -0
  9. package/dist/chunk-5OWZVZSO.js.map +1 -0
  10. package/dist/chunk-DSN5CEHO.js +175 -0
  11. package/dist/chunk-DSN5CEHO.js.map +1 -0
  12. package/dist/chunk-GDJH7XJC.js +119 -0
  13. package/dist/chunk-GDJH7XJC.js.map +1 -0
  14. package/dist/chunk-IBMJYIEP.js +1578 -0
  15. package/dist/chunk-IBMJYIEP.js.map +1 -0
  16. package/dist/chunk-IE2OUO54.js +199 -0
  17. package/dist/chunk-IE2OUO54.js.map +1 -0
  18. package/dist/chunk-IHQM2ZDV.js +19 -0
  19. package/dist/chunk-IHQM2ZDV.js.map +1 -0
  20. package/dist/chunk-ITGRANYW.js +63 -0
  21. package/dist/chunk-ITGRANYW.js.map +1 -0
  22. package/dist/chunk-K63EOA4B.js +416 -0
  23. package/dist/chunk-K63EOA4B.js.map +1 -0
  24. package/dist/chunk-OLFCOR4U.js +8580 -0
  25. package/dist/chunk-OLFCOR4U.js.map +1 -0
  26. package/dist/chunk-PQK3GKZH.js +98 -0
  27. package/dist/chunk-PQK3GKZH.js.map +1 -0
  28. package/dist/chunk-PYLH4MH5.js +34 -0
  29. package/dist/chunk-PYLH4MH5.js.map +1 -0
  30. package/dist/chunk-PZ5AY32C.js +10 -0
  31. package/dist/chunk-PZ5AY32C.js.map +1 -0
  32. package/dist/chunk-TI5TQD6D.js +324 -0
  33. package/dist/chunk-TI5TQD6D.js.map +1 -0
  34. package/dist/chunk-WHZSVY2L.js +144 -0
  35. package/dist/chunk-WHZSVY2L.js.map +1 -0
  36. package/dist/cli/index.d.ts +1 -0
  37. package/dist/cli/index.js +15 -0
  38. package/dist/cli/index.js.map +1 -0
  39. package/dist/codebuddy-D2xJ6hFk.d.ts +841 -0
  40. package/dist/config-S2TULOMK.js +11 -0
  41. package/dist/config-S2TULOMK.js.map +1 -0
  42. package/dist/index.d.ts +2527 -0
  43. package/dist/index.js +116 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/langgraph/index.d.ts +53 -0
  46. package/dist/langgraph/index.js +143 -0
  47. package/dist/langgraph/index.js.map +1 -0
  48. package/dist/lean-command-D6TZJEFX.js +13 -0
  49. package/dist/lean-command-D6TZJEFX.js.map +1 -0
  50. package/dist/main-BFDVQHKO.js +4575 -0
  51. package/dist/main-BFDVQHKO.js.map +1 -0
  52. package/dist/memory-NIBFAMY4.js +57 -0
  53. package/dist/memory-NIBFAMY4.js.map +1 -0
  54. package/dist/pretool-command-MQQ2UNQM.js +10 -0
  55. package/dist/pretool-command-MQQ2UNQM.js.map +1 -0
  56. package/dist/rerank-Q7MIFNKA.js +60 -0
  57. package/dist/rerank-Q7MIFNKA.js.map +1 -0
  58. package/dist/summaries-TSE44KUQ.js +18 -0
  59. package/dist/summaries-TSE44KUQ.js.map +1 -0
  60. package/dist/zvec-F27AR357.js +23 -0
  61. package/dist/zvec-F27AR357.js.map +1 -0
  62. package/docker-compose.yml +20 -0
  63. package/examples/claude-code/README.md +67 -0
  64. package/examples/claude-desktop/README.md +54 -0
  65. package/examples/claude-desktop/claude_desktop_config.json +13 -0
  66. package/examples/langgraph-agent/README.md +32 -0
  67. package/examples/langgraph-agent/index.ts +71 -0
  68. package/examples/multi-agent-handoff/README.md +35 -0
  69. package/examples/multi-agent-handoff/index.ts +68 -0
  70. package/package.json +108 -4
  71. package/src/db/migrations/0000_cultured_satana.sql +144 -0
  72. package/src/db/migrations/0001_embedding_lease.sql +3 -0
  73. package/src/db/migrations/0002_embedding_lease_token.sql +1 -0
  74. package/src/db/migrations/0003_embedding_space.sql +9 -0
  75. package/src/db/migrations/0004_markdown_reconcile.sql +5 -0
  76. package/src/db/migrations/0005_fact_propositions.sql +1 -0
  77. package/src/db/migrations/meta/0000_snapshot.json +1169 -0
  78. package/src/db/migrations/meta/0002_snapshot.json +1181 -0
  79. package/src/db/migrations/meta/0003_snapshot.json +1214 -0
  80. package/src/db/migrations/meta/0004_snapshot.json +1225 -0
  81. package/src/db/migrations/meta/0005_snapshot.json +1231 -0
  82. package/src/db/migrations/meta/_journal.json +48 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/map/indexer.ts","../src/indexer/engine.ts","../src/map/cache.ts","../src/indexer/store.ts","../src/indexer/types.ts","../src/indexer/scan.ts","../src/indexer/summary.ts","../src/integrations/graphify.ts","../src/map/graph-freshness.ts","../src/context/discovery.ts","../src/map/graphify.ts","../src/context/anchors.ts"],"sourcesContent":["import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { dirname, extname, join, relative, resolve } from \"node:path\";\nimport type { ArchitectureMap, MapQuery, ModuleEdge, ModuleNode } from \"./types.js\";\n\nconst SUPPORTED_EXTENSIONS = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\nconst IGNORED_DIRECTORIES = new Set([\n \".git\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \"coverage\",\n \".codebuddy\",\n]);\n\nexport async function buildArchitectureMap(\n repositoryRoot = process.cwd(),\n): Promise<ArchitectureMap> {\n const root = resolve(repositoryRoot);\n const files = await listSourceFiles(root);\n const fileSet = new Set(files.map((file) => normalize(relative(root, file))));\n const modules: ModuleNode[] = [];\n const edges: ModuleEdge[] = [];\n\n for (const absolutePath of files) {\n const source = await readFile(absolutePath, \"utf8\");\n const from = normalize(relative(root, absolutePath));\n const imports = extractImports(source);\n const resolvedImports: string[] = [];\n for (const specifier of imports) {\n const resolved = resolveImport(root, from, specifier.value, fileSet);\n if (!resolved) continue;\n resolvedImports.push(resolved);\n edges.push({ from, to: resolved, kind: specifier.kind });\n }\n modules.push({\n path: from,\n language: extname(absolutePath).includes(\"ts\") ? \"ts\" : \"js\",\n imports: [...new Set(resolvedImports)].sort(),\n });\n }\n\n return {\n modules: modules.sort((left, right) => left.path.localeCompare(right.path)),\n edges: edges.sort((left, right) =>\n `${left.from}:${left.to}`.localeCompare(`${right.from}:${right.to}`),\n ),\n };\n}\n\nexport type IncrementalMapStats = { readFiles: number; reusedFiles: number; rebuilt: boolean };\n\n/** Build or update a map from an already-known source file set. */\nexport async function updateArchitectureMap(\n repositoryRoot: string,\n sourcePaths: string[],\n previous: ArchitectureMap | null,\n changedPaths: string[],\n): Promise<{ map: ArchitectureMap; stats: IncrementalMapStats }> {\n const root = resolve(repositoryRoot);\n const normalizedPaths = sourcePaths.map(normalize).sort();\n const fileSet = new Set(normalizedPaths);\n const changed = new Set(changedPaths.map(normalize));\n const retainedModules = (previous?.modules ?? []).filter(\n (module) => fileSet.has(module.path) && !changed.has(module.path),\n );\n const retainedEdges = (previous?.edges ?? []).filter(\n (edge) => fileSet.has(edge.from) && fileSet.has(edge.to) && !changed.has(edge.from),\n );\n const modules = [...retainedModules];\n const edges = [...retainedEdges];\n\n for (const path of normalizedPaths) {\n if (!changed.has(path)) continue;\n const source = await readFile(join(root, path), \"utf8\");\n const imports = extractImports(source);\n const resolvedImports: string[] = [];\n for (const specifier of imports) {\n const resolvedImport = resolveImport(root, path, specifier.value, fileSet);\n if (!resolvedImport) continue;\n resolvedImports.push(resolvedImport);\n edges.push({ from: path, to: resolvedImport, kind: specifier.kind });\n }\n modules.push({\n path,\n language: extname(path).includes(\"ts\") ? \"ts\" : \"js\",\n imports: [...new Set(resolvedImports)].sort(),\n });\n }\n\n return {\n map: {\n modules: modules.sort((left, right) => left.path.localeCompare(right.path)),\n edges: edges.sort((left, right) =>\n `${left.from}:${left.to}`.localeCompare(`${right.from}:${right.to}`),\n ),\n },\n stats: {\n readFiles: changed.size,\n reusedFiles: retainedModules.length,\n rebuilt: previous === null || changed.size === normalizedPaths.length,\n },\n };\n}\n\nexport function queryMap(map: ArchitectureMap, query: MapQuery): ModuleEdge[] {\n const limit = query.limit ?? 50;\n return map.edges\n .filter((edge) => (query.from ? edge.from === normalize(query.from) : true))\n .filter((edge) => (query.to ? edge.to === normalize(query.to) : true))\n .slice(0, limit);\n}\n\nexport function neighbours(\n map: ArchitectureMap,\n modulePath: string,\n direction: \"in\" | \"out\" | \"both\" = \"both\",\n): { modules: ModuleNode[]; edges: ModuleEdge[] } {\n const target = normalize(modulePath);\n const edges = map.edges.filter((edge) => {\n if (direction === \"in\") return edge.to === target;\n if (direction === \"out\") return edge.from === target;\n return edge.from === target || edge.to === target;\n });\n const paths = new Set<string>([target]);\n for (const edge of edges) {\n paths.add(edge.from);\n paths.add(edge.to);\n }\n return {\n modules: map.modules.filter((module) => paths.has(module.path)),\n edges,\n };\n}\n\nasync function listSourceFiles(root: string): Promise<string[]> {\n const files: string[] = [];\n await walk(root, files);\n return files.sort();\n}\n\nasync function walk(directory: string, files: string[]): Promise<void> {\n const entries = await readdir(directory, { withFileTypes: true });\n for (const entry of entries) {\n const absolute = join(directory, entry.name);\n if (entry.isDirectory()) {\n if (IGNORED_DIRECTORIES.has(entry.name)) continue;\n await walk(absolute, files);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!SUPPORTED_EXTENSIONS.has(extname(entry.name))) continue;\n const info = await stat(absolute);\n if (info.size > 500_000) continue;\n files.push(absolute);\n }\n}\n\nfunction extractImports(source: string): Array<{ value: string; kind: ModuleEdge[\"kind\"] }> {\n const imports: Array<{ value: string; kind: ModuleEdge[\"kind\"] }> = [];\n // Strip line/block comments first so quoted specifiers inside comments can't\n // fabricate phantom edges in the architecture map.\n const stripped = source.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \" \").replace(/(^|[^:])\\/\\/[^\\n]*/g, \"$1 \");\n const staticImport = /\\bimport\\s+(?:type\\s+)?(?:[^'\"()+]+?\\s+from\\s+)?[\"']([^\"']+)[\"']/g;\n const exportFrom = /\\bexport\\s+[^'\"()+]+?\\s+from\\s+[\"']([^\"']+)[\"']/g;\n const dynamicImport = /\\bimport\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n for (const match of stripped.matchAll(staticImport)) {\n if (match[1]) imports.push({ value: match[1], kind: \"import\" });\n }\n for (const match of stripped.matchAll(exportFrom)) {\n if (match[1]) imports.push({ value: match[1], kind: \"import\" });\n }\n for (const match of stripped.matchAll(dynamicImport)) {\n if (match[1]) imports.push({ value: match[1], kind: \"dynamic_import\" });\n }\n return imports;\n}\n\nfunction resolveImport(\n root: string,\n from: string,\n specifier: string,\n fileSet: Set<string>,\n): string | null {\n if (!specifier.startsWith(\".\")) return null;\n const base = normalize(relative(root, resolve(root, dirname(from), specifier)));\n // ESM specifiers point at emitted JS (`./x.js`), but the source on disk is\n // often `./x.ts`. Try the specifier EXACTLY as written first (so a real\n // `x.js` file wins when both `x.ts` and `x.js` exist), then fall back to the\n // extension-stripped stem for the TS-source case.\n const stem = base.replace(/\\.(js|jsx|mjs|cjs)$/, \"\");\n const bases = stem === base ? [base] : [base, stem];\n const candidates = bases.flatMap((b) => [\n b,\n `${b}.ts`,\n `${b}.tsx`,\n `${b}.js`,\n `${b}.jsx`,\n `${b}.mjs`,\n `${b}.cjs`,\n `${b}/index.ts`,\n `${b}/index.tsx`,\n `${b}/index.js`,\n `${b}/index.jsx`,\n ]);\n return candidates.find((candidate) => fileSet.has(candidate)) ?? null;\n}\n\nfunction normalize(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n","import { createHash } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { refreshArchitectureCache } from \"../map/cache.js\";\nimport { listIndexableFiles } from \"./scan.js\";\nimport { emptyManifest, IndexStore } from \"./store.js\";\nimport { summarizeSource } from \"./summary.js\";\nimport { extractSymbolTable, supportsSymbols } from \"./symbols.js\";\nimport {\n INDEX_MANIFEST_VERSION,\n type IndexEntry,\n type IndexError,\n type IndexManifest,\n type IndexResult,\n} from \"./types.js\";\n\n/**\n * Incremental repository indexing. A file is re-summarized only when its\n * content hash differs from the manifest, so repeated runs over an unchanged\n * tree are cheap and deterministic. A file whose size, mtime and ctime still\n * match the entry is not even re-read. Per-file failures (unreadable, too\n * large) are isolated and reported; they never abort the pass. `full` ignores\n * existing hashes and rebuilds every entry.\n *\n * The same pass doubles as use-time validation (`loadFreshIndex`): context\n * tools run it before trusting indexed symbols, summaries or imports, so a CLI\n * or hook process with no watcher still sees current source.\n */\n\n/** Skip files larger than this — summarizing them is neither cheap nor useful. */\nconst MAX_FILE_BYTES = 512_000;\n/**\n * Files changed this recently are always re-hashed: a second edit inside a\n * coarse mtime tick could otherwise keep the same size and timestamps.\n */\nconst RACY_WINDOW_MS = 3_000;\n\nexport type IndexOptions = {\n repositoryRoot?: string;\n full?: boolean;\n /** Injectable clock for deterministic tests. */\n now?: () => Date;\n};\n\nexport async function indexRepository(options: IndexOptions = {}): Promise<IndexResult> {\n return (await refreshIndex(options)).result;\n}\n\nexport type FreshIndex = {\n manifest: IndexManifest;\n /** One `index:` explain line: how the manifest compared with current source. */\n explain: string;\n};\n\n/**\n * The manifest, validated against current source right now. Changed files are\n * re-summarized (symbols, imports), deleted ones dropped, new ones added, and\n * the result is persisted so the next call takes the metadata fast path. Never\n * throws: if validation fails the stored manifest is returned with a reason.\n */\nexport async function loadFreshIndex(repositoryRoot: string): Promise<FreshIndex> {\n try {\n const { result, manifest } = await refreshIndex({ repositoryRoot });\n const delta = result.added + result.changed + result.removed;\n const failures =\n result.errors.length > 0\n ? `; ${result.errors.length} file(s) could not be validated and were omitted`\n : \"\";\n return {\n manifest,\n explain:\n delta === 0\n ? `index: ${result.totalIndexed} indexed file(s) match current source${failures}`\n : `index: refreshed against current source (${result.changed} changed, ${result.added} added, ${result.removed} removed; ${result.totalIndexed} indexed)${failures}`,\n };\n } catch (error) {\n return {\n manifest: emptyManifest(),\n explain: `index: freshness check failed (${(error as Error).message}); indexed evidence omitted`,\n };\n }\n}\n\n// ponytail: in-process serialization only; separate processes (hook + MCP\n// server) can still race, which the metadata check heals on the next pass.\nconst passes = new Map<string, Promise<unknown>>();\n\n/** One pass at a time per repository, so overlapping callers never interleave writes. */\nfunction refreshIndex(\n options: IndexOptions,\n): Promise<{ result: IndexResult; manifest: IndexManifest }> {\n const key = resolve(options.repositoryRoot ?? process.cwd());\n const next = (passes.get(key) ?? Promise.resolve())\n .catch(() => undefined)\n .then(() => runIndexPass(options));\n passes.set(key, next);\n void next\n .finally(() => {\n if (passes.get(key) === next) passes.delete(key);\n })\n .catch(() => undefined);\n return next;\n}\n\nasync function runIndexPass(\n options: IndexOptions,\n): Promise<{ result: IndexResult; manifest: IndexManifest }> {\n const start = Date.now();\n const now = options.now ?? (() => new Date());\n const repositoryRoot = resolve(options.repositoryRoot ?? process.cwd());\n const store = new IndexStore(repositoryRoot);\n\n const [files, previous] = await Promise.all([listIndexableFiles(repositoryRoot), store.read()]);\n\n const entries: Record<string, IndexEntry> = {};\n const errors: IndexError[] = [];\n let added = 0;\n let changed = 0;\n let unchanged = 0;\n let skipped = 0;\n // A never-written manifest is persisted even when the tree is empty.\n let dirty = previous.generatedAt === emptyManifest().generatedAt;\n\n for (const path of files) {\n try {\n const info = await stat(join(repositoryRoot, path));\n if (!info.isFile()) continue;\n if (info.size > MAX_FILE_BYTES) {\n skipped++;\n continue;\n }\n\n const existing = previous.entries[path];\n if (!options.full && existing && statUnchanged(existing, info)) {\n entries[path] = existing;\n unchanged++;\n continue;\n }\n\n const content = await readFile(join(repositoryRoot, path), \"utf8\");\n const hash = hashContent(content);\n const metadata = trustedMetadata(info);\n dirty = true;\n\n if (!options.full && existing && existing.hash === hash) {\n const { mtimeMs: _mtime, ctimeMs: _ctime, ...rest } = existing;\n entries[path] = { ...rest, size: info.size, ...metadata };\n unchanged++;\n continue;\n }\n\n const { language, lines, symbols, summary } = summarizeSource(path, content);\n const symbolTable = supportsSymbols(path) ? extractSymbolTable(content) : [];\n entries[path] = {\n path,\n hash,\n size: info.size,\n ...metadata,\n language,\n lines,\n symbols,\n ...(symbolTable.length > 0 ? { symbolTable } : {}),\n summary,\n indexedAt: now().toISOString(),\n };\n if (existing) changed++;\n else added++;\n } catch (error) {\n errors.push({ path, error: (error as Error).message });\n skipped++;\n }\n }\n\n const removed = Object.keys(previous.entries).filter((path) => !(path in entries)).length;\n\n const manifest: IndexManifest = {\n version: INDEX_MANIFEST_VERSION,\n generatedAt: now().toISOString(),\n entries: sortEntries(entries),\n };\n if (dirty || removed > 0) await store.write(manifest);\n const architecture = await refreshArchitectureCache(repositoryRoot, manifest);\n\n const result: IndexResult = {\n scanned: files.length,\n added,\n changed,\n unchanged,\n removed,\n skipped,\n errors,\n durationMs: Date.now() - start,\n totalIndexed: Object.keys(entries).length,\n architecture: {\n source: architecture.source,\n readFiles: architecture.stats.readFiles,\n reusedFiles: architecture.stats.reusedFiles,\n },\n };\n return { result, manifest };\n}\n\nfunction statUnchanged(entry: IndexEntry, info: Stats): boolean {\n return (\n entry.mtimeMs !== undefined &&\n entry.size === info.size &&\n entry.mtimeMs === info.mtimeMs &&\n entry.ctimeMs === info.ctimeMs\n );\n}\n\n/** Stat metadata worth trusting later, or nothing while the file is still racy. */\nfunction trustedMetadata(info: Stats): { mtimeMs?: number; ctimeMs?: number } {\n if (Date.now() - Math.max(info.mtimeMs, info.ctimeMs) < RACY_WINDOW_MS) return {};\n return { mtimeMs: info.mtimeMs, ctimeMs: info.ctimeMs };\n}\n\nexport function hashContent(content: string): string {\n return createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction sortEntries(entries: Record<string, IndexEntry>): Record<string, IndexEntry> {\n return Object.fromEntries(\n Object.keys(entries)\n .sort()\n .map((key) => [key, entries[key] as IndexEntry]),\n );\n}\n","import { mkdir, readFile } from \"node:fs/promises\";\nimport { dirname, extname, join, resolve } from \"node:path\";\nimport { assertNoSymlinkBetween, writeAtomic } from \"../core/markdown-store-fs.js\";\nimport { IndexStore } from \"../indexer/store.js\";\nimport type { IndexManifest } from \"../indexer/types.js\";\nimport {\n buildArchitectureMap,\n type IncrementalMapStats,\n updateArchitectureMap,\n} from \"./indexer.js\";\nimport type { ArchitectureMap } from \"./types.js\";\n\nconst CACHE_VERSION = 1;\nconst SOURCE_EXTENSIONS = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n\ntype ArchitectureCache = {\n version: 1;\n generatedAt: string;\n sourceHashes: Record<string, string>;\n map: ArchitectureMap;\n};\n\nexport type CachedArchitectureResult = {\n map: ArchitectureMap;\n stats: IncrementalMapStats;\n source: \"cache\" | \"incremental\" | \"rebuild\" | \"fallback\";\n};\n\nexport async function loadArchitectureMap(\n repositoryRoot = process.cwd(),\n suppliedManifest?: IndexManifest,\n): Promise<CachedArchitectureResult> {\n const root = resolve(repositoryRoot);\n const manifest = suppliedManifest ?? (await new IndexStore(root).read());\n if (Object.keys(manifest.entries).length === 0) {\n const map = await buildArchitectureMap(root);\n return {\n map,\n stats: { readFiles: map.modules.length, reusedFiles: 0, rebuilt: true },\n source: \"fallback\",\n };\n }\n return refreshArchitectureCache(root, manifest);\n}\n\nexport async function refreshArchitectureCache(\n repositoryRoot: string,\n manifest: IndexManifest,\n): Promise<CachedArchitectureResult> {\n const root = resolve(repositoryRoot);\n const path = join(root, \".codebuddy\", \"cache\", \"architecture.json\");\n const currentHashes = sourceHashes(manifest);\n const currentPaths = Object.keys(currentHashes).sort();\n const cached = await readCache(path);\n const cachedPaths = cached ? Object.keys(cached.sourceHashes).sort() : [];\n const fileSetChanged = cachedPaths.join(\"\\n\") !== currentPaths.join(\"\\n\");\n const changedPaths =\n !cached || fileSetChanged\n ? currentPaths\n : currentPaths.filter(\n (sourcePath) => cached.sourceHashes[sourcePath] !== currentHashes[sourcePath],\n );\n\n if (cached && changedPaths.length === 0) {\n return {\n map: cached.map,\n stats: { readFiles: 0, reusedFiles: cached.map.modules.length, rebuilt: false },\n source: \"cache\",\n };\n }\n\n const updated = await updateArchitectureMap(\n root,\n currentPaths,\n fileSetChanged ? null : (cached?.map ?? null),\n changedPaths,\n );\n const next: ArchitectureCache = {\n version: CACHE_VERSION,\n generatedAt: manifest.generatedAt,\n sourceHashes: currentHashes,\n map: updated.map,\n };\n await assertNoSymlinkBetween(root, dirname(path));\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await writeAtomic(path, `${JSON.stringify(next, null, 2)}\\n`);\n return { ...updated, source: fileSetChanged || !cached ? \"rebuild\" : \"incremental\" };\n}\n\nasync function readCache(path: string): Promise<ArchitectureCache | null> {\n try {\n const parsed = JSON.parse(await readFile(path, \"utf8\")) as ArchitectureCache;\n if (parsed.version !== CACHE_VERSION || !parsed.map || !parsed.sourceHashes) return null;\n if (!Array.isArray(parsed.map.modules) || !Array.isArray(parsed.map.edges)) return null;\n if (\n !parsed.map.modules.every(\n (module) =>\n module &&\n typeof module.path === \"string\" &&\n typeof module.language === \"string\" &&\n Array.isArray(module.imports),\n ) ||\n !parsed.map.edges.every(\n (edge) => edge && typeof edge.from === \"string\" && typeof edge.to === \"string\",\n )\n ) {\n return null;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction sourceHashes(manifest: IndexManifest): Record<string, string> {\n return Object.fromEntries(\n Object.values(manifest.entries)\n .filter((entry) => SOURCE_EXTENSIONS.has(extname(entry.path).toLowerCase()))\n .map((entry) => [entry.path, entry.hash]),\n );\n}\n","import { mkdir, readFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { assertNoSymlinkBetween, writeAtomic } from \"../core/markdown-store-fs.js\";\nimport { INDEX_MANIFEST_VERSION, type IndexManifest } from \"./types.js\";\n\n/**\n * Persists the index manifest as a single JSON file under\n * `.codebuddy/cache/index.json`. `cache/` is gitignored by the project\n * scaffold, so the manifest is treated as a rebuildable derived artifact —\n * corrupt or version-mismatched manifests degrade to \"empty\" rather than\n * throwing, and a full `codebuddy index` regenerates them.\n */\n\nconst symbolSpanSchema = z.object({\n name: z.string(),\n kind: z.enum([\"function\", \"method\", \"class\", \"interface\", \"type\", \"enum\", \"const\"]),\n startLine: z.number().int().nonnegative(),\n endLine: z.number().int().nonnegative(),\n signature: z.string(),\n exported: z.boolean(),\n});\n\nconst entrySchema = z.object({\n path: z.string(),\n hash: z.string(),\n size: z.number().int().nonnegative(),\n mtimeMs: z.number().optional(),\n ctimeMs: z.number().optional(),\n language: z.string(),\n lines: z.number().int().nonnegative(),\n symbols: z.array(z.string()),\n symbolTable: z.array(symbolSpanSchema).optional(),\n summary: z.string(),\n indexedAt: z.string(),\n});\n\nconst manifestSchema = z.object({\n version: z.literal(INDEX_MANIFEST_VERSION),\n generatedAt: z.string(),\n entries: z.record(z.string(), entrySchema),\n});\n\nexport class IndexStore {\n readonly repositoryRoot: string;\n readonly cacheDirectory: string;\n readonly manifestPath: string;\n\n constructor(repositoryRoot = process.cwd()) {\n this.repositoryRoot = resolve(repositoryRoot);\n this.cacheDirectory = join(this.repositoryRoot, \".codebuddy\", \"cache\");\n this.manifestPath = join(this.cacheDirectory, \"index.json\");\n }\n\n /** Read the manifest, or an empty one if absent/corrupt/version-mismatched. */\n async read(): Promise<IndexManifest> {\n try {\n const raw = await readFile(this.manifestPath, \"utf8\");\n const parsed = manifestSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) return emptyManifest();\n // Zod's optional() widens to `| undefined`; the parse guarantees the shape.\n return parsed.data as IndexManifest;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return emptyManifest();\n // Unreadable cache is non-fatal: rebuild from scratch.\n return emptyManifest();\n }\n }\n\n async write(manifest: IndexManifest): Promise<void> {\n await assertNoSymlinkBetween(this.repositoryRoot, dirname(this.manifestPath));\n await mkdir(this.cacheDirectory, { recursive: true, mode: 0o700 });\n await writeAtomic(this.manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n }\n}\n\nexport function emptyManifest(): IndexManifest {\n return { version: INDEX_MANIFEST_VERSION, generatedAt: new Date(0).toISOString(), entries: {} };\n}\n","/**\n * Background index model (Proposal 04 Phase 04.3). The indexer builds a\n * deterministic, local-first picture of the repository — one content hash and\n * one lightweight summary per indexable file — so CodeBuddy knows something\n * useful before any memory is manually written. It is a derived *cache* under\n * `.codebuddy/cache/`, never a source of truth: deleting it and re-running\n * `codebuddy index` reproduces it exactly. No LLM is involved; summaries are\n * extracted with simple, stable heuristics.\n */\n\nimport type { SymbolSpan } from \"./symbols.js\";\n\n/** Bumped to 2 when symbol tables gained class methods, so old caches rebuild. */\nexport const INDEX_MANIFEST_VERSION = 2 as const;\n\n/** One indexed file. Everything here is reproducible from the file contents. */\nexport type IndexEntry = {\n /** Repo-relative POSIX path. */\n path: string;\n /** SHA-256 of the file contents; the authoritative change-detection signal. */\n hash: string;\n /** Byte size at index time. */\n size: number;\n /**\n * File mtime/ctime observed when `hash` was taken. Recorded only once the file\n * is older than the racy window, so a matching size+mtime+ctime is a reliable\n * \"unchanged\" shortcut; when absent the file is re-hashed.\n */\n mtimeMs?: number;\n ctimeMs?: number;\n /** Coarse language tag derived from the extension (ts, js, md, py, …). */\n language: string;\n /** Line count (excluding a single trailing newline). */\n lines: number;\n /** Best-effort top-level/exported symbol names. Empty for non-code files. */\n symbols: string[];\n /**\n * Optional richer symbol table (name/kind/range/signature) for code files —\n * the basis for symbol-level context (Roadmap N.3). Absent for non-code files\n * and older manifests, so consumers must treat it as optional.\n */\n symbolTable?: SymbolSpan[];\n /** Deterministic one-line summary. */\n summary: string;\n /** ISO timestamp of when this entry was (re)computed. */\n indexedAt: string;\n};\n\nexport type IndexManifest = {\n version: typeof INDEX_MANIFEST_VERSION;\n generatedAt: string;\n /** Keyed by repo-relative POSIX path. */\n entries: Record<string, IndexEntry>;\n};\n\nexport type IndexError = {\n path: string;\n error: string;\n};\n\n/** Outcome of one indexing pass. Counts are disjoint where noted. */\nexport type IndexResult = {\n scanned: number;\n added: number;\n changed: number;\n /** Unchanged files whose summary was reused (the incremental fast path). */\n unchanged: number;\n /** Entries dropped because the file no longer exists or is now ignored. */\n removed: number;\n /** Files skipped as too large or unreadable (isolated, non-fatal). */\n skipped: number;\n errors: IndexError[];\n durationMs: number;\n totalIndexed: number;\n architecture: {\n source: \"cache\" | \"incremental\" | \"rebuild\" | \"fallback\";\n readFiles: number;\n reusedFiles: number;\n };\n};\n","import { spawn } from \"node:child_process\";\nimport { readdir } from \"node:fs/promises\";\nimport { extname, join, relative } from \"node:path\";\nimport { SUPPORTED_EXTENSIONS } from \"./summary.js\";\n\n/**\n * Enumerate the repo-relative POSIX paths the indexer should consider.\n *\n * `.gitignore` respect is delegated to git itself: `git ls-files` lists tracked\n * plus untracked-but-not-ignored files, which is exactly the set a developer\n * expects to be \"in the project\". When the directory is not a git repository we\n * fall back to a plain walk with a conservative ignore list so indexing still\n * works on partially configured repos.\n *\n * CodeBuddy's own generated artifacts (`.codebuddy/`, `graphify-out/`) are\n * always excluded — the index does not index itself.\n */\n\nconst FALLBACK_IGNORED_DIRECTORIES = new Set([\n \".git\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \"coverage\",\n \".codebuddy\",\n \"graphify-out\",\n \".next\",\n \".turbo\",\n \"out\",\n]);\n\nexport async function listIndexableFiles(repositoryRoot: string): Promise<string[]> {\n const tracked = await gitListFiles(repositoryRoot);\n const paths = tracked ?? (await walkFiles(repositoryRoot));\n return paths\n .map(normalize)\n .filter((path) => !path.startsWith(\".codebuddy/\") && !path.startsWith(\"graphify-out/\"))\n .filter((path) => SUPPORTED_EXTENSIONS.has(extname(path).toLowerCase()))\n .sort();\n}\n\n/** Returns null when the directory is not a git repository. */\nasync function gitListFiles(repositoryRoot: string): Promise<string[] | null> {\n const result = await runGit(repositoryRoot, [\n \"ls-files\",\n \"--cached\",\n \"--others\",\n \"--exclude-standard\",\n ]);\n if (result.code !== 0) return null;\n return result.stdout\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean);\n}\n\nasync function walkFiles(root: string): Promise<string[]> {\n const files: string[] = [];\n const walk = async (directory: string): Promise<void> => {\n const entries = await readdir(directory, { withFileTypes: true });\n for (const entry of entries) {\n const absolute = join(directory, entry.name);\n if (entry.isDirectory()) {\n if (FALLBACK_IGNORED_DIRECTORIES.has(entry.name)) continue;\n await walk(absolute);\n continue;\n }\n if (entry.isFile()) files.push(relative(root, absolute));\n }\n };\n await walk(root);\n return files;\n}\n\nfunction runGit(\n cwd: string,\n args: string[],\n): Promise<{ code: number; stdout: string; stderr: string }> {\n return new Promise((resolveResult) => {\n const child = spawn(\"git\", args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.on(\"data\", (chunk) => {\n stdout += String(chunk);\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += String(chunk);\n });\n // A missing git binary should degrade to the walk fallback, not crash.\n child.on(\"error\", () => resolveResult({ code: -1, stdout: \"\", stderr: \"git unavailable\" }));\n child.on(\"close\", (code) => resolveResult({ code: code ?? 0, stdout, stderr }));\n });\n}\n\nfunction normalize(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n","import { extname } from \"node:path\";\n\n/**\n * Deterministic file summarization. No LLM, no network — the same file always\n * produces the same summary, which keeps the index stable across runs and easy\n * to diff. Symbol extraction is intentionally best-effort regex over source\n * text: good enough to orient an agent, cheap enough to run on every save.\n */\n\nconst LANGUAGE_BY_EXTENSION: Record<string, string> = {\n \".ts\": \"ts\",\n \".tsx\": \"tsx\",\n \".js\": \"js\",\n \".jsx\": \"jsx\",\n \".mjs\": \"js\",\n \".cjs\": \"js\",\n \".json\": \"json\",\n \".md\": \"md\",\n \".mdx\": \"md\",\n \".yaml\": \"yaml\",\n \".yml\": \"yaml\",\n \".toml\": \"toml\",\n \".css\": \"css\",\n \".scss\": \"scss\",\n \".html\": \"html\",\n \".py\": \"py\",\n \".go\": \"go\",\n \".rs\": \"rust\",\n \".java\": \"java\",\n \".rb\": \"ruby\",\n \".php\": \"php\",\n \".sh\": \"shell\",\n \".sql\": \"sql\",\n \".txt\": \"text\",\n};\n\n/** Extensions the indexer will read and summarize. */\nexport const SUPPORTED_EXTENSIONS = new Set(Object.keys(LANGUAGE_BY_EXTENSION));\n\nconst CODE_LANGUAGES = new Set([\"ts\", \"tsx\", \"js\", \"jsx\"]);\nconst SYMBOL_LIMIT = 8;\nconst SUMMARY_COMMENT_MAX = 80;\n\nexport function languageFor(path: string): string {\n return LANGUAGE_BY_EXTENSION[extname(path).toLowerCase()] ?? \"text\";\n}\n\nexport type FileSummary = {\n language: string;\n lines: number;\n symbols: string[];\n summary: string;\n};\n\nexport function summarizeSource(path: string, content: string): FileSummary {\n const language = languageFor(path);\n const lines = countLines(content);\n const symbols = CODE_LANGUAGES.has(language) ? extractSymbols(content) : [];\n const summary = composeSummary(language, lines, symbols, content);\n return { language, lines, symbols, summary };\n}\n\nfunction countLines(content: string): number {\n if (content.length === 0) return 0;\n return content.replace(/\\r/g, \"\").replace(/\\n$/, \"\").split(\"\\n\").length;\n}\n\n/**\n * Pull exported/top-level symbol names from JS/TS source. Covers the common\n * `export <kind> Name` forms, `export default function Name`, and named\n * re-export braces. Order-preserving and de-duplicated.\n */\nexport function extractSymbols(content: string): string[] {\n const names: string[] = [];\n const push = (name: string | undefined) => {\n const trimmed = name?.trim();\n if (trimmed && /^[A-Za-z_$][\\w$]*$/.test(trimmed) && !names.includes(trimmed)) {\n names.push(trimmed);\n }\n };\n\n const declaration =\n /^export\\s+(?:default\\s+)?(?:async\\s+)?(?:abstract\\s+)?(?:const|let|var|function|class|interface|type|enum)\\s+([A-Za-z_$][\\w$]*)/gm;\n for (const match of content.matchAll(declaration)) push(match[1]);\n\n const namedExports = /^export\\s*\\{([^}]*)\\}/gm;\n for (const match of content.matchAll(namedExports)) {\n for (const part of (match[1] ?? \"\").split(\",\")) {\n // Handle `foo as bar` — record the exported name (`bar`).\n const alias = part.includes(\" as \") ? part.split(\" as \").pop() : part;\n push(alias);\n }\n }\n\n return names.slice(0, SYMBOL_LIMIT);\n}\n\nfunction composeSummary(\n language: string,\n lines: number,\n symbols: string[],\n content: string,\n): string {\n const head = `${language} • ${lines} line${lines === 1 ? \"\" : \"s\"}`;\n if (symbols.length > 0) return `${head} • exports ${symbols.join(\", \")}`;\n const comment = leadingComment(content);\n if (comment) return `${head} • ${comment}`;\n return head;\n}\n\n/** First meaningful line of a leading comment block, if any. */\nfunction leadingComment(content: string): string | null {\n for (const raw of content.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (line === \"\") continue;\n const stripped = line\n .replace(/^\\/\\/+/, \"\")\n .replace(/^\\/\\*+/, \"\")\n .replace(/\\*+\\/$/, \"\")\n .replace(/^[#*]+/, \"\")\n .trim();\n if (\n line.startsWith(\"//\") ||\n line.startsWith(\"/*\") ||\n line.startsWith(\"#\") ||\n line.startsWith(\"*\")\n ) {\n if (stripped) return truncate(stripped, SUMMARY_COMMENT_MAX);\n continue;\n }\n // First non-blank line is not a comment: nothing to summarize.\n return null;\n }\n return null;\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length <= max ? value : `${value.slice(0, max - 1)}…`;\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdir, mkdtemp, readFile, rm, stat, utimes } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { writeAtomic } from \"../core/markdown-store-fs.js\";\nimport { loadFreshIndex } from \"../indexer/engine.js\";\nimport { writeGraphSourceSnapshot } from \"../map/graph-freshness.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type GraphifyCommandRunner = (\n command: string,\n args: string[],\n cwd: string,\n) => Promise<{ stdout: string; stderr: string }>;\n\nexport type GraphifySetupOptions = {\n repositoryRoot: string;\n run?: GraphifyCommandRunner;\n};\n\nexport type GraphifySetupResult = {\n available: boolean;\n installed: boolean;\n generated: boolean;\n graphPath: string;\n message: string;\n};\n\nexport type GenerateGraphifyOptions = {\n repositoryRoot: string;\n graphPath?: string;\n run?: GraphifyCommandRunner;\n};\n\nexport type GenerateGraphifyResult = {\n graphPath: string;\n generated: boolean;\n nodes: number;\n edges: number;\n};\n\nconst DEFAULT_GRAPH_PATH = \"graphify-out/graph.json\";\n\n/** Detect, install, and register Graphify without making it a CodeBuddy dependency. */\nexport async function setupGraphify(options: GraphifySetupOptions): Promise<GraphifySetupResult> {\n const run = options.run ?? runCommand;\n let available = await commandWorks(run, \"graphify\", [\"--version\"], options.repositoryRoot);\n let installed = false;\n\n if (!available) {\n const installers = [\n [\"uv\", [\"tool\", \"install\", \"graphifyy\"]],\n [\"pipx\", [\"install\", \"graphifyy\"]],\n [\"python\", [\"-m\", \"pip\", \"install\", \"--user\", \"graphifyy\"]],\n ] as const;\n for (const [command, args] of installers) {\n try {\n await run(command, [...args], options.repositoryRoot);\n available = await commandWorks(run, \"graphify\", [\"--version\"], options.repositoryRoot);\n if (available) {\n installed = true;\n break;\n }\n } catch {\n // Try the next supported local installer.\n }\n }\n }\n\n if (!available) {\n return {\n available: false,\n installed,\n generated: false,\n graphPath: DEFAULT_GRAPH_PATH,\n message:\n \"Graphify was selected but is not available. Install graphifyy with uv/pipx, then run `codebuddy graphify index`.\",\n };\n }\n\n try {\n await run(\"graphify\", [\"install\"], options.repositoryRoot).catch(() => undefined);\n const graph = await generateGraphifyGraph({ repositoryRoot: options.repositoryRoot, run });\n return {\n available: true,\n installed,\n generated: true,\n graphPath: graph.graphPath,\n message: `Graphify graph generated (${graph.nodes} nodes, ${graph.edges} edges).`,\n };\n } catch (error) {\n return {\n available: true,\n installed,\n generated: false,\n graphPath: DEFAULT_GRAPH_PATH,\n message: `Graphify is installed but its graph could not be generated: ${(error as Error).message}`,\n };\n }\n}\n\nasync function commandWorks(\n run: GraphifyCommandRunner,\n command: string,\n args: string[],\n cwd: string,\n): Promise<boolean> {\n try {\n await run(command, args, cwd);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function runCommand(\n command: string,\n args: string[],\n cwd: string,\n): Promise<{ stdout: string; stderr: string }> {\n return execFileAsync(command, args, { cwd });\n}\n\nexport async function graphifyGraphExists(\n repositoryRoot: string,\n graphPath = DEFAULT_GRAPH_PATH,\n): Promise<boolean> {\n try {\n const parsed = await readGraphFile(resolveGraphPath(repositoryRoot, graphPath));\n return parsed.nodes > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Build a graph with Graphify itself. Staging is used for first builds and\n * invalid graphs so a failed extractor can never replace a usable graph.\n */\nexport async function generateGraphifyGraph(\n options: GenerateGraphifyOptions,\n): Promise<GenerateGraphifyResult> {\n const run = options.run ?? runCommand;\n const repositoryRoot = resolve(options.repositoryRoot);\n const graphPath = options.graphPath ?? DEFAULT_GRAPH_PATH;\n const destination = resolveGraphPath(repositoryRoot, graphPath);\n await mkdir(dirname(destination), { recursive: true });\n await ignoreGeneratedGraphDirectory(dirname(destination));\n\n const { manifest: sourceSnapshot } = await loadFreshIndex(repositoryRoot);\n const current = await readGraphFileIfPresent(destination);\n const isDefaultPath = graphPath === DEFAULT_GRAPH_PATH;\n if (current && isDefaultPath) {\n const backup = await readFile(destination, \"utf8\");\n const backupStat = await stat(destination);\n try {\n await run(\"graphify\", [\"update\", repositoryRoot, \"--force\", \"--no-cluster\"], repositoryRoot);\n const updated = await readGraphFile(destination);\n await writeGraphSourceSnapshot(destination, sourceSnapshot);\n return { graphPath, generated: true, ...updated };\n } catch (error) {\n await writeAtomic(destination, backup);\n await utimes(destination, backupStat.atime, backupStat.mtime);\n throw new Error(\n `Graphify update failed; the previous graph was preserved: ${(error as Error).message}`,\n );\n }\n }\n\n const stagingRoot = await mkdtemp(join(tmpdir(), \"codebuddy-graphify-\"));\n try {\n await run(\n \"graphify\",\n [\"extract\", repositoryRoot, \"--out\", stagingRoot, \"--code-only\", \"--no-cluster\"],\n repositoryRoot,\n );\n const stagedPath = join(stagingRoot, DEFAULT_GRAPH_PATH);\n const staged = await readGraphFile(stagedPath);\n await writeAtomic(destination, await readFile(stagedPath, \"utf8\"));\n await writeGraphSourceSnapshot(destination, sourceSnapshot);\n return { graphPath, generated: true, ...staged };\n } finally {\n await rm(stagingRoot, { recursive: true, force: true });\n }\n}\n\n/**\n * The graph directory is derived output CodeBuddy writes itself, so it is\n * self-ignoring like `.codebuddy/`. An existing .gitignore is never rewritten:\n * a project that deliberately commits its graph keeps doing so.\n */\nasync function ignoreGeneratedGraphDirectory(directory: string): Promise<void> {\n const path = join(directory, \".gitignore\");\n try {\n await stat(path);\n } catch {\n await writeAtomic(path, \"# CodeBuddy-generated Graphify output (derived, rebuildable)\\n*\\n\");\n }\n}\n\nfunction resolveGraphPath(repositoryRoot: string, graphPath: string): string {\n const absolute = resolve(repositoryRoot, graphPath);\n const relativePath = relative(repositoryRoot, absolute);\n if (relativePath === \"\" || relativePath === \"..\" || relativePath.startsWith(`..${sep}`)) {\n throw new Error(`Graph path must be inside the project root: ${graphPath}`);\n }\n return absolute;\n}\n\nasync function readGraphFileIfPresent(\n path: string,\n): Promise<{ nodes: number; edges: number } | null> {\n try {\n return await readGraphFile(path);\n } catch {\n return null;\n }\n}\n\nasync function readGraphFile(path: string): Promise<{ nodes: number; edges: number }> {\n const info = await stat(path);\n if (!info.isFile() || info.size === 0)\n throw new Error(`Graphify graph is missing or empty: ${path}`);\n const raw = JSON.parse(await readFile(path, \"utf8\")) as Record<string, unknown>;\n const nodes = arrayLength(raw.nodes ?? raw.entities);\n const edges = arrayLength(raw.edges ?? raw.links ?? raw.relationships);\n if (nodes === 0) throw new Error(`Graphify graph contains no nodes: ${path}`);\n return { nodes, edges };\n}\n\nfunction arrayLength(value: unknown): number {\n return Array.isArray(value) ? value.length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeAtomic } from \"../core/markdown-store-fs.js\";\nimport type { IndexManifest } from \"../indexer/types.js\";\n\nconst digest = (value: string) => createHash(\"sha256\").update(value).digest(\"hex\");\n\n/** Record the source snapshot from BEFORE extraction, so edits during extraction fail closed. */\nexport async function writeGraphSourceSnapshot(\n path: string,\n manifest: IndexManifest,\n): Promise<void> {\n await writeAtomic(\n `${path}.sources.json`,\n JSON.stringify({\n version: 1,\n graphHash: digest(await readFile(path, \"utf8\")),\n sources: Object.fromEntries(\n Object.values(manifest.entries).map((entry) => [entry.path, entry.hash]),\n ),\n }),\n );\n}\n\n/** Missing = legacy graph. Invalid/mismatched = trust no endpoints until rebuilt. */\nexport async function readGraphSourceSnapshot(\n path: string,\n): Promise<Record<string, string> | null> {\n let raw: string;\n try {\n raw = await readFile(`${path}.sources.json`, \"utf8\");\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ENOENT\" ? null : {};\n }\n try {\n const snapshot = JSON.parse(raw);\n if (\n snapshot.version !== 1 ||\n snapshot.graphHash !== digest(await readFile(path, \"utf8\")) ||\n !snapshot.sources ||\n typeof snapshot.sources !== \"object\" ||\n Array.isArray(snapshot.sources)\n )\n return {};\n return Object.fromEntries(\n Object.entries(snapshot.sources).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n );\n } catch {\n return {};\n }\n}\n","import { readFile, realpath, stat } from \"node:fs/promises\";\nimport { isAbsolute, join, relative } from \"node:path\";\nimport { readConfigFile } from \"../core/config-file.js\";\nimport type { IndexManifest } from \"../indexer/types.js\";\nimport { graphifyGraphExists } from \"../integrations/graphify.js\";\nimport { loadArchitectureMap } from \"../map/cache.js\";\nimport { readGraphSourceSnapshot } from \"../map/graph-freshness.js\";\nimport { loadGraphifyMap } from \"../map/graphify.js\";\nimport type { ArchitectureMap } from \"../map/types.js\";\nimport type { RetrievalHit, ZvecCandidates } from \"../retrieval/zvec.js\";\nimport { extractTaskAnchors } from \"./anchors.js\";\n\n/**\n * Task-path discovery: rank indexed files against a natural-language task,\n * with calibrated abstention. Kept apart from the context engine so the lean\n * hook can use it without loading plan, risk, worklog or memory code.\n */\n\n/** Most files the engine describes (symbols, excerpts) for one request. */\nexport const TASK_PATH_LIMIT = 10;\n/** Task-discovered targets: a wrong file costs the agent a read, a missing one costs nothing. */\nconst TASK_FILES = 3;\n/** Multi-file expansion: neighbours of the top `seeds` targets, at most `files`. */\nconst EXPANSION = { seeds: 2, files: 1 } as const;\n\nconst MAX_EVIDENCE_BYTES = 512_000;\n\n/** Current file text, or null when it is missing, oversized, or binary. */\nexport async function readBoundedSource(\n repositoryRoot: string,\n path: string,\n): Promise<string | null> {\n try {\n const absolute = join(repositoryRoot, path);\n if ((await stat(absolute)).size > MAX_EVIDENCE_BYTES) return null;\n const source = await readFile(absolute, \"utf8\");\n return source.includes(\"\\0\") ? null : source;\n } catch {\n return null;\n }\n}\n\n/**\n * Rank cached file summaries for a task when the agent has not named files.\n * Explicit anchors in the task (paths, `path:line`, stack frames, quoted\n * error strings) come first; ranking fills the remaining slots.\n */\nexport async function discoverTaskPaths(\n repositoryRoot: string,\n task: string,\n manifest: IndexManifest,\n mapSource: Promise<ArchitectureMap>,\n options: DiscoveryOptions = {},\n): Promise<DiscoveredPaths> {\n const anchors = await extractTaskAnchors(\n repositoryRoot,\n task,\n new Set(Object.keys(manifest.entries)),\n );\n if (anchors.length === 0)\n return rankTaskFiles(repositoryRoot, task, manifest, mapSource, options);\n const anchored = anchors.map((anchor) => anchor.path);\n const hits: RetrievalHit[] = anchors.flatMap((anchor) =>\n anchor.line === null\n ? []\n : [\n {\n path: anchor.path,\n startLine: anchor.line,\n endLine: anchor.line,\n rank: 0,\n source: \"anchor\" as const,\n freshness: \"unverified\" as const,\n },\n ],\n );\n const explain = `retrieval: anchors (${anchors\n .map(\n (anchor) => `${anchor.kind} ${anchor.path}${anchor.line === null ? \"\" : `:${anchor.line}`}`,\n )\n .join(\", \")})`;\n if (anchored.length >= TASK_FILES) return { paths: anchored, hits, explain: [explain] };\n const ranked = await rankTaskFiles(repositoryRoot, task, manifest, mapSource, options);\n return {\n ...(ranked.symbols ? { symbols: ranked.symbols } : {}),\n paths: [...anchored, ...ranked.paths.filter((path) => !anchored.includes(path))].slice(\n 0,\n TASK_FILES,\n ),\n hits: [...hits, ...ranked.hits.filter((hit) => !anchored.includes(hit.path))],\n explain: [explain, ...ranked.explain],\n };\n}\n\n/**\n * Index entries with their BYOK model summaries attached as `llmText` (when\n * the layer and its summaries feature are on). Loaded on demand so a repo\n * without the layer never imports it.\n */\nasync function withLlmSummaries(\n repositoryRoot: string,\n manifest: IndexManifest,\n): Promise<Array<IndexManifest[\"entries\"][string] & { llmText?: string }>> {\n const entries = Object.values(manifest.entries);\n try {\n const { resolveLlmConfig } = await import(\"../llm/config.js\");\n const config = await resolveLlmConfig(repositoryRoot);\n if (!config.enabled || !config.features.summaries) return entries;\n const { loadLlmSummaries } = await import(\"../llm/summaries.js\");\n const summaries = await loadLlmSummaries(repositoryRoot, manifest);\n if (summaries.size === 0) return entries;\n return entries.map((entry) => {\n const summary = summaries.get(entry.path);\n return summary\n ? { ...entry, llmText: `${summary.summary} ${Object.values(summary.symbols).join(\" \")}` }\n : entry;\n });\n } catch {\n return entries;\n }\n}\n\nexport type DiscoveryOptions = {\n semantic?: boolean;\n /**\n * Epoch ms by which the BYOK rerank must have answered (the caller's hook\n * budget). The call gets min(configured timeout, time left) measured right\n * before it is made; under 200 ms left it is skipped. Default: no deadline\n * beyond the configured timeout.\n */\n llmDeadlineAt?: number;\n};\n\nexport type DiscoveredPaths = {\n paths: string[];\n hits: RetrievalHit[];\n explain: string[];\n /** Symbols the BYOK rerank named per file, validated against the symbol table. */\n symbols?: Record<string, string[]>;\n};\n\nasync function rankTaskFiles(\n repositoryRoot: string,\n task: string,\n manifest: IndexManifest,\n mapSource: Promise<ArchitectureMap>,\n options: DiscoveryOptions,\n): Promise<DiscoveredPaths> {\n const entries = await withLlmSummaries(repositoryRoot, manifest);\n const wantsTests = /\\b(tests?|spec)\\b/i.test(task);\n // An exact code identifier names its file better than any embedding: route\n // it lexically to the declaring files and skip vector noise.\n const identifiers = identifierTokens(task).filter((token) => CODE_IDENTIFIER.test(token));\n if (identifiers.length > 0) {\n // Files declaring more of the named identifiers first.\n const exact = entries\n .filter((entry) => wantsTests || !TEST_PATH.test(entry.path))\n .map((entry) => ({\n path: entry.path,\n named: new Set(\n (entry.symbolTable ?? []).flatMap((symbol) =>\n symbol.name.split(\".\").filter((segment) => identifiers.includes(segment)),\n ),\n ).size,\n }))\n .filter((entry) => entry.named > 0)\n .sort((left, right) => right.named - left.named || left.path.localeCompare(right.path))\n .map((entry) => entry.path);\n if (exact.length > 0) {\n const evidence = new Map(\n scoreTaskPaths(entries, task)\n .filter((entry) => entry.score > 0)\n .map((entry) => [entry.path, entry.score]),\n );\n const expansion = expandAlongImports(exact, await mapSource, evidence, task, {\n allowGraphOnly: true,\n });\n return {\n paths: expansion.paths.slice(0, TASK_FILES),\n hits: [],\n explain: [\n `retrieval: exact-symbol routing (${identifiers.slice(0, 5).join(\", \")})`,\n ...(expansion.explain ? [expansion.explain] : []),\n ],\n };\n }\n }\n // A named CLI command (`<bin> <command>`) routes to its command module,\n // ahead of keyword ranking; the logic it calls still comes from keywords.\n const commands = await commandFiles(repositoryRoot, task, entries);\n const scored = scoreTaskPaths(entries, task);\n const keyword = scored\n .filter((entry) => entry.score >= EVIDENCE_FLOOR.keywordScore)\n .map((entry) => entry.path);\n const weakKeyword = scored.length - keyword.length;\n // Loaded on demand so callers that opt out (the lean hook) never import it.\n const semantic: ZvecCandidates =\n options.semantic === false\n ? {\n status: \"disabled\",\n paths: [],\n hits: [],\n reason: \"semantic retrieval off\",\n stale: 0,\n changed: 0,\n }\n : await import(\"../retrieval/zvec.js\")\n .then(({ zvecCandidates }) => zvecCandidates(repositoryRoot, task))\n .catch(\n (): ZvecCandidates => ({\n status: \"failed\",\n paths: [],\n hits: [],\n reason: \"zvec-grep failed\",\n stale: 0,\n changed: 0,\n }),\n );\n // Lexical evidence for expansion: any task term, even below the floor.\n const evidence = new Map(\n scored.filter((entry) => entry.score > 0).map((entry) => [entry.path, entry.score]),\n );\n let ranked = keyword;\n let hits: RetrievalHit[] = [];\n const explain: string[] = [];\n if (semantic.status !== \"disabled\" && semantic.paths.length === 0) {\n explain.push(`retrieval: keyword ranking only (${semantic.reason})`);\n } else if (semantic.status !== \"disabled\") {\n // Keep zvec hits consistent with keyword rules: no tests unless asked for.\n // zg 0.2.x reports a rank, not a calibrated score, so a vector hit below the\n // keyword floor must share enough task terms with its current source.\n const terms = taskTerms(task);\n const vector: string[] = [];\n const partial: string[] = [];\n let uncorroborated = 0;\n for (const path of semantic.paths) {\n if (!wantsTests && TEST_PATH.test(path)) continue;\n if (keyword.includes(path)) vector.push(path);\n else if (\n await hasMatchedPassageEvidence(\n repositoryRoot,\n path,\n semantic.hits,\n terms,\n manifest.entries[path]?.symbolTable ?? [],\n )\n ) {\n const source = (await readBoundedSource(repositoryRoot, path)) ?? \"\";\n if (countTerms(source, terms) >= EVIDENCE_FLOOR.vectorTerms) vector.push(path);\n else partial.push(path);\n if (!evidence.has(path)) evidence.set(path, 0);\n } else uncorroborated++;\n }\n // The floor admits files; it does not reorder them. A weak keyword match\n // still votes in fusion when its vector hit was corroborated.\n ranked = rankEvidenceCandidates(\n scored.map((entry) => entry.path),\n keyword,\n vector,\n partial,\n );\n hits = semantic.hits.filter((hit) => vector.includes(hit.path) || partial.includes(hit.path));\n explain.push(\n `retrieval: keyword ranking fused with ${semantic.reason}` +\n (uncorroborated > 0 ? `; ${uncorroborated} uncorroborated vector file(s) dropped` : \"\"),\n );\n }\n\n let symbols: Record<string, string[]> | undefined;\n const reranked = await llmRerank({\n repositoryRoot,\n task,\n manifest,\n entries,\n scored,\n semantic: semantic.paths,\n ranked,\n wantsTests,\n deadlineAt: options.llmDeadlineAt,\n });\n if (reranked) {\n explain.push(reranked.explain);\n ranked = reranked.ranked;\n symbols = reranked.symbols;\n }\n\n // Calibrated abstention (#45): return nothing rather than code when no\n // *source* file reaches the evidence floor; docs and config alone (an eval\n // dataset quoting the prompt, say) never justify sending code.\n if (!ranked.some((path) => !NON_SOURCE_PATH.test(path))) {\n explain.push(\n \"abstention: no source file reached the evidence floor (\" +\n (ranked.length > 0\n ? \"only docs/config did\"\n : `best keyword score ${scored[0]?.score ?? 0} < ${EVIDENCE_FLOOR.keywordScore}`) +\n (commands.length > 0\n ? \"); only the named CLI command returned\"\n : \"); no task targets returned\"),\n );\n return { paths: commands, hits: [], explain };\n }\n if (weakKeyword > 0) {\n explain.push(\n `abstention: ${weakKeyword} weak keyword candidate(s) below the evidence floor (score < ${EVIDENCE_FLOOR.keywordScore}) dropped`,\n );\n }\n const expansion = expandAlongImports(ranked, await mapSource, evidence, task);\n if (expansion.explain) explain.push(expansion.explain);\n if (commands.length > 0) {\n explain.push(`retrieval: CLI command routing (${commands.join(\", \")})`);\n }\n const paths = [...new Set([...commands, ...expansion.paths])];\n if (paths.length > TASK_FILES) {\n explain.push(\n `abstention: ${paths.length - TASK_FILES} lower-ranked candidate(s) beyond the top ${TASK_FILES} dropped`,\n );\n }\n return {\n paths: paths.slice(0, TASK_FILES),\n hits,\n explain,\n ...(symbols && Object.keys(symbols).length > 0 ? { symbols } : {}),\n };\n}\n\n/**\n * BYOK rerank of the keyword/fused path. Returns null when the layer is off.\n * The model may reorder admitted files, abstain, or promote a below-floor\n * candidate that has at least two task terms in its model summary or current\n * source (the vector corroboration rule); anything else it names is dropped.\n */\n/** A rerank call shorter than this cannot answer in time; skip it. */\nconst MIN_RERANK_MS = 200;\n\nasync function llmRerank(input: {\n repositoryRoot: string;\n task: string;\n manifest: IndexManifest;\n entries: Array<{ path: string; summary: string; llmText?: string }>;\n scored: Array<{ path: string; score: number; order: number }>;\n semantic: string[];\n ranked: string[];\n wantsTests: boolean;\n deadlineAt: number | undefined;\n}): Promise<{ ranked: string[]; explain: string; symbols: Record<string, string[]> } | null> {\n let config: Awaited<ReturnType<typeof import(\"../llm/config.js\").resolveLlmConfig>>;\n try {\n config = await (await import(\"../llm/config.js\")).resolveLlmConfig(input.repositoryRoot);\n } catch {\n return null;\n }\n if (!config.enabled || !config.features.rerank) return null;\n const skipped = (reason: string) => ({\n ranked: input.ranked,\n explain: `retrieval: llm rerank skipped (${reason})`,\n symbols: {},\n });\n const usable = (path: string) => input.wantsTests || !TEST_PATH.test(path);\n const candidatePaths = [\n ...new Set([\n ...input.ranked,\n ...input.scored\n .map((entry) => entry.path)\n .filter(usable)\n .slice(0, 12),\n ...input.semantic.filter(usable).slice(0, 8),\n ]),\n ].slice(0, 15);\n if (candidatePaths.length === 0) return null;\n const byPath = new Map(input.entries.map((entry) => [entry.path, entry]));\n const deadlineMs = Math.min(\n config.timeoutMs,\n input.deadlineAt === undefined ? config.timeoutMs : input.deadlineAt - Date.now(),\n );\n if (deadlineMs < MIN_RERANK_MS) return skipped(\"no time left in the hook budget\");\n const { rerankCandidates } = await import(\"../llm/rerank.js\");\n const result = await rerankCandidates(\n input.repositoryRoot,\n config,\n input.task,\n candidatePaths.map((path) => ({\n path,\n summary: byPath.get(path)?.llmText || byPath.get(path)?.summary || \"\",\n signatures: (input.manifest.entries[path]?.symbolTable ?? []).map((s) => s.signature),\n })),\n deadlineMs,\n ).catch(() => ({ ok: false as const, reason: \"invalid\" as const }));\n if (!result.ok) return skipped(result.reason);\n const label = `${config.provider} ${config.model}, ${result.cached ? \"cached\" : `${result.latencyMs} ms`}`;\n if (result.value.abstain) {\n return {\n ranked: [],\n explain: `retrieval: llm rerank (${label}, model abstained over ${candidatePaths.length} candidates)`,\n symbols: {},\n };\n }\n const terms = taskTerms(input.task);\n const picks: string[] = [];\n const symbols: Record<string, string[]> = {};\n let promoted = 0;\n for (const file of result.value.files) {\n if (!input.ranked.includes(file.path)) {\n const source = (await readBoundedSource(input.repositoryRoot, file.path)) ?? \"\";\n const llmText = byPath.get(file.path)?.llmText ?? \"\";\n if (\n Math.max(countTerms(llmText, terms), countTerms(source, terms)) < EVIDENCE_FLOOR.vectorTerms\n )\n continue;\n promoted++;\n }\n picks.push(file.path);\n const known = new Set(\n (input.manifest.entries[file.path]?.symbolTable ?? []).map((s) => s.name),\n );\n const named = file.symbols.filter((name) => known.has(name));\n if (named.length > 0) symbols[file.path] = named;\n }\n return {\n ranked: [...picks, ...input.ranked.filter((path) => !picks.includes(path))],\n explain:\n `retrieval: llm rerank (${label}, ${picks.length} of ${candidatePaths.length} candidates` +\n (promoted > 0 ? `, ${promoted} promoted` : \"\") +\n \")\",\n symbols,\n };\n}\n\n/**\n * Source files for CLI commands the task names as `<bin> <command> [sub]`,\n * where `<bin>` is a `bin` entry of the repository's package.json: a file in a\n * `cli`/`cmd`/`commands` directory whose stem is `command` or `command-sub`.\n */\nasync function commandFiles(\n repositoryRoot: string,\n task: string,\n entries: Array<{ path: string }>,\n): Promise<string[]> {\n const bins = await packageBins(repositoryRoot);\n if (bins.length === 0) return [];\n const stems = new Set<string>();\n const pattern = new RegExp(\n `\\\\b(?:${bins.map(escapeRegExp).join(\"|\")})\\\\s+([a-z][\\\\w-]*)(?:\\\\s+([a-z][\\\\w-]*))?`,\n \"gi\",\n );\n for (const [, command, sub] of task.matchAll(pattern)) {\n if (!command) continue;\n stems.add(command.toLowerCase());\n if (sub) stems.add(`${command}-${sub}`.toLowerCase());\n }\n if (stems.size === 0) return [];\n const matches = entries\n .map((entry) => entry.path)\n .filter((path) => {\n if (TEST_PATH.test(path) || NON_SOURCE_PATH.test(path) || !COMMAND_DIR.test(path)) {\n return false;\n }\n const name = path.slice(path.lastIndexOf(\"/\") + 1);\n return stems.has(name.slice(0, name.lastIndexOf(\".\")).toLowerCase());\n });\n // `command-sub` names the command more precisely than `command`.\n return matches\n .sort((left, right) => right.length - left.length || left.localeCompare(right))\n .slice(0, TASK_FILES);\n}\n\nconst COMMAND_DIR = /(^|\\/)(cli|cmd|commands?)\\//;\n\nasync function packageBins(repositoryRoot: string): Promise<string[]> {\n try {\n const manifest = JSON.parse(await readFile(join(repositoryRoot, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n bin?: unknown;\n };\n if (typeof manifest.bin === \"string\" && typeof manifest.name === \"string\") {\n return [manifest.name.slice(manifest.name.lastIndexOf(\"/\") + 1)];\n }\n if (manifest.bin && typeof manifest.bin === \"object\") return Object.keys(manifest.bin);\n } catch {\n // No (readable) package.json: no CLI routing.\n }\n return [];\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** Task wording that asks for a path through several files. */\nconst MULTI_FILE_TASK =\n /\\b(trace|follow|flows?|through|across|between|end[- ]to[- ]end|pipeline)\\b|\\bfrom\\b.+\\bto\\b/i;\n\n/**\n * Bounded multi-file expansion (#45). Only when the task asks for a path\n * through several files: import neighbours of the top targets that carry\n * lexical evidence (at least one task term, even below the floor) get the\n * import edge credited as one more term, up to `expansionFiles` of them, most\n * linked first. Each is placed before the first lower-scoring non-seed target,\n * so it never displaces a file with stronger evidence.\n */\nfunction expandAlongImports(\n ranked: string[],\n map: ArchitectureMap,\n evidence: Map<string, number>,\n task: string,\n options: { allowGraphOnly?: boolean } = {},\n): { paths: string[]; explain: string | null } {\n if (!MULTI_FILE_TASK.test(task)) return { paths: ranked, explain: null };\n const seeds = ranked.slice(0, EXPANSION.seeds);\n const links = new Map<string, Set<string>>();\n const graphOnly = new Map<string, number>();\n for (const edge of map.edges) {\n for (const [seed, other] of [\n [edge.from, edge.to],\n [edge.to, edge.from],\n ] as const) {\n if (!seeds.includes(seed) || seeds.includes(other)) continue;\n if (!evidence.has(other)) {\n if (\n !options.allowGraphOnly ||\n edge.from !== seed ||\n TEST_PATH.test(other) ||\n NON_SOURCE_PATH.test(other)\n )\n continue;\n graphOnly.set(\n other,\n Math.max(\n graphOnly.get(other) ?? 0,\n edge.symbols?.length ? 2 : edge.kind === \"import\" ? 1 : 0,\n ),\n );\n }\n links.set(other, (links.get(other) ?? new Set()).add(seed));\n }\n }\n const scoreOf = (path: string) => evidence.get(path) ?? 0;\n const added = [...links]\n .sort(\n ([left, a], [right, b]) =>\n b.size - a.size ||\n scoreOf(right) - scoreOf(left) ||\n (graphOnly.get(right) ?? 0) - (graphOnly.get(left) ?? 0) ||\n left.localeCompare(right),\n )\n .slice(0, EXPANSION.files)\n .map(([path]) => path);\n if (added.length === 0) return { paths: ranked, explain: null };\n const paths = ranked.filter((path) => !added.includes(path));\n for (const path of added) {\n const credited = scoreOf(path) + 1;\n const at = paths.findIndex(\n (other, index) => index >= seeds.length && scoreOf(other) < credited,\n );\n paths.splice(at < 0 ? paths.length : at, 0, path);\n }\n return {\n paths,\n explain:\n `expansion: ${added.length} import neighbour(s) of the top ${seeds.length} target(s) ranked with the import edge credited as a task term (${added.join(\", \")}; multi-file task wording)` +\n (added.some((path) => graphOnly.has(path)) ? \"; graph-only import bridge\" : \"\"),\n };\n}\n\n/** Partial semantic matches fill available slots after established evidence. */\nexport function rankEvidenceCandidates(\n lexical: string[],\n admittedKeywords: string[],\n vector: string[],\n partial: string[],\n): string[] {\n const admitted = new Set([...admittedKeywords, ...vector]);\n const established = fuseRankings([lexical, vector]).filter((path) => admitted.has(path));\n return [...new Set([...established, ...partial])];\n}\n\n/** Reciprocal rank fusion: robust to the two lists using unrelated score scales. */\nfunction fuseRankings(lists: string[][], k = 60): string[] {\n const scores = new Map<string, number>();\n for (const list of lists) {\n list.forEach((path, index) => {\n scores.set(path, (scores.get(path) ?? 0) + 1 / (k + index + 1));\n });\n }\n return [...scores]\n .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))\n .map(([path]) => path);\n}\n\nconst TASK_STOPWORDS = new Set(\n \"the and for are was were how does did which where when what why who with without from into onto that this these those there their them then than have has had not but can could should would will its it's our your you all any each some such only also just like make makes made use uses used get gets set sets new old way\".split(\n \" \",\n ),\n);\n/**\n * Minimum evidence for a task-discovered file (#45). `keywordScore` is the\n * `scoreTaskPaths` score: two distinct task terms, or one in the file name. A\n * vector hit below it needs `vectorTerms` distinct task terms in current source.\n * Calibrated on the `tune` split of evals/task-savings.json only: every expected\n * file retrieved there scored ≥ 2 (one 0.5 step of margin kept; no tune file\n * scoring 1 was expected) and expected vector-only files matched 2 and 3 terms.\n */\nexport const EVIDENCE_FLOOR = { keywordScore: 1.5, vectorTerms: 2 } as const;\n/** A zg chunk is evidence for its matched passage, not unrelated terms elsewhere in the file. */\nasync function hasMatchedPassageEvidence(\n repositoryRoot: string,\n path: string,\n hits: RetrievalHit[],\n terms: string[],\n symbols: Array<{ startLine: number; endLine: number }>,\n): Promise<boolean> {\n const source = await readBoundedSource(repositoryRoot, path);\n if (source === null) return false;\n // Keep the established file-evidence route: passage-only filtering lost\n // required files on the fused evaluation. Passages additionally admit narrow paraphrases.\n if (countTerms(source, terms) >= EVIDENCE_FLOOR.vectorTerms) return true;\n const lines = source.split(/\\r?\\n/);\n return hits.some((hit) => {\n if (hit.path !== path || hit.endLine > lines.length) return false;\n const passage = lines.slice(hit.startLine - 1, hit.endLine);\n const matched = countTerms(passage.join(\" \"), terms);\n return (\n matched >= EVIDENCE_FLOOR.vectorTerms ||\n (matched >= 1 &&\n terms.length === 2 &&\n hit.rank <= 3 &&\n symbols.some(\n (symbol) => hit.startLine <= symbol.endLine && hit.endLine >= symbol.startLine,\n ))\n );\n });\n}\nexport const TEST_PATH =\n /(^|\\/)(__tests__|__fixtures__|fixtures?|test|tests)\\/|\\.(test|spec)\\.[a-z]+$/;\nexport const NON_SOURCE_PATH =\n /(^|\\/)(docs?|\\.github)\\/|\\.(md|mdx|txt|ya?ml|json|lock)$|(^|\\/)CHANGELOG/i;\n\n/**\n * Rank indexed files against a natural-language task. Terms match whole words\n * (camelCase and snake_case split, simple plurals folded) in the path, summary\n * and symbols; a term in the file name counts extra. Tests and fixtures are\n * skipped unless the task is about tests, and docs/config files are\n * down-weighted so source files win ties.\n */\nexport function rankTaskPaths(entries: TaskPathEntry[], task: string): string[] {\n return scoreTaskPaths(entries, task).map((entry) => entry.path);\n}\n\ntype TaskPathEntry = {\n path: string;\n summary: string;\n symbols: string[];\n symbolTable?: Array<{ name: string }>;\n /** Model-written description (BYOK summaries): affects `order`, never `score`. */\n llmText?: string;\n};\n\n/** `rankTaskPaths` with each file's score, best first. */\nexport function scoreTaskPaths(\n entries: TaskPathEntry[],\n task: string,\n): Array<{ path: string; score: number; order: number }> {\n const terms = taskTerms(task);\n if (terms.length === 0) return [];\n const wantsTests = terms.some((term) => term === \"test\" || term === \"spec\");\n const candidates = entries.flatMap((entry) => {\n if (TEST_PATH.test(entry.path) && !wantsTests) return [];\n const words = new Set(\n splitWords(\n `${entry.path} ${entry.summary} ${entry.symbols.join(\" \")} ${entry.symbolTable?.map((symbol) => symbol.name).join(\" \") ?? \"\"}`,\n ),\n );\n const llmWords = new Set(entry.llmText ? splitWords(entry.llmText) : []);\n const fileWords = new Set(splitWords(entry.path.slice(entry.path.lastIndexOf(\"/\") + 1)));\n return [{ path: entry.path, words, llmWords, fileWords }];\n });\n // Rare task terms identify a file better than common ones, so ordering\n // weighs each matched term by inverse document frequency. The returned\n // `score` stays unweighted and ignores model-written text: the evidence\n // floor is calibrated on it.\n const idf = new Map(\n terms.map((term) => {\n const df = candidates.filter(\n (candidate) => candidate.words.has(term) || candidate.llmWords.has(term),\n ).length;\n return [term, Math.log((candidates.length + 1) / (df + 1)) + 1];\n }),\n );\n return candidates\n .flatMap(({ path, words, llmWords, fileWords }) => {\n let score = 0;\n let weighted = 0;\n for (const term of terms) {\n if (words.has(term)) {\n const points = fileWords.has(term) ? 1.5 : 1;\n score += points;\n weighted += points * (idf.get(term) ?? 1);\n } else if (llmWords.has(term)) {\n weighted += 0.5 * (idf.get(term) ?? 1);\n }\n }\n if (weighted === 0) return [];\n if (NON_SOURCE_PATH.test(path)) {\n score *= 0.5;\n weighted *= 0.5;\n }\n return [{ path, score, order: weighted }];\n })\n .sort(\n (left, right) =>\n right.order - left.order || right.score - left.score || left.path.localeCompare(right.path),\n );\n}\n\n/** Lowercase words with camelCase/snake_case split and a trailing plural \"s\" folded. */\nfunction splitWords(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((word) => word.length > 2)\n .map((word) =>\n word.length > 3 && word.endsWith(\"s\") && !word.endsWith(\"ss\") ? word.slice(0, -1) : word,\n );\n}\n\n/** Task words that carry meaning (stopwords removed), as used for path ranking. */\nexport function taskTerms(task: string): string[] {\n return [...new Set(splitWords(task).filter((term) => !TASK_STOPWORDS.has(term)))];\n}\n\n/** How many distinct task terms appear in `text`. */\nexport function countTerms(text: string, terms: string[]): number {\n if (terms.length === 0) return 0;\n const words = new Set(splitWords(text));\n return terms.filter((term) => words.has(term)).length;\n}\n\n/** Looks like code, not prose: camelCase humps, snake_case, `$`, or dotted `Class.method`. */\nconst CODE_IDENTIFIER = /[a-z0-9][A-Z]|[_$.]/;\n\n/** Identifier-shaped task tokens; dotted ones also split (`Vault.lock` → `Vault`, `lock`). */\nexport function identifierTokens(task: string): string[] {\n const tokens = task.match(/[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*/g) ?? [];\n return [...new Set(tokens.flatMap((token) => [token, ...token.split(\".\")]))];\n}\n\n/** How many segments of a (`Class.method`) symbol name the tokens name. */\nexport function namedSegments(name: string, tokens: string[]): number {\n return name.split(\".\").filter((segment) => tokens.includes(segment)).length;\n}\n\nexport async function loadProjectArchitectureMap(\n repositoryRoot: string,\n manifestSource: IndexManifest | Promise<IndexManifest>,\n): Promise<ArchitectureMap> {\n const [config, manifest] = await Promise.all([readConfigFile(repositoryRoot), manifestSource]);\n const builtIn = (await loadArchitectureMap(repositoryRoot, manifest)).map;\n if (\n config.graphify?.enabled &&\n (await graphifyGraphExists(repositoryRoot, config.graphify.graphPath))\n ) {\n try {\n const graphPath = join(\n repositoryRoot,\n config.graphify.graphPath ?? \"graphify-out/graph.json\",\n );\n const [graph, graphFile, sourceHashes] = await Promise.all([\n loadGraphifyMap(graphPath, repositoryRoot),\n stat(graphPath),\n readGraphSourceSnapshot(graphPath),\n ]);\n // A graph can be valid JSON yet lag the current source, or cover only a\n // subset of files. Keep fresh Graphify-only relations and symbol labels,\n // while retaining the current import scan for the rest of the project.\n const livePaths = new Set(\n (\n await Promise.all(\n graph.modules.map(async (module) => {\n try {\n const absolute = await realpath(join(repositoryRoot, module.path));\n const inside = relative(await realpath(repositoryRoot), absolute);\n if (inside.startsWith(\"..\") || isAbsolute(inside)) return null;\n const source = await stat(absolute);\n const fresh =\n sourceHashes === null\n ? source.mtimeMs <= graphFile.mtimeMs\n : sourceHashes[module.path] !== undefined &&\n sourceHashes[module.path] === manifest.entries[module.path]?.hash;\n return source.isFile() && fresh ? module.path : null;\n } catch {\n // Deleted files must not contribute graph relationships.\n return null;\n }\n }),\n )\n ).filter((path): path is string => path !== null),\n );\n const modules = new Map(builtIn.modules.map((module) => [module.path, module]));\n for (const module of graph.modules) {\n if (livePaths.has(module.path) && !modules.has(module.path))\n modules.set(module.path, module);\n }\n const edges = new Map(builtIn.edges.map((edge) => [`${edge.from}\\0${edge.to}`, edge]));\n let freshGraphEdges = 0;\n for (const edge of graph.edges) {\n if (!livePaths.has(edge.from) || !livePaths.has(edge.to)) continue;\n freshGraphEdges++;\n const key = `${edge.from}\\0${edge.to}`;\n const scanned = edges.get(key);\n edges.set(\n key,\n scanned ? { ...scanned, ...(edge.symbols ? { symbols: edge.symbols } : {}) } : edge,\n );\n }\n const mergedEdges = [...edges.values()].sort((left, right) =>\n `${left.from}:${left.to}`.localeCompare(`${right.from}:${right.to}`),\n );\n const importsByPath = new Map<string, string[]>();\n for (const edge of mergedEdges) {\n const imports = importsByPath.get(edge.from) ?? [];\n imports.push(edge.to);\n importsByPath.set(edge.from, imports);\n }\n return {\n modules: [...modules.values()]\n .map((module) => ({ ...module, imports: importsByPath.get(module.path) ?? [] }))\n .sort((left, right) => left.path.localeCompare(right.path)),\n edges: mergedEdges,\n source: freshGraphEdges > 0 ? \"graphify+imports\" : \"imports\",\n };\n } catch {\n // An unusable or malformed graph degrades to the built-in import map\n // instead of failing the whole context request.\n }\n }\n return { ...builtIn, source: \"imports\" };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport type { ArchitectureMap, ModuleEdge, ModuleNode } from \"./types.js\";\n\ntype GraphifyRecord = Record<string, unknown>;\n\n/**\n * Graphify emits containment and documentation relations alongside real\n * dependencies. Keeping them would make a README or an MCP config look like an\n * importer of the code it mentions, so they are dropped. Edges with no relation\n * field (older graph.json exports) are still treated as imports.\n */\nconst NON_DEPENDENCY_RELATIONS = new Set([\n \"contains\",\n \"part_of\",\n \"defines\",\n \"declares\",\n \"references\",\n \"requires_env\",\n \"rationale_for\",\n]);\n\n/**\n * Graphify's graph is undirected, so a relation phrased from the dependency's\n * point of view (\"b is imported by a\") arrives with its endpoints the wrong way\n * round for a dependency edge. These are swapped rather than dropped.\n */\nconst INVERSE_RELATIONS = new Set([\n \"imported_by\",\n \"called_by\",\n \"used_by\",\n \"referenced_by\",\n \"extended_by\",\n \"implemented_by\",\n \"dependency_of\",\n \"depended_on_by\",\n]);\n\n// Only known code dependencies may become file-level import neighbours. A new\n// Graphify relation must be reviewed before it can influence retrieval.\nconst DIRECT_DEPENDENCY_RELATIONS = new Set([\n \"import\",\n \"imports\",\n \"imports_from\",\n \"dynamic_import\",\n \"dynamic_imports\",\n \"calls\",\n \"uses\",\n \"extends\",\n \"implements\",\n \"depends_on\",\n]);\n\n/** How many symbol names an edge carries, so a large fan-in stays bounded. */\nconst MAX_EDGE_SYMBOLS = 8;\n\n/** Import the common graph.json node/edge shape without depending on Graphify. */\nexport async function loadGraphifyMap(\n graphPath: string,\n repositoryRoot = process.cwd(),\n): Promise<ArchitectureMap> {\n const raw = JSON.parse(await readFile(graphPath, \"utf8\")) as GraphifyRecord;\n const nodes = arrayRecord(raw.nodes ?? raw.entities);\n const edges = arrayRecord(raw.edges ?? raw.links ?? raw.relationships);\n const nodePaths = new Map<string, string>();\n const nodeLabels = new Map<string, string>();\n const modules: ModuleNode[] = [];\n\n for (const node of nodes) {\n const id = stringValue(node.id ?? node.key ?? node.name);\n const path = graphifyPath(node, repositoryRoot);\n if (!id || !path) continue;\n nodePaths.set(id, path);\n const label = stringValue(node.label ?? node.name);\n // The node standing for the file itself carries no useful symbol name.\n if (label && label !== path && !path.endsWith(`/${label}`)) nodeLabels.set(id, label);\n modules.push({ path, language: languageFor(path), imports: [] });\n }\n\n const modulePaths = new Set(modules.map((module) => module.path));\n const importedEdges: ModuleEdge[] = [];\n for (const edge of edges) {\n const relation = stringValue(edge.relation ?? edge.type ?? edge.kind)?.toLowerCase() ?? null;\n if (relation && NON_DEPENDENCY_RELATIONS.has(relation)) continue;\n if (relation && !DIRECT_DEPENDENCY_RELATIONS.has(relation) && !INVERSE_RELATIONS.has(relation))\n continue;\n const inverse = relation !== null && INVERSE_RELATIONS.has(relation);\n const sourceEndpoint = edge.from ?? edge.source;\n const targetEndpoint = edge.to ?? edge.target;\n const [tail, head] = inverse\n ? [targetEndpoint, sourceEndpoint]\n : [sourceEndpoint, targetEndpoint];\n const from = endpointPath(tail, nodePaths, repositoryRoot);\n const to = endpointPath(head, nodePaths, repositoryRoot);\n if (!from || !to || !modulePaths.has(from) || !modulePaths.has(to) || from === to) continue;\n // The endpoint inside the dependency names the symbol the dependant uses.\n const symbol = endpointLabel(head, nodeLabels);\n importedEdges.push({\n from,\n to,\n kind: relation?.includes(\"dynamic\") ? \"dynamic_import\" : \"import\",\n ...(symbol ? { symbols: [symbol] } : {}),\n });\n }\n\n const uniqueModules = [...new Map(modules.map((module) => [module.path, module])).values()].sort(\n (left, right) => left.path.localeCompare(right.path),\n );\n const byEndpoints = new Map<string, ModuleEdge>();\n for (const edge of importedEdges) {\n const key = `${edge.from}:${edge.to}`;\n const existing = byEndpoints.get(key);\n if (!existing) {\n byEndpoints.set(key, edge);\n continue;\n }\n // Several symbol-level links collapse into one file edge: keep every symbol\n // name, and let a static import win over a dynamic one.\n const symbols = mergeSymbols(existing.symbols, edge.symbols);\n byEndpoints.set(key, {\n ...(existing.kind === \"dynamic_import\" && edge.kind === \"import\" ? edge : existing),\n ...(symbols ? { symbols } : {}),\n });\n }\n const uniqueEdges = [...byEndpoints.values()].sort((left, right) =>\n `${left.from}:${left.to}`.localeCompare(`${right.from}:${right.to}`),\n );\n if (uniqueModules.length === 0 || uniqueEdges.length === 0) {\n throw new Error(`Graphify graph contains no usable file relationships: ${graphPath}`);\n }\n for (const module of uniqueModules) {\n module.imports = uniqueEdges\n .filter((edge) => edge.from === module.path)\n .map((edge) => edge.to)\n .sort();\n }\n return { modules: uniqueModules, edges: uniqueEdges };\n}\n\nfunction arrayRecord(value: unknown): GraphifyRecord[] {\n return Array.isArray(value)\n ? value.filter((item): item is GraphifyRecord => Boolean(item && typeof item === \"object\"))\n : [];\n}\n\nfunction endpointPath(\n endpoint: unknown,\n nodePaths: Map<string, string>,\n repositoryRoot: string,\n): string | null {\n if (typeof endpoint === \"string\")\n return nodePaths.get(endpoint) ?? normalizeGraphPath(endpoint, repositoryRoot);\n if (!endpoint || typeof endpoint !== \"object\") return null;\n const record = endpoint as GraphifyRecord;\n const id = stringValue(record.id ?? record.key ?? record.name);\n return nodePaths.get(id ?? \"\") ?? graphifyPath(record, repositoryRoot);\n}\n\nfunction endpointLabel(endpoint: unknown, nodeLabels: Map<string, string>): string | null {\n if (typeof endpoint === \"string\") return nodeLabels.get(endpoint) ?? null;\n if (!endpoint || typeof endpoint !== \"object\") return null;\n const id = stringValue((endpoint as GraphifyRecord).id);\n return id ? (nodeLabels.get(id) ?? null) : null;\n}\n\nfunction mergeSymbols(left?: string[], right?: string[]): string[] | undefined {\n if (!left && !right) return undefined;\n return [...new Set([...(left ?? []), ...(right ?? [])])].sort().slice(0, MAX_EDGE_SYMBOLS);\n}\n\nfunction graphifyPath(node: GraphifyRecord, repositoryRoot: string): string | null {\n const source = node.source;\n const location = node.location;\n const candidate =\n stringValue(node.path ?? node.file ?? node.file_path ?? node.source_file) ??\n (source && typeof source === \"object\" ? stringValue((source as GraphifyRecord).path) : null) ??\n (location && typeof location === \"object\"\n ? stringValue((location as GraphifyRecord).file ?? (location as GraphifyRecord).path)\n : null);\n return candidate ? normalizeGraphPath(candidate, repositoryRoot) : null;\n}\n\nfunction normalizeGraphPath(path: string, repositoryRoot: string): string | null {\n const absolute = isAbsolute(path) ? resolve(path) : resolve(repositoryRoot, path);\n const relativePath = relative(resolve(repositoryRoot), absolute).replace(/\\\\/g, \"/\");\n if (relativePath === \"\" || relativePath === \"..\" || relativePath.startsWith(\"../\")) return null;\n return relativePath.replace(/^\\.\\//, \"\");\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction languageFor(path: string): \"ts\" | \"js\" {\n return /\\.tsx?$/.test(path) ? \"ts\" : \"js\";\n}\n","import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { NON_SOURCE_PATH, readBoundedSource, TEST_PATH } from \"./discovery.js\";\n\n/**\n * Explicit anchors in a task: repo paths, `path:line`, stack frames and quoted\n * error strings found verbatim in current source. They name the code better\n * than any ranking, so discovery puts them first. Only files in the index count;\n * a typo or a deleted file yields no anchor.\n */\nexport type TaskAnchor = {\n path: string;\n line: number | null;\n kind: \"path\" | \"line\" | \"stack\" | \"error\";\n};\n\nconst MAX_ANCHORS = 3;\n/** Source files searched for a quoted error string (bounded for the prompt hook). */\nconst MAX_ERROR_SEARCH_FILES = 2000;\n\nconst JS_FRAME = /\\bat\\s+(?:[^\\s()]+\\s+\\()?([^\\s()]+?):(\\d+):\\d+\\)?/g;\nconst PY_FRAME = /\\bFile\\s+\"([^\"]+)\",\\s+line\\s+(\\d+)/g;\nconst PATH_TOKEN =\n /(?:^|[\\s(`'\"[])((?:\\.{0,2}\\/)?[\\w@.-]+(?:\\/[\\w@.-]+)*\\.[A-Za-z0-9]+)(?::(\\d+))?/g;\nconst QUOTED = /\"([^\"\\n]{8,200})\"|'([^'\\n]{8,200})'|`([^`\\n]{8,200})`/g;\n\nexport async function extractTaskAnchors(\n repositoryRoot: string,\n task: string,\n paths: ReadonlySet<string>,\n): Promise<TaskAnchor[]> {\n const root = resolve(repositoryRoot);\n const found: Array<TaskAnchor & { at: number }> = [];\n const add = (raw: string, line: string | undefined, kind: TaskAnchor[\"kind\"], at: number) => {\n const path = toIndexedPath(root, raw, paths);\n if (path) found.push({ path, line: line ? Number(line) : null, kind, at });\n };\n for (const match of task.matchAll(JS_FRAME)) add(match[1] ?? \"\", match[2], \"stack\", match.index);\n for (const match of task.matchAll(PY_FRAME)) add(match[1] ?? \"\", match[2], \"stack\", match.index);\n for (const match of task.matchAll(PATH_TOKEN)) {\n add(match[1] ?? \"\", match[2], match[2] ? \"line\" : \"path\", match.index);\n }\n\n const anchors: TaskAnchor[] = [];\n const seen = new Set<string>();\n // A stack frame and a plain path token can match the same text; the first\n // (stack frames are collected first) wins for that path.\n for (const { at: _at, ...anchor } of found.sort((left, right) => left.at - right.at)) {\n if (seen.has(anchor.path)) continue;\n seen.add(anchor.path);\n anchors.push(anchor);\n }\n if (anchors.length < MAX_ANCHORS) {\n for (const error of await errorAnchors(root, task, paths)) {\n if (seen.has(error.path)) continue;\n seen.add(error.path);\n anchors.push(error);\n }\n }\n return anchors.slice(0, MAX_ANCHORS);\n}\n\nfunction toIndexedPath(root: string, raw: string, paths: ReadonlySet<string>): string | null {\n const absolute = isAbsolute(raw) ? raw : resolve(root, raw);\n const rel = relative(root, absolute);\n if (rel === \"\" || rel.startsWith(`..${sep}`) || rel === \"..\" || isAbsolute(rel)) return null;\n const normalized = rel.replace(/\\\\/g, \"/\");\n return paths.has(normalized) ? normalized : null;\n}\n\n/**\n * Quoted strings (not paths) found verbatim in exactly one source file. A\n * string in several files (\"use client\", a shared label) names none of them.\n */\nasync function errorAnchors(\n root: string,\n task: string,\n paths: ReadonlySet<string>,\n): Promise<TaskAnchor[]> {\n const quotes = [...task.matchAll(QUOTED)]\n .map((match) => match[1] ?? match[2] ?? match[3] ?? \"\")\n .filter((text) => text.trim().length >= 8 && !toIndexedPath(root, text, paths));\n if (quotes.length === 0) return [];\n const sources = [...paths]\n .filter((path) => !TEST_PATH.test(path) && !NON_SOURCE_PATH.test(path))\n .sort()\n .slice(0, MAX_ERROR_SEARCH_FILES);\n // ponytail: one pass per quote over bounded sources; an index of string literals if repos outgrow it.\n const matches = quotes.map(() => [] as TaskAnchor[]);\n for (const path of sources) {\n if (matches.every((found) => found.length > 1)) break;\n const source = await readBoundedSource(root, path);\n if (!source) continue;\n quotes.forEach((quote, i) => {\n const found = matches[i] as TaskAnchor[];\n if (found.length > 1) return;\n const index = source.indexOf(quote);\n if (index >= 0) {\n found.push({ path, line: source.slice(0, index).split(\"\\n\").length, kind: \"error\" });\n }\n });\n }\n return matches.flatMap((found) => (found.length === 1 ? found : []));\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,SAAS,UAAU,YAAY;AACxC,SAAS,SAAS,SAAS,MAAM,UAAU,eAAe;AAG1D,IAAM,uBAAuB,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,MAAM,CAAC;AACnF,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,eAAsB,qBACpB,iBAAiB,QAAQ,IAAI,GACH;AAC1B,QAAM,OAAO,QAAQ,cAAc;AACnC,QAAM,QAAQ,MAAM,gBAAgB,IAAI;AACxC,QAAM,UAAU,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,UAAU,SAAS,MAAM,IAAI,CAAC,CAAC,CAAC;AAC5E,QAAM,UAAwB,CAAC;AAC/B,QAAM,QAAsB,CAAC;AAE7B,aAAW,gBAAgB,OAAO;AAChC,UAAM,SAAS,MAAM,SAAS,cAAc,MAAM;AAClD,UAAM,OAAO,UAAU,SAAS,MAAM,YAAY,CAAC;AACnD,UAAM,UAAU,eAA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AAK,CAAC,MAAM,UAAU,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC;AAAA,QAC5D,OAAO;AAAA,QACP,QAAQ,kBAAkB,IAAI,qBAAqB;AAAA,MACrD;AAAA,IACF,QAAQ;AAAA,IAGR;AAAA,EACF;AACA,SAAO,EAAE,GAAG,SAAS,QAAQ,UAAU;AACzC;","names":["readFile","stat","join","resolve","mkdir","readFile","dirname","extname","join","resolve","readFile","dirname","join","resolve","resolve","join","readFile","dirname","resolve","join","dirname","mkdir","readFile","extname","readdir","extname","join","relative","extname","SUPPORTED_EXTENSIONS","normalize","SUPPORTED_EXTENSIONS","extname","walk","readdir","join","relative","resolve","stat","join","readFile","mkdir","readFile","stat","dirname","join","relative","resolve","createHash","readFile","createHash","readFile","resolve","mkdir","dirname","readFile","stat","join","relative","readFile","stat","isAbsolute","join","relative","readFile","relative","resolve","languageFor","isAbsolute","relative","resolve","sep","resolve","isAbsolute","relative","sep","join","stat","readFile","evidence","expansion","join","sourceHashes","stat","relative","isAbsolute"]}
@@ -0,0 +1,199 @@
1
+ import {
2
+ redactLlmKeys
3
+ } from "./chunk-ITGRANYW.js";
4
+ import {
5
+ writeAtomic
6
+ } from "./chunk-K63EOA4B.js";
7
+
8
+ // src/llm/budget.ts
9
+ import { mkdir, readFile } from "fs/promises";
10
+ import { join } from "path";
11
+ var BACKGROUND_SHARE = 0.7;
12
+ var CACHE_LIMIT = 2e3;
13
+ var file = (root, name) => join(root, ".codebuddy", "cache", name);
14
+ async function readJson(path, fallback) {
15
+ try {
16
+ return JSON.parse(await readFile(path, "utf8"));
17
+ } catch {
18
+ return fallback;
19
+ }
20
+ }
21
+ async function writeJson(path, value) {
22
+ await mkdir(join(path, ".."), { recursive: true });
23
+ await writeAtomic(path, `${JSON.stringify(value)}
24
+ `);
25
+ }
26
+ var utcDay = (now) => now.toISOString().slice(0, 10);
27
+ async function usageToday(root, now = /* @__PURE__ */ new Date()) {
28
+ const ledger = await readJson(file(root, "llm-usage.json"), { day: "", used: {} });
29
+ return ledger.day === utcDay(now) ? ledger.used : {};
30
+ }
31
+ async function recordUsage(root, key, tokens, now = /* @__PURE__ */ new Date()) {
32
+ const used = await usageToday(root, now);
33
+ used[key] = (used[key] ?? 0) + tokens;
34
+ await writeJson(file(root, "llm-usage.json"), { day: utcDay(now), used });
35
+ }
36
+ async function reserveBudget(root, key, purpose, estimate, dailyBudget, now = /* @__PURE__ */ new Date()) {
37
+ const limit = purpose === "background" ? dailyBudget * BACKGROUND_SHARE : dailyBudget;
38
+ return ((await usageToday(root, now))[key] ?? 0) + estimate <= limit;
39
+ }
40
+ async function coolingDown(root, key, now = /* @__PURE__ */ new Date()) {
41
+ const until = (await readJson(file(root, "llm-cooldown.json"), {}))[key];
42
+ return until ? Math.max(0, until - now.getTime()) : 0;
43
+ }
44
+ async function startCooldown(root, key, seconds, now = /* @__PURE__ */ new Date()) {
45
+ const path = file(root, "llm-cooldown.json");
46
+ const cooldowns = await readJson(path, {});
47
+ cooldowns[key] = now.getTime() + seconds * 1e3;
48
+ await writeJson(path, cooldowns);
49
+ }
50
+ async function cachedResponse(root, key) {
51
+ return (await readJson(file(root, "llm-responses.json"), {}))[key];
52
+ }
53
+ async function storeResponse(root, key, value) {
54
+ const path = file(root, "llm-responses.json");
55
+ const cache = await readJson(path, {});
56
+ delete cache[key];
57
+ cache[key] = value;
58
+ const keys = Object.keys(cache);
59
+ for (const old of keys.slice(0, Math.max(0, keys.length - CACHE_LIMIT))) delete cache[old];
60
+ await writeJson(path, cache);
61
+ }
62
+
63
+ // src/llm/client.ts
64
+ var DEFAULT_COOLDOWN_SECONDS = 60;
65
+ async function chatJson(config, request) {
66
+ const started = Date.now();
67
+ try {
68
+ return await call(config, request, started);
69
+ } catch (error) {
70
+ return {
71
+ ok: false,
72
+ reason: "invalid",
73
+ detail: redact(config, String(error?.message ?? error)).slice(0, 300),
74
+ latencyMs: Date.now() - started
75
+ };
76
+ }
77
+ }
78
+ async function call(config, request, started) {
79
+ const fail = (reason, detail) => ({
80
+ ok: false,
81
+ reason,
82
+ detail: redact(config, detail).slice(0, 300),
83
+ latencyMs: Date.now() - started
84
+ });
85
+ const root = request.repositoryRoot;
86
+ const ledgerKey = `${config.provider}:${config.model}`;
87
+ const cooling = await coolingDown(root, ledgerKey);
88
+ if (cooling > 0) return fail("cooldown", `rate limited; retry in ${Math.ceil(cooling / 1e3)} s`);
89
+ const cacheKey = request.cacheKey && `${ledgerKey}:${request.cacheKey}`;
90
+ if (cacheKey) {
91
+ const parsed2 = request.schema.safeParse(await cachedResponse(root, cacheKey));
92
+ if (parsed2.success) {
93
+ return {
94
+ ok: true,
95
+ value: parsed2.data,
96
+ model: config.model,
97
+ latencyMs: Date.now() - started,
98
+ tokens: 0,
99
+ cached: true
100
+ };
101
+ }
102
+ }
103
+ const estimate = estimateTokens(request, "") + request.maxTokens;
104
+ if (!await reserveBudget(root, ledgerKey, request.purpose, estimate, config.dailyTokenBudget)) {
105
+ return fail("budget", `daily ${request.purpose} budget for ${ledgerKey} is spent`);
106
+ }
107
+ let response;
108
+ try {
109
+ response = await fetch(`${config.baseUrl}/chat/completions`, {
110
+ method: "POST",
111
+ headers: {
112
+ authorization: `Bearer ${config.apiKey}`,
113
+ "content-type": "application/json",
114
+ ...config.provider === "openrouter" ? { "x-title": "CodeBuddy" } : {}
115
+ },
116
+ body: JSON.stringify({
117
+ model: config.model,
118
+ messages: [
119
+ { role: "system", content: request.system },
120
+ { role: "user", content: request.user }
121
+ ],
122
+ temperature: 0,
123
+ max_tokens: request.maxTokens,
124
+ response_format: { type: "json_object" }
125
+ }),
126
+ signal: AbortSignal.timeout(request.deadlineMs)
127
+ });
128
+ } catch (error) {
129
+ const name = error?.name;
130
+ if (name === "TimeoutError" || name === "AbortError") {
131
+ return fail("timeout", `no answer within ${request.deadlineMs} ms`);
132
+ }
133
+ return fail("http", error?.message ?? String(error));
134
+ }
135
+ let body;
136
+ try {
137
+ body = await response.text();
138
+ } catch (error) {
139
+ const name = error?.name;
140
+ return fail(
141
+ name === "TimeoutError" || name === "AbortError" ? "timeout" : "http",
142
+ String(error)
143
+ );
144
+ }
145
+ if (response.status === 429) {
146
+ const retryAfter = Number(response.headers.get("retry-after"));
147
+ await startCooldown(
148
+ root,
149
+ ledgerKey,
150
+ Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : DEFAULT_COOLDOWN_SECONDS
151
+ );
152
+ return fail("rate-limited", body);
153
+ }
154
+ if (!response.ok) return fail("http", `HTTP ${response.status}: ${body}`);
155
+ let completion;
156
+ try {
157
+ completion = JSON.parse(body);
158
+ } catch {
159
+ return fail("invalid", "response is not JSON");
160
+ }
161
+ const raw = completion?.choices?.[0]?.message?.content;
162
+ if (typeof raw !== "string") return fail("invalid", "answer has no text content");
163
+ const content = raw;
164
+ const reported = completion?.usage?.total_tokens;
165
+ const tokens = typeof reported === "number" && Number.isFinite(reported) ? reported : estimateTokens(request, content);
166
+ await recordUsage(root, ledgerKey, tokens);
167
+ const parsed = request.schema.safeParse(parseJsonContent(content));
168
+ if (!parsed.success) return fail("invalid", `output failed validation: ${content.slice(0, 120)}`);
169
+ if (cacheKey) await storeResponse(root, cacheKey, parsed.data);
170
+ return {
171
+ ok: true,
172
+ value: parsed.data,
173
+ model: typeof completion?.model === "string" ? completion.model : config.model,
174
+ latencyMs: Date.now() - started,
175
+ tokens,
176
+ cached: false
177
+ };
178
+ }
179
+ function parseJsonContent(content) {
180
+ const fenced = content.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1];
181
+ try {
182
+ return JSON.parse((fenced ?? content).trim());
183
+ } catch {
184
+ return void 0;
185
+ }
186
+ }
187
+ function estimateTokens(request, content) {
188
+ return Math.ceil((request.system.length + request.user.length + content.length) / 4);
189
+ }
190
+ function redact(config, text) {
191
+ return redactLlmKeys(text).split(config.apiKey).join("[REDACTED]");
192
+ }
193
+
194
+ export {
195
+ usageToday,
196
+ coolingDown,
197
+ chatJson
198
+ };
199
+ //# sourceMappingURL=chunk-IE2OUO54.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/llm/budget.ts","../src/llm/client.ts"],"sourcesContent":["import { mkdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { writeAtomic } from \"../core/markdown-store-fs.js\";\n\n/**\n * Free-tier hygiene for the LLM layer, all in `.codebuddy/cache/` (gitignored,\n * rebuildable): a per-day token ledger per provider:model, a cooldown after\n * 429s, and a response cache. Background work stops at 70% of the daily\n * budget so prompt-time calls keep a reserved 30%.\n *\n * ponytail: read-modify-write JSON without a lock; two hook processes can lose\n * one update. Fine for a soft budget; add the staging lock if it ever matters.\n */\nconst BACKGROUND_SHARE = 0.7;\nconst CACHE_LIMIT = 2_000;\n\nconst file = (root: string, name: string) => join(root, \".codebuddy\", \"cache\", name);\n\nasync function readJson<T>(path: string, fallback: T): Promise<T> {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n } catch {\n return fallback;\n }\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n await mkdir(join(path, \"..\"), { recursive: true });\n await writeAtomic(path, `${JSON.stringify(value)}\\n`);\n}\n\ntype Ledger = { day: string; used: Record<string, number> };\nconst utcDay = (now: Date) => now.toISOString().slice(0, 10);\n\nexport async function usageToday(root: string, now = new Date()): Promise<Record<string, number>> {\n const ledger = await readJson<Ledger>(file(root, \"llm-usage.json\"), { day: \"\", used: {} });\n return ledger.day === utcDay(now) ? ledger.used : {};\n}\n\nexport async function recordUsage(\n root: string,\n key: string,\n tokens: number,\n now = new Date(),\n): Promise<void> {\n const used = await usageToday(root, now);\n used[key] = (used[key] ?? 0) + tokens;\n await writeJson(file(root, \"llm-usage.json\"), { day: utcDay(now), used });\n}\n\n/** Whether `estimate` more tokens fit today's share for this purpose. */\nexport async function reserveBudget(\n root: string,\n key: string,\n purpose: \"prompt\" | \"background\",\n estimate: number,\n dailyBudget: number,\n now = new Date(),\n): Promise<boolean> {\n const limit = purpose === \"background\" ? dailyBudget * BACKGROUND_SHARE : dailyBudget;\n return ((await usageToday(root, now))[key] ?? 0) + estimate <= limit;\n}\n\n/** Milliseconds of cooldown left for this provider:model (0 = none). */\nexport async function coolingDown(root: string, key: string, now = new Date()): Promise<number> {\n const until = (await readJson<Record<string, number>>(file(root, \"llm-cooldown.json\"), {}))[key];\n return until ? Math.max(0, until - now.getTime()) : 0;\n}\n\nexport async function startCooldown(\n root: string,\n key: string,\n seconds: number,\n now = new Date(),\n): Promise<void> {\n const path = file(root, \"llm-cooldown.json\");\n const cooldowns = await readJson<Record<string, number>>(path, {});\n cooldowns[key] = now.getTime() + seconds * 1_000;\n await writeJson(path, cooldowns);\n}\n\nexport async function cachedResponse(root: string, key: string): Promise<unknown | undefined> {\n return (await readJson<Record<string, unknown>>(file(root, \"llm-responses.json\"), {}))[key];\n}\n\n/** Insertion-ordered; the oldest entries go once the cache holds CACHE_LIMIT. */\nexport async function storeResponse(root: string, key: string, value: unknown): Promise<void> {\n const path = file(root, \"llm-responses.json\");\n const cache = await readJson<Record<string, unknown>>(path, {});\n delete cache[key];\n cache[key] = value;\n const keys = Object.keys(cache);\n for (const old of keys.slice(0, Math.max(0, keys.length - CACHE_LIMIT))) delete cache[old];\n await writeJson(path, cache);\n}\n","import type { z } from \"zod\";\nimport {\n cachedResponse,\n coolingDown,\n recordUsage,\n reserveBudget,\n startCooldown,\n storeResponse,\n} from \"./budget.js\";\nimport { type EnabledLlmConfig, redactLlmKeys } from \"./config.js\";\n\n/** Seconds to back off after a 429 without a usable retry-after header. */\nconst DEFAULT_COOLDOWN_SECONDS = 60;\n\n/**\n * One OpenAI-compatible chat call that must answer with JSON (Groq and\n * OpenRouter share the API). It never throws: every failure is a reason the\n * caller turns into today's deterministic behaviour plus an explain line.\n */\nexport type LlmFailure =\n | \"disabled\"\n | \"timeout\"\n | \"rate-limited\"\n | \"cooldown\"\n | \"budget\"\n | \"http\"\n | \"invalid\";\n\nexport type LlmResult<T> =\n | { ok: true; value: T; model: string; latencyMs: number; tokens: number; cached: boolean }\n | { ok: false; reason: LlmFailure; detail: string; latencyMs: number };\n\nexport type ChatJsonRequest<T> = {\n system: string;\n user: string;\n schema: z.ZodType<T>;\n maxTokens: number;\n deadlineMs: number;\n /** Prompt-path calls get the reserved budget share; background work stops earlier. */\n purpose: \"prompt\" | \"background\";\n /** Cache identity (inputs + prompt version); omitted = never cached. */\n cacheKey?: string;\n repositoryRoot: string;\n};\n\nexport async function chatJson<T>(\n config: EnabledLlmConfig,\n request: ChatJsonRequest<T>,\n): Promise<LlmResult<T>> {\n const started = Date.now();\n try {\n return await call(config, request, started);\n } catch (error) {\n // Structural guarantee: an unexpected body shape is an invalid answer, not a crash.\n return {\n ok: false,\n reason: \"invalid\",\n detail: redact(config, String((error as Error)?.message ?? error)).slice(0, 300),\n latencyMs: Date.now() - started,\n };\n }\n}\n\nasync function call<T>(\n config: EnabledLlmConfig,\n request: ChatJsonRequest<T>,\n started: number,\n): Promise<LlmResult<T>> {\n const fail = (reason: LlmFailure, detail: string): LlmResult<T> => ({\n ok: false,\n reason,\n detail: redact(config, detail).slice(0, 300),\n latencyMs: Date.now() - started,\n });\n const root = request.repositoryRoot;\n const ledgerKey = `${config.provider}:${config.model}`;\n const cooling = await coolingDown(root, ledgerKey);\n if (cooling > 0) return fail(\"cooldown\", `rate limited; retry in ${Math.ceil(cooling / 1000)} s`);\n const cacheKey = request.cacheKey && `${ledgerKey}:${request.cacheKey}`;\n if (cacheKey) {\n const parsed = request.schema.safeParse(await cachedResponse(root, cacheKey));\n if (parsed.success) {\n return {\n ok: true,\n value: parsed.data,\n model: config.model,\n latencyMs: Date.now() - started,\n tokens: 0,\n cached: true,\n };\n }\n }\n const estimate = estimateTokens(request, \"\") + request.maxTokens;\n if (!(await reserveBudget(root, ledgerKey, request.purpose, estimate, config.dailyTokenBudget))) {\n return fail(\"budget\", `daily ${request.purpose} budget for ${ledgerKey} is spent`);\n }\n let response: Response;\n try {\n response = await fetch(`${config.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${config.apiKey}`,\n \"content-type\": \"application/json\",\n ...(config.provider === \"openrouter\" ? { \"x-title\": \"CodeBuddy\" } : {}),\n },\n body: JSON.stringify({\n model: config.model,\n messages: [\n { role: \"system\", content: request.system },\n { role: \"user\", content: request.user },\n ],\n temperature: 0,\n max_tokens: request.maxTokens,\n response_format: { type: \"json_object\" },\n }),\n signal: AbortSignal.timeout(request.deadlineMs),\n });\n } catch (error) {\n const name = (error as Error)?.name;\n if (name === \"TimeoutError\" || name === \"AbortError\") {\n return fail(\"timeout\", `no answer within ${request.deadlineMs} ms`);\n }\n return fail(\"http\", (error as Error)?.message ?? String(error));\n }\n let body: string;\n try {\n body = await response.text();\n } catch (error) {\n const name = (error as Error)?.name;\n return fail(\n name === \"TimeoutError\" || name === \"AbortError\" ? \"timeout\" : \"http\",\n String(error),\n );\n }\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get(\"retry-after\"));\n await startCooldown(\n root,\n ledgerKey,\n Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : DEFAULT_COOLDOWN_SECONDS,\n );\n return fail(\"rate-limited\", body);\n }\n if (!response.ok) return fail(\"http\", `HTTP ${response.status}: ${body}`);\n\n let completion: {\n model?: unknown;\n choices?: Array<{ message?: { content?: unknown } }>;\n usage?: { total_tokens?: unknown };\n } | null;\n try {\n completion = JSON.parse(body);\n } catch {\n return fail(\"invalid\", \"response is not JSON\");\n }\n const raw = completion?.choices?.[0]?.message?.content;\n if (typeof raw !== \"string\") return fail(\"invalid\", \"answer has no text content\");\n const content = raw;\n const reported = completion?.usage?.total_tokens;\n const tokens =\n typeof reported === \"number\" && Number.isFinite(reported)\n ? reported\n : estimateTokens(request, content);\n await recordUsage(root, ledgerKey, tokens);\n const parsed = request.schema.safeParse(parseJsonContent(content));\n if (!parsed.success) return fail(\"invalid\", `output failed validation: ${content.slice(0, 120)}`);\n if (cacheKey) await storeResponse(root, cacheKey, parsed.data);\n return {\n ok: true,\n value: parsed.data,\n model: typeof completion?.model === \"string\" ? completion.model : config.model,\n latencyMs: Date.now() - started,\n tokens,\n cached: false,\n };\n}\n\n/** Free models often wrap JSON in a ```json fence despite json_object mode. */\nfunction parseJsonContent(content: string): unknown {\n const fenced = content.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)?.[1];\n try {\n return JSON.parse((fenced ?? content).trim());\n } catch {\n return undefined;\n }\n}\n\nfunction estimateTokens(request: { system: string; user: string }, content: string): number {\n return Math.ceil((request.system.length + request.user.length + content.length) / 4);\n}\n\nfunction redact(config: EnabledLlmConfig, text: string): string {\n return redactLlmKeys(text).split(config.apiKey).join(\"[REDACTED]\");\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,YAAY;AAYrB,IAAM,mBAAmB;AACzB,IAAM,cAAc;AAEpB,IAAM,OAAO,CAAC,MAAc,SAAiB,KAAK,MAAM,cAAc,SAAS,IAAI;AAEnF,eAAe,SAAY,MAAc,UAAyB;AAChE,MAAI;AACF,WAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,EAChD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,UAAU,MAAc,OAA+B;AACpE,QAAM,MAAM,KAAK,MAAM,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACjD,QAAM,YAAY,MAAM,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,CAAI;AACtD;AAGA,IAAM,SAAS,CAAC,QAAc,IAAI,YAAY,EAAE,MAAM,GAAG,EAAE;AAE3D,eAAsB,WAAW,MAAc,MAAM,oBAAI,KAAK,GAAoC;AAChG,QAAM,SAAS,MAAM,SAAiB,KAAK,MAAM,gBAAgB,GAAG,EAAE,KAAK,IAAI,MAAM,CAAC,EAAE,CAAC;AACzF,SAAO,OAAO,QAAQ,OAAO,GAAG,IAAI,OAAO,OAAO,CAAC;AACrD;AAEA,eAAsB,YACpB,MACA,KACA,QACA,MAAM,oBAAI,KAAK,GACA;AACf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AAO;AAAA,EACT;AACF;AAEA,SAAS,eAAe,SAA2C,SAAyB;AAC1F,SAAO,KAAK,MAAM,QAAQ,OAAO,SAAS,QAAQ,KAAK,SAAS,QAAQ,UAAU,CAAC;AACrF;AAEA,SAAS,OAAO,QAA0B,MAAsB;AAC9D,SAAO,cAAc,IAAI,EAAE,MAAM,OAAO,MAAM,EAAE,KAAK,YAAY;AACnE;","names":["parsed"]}
@@ -0,0 +1,19 @@
1
+ // src/memory-extract/types.ts
2
+ import { z } from "zod";
3
+ var MEMORY_CLASSES = ["fact", "decision", "incident", "note", "ignored"];
4
+ var memoryCandidateSchema = z.object({
5
+ class: z.enum(MEMORY_CLASSES),
6
+ content: z.string().min(1),
7
+ subject: z.string().min(1),
8
+ predicate: z.string().min(1),
9
+ object: z.string().min(1),
10
+ confidence: z.number().min(0).max(1),
11
+ paths: z.array(z.string().min(1)).default([]),
12
+ severity: z.enum(["low", "medium", "high", "critical"]).nullable().default(null)
13
+ });
14
+
15
+ export {
16
+ MEMORY_CLASSES,
17
+ memoryCandidateSchema
18
+ };
19
+ //# sourceMappingURL=chunk-IHQM2ZDV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory-extract/types.ts"],"sourcesContent":["/**\n * Automatic memory extraction model (Proposal 04 Phase 04.4). After a coding\n * turn, CodeBuddy turns a short summary into structured memory *candidates*,\n * classifies each, and — only when confidence and safety allow — saves durable\n * Markdown. Everything else is routed to a reviewable queue or dropped. The\n * guiding rule: prefer a false negative (missed memory) over a false durable\n * fact. Junk memory poisons recall, so capture is deliberately conservative.\n */\n\nimport { z } from \"zod\";\nimport type { IncidentSeverity } from \"../core/memory-file-store.js\";\n\n/** How a candidate is classified. `ignored` is chatter we deliberately drop. */\nexport const MEMORY_CLASSES = [\"fact\", \"decision\", \"incident\", \"note\", \"ignored\"] as const;\nexport type MemoryClass = (typeof MEMORY_CLASSES)[number];\n\n/** What ultimately happened to a candidate. */\nexport type CandidateOutcome = \"saved\" | \"queued\" | \"ignored\";\n\n/**\n * A single extracted memory candidate, before gating. `content` is the human\n * sentence; the subject/predicate/object triple mirrors the durable fact\n * schema so an approved candidate maps cleanly onto `MemoryFileStore`.\n */\nexport type MemoryCandidate = {\n class: MemoryClass;\n content: string;\n subject: string;\n predicate: string;\n object: string;\n confidence: number;\n paths: string[];\n severity: IncidentSeverity | null;\n};\n\n/** Zod schema used to validate extractor (esp. LLM) output strictly. */\nexport const memoryCandidateSchema = z.object({\n class: z.enum(MEMORY_CLASSES),\n content: z.string().min(1),\n subject: z.string().min(1),\n predicate: z.string().min(1),\n object: z.string().min(1),\n confidence: z.number().min(0).max(1),\n paths: z.array(z.string().min(1)).default([]),\n severity: z.enum([\"low\", \"medium\", \"high\", \"critical\"]).nullable().default(null),\n});\n\nexport type ExtractionInput = {\n summary: string;\n namespace: string;\n changedFiles?: string[];\n planId?: string;\n taskType?: string;\n agentId?: string;\n sessionId?: string;\n commitSha?: string;\n verification?: string[];\n /** Standing rules the user stated this turn (`extractUserRules`). */\n userRules?: string[];\n /** User sentences withdrawing an earlier rule. */\n revokedRules?: string[];\n /** A turn without edits that still produced findings: record a handoff anyway. */\n investigation?: boolean;\n /** false: skip extraction from `summary` (only user rules, procedures and the handoff). */\n extract?: boolean;\n};\n\n/** A candidate paired with the gating decision made about it. */\nexport type CandidateDecision = {\n candidate: MemoryCandidate;\n outcome: CandidateOutcome;\n reason: string;\n /** Present when the outcome is `saved` (fact id) or `queued` (review id). */\n ref?: string;\n sensitive: boolean;\n sensitiveReasons: string[];\n};\n\nexport type AfterTurnResult = {\n saved: CandidateDecision[];\n queuedForReview: CandidateDecision[];\n ignored: CandidateDecision[];\n /** One line per decision, for explainability. */\n reasons: string[];\n extractor: \"deterministic\" | \"llm\";\n /** Worklog entry recorded for this turn, or null when the turn changed nothing. */\n worklogId: string | null;\n};\n"],"mappings":";AASA,SAAS,SAAS;AAIX,IAAM,iBAAiB,CAAC,QAAQ,YAAY,YAAY,QAAQ,SAAS;AAuBzE,IAAM,wBAAwB,EAAE,OAAO;AAAA,EAC5C,OAAO,EAAE,KAAK,cAAc;AAAA,EAC5B,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC3B,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACxB,YAAY,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC;AAAA,EACnC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EAC5C,UAAU,EAAE,KAAK,CAAC,OAAO,UAAU,QAAQ,UAAU,CAAC,EAAE,SAAS,EAAE,QAAQ,IAAI;AACjF,CAAC;","names":[]}