@orquentra/codebuddy 2.14.0 → 2.15.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.
- package/ARCHITECTURE.md +98 -0
- package/README.md +87 -6
- package/dist/{chunk-YNSTIMCF.js → chunk-4DTO2E4Y.js} +352 -157
- package/dist/chunk-4DTO2E4Y.js.map +1 -0
- package/dist/{chunk-CAEPHLHC.js → chunk-57642NGU.js} +2 -44
- package/dist/chunk-57642NGU.js.map +1 -0
- package/dist/chunk-6OQKL35B.js +55 -0
- package/dist/chunk-6OQKL35B.js.map +1 -0
- package/dist/{chunk-4DKYKDHI.js → chunk-7IPSDDO5.js} +5 -3
- package/dist/{chunk-4DKYKDHI.js.map → chunk-7IPSDDO5.js.map} +1 -1
- package/dist/chunk-7JPUMXFE.js +413 -0
- package/dist/chunk-7JPUMXFE.js.map +1 -0
- package/dist/{chunk-LRQNPYCK.js → chunk-AFXWCSQ4.js} +13 -7
- package/dist/chunk-AFXWCSQ4.js.map +1 -0
- package/dist/chunk-BNZDEU5K.js +368 -0
- package/dist/chunk-BNZDEU5K.js.map +1 -0
- package/dist/chunk-EMWGLKPR.js +45 -0
- package/dist/chunk-EMWGLKPR.js.map +1 -0
- package/dist/{chunk-YJPCS2GP.js → chunk-GNV4X67F.js} +59 -20
- package/dist/chunk-GNV4X67F.js.map +1 -0
- package/dist/{chunk-YWDH6DQ6.js → chunk-IM5RFEW4.js} +21 -19
- package/dist/{chunk-YWDH6DQ6.js.map → chunk-IM5RFEW4.js.map} +1 -1
- package/dist/chunk-K4XNTYV7.js +136 -0
- package/dist/chunk-K4XNTYV7.js.map +1 -0
- package/dist/{chunk-ESZXCZIN.js → chunk-MNSMW4MZ.js} +33 -5
- package/dist/chunk-MNSMW4MZ.js.map +1 -0
- package/dist/chunk-NNJSAYHY.js +372 -0
- package/dist/chunk-NNJSAYHY.js.map +1 -0
- package/dist/{chunk-XSNW6Y3X.js → chunk-OO7Q7XZF.js} +28 -24
- package/dist/chunk-OO7Q7XZF.js.map +1 -0
- package/dist/{chunk-L6BRYZ6G.js → chunk-PZ4EBFIA.js} +7 -7
- package/dist/{chunk-L6BRYZ6G.js.map → chunk-PZ4EBFIA.js.map} +1 -1
- package/dist/chunk-RGIVHKBH.js +156 -0
- package/dist/chunk-RGIVHKBH.js.map +1 -0
- package/dist/{chunk-LW75SKZR.js → chunk-RKF4HBBQ.js} +126 -18
- package/dist/chunk-RKF4HBBQ.js.map +1 -0
- package/dist/{chunk-7QMHIJBA.js → chunk-VBDM7HC5.js} +969 -968
- package/dist/chunk-VBDM7HC5.js.map +1 -0
- package/dist/chunk-VF7DKRIU.js +50 -0
- package/dist/chunk-VF7DKRIU.js.map +1 -0
- package/dist/{chunk-KNR2P2UY.js → chunk-Y4QQML24.js} +21 -6
- package/dist/chunk-Y4QQML24.js.map +1 -0
- package/dist/cli/index.js +4 -4
- package/dist/config-S2BDMT4B.js +15 -0
- package/dist/expand-TONFVT5D.js +98 -0
- package/dist/expand-TONFVT5D.js.map +1 -0
- package/dist/file-vectors-VREL75MA.js +19 -0
- package/dist/index-facts-MBJKBYA3.js +38 -0
- package/dist/index-pass-RP23G2CR.js +15 -0
- package/dist/index.js +24 -22
- package/dist/{install-EU35ERK5.js → install-MCJIJMFF.js} +11 -10
- package/dist/{lean-43ADYTBW.js → lean-CBHVW6JM.js} +8 -7
- package/dist/local-TH5XCLVJ.js +48 -0
- package/dist/local-llm-GZREB5DF.js +19 -0
- package/dist/local-llm-GZREB5DF.js.map +1 -0
- package/dist/{main-SFC5LV4E.js → main-QF6Z552J.js} +346 -140
- package/dist/main-QF6Z552J.js.map +1 -0
- package/dist/{memory-TGHVTBME.js → memory-LSZKSF53.js} +9 -6
- package/dist/{memory-TGHVTBME.js.map → memory-LSZKSF53.js.map} +1 -1
- package/dist/{operations-6Z6ZDVBP.js → operations-BPI633VN.js} +8 -7
- package/dist/operations-BPI633VN.js.map +1 -0
- package/dist/{rerank-IQAEWLQR.js → rerank-EPCTSEVP.js} +7 -4
- package/dist/{rerank-IQAEWLQR.js.map → rerank-EPCTSEVP.js.map} +1 -1
- package/dist/{runtime-W5AW32SD.js → runtime-W5ACTDFS.js} +9 -8
- package/dist/runtime-W5ACTDFS.js.map +1 -0
- package/dist/summaries-W2J5FCLG.js +32 -0
- package/dist/summaries-W2J5FCLG.js.map +1 -0
- package/dist/{zvec-24HLAFGN.js → zvec-LSA2IRAU.js} +13 -5
- package/dist/zvec-LSA2IRAU.js.map +1 -0
- package/package.json +3 -2
- package/dist/chunk-7QMHIJBA.js.map +0 -1
- package/dist/chunk-CAEPHLHC.js.map +0 -1
- package/dist/chunk-ESC4Y3L7.js +0 -204
- package/dist/chunk-ESC4Y3L7.js.map +0 -1
- package/dist/chunk-ESZXCZIN.js.map +0 -1
- package/dist/chunk-KNR2P2UY.js.map +0 -1
- package/dist/chunk-LRQNPYCK.js.map +0 -1
- package/dist/chunk-LW75SKZR.js.map +0 -1
- package/dist/chunk-SFMIMLXR.js +0 -63
- package/dist/chunk-SFMIMLXR.js.map +0 -1
- package/dist/chunk-XSNW6Y3X.js.map +0 -1
- package/dist/chunk-YJPCS2GP.js.map +0 -1
- package/dist/chunk-YNSTIMCF.js.map +0 -1
- package/dist/config-GEZFLXK6.js +0 -12
- package/dist/main-SFC5LV4E.js.map +0 -1
- package/dist/summaries-32PHOB6L.js +0 -20
- /package/dist/{config-GEZFLXK6.js.map → config-S2BDMT4B.js.map} +0 -0
- /package/dist/{install-EU35ERK5.js.map → file-vectors-VREL75MA.js.map} +0 -0
- /package/dist/{lean-43ADYTBW.js.map → index-facts-MBJKBYA3.js.map} +0 -0
- /package/dist/{operations-6Z6ZDVBP.js.map → index-pass-RP23G2CR.js.map} +0 -0
- /package/dist/{runtime-W5AW32SD.js.map → install-MCJIJMFF.js.map} +0 -0
- /package/dist/{summaries-32PHOB6L.js.map → lean-CBHVW6JM.js.map} +0 -0
- /package/dist/{zvec-24HLAFGN.js.map → local-TH5XCLVJ.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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/file-vectors.ts","../src/context/discovery.ts","../src/map/graphify.ts","../src/context/anchors.ts","../src/context/content-index.ts"],"sourcesContent":["import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { dirname, extname, join, relative, resolve } from \"node:path\";\nimport { extractPythonImports } from \"../indexer/python.js\";\nimport type { ArchitectureMap, MapQuery, ModuleEdge, ModuleNode } from \"./types.js\";\n\nconst SUPPORTED_EXTENSIONS = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".py\"]);\nconst IGNORED_DIRECTORIES = new Set([\n \".git\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \"coverage\",\n \".codebuddy\",\n // Python virtualenvs and caches would otherwise map site-packages.\n \".venv\",\n \"venv\",\n \".tox\",\n \"__pycache__\",\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 resolvedImports = moduleImports(root, from, source, fileSet);\n edges.push(...resolvedImports.map(({ to, kind }) => ({ from, to, kind })));\n modules.push({\n path: from,\n language: moduleLanguage(from),\n imports: [...new Set(resolvedImports.map(({ to }) => to))].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 resolvedImports = moduleImports(root, path, source, fileSet);\n edges.push(...resolvedImports.map(({ to, kind }) => ({ from: path, to, kind })));\n modules.push({\n path,\n language: moduleLanguage(path),\n imports: [...new Set(resolvedImports.map(({ to }) => to))].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 moduleLanguage(path: string): ModuleNode[\"language\"] {\n const extension = extname(path);\n if (extension === \".py\") return \"py\";\n return extension.includes(\"ts\") ? \"ts\" : \"js\";\n}\n\n/** Resolved in-repo imports of one module; external specifiers yield nothing. */\nfunction moduleImports(\n root: string,\n from: string,\n source: string,\n fileSet: Set<string>,\n): Array<{ to: string; kind: ModuleEdge[\"kind\"] }> {\n if (extname(from) === \".py\") {\n return pythonImports(from, source, fileSet).map((to) => ({ to, kind: \"import\" as const }));\n }\n return extractImports(source).flatMap((specifier) => {\n const to = resolveImport(root, from, specifier.value, fileSet);\n return to ? [{ to, kind: specifier.kind }] : [];\n });\n}\n\n/** Where absolute Python imports are looked up: the repo root, then a `src/` layout. */\nconst PYTHON_ROOTS = [\"\", \"src/\"];\n\n/**\n * Python imports resolved to repo files. Absolute modules are looked up under\n * `PYTHON_ROOTS` (first root that has them wins), relative ones from the\n * importing file's package. In `from pkg import name`, a `name` that is a\n * submodule gets its own edge; other names point at the package. Anything not\n * found (stdlib, third-party) is external and yields no edge.\n */\nfunction pythonImports(from: string, source: string, fileSet: Set<string>): string[] {\n const pick = (...candidates: string[]) =>\n candidates.find((candidate) => fileSet.has(candidate)) ?? null;\n const moduleFile = (base: string) => pick(`${base}.py`, `${base}/__init__.py`);\n const packageDir = from.split(\"/\").slice(0, -1);\n const targets: string[] = [];\n for (const statement of extractPythonImports(source)) {\n const parts = statement.module ? statement.module.split(\".\") : [];\n let bases: string[];\n if (statement.level > 0) {\n const up = statement.level - 1;\n if (up > packageDir.length) continue;\n bases = [[...packageDir.slice(0, packageDir.length - up), ...parts].join(\"/\")];\n } else {\n bases = PYTHON_ROOTS.map((prefix) => `${prefix}${parts.join(\"/\")}`);\n }\n for (const base of bases) {\n const prefix = base ? `${base}/` : \"\";\n // `from . import x` names the package itself, which only an __init__ can be.\n const module = parts.length > 0 ? moduleFile(base) : pick(`${prefix}__init__.py`);\n const submodules = statement.names.flatMap((name) => moduleFile(`${prefix}${name}`) ?? []);\n if (!module && submodules.length === 0) continue;\n targets.push(...submodules);\n if (module && submodules.length < Math.max(1, statement.names.length)) targets.push(module);\n break;\n }\n }\n return [...new Set(targets)].filter((target) => target !== from);\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, path) : [];\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\", \".py\"]);\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\", \"heading\"]),\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 when symbol tables change shape (2: class methods; 3: Python, doc headings) so old caches rebuild. */\nexport const INDEX_MANIFEST_VERSION = 3 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, sep } 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 \".venv\",\n \"venv\",\n \"__pycache__\",\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 // `-z`: NUL-separated and unquoted, so names with non-ASCII, quotes, tabs\n // or newlines arrive verbatim instead of C-quoted.\n const result = await runGit(repositoryRoot, [\n \"ls-files\",\n \"-z\",\n \"--cached\",\n \"--others\",\n \"--exclude-standard\",\n ]);\n if (result.code !== 0) return null;\n return result.stdout.split(\"\\0\").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 // Decode as one stream so a multi-byte character split across chunks survives.\n child.stdout.setEncoding(\"utf8\");\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\n/** POSIX form; a backslash is a separator only on Windows, elsewhere part of the name. */\nfunction normalize(path: string): string {\n return (sep === \"\\\\\" ? path.replace(/\\\\/g, \"/\") : path).replace(/^\\.\\//, \"\");\n}\n","import { extname } from \"node:path\";\nimport { extractSymbolTable } from \"./symbols.js\";\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 \".rst\": \"rst\",\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)\n ? extractSymbols(content)\n : language === \"py\"\n ? pythonPublicNames(content)\n : [];\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\n/** Public (no leading underscore) top-level Python names, in file order. */\nfunction pythonPublicNames(content: string): string[] {\n return extractSymbolTable(content, \"x.py\")\n .filter((symbol) => symbol.exported && symbol.kind !== \"method\")\n .map((symbol) => symbol.name)\n .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 { mkdir, readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { writeAtomic } from \"../core/markdown-store-fs.js\";\nimport { loadFreshIndex } from \"../indexer/engine.js\";\nimport type { IndexManifest } from \"../indexer/types.js\";\nimport { LOCAL_EMBEDDING_MODEL } from \"../providers/models.js\";\nimport { NON_SOURCE_PATH, readBoundedSource, TEST_PATH } from \"./discovery.js\";\n\n/**\n * Dense file vectors for task → file ordering: the local embedder (granite)\n * over 40-line chunks of each source file, cached by content hash in\n * `.codebuddy/cache/file-vectors.json` (gitignored, rebuildable).\n *\n * Built only in the background (`hooks sync`, `codebuddy index`), never while\n * a prompt waits; a prompt only embeds its own text. Keyword evidence decides\n * whether a task concerns this repository at all, vectors then pick the\n * files: on their own they cannot tell an unrelated task (best chunk ≤ 0.81\n * on the labelled sets) from a reworded related one (as low as 0.79), but for\n * admitted tasks they find the right files more often than keywords. Measured with granite: on dsicord-bot's 40\n * labelled tasks top-1 went from 45% to 55% and top-3 from 60% to 71%; on\n * evals/task-savings.json retrieval recall from 0.741 to 0.815, with every\n * unrelated task still silent. A prompt pays ~170 ms to load the model when\n * nothing else in the hook loaded it (a project with no stored facts).\n */\n\ntype FileVectors = { hash: string; vectors: string[] };\ntype Store = { version: 1; model: string; files: Record<string, FileVectors> };\n\nconst CHUNK_LINES = 40;\nconst CHUNK_STEP = 30;\nconst CHUNK_CHARS = 2_000;\nconst BATCH = 16;\nconst MODEL = `${LOCAL_EMBEDDING_MODEL.id}@${LOCAL_EMBEDDING_MODEL.revision}`;\n\nexport type FileVectorRefresh = { embedded: number; files: number; pending: number };\n/** Texts in, L2-normalized vectors out (tests pass a stub; default: the local model). */\nexport type Embed = (texts: string[]) => Promise<number[][]>;\n\nasync function localEmbed(texts: string[]): Promise<number[][]> {\n const { LocalModelProvider } = await import(\"../providers/local.js\");\n return (await new LocalModelProvider().embed({ input: texts })).vectors;\n}\n\n/**\n * Embed the chunks of every source file whose hash changed since the last\n * run, until `deadlineAt`; what is left waits for the next run. Saves after\n * each batch group so an interrupted run keeps its work.\n */\nexport async function refreshFileVectors(\n repositoryRoot: string,\n manifest: IndexManifest,\n deadlineAt: number,\n embed: Embed = localEmbed,\n): Promise<FileVectorRefresh> {\n const store = await loadStore(repositoryRoot);\n const eligible = eligiblePaths(manifest);\n const files: Record<string, FileVectors> = {};\n const todo: string[] = [];\n for (const path of eligible) {\n const cached = store.files[path];\n if (cached && cached.hash === manifest.entries[path]?.hash) files[path] = cached;\n else todo.push(path);\n }\n let embedded = 0;\n let lastSave = Date.now();\n for (const path of todo) {\n if (Date.now() >= deadlineAt) break;\n const source = await readBoundedSource(repositoryRoot, path);\n if (source === null) continue;\n const vectors: string[] = [];\n const chunks = chunk(path, source);\n for (let start = 0; start < chunks.length; start += BATCH) {\n for (const vector of await embed(chunks.slice(start, start + BATCH))) {\n vectors.push(encode(vector));\n }\n }\n files[path] = { hash: manifest.entries[path]?.hash ?? \"\", vectors };\n embedded += 1;\n if (Date.now() - lastSave > 30_000) {\n await saveStore(repositoryRoot, { version: 1, model: MODEL, files });\n lastSave = Date.now();\n }\n }\n await saveStore(repositoryRoot, { version: 1, model: MODEL, files });\n return {\n embedded,\n files: Object.keys(files).length,\n pending: eligible.length - Object.keys(files).length,\n };\n}\n\n/** Refresh the index, then the vectors of what changed. Null when the embedder cannot load. */\nexport async function syncFileVectors(\n repositoryRoot: string,\n budgetMs: number,\n): Promise<FileVectorRefresh | null> {\n const started = Date.now();\n try {\n const { manifest } = await loadFreshIndex(repositoryRoot);\n return await refreshFileVectors(repositoryRoot, manifest, started + budgetMs);\n } catch {\n return null;\n }\n}\n\n/**\n * Indexed source files by their best chunk's cosine to the task, best first.\n * Null when there are no vectors (never built, another model, semantic off)\n * or the embedder cannot load: callers keep the keyword order.\n */\nexport async function rankFilesByVector(\n repositoryRoot: string,\n manifest: IndexManifest,\n task: string,\n embed: Embed = localEmbed,\n): Promise<Array<{ path: string; score: number }> | null> {\n if (process.env.CODEBUDDY_SEMANTIC === \"0\") return null;\n const store = await loadStore(repositoryRoot);\n const current = eligiblePaths(manifest).filter(\n (path) => store.files[path]?.hash === manifest.entries[path]?.hash,\n );\n if (current.length === 0) return null;\n let query: number[];\n try {\n const [vector] = await embed([task]);\n if (!vector) return null;\n query = vector;\n } catch {\n return null;\n }\n return current\n .map((path) => ({\n path,\n score: Math.max(...(store.files[path]?.vectors ?? []).map((v) => dot(decode(v), query))),\n }))\n .sort((left, right) => right.score - left.score || left.path.localeCompare(right.path));\n}\n\nfunction eligiblePaths(manifest: IndexManifest): string[] {\n return Object.keys(manifest.entries).filter(\n (path) => !NON_SOURCE_PATH.test(path) && !TEST_PATH.test(path),\n );\n}\n\n/** The path heads every chunk, so a file's name counts toward each of its passages. */\nfunction chunk(path: string, source: string): string[] {\n const lines = source.split(\"\\n\");\n const chunks: string[] = [];\n for (let start = 0; start === 0 || start + 10 < lines.length; start += CHUNK_STEP) {\n // Capped: one minified or data line would otherwise make the whole batch's\n // attention tensor too large for ONNX Runtime.\n chunks.push(\n `${path}\\n${lines.slice(start, start + CHUNK_LINES).join(\"\\n\")}`.slice(0, CHUNK_CHARS),\n );\n }\n return chunks;\n}\n\nfunction encode(vector: number[]): string {\n return Buffer.from(Float32Array.from(vector).buffer).toString(\"base64\");\n}\n\nfunction decode(text: string): Float32Array {\n const bytes = Buffer.from(text, \"base64\");\n return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);\n}\n\nfunction dot(left: Float32Array, right: number[]): number {\n let sum = 0;\n for (let index = 0; index < right.length; index++)\n sum += (left[index] ?? 0) * (right[index] ?? 0);\n return sum;\n}\n\nfunction storePath(repositoryRoot: string): string {\n return join(repositoryRoot, \".codebuddy\", \"cache\", \"file-vectors.json\");\n}\n\nasync function loadStore(repositoryRoot: string): Promise<Store> {\n try {\n const parsed = JSON.parse(await readFile(storePath(repositoryRoot), \"utf8\")) as Store;\n if (parsed.version === 1 && parsed.model === MODEL && parsed.files) return parsed;\n } catch {\n // Missing or corrupt: nothing to rank by until the next refresh.\n }\n return { version: 1, model: MODEL, files: {} };\n}\n\nasync function saveStore(repositoryRoot: string, store: Store): Promise<void> {\n const path = storePath(repositoryRoot);\n await mkdir(dirname(path), { recursive: true });\n await writeAtomic(path, JSON.stringify(store));\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 { isCredentialPath } from \"../core/sensitive.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\";\nimport { idfCoverage, rankContent } from \"./content-index.js\";\nimport { rankFilesByVector } from \"./file-vectors.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 // Credential files are never read as evidence: not ranked, indexed or shown.\n if (isCredentialPath(path)) return 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 task = stripIssueTemplate(task);\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 * With `semantic: false`, still ask zvec-grep (when enabled) but only while a\n * `zg server` is running, every zg call killed at this epoch ms. Lets the lean\n * hook use zvec without the local embedding model or an unbounded probe.\n */\n zvecDeadlineAt?: 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 // Changelogs restate every feature's wording; they are never a task's target\n // unless the task is about the changelog itself.\n const wantsChangelog = asksForChangelog(task);\n const entries = (await withLlmSummaries(repositoryRoot, manifest)).filter(\n (entry) => wantsChangelog || !CHANGELOG_PATH.test(entry.path),\n );\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(\n (token) => CODE_IDENTIFIER.test(token) && !ABBREVIATION.test(token),\n );\n if (identifiers.length > 0) {\n // Files declaring more of the named identifiers first. Docs/examples only\n // for a docs task; exception modules never: a report names the error it\n // hit, and the fix is where it is raised, not where it is declared.\n const exact = entries\n .filter(\n (entry) =>\n (wantsTests || !TEST_PATH.test(entry.path)) &&\n countsAsSource(entry.path, task) &&\n !EXCEPTION_MODULE.test(entry.path),\n )\n .map((entry) => ({\n path: entry.path,\n named: new Set(\n (entry.symbolTable ?? []).flatMap((symbol) =>\n // A doc heading naming an identifier is not its declaration.\n symbol.kind === \"heading\"\n ? []\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 summaryKeyword = scored\n .filter((entry) => entry.score >= EVIDENCE_FLOOR.keywordScore)\n .map((entry) => entry.path);\n // Full-text evidence (words inside function bodies): already gated, so it\n // admits files the summary floor misses and votes in the order of both.\n const { matches: content, idf } = await rankContent(\n repositoryRoot,\n manifest,\n taskTerms(task),\n wantsTests,\n DOCS_TASK.test(task),\n wantsChangelog,\n );\n const keyword =\n content.length > 0\n ? fuseRankings([summaryKeyword, content.map((match) => match.path)])\n : summaryKeyword;\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 && options.zvecDeadlineAt === undefined\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 }) =>\n zvecCandidates(\n repositoryRoot,\n task,\n options.semantic === false && options.zvecDeadlineAt !== undefined\n ? { deadlineAt: options.zvecDeadlineAt, requireServer: true }\n : {},\n ),\n )\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 let belowFloor = 0;\n // zg's own score is rank-derived (RRF), not a similarity, so the floor is on\n // the hit's current source: the content gate's task IDF coverage.\n const minScore = semantic.minScore ?? 0;\n for (const path of semantic.paths) {\n if (!wantsTests && TEST_PATH.test(path)) continue;\n if (!wantsChangelog && CHANGELOG_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 // The path counts too, as it does in the BM25 counts the IDF table comes from.\n if (idfCoverage(`${path} ${source}`, terms, idf) < minScore) {\n belowFloor++;\n continue;\n }\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 if (belowFloor > 0) {\n explain.push(\n `abstention: ${belowFloor} vector-only file(s) below zvec.minScore ${minScore} (task IDF coverage of current source) dropped`,\n );\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 const wantsDocs = DOCS_TASK.test(task);\n if (!ranked.some((path) => countsAsSource(path, task))) {\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 // Keyword evidence decided the task is about this repository; built file\n // vectors pick which files (see file-vectors.ts for the measurements).\n const vectors =\n options.semantic === false || reranked\n ? null\n : await rankFilesByVector(repositoryRoot, manifest, task);\n if (vectors && vectors.length > 0) {\n // Vectors cover source only; a docs task keeps its best-ranked doc first.\n const doc = wantsDocs ? ranked.filter((path) => DOC_PATH.test(path)).slice(0, 1) : [];\n ranked = [...doc, ...vectors.map((match) => match.path)].slice(0, TASK_FILES);\n explain.push(\n `retrieval: file vectors ordered the files (best ${vectors[0]?.score.toFixed(2)})`,\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]+$|(^|\\/)(test_[^/]*|[^/]*_test|conftest)\\.py$/;\n/**\n * Changelogs and release notes: upper-case names (NEWS, CHANGES.rst, HISTORY.md)\n * with any extension, \"changelog\"/\"release notes\" in any case, and lower-case\n * changes/history/news/releases only as prose files (so `src/history.ts` is code).\n */\nexport const CHANGELOG_PATH = new RegExp(\n [\n \"(?:CHANGES|CHANGELOG|HISTORY|NEWS|RELEASES?|RELEASE[-_]?NOTES)(?:[._-][^/]*)?\",\n \"[Cc]hange[-_]?[Ll]og[^/]*\",\n \"[Rr]elease[-_]?[Nn]otes[^/]*\",\n \"(?:[Cc]hanges|[Hh]istory|[Nn]ews|[Rr]eleases?)\\\\.(?:md|mdx|rst|txt|adoc|markdown)\",\n ]\n .map((name) => `(?:^|/)${name}$`)\n .join(\"|\"),\n);\n/**\n * The task is about the changelog: \"changelog\", \"release notes\", \"version\n * history\", or a changelog file named in capitals or with its extension. The\n * plain words \"changes\" and \"history\" are too common in coding tasks to count.\n */\nexport function asksForChangelog(task: string): boolean {\n return (\n /\\b(?:change[-_ ]?logs?|release[-_ ]?notes?|(?:release|version) history)\\b/i.test(task) ||\n /\\b(?:CHANGES|HISTORY|NEWS|RELEASES?)\\b/.test(task) ||\n /\\b(?:changes|history|news|releases?)\\.(?:md|mdx|rst|txt|adoc)\\b/i.test(task)\n );\n}\nconst NON_SOURCE_BASE =\n /(^|\\/)(docs?|\\.github)\\/|\\.(md|mdx|rst|adoc|txt|ya?ml|json|lock)$|(^|\\/)CHANGELOG/i;\n/** Docs, config and changelogs: never enough on their own to send code. */\nexport const NON_SOURCE_PATH = {\n test: (path: string): boolean => NON_SOURCE_BASE.test(path) || CHANGELOG_PATH.test(path),\n};\nconst PROSE_PATH = /(^|\\/)docs?\\/|\\.(md|mdx|rst|txt)$/i;\n/**\n * Prose documentation (a subset of NON_SOURCE_PATH; config files are not\n * docs). Changelogs are not docs: a docs task never makes them targets.\n */\nexport const DOC_PATH = {\n test: (path: string): boolean => PROSE_PATH.test(path) && !CHANGELOG_PATH.test(path),\n};\n/** A task about documentation lets docs compete with (and stand in for) source. */\nconst DOCS_TASK = /\\b(docs?|documentation|documented|guides?|tutorials?|readme|manual)\\b/i;\n\n/**\n * Source, or a non-source file the task is about: a doc for a docs task, a\n * changelog for a changelog task. Only these can stop abstention.\n */\nexport function countsAsSource(path: string, task: string): boolean {\n return (\n !NON_SOURCE_PATH.test(path) ||\n (DOCS_TASK.test(task) && DOC_PATH.test(path)) ||\n (asksForChangelog(task) && CHANGELOG_PATH.test(path))\n );\n}\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 (!countsAsSource(path, task)) {\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. */\nexport function splitWords(text: string): string[] {\n return rawWords(text).map(foldPlural);\n}\n\nfunction rawWords(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}\n\n/** `crashes` → `crash`, `users` → `user`, `cookies` → `cookie`; `class`, `status`, `this` stay. */\nfunction foldPlural(word: string): string {\n if (word.length <= 3 || !word.endsWith(\"s\") || /(ss|us|is)$/.test(word)) return word;\n if (/(ss|sh|ch|x|z)es$/.test(word)) return word.slice(0, -2);\n return word.slice(0, -1);\n}\n\n/**\n * GitHub issue-form scaffolding that a pasted issue carries into a task: section\n * headings, `_No response_`, checkbox options, placeholder steps and the version\n * field. Its words (\"response\", \"code\", \"error\", \"version\") match unrelated files.\n */\nconst ISSUE_TEMPLATE = [\n /_No response_/gi,\n /\\(Please specify[^)]*\\)/gi,\n /-\\s*\\[[ xX]\\]\\s*[\\w.+-]+/g,\n /\\d+\\.\\s*(?:Go to|Click on|Scroll down to)\\s*'\\.+'|\\bSee error\\b/gi,\n /#{1,6}\\s*[\\w-]+ Version\\b(?:\\s*v?\\d+(?:\\.\\d+)+[\\w.-]*,?)*/gi,\n /#{1,6}\\s*(?:Description|Summary|URL to code causing the issue|MCVE|Minimal reproducible example|Steps to reproduce|Expected behaviou?r|Actual behaviou?r|Screenshots|Logs|Environment|Platform|Additional context)\\b/gi,\n];\n\n/** The task without issue-form scaffolding; plain prose is returned unchanged. */\nexport function stripIssueTemplate(task: string): string {\n return ISSUE_TEMPLATE.reduce((text, pattern) => text.replace(pattern, \" \"), task);\n}\n\n/** Task words that carry meaning (stopwords removed), as used for path ranking. */\nexport function taskTerms(task: string): string[] {\n return [\n ...new Set(\n rawWords(task)\n .filter((word) => !TASK_STOPWORDS.has(word))\n .map(foldPlural)\n .filter((term) => !TASK_STOPWORDS.has(term)),\n ),\n ];\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/** `e.g`, `i.e`: dotted single letters are prose, not `Class.method`. */\nconst ABBREVIATION = /^[a-z](?:\\.[a-z])+$/i;\n/**\n * Modules that only declare errors (`exceptions.py`, `errors/`). ponytail: a task\n * that changes an exception class itself still reaches it through keyword ranking only.\n */\nconst EXCEPTION_MODULE = /(^|\\/)(exceptions?|errors?)(\\/|\\.[a-z]+$)/i;\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): ModuleNode[\"language\"] {\n if (/\\.py$/.test(path)) return \"py\";\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","import { mkdir, readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { writeAtomic } from \"../core/markdown-store-fs.js\";\nimport type { IndexManifest } from \"../indexer/types.js\";\nimport {\n CHANGELOG_PATH,\n DOC_PATH,\n NON_SOURCE_PATH,\n readBoundedSource,\n splitWords,\n TEST_PATH,\n} from \"./discovery.js\";\n\n/**\n * Full-text relevance for task → file discovery: BM25 over each indexed\n * source file's words, not just its path, summary and symbol names (which\n * miss every word inside a function body). On the dsicord-bot labelled set it\n * took exact-wording tasks from 46.7% to 66.7% top-1 and reworded ones from\n * 0% to 30%.\n *\n * Word counts are cached per file by content hash in\n * `.codebuddy/cache/content-terms.json` (gitignored, rebuildable), so a prompt\n * re-reads only files that changed since the last one.\n */\n\n/** `passages`: the distinct words of each 40-line window (stepping 20 lines). */\ntype FileTerms = {\n hash: string;\n length: number;\n counts: Record<string, number>;\n passages: string[][];\n};\ntype Cache = { version: 2; files: Record<string, FileTerms> };\n\nconst PASSAGE_LINES = 40;\n\nconst K1 = 1.2;\nconst B = 0.75;\n/**\n * A match must hold at least this many distinct task terms in one passage\n * (fewer if the task has fewer). Terms scattered across a large file are how\n * unrelated tasks matched: one task word in a git helper, another in an\n * unrelated function further down.\n */\nconst MIN_TERMS = 2;\n/** …and score at least this share of the best file, so a weak tail never rides along. */\nconst MIN_SHARE = 0.5;\n/**\n * …and cover at least this share of the task's rarity (IDF) mass. A task whose\n * most specific words appear nowhere in the repository (an email feature asked\n * of a repo with no mail code) is about something else, however well two\n * common words match. 0.3 is the lowest value that kept every unrelated task in\n * evals/task-savings.json silent (0.2 let two through); higher values cost recall.\n */\nconst MIN_IDF_COVERAGE = 0.3;\n\nexport type ContentMatch = { path: string; score: number; terms: number };\n\n/**\n * Source files ranked by BM25 for the task, already gated: each one contains\n * at least two task terms and scores at least half of the best file. Empty\n * when nothing clears that bar, so callers can stay silent instead of\n * guessing.\n */\nexport async function rankByContent(\n repositoryRoot: string,\n manifest: IndexManifest,\n terms: string[],\n wantsTests: boolean,\n /** A docs task also ranks prose docs (never config). */\n wantsDocs = false,\n wantsChangelog = false,\n): Promise<ContentMatch[]> {\n return (await rankContent(repositoryRoot, manifest, terms, wantsTests, wantsDocs, wantsChangelog))\n .matches;\n}\n\n/** `rankByContent` plus each task term's IDF over the indexed source files. */\nexport async function rankContent(\n repositoryRoot: string,\n manifest: IndexManifest,\n terms: string[],\n wantsTests: boolean,\n wantsDocs = false,\n wantsChangelog = false,\n): Promise<{ matches: ContentMatch[]; idf: Map<string, number> }> {\n const none = { matches: [], idf: new Map<string, number>() };\n if (terms.length === 0) return none;\n const paths = Object.keys(manifest.entries).filter(\n (path) =>\n (!NON_SOURCE_PATH.test(path) ||\n (wantsDocs && DOC_PATH.test(path)) ||\n (wantsChangelog && CHANGELOG_PATH.test(path))) &&\n (wantsTests || !TEST_PATH.test(path)),\n );\n const cache = await loadCache(repositoryRoot);\n let changed = false;\n const files: Record<string, FileTerms> = {};\n await Promise.all(\n paths.map(async (path) => {\n const hash = manifest.entries[path]?.hash ?? \"\";\n const cached = cache.files[path];\n if (cached && cached.hash === hash) {\n files[path] = cached;\n return;\n }\n const source = await readBoundedSource(repositoryRoot, path);\n if (source === null) return;\n const counts: Record<string, number> = {};\n const words = splitWords(`${path} ${source}`);\n for (const word of words) counts[word] = (counts[word] ?? 0) + 1;\n const lines = source.split(\"\\n\");\n const passages: string[][] = [];\n for (\n let start = 0;\n start === 0 || start + PASSAGE_LINES / 2 < lines.length;\n start += PASSAGE_LINES / 2\n ) {\n passages.push([\n ...new Set(splitWords(lines.slice(start, start + PASSAGE_LINES).join(\"\\n\"))),\n ]);\n }\n files[path] = { hash, length: words.length, counts, passages };\n changed = true;\n }),\n );\n // Entries this task did not rank (docs on a code task) stay while current.\n const retained = Object.fromEntries(\n Object.entries(cache.files).filter(\n ([path, file]) => !(path in files) && manifest.entries[path]?.hash === file.hash,\n ),\n );\n const kept = Object.keys(retained).length + Object.keys(files).length;\n if (changed || kept !== Object.keys(cache.files).length) {\n await saveCache(repositoryRoot, { version: 2, files: { ...retained, ...files } });\n }\n\n const documents = Object.entries(files);\n if (documents.length === 0) return none;\n const averageLength =\n documents.reduce((sum, [, file]) => sum + file.length, 0) / documents.length;\n const idf = new Map(\n terms.map((term) => {\n const df = documents.filter(([, file]) => (file.counts[term] ?? 0) > 0).length;\n return [term, Math.log(1 + (documents.length - df + 0.5) / (df + 0.5))];\n }),\n );\n const totalIdf = [...idf.values()].reduce((sum, value) => sum + value, 0);\n const scored = documents\n .map(([path, file]) => {\n const fileName = new Set(splitWords(path.slice(path.lastIndexOf(\"/\") + 1)));\n let score = 0;\n let covered = 0;\n for (const term of terms) {\n const tf = file.counts[term] ?? 0;\n if (tf === 0) continue;\n covered += idf.get(term) ?? 0;\n const saturation =\n (tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * file.length) / averageLength));\n score += (idf.get(term) ?? 0) * saturation * (fileName.has(term) ? 1.5 : 1);\n }\n // The file name counts as part of every passage.\n const named = terms.filter((term) => fileName.has(term));\n const matched = Math.max(\n named.length,\n ...file.passages.map(\n (words) => new Set([...named, ...terms.filter((term) => words.includes(term))]).size,\n ),\n );\n return { path, score, terms: matched, coverage: totalIdf > 0 ? covered / totalIdf : 0 };\n })\n .filter((match) => match.score > 0)\n .sort((left, right) => right.score - left.score || left.path.localeCompare(right.path));\n const best = scored[0]?.score ?? 0;\n const needed = Math.min(MIN_TERMS, terms.length);\n const matches = scored\n .filter(\n (match) =>\n match.terms >= needed &&\n match.score >= MIN_SHARE * best &&\n match.coverage >= MIN_IDF_COVERAGE,\n )\n .map(({ path, score, terms: matched }) => ({ path, score, terms: matched }));\n return { matches, idf };\n}\n\n/**\n * Share of the task's IDF mass whose terms occur in `text` (0..1): the\n * `MIN_IDF_COVERAGE` measure, applied to any text. Terms absent from every\n * indexed file carry the most weight, so a task about something the repository\n * does not contain covers little however many common words a file shares.\n */\nexport function idfCoverage(text: string, terms: string[], idf: Map<string, number>): number {\n const total = terms.reduce((sum, term) => sum + (idf.get(term) ?? 0), 0);\n if (total === 0) return 0;\n const words = new Set(splitWords(text));\n return terms.reduce((sum, term) => sum + (words.has(term) ? (idf.get(term) ?? 0) : 0), 0) / total;\n}\n\nfunction cachePath(repositoryRoot: string): string {\n return join(repositoryRoot, \".codebuddy\", \"cache\", \"content-terms.json\");\n}\n\nasync function loadCache(repositoryRoot: string): Promise<Cache> {\n try {\n const parsed = JSON.parse(await readFile(cachePath(repositoryRoot), \"utf8\")) as Cache;\n if (parsed.version === 2 && parsed.files && typeof parsed.files === \"object\") return parsed;\n } catch {\n // Missing or corrupt: rebuild from the files.\n }\n return { version: 2, files: {} };\n}\n\nasync function saveCache(repositoryRoot: string, cache: Cache): Promise<void> {\n try {\n const path = cachePath(repositoryRoot);\n await mkdir(dirname(path), { recursive: true });\n await writeAtomic(path, JSON.stringify(cache));\n } catch {\n // A cache that cannot be written only costs a re-read next prompt.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,UAAU,YAAY;AACxC,SAAS,SAAS,SAAS,MAAM,UAAU,eAAe;AAI1D,IAAM,uBAAuB,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,KAAK,CAAC;AAC1F,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,eAAsB,qBAC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AK,KAAK,MAAM,MAAM,KAAK,KAAK;AAC/C,SAAO;AACT;AAEA,SAAS,UAAU,gBAAgC;AACjD,SAAOI,MAAK,gBAAgB,cAAc,SAAS,mBAAmB;AACxE;AAEA,eAAe,UAAU,gBAAwC;AAC/D,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,MAAMC,WAAS,UAAU,cAAc,GAAG,MAAM,CAAC;AAC3E,QAAI,OAAO,YAAY,KAAK,OAAO,UAAU,SAAS,OAAO,MAAO,QAAO;AAAA,EAC7E,QAAQ;AAAA,EAER;AACA,SAAO,EAAE,SAAS,GAAG,OAAO,OAAO,OAAO,CAAC,EAAE;AAC/C;AAEA,eAAe,UAAU,gBAAwB,OAA6B;AAC5E,QAAM,OAAO,UAAU,cAAc;AACrC,QAAMC,OAAMC,SAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,QAAM,YAAY,MAAM,KAAK,UAAU,KAAK,CAAC;AAC/C;","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","extname","normalize","SUPPORTED_EXTENSIONS","extname","walk","readdir","join","relative","chunk","resolve","stat","join","readFile","mkdir","readFile","stat","dirname","join","relative","resolve","sep","createHash","readFile","createHash","readFile","resolve","mkdir","dirname","readFile","stat","join","relative","sep","mkdir","readFile","dirname","join","readFile","stat","isAbsolute","join","relative","readFile","relative","resolve","languageFor","isAbsolute","relative","resolve","sep","resolve","isAbsolute","relative","sep","mkdir","readFile","dirname","join","join","readFile","mkdir","dirname","join","stat","readFile","evidence","expansion","join","sourceHashes","stat","relative","isAbsolute","join","readFile","mkdir","dirname"]}
|
package/dist/config-GEZFLXK6.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
redactLlmKeys,
|
|
3
|
-
resolveLlmConfig
|
|
4
|
-
} from "./chunk-SFMIMLXR.js";
|
|
5
|
-
import "./chunk-KNR2P2UY.js";
|
|
6
|
-
import "./chunk-CG5B3LYG.js";
|
|
7
|
-
import "./chunk-PZ5AY32C.js";
|
|
8
|
-
export {
|
|
9
|
-
redactLlmKeys,
|
|
10
|
-
resolveLlmConfig
|
|
11
|
-
};
|
|
12
|
-
//# sourceMappingURL=config-GEZFLXK6.js.map
|