@ninjaxtools/slopdex 0.3.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/slopdex/SKILL.md +173 -24
- package/README.md +93 -94
- package/dist/cli.js +1254 -198
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +129 -2
- package/dist/index.js +796 -116
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/code-index.ts","../src/errors.ts","../src/git/repository.ts","../src/parser/callable-parser.ts","../src/utils.ts","../src/source-policy.ts","../src/storage/database.ts","../src/embeddings/http.ts","../src/embeddings/jina.ts","../src/embeddings/openai.ts","../src/format.ts","../src/search/cross-search.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { existsSync, readFileSync, rmSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { CodeIndex } from \"./code-index.js\";\nimport { JinaEmbeddingProvider } from \"./embeddings/jina.js\";\nimport { OpenAIEmbeddingProvider } from \"./embeddings/openai.js\";\nimport { CodeIndexError } from \"./errors.js\";\nimport { formatSimilaritySummary } from \"./format.js\";\nimport { crossSearch } from \"./search/cross-search.js\";\nimport type { CodeIndexOptions, EmbeddingProvider, IndexedFunction, SimilarityResult, UpdateStats } from \"./types.js\";\n\ninterface FileConfig {\n provider?: \"openai\" | \"jina\";\n model?: string;\n dimensions?: number;\n indexPath?: string;\n include?: string[];\n exclude?: string[];\n maxFileSize?: number;\n embeddingBatchSize?: number;\n}\n\nconst parsed = parseArgs({\n args: process.argv.slice(2),\n allowPositionals: true,\n strict: true,\n options: {\n root: { type: \"string\", default: process.cwd() },\n config: { type: \"string\" },\n index: { type: \"string\" },\n provider: { type: \"string\" },\n model: { type: \"string\" },\n dimensions: { type: \"string\" },\n target: { type: \"string\" },\n \"target-root\": { type: \"string\" },\n \"target-index\": { type: \"string\" },\n \"added-since\": { type: \"string\" },\n \"source-path\": { type: \"string\" },\n limit: { type: \"string\" },\n \"min-similarity\": { type: \"string\" },\n threshold: { type: \"string\" },\n format: { type: \"string\" },\n \"include-symmetric-duplicates\": { type: \"boolean\", default: false },\n \"rebuild-on-divergence\": { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n});\n\nconst [command, ...positionals] = parsed.positionals;\n\nif (parsed.values.help || !command) {\n printHelp();\n process.exit(parsed.values.help ? 0 : 1);\n}\n\nvoid main().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`slopdex: ${message}\\n`);\n process.exitCode = error instanceof CodeIndexError ? 2 : 1;\n});\n\nasync function main(): Promise<void> {\n const rootDir = path.resolve(parsed.values.root!);\n const config = loadConfig(rootDir, parsed.values.config);\n const provider = createProvider(config);\n const indexOptions: CodeIndexOptions = {\n rootDir,\n provider,\n onWarning: (message) => process.stderr.write(`slopdex: warning: ${message}\\n`),\n ...(parsed.values.index || config.indexPath ? { indexPath: parsed.values.index ?? config.indexPath } : {}),\n ...(config.include ? { include: config.include } : {}),\n ...(config.exclude ? { exclude: config.exclude } : {}),\n ...(config.maxFileSize ? { maxFileSize: config.maxFileSize } : {}),\n ...(config.embeddingBatchSize ? { embeddingBatchSize: config.embeddingBatchSize } : {}),\n };\n const initialized = await initializeMissingIndex(\n indexOptions,\n \"index\",\n command === \"update-git\" ? parsed.values.target ?? \"HEAD\" : \"HEAD\",\n );\n const index = new CodeIndex(indexOptions);\n try {\n switch (command) {\n case \"status\":\n printJson(index.status());\n break;\n case \"update-files\":\n if (positionals.length === 0) throw new CodeIndexError(\"update-files requires at least one path.\");\n printJson(await index.updateFiles({ upsert: positionals }));\n break;\n case \"delete-files\":\n if (positionals.length === 0) throw new CodeIndexError(\"delete-files requires at least one path.\");\n printJson(await index.updateFiles({ delete: positionals }));\n break;\n case \"update-git\": {\n const stats = initialized ?? await index.updateFromGit({\n ...(parsed.values.target ? { target: parsed.values.target } : {}),\n rebuildOnDivergence: parsed.values[\"rebuild-on-divergence\"],\n });\n printJson(stats);\n break;\n }\n case \"search\": {\n const query = positionals.join(\" \").trim();\n if (!query) throw new CodeIndexError(\"search requires a query.\");\n const threshold = similarityThreshold();\n const results = await index.similaritySearch({\n query,\n limit: numberOption(parsed.values.limit, 10, \"limit\"),\n minSimilarity: threshold.min,\n ...(threshold.max !== undefined ? { maxSimilarity: threshold.max } : {}),\n });\n if (outputFormat() === \"summary\") process.stdout.write(`${formatSimilaritySummary(results)}\\n`);\n else printJson(results.map(presentMatch));\n break;\n }\n case \"cross-search\":\n await runCrossSearch(index, indexOptions, provider);\n break;\n default:\n throw new CodeIndexError(`Unknown command: ${command}`);\n }\n } finally {\n index.close();\n }\n}\n\nasync function runCrossSearch(\n source: CodeIndex,\n sourceOptions: CodeIndexOptions,\n provider: EmbeddingProvider,\n): Promise<void> {\n const targetRoot = parsed.values[\"target-root\"];\n const targetPath = parsed.values[\"target-index\"];\n if ((targetRoot && !targetPath) || (!targetRoot && targetPath)) {\n throw new CodeIndexError(\"Cross-index search requires both --target-root and --target-index.\");\n }\n const targetOptions: CodeIndexOptions | undefined = targetRoot && targetPath\n ? {\n ...sourceOptions,\n rootDir: path.resolve(targetRoot),\n indexPath: path.resolve(targetPath),\n provider,\n }\n : undefined;\n if (targetOptions) await initializeMissingIndex(targetOptions, \"target index\", \"HEAD\");\n const target = targetOptions ? new CodeIndex({ ...targetOptions, readOnly: true }) : undefined;\n const format = outputFormat();\n const threshold = similarityThreshold();\n try {\n for await (const result of crossSearch({\n source,\n ...(target ? { target } : {}),\n sourceFilter: parsed.values[\"added-since\"]\n ? {\n type: \"added-since\",\n commit: parsed.values[\"added-since\"],\n ...(parsed.values[\"source-path\"] ? { path: parsed.values[\"source-path\"] } : {}),\n }\n : {\n type: \"all\",\n ...(parsed.values[\"source-path\"] ? { path: parsed.values[\"source-path\"] } : {}),\n },\n limitPerFunction: numberOption(parsed.values.limit, 5, \"limit\"),\n minSimilarity: threshold.min,\n ...(threshold.max !== undefined ? { maxSimilarity: threshold.max } : {}),\n includeSymmetricDuplicates: parsed.values[\"include-symmetric-duplicates\"],\n })) {\n if (format === \"summary\") {\n process.stdout.write(`${formatSimilaritySummary(result.matches, result.source)}\\n`);\n } else {\n process.stdout.write(`${JSON.stringify({\n source: presentFunction(result.source),\n matches: result.matches.map(presentMatch),\n })}\\n`);\n }\n }\n } finally {\n target?.close();\n }\n}\n\nasync function initializeMissingIndex(\n options: CodeIndexOptions,\n label: string,\n target: string,\n): Promise<UpdateStats | null> {\n const indexPath = path.resolve(options.indexPath ?? path.join(path.resolve(options.rootDir), \".slopdex\", \"index.sqlite\"));\n if (existsSync(indexPath)) return null;\n\n process.stderr.write(`slopdex: ${label} not found at ${indexPath}; initializing automatically from committed ${target}.\\n`);\n const index = new CodeIndex({ ...options, indexPath });\n let initialized = false;\n try {\n const stats = await index.updateFromGit({ target });\n initialized = true;\n return stats;\n } finally {\n index.close();\n if (!initialized) {\n for (const suffix of [\"\", \"-shm\", \"-wal\", \"-journal\"]) rmSync(`${indexPath}${suffix}`, { force: true });\n }\n }\n}\n\nfunction loadConfig(rootDir: string, configuredPath?: string): FileConfig {\n const configPath = path.resolve(configuredPath ?? path.join(rootDir, \".slopdex\", \"config.json\"));\n if (!existsSync(configPath)) return commandLineConfig({});\n const value = JSON.parse(readFileSync(configPath, \"utf8\")) as FileConfig;\n return commandLineConfig(value);\n}\n\nfunction commandLineConfig(config: FileConfig): FileConfig {\n const dimensions = parsed.values.dimensions\n ? numberOption(parsed.values.dimensions, 0, \"dimensions\")\n : config.dimensions;\n const providerValue = parsed.values.provider ?? config.provider;\n if (providerValue !== undefined && providerValue !== \"openai\" && providerValue !== \"jina\") {\n throw new CodeIndexError(`Unsupported provider: ${providerValue}`);\n }\n const provider: FileConfig[\"provider\"] = providerValue === \"openai\" || providerValue === \"jina\"\n ? providerValue\n : undefined;\n return {\n ...config,\n ...(provider ? { provider } : {}),\n ...(parsed.values.model ? { model: parsed.values.model } : {}),\n ...(dimensions ? { dimensions } : {}),\n };\n}\n\nfunction createProvider(config: FileConfig): EmbeddingProvider {\n if ((config.provider ?? \"openai\") === \"jina\") {\n return new JinaEmbeddingProvider({\n ...(config.model ? { model: config.model } : {}),\n ...(config.dimensions ? { dimensions: config.dimensions } : {}),\n });\n }\n return new OpenAIEmbeddingProvider({\n ...(config.model ? { model: config.model } : {}),\n ...(config.dimensions ? { dimensions: config.dimensions } : {}),\n });\n}\n\nfunction numberOption(value: string | undefined, defaultValue: number, name: string): number {\n if (value === undefined) return defaultValue;\n const parsedValue = Number(value);\n if (!Number.isFinite(parsedValue)) throw new CodeIndexError(`${name} must be a number.`);\n return parsedValue;\n}\n\nfunction similarityThreshold(): { min: number; max?: number } {\n const threshold = parsed.values.threshold;\n const minimum = parsed.values[\"min-similarity\"];\n if (threshold !== undefined && minimum !== undefined) {\n throw new CodeIndexError(\"Use either --threshold or --min-similarity, not both.\");\n }\n if (threshold === undefined) return { min: numberOption(minimum, -1, \"min-similarity\") };\n\n const number = \"[+-]?(?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:e[+-]?\\\\d+)?\";\n const range = new RegExp(`^\\\\s*(${number})\\\\s*-\\\\s*(${number})\\\\s*$`, \"i\").exec(threshold);\n if (!range) return { min: numberOption(threshold, -1, \"threshold\") };\n const min = Number(range[1]);\n const max = Number(range[2]);\n if (!Number.isFinite(min) || !Number.isFinite(max)) throw new CodeIndexError(\"threshold range bounds must be numbers.\");\n if (min > max) throw new CodeIndexError(\"threshold range minimum must not exceed its maximum.\");\n return { min, max };\n}\n\nfunction outputFormat(): \"json\" | \"summary\" {\n const value = parsed.values.format ?? \"json\";\n if (value !== \"json\" && value !== \"summary\") throw new CodeIndexError(\"format must be json or summary.\");\n return value;\n}\n\nfunction presentFunction(value: IndexedFunction) {\n const { embeddingInput: _embeddingInput, embeddingId: _embeddingId, ...result } = value;\n return result;\n}\n\nfunction presentMatch(value: SimilarityResult) {\n return { similarity: value.similarity, function: presentFunction(value.function) };\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction printHelp(): void {\n process.stdout.write(`Usage: slopdex <command> [arguments] [options]\n\nCommands:\n status Show index metadata\n update-files <path...> Index specific working-tree files\n delete-files <path...> Remove specific files from the index\n update-git Index committed changes since the checkpoint\n search <query> Search functions by semantic similarity\n cross-search Find nearest functions for each source function\n\nOptions:\n --root <path> Repository root (default: current directory)\n --config <path> Config file (default: .slopdex/config.json)\n --index <path> SQLite index path\n --provider <openai|jina> Embedding provider\n --model <name> Embedding model\n --dimensions <number> Embedding dimensions\n --target <ref> Target ref for update-git (default: HEAD)\n --rebuild-on-divergence Rebuild after a rebase or branch change\n --limit <number> Search result limit\n --threshold <number|range> Show similarities at/above a value or within a range\n --min-similarity <number> Minimum raw cosine similarity\n --format <json|summary> Similarity output format (default: json)\n --include-symmetric-duplicates Show both directions of same-index matches\n --added-since <commit> Restrict cross-search source functions\n --source-path <path> Restrict cross-search sources to a file or directory\n --target-root <path> Root of a second indexed codebase\n --target-index <path> SQLite path of a second index\n\nExamples:\n Show metadata for the current index:\n slopdex status\n\n Index specific working-tree files:\n slopdex update-files src/service.ts src/model.ts\n\n Remove deleted files from the index:\n slopdex delete-files src/removed.ts\n\n Index the latest committed Git snapshot:\n slopdex update-git --target HEAD\n\n Find functions matching a semantic query:\n slopdex search \"validate an authenticated session\" --limit 10\n\n Review similar functions as duplicate-code candidates:\n slopdex cross-search --format summary --threshold 0.8 --limit 5\n\n Review functions under a path against the whole codebase:\n slopdex cross-search --source-path src/services --format summary\n`);\n}\n","import { lstat, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { CodeIndexError, GitDivergenceError } from \"./errors.js\";\nimport { GitRepository, type GitChange, type GitTreeEntry } from \"./git/repository.js\";\nimport { parseCallables } from \"./parser/callable-parser.js\";\nimport { SourcePolicy } from \"./source-policy.js\";\nimport { IndexDatabase, type PreparedCallable, type PreparedFile } from \"./storage/database.js\";\nimport type {\n CodeIndexOptions,\n CrossSearchSourceFilter,\n EmbeddingProfile,\n IndexStatus,\n IndexedFunction,\n SimilarityResult,\n SimilaritySearchOptions,\n UpdateFilesOptions,\n UpdateFromGitOptions,\n UpdateStats,\n} from \"./types.js\";\nimport { assertPositiveInteger, chunk, normalizeEmbeddingVector, normalizeRelativePath, sha256, throwIfAborted } from \"./utils.js\";\n\nconst DEFAULT_MAX_FILE_SIZE = 1024 * 1024;\nconst DEFAULT_BATCH_SIZE = 32;\n\nexport class CodeIndex {\n public readonly rootDir: string;\n public readonly indexPath: string;\n public readonly provider;\n readonly #database: IndexDatabase;\n readonly #policy: SourcePolicy;\n readonly #maxFileSize: number;\n readonly #embeddingBatchSize: number;\n readonly #git: GitRepository;\n readonly #onWarning: (message: string) => void;\n\n public constructor(options: CodeIndexOptions) {\n this.rootDir = path.resolve(options.rootDir);\n this.indexPath = path.resolve(options.indexPath ?? path.join(this.rootDir, \".slopdex\", \"index.sqlite\"));\n this.provider = options.provider;\n const profile = normalizeProfile(options.provider.profile);\n assertPositiveInteger(profile.dimensions, \"embedding dimensions\");\n this.#database = new IndexDatabase(this.indexPath, this.rootDir, profile, options.readOnly ?? false);\n this.#policy = new SourcePolicy(options.include, options.exclude);\n this.#maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n this.#embeddingBatchSize = options.embeddingBatchSize ?? DEFAULT_BATCH_SIZE;\n this.#onWarning = options.onWarning ?? console.warn;\n assertPositiveInteger(this.#maxFileSize, \"maxFileSize\");\n assertPositiveInteger(this.#embeddingBatchSize, \"embeddingBatchSize\");\n this.#git = new GitRepository(this.rootDir);\n }\n\n public close(): void {\n this.#database.close();\n }\n\n public status(): IndexStatus {\n return this.#database.status();\n }\n\n public allFunctions(): IndexedFunction[] {\n return this.#database.allFunctions();\n }\n\n public async updateFiles(options: UpdateFilesOptions): Promise<UpdateStats> {\n const normalizedRenames = (options.renames ?? []).map(({ from, to }) => ({\n from: normalizeRelativePath(this.rootDir, from),\n to: normalizeRelativePath(this.rootDir, to),\n }));\n validateRenames(normalizedRenames);\n const upsertPaths = [...new Set((options.upsert ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];\n const deletePaths = [...new Set((options.delete ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];\n const renameMap = new Map(\n normalizedRenames.map(({ from, to }) => [to, from]),\n );\n for (const target of renameMap.keys()) {\n if (!upsertPaths.includes(target)) upsertPaths.push(target);\n }\n\n const prepared: PreparedFile[] = [];\n for (const relativePath of upsertPaths) {\n throwIfAborted(options.signal);\n if (!this.#policy.includes(relativePath)) throw new CodeIndexError(`Unsupported or excluded source file: ${relativePath}`);\n const absolutePath = path.join(this.rootDir, relativePath);\n const info = await lstat(absolutePath);\n if (info.isSymbolicLink()) throw new CodeIndexError(`Symbolic links are not supported: ${relativePath}`);\n if (!info.isFile()) throw new CodeIndexError(`Not a regular file: ${relativePath}`);\n if (info.size > this.#maxFileSize) throw new CodeIndexError(`File exceeds maxFileSize: ${relativePath}`);\n const content = await readFile(absolutePath);\n const renameSource = renameMap.get(relativePath);\n const originalPath = renameSource ? this.#database.previousPath(renameSource) ?? renameSource : undefined;\n prepared.push(this.#prepareFile(relativePath, content, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(originalPath ? { previousPath: originalPath } : {}),\n ...(renameSource ? { replacePath: renameSource } : {}),\n }));\n }\n await this.#attachEmbeddings(prepared, options.signal);\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletePaths, ...renameMap.values()],\n });\n }\n\n public async updateFromGit(options: UpdateFromGitOptions = {}): Promise<UpdateStats> {\n throwIfAborted(options.signal);\n await this.#git.assertRepository();\n const relativeIndexPath = path.relative(this.rootDir, this.indexPath).replaceAll(path.sep, \"/\");\n const indexArtifacts = relativeIndexPath && !relativeIndexPath.startsWith(\"../\")\n ? [relativeIndexPath, `${relativeIndexPath}-shm`, `${relativeIndexPath}-wal`, `${relativeIndexPath}-journal`]\n : [];\n await this.#git.assertCleanWorkingTree(indexArtifacts);\n const target = await this.#git.resolveCommit(options.target ?? \"HEAD\");\n const checkpoint = this.#database.getCheckpoint();\n let rebuild = checkpoint === null;\n if (checkpoint && !(await this.#git.isAncestor(checkpoint, target))) {\n if (!options.rebuildOnDivergence) throw new GitDivergenceError(checkpoint, target);\n rebuild = true;\n }\n\n const tree = await this.#git.listTree(target);\n const workingFiles = this.#database.getWorkingTreeFiles();\n const changes = rebuild || !checkpoint ? [] : await this.#git.diff(checkpoint, target);\n const upserts = new Map<string, { entry: GitTreeEntry; previousPath?: string }>();\n const deletes = new Set<string>();\n if (rebuild) {\n for (const existing of this.#database.allFilePaths()) deletes.add(existing);\n for (const entry of tree.values()) {\n if (this.#policy.includes(entry.path) && entry.size <= this.#maxFileSize) upserts.set(entry.path, { entry });\n }\n } else {\n this.#classifyGitChanges(changes, tree, upserts, deletes);\n for (const { path: dirtyPath } of workingFiles) {\n const entry = tree.get(dirtyPath);\n if (entry && this.#policy.includes(dirtyPath) && entry.size <= this.#maxFileSize) upserts.set(dirtyPath, { entry });\n else deletes.add(dirtyPath);\n }\n const eligibleTargetPaths = new Set(\n [...tree.values()]\n .filter((entry) => this.#policy.includes(entry.path) && entry.size <= this.#maxFileSize)\n .map((entry) => entry.path),\n );\n const indexedPaths = new Set(this.#database.allFilePaths());\n for (const targetPath of eligibleTargetPaths) {\n if (!indexedPaths.has(targetPath) && !upserts.has(targetPath)) {\n upserts.set(targetPath, { entry: tree.get(targetPath)! });\n }\n }\n for (const indexedPath of indexedPaths) {\n if (!eligibleTargetPaths.has(indexedPath)) deletes.add(indexedPath);\n }\n }\n\n if (!rebuild && checkpoint === target && upserts.size === 0 && deletes.size === 0) return emptyStats(checkpoint);\n\n const prepared: PreparedFile[] = [];\n for (const { entry, previousPath } of upserts.values()) {\n throwIfAborted(options.signal);\n const content = await this.#git.readBlob(entry.oid);\n if (content.byteLength > this.#maxFileSize) {\n deletes.add(entry.path);\n continue;\n }\n prepared.push(this.#prepareFile(entry.path, content, {\n blobOid: entry.oid,\n sourceMode: \"git\",\n indexedCommit: target,\n ...(previousPath ? { replacePath: previousPath } : {}),\n }));\n }\n await this.#attachEmbeddings(prepared, options.signal);\n const resolvedAgain = await this.#git.resolveCommit(options.target ?? \"HEAD\");\n if (resolvedAgain !== target) throw new CodeIndexError(\"Target Git ref changed while indexing; retry the update.\");\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletes],\n checkpoint: target,\n expectedCheckpoint: checkpoint,\n });\n }\n\n #classifyGitChanges(\n changes: readonly GitChange[],\n tree: ReadonlyMap<string, GitTreeEntry>,\n upserts: Map<string, { entry: GitTreeEntry; previousPath?: string }>,\n deletes: Set<string>,\n ): void {\n for (const change of changes) {\n if (change.status === \"D\") {\n deletes.add(change.path);\n continue;\n }\n if (change.status === \"R\") {\n deletes.add(change.oldPath);\n const entry = tree.get(change.path);\n if (entry && this.#policy.includes(change.path) && entry.size <= this.#maxFileSize) {\n upserts.set(change.path, { entry, previousPath: change.oldPath });\n }\n continue;\n }\n const entry = tree.get(change.path);\n if (entry && this.#policy.includes(change.path) && entry.size <= this.#maxFileSize) upserts.set(change.path, { entry });\n else deletes.add(change.path);\n }\n }\n\n #prepareFile(\n relativePath: string,\n buffer: Buffer,\n provenance: Pick<PreparedFile, \"blobOid\" | \"sourceMode\" | \"indexedCommit\" | \"previousPath\" | \"replacePath\">,\n ): PreparedFile {\n const content = buffer.toString(\"utf8\");\n const callables = parseCallables(relativePath, content, this.#onWarning) as PreparedCallable[];\n const language = callables[0]?.language ?? path.extname(relativePath).slice(1);\n return {\n path: relativePath,\n contentHash: sha256(content),\n blobOid: provenance.blobOid,\n sourceMode: provenance.sourceMode,\n indexedCommit: provenance.indexedCommit,\n language,\n byteSize: buffer.byteLength,\n ...(provenance.previousPath ? { previousPath: provenance.previousPath } : {}),\n ...(provenance.replacePath ? { replacePath: provenance.replacePath } : {}),\n callables,\n };\n }\n\n async #attachEmbeddings(files: PreparedFile[], signal?: AbortSignal): Promise<void> {\n const profile = JSON.stringify(normalizeProfile(this.provider.profile));\n const unique = new Map<string, PreparedCallable[]>();\n for (const file of files) {\n for (const callable of file.callables) {\n callable.embeddingKey = sha256(`${profile}\\0${callable.embeddingInput}`);\n const values = unique.get(callable.embeddingKey) ?? [];\n values.push(callable);\n unique.set(callable.embeddingKey, values);\n }\n }\n const existing = this.#database.getEmbeddingKeys([...unique.keys()]);\n const missing = [...unique.entries()].filter(([key]) => !existing.has(key));\n for (const batch of chunk(missing, this.#embeddingBatchSize)) {\n throwIfAborted(signal);\n const vectors = await this.provider.embedDocuments(batch.map(([, callables]) => callables[0]!.embeddingInput), signal ? { signal } : undefined);\n if (vectors.length !== batch.length) throw new CodeIndexError(\"Embedding provider returned an unexpected number of vectors.\");\n vectors.forEach((vector, index) => {\n const converted = normalizeEmbeddingVector(vector, this.provider.profile.dimensions);\n for (const callable of batch[index]![1]) callable.vector = converted;\n });\n }\n }\n\n public async similaritySearch(options: SimilaritySearchOptions): Promise<SimilarityResult[]> {\n if (!options.query.trim()) throw new CodeIndexError(\"query must not be empty.\");\n const limit = options.limit ?? 10;\n assertPositiveInteger(limit, \"limit\");\n throwIfAborted(options.signal);\n const vector = await this.provider.embedQuery(options.query, options.signal ? { signal: options.signal } : undefined);\n return this.searchByVector(vector, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n }\n\n public similarToFunction(functionId: number, options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n }): SimilarityResult[] {\n const vector = this.#database.vectorForFunction(functionId);\n return this.#database.searchVector(vector, {\n limit: options.limit,\n minSimilarity: options.minSimilarity,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n excludeId: functionId,\n });\n }\n\n public vectorForFunction(functionId: number): number[] {\n return this.#database.vectorForFunction(functionId);\n }\n\n public searchByVector(vector: readonly number[], options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n }): SimilarityResult[] {\n return this.#database.searchVector(normalizeEmbeddingVector(vector, this.provider.profile.dimensions), options);\n }\n\n public async sourceFunctions(filter: CrossSearchSourceFilter): Promise<IndexedFunction[]> {\n const functions = filter.type === \"all\" ? this.allFunctions() : await this.#functionsAddedSince(filter.commit);\n if (!filter.path) return functions;\n const sourcePath = normalizeRelativePath(this.rootDir, filter.path);\n return functions.filter((callable) => callable.path === sourcePath || callable.path.startsWith(`${sourcePath}/`));\n }\n\n async #functionsAddedSince(baseRef: string): Promise<IndexedFunction[]> {\n await this.#git.assertRepository();\n const checkpoint = this.#database.getCheckpoint();\n if (!checkpoint) throw new CodeIndexError(\"added-since requires an index with a Git checkpoint.\");\n const base = await this.#git.resolveCommit(baseRef);\n if (!(await this.#git.isAncestor(base, checkpoint))) {\n throw new GitDivergenceError(base, checkpoint);\n }\n\n const changes = await this.#git.diff(base, checkpoint);\n const baseTree = await this.#git.listTree(base);\n const comparisonPaths = new Map<string, string | null>();\n for (const change of changes) {\n if (change.status === \"D\") continue;\n if (change.status === \"R\") comparisonPaths.set(change.path, change.oldPath);\n else if (change.status === \"A\" || change.status === \"C\") comparisonPaths.set(change.path, null);\n else comparisonPaths.set(change.path, change.path);\n }\n for (const dirtyFile of this.#database.getWorkingTreeFiles()) {\n if (!comparisonPaths.has(dirtyFile.path)) {\n comparisonPaths.set(dirtyFile.path, dirtyFile.previousPath ?? dirtyFile.path);\n }\n }\n\n const current = this.#database.functionsForPaths([...comparisonPaths.keys()]);\n const baseFunctionsByCurrentPath = new Map<string, ReturnType<typeof parseCallables>>();\n for (const [currentPath, basePath] of comparisonPaths) {\n if (!basePath) {\n baseFunctionsByCurrentPath.set(currentPath, []);\n continue;\n }\n const entry = baseTree.get(basePath);\n if (!entry) {\n baseFunctionsByCurrentPath.set(currentPath, []);\n continue;\n }\n const content = (await this.#git.readBlob(entry.oid)).toString(\"utf8\");\n baseFunctionsByCurrentPath.set(currentPath, parseCallables(basePath, content, this.#onWarning));\n }\n const currentByPath = groupBy(current, (callable) => callable.path);\n const addedIds = new Set<number>();\n for (const [currentPath, currentFunctions] of currentByPath) {\n for (const id of addedFunctionIds(currentFunctions, baseFunctionsByCurrentPath.get(currentPath) ?? [])) {\n addedIds.add(id);\n }\n }\n return current.filter((callable) => addedIds.has(callable.id));\n }\n}\n\nfunction addedFunctionIds(\n current: readonly IndexedFunction[],\n base: readonly Pick<IndexedFunction, \"qualifiedName\" | \"kind\" | \"sourceHash\">[],\n): number[] {\n const currentGroups = groupBy(current, (callable) => `${callable.qualifiedName}\\0${callable.kind}`);\n const baseGroups = groupBy(base, (callable) => `${callable.qualifiedName}\\0${callable.kind}`);\n const added: number[] = [];\n for (const [key, currentGroup] of currentGroups) {\n const baseGroup = baseGroups.get(key) ?? [];\n const unmatchedBase = new Set(baseGroup.map((_, index) => index));\n const unmatchedCurrent = new Set(currentGroup.map((_, index) => index));\n for (let currentIndex = 0; currentIndex < currentGroup.length; currentIndex += 1) {\n const exactBaseIndex = [...unmatchedBase].find(\n (baseIndex) => baseGroup[baseIndex]!.sourceHash === currentGroup[currentIndex]!.sourceHash,\n );\n if (exactBaseIndex !== undefined) {\n unmatchedBase.delete(exactBaseIndex);\n unmatchedCurrent.delete(currentIndex);\n }\n }\n for (const currentIndex of unmatchedCurrent) {\n const baseIndex = unmatchedBase.values().next().value as number | undefined;\n if (baseIndex === undefined) added.push(currentGroup[currentIndex]!.id);\n else unmatchedBase.delete(baseIndex);\n }\n }\n return added;\n}\n\nfunction normalizeProfile(profile: EmbeddingProfile): Required<EmbeddingProfile> {\n return {\n provider: profile.provider,\n model: profile.model,\n dimensions: profile.dimensions,\n strategyVersion: profile.strategyVersion ?? \"callable-v1\",\n };\n}\n\nfunction emptyStats(checkpoint: string | null): UpdateStats {\n return {\n filesUpdated: 0,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint,\n };\n}\n\nfunction validateRenames(renames: readonly { from: string; to: string }[]): void {\n const sources = new Set(renames.map((rename) => rename.from));\n const targets = new Set(renames.map((rename) => rename.to));\n if (sources.size !== renames.length || targets.size !== renames.length) {\n throw new CodeIndexError(\"Rename sources and targets must be unique.\");\n }\n if ([...sources].some((source) => targets.has(source))) {\n throw new CodeIndexError(\"Chained or cyclic renames must be applied in separate updates.\");\n }\n}\n\nfunction groupBy<T>(values: readonly T[], keyFor: (value: T) => string): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n for (const value of values) {\n const key = keyFor(value);\n const group = groups.get(key) ?? [];\n group.push(value);\n groups.set(key, group);\n }\n return groups;\n}\n","export class CodeIndexError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CodeIndexError\";\n }\n}\n\nexport class GitDivergenceError extends CodeIndexError {\n public constructor(checkpoint: string, target: string) {\n super(`Stored Git checkpoint ${checkpoint} is not an ancestor of ${target}; rebuild the index.`);\n this.name = \"GitDivergenceError\";\n }\n}\n\nexport class IncompatibleIndexError extends CodeIndexError {\n public constructor(message: string) {\n super(message);\n this.name = \"IncompatibleIndexError\";\n }\n}\n","import { spawn } from \"node:child_process\";\nimport path from \"node:path\";\n\nimport { CodeIndexError } from \"../errors.js\";\n\nexport type GitChange =\n | { status: \"A\" | \"M\" | \"D\" | \"T\"; path: string }\n | { status: \"R\" | \"C\"; oldPath: string; path: string };\n\nexport interface GitTreeEntry {\n path: string;\n oid: string;\n mode: string;\n size: number;\n}\n\nexport class GitRepository {\n public constructor(public readonly rootDir: string) {}\n\n async #run(args: readonly string[], allowExitOne = false): Promise<{ stdout: Buffer; code: number }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(\"git\", [\"-C\", this.rootDir, ...args], { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n child.stdout.on(\"data\", (value: Buffer) => stdout.push(value));\n child.stderr.on(\"data\", (value: Buffer) => stderr.push(value));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => {\n const exitCode = code ?? -1;\n if (exitCode === 0 || (allowExitOne && exitCode === 1)) {\n resolve({ stdout: Buffer.concat(stdout), code: exitCode });\n return;\n }\n reject(new CodeIndexError(`Git command failed: ${Buffer.concat(stderr).toString(\"utf8\").trim()}`));\n });\n });\n }\n\n public async assertRepository(): Promise<void> {\n const result = await this.#run([\"rev-parse\", \"--is-inside-work-tree\"]);\n if (result.stdout.toString(\"utf8\").trim() !== \"true\") {\n throw new CodeIndexError(`${this.rootDir} is not a Git worktree.`);\n }\n const topLevel = (await this.#run([\"rev-parse\", \"--show-toplevel\"])).stdout.toString(\"utf8\").trim();\n if (path.resolve(topLevel) !== path.resolve(this.rootDir)) {\n throw new CodeIndexError(`rootDir must be the Git worktree root: ${topLevel}`);\n }\n }\n\n public async assertCleanWorkingTree(excludePaths: readonly string[] = []): Promise<void> {\n const pathspecs = [\".\", ...excludePaths.map((filePath) => `:(top,literal,exclude)${filePath}`)];\n const result = await this.#run([\n \"status\",\n \"--porcelain=v1\",\n \"-z\",\n \"--untracked-files=all\",\n \"--ignore-submodules=none\",\n \"--\",\n ...pathspecs,\n ]);\n if (result.stdout.length > 0) {\n throw new CodeIndexError(\"Cannot update from Git: the working tree has uncommitted changes. Commit or stash them first.\");\n }\n }\n\n public async resolveCommit(ref: string): Promise<string> {\n const result = await this.#run([\"rev-parse\", \"--verify\", \"--end-of-options\", `${ref}^{commit}`]);\n const oid = result.stdout.toString(\"ascii\").trim();\n if (!/^[0-9a-f]{40,64}$/.test(oid)) throw new CodeIndexError(`Could not resolve Git commit: ${ref}`);\n return oid;\n }\n\n public async isAncestor(ancestor: string, descendant: string): Promise<boolean> {\n const result = await this.#run([\"merge-base\", \"--is-ancestor\", ancestor, descendant], true);\n return result.code === 0;\n }\n\n public async listTree(commit: string): Promise<Map<string, GitTreeEntry>> {\n const result = await this.#run([\"ls-tree\", \"-r\", \"-z\", \"-l\", \"--full-tree\", commit, \"--\"]);\n const entries = new Map<string, GitTreeEntry>();\n for (const record of splitNull(result.stdout)) {\n const tab = record.indexOf(\"\\t\");\n if (tab < 0) continue;\n const [mode, type, oid, sizeText] = record.slice(0, tab).trim().split(/\\s+/);\n const filePath = record.slice(tab + 1);\n const size = Number(sizeText);\n if ((mode === \"100644\" || mode === \"100755\") && type === \"blob\" && oid && Number.isSafeInteger(size)) {\n entries.set(filePath, { path: filePath, oid, mode, size });\n }\n }\n return entries;\n }\n\n public async readBlob(oid: string): Promise<Buffer> {\n return (await this.#run([\"cat-file\", \"blob\", oid])).stdout;\n }\n\n public async diff(base: string, target: string): Promise<GitChange[]> {\n const result = await this.#run([\"diff\", \"--name-status\", \"-z\", \"--find-renames\", `${base}..${target}`, \"--\"]);\n const values = splitNull(result.stdout);\n const changes: GitChange[] = [];\n for (let index = 0; index < values.length;) {\n const rawStatus = values[index++];\n if (!rawStatus) continue;\n const status = rawStatus[0];\n if (status === \"R\" || status === \"C\") {\n const oldPath = values[index++];\n const filePath = values[index++];\n if (oldPath && filePath) changes.push({ status, oldPath, path: filePath });\n } else if (status === \"A\" || status === \"M\" || status === \"D\" || status === \"T\") {\n const filePath = values[index++];\n if (filePath) changes.push({ status, path: filePath });\n } else {\n throw new CodeIndexError(`Unsupported Git diff status: ${rawStatus}`);\n }\n }\n return changes;\n }\n}\n\nfunction splitNull(buffer: Buffer): string[] {\n const value = buffer.toString(\"utf8\");\n const parts = value.split(\"\\0\");\n if (parts.at(-1) === \"\") parts.pop();\n return parts;\n}\n","import path from \"node:path\";\n\nimport Parser from \"tree-sitter\";\nimport JavaScript from \"tree-sitter-javascript\";\nimport TypeScript from \"tree-sitter-typescript\";\n\nimport { CodeIndexError } from \"../errors.js\";\nimport type { CallableKind, ParsedCallable, SupportedLanguage } from \"../types.js\";\nimport { sha256 } from \"../utils.js\";\n\ninterface CallableCandidate {\n node: Parser.SyntaxNode;\n name: string;\n kind: CallableKind;\n scope: readonly string[];\n}\n\nconst parsers = new Map<SupportedLanguage, Parser>();\n\nexport function languageForPath(filePath: string): SupportedLanguage | null {\n switch (path.extname(filePath).toLowerCase()) {\n case \".ts\":\n case \".mts\":\n case \".cts\":\n return \"typescript\";\n case \".tsx\":\n return \"tsx\";\n case \".js\":\n case \".mjs\":\n case \".cjs\":\n return \"javascript\";\n case \".jsx\":\n return \"jsx\";\n default:\n return null;\n }\n}\n\nfunction getParser(language: SupportedLanguage): Parser {\n const existing = parsers.get(language);\n if (existing) return existing;\n\n const parser = new Parser();\n if (language === \"typescript\") parser.setLanguage(TypeScript.typescript);\n else if (language === \"tsx\") parser.setLanguage(TypeScript.tsx);\n else parser.setLanguage(JavaScript);\n parsers.set(language, parser);\n return parser;\n}\n\nfunction parseTree(parser: Parser, content: string, relativePath: string): Parser.Tree {\n try {\n return parser.parse(content, undefined, { bufferSize: Buffer.byteLength(content) + 1 });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CodeIndexError(`Cannot index ${relativePath}: tree-sitter failed: ${message}`, { cause: error });\n }\n}\n\nfunction maskSyntax(value: string, replacement: string): string {\n return replacement + value.slice(replacement.length).replace(/[^\\r\\n]/g, \" \");\n}\n\nfunction recoverUnsupportedTypeScriptSyntax(\n parser: Parser,\n tree: Parser.Tree,\n content: string,\n relativePath: string,\n): Parser.Tree | null {\n const errors: Parser.SyntaxNode[] = [];\n const collectErrors = (node: Parser.SyntaxNode): void => {\n if (node.isError || node.isMissing) errors.push(node);\n for (const child of node.children) collectErrors(child);\n };\n collectErrors(tree.rootNode);\n\n if (errors.length === 0) return null;\n\n let recoveredContent = content;\n let changed = false;\n const taggedTemplateTypeArguments = new Map<number, Parser.SyntaxNode>();\n for (const error of errors) {\n const parent = error.parent;\n if (error.isMissing\n && error.type === \"!\"\n && parent?.type === \"type_arguments\"\n && /^\\s*`/.test(content.slice(parent.endIndex))) {\n taggedTemplateTypeArguments.set(parent.startIndex, parent);\n }\n }\n for (const node of [...taggedTemplateTypeArguments.values()].toSorted((left, right) => right.startIndex - left.startIndex)) {\n const value = recoveredContent.slice(node.startIndex, node.endIndex);\n recoveredContent = `${recoveredContent.slice(0, node.startIndex)}${value.replace(/[^\\r\\n]/g, \" \")}${recoveredContent.slice(node.endIndex)}`;\n changed = true;\n }\n\n for (const node of errors.filter((candidate) => {\n const parent = candidate.parent;\n return !candidate.isMissing\n && candidate.type === \"ERROR\"\n && candidate.text === \"type\"\n && parent?.type === \"export_statement\"\n && content.slice(parent.startIndex, candidate.startIndex).trim() === \"export\"\n && /^\\s*\\*/.test(content.slice(candidate.endIndex, parent.endIndex));\n }).toSorted((left, right) => right.startIndex - left.startIndex)) {\n recoveredContent = `${recoveredContent.slice(0, node.startIndex)} ${recoveredContent.slice(node.endIndex)}`;\n changed = true;\n }\n\n recoveredContent = recoveredContent.replace(\n /\\bimport\\s*\\(\\s*([\"'])(?:\\\\.|(?!\\1)[^\\\\])*\\1\\s*\\)/g,\n (value) => {\n changed = true;\n return maskSyntax(value, \"X\");\n },\n );\n if (!changed) return null;\n\n const recoveredTree = parseTree(parser, recoveredContent, relativePath);\n return recoveredTree.rootNode.hasError ? null : recoveredTree;\n}\n\nfunction textFor(content: string, node: Parser.SyntaxNode): string {\n return content.slice(node.startIndex, node.endIndex);\n}\n\nfunction fieldText(content: string, node: Parser.SyntaxNode, field: string): string | null {\n const child = node.childForFieldName(field);\n return child ? textFor(content, child) : null;\n}\n\nfunction callableKind(node: Parser.SyntaxNode, name: string): CallableKind {\n if (name === \"constructor\") return \"constructor\";\n if (node.type.includes(\"generator\") || /^\\s*(?:async\\s+)?\\*/.test(node.text)) return \"generator\";\n return node.type === \"method_definition\" ? \"method\" : \"function\";\n}\n\nfunction bindingName(content: string, node: Parser.SyntaxNode): string | null {\n const nameNode = node.childForFieldName(\"name\");\n if (!nameNode || ![\"identifier\", \"property_identifier\", \"private_property_identifier\"].includes(nameNode.type)) {\n return null;\n }\n return textFor(content, nameNode).replace(/^#/, \"\");\n}\n\nfunction assignmentName(content: string, node: Parser.SyntaxNode): string | null {\n const left = node.childForFieldName(\"left\");\n if (!left) return null;\n const value = textFor(content, left).trim();\n const match = value.match(/(?:^|[.#])([A-Za-z_$][\\w$]*)$/);\n return match?.[1] ?? null;\n}\n\nfunction objectScopeName(content: string, node: Parser.SyntaxNode): string | null {\n const parent = node.parent;\n if (!parent) return null;\n if (parent.type === \"variable_declarator\" && parent.childForFieldName(\"value\")?.id === node.id) {\n return bindingName(content, parent);\n }\n if (parent.type === \"pair\" && parent.childForFieldName(\"value\")?.id === node.id) {\n return fieldText(content, parent, \"key\")?.replace(/[\"']/g, \"\") ?? null;\n }\n if (parent.type === \"assignment_expression\" && parent.childForFieldName(\"right\")?.id === node.id) {\n return assignmentName(content, parent);\n }\n return null;\n}\n\nfunction walk(\n node: Parser.SyntaxNode,\n content: string,\n scope: readonly string[],\n candidates: CallableCandidate[],\n): void {\n if (node.type === \"class_declaration\" || node.type === \"class\") {\n const name = fieldText(content, node, \"name\") ?? objectScopeName(content, node);\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if (node.type === \"internal_module\" || node.type === \"module\") {\n const name = fieldText(content, node, \"name\")?.replace(/[\"']/g, \"\");\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if (node.type === \"object\") {\n const name = objectScopeName(content, node);\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if ([\"function_declaration\", \"generator_function_declaration\"].includes(node.type)) {\n const name = fieldText(content, node, \"name\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if (node.type === \"method_definition\") {\n const name = fieldText(content, node, \"name\")?.replace(/^#/, \"\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if (node.type === \"public_field_definition\" || node.type === \"field_definition\") {\n const name = (fieldText(content, node, \"name\") ?? fieldText(content, node, \"property\"))?.replace(/^#/, \"\");\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n const kind = callableKind(value, name) === \"generator\" ? \"generator\" : \"method\";\n candidates.push({ node: value, name, kind, scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"variable_declarator\") {\n const name = bindingName(content, node);\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"pair\") {\n const name = fieldText(content, node, \"key\")?.replace(/[\"']/g, \"\");\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"assignment_expression\") {\n const name = assignmentName(content, node);\n const value = node.childForFieldName(\"right\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if ([\"function_expression\", \"generator_function\"].includes(node.type)) {\n const name = fieldText(content, node, \"name\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n for (const child of node.namedChildren) walk(child, content, scope, candidates);\n}\n\nfunction signatureFor(content: string, node: Parser.SyntaxNode, name: string): string | null {\n const parameters = node.childForFieldName(\"parameters\");\n if (!parameters) return name;\n const returnType = node.childForFieldName(\"return_type\");\n return `${name}${textFor(content, parameters)}${returnType ? textFor(content, returnType) : \"\"}`;\n}\n\nexport function parseCallables(\n relativePath: string,\n content: string,\n onWarning: (message: string) => void = console.warn,\n): ParsedCallable[] {\n const language = languageForPath(relativePath);\n if (!language) return [];\n\n const parser = getParser(language);\n const parsedTree = parseTree(parser, content, relativePath);\n const tree = parsedTree.rootNode.hasError\n ? recoverUnsupportedTypeScriptSyntax(parser, parsedTree, content, relativePath) ?? parsedTree\n : parsedTree;\n if (tree.rootNode.hasError) {\n onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);\n }\n\n const candidates: CallableCandidate[] = [];\n walk(tree.rootNode, content, [], candidates);\n candidates.sort((left, right) => left.node.startIndex - right.node.startIndex);\n\n const occurrences = new Map<string, number>();\n return candidates.map(({ node, name, kind, scope }) => {\n const qualifiedName = [...scope, name].join(\".\");\n const baseIdentity = `${relativePath}\\0${qualifiedName}\\0${kind}`;\n const occurrence = occurrences.get(baseIdentity) ?? 0;\n occurrences.set(baseIdentity, occurrence + 1);\n const identityKey = sha256(`${baseIdentity}\\0${occurrence}`);\n const source = textFor(content, node);\n const signature = signatureFor(content, node, name);\n const embeddingInput = [\n `language: ${language}`,\n `kind: ${kind}`,\n `symbol: ${qualifiedName}`,\n signature ? `signature: ${signature}` : null,\n \"source:\",\n source,\n ].filter((value): value is string => value !== null).join(\"\\n\");\n\n return {\n path: relativePath,\n language,\n kind,\n name,\n qualifiedName,\n signature,\n identityKey,\n startLine: node.startPosition.row + 1,\n startColumn: node.startPosition.column + 1,\n endLine: node.endPosition.row + 1,\n endColumn: node.endPosition.column + 1,\n source,\n sourceHash: sha256(source),\n embeddingInput,\n };\n });\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { CodeIndexError } from \"./errors.js\";\n\nexport function sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function normalizeRelativePath(rootDir: string, inputPath: string): string {\n const absolute = path.resolve(rootDir, inputPath);\n const relative = path.relative(rootDir, absolute);\n if (relative === \"\" || relative === \".\") {\n throw new CodeIndexError(`Expected a file path, received repository root: ${inputPath}`);\n }\n if (relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n throw new CodeIndexError(`Path escapes repository root: ${inputPath}`);\n }\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function throwIfAborted(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nexport function chunk<T>(values: readonly T[], size: number): T[][] {\n const batches: T[][] = [];\n for (let index = 0; index < values.length; index += size) {\n batches.push(values.slice(index, index + size));\n }\n return batches;\n}\n\nexport function assertPositiveInteger(value: number, name: string): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new CodeIndexError(`${name} must be a positive integer.`);\n }\n}\n\nexport function normalizeEmbeddingVector(value: unknown, dimensions: number): number[] {\n if (!Array.isArray(value) || value.length !== dimensions) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n const converted: number[] = [];\n for (const component of value) {\n if (typeof component !== \"number\" || !Number.isFinite(component)) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n const normalized = Math.fround(component);\n if (!Number.isFinite(normalized)) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n converted.push(normalized);\n }\n if (!converted.some((component) => component !== 0)) {\n throw new CodeIndexError(\"Embedding vector must not be all zeroes.\");\n }\n return converted;\n}\n","import path from \"node:path\";\n\nimport { languageForPath } from \"./parser/callable-parser.js\";\n\nconst DEFAULT_EXCLUDED_SEGMENTS = new Set([\n \".git\",\n \".slopdex\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \"coverage\",\n \"vendor\",\n \"generated\",\n]);\n\nexport class SourcePolicy {\n readonly #include: readonly string[];\n readonly #exclude: readonly string[];\n\n public constructor(include: readonly string[] = [], exclude: readonly string[] = []) {\n this.#include = include;\n this.#exclude = exclude;\n }\n\n public includes(relativePath: string): boolean {\n const normalized = relativePath.replaceAll(\"\\\\\", \"/\");\n if (!languageForPath(normalized)) return false;\n if (normalized.split(\"/\").some((segment) => DEFAULT_EXCLUDED_SEGMENTS.has(segment))) return false;\n if (this.#exclude.some((pattern) => path.matchesGlob(normalized, pattern))) return false;\n return this.#include.length === 0 || this.#include.some((pattern) => path.matchesGlob(normalized, pattern));\n }\n}\n","import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\n\nimport * as sqliteVec from \"sqlite-vec\";\n\nimport { CodeIndexError, IncompatibleIndexError } from \"../errors.js\";\nimport type {\n EmbeddingProfile,\n IndexStatus,\n IndexedFunction,\n ParsedCallable,\n SourceMode,\n UpdateStats,\n} from \"../types.js\";\n\nconst SCHEMA_VERSION = \"1\";\n\nexport interface PreparedCallable extends ParsedCallable {\n embeddingKey: string;\n vector?: readonly number[];\n}\n\nexport interface PreparedFile {\n path: string;\n contentHash: string;\n blobOid: string | null;\n sourceMode: SourceMode;\n indexedCommit: string | null;\n language: string;\n byteSize: number;\n previousPath?: string;\n replacePath?: string;\n callables: PreparedCallable[];\n}\n\ninterface FunctionRow {\n id: number;\n path: string;\n language: IndexedFunction[\"language\"];\n kind: IndexedFunction[\"kind\"];\n name: string;\n qualified_name: string;\n signature: string | null;\n identity_key: string;\n start_line: number;\n start_column: number;\n end_line: number;\n end_column: number;\n source: string;\n source_hash: string;\n embedding_input: string;\n first_seen_commit: string | null;\n last_seen_commit: string | null;\n source_mode: SourceMode;\n embedding_id: number;\n}\n\nexport class IndexDatabase {\n readonly #db: DatabaseSync;\n readonly #rootDir: string;\n readonly #indexPath: string;\n readonly #profile: Required<EmbeddingProfile>;\n\n public constructor(indexPath: string, rootDir: string, profile: Required<EmbeddingProfile>, readOnly = false) {\n if (!readOnly) mkdirSync(path.dirname(indexPath), { recursive: true });\n this.#indexPath = indexPath;\n this.#rootDir = rootDir;\n this.#profile = profile;\n this.#db = new DatabaseSync(indexPath, { allowExtension: true, readOnly });\n sqliteVec.load(this.#db);\n this.#db.enableLoadExtension(false);\n if (readOnly) {\n this.#db.exec(\"PRAGMA foreign_keys=ON\");\n } else {\n this.#db.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;\");\n this.#migrate();\n }\n this.#validateMetadata(readOnly);\n }\n\n public close(): void {\n this.#db.close();\n }\n\n #migrate(): void {\n this.#db.exec(`\n CREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS files (\n path TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n blob_oid TEXT,\n source_mode TEXT NOT NULL CHECK(source_mode IN ('git', 'working-tree')),\n indexed_commit TEXT,\n previous_path TEXT,\n language TEXT NOT NULL,\n byte_size INTEGER NOT NULL\n );\n CREATE TABLE IF NOT EXISTS embeddings (\n id INTEGER PRIMARY KEY,\n embedding_key TEXT NOT NULL UNIQUE,\n vector BLOB NOT NULL\n );\n CREATE TABLE IF NOT EXISTS functions (\n id INTEGER PRIMARY KEY,\n path TEXT NOT NULL REFERENCES files(path) ON DELETE CASCADE ON UPDATE CASCADE,\n language TEXT NOT NULL,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL,\n signature TEXT,\n identity_key TEXT NOT NULL UNIQUE,\n start_line INTEGER NOT NULL,\n start_column INTEGER NOT NULL,\n end_line INTEGER NOT NULL,\n end_column INTEGER NOT NULL,\n source TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n embedding_input TEXT NOT NULL,\n first_seen_commit TEXT,\n last_seen_commit TEXT,\n source_mode TEXT NOT NULL CHECK(source_mode IN ('git', 'working-tree')),\n embedding_id INTEGER NOT NULL REFERENCES embeddings(id)\n );\n CREATE INDEX IF NOT EXISTS functions_path ON functions(path);\n CREATE INDEX IF NOT EXISTS functions_embedding ON functions(embedding_id);\n `);\n const fileColumns = this.#db.prepare(\"PRAGMA table_info(files)\").all() as Array<{ name: string }>;\n if (!fileColumns.some((column) => column.name === \"previous_path\")) {\n this.#db.exec(\"ALTER TABLE files ADD COLUMN previous_path TEXT\");\n }\n }\n\n #metadata(key: string): string | null {\n const row = this.#db.prepare(\"SELECT value FROM metadata WHERE key = ?\").get(key) as { value: string } | undefined;\n return row?.value ?? null;\n }\n\n #setMetadata(key: string, value: string): void {\n this.#db.prepare(`\n INSERT INTO metadata(key, value) VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n `).run(key, value);\n }\n\n #validateMetadata(readOnly: boolean): void {\n const schemaVersion = this.#metadata(\"schema_version\");\n if (readOnly && !schemaVersion) throw new IncompatibleIndexError(\"Target file is not a slopdex index.\");\n if (schemaVersion && schemaVersion !== SCHEMA_VERSION) {\n throw new IncompatibleIndexError(`Unsupported index schema version ${schemaVersion}.`);\n }\n const storedRoot = this.#metadata(\"root_dir\");\n if (readOnly && !storedRoot) throw new IncompatibleIndexError(\"Target index has no repository identity.\");\n if (storedRoot && path.resolve(storedRoot) !== this.#rootDir) {\n throw new IncompatibleIndexError(`Index belongs to ${storedRoot}, not ${this.#rootDir}.`);\n }\n const profileJson = JSON.stringify(this.#profile);\n const storedProfile = this.#metadata(\"embedding_profile\");\n if (readOnly && !storedProfile) throw new IncompatibleIndexError(\"Target index has no embedding profile.\");\n if (storedProfile && storedProfile !== profileJson) {\n throw new IncompatibleIndexError(\"Embedding provider, model, dimensions, or strategy differs from this index.\");\n }\n if (readOnly) return;\n this.#transaction(() => {\n this.#setMetadata(\"schema_version\", SCHEMA_VERSION);\n this.#setMetadata(\"root_dir\", this.#rootDir);\n this.#setMetadata(\"embedding_profile\", profileJson);\n if (!this.#metadata(\"generation\")) this.#setMetadata(\"generation\", \"0\");\n });\n }\n\n #transaction<T>(operation: () => T): T {\n this.#db.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = operation();\n this.#db.exec(\"COMMIT\");\n return result;\n } catch (error) {\n this.#db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n public getCheckpoint(): string | null {\n return this.#metadata(\"git_checkpoint\");\n }\n\n public getGeneration(): number {\n return Number(this.#metadata(\"generation\") ?? 0);\n }\n\n public getWorkingTreeFiles(): Array<{ path: string; previousPath: string | null }> {\n return this.#db.prepare(`\n SELECT path, previous_path AS previousPath\n FROM files WHERE source_mode = 'working-tree' ORDER BY path\n `).all() as Array<{ path: string; previousPath: string | null }>;\n }\n\n public getEmbeddingKeys(keys: readonly string[]): Set<string> {\n const found = new Set<string>();\n const statement = this.#db.prepare(\"SELECT 1 FROM embeddings WHERE embedding_key = ?\");\n for (const key of keys) {\n if (statement.get(key)) found.add(key);\n }\n return found;\n }\n\n public applyUpdate(options: {\n files: readonly PreparedFile[];\n deletePaths: readonly string[];\n checkpoint?: string;\n expectedCheckpoint?: string | null;\n }): UpdateStats {\n return this.#transaction(() => {\n if (options.expectedCheckpoint !== undefined && this.getCheckpoint() !== options.expectedCheckpoint) {\n throw new CodeIndexError(\"Git checkpoint changed while the update was being prepared.\");\n }\n\n const stats: UpdateStats = {\n filesUpdated: options.files.length,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint: options.checkpoint ?? this.getCheckpoint(),\n };\n\n const deleteFile = this.#db.prepare(\"DELETE FROM files WHERE path = ?\");\n const countFunctions = this.#db.prepare(\"SELECT COUNT(*) AS count FROM functions WHERE path = ?\");\n const uniqueDeletes = new Set(options.deletePaths);\n for (const file of options.files) {\n uniqueDeletes.delete(file.path);\n if (file.previousPath) uniqueDeletes.delete(file.previousPath);\n if (file.replacePath) uniqueDeletes.delete(file.replacePath);\n }\n for (const filePath of uniqueDeletes) {\n const count = Number((countFunctions.get(filePath) as { count: number }).count);\n const result = deleteFile.run(filePath);\n if (result.changes > 0) {\n stats.filesDeleted += 1;\n stats.functionsDeleted += count;\n }\n }\n\n for (const file of options.files) this.#replaceFile(file, stats);\n\n this.#db.exec(\"DELETE FROM embeddings WHERE id NOT IN (SELECT DISTINCT embedding_id FROM functions)\");\n const generation = this.getGeneration() + 1;\n this.#setMetadata(\"generation\", String(generation));\n if (options.checkpoint) this.#setMetadata(\"git_checkpoint\", options.checkpoint);\n return stats;\n });\n }\n\n #replaceFile(file: PreparedFile, stats: UpdateStats): void {\n const sourcePath = file.replacePath ?? file.previousPath ?? file.path;\n const oldRows = this.#rowsForPath(sourcePath);\n const existingFile = this.#db.prepare(\"SELECT previous_path FROM files WHERE path = ?\").get(sourcePath) as\n | { previous_path: string | null }\n | undefined;\n const oldMatches = reconcileFunctions(file.callables, oldRows);\n\n if (sourcePath !== file.path) {\n this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(sourcePath);\n } else {\n this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(file.path);\n }\n this.#db.prepare(`\n INSERT INTO files(path, content_hash, blob_oid, source_mode, indexed_commit, previous_path, language, byte_size)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n file.path,\n file.contentHash,\n file.blobOid,\n file.sourceMode,\n file.indexedCommit,\n file.sourceMode === \"working-tree\" ? file.previousPath ?? existingFile?.previous_path ?? null : null,\n file.language,\n file.byteSize,\n );\n\n const usedIds = new Set<number>();\n const orderedCallables = [\n ...file.callables.filter((callable) => oldMatches.has(callable)),\n ...file.callables.filter((callable) => !oldMatches.has(callable)),\n ];\n for (const callable of orderedCallables) {\n if (callable.vector) {\n const result = this.#db.prepare(\"INSERT OR IGNORE INTO embeddings(embedding_key, vector) VALUES (?, ?)\")\n .run(callable.embeddingKey, vectorBuffer(callable.vector));\n stats.embeddingsCreated += Number(result.changes);\n }\n const embedding = this.#db.prepare(\"SELECT id FROM embeddings WHERE embedding_key = ?\").get(callable.embeddingKey) as { id: number } | undefined;\n if (!embedding) throw new CodeIndexError(`Missing embedding for ${callable.qualifiedName}.`);\n\n const old = oldMatches.get(callable);\n if (old) usedIds.add(old.id);\n const firstSeenCommit = old?.first_seen_commit ?? file.indexedCommit;\n this.#db.prepare(`\n INSERT INTO functions(\n id, path, language, kind, name, qualified_name, signature, identity_key,\n start_line, start_column, end_line, end_column, source, source_hash,\n embedding_input, first_seen_commit, last_seen_commit, source_mode, embedding_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n old?.id ?? null,\n file.path,\n callable.language,\n callable.kind,\n callable.name,\n callable.qualifiedName,\n callable.signature,\n callable.identityKey,\n callable.startLine,\n callable.startColumn,\n callable.endLine,\n callable.endColumn,\n callable.source,\n callable.sourceHash,\n callable.embeddingInput,\n firstSeenCommit,\n file.indexedCommit,\n file.sourceMode,\n embedding.id,\n );\n if (old) stats.functionsUpdated += 1;\n else stats.functionsAdded += 1;\n }\n stats.functionsDeleted += oldRows.length - usedIds.size;\n }\n\n #rowsForPath(filePath: string): FunctionRow[] {\n return this.#db.prepare(\"SELECT * FROM functions WHERE path = ? ORDER BY start_line, start_column, id\").all(filePath) as unknown as FunctionRow[];\n }\n\n public allFunctions(): IndexedFunction[] {\n return (this.#db.prepare(\"SELECT * FROM functions ORDER BY path, start_line, start_column, id\").all() as unknown as FunctionRow[])\n .map(toIndexedFunction);\n }\n\n public allFilePaths(): string[] {\n return (this.#db.prepare(\"SELECT path FROM files ORDER BY path\").all() as Array<{ path: string }>).map((row) => row.path);\n }\n\n public previousPath(filePath: string): string | null {\n const row = this.#db.prepare(\"SELECT previous_path FROM files WHERE path = ?\").get(filePath) as\n | { previous_path: string | null }\n | undefined;\n return row?.previous_path ?? null;\n }\n\n public functionsForPaths(paths: readonly string[]): IndexedFunction[] {\n const results: IndexedFunction[] = [];\n for (const filePath of paths) results.push(...this.#rowsForPath(filePath).map(toIndexedFunction));\n return results;\n }\n\n public searchVector(vector: readonly number[], options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludeId?: number;\n }): Array<{ function: IndexedFunction; similarity: number }> {\n const rows = this.#db.prepare(`\n SELECT f.*, 1.0 - vec_distance_cosine(e.vector, ?) AS similarity\n FROM functions f\n JOIN embeddings e ON e.id = f.embedding_id\n WHERE (? IS NULL OR f.id != ?)\n AND (1.0 - vec_distance_cosine(e.vector, ?)) >= ?\n AND (? IS NULL OR (1.0 - vec_distance_cosine(e.vector, ?)) <= ?)\n ORDER BY similarity DESC, f.id ASC\n LIMIT ?\n `).all(\n vectorBuffer(vector),\n options.excludeId ?? null,\n options.excludeId ?? null,\n vectorBuffer(vector),\n options.minSimilarity,\n options.maxSimilarity ?? null,\n vectorBuffer(vector),\n options.maxSimilarity ?? null,\n options.limit,\n ) as unknown as Array<FunctionRow & { similarity: number }>;\n return rows.map((row) => ({ function: toIndexedFunction(row), similarity: row.similarity }));\n }\n\n public vectorForFunction(id: number): number[] {\n const row = this.#db.prepare(`\n SELECT e.vector FROM functions f JOIN embeddings e ON e.id = f.embedding_id WHERE f.id = ?\n `).get(id) as { vector: Uint8Array } | undefined;\n if (!row) throw new CodeIndexError(`Function ${id} does not exist.`);\n return Array.from(new Float32Array(row.vector.buffer, row.vector.byteOffset, row.vector.byteLength / 4));\n }\n\n public status(): IndexStatus {\n const functionCount = Number((this.#db.prepare(\"SELECT COUNT(*) AS count FROM functions\").get() as { count: number }).count);\n const fileCount = Number((this.#db.prepare(\"SELECT COUNT(*) AS count FROM files\").get() as { count: number }).count);\n return {\n rootDir: this.#rootDir,\n indexPath: this.#indexPath,\n functionCount,\n fileCount,\n generation: this.getGeneration(),\n gitCheckpoint: this.getCheckpoint(),\n embeddingProfile: this.#profile,\n };\n }\n}\n\nfunction vectorBuffer(vector: readonly number[]): Uint8Array {\n const values = Float32Array.from(vector);\n return new Uint8Array(values.buffer);\n}\n\nfunction toIndexedFunction(row: FunctionRow): IndexedFunction {\n return {\n id: row.id,\n path: row.path,\n language: row.language,\n kind: row.kind,\n name: row.name,\n qualifiedName: row.qualified_name,\n signature: row.signature,\n identityKey: row.identity_key,\n startLine: row.start_line,\n startColumn: row.start_column,\n endLine: row.end_line,\n endColumn: row.end_column,\n source: row.source,\n sourceHash: row.source_hash,\n embeddingInput: row.embedding_input,\n firstSeenCommit: row.first_seen_commit,\n lastSeenCommit: row.last_seen_commit,\n sourceMode: row.source_mode,\n embeddingId: row.embedding_id,\n };\n}\n\nfunction reconcileFunctions(\n current: readonly PreparedCallable[],\n previous: readonly FunctionRow[],\n): Map<PreparedCallable, FunctionRow> {\n const matches = new Map<PreparedCallable, FunctionRow>();\n const keys = new Set([\n ...current.map((callable) => `${callable.qualifiedName}\\0${callable.kind}`),\n ...previous.map((callable) => `${callable.qualified_name}\\0${callable.kind}`),\n ]);\n for (const key of keys) {\n const currentGroup = current.filter((callable) => `${callable.qualifiedName}\\0${callable.kind}` === key);\n const previousGroup = previous.filter((callable) => `${callable.qualified_name}\\0${callable.kind}` === key);\n const unmatchedPrevious = new Set(previousGroup);\n const unmatchedCurrent = new Set(currentGroup);\n for (const callable of currentGroup) {\n const exact = [...unmatchedPrevious].find((old) => old.source_hash === callable.sourceHash);\n if (exact) {\n matches.set(callable, exact);\n unmatchedPrevious.delete(exact);\n unmatchedCurrent.delete(callable);\n }\n }\n for (const callable of unmatchedCurrent) {\n const old = unmatchedPrevious.values().next().value as FunctionRow | undefined;\n if (!old) break;\n matches.set(callable, old);\n unmatchedPrevious.delete(old);\n }\n }\n return matches;\n}\n","import { CodeIndexError } from \"../errors.js\";\nimport { normalizeEmbeddingVector } from \"../utils.js\";\n\ninterface EmbeddingResponse {\n data?: Array<{ index?: number; embedding?: number[] }>;\n}\n\nexport async function requestEmbeddings(options: {\n url: string;\n apiKey: string;\n body: Record<string, unknown>;\n expectedCount: number;\n dimensions: number;\n signal?: AbortSignal;\n}): Promise<number[][]> {\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n const response = await fetch(options.url, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(options.body),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n const detail = (await response.text()).slice(0, 500);\n const error = new CodeIndexError(`Embedding request failed (${response.status}): ${detail}`);\n if (response.status !== 429 && response.status < 500) throw error;\n lastError = error;\n } else {\n const payload = await response.json() as EmbeddingResponse;\n if (!Array.isArray(payload.data) || payload.data.length !== options.expectedCount) {\n throw new CodeIndexError(\"Embedding provider returned an unexpected number of vectors.\");\n }\n const indexes = payload.data.map((item) => item.index);\n if (indexes.some((index) => !Number.isInteger(index))\n || new Set(indexes).size !== options.expectedCount\n || indexes.some((index) => index! < 0 || index! >= options.expectedCount)) {\n throw new CodeIndexError(\"Embedding provider returned invalid vector indexes.\");\n }\n const ordered = new Array<{ index?: number; embedding?: number[] }>(options.expectedCount);\n for (const item of payload.data) ordered[item.index!] = item;\n try {\n return ordered.map((item) => normalizeEmbeddingVector(item.embedding, options.dimensions));\n } catch {\n throw new CodeIndexError(\"Embedding provider returned a malformed vector.\");\n }\n }\n } catch (error) {\n if (options.signal?.aborted) throw error;\n lastError = error;\n if (error instanceof CodeIndexError && !/\\((429|5\\d\\d)\\)/.test(error.message)) throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, 250 * 2 ** attempt));\n }\n throw new CodeIndexError(\"Embedding request failed after three attempts.\", { cause: lastError });\n}\n","import type { EmbeddingProvider } from \"../types.js\";\nimport { requestEmbeddings } from \"./http.js\";\n\nexport interface JinaEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n}\n\nexport class JinaEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #url: string;\n\n public constructor(options: JinaEmbeddingProviderOptions = {}) {\n this.#apiKey = options.apiKey ?? process.env.JINA_API_KEY ?? \"\";\n if (!this.#apiKey) throw new Error(\"JINA_API_KEY is required.\");\n const model = options.model ?? \"jina-embeddings-v4\";\n const dimensions = options.dimensions ?? 1024;\n if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error(\"dimensions must be a positive integer.\");\n this.profile = {\n provider: \"jina\",\n model,\n dimensions,\n strategyVersion: \"callable-v1:code-query-passage\",\n } as const;\n this.#url = options.baseUrl ?? \"https://api.jina.ai/v1/embeddings\";\n }\n\n public embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return Promise.resolve([]);\n return this.#embed(inputs, \"code.passage\", options?.signal);\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n return (await this.#embed([input], \"code.query\", options?.signal))[0]!;\n }\n\n #embed(inputs: readonly string[], task: \"code.passage\" | \"code.query\", signal?: AbortSignal): Promise<number[][]> {\n return requestEmbeddings({\n url: this.#url,\n apiKey: this.#apiKey,\n body: {\n model: this.profile.model,\n dimensions: this.profile.dimensions,\n embedding_type: \"float\",\n truncate: true,\n task,\n input: inputs,\n },\n expectedCount: inputs.length,\n dimensions: this.profile.dimensions,\n ...(signal ? { signal } : {}),\n });\n }\n}\n","import { Tiktoken } from \"js-tiktoken/lite\";\nimport cl100kBase from \"js-tiktoken/ranks/cl100k_base\";\n\nimport type { EmbeddingProvider } from \"../types.js\";\nimport { requestEmbeddings } from \"./http.js\";\n\nconst MAX_INPUT_TOKENS = 8192;\nlet tokenizer: Tiktoken | undefined;\n\nfunction truncateInput(input: string): string {\n tokenizer ??= new Tiktoken(cl100kBase);\n const tokens = tokenizer.encode(input);\n return tokens.length <= MAX_INPUT_TOKENS ? input : tokenizer.decode(tokens.slice(0, MAX_INPUT_TOKENS));\n}\n\nexport interface OpenAIEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n}\n\nexport class OpenAIEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #url: string;\n\n public constructor(options: OpenAIEmbeddingProviderOptions = {}) {\n this.#apiKey = options.apiKey ?? process.env.OPENAI_API_KEY ?? \"\";\n if (!this.#apiKey) throw new Error(\"OPENAI_API_KEY is required.\");\n const model = options.model ?? \"text-embedding-3-small\";\n const dimensions = options.dimensions ?? 1536;\n if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error(\"dimensions must be a positive integer.\");\n this.profile = { provider: \"openai\", model, dimensions, strategyVersion: \"callable-v1\" } as const;\n this.#url = `${(options.baseUrl ?? \"https://api.openai.com/v1\").replace(/\\/$/, \"\")}/embeddings`;\n }\n\n public embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return Promise.resolve([]);\n return this.#embed(inputs, options?.signal);\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n return (await this.#embed([input], options?.signal))[0]!;\n }\n\n #embed(inputs: readonly string[], signal?: AbortSignal): Promise<number[][]> {\n return requestEmbeddings({\n url: this.#url,\n apiKey: this.#apiKey,\n body: {\n model: this.profile.model,\n dimensions: this.profile.dimensions,\n encoding_format: \"float\",\n input: inputs.map(truncateInput),\n },\n expectedCount: inputs.length,\n dimensions: this.profile.dimensions,\n ...(signal ? { signal } : {}),\n });\n }\n}\n","import type { IndexedFunction, SimilarityResult } from \"./types.js\";\n\nfunction functionName(value: Pick<IndexedFunction, \"path\" | \"qualifiedName\">): string {\n return `${value.path} :: ${value.qualifiedName}`;\n}\n\nexport function formatSimilaritySummary(\n matches: readonly SimilarityResult[],\n source?: IndexedFunction,\n): string {\n const lines = matches.map((match) => `${source ? \" \" : \"\"}${match.similarity.toFixed(4)} ${functionName(match.function)}`);\n if (!source) return lines.length > 0 ? lines.join(\"\\n\") : \"No matches.\";\n return [functionName(source), ...(lines.length > 0 ? lines : [\" No matches.\"])].join(\"\\n\");\n}\n","import { IncompatibleIndexError } from \"../errors.js\";\nimport type { CrossSearchOptions, CrossSearchResult } from \"../types.js\";\nimport { assertPositiveInteger, throwIfAborted } from \"../utils.js\";\n\nexport async function* crossSearch(options: CrossSearchOptions): AsyncGenerator<CrossSearchResult> {\n const target = options.target ?? options.source;\n const sourceProfile = JSON.stringify(options.source.status().embeddingProfile);\n const targetProfile = JSON.stringify(target.status().embeddingProfile);\n if (sourceProfile !== targetProfile) {\n throw new IncompatibleIndexError(\"Cross-search requires identical embedding profiles.\");\n }\n\n const limit = options.limitPerFunction ?? 5;\n assertPositiveInteger(limit, \"limitPerFunction\");\n const sourceFunctions = await options.source.sourceFunctions(options.sourceFilter ?? { type: \"all\" });\n const sameIndex = target.indexPath === options.source.indexPath;\n const seenPairs = new Set<string>();\n for (let index = 0; index < sourceFunctions.length; index += 1) {\n throwIfAborted(options.signal);\n const source = sourceFunctions[index]!;\n const vector = options.source.vectorForFunction(source.id);\n const candidates = sameIndex\n ? options.source.similarToFunction(source.id, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n })\n : target.searchByVector(vector, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n const matches = sameIndex && !options.includeSymmetricDuplicates\n ? candidates.filter((match) => {\n const pair = source.id < match.function.id\n ? `${source.id}:${match.function.id}`\n : `${match.function.id}:${source.id}`;\n if (seenPairs.has(pair)) return false;\n seenPairs.add(pair);\n return true;\n })\n : candidates;\n if (matches.length > 0) yield { source, matches };\n options.onProgress?.({ completed: index + 1, total: sourceFunctions.length });\n }\n}\n"],"mappings":";;;AAEA,SAAS,YAAY,cAAc,cAAc;AACjD,OAAOA,WAAU;AACjB,SAAS,iBAAiB;;;ACJ1B,SAAS,OAAO,gBAAgB;AAChC,O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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAkDtB;AACD;","names":["path","path","path","path","path","path","path","path","path","path","path","entry","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/code-index.ts","../src/errors.ts","../src/git/repository.ts","../src/parser/callable-parser.ts","../src/utils.ts","../src/source-policy.ts","../src/storage/database.ts","../src/analysis/cohesion.ts","../src/embeddings/http.ts","../src/embeddings/jina.ts","../src/embeddings/openai.ts","../src/format.ts","../src/search/cross-search.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { existsSync, readFileSync, rmSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { CodeIndex } from \"./code-index.js\";\nimport { analyzeCohesion } from \"./analysis/cohesion.js\";\nimport { JinaEmbeddingProvider } from \"./embeddings/jina.js\";\nimport { OpenAIEmbeddingProvider } from \"./embeddings/openai.js\";\nimport { CodeIndexError, GitUnavailableError, IncompatibleIndexError } from \"./errors.js\";\nimport { formatCohesionSummary, formatSimilarityClusters, formatSimilaritySummary } from \"./format.js\";\nimport { crossSearch } from \"./search/cross-search.js\";\nimport type {\n CodeIndexOptions,\n CohesionFunctionReference,\n CohesionJsonReport,\n CohesionReport,\n CrossSearchOptions,\n CrossSearchResult,\n CrossSearchSourceFilter,\n EmbeddingProvider,\n IndexedFunction,\n SimilarityResult,\n UpdateStats,\n} from \"./types.js\";\n\ninterface FileConfig {\n provider?: \"openai\" | \"jina\";\n model?: string;\n dimensions?: number;\n indexPath?: string;\n include?: string[];\n exclude?: string[];\n maxFileSize?: number;\n embeddingBatchSize?: number;\n}\n\nconst parsed = (() => {\n try {\n return parseArgs({\n args: process.argv.slice(2),\n allowPositionals: true,\n strict: true,\n options: {\n root: { type: \"string\", default: process.cwd() },\n config: { type: \"string\" },\n index: { type: \"string\" },\n provider: { type: \"string\" },\n model: { type: \"string\" },\n dimensions: { type: \"string\" },\n target: { type: \"string\" },\n \"target-root\": { type: \"string\" },\n \"target-index\": { type: \"string\" },\n \"target-config\": { type: \"string\" },\n \"changed-since\": { type: \"string\" },\n uncommitted: { type: \"boolean\", default: false },\n \"source-path\": { type: \"string\" },\n \"min-lines\": { type: \"string\" },\n regex: { type: \"string\" },\n limit: { type: \"string\" },\n neighbors: { type: \"string\" },\n threshold: { type: \"string\" },\n format: { type: \"string\" },\n \"include-source\": { type: \"boolean\", default: false },\n \"include-symmetric-duplicates\": { type: \"boolean\", default: false },\n \"cross-file-only\": { type: \"boolean\", default: false },\n \"rebuild-on-divergence\": { type: \"boolean\", default: false },\n \"force-reindex\": { type: \"boolean\", default: false },\n \"no-reindex\": { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n });\n } catch (error) {\n process.stderr.write(`slopdex: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(2);\n }\n})();\n\nconst [command, ...positionals] = parsed.positionals;\n\nif (parsed.values.help || !command) {\n printHelp();\n process.exit(parsed.values.help ? 0 : 1);\n}\n\nvoid main().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`slopdex: ${message}\\n`);\n process.exitCode = error instanceof CodeIndexError ? 2 : 1;\n});\n\nasync function main(): Promise<void> {\n validateInvocation();\n const rootDir = path.resolve(parsed.values.root!);\n const config = loadConfig(rootDir, parsed.values.config);\n const provider = createProvider(config);\n const indexOptions: CodeIndexOptions = {\n rootDir,\n provider,\n onWarning: (message) => process.stderr.write(`slopdex: warning: ${message}\\n`),\n ...(parsed.values.index || config.indexPath ? { indexPath: parsed.values.index ?? config.indexPath } : {}),\n ...(config.include ? { include: config.include } : {}),\n ...(config.exclude ? { exclude: config.exclude } : {}),\n ...(config.maxFileSize ? { maxFileSize: config.maxFileSize } : {}),\n ...(config.embeddingBatchSize ? { embeddingBatchSize: config.embeddingBatchSize } : {}),\n };\n const updateTarget = command === \"update-git\" ? parsed.values.target ?? \"HEAD\" : \"HEAD\";\n const updateStats = await ensureIndexUpdated(\n indexOptions,\n \"index\",\n updateTarget,\n parsed.values[\"rebuild-on-divergence\"],\n parsed.values[\"force-reindex\"],\n parsed.values[\"no-reindex\"],\n );\n const index = new CodeIndex(indexOptions);\n try {\n switch (command) {\n case \"status\":\n printJson(index.status());\n break;\n case \"update-files\":\n if (positionals.length === 0) throw new CodeIndexError(\"update-files requires at least one path.\");\n printJson(await index.updateFiles({ upsert: positionals }));\n break;\n case \"delete-files\":\n if (positionals.length === 0) throw new CodeIndexError(\"delete-files requires at least one path.\");\n printJson(await index.updateFiles({ delete: positionals }));\n break;\n case \"update-git\": {\n printJson(updateStats);\n break;\n }\n case \"search\": {\n const query = positionals.join(\" \").trim();\n if (!query) throw new CodeIndexError(\"search requires a query.\");\n const threshold = similarityThreshold();\n const results = await index.similaritySearch({\n query,\n limit: numberOption(parsed.values.limit, 10, \"limit\"),\n minSimilarity: threshold.min,\n ...(threshold.max !== undefined ? { maxSimilarity: threshold.max } : {}),\n });\n const format = outputFormat(\"json\");\n if (format === \"clusters\") throw new CodeIndexError(\"clusters format is only available for cross-search.\");\n if (format === \"summary\") process.stdout.write(`${formatSimilaritySummary(results)}\\n`);\n else printJson(results.map(presentMatch));\n break;\n }\n case \"cross-search\":\n await runCrossSearch(index, indexOptions, provider);\n break;\n case \"cohesion\": {\n const threshold = cohesionThreshold();\n const report = await analyzeCohesion({\n source: index,\n sourceFilter: crossSearchSourceFilter(),\n neighbors: positiveIntegerOption(parsed.values.neighbors, 20, \"neighbors\"),\n limit: positiveIntegerOption(parsed.values.limit, 50, \"limit\"),\n minSimilarity: threshold.min,\n ...(threshold.max !== undefined ? { maxSimilarity: threshold.max } : {}),\n minLines: minimumLines(),\n ...(parsed.values.regex !== undefined ? { nameRegex: parsed.values.regex } : {}),\n });\n const format = outputFormat(\"json\");\n if (format === \"clusters\") throw new CodeIndexError(\"clusters format is only available for cross-search.\");\n if (format === \"summary\") process.stdout.write(`${formatCohesionSummary(report)}\\n`);\n else printJson(presentCohesionReport(report, parsed.values[\"include-source\"]));\n break;\n }\n default:\n throw new CodeIndexError(`Unknown command: ${command}`);\n }\n } finally {\n index.close();\n }\n}\n\nasync function runCrossSearch(\n source: CodeIndex,\n sourceOptions: CodeIndexOptions,\n provider: EmbeddingProvider,\n): Promise<void> {\n const targetRoot = parsed.values[\"target-root\"];\n const targetPath = parsed.values[\"target-index\"];\n if ((targetRoot && !targetPath) || (!targetRoot && targetPath)) {\n throw new CodeIndexError(\"Cross-index search requires both --target-root and --target-index.\");\n }\n const targetRootDir = targetRoot ? path.resolve(targetRoot) : undefined;\n const resolvedTargetPath = targetPath ? path.resolve(targetPath) : undefined;\n const usesSourceAsTarget = targetRootDir === source.rootDir && resolvedTargetPath === source.indexPath;\n const targetConfig = targetRootDir && !usesSourceAsTarget\n ? loadConfig(targetRootDir, parsed.values[\"target-config\"])\n : undefined;\n const targetOptions: CodeIndexOptions | undefined = targetRootDir && resolvedTargetPath && !usesSourceAsTarget ? {\n rootDir: targetRootDir,\n indexPath: resolvedTargetPath,\n provider,\n ...(sourceOptions.onWarning ? { onWarning: sourceOptions.onWarning } : {}),\n ...(targetConfig?.include ? { include: targetConfig.include } : {}),\n ...(targetConfig?.exclude ? { exclude: targetConfig.exclude } : {}),\n ...(targetConfig?.maxFileSize ? { maxFileSize: targetConfig.maxFileSize } : {}),\n ...(targetConfig?.embeddingBatchSize ? { embeddingBatchSize: targetConfig.embeddingBatchSize } : {}),\n } : undefined;\n if (targetOptions) {\n await ensureIndexUpdated(\n targetOptions,\n \"target index\",\n \"HEAD\",\n parsed.values[\"rebuild-on-divergence\"],\n parsed.values[\"force-reindex\"],\n parsed.values[\"no-reindex\"],\n );\n }\n const target = targetOptions ? new CodeIndex({ ...targetOptions, readOnly: true }) : undefined;\n const format = outputFormat(\"clusters\");\n const threshold = similarityThreshold();\n const searchOptions: CrossSearchOptions = {\n source,\n ...(target ? { target } : {}),\n sourceFilter: crossSearchSourceFilter(),\n limitPerFunction: numberOption(parsed.values.limit, 5, \"limit\"),\n minSimilarity: threshold.min,\n ...(threshold.max !== undefined ? { maxSimilarity: threshold.max } : {}),\n includeSymmetricDuplicates: parsed.values[\"include-symmetric-duplicates\"],\n crossFileOnly: parsed.values[\"cross-file-only\"],\n minLines: minimumLines(),\n ...(parsed.values.regex !== undefined ? { nameRegex: parsed.values.regex } : {}),\n };\n try {\n if (format === \"clusters\") {\n const results: CrossSearchResult[] = [];\n for await (const result of crossSearch(searchOptions)) results.push(result);\n process.stdout.write(`${formatSimilarityClusters(results, !target)}\\n`);\n return;\n }\n for await (const result of crossSearch(searchOptions)) {\n if (format === \"summary\") {\n process.stdout.write(`${formatSimilaritySummary(result.matches, result.source)}\\n`);\n } else {\n process.stdout.write(`${JSON.stringify({\n source: presentFunction(result.source),\n matches: result.matches.map(presentMatch),\n })}\\n`);\n }\n }\n } finally {\n target?.close();\n }\n}\n\nasync function ensureIndexUpdated(\n options: CodeIndexOptions,\n label: string,\n target: string,\n rebuildOnDivergence: boolean,\n forceRebuild: boolean,\n noReindex: boolean,\n): Promise<UpdateStats> {\n const initialized = await initializeMissingIndex(options, label, target, noReindex);\n if (initialized) return initialized;\n try {\n const index = new CodeIndex(options);\n try {\n return await refreshIndex(index, label, target, rebuildOnDivergence, noReindex);\n } finally {\n index.close();\n }\n } catch (error) {\n if (!forceRebuild || !(error instanceof IncompatibleIndexError)) throw error;\n process.stderr.write(\n `slopdex: warning: ${label} is incompatible (${error.message}); rebuilding automatically because --force-reindex was specified.\\n`,\n );\n const indexPath = resolveIndexPath(options);\n removeIndexArtifacts(indexPath);\n return initializeIndex(options, indexPath, label, target, noReindex);\n }\n}\n\nasync function initializeMissingIndex(\n options: CodeIndexOptions,\n label: string,\n target: string,\n noReindex: boolean,\n): Promise<UpdateStats | null> {\n const indexPath = resolveIndexPath(options);\n if (existsSync(indexPath)) return null;\n\n process.stderr.write(\n `slopdex: ${label} not found at ${indexPath}; initializing automatically from ${target}${noReindex ? \"\" : \" and the working tree\"}.\\n`,\n );\n return initializeIndex(options, indexPath, label, target, noReindex);\n}\n\nasync function initializeIndex(\n options: CodeIndexOptions,\n indexPath: string,\n label: string,\n target: string,\n noReindex: boolean,\n): Promise<UpdateStats> {\n const index = new CodeIndex({ ...options, indexPath });\n let initialized = false;\n try {\n const stats = await refreshIndex(index, label, target, false, noReindex);\n initialized = true;\n return stats;\n } finally {\n index.close();\n if (!initialized) {\n removeIndexArtifacts(indexPath);\n }\n }\n}\n\nasync function refreshIndex(\n index: CodeIndex,\n label: string,\n target: string,\n rebuildOnDivergence: boolean,\n noReindex: boolean,\n): Promise<UpdateStats> {\n try {\n return await index.updateFromGit({ target, rebuildOnDivergence, includeWorkingTree: !noReindex });\n } catch (error) {\n if (!(error instanceof GitUnavailableError)) throw error;\n const status = index.status();\n if (noReindex && status.fileCount > 0) {\n process.stderr.write(\n `slopdex: warning: no Git repository is available for ${label}; full working-tree re-index skipped because --no-reindex was specified.\\n`,\n );\n return {\n filesUpdated: 0,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint: status.gitCheckpoint,\n };\n }\n process.stderr.write(\n `slopdex: warning: no Git repository is available for ${label}; re-indexing all source files from the working tree.\\n`,\n );\n return await index.updateFromWorkingTree();\n }\n}\n\nfunction resolveIndexPath(options: CodeIndexOptions): string {\n return path.resolve(options.indexPath ?? path.join(path.resolve(options.rootDir), \".slopdex\", \"index.sqlite\"));\n}\n\nfunction removeIndexArtifacts(indexPath: string): void {\n for (const suffix of [\"\", \"-shm\", \"-wal\", \"-journal\"]) rmSync(`${indexPath}${suffix}`, { force: true });\n}\n\nfunction loadConfig(rootDir: string, configuredPath?: string): FileConfig {\n const configPath = path.resolve(configuredPath ?? path.join(rootDir, \".slopdex\", \"config.json\"));\n if (!existsSync(configPath)) return commandLineConfig({});\n const value = JSON.parse(readFileSync(configPath, \"utf8\")) as FileConfig;\n return commandLineConfig(value);\n}\n\nfunction commandLineConfig(config: FileConfig): FileConfig {\n const dimensions = parsed.values.dimensions\n ? numberOption(parsed.values.dimensions, 0, \"dimensions\")\n : config.dimensions;\n const providerValue = parsed.values.provider ?? config.provider;\n if (providerValue !== undefined && providerValue !== \"openai\" && providerValue !== \"jina\") {\n throw new CodeIndexError(`Unsupported provider: ${providerValue}`);\n }\n const provider: FileConfig[\"provider\"] = providerValue === \"openai\" || providerValue === \"jina\"\n ? providerValue\n : undefined;\n return {\n ...config,\n ...(provider ? { provider } : {}),\n ...(parsed.values.model ? { model: parsed.values.model } : {}),\n ...(dimensions ? { dimensions } : {}),\n };\n}\n\nfunction createProvider(config: FileConfig): EmbeddingProvider {\n if ((config.provider ?? \"openai\") === \"jina\") {\n return new JinaEmbeddingProvider({\n ...(config.model ? { model: config.model } : {}),\n ...(config.dimensions ? { dimensions: config.dimensions } : {}),\n });\n }\n return new OpenAIEmbeddingProvider({\n ...(config.model ? { model: config.model } : {}),\n ...(config.dimensions ? { dimensions: config.dimensions } : {}),\n });\n}\n\nfunction numberOption(value: string | undefined, defaultValue: number, name: string): number {\n if (value === undefined) return defaultValue;\n const parsedValue = Number(value);\n if (!Number.isFinite(parsedValue)) throw new CodeIndexError(`${name} must be a number.`);\n return parsedValue;\n}\n\nfunction validateInvocation(): void {\n switch (command) {\n case \"status\":\n case \"update-git\":\n return;\n case \"update-files\":\n if (positionals.length === 0) throw new CodeIndexError(\"update-files requires at least one path.\");\n return;\n case \"delete-files\":\n if (positionals.length === 0) throw new CodeIndexError(\"delete-files requires at least one path.\");\n return;\n case \"search\": {\n if (!positionals.join(\" \").trim()) throw new CodeIndexError(\"search requires a query.\");\n validateLimit(10);\n similarityThreshold();\n if (outputFormat(\"json\") === \"clusters\") throw new CodeIndexError(\"clusters format is only available for cross-search.\");\n return;\n }\n case \"cross-search\":\n if (Boolean(parsed.values[\"target-root\"]) !== Boolean(parsed.values[\"target-index\"])) {\n throw new CodeIndexError(\"Cross-index search requires both --target-root and --target-index.\");\n }\n if (parsed.values[\"target-config\"] && !parsed.values[\"target-root\"]) {\n throw new CodeIndexError(\"--target-config requires --target-root and --target-index.\");\n }\n validateLimit(5);\n similarityThreshold();\n outputFormat(\"clusters\");\n minimumLines();\n functionNameRegex();\n crossSearchSourceFilter();\n return;\n case \"cohesion\":\n positiveIntegerOption(parsed.values.limit, 50, \"limit\");\n positiveIntegerOption(parsed.values.neighbors, 20, \"neighbors\");\n cohesionThreshold();\n if (outputFormat(\"json\") === \"clusters\") throw new CodeIndexError(\"clusters format is only available for cross-search.\");\n minimumLines();\n functionNameRegex();\n crossSearchSourceFilter();\n return;\n default:\n throw new CodeIndexError(`Unknown command: ${command}`);\n }\n}\n\nfunction validateLimit(defaultValue: number): void {\n positiveIntegerOption(parsed.values.limit, defaultValue, \"limit\");\n}\n\nfunction positiveIntegerOption(value: string | undefined, defaultValue: number, name: string): number {\n const parsedValue = numberOption(value, defaultValue, name);\n if (!Number.isInteger(parsedValue) || parsedValue < 1) throw new CodeIndexError(`${name} must be a positive integer.`);\n return parsedValue;\n}\n\nfunction similarityThreshold(defaultMin = -1): { min: number; max?: number } {\n const threshold = parsed.values.threshold;\n if (threshold === undefined) return { min: defaultMin };\n\n const number = \"[+-]?(?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:e[+-]?\\\\d+)?\";\n const range = new RegExp(`^\\\\s*(${number})\\\\s*-\\\\s*(${number})\\\\s*$`, \"i\").exec(threshold);\n if (!range) return { min: numberOption(threshold, -1, \"threshold\") };\n const min = Number(range[1]);\n const max = Number(range[2]);\n if (!Number.isFinite(min) || !Number.isFinite(max)) throw new CodeIndexError(\"threshold range bounds must be numbers.\");\n if (min >= max) throw new CodeIndexError(\"threshold range minimum must be less than its maximum.\");\n return { min, max };\n}\n\nfunction cohesionThreshold(): { min: number; max?: number } {\n const threshold = similarityThreshold(0.8);\n if (threshold.min < -1 || threshold.min >= 1) {\n throw new CodeIndexError(\"cohesion threshold must be at least -1 and less than 1.\");\n }\n return threshold;\n}\n\nfunction outputFormat(defaultValue: \"json\" | \"clusters\"): \"json\" | \"summary\" | \"clusters\" {\n const value = parsed.values.format ?? defaultValue;\n if (value !== \"json\" && value !== \"summary\" && value !== \"clusters\") {\n throw new CodeIndexError(\"format must be json, summary, or clusters.\");\n }\n return value;\n}\n\nfunction minimumLines(): number {\n const value = numberOption(parsed.values[\"min-lines\"], 2, \"min-lines\");\n if (!Number.isInteger(value) || value < 1) throw new CodeIndexError(\"min-lines must be a positive integer.\");\n return value;\n}\n\nfunction functionNameRegex(): RegExp | undefined {\n const pattern = parsed.values.regex;\n if (pattern === undefined) return undefined;\n try {\n return new RegExp(pattern);\n } catch (error) {\n throw new CodeIndexError(`Invalid --regex value: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nfunction crossSearchSourceFilter(): CrossSearchSourceFilter {\n const changedSince = parsed.values[\"changed-since\"];\n const uncommitted = parsed.values.uncommitted;\n if (changedSince && uncommitted) throw new CodeIndexError(\"Use either --changed-since or --uncommitted, not both.\");\n const pathOption = parsed.values[\"source-path\"] ? { path: parsed.values[\"source-path\"] } : {};\n if (changedSince) return { type: \"changed-since\", commit: changedSince, ...pathOption };\n if (uncommitted) return { type: \"uncommitted\", ...pathOption };\n return { type: \"all\", ...pathOption };\n}\n\nfunction presentFunction(value: IndexedFunction) {\n const { embeddingInput: _embeddingInput, embeddingId: _embeddingId, ...result } = value;\n return result;\n}\n\nfunction presentMatch(value: SimilarityResult) {\n return { similarity: value.similarity, function: presentFunction(value.function) };\n}\n\nfunction presentCohesionReport(report: CohesionReport, includeSource: boolean): CohesionJsonReport {\n const presentCohesionFunction = (value: IndexedFunction): CohesionFunctionReference => ({\n path: value.path,\n qualifiedName: value.qualifiedName,\n kind: value.kind,\n signature: value.signature,\n startLine: value.startLine,\n startColumn: value.startColumn,\n endLine: value.endLine,\n endColumn: value.endColumn,\n lineCount: value.lineCount,\n ...(includeSource ? { source: value.source } : {}),\n });\n return {\n ...report,\n pairs: report.pairs.map((pair) => ({\n ...pair,\n left: presentCohesionFunction(pair.left),\n right: presentCohesionFunction(pair.right),\n })),\n files: report.files.map((file) => ({\n ...file,\n ...(file.strongestExternalMatch ? {\n strongestExternalMatch: {\n ...file.strongestExternalMatch,\n function: presentCohesionFunction(file.strongestExternalMatch.function),\n },\n } : {}),\n })),\n groups: report.groups.map((group) => ({\n ...group,\n members: group.members.map(presentCohesionFunction),\n })),\n };\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction printHelp(): void {\n process.stdout.write(`Usage: slopdex <command> [arguments] [options]\n\nCommands:\n status Show index metadata\n update-files <path...> Index specific working-tree files\n delete-files <path...> Remove specific files from the index\n update-git Index a Git snapshot plus working-tree changes\n search <query> Search functions by semantic similarity\n cross-search Find nearest functions for each source function\n cohesion Rank related functions separated across the repository\n\nAnalysis Examples:\n Duplicate Analysis:\n slopdex cross-search --cross-file-only --min-lines 4 --threshold 0.9 --limit 5\n\n Cluster 1 (3 functions, similarity 0.9124-0.9568)\n src/auth/session.ts:18:1 :: validateSession\n src/http/middleware.ts:42:1 :: authenticate\n src/users/user-service.ts:27:3 :: UserService.authenticate\n\n This found three substantial authentication functions in separate files with very\n high similarity. Review them for repeated validation or session logic that could be shared.\n Middleware and service locations may be intentional architectural layers, so this is\n evidence to inspect rather than proof they should merge. Connected components may use\n transitive links, so every function need not directly match every other function.\n\n Cohesion Analysis:\n slopdex cohesion --threshold 0.8 --neighbors 20 --limit 50 --format summary\n\n Cohesion: 184 functions analyzed, 37 semantic edges\n same file 35.1% same folder 29.7% remote 35.2% mean distance 1.84\n\n 1. gap 0.6053 similarity 0.9400 distance 4 reciprocal\n src/auth/session.ts:18:1 :: validateSession\n packages/http/middleware.ts:42:1 :: authenticate\n\n There is no universal pass/fail cutoff, but this warrants review: 35.2% of weighted\n semantic affinity crosses folders, mean distance 1.84 exceeds the same-folder distance\n of one, and the top pair is 0.94 similar but four units apart. A more cohesive result\n would concentrate affinity in the same file or folder and have few high-gap remote\n pairs. Compare modules or history rather than treating one percentage as a fixed\n threshold, and allow for intentionally separate architectural responsibilities.\n\nReading Analysis Output:\n Compare values only with the same embedding profile and similar threshold, neighbor,\n source-filter, and minimum-line settings.\n\n Duplicate cluster line:\n Cluster N Display order by function count, then name; not severity\n functions Unique connected callables; higher may mean a larger duplicate family\n similarity range Raw cosine edge range; higher means stronger model-assessed resemblance\n A high minimum means all observed links are strong; a wide range may\n indicate that a weaker transitive edge joined tighter matches\n callable location path:line:column :: qualifiedFunctionName; inspect architectural roles\n\n Cohesion headline:\n functions analyzed Filtered source coverage; higher or lower does not mean better or worse\n semantic edges Unique qualifying neighbor pairs before --limit; not a quality score\n More neighbors or a lower threshold generally increases this count\n\n Cohesion distribution:\n same file Higher generally means related implementation is co-located\n same folder Higher means related modules remain locally grouped\n remote Higher means more affinity crosses folders and weaker physical cohesion\n mean distance Lower is generally more cohesive (same file 0, same folder 1)\n\n Ranked cohesion finding:\n rank Lower number means higher review priority\n gap 0-to-1 combined signal; higher means strongly related and farther apart\n similarity Higher means greater resemblance; values are model-specific\n distance Higher means more file and directory-tree separation\n reciprocal Mutual top-neighbor relationship; strengthens confidence when present\n\n JSON diagnostics:\n semanticWeight Higher means similarity is farther above --threshold\n separationWeight Higher means greater path distance, saturating near one\n sourceTestPair True flags a possibly intentional source/test relationship\n externalAffinityRatio\n Higher means more of a file's related affinity lies outside its folder\n\nOptions:\n --root <path> Repository root (default: current directory)\n --config <path> Config file (default: .slopdex/config.json)\n --index <path> SQLite index path\n --provider <openai|jina> Embedding provider\n --model <name> Embedding model\n --dimensions <number> Embedding dimensions\n --target <ref> Target ref for update-git (default: HEAD)\n --rebuild-on-divergence Rebuild after a rebase or branch change\n --force-reindex Rebuild an incompatible existing index\n --no-reindex Skip worktree overlays or reuse a non-Git index\n --limit <number> Search result limit\n --neighbors <number> Semantic neighbors per function for cohesion (default: 20)\n --threshold <number|range> Show similarities at/above a value or within a range\n --format <json|summary|clusters> Output format (search: json; cross-search: clusters)\n --include-source Include function source in cohesion JSON\n --include-symmetric-duplicates Show both directions of same-index matches\n --cross-file-only Exclude matches from the source file\n --min-lines <number> Minimum callable length for cross-search (default: 2)\n --regex <regex> Restrict cross-search to matching qualified names\n --changed-since <commit> Search added, modified, or moved functions\n --uncommitted Search functions from uncommitted files\n --source-path <path> Restrict cross-search sources to a file or directory\n --target-root <path> Root of a second indexed codebase\n --target-index <path> SQLite path of a second index\n --target-config <path> Config file for a second indexed codebase\n\nOther Examples:\n Show metadata for the current index:\n slopdex status\n\n Index specific working-tree files:\n slopdex update-files src/service.ts src/model.ts\n\n Remove deleted files from the index:\n slopdex delete-files src/removed.ts\n\n Index HEAD and overlay uncommitted working-tree changes:\n slopdex update-git --target HEAD\n\n Find functions matching a semantic query:\n slopdex search \"validate an authenticated session\" --limit 10\n\n Review functions under a path against the whole codebase:\n slopdex cross-search --source-path src/services --format summary\n`);\n}\n","import { lstat, readFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { CodeIndexError, GitDivergenceError } from \"./errors.js\";\nimport { GitRepository, type GitChange, type GitTreeEntry } from \"./git/repository.js\";\nimport { parseCallables } from \"./parser/callable-parser.js\";\nimport { SourcePolicy } from \"./source-policy.js\";\nimport { IndexDatabase, type PreparedCallable, type PreparedFile } from \"./storage/database.js\";\nimport type {\n CodeIndexOptions,\n CrossSearchSourceFilter,\n EmbeddingProfile,\n IndexStatus,\n IndexedFunction,\n SimilarityResult,\n SimilaritySearchOptions,\n UpdateFilesOptions,\n UpdateFromGitOptions,\n UpdateFromWorkingTreeOptions,\n UpdateStats,\n} from \"./types.js\";\nimport { assertPositiveInteger, chunk, normalizeEmbeddingVector, normalizeRelativePath, sha256, throwIfAborted } from \"./utils.js\";\n\nconst DEFAULT_MAX_FILE_SIZE = 1024 * 1024;\nconst DEFAULT_BATCH_SIZE = 32;\n\nexport class CodeIndex {\n public readonly rootDir: string;\n public readonly indexPath: string;\n public readonly provider;\n readonly #database: IndexDatabase;\n readonly #policy: SourcePolicy;\n readonly #maxFileSize: number;\n readonly #embeddingBatchSize: number;\n readonly #git: GitRepository;\n readonly #onWarning: (message: string) => void;\n\n public constructor(options: CodeIndexOptions) {\n this.rootDir = path.resolve(options.rootDir);\n this.indexPath = path.resolve(options.indexPath ?? path.join(this.rootDir, \".slopdex\", \"index.sqlite\"));\n this.provider = options.provider;\n const profile = normalizeProfile(options.provider.profile);\n assertPositiveInteger(profile.dimensions, \"embedding dimensions\");\n this.#database = new IndexDatabase(this.indexPath, this.rootDir, profile, options.readOnly ?? false);\n this.#policy = new SourcePolicy(options.include, options.exclude);\n this.#maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n this.#embeddingBatchSize = options.embeddingBatchSize ?? DEFAULT_BATCH_SIZE;\n this.#onWarning = options.onWarning ?? console.warn;\n assertPositiveInteger(this.#maxFileSize, \"maxFileSize\");\n assertPositiveInteger(this.#embeddingBatchSize, \"embeddingBatchSize\");\n this.#git = new GitRepository(this.rootDir);\n }\n\n public close(): void {\n this.#database.close();\n }\n\n public status(): IndexStatus {\n return this.#database.status();\n }\n\n public allFunctions(): IndexedFunction[] {\n return this.#database.allFunctions();\n }\n\n public async updateFiles(options: UpdateFilesOptions): Promise<UpdateStats> {\n const normalizedRenames = (options.renames ?? []).map(({ from, to }) => ({\n from: normalizeRelativePath(this.rootDir, from),\n to: normalizeRelativePath(this.rootDir, to),\n }));\n validateRenames(normalizedRenames);\n const upsertPaths = [...new Set((options.upsert ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];\n const deletePaths = [...new Set((options.delete ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];\n const renameMap = new Map(\n normalizedRenames.map(({ from, to }) => [to, from]),\n );\n for (const target of renameMap.keys()) {\n if (!upsertPaths.includes(target)) upsertPaths.push(target);\n }\n\n const prepared: PreparedFile[] = [];\n for (const relativePath of upsertPaths) {\n throwIfAborted(options.signal);\n if (!this.#policy.includes(relativePath)) throw new CodeIndexError(`Unsupported or excluded source file: ${relativePath}`);\n const absolutePath = path.join(this.rootDir, relativePath);\n const info = await lstat(absolutePath);\n if (info.isSymbolicLink()) throw new CodeIndexError(`Symbolic links are not supported: ${relativePath}`);\n if (!info.isFile()) throw new CodeIndexError(`Not a regular file: ${relativePath}`);\n if (info.size > this.#maxFileSize) throw new CodeIndexError(`File exceeds maxFileSize: ${relativePath}`);\n const content = await readFile(absolutePath);\n const renameSource = renameMap.get(relativePath);\n const originalPath = renameSource ? this.#database.previousPath(renameSource) ?? renameSource : undefined;\n prepared.push(this.#prepareFile(relativePath, content, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(originalPath ? { previousPath: originalPath } : {}),\n ...(renameSource ? { replacePath: renameSource } : {}),\n }));\n }\n await this.#attachEmbeddings(prepared, options.signal);\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletePaths, ...renameMap.values()],\n });\n }\n\n public async updateFromWorkingTree(options: UpdateFromWorkingTreeOptions = {}): Promise<UpdateStats> {\n throwIfAborted(options.signal);\n const generation = this.#database.getGeneration();\n const indexedFiles = this.#database.getFileStates();\n const sourcePaths = await this.#workingTreeSourcePaths(options.signal);\n const prepared: PreparedFile[] = [];\n const skippedPaths = new Set<string>();\n for (const relativePath of sourcePaths) {\n throwIfAborted(options.signal);\n const absolutePath = path.join(this.rootDir, relativePath);\n const info = await lstat(absolutePath);\n if (!info.isFile() || info.isSymbolicLink() || info.size > this.#maxFileSize) {\n skippedPaths.add(relativePath);\n continue;\n }\n const content = await readFile(absolutePath);\n prepared.push(this.#prepareFile(relativePath, content, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n }));\n }\n await this.#attachEmbeddings(prepared, options.signal);\n\n const pathsAgain = await this.#workingTreeSourcePaths(options.signal);\n if (JSON.stringify(pathsAgain) !== JSON.stringify(sourcePaths)) {\n throw new CodeIndexError(\"Working-tree files changed while indexing; retry the update.\");\n }\n for (const file of prepared) {\n try {\n const info = await lstat(path.join(this.rootDir, file.path));\n const content = await readFile(path.join(this.rootDir, file.path));\n if (!info.isFile() || info.isSymbolicLink() || info.size > this.#maxFileSize || sha256(content.toString(\"utf8\")) !== file.contentHash) {\n throw new CodeIndexError(`Working-tree file changed while indexing: ${file.path}`);\n }\n } catch (error) {\n if (error instanceof CodeIndexError) throw error;\n throw new CodeIndexError(`Working-tree file changed while indexing: ${file.path}`, { cause: error });\n }\n }\n for (const relativePath of skippedPaths) {\n const info = await lstat(path.join(this.rootDir, relativePath));\n if (info.isFile() && !info.isSymbolicLink() && info.size <= this.#maxFileSize) {\n throw new CodeIndexError(`Working-tree file changed while indexing: ${relativePath}`);\n }\n }\n\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: indexedFiles.map((file) => file.path),\n checkpoint: null,\n expectedGeneration: generation,\n });\n }\n\n public async updateFromGit(options: UpdateFromGitOptions = {}): Promise<UpdateStats> {\n throwIfAborted(options.signal);\n await this.#git.assertRepository();\n const relativeIndexPath = path.relative(this.rootDir, this.indexPath).replaceAll(path.sep, \"/\");\n const indexArtifacts = relativeIndexPath && !relativeIndexPath.startsWith(\"../\")\n ? [relativeIndexPath, `${relativeIndexPath}-shm`, `${relativeIndexPath}-wal`, `${relativeIndexPath}-journal`]\n : [];\n const target = await this.#git.resolveCommit(options.target ?? \"HEAD\");\n const head = await this.#git.resolveCommit(\"HEAD\");\n const overlayWorkingTree = target === head && options.includeWorkingTree !== false;\n const checkpoint = this.#database.getCheckpoint();\n const generation = this.#database.getGeneration();\n let reconcileAll = checkpoint === null;\n if (checkpoint && !(await this.#git.isAncestor(checkpoint, target))) {\n if (!options.rebuildOnDivergence) throw new GitDivergenceError(checkpoint, target);\n reconcileAll = true;\n }\n\n const tree = await this.#git.listTree(target);\n const indexedFiles = this.#database.getFileStates();\n const indexedByPath = new Map(indexedFiles.map((file) => [file.path, file]));\n const workingFiles = indexedFiles.filter((file) => file.sourceMode === \"working-tree\");\n const workingChanges = overlayWorkingTree ? await this.#git.workTreeChanges(target, indexArtifacts) : [];\n const visibleWorkingPaths = new Set(\n workingChanges.filter((change) => change.status !== \"D\").map((change) => change.path),\n );\n const changes = reconcileAll || !checkpoint ? [] : await this.#git.diff(checkpoint, target);\n const upserts = new Map<string, { entry: GitTreeEntry; previousPath?: string }>();\n const deletes = new Set<string>();\n const eligibleEntries = [...tree.values()]\n .filter((entry) => this.#policy.includes(entry.path) && entry.size <= this.#maxFileSize);\n const eligibleTargetPaths = new Set(eligibleEntries.map((entry) => entry.path));\n if (reconcileAll) {\n const renameCandidates = indexedFiles.filter((file) => (\n file.sourceMode === \"git\" && file.blobOid && !eligibleTargetPaths.has(file.path)\n ));\n const claimedRenameSources = new Set<string>();\n for (const entry of eligibleEntries) {\n const indexed = indexedByPath.get(entry.path);\n if (indexed?.sourceMode === \"git\" && indexed.blobOid === entry.oid) continue;\n const matches = renameCandidates.filter((candidate) => (\n candidate.blobOid === entry.oid && !claimedRenameSources.has(candidate.path)\n ));\n const previousPath = matches.length === 1 ? matches[0]!.path : undefined;\n if (previousPath) claimedRenameSources.add(previousPath);\n upserts.set(entry.path, { entry, ...(previousPath ? { previousPath } : {}) });\n }\n for (const indexed of indexedFiles) {\n if (!eligibleTargetPaths.has(indexed.path)) deletes.add(indexed.path);\n }\n } else {\n this.#classifyGitChanges(changes, tree, upserts, deletes);\n const indexedPaths = new Set(indexedByPath.keys());\n for (const targetPath of eligibleTargetPaths) {\n const indexed = indexedByPath.get(targetPath);\n const entry = tree.get(targetPath)!;\n if (\n (!indexed || (indexed.sourceMode === \"git\" && indexed.blobOid !== entry.oid))\n && !upserts.has(targetPath)\n ) {\n upserts.set(targetPath, { entry });\n }\n }\n for (const indexedPath of indexedPaths) {\n if (!eligibleTargetPaths.has(indexedPath)) deletes.add(indexedPath);\n }\n }\n for (const dirtyFile of workingFiles) {\n const entry = tree.get(dirtyFile.path);\n const previousEntry = dirtyFile.previousPath ? tree.get(dirtyFile.previousPath) : undefined;\n if (\n previousEntry\n && this.#policy.includes(previousEntry.path)\n && previousEntry.size <= this.#maxFileSize\n && (entry !== undefined || !visibleWorkingPaths.has(dirtyFile.path))\n ) {\n const currentPlan = entry ? upserts.get(dirtyFile.path) : undefined;\n upserts.delete(dirtyFile.path);\n upserts.delete(previousEntry.path);\n upserts.set(previousEntry.path, { entry: previousEntry, previousPath: dirtyFile.path });\n if (entry && this.#policy.includes(entry.path) && entry.size <= this.#maxFileSize) {\n upserts.set(dirtyFile.path, currentPlan ?? { entry });\n }\n continue;\n }\n if (entry && this.#policy.includes(dirtyFile.path) && entry.size <= this.#maxFileSize) {\n const planned = upserts.get(dirtyFile.path);\n if (planned?.previousPath && !indexedByPath.has(planned.previousPath)) {\n upserts.set(dirtyFile.path, { entry, previousPath: dirtyFile.path });\n } else if (!planned) {\n upserts.set(dirtyFile.path, { entry });\n }\n continue;\n }\n if (previousEntry && this.#policy.includes(previousEntry.path) && previousEntry.size <= this.#maxFileSize) {\n upserts.set(previousEntry.path, { entry: previousEntry, previousPath: dirtyFile.path });\n } else {\n deletes.add(dirtyFile.path);\n }\n }\n for (const [filePath, { entry, previousPath }] of upserts) {\n const indexed = indexedByPath.get(filePath);\n if (!previousPath && indexed?.sourceMode === \"git\" && indexed.blobOid === entry.oid) upserts.delete(filePath);\n }\n\n const workingPrepared: PreparedFile[] = [];\n const workingDeletes = new Set<string>();\n const skippedWorkingPaths = new Set<string>();\n for (const change of workingChanges) {\n throwIfAborted(options.signal);\n if (change.status === \"D\") {\n upserts.delete(change.path);\n workingDeletes.add(change.path);\n continue;\n }\n\n let previousPath: string | undefined;\n let replacePath: string | undefined;\n if (change.status === \"R\") {\n const plannedBase = upserts.get(change.oldPath);\n const existingAtTarget = indexedByPath.get(change.oldPath);\n const existingAtFinal = indexedByPath.get(change.path);\n const continuingRename = existingAtFinal?.sourceMode === \"working-tree\"\n && existingAtFinal.previousPath === change.oldPath;\n replacePath = continuingRename\n ? change.path\n : existingAtTarget\n ? change.oldPath\n : existingAtFinal\n ? change.path\n : plannedBase?.previousPath && indexedByPath.has(plannedBase.previousPath)\n ? plannedBase.previousPath\n : undefined;\n previousPath = existingAtFinal?.previousPath ?? change.oldPath;\n upserts.delete(change.oldPath);\n upserts.delete(change.path);\n if (replacePath) deletes.delete(replacePath);\n workingDeletes.add(change.oldPath);\n } else {\n const planned = upserts.get(change.path);\n const existing = indexedByPath.get(change.path);\n replacePath = existing\n ? change.path\n : planned?.previousPath && indexedByPath.has(planned.previousPath)\n ? planned.previousPath\n : undefined;\n previousPath = existing?.previousPath ?? planned?.previousPath;\n upserts.delete(change.path);\n if (replacePath) deletes.delete(replacePath);\n }\n const relativePath = change.path;\n if (!this.#policy.includes(relativePath)) {\n if (replacePath) workingDeletes.add(replacePath);\n workingDeletes.add(relativePath);\n continue;\n }\n const absolutePath = path.join(this.rootDir, relativePath);\n const info = await lstat(absolutePath);\n if (!info.isFile() || info.isSymbolicLink() || info.size > this.#maxFileSize) {\n if (replacePath) workingDeletes.add(replacePath);\n workingDeletes.add(relativePath);\n skippedWorkingPaths.add(relativePath);\n continue;\n }\n const content = await readFile(absolutePath);\n if (!replacePath && change.status === \"A\") {\n const contentHash = sha256(content.toString(\"utf8\"));\n const renameCandidates = workingFiles.filter((file) => (\n file.path !== relativePath\n && !visibleWorkingPaths.has(file.path)\n && deletes.has(file.path)\n && file.contentHash === contentHash\n ));\n const renamed = renameCandidates.length === 1 ? renameCandidates[0] : undefined;\n if (renamed) {\n replacePath = renamed.path;\n previousPath = renamed.previousPath ?? renamed.path;\n deletes.delete(renamed.path);\n }\n }\n workingPrepared.push(this.#prepareFile(relativePath, content, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(previousPath ? { previousPath } : {}),\n ...(replacePath ? { replacePath } : {}),\n }));\n }\n\n const prepared: PreparedFile[] = [];\n for (const { entry, previousPath } of upserts.values()) {\n throwIfAborted(options.signal);\n const content = await this.#git.readBlob(entry.oid);\n if (content.byteLength > this.#maxFileSize) {\n deletes.add(entry.path);\n continue;\n }\n prepared.push(this.#prepareFile(entry.path, content, {\n blobOid: entry.oid,\n sourceMode: \"git\",\n indexedCommit: target,\n ...(previousPath ? { replacePath: previousPath } : {}),\n }));\n }\n await this.#attachEmbeddings([...prepared, ...workingPrepared], options.signal);\n const noChanges = (\n !reconcileAll\n && checkpoint === target\n && prepared.length === 0\n && deletes.size === 0\n && workingPrepared.length === 0\n && workingDeletes.size === 0\n );\n\n const resolvedAgain = await this.#git.resolveCommit(options.target ?? \"HEAD\");\n if (resolvedAgain !== target) throw new CodeIndexError(\"Target Git ref changed while indexing; retry the update.\");\n if (overlayWorkingTree) {\n const headAgain = await this.#git.resolveCommit(\"HEAD\");\n const workingChangesAgain = await this.#git.workTreeChanges(target, indexArtifacts);\n if (headAgain !== head || JSON.stringify(workingChangesAgain) !== JSON.stringify(workingChanges)) {\n throw new CodeIndexError(\"Git HEAD or working-tree changes changed while indexing; retry the update.\");\n }\n for (const file of workingPrepared) {\n const info = await lstat(path.join(this.rootDir, file.path));\n const content = await readFile(path.join(this.rootDir, file.path));\n if (!info.isFile() || info.isSymbolicLink() || info.size > this.#maxFileSize || sha256(content.toString(\"utf8\")) !== file.contentHash) {\n throw new CodeIndexError(`Working-tree file changed while indexing: ${file.path}`);\n }\n }\n for (const relativePath of skippedWorkingPaths) {\n const info = await lstat(path.join(this.rootDir, relativePath));\n if (info.isFile() && !info.isSymbolicLink() && info.size <= this.#maxFileSize) {\n throw new CodeIndexError(`Working-tree file changed while indexing: ${relativePath}`);\n }\n }\n }\n if (noChanges) {\n if (this.#database.getCheckpoint() !== checkpoint || this.#database.getGeneration() !== generation) {\n throw new CodeIndexError(\"Index changed while the update was being prepared; retry the update.\");\n }\n return emptyStats(checkpoint);\n }\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletes],\n workingTree: {\n files: workingPrepared,\n deletePaths: [...workingDeletes],\n },\n checkpoint: target,\n expectedCheckpoint: checkpoint,\n expectedGeneration: generation,\n });\n }\n\n #classifyGitChanges(\n changes: readonly GitChange[],\n tree: ReadonlyMap<string, GitTreeEntry>,\n upserts: Map<string, { entry: GitTreeEntry; previousPath?: string }>,\n deletes: Set<string>,\n ): void {\n for (const change of changes) {\n if (change.status === \"D\") {\n deletes.add(change.path);\n continue;\n }\n if (change.status === \"R\") {\n deletes.add(change.oldPath);\n const entry = tree.get(change.path);\n if (entry && this.#policy.includes(change.path) && entry.size <= this.#maxFileSize) {\n upserts.set(change.path, { entry, previousPath: change.oldPath });\n }\n continue;\n }\n const entry = tree.get(change.path);\n if (entry && this.#policy.includes(change.path) && entry.size <= this.#maxFileSize) upserts.set(change.path, { entry });\n else deletes.add(change.path);\n }\n }\n\n async #workingTreeSourcePaths(signal?: AbortSignal): Promise<string[]> {\n const relativeIndexPath = path.relative(this.rootDir, this.indexPath).replaceAll(path.sep, \"/\");\n const indexArtifacts = new Set(relativeIndexPath && !relativeIndexPath.startsWith(\"../\")\n ? [relativeIndexPath, `${relativeIndexPath}-shm`, `${relativeIndexPath}-wal`, `${relativeIndexPath}-journal`]\n : []);\n const directories = [\"\"];\n const sourcePaths: string[] = [];\n while (directories.length > 0) {\n throwIfAborted(signal);\n const relativeDirectory = directories.shift()!;\n const entries = await readdir(path.join(this.rootDir, relativeDirectory), { withFileTypes: true });\n entries.sort((left, right) => left.name.localeCompare(right.name));\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? `${relativeDirectory.replaceAll(path.sep, \"/\")}/${entry.name}`\n : entry.name;\n if (entry.isDirectory()) {\n if (this.#policy.traversesDirectory(relativePath)) directories.push(relativePath);\n } else if (entry.isFile() && !indexArtifacts.has(relativePath) && this.#policy.includes(relativePath)) {\n sourcePaths.push(relativePath);\n }\n }\n }\n sourcePaths.sort();\n return sourcePaths;\n }\n\n #prepareFile(\n relativePath: string,\n buffer: Buffer,\n provenance: Pick<PreparedFile, \"blobOid\" | \"sourceMode\" | \"indexedCommit\" | \"previousPath\" | \"replacePath\">,\n ): PreparedFile {\n const content = buffer.toString(\"utf8\");\n const callables = parseCallables(relativePath, content, this.#onWarning) as PreparedCallable[];\n const language = callables[0]?.language ?? path.extname(relativePath).slice(1);\n return {\n path: relativePath,\n contentHash: sha256(content),\n blobOid: provenance.blobOid,\n sourceMode: provenance.sourceMode,\n indexedCommit: provenance.indexedCommit,\n language,\n byteSize: buffer.byteLength,\n ...(provenance.previousPath ? { previousPath: provenance.previousPath } : {}),\n ...(provenance.replacePath ? { replacePath: provenance.replacePath } : {}),\n callables,\n };\n }\n\n async #attachEmbeddings(files: PreparedFile[], signal?: AbortSignal): Promise<void> {\n const profile = JSON.stringify(normalizeProfile(this.provider.profile));\n const unique = new Map<string, PreparedCallable[]>();\n for (const file of files) {\n for (const callable of file.callables) {\n callable.embeddingKey = sha256(`${profile}\\0${callable.embeddingInput}`);\n const values = unique.get(callable.embeddingKey) ?? [];\n values.push(callable);\n unique.set(callable.embeddingKey, values);\n }\n }\n const existing = this.#database.getEmbeddingKeys([...unique.keys()]);\n const missing = [...unique.entries()].filter(([key]) => !existing.has(key));\n for (const batch of chunk(missing, this.#embeddingBatchSize)) {\n throwIfAborted(signal);\n const vectors = await this.provider.embedDocuments(batch.map(([, callables]) => callables[0]!.embeddingInput), signal ? { signal } : undefined);\n if (vectors.length !== batch.length) throw new CodeIndexError(\"Embedding provider returned an unexpected number of vectors.\");\n vectors.forEach((vector, index) => {\n const converted = normalizeEmbeddingVector(vector, this.provider.profile.dimensions);\n for (const callable of batch[index]![1]) callable.vector = converted;\n });\n }\n }\n\n public async similaritySearch(options: SimilaritySearchOptions): Promise<SimilarityResult[]> {\n if (!options.query.trim()) throw new CodeIndexError(\"query must not be empty.\");\n const limit = options.limit ?? 10;\n assertPositiveInteger(limit, \"limit\");\n throwIfAborted(options.signal);\n const vector = await this.provider.embedQuery(options.query, options.signal ? { signal: options.signal } : undefined);\n return this.searchByVector(vector, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n }\n\n public similarToFunction(functionId: number, options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludePaths?: readonly string[];\n minLines?: number;\n nameRegex?: string;\n }): SimilarityResult[] {\n const vector = this.#database.vectorForFunction(functionId);\n return this.#database.searchVector(vector, {\n limit: options.limit,\n minSimilarity: options.minSimilarity,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n excludeId: functionId,\n ...(options.excludePaths !== undefined ? { excludePaths: options.excludePaths } : {}),\n ...(options.minLines !== undefined ? { minLines: options.minLines } : {}),\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n });\n }\n\n public vectorForFunction(functionId: number): number[] {\n return this.#database.vectorForFunction(functionId);\n }\n\n public searchByVector(vector: readonly number[], options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludePaths?: readonly string[];\n minLines?: number;\n nameRegex?: string;\n }): SimilarityResult[] {\n return this.#database.searchVector(normalizeEmbeddingVector(vector, this.provider.profile.dimensions), options);\n }\n\n public async sourceFunctions(filter: CrossSearchSourceFilter): Promise<IndexedFunction[]> {\n const functions = filter.type === \"all\"\n ? this.allFunctions()\n : filter.type === \"uncommitted\"\n ? this.allFunctions().filter((callable) => callable.sourceMode === \"working-tree\")\n : await this.#functionsChangedSince(filter.commit);\n if (!filter.path) return functions;\n const sourcePath = normalizeRelativePath(this.rootDir, filter.path);\n return functions.filter((callable) => callable.path === sourcePath || callable.path.startsWith(`${sourcePath}/`));\n }\n\n async #functionsChangedSince(baseRef: string): Promise<IndexedFunction[]> {\n await this.#git.assertRepository();\n const checkpoint = this.#database.getCheckpoint();\n if (!checkpoint) throw new CodeIndexError(\"changed-since requires an index with a Git checkpoint.\");\n const base = await this.#git.resolveCommit(baseRef);\n if (!(await this.#git.isAncestor(base, checkpoint))) {\n throw new GitDivergenceError(base, checkpoint);\n }\n\n const changes = await this.#git.diff(base, checkpoint);\n const baseTree = await this.#git.listTree(base);\n const comparisonPaths = new Map<string, { basePath: string | null; pathChanged: boolean }>();\n for (const change of changes) {\n if (change.status === \"D\") continue;\n if (change.status === \"R\") comparisonPaths.set(change.path, { basePath: change.oldPath, pathChanged: true });\n else if (change.status === \"A\" || change.status === \"C\") comparisonPaths.set(change.path, { basePath: null, pathChanged: false });\n else comparisonPaths.set(change.path, { basePath: change.path, pathChanged: false });\n }\n for (const dirtyFile of this.#database.getWorkingTreeFiles()) {\n const basePath = dirtyFile.previousPath ?? comparisonPaths.get(dirtyFile.path)?.basePath ?? dirtyFile.path;\n comparisonPaths.set(dirtyFile.path, { basePath, pathChanged: basePath !== dirtyFile.path });\n }\n\n const current = this.#database.functionsForPaths([...comparisonPaths.keys()]);\n const baseFunctionsByCurrentPath = new Map<string, ReturnType<typeof parseCallables>>();\n for (const [currentPath, { basePath }] of comparisonPaths) {\n if (!basePath) {\n baseFunctionsByCurrentPath.set(currentPath, []);\n continue;\n }\n const entry = baseTree.get(basePath);\n if (!entry) {\n baseFunctionsByCurrentPath.set(currentPath, []);\n continue;\n }\n const content = (await this.#git.readBlob(entry.oid)).toString(\"utf8\");\n baseFunctionsByCurrentPath.set(currentPath, parseCallables(basePath, content, this.#onWarning));\n }\n const currentByPath = groupBy(current, (callable) => callable.path);\n const changedIds = new Set<number>();\n for (const [currentPath, currentFunctions] of currentByPath) {\n const comparison = comparisonPaths.get(currentPath)!;\n for (const id of changedFunctionIds(\n currentFunctions,\n baseFunctionsByCurrentPath.get(currentPath) ?? [],\n comparison.pathChanged,\n )) {\n changedIds.add(id);\n }\n }\n return current.filter((callable) => changedIds.has(callable.id));\n }\n}\n\nfunction changedFunctionIds(\n current: readonly IndexedFunction[],\n base: readonly Pick<IndexedFunction, \"qualifiedName\" | \"kind\" | \"sourceHash\">[],\n pathChanged: boolean,\n): number[] {\n if (pathChanged) return current.map((callable) => callable.id);\n const currentGroups = groupBy(current, (callable) => `${callable.qualifiedName}\\0${callable.kind}`);\n const baseGroups = groupBy(base, (callable) => `${callable.qualifiedName}\\0${callable.kind}`);\n const changed: number[] = [];\n for (const [key, currentGroup] of currentGroups) {\n const baseGroup = baseGroups.get(key) ?? [];\n const unmatchedBase = new Set(baseGroup.map((_, index) => index));\n const unmatchedCurrent = new Set(currentGroup.map((_, index) => index));\n for (let currentIndex = 0; currentIndex < currentGroup.length; currentIndex += 1) {\n const exactBaseIndex = [...unmatchedBase].find(\n (baseIndex) => baseGroup[baseIndex]!.sourceHash === currentGroup[currentIndex]!.sourceHash,\n );\n if (exactBaseIndex !== undefined) {\n unmatchedBase.delete(exactBaseIndex);\n unmatchedCurrent.delete(currentIndex);\n }\n }\n for (const currentIndex of unmatchedCurrent) changed.push(currentGroup[currentIndex]!.id);\n }\n return changed;\n}\n\nfunction normalizeProfile(profile: EmbeddingProfile): Required<EmbeddingProfile> {\n return {\n provider: profile.provider,\n model: profile.model,\n dimensions: profile.dimensions,\n strategyVersion: profile.strategyVersion ?? \"callable-v1\",\n };\n}\n\nfunction emptyStats(checkpoint: string | null): UpdateStats {\n return {\n filesUpdated: 0,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint,\n };\n}\n\nfunction validateRenames(renames: readonly { from: string; to: string }[]): void {\n const sources = new Set(renames.map((rename) => rename.from));\n const targets = new Set(renames.map((rename) => rename.to));\n if (sources.size !== renames.length || targets.size !== renames.length) {\n throw new CodeIndexError(\"Rename sources and targets must be unique.\");\n }\n if ([...sources].some((source) => targets.has(source))) {\n throw new CodeIndexError(\"Chained or cyclic renames must be applied in separate updates.\");\n }\n}\n\nfunction groupBy<T>(values: readonly T[], keyFor: (value: T) => string): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n for (const value of values) {\n const key = keyFor(value);\n const group = groups.get(key) ?? [];\n group.push(value);\n groups.set(key, group);\n }\n return groups;\n}\n","export class CodeIndexError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CodeIndexError\";\n }\n}\n\nexport class GitDivergenceError extends CodeIndexError {\n public constructor(checkpoint: string, target: string) {\n super(`Stored Git checkpoint ${checkpoint} is not an ancestor of ${target}; rebuild the index.`);\n this.name = \"GitDivergenceError\";\n }\n}\n\nexport class GitUnavailableError extends CodeIndexError {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"GitUnavailableError\";\n }\n}\n\nexport class IncompatibleIndexError extends CodeIndexError {\n public constructor(message: string) {\n super(message);\n this.name = \"IncompatibleIndexError\";\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { lstat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { CodeIndexError, GitUnavailableError } from \"../errors.js\";\n\nexport type GitChange =\n | { status: \"A\" | \"M\" | \"D\" | \"T\"; path: string }\n | { status: \"R\" | \"C\"; oldPath: string; path: string };\n\nexport interface GitTreeEntry {\n path: string;\n oid: string;\n mode: string;\n size: number;\n}\n\nexport class GitRepository {\n public constructor(public readonly rootDir: string) {}\n\n async #run(args: readonly string[], allowExitOne = false): Promise<{ stdout: Buffer; code: number }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(\"git\", [\"-C\", this.rootDir, ...args], { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n child.stdout.on(\"data\", (value: Buffer) => stdout.push(value));\n child.stderr.on(\"data\", (value: Buffer) => stderr.push(value));\n child.on(\"error\", (error) => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(new GitUnavailableError(\"Git executable is not available.\", { cause: error }));\n return;\n }\n reject(error);\n });\n child.on(\"close\", (code) => {\n const exitCode = code ?? -1;\n if (exitCode === 0 || (allowExitOne && exitCode === 1)) {\n resolve({ stdout: Buffer.concat(stdout), code: exitCode });\n return;\n }\n reject(new CodeIndexError(`Git command failed: ${Buffer.concat(stderr).toString(\"utf8\").trim()}`));\n });\n });\n }\n\n public async assertRepository(): Promise<void> {\n let result: { stdout: Buffer; code: number };\n try {\n result = await this.#run([\"rev-parse\", \"--is-inside-work-tree\"]);\n } catch (error) {\n if (error instanceof GitUnavailableError) throw error;\n try {\n await lstat(path.join(this.rootDir, \".git\"));\n } catch (markerError) {\n if ((markerError as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new GitUnavailableError(`${this.rootDir} is not a Git worktree.`, { cause: error });\n }\n throw markerError;\n }\n throw error;\n }\n if (result.stdout.toString(\"utf8\").trim() !== \"true\") {\n throw new GitUnavailableError(`${this.rootDir} is not a Git worktree.`);\n }\n const topLevel = (await this.#run([\"rev-parse\", \"--show-toplevel\"])).stdout.toString(\"utf8\").trim();\n if (path.resolve(topLevel) !== path.resolve(this.rootDir)) {\n throw new CodeIndexError(`rootDir must be the Git worktree root: ${topLevel}`);\n }\n }\n\n public async workTreeChanges(base: string, excludePaths: readonly string[] = []): Promise<GitChange[]> {\n const pathspecs = [\".\", ...excludePaths.map((filePath) => `:(top,literal,exclude)${filePath}`)];\n const result = await this.#run([\n \"diff\",\n \"--name-status\",\n \"-z\",\n \"--find-renames\",\n base,\n \"--\",\n ...pathspecs,\n ]);\n const changes = parseChanges(splitNull(result.stdout));\n const untracked = await this.#run([\n \"ls-files\",\n \"--others\",\n \"--exclude-standard\",\n \"-z\",\n \"--\",\n ...pathspecs,\n ]);\n for (const filePath of splitNull(untracked.stdout)) changes.push({ status: \"A\", path: filePath });\n return changes;\n }\n\n public async resolveCommit(ref: string): Promise<string> {\n const result = await this.#run([\"rev-parse\", \"--verify\", \"--end-of-options\", `${ref}^{commit}`]);\n const oid = result.stdout.toString(\"ascii\").trim();\n if (!/^[0-9a-f]{40,64}$/.test(oid)) throw new CodeIndexError(`Could not resolve Git commit: ${ref}`);\n return oid;\n }\n\n public async isAncestor(ancestor: string, descendant: string): Promise<boolean> {\n const result = await this.#run([\"merge-base\", \"--is-ancestor\", ancestor, descendant], true);\n return result.code === 0;\n }\n\n public async listTree(commit: string): Promise<Map<string, GitTreeEntry>> {\n const result = await this.#run([\"ls-tree\", \"-r\", \"-z\", \"-l\", \"--full-tree\", commit, \"--\"]);\n const entries = new Map<string, GitTreeEntry>();\n for (const record of splitNull(result.stdout)) {\n const tab = record.indexOf(\"\\t\");\n if (tab < 0) continue;\n const [mode, type, oid, sizeText] = record.slice(0, tab).trim().split(/\\s+/);\n const filePath = record.slice(tab + 1);\n const size = Number(sizeText);\n if ((mode === \"100644\" || mode === \"100755\") && type === \"blob\" && oid && Number.isSafeInteger(size)) {\n entries.set(filePath, { path: filePath, oid, mode, size });\n }\n }\n return entries;\n }\n\n public async readBlob(oid: string): Promise<Buffer> {\n return (await this.#run([\"cat-file\", \"blob\", oid])).stdout;\n }\n\n public async diff(base: string, target: string): Promise<GitChange[]> {\n const result = await this.#run([\"diff\", \"--name-status\", \"-z\", \"--find-renames\", `${base}..${target}`, \"--\"]);\n return parseChanges(splitNull(result.stdout));\n }\n}\n\nfunction parseChanges(values: readonly string[]): GitChange[] {\n const changes: GitChange[] = [];\n for (let index = 0; index < values.length;) {\n const rawStatus = values[index++];\n if (!rawStatus) continue;\n const status = rawStatus[0];\n if (status === \"R\" || status === \"C\") {\n const oldPath = values[index++];\n const filePath = values[index++];\n if (oldPath && filePath) changes.push({ status, oldPath, path: filePath });\n } else if (status === \"A\" || status === \"M\" || status === \"D\" || status === \"T\") {\n const filePath = values[index++];\n if (filePath) changes.push({ status, path: filePath });\n } else {\n throw new CodeIndexError(`Unsupported Git diff status: ${rawStatus}`);\n }\n }\n return changes;\n}\n\nfunction splitNull(buffer: Buffer): string[] {\n const value = buffer.toString(\"utf8\");\n const parts = value.split(\"\\0\");\n if (parts.at(-1) === \"\") parts.pop();\n return parts;\n}\n","import path from \"node:path\";\n\nimport Parser from \"tree-sitter\";\nimport JavaScript from \"tree-sitter-javascript\";\nimport TypeScript from \"tree-sitter-typescript\";\n\nimport { CodeIndexError } from \"../errors.js\";\nimport type { CallableKind, ParsedCallable, SupportedLanguage } from \"../types.js\";\nimport { sha256 } from \"../utils.js\";\n\ninterface CallableCandidate {\n node: Parser.SyntaxNode;\n name: string;\n kind: CallableKind;\n scope: readonly string[];\n}\n\nconst parsers = new Map<SupportedLanguage, Parser>();\n\nexport function languageForPath(filePath: string): SupportedLanguage | null {\n switch (path.extname(filePath).toLowerCase()) {\n case \".ts\":\n case \".mts\":\n case \".cts\":\n return \"typescript\";\n case \".tsx\":\n return \"tsx\";\n case \".js\":\n case \".mjs\":\n case \".cjs\":\n return \"javascript\";\n case \".jsx\":\n return \"jsx\";\n default:\n return null;\n }\n}\n\nfunction getParser(language: SupportedLanguage): Parser {\n const existing = parsers.get(language);\n if (existing) return existing;\n\n const parser = new Parser();\n if (language === \"typescript\") parser.setLanguage(TypeScript.typescript);\n else if (language === \"tsx\") parser.setLanguage(TypeScript.tsx);\n else parser.setLanguage(JavaScript);\n parsers.set(language, parser);\n return parser;\n}\n\nfunction parseTree(parser: Parser, content: string, relativePath: string): Parser.Tree {\n try {\n return parser.parse(content, undefined, { bufferSize: Buffer.byteLength(content) + 1 });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CodeIndexError(`Cannot index ${relativePath}: tree-sitter failed: ${message}`, { cause: error });\n }\n}\n\nfunction maskSyntax(value: string, replacement: string): string {\n return replacement + value.slice(replacement.length).replace(/[^\\r\\n]/g, \" \");\n}\n\nfunction recoverUnsupportedTypeScriptSyntax(\n parser: Parser,\n tree: Parser.Tree,\n content: string,\n relativePath: string,\n): Parser.Tree | null {\n const errors: Parser.SyntaxNode[] = [];\n const collectErrors = (node: Parser.SyntaxNode): void => {\n if (node.isError || node.isMissing) errors.push(node);\n for (const child of node.children) collectErrors(child);\n };\n collectErrors(tree.rootNode);\n\n if (errors.length === 0) return null;\n\n let recoveredContent = content;\n let changed = false;\n const taggedTemplateTypeArguments = new Map<number, Parser.SyntaxNode>();\n for (const error of errors) {\n const parent = error.parent;\n if (error.isMissing\n && error.type === \"!\"\n && parent?.type === \"type_arguments\"\n && /^\\s*`/.test(content.slice(parent.endIndex))) {\n taggedTemplateTypeArguments.set(parent.startIndex, parent);\n }\n }\n for (const node of [...taggedTemplateTypeArguments.values()].toSorted((left, right) => right.startIndex - left.startIndex)) {\n const value = recoveredContent.slice(node.startIndex, node.endIndex);\n recoveredContent = `${recoveredContent.slice(0, node.startIndex)}${value.replace(/[^\\r\\n]/g, \" \")}${recoveredContent.slice(node.endIndex)}`;\n changed = true;\n }\n\n for (const node of errors.filter((candidate) => {\n const parent = candidate.parent;\n return !candidate.isMissing\n && candidate.type === \"ERROR\"\n && candidate.text === \"type\"\n && parent?.type === \"export_statement\"\n && content.slice(parent.startIndex, candidate.startIndex).trim() === \"export\"\n && /^\\s*\\*/.test(content.slice(candidate.endIndex, parent.endIndex));\n }).toSorted((left, right) => right.startIndex - left.startIndex)) {\n recoveredContent = `${recoveredContent.slice(0, node.startIndex)} ${recoveredContent.slice(node.endIndex)}`;\n changed = true;\n }\n\n recoveredContent = recoveredContent.replace(\n /\\bimport\\s*\\(\\s*([\"'])(?:\\\\.|(?!\\1)[^\\\\])*\\1\\s*\\)/g,\n (value) => {\n changed = true;\n return maskSyntax(value, \"X\");\n },\n );\n if (!changed) return null;\n\n const recoveredTree = parseTree(parser, recoveredContent, relativePath);\n return recoveredTree.rootNode.hasError ? null : recoveredTree;\n}\n\nfunction textFor(content: string, node: Parser.SyntaxNode): string {\n return content.slice(node.startIndex, node.endIndex);\n}\n\nfunction fieldText(content: string, node: Parser.SyntaxNode, field: string): string | null {\n const child = node.childForFieldName(field);\n return child ? textFor(content, child) : null;\n}\n\nfunction callableKind(node: Parser.SyntaxNode, name: string): CallableKind {\n if (name === \"constructor\") return \"constructor\";\n if (node.type.includes(\"generator\") || /^\\s*(?:async\\s+)?\\*/.test(node.text)) return \"generator\";\n return node.type === \"method_definition\" ? \"method\" : \"function\";\n}\n\nfunction bindingName(content: string, node: Parser.SyntaxNode): string | null {\n const nameNode = node.childForFieldName(\"name\");\n if (!nameNode || ![\"identifier\", \"property_identifier\", \"private_property_identifier\"].includes(nameNode.type)) {\n return null;\n }\n return textFor(content, nameNode).replace(/^#/, \"\");\n}\n\nfunction assignmentName(content: string, node: Parser.SyntaxNode): string | null {\n const left = node.childForFieldName(\"left\");\n if (!left) return null;\n const value = textFor(content, left).trim();\n const match = value.match(/(?:^|[.#])([A-Za-z_$][\\w$]*)$/);\n return match?.[1] ?? null;\n}\n\nfunction objectScopeName(content: string, node: Parser.SyntaxNode): string | null {\n const parent = node.parent;\n if (!parent) return null;\n if (parent.type === \"variable_declarator\" && parent.childForFieldName(\"value\")?.id === node.id) {\n return bindingName(content, parent);\n }\n if (parent.type === \"pair\" && parent.childForFieldName(\"value\")?.id === node.id) {\n return fieldText(content, parent, \"key\")?.replace(/[\"']/g, \"\") ?? null;\n }\n if (parent.type === \"assignment_expression\" && parent.childForFieldName(\"right\")?.id === node.id) {\n return assignmentName(content, parent);\n }\n return null;\n}\n\nfunction walk(\n node: Parser.SyntaxNode,\n content: string,\n scope: readonly string[],\n candidates: CallableCandidate[],\n): void {\n if (node.type === \"class_declaration\" || node.type === \"class\") {\n const name = fieldText(content, node, \"name\") ?? objectScopeName(content, node);\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if (node.type === \"internal_module\" || node.type === \"module\") {\n const name = fieldText(content, node, \"name\")?.replace(/[\"']/g, \"\");\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if (node.type === \"object\") {\n const name = objectScopeName(content, node);\n const nextScope = name ? [...scope, name] : scope;\n for (const child of node.namedChildren) walk(child, content, nextScope, candidates);\n return;\n }\n\n if ([\"function_declaration\", \"generator_function_declaration\"].includes(node.type)) {\n const name = fieldText(content, node, \"name\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if (node.type === \"method_definition\") {\n const name = fieldText(content, node, \"name\")?.replace(/^#/, \"\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if (node.type === \"public_field_definition\" || node.type === \"field_definition\") {\n const name = (fieldText(content, node, \"name\") ?? fieldText(content, node, \"property\"))?.replace(/^#/, \"\");\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n const kind = callableKind(value, name) === \"generator\" ? \"generator\" : \"method\";\n candidates.push({ node: value, name, kind, scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"variable_declarator\") {\n const name = bindingName(content, node);\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"pair\") {\n const name = fieldText(content, node, \"key\")?.replace(/[\"']/g, \"\");\n const value = node.childForFieldName(\"value\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if (node.type === \"assignment_expression\") {\n const name = assignmentName(content, node);\n const value = node.childForFieldName(\"right\");\n if (name && value && [\"arrow_function\", \"function_expression\", \"generator_function\"].includes(value.type)) {\n candidates.push({ node: value, name, kind: callableKind(value, name), scope });\n const body = value.childForFieldName(\"body\");\n if (body) walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n if ([\"function_expression\", \"generator_function\"].includes(node.type)) {\n const name = fieldText(content, node, \"name\");\n const body = node.childForFieldName(\"body\");\n if (name && body) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n walk(body, content, [...scope, name], candidates);\n return;\n }\n }\n\n for (const child of node.namedChildren) walk(child, content, scope, candidates);\n}\n\nfunction signatureFor(content: string, node: Parser.SyntaxNode, name: string): string | null {\n const parameters = node.childForFieldName(\"parameters\");\n if (!parameters) return name;\n const returnType = node.childForFieldName(\"return_type\");\n return `${name}${textFor(content, parameters)}${returnType ? textFor(content, returnType) : \"\"}`;\n}\n\nexport function parseCallables(\n relativePath: string,\n content: string,\n onWarning: (message: string) => void = console.warn,\n): ParsedCallable[] {\n const language = languageForPath(relativePath);\n if (!language) return [];\n\n const parser = getParser(language);\n const parsedTree = parseTree(parser, content, relativePath);\n const tree = parsedTree.rootNode.hasError\n ? recoverUnsupportedTypeScriptSyntax(parser, parsedTree, content, relativePath) ?? parsedTree\n : parsedTree;\n if (tree.rootNode.hasError) {\n onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);\n }\n\n const candidates: CallableCandidate[] = [];\n walk(tree.rootNode, content, [], candidates);\n candidates.sort((left, right) => left.node.startIndex - right.node.startIndex);\n\n const occurrences = new Map<string, number>();\n return candidates.map(({ node, name, kind, scope }) => {\n const qualifiedName = [...scope, name].join(\".\");\n const baseIdentity = `${relativePath}\\0${qualifiedName}\\0${kind}`;\n const occurrence = occurrences.get(baseIdentity) ?? 0;\n occurrences.set(baseIdentity, occurrence + 1);\n const identityKey = sha256(`${baseIdentity}\\0${occurrence}`);\n const source = textFor(content, node);\n const signature = signatureFor(content, node, name);\n const embeddingInput = [\n `language: ${language}`,\n `kind: ${kind}`,\n `symbol: ${qualifiedName}`,\n signature ? `signature: ${signature}` : null,\n \"source:\",\n source,\n ].filter((value): value is string => value !== null).join(\"\\n\");\n\n return {\n path: relativePath,\n language,\n kind,\n name,\n qualifiedName,\n signature,\n identityKey,\n startLine: node.startPosition.row + 1,\n startColumn: node.startPosition.column + 1,\n endLine: node.endPosition.row + 1,\n endColumn: node.endPosition.column + 1,\n lineCount: node.endPosition.row - node.startPosition.row + 1,\n source,\n sourceHash: sha256(source),\n embeddingInput,\n };\n });\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { CodeIndexError } from \"./errors.js\";\n\nexport function sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function normalizeRelativePath(rootDir: string, inputPath: string): string {\n const absolute = path.resolve(rootDir, inputPath);\n const relative = path.relative(rootDir, absolute);\n if (relative === \"\" || relative === \".\") {\n throw new CodeIndexError(`Expected a file path, received repository root: ${inputPath}`);\n }\n if (relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n throw new CodeIndexError(`Path escapes repository root: ${inputPath}`);\n }\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function throwIfAborted(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nexport function chunk<T>(values: readonly T[], size: number): T[][] {\n const batches: T[][] = [];\n for (let index = 0; index < values.length; index += size) {\n batches.push(values.slice(index, index + size));\n }\n return batches;\n}\n\nexport function assertPositiveInteger(value: number, name: string): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new CodeIndexError(`${name} must be a positive integer.`);\n }\n}\n\nexport function normalizeEmbeddingVector(value: unknown, dimensions: number): number[] {\n if (!Array.isArray(value) || value.length !== dimensions) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n const converted: number[] = [];\n for (const component of value) {\n if (typeof component !== \"number\" || !Number.isFinite(component)) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n const normalized = Math.fround(component);\n if (!Number.isFinite(normalized)) {\n throw new CodeIndexError(`Expected a finite ${dimensions}-dimensional embedding vector.`);\n }\n converted.push(normalized);\n }\n if (!converted.some((component) => component !== 0)) {\n throw new CodeIndexError(\"Embedding vector must not be all zeroes.\");\n }\n return converted;\n}\n","import path from \"node:path\";\n\nimport { languageForPath } from \"./parser/callable-parser.js\";\n\nconst DEFAULT_EXCLUDED_SEGMENTS = new Set([\n \".git\",\n \".slopdex\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \"coverage\",\n \"vendor\",\n \"generated\",\n]);\n\nexport class SourcePolicy {\n readonly #include: readonly string[];\n readonly #exclude: readonly string[];\n\n public constructor(include: readonly string[] = [], exclude: readonly string[] = []) {\n this.#include = include;\n this.#exclude = exclude;\n }\n\n public includes(relativePath: string): boolean {\n const normalized = relativePath.replaceAll(\"\\\\\", \"/\");\n if (!languageForPath(normalized)) return false;\n if (hasExcludedSegment(normalized)) return false;\n if (this.#exclude.some((pattern) => path.matchesGlob(normalized, pattern))) return false;\n return this.#include.length === 0 || this.#include.some((pattern) => path.matchesGlob(normalized, pattern));\n }\n\n public traversesDirectory(relativePath: string): boolean {\n return !hasExcludedSegment(relativePath.replaceAll(\"\\\\\", \"/\"));\n }\n}\n\nfunction hasExcludedSegment(relativePath: string): boolean {\n return relativePath.split(\"/\").some((segment) => DEFAULT_EXCLUDED_SEGMENTS.has(segment));\n}\n","import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\n\nimport * as sqliteVec from \"sqlite-vec\";\n\nimport { CodeIndexError, IncompatibleIndexError } from \"../errors.js\";\nimport type {\n EmbeddingProfile,\n IndexStatus,\n IndexedFunction,\n ParsedCallable,\n SourceMode,\n UpdateStats,\n} from \"../types.js\";\n\nconst SCHEMA_VERSION = \"2\";\n\nexport interface PreparedCallable extends ParsedCallable {\n embeddingKey: string;\n vector?: readonly number[];\n}\n\nexport interface PreparedFile {\n path: string;\n contentHash: string;\n blobOid: string | null;\n sourceMode: SourceMode;\n indexedCommit: string | null;\n language: string;\n byteSize: number;\n previousPath?: string;\n replacePath?: string;\n callables: PreparedCallable[];\n}\n\nexport interface IndexedFileState {\n path: string;\n contentHash: string;\n blobOid: string | null;\n sourceMode: SourceMode;\n previousPath: string | null;\n}\n\ninterface FunctionRow {\n id: number;\n path: string;\n language: IndexedFunction[\"language\"];\n kind: IndexedFunction[\"kind\"];\n name: string;\n qualified_name: string;\n signature: string | null;\n identity_key: string;\n start_line: number;\n start_column: number;\n end_line: number;\n end_column: number;\n line_count: number;\n source: string;\n source_hash: string;\n embedding_input: string;\n first_seen_commit: string | null;\n last_seen_commit: string | null;\n source_mode: SourceMode;\n embedding_id: number;\n}\n\nexport class IndexDatabase {\n readonly #db: DatabaseSync;\n readonly #rootDir: string;\n readonly #indexPath: string;\n readonly #profile: Required<EmbeddingProfile>;\n\n public constructor(indexPath: string, rootDir: string, profile: Required<EmbeddingProfile>, readOnly = false) {\n if (!readOnly) mkdirSync(path.dirname(indexPath), { recursive: true });\n this.#indexPath = indexPath;\n this.#rootDir = rootDir;\n this.#profile = profile;\n this.#db = new DatabaseSync(indexPath, { allowExtension: true, readOnly });\n try {\n sqliteVec.load(this.#db);\n this.#db.enableLoadExtension(false);\n const regexes = new Map<string, RegExp>();\n this.#db.function(\"slopdex_regexp\", { deterministic: true }, (pattern, value) => {\n if (typeof pattern !== \"string\" || typeof value !== \"string\") return 0;\n let regex = regexes.get(pattern);\n if (!regex) {\n regex = new RegExp(pattern);\n regexes.set(pattern, regex);\n }\n return regex.test(value) ? 1 : 0;\n });\n if (readOnly) {\n this.#db.exec(\"PRAGMA foreign_keys=ON\");\n } else {\n this.#db.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;\");\n this.#migrate();\n }\n this.#validateMetadata(readOnly);\n } catch (error) {\n this.#db.close();\n throw error;\n }\n }\n\n public close(): void {\n this.#db.close();\n }\n\n #migrate(): void {\n this.#db.exec(`\n CREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS files (\n path TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n blob_oid TEXT,\n source_mode TEXT NOT NULL CHECK(source_mode IN ('git', 'working-tree')),\n indexed_commit TEXT,\n previous_path TEXT,\n language TEXT NOT NULL,\n byte_size INTEGER NOT NULL\n );\n CREATE TABLE IF NOT EXISTS embeddings (\n id INTEGER PRIMARY KEY,\n embedding_key TEXT NOT NULL UNIQUE,\n vector BLOB NOT NULL\n );\n CREATE TABLE IF NOT EXISTS functions (\n id INTEGER PRIMARY KEY,\n path TEXT NOT NULL REFERENCES files(path) ON DELETE CASCADE ON UPDATE CASCADE,\n language TEXT NOT NULL,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL,\n signature TEXT,\n identity_key TEXT NOT NULL UNIQUE,\n start_line INTEGER NOT NULL,\n start_column INTEGER NOT NULL,\n end_line INTEGER NOT NULL,\n end_column INTEGER NOT NULL,\n line_count INTEGER NOT NULL,\n source TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n embedding_input TEXT NOT NULL,\n first_seen_commit TEXT,\n last_seen_commit TEXT,\n source_mode TEXT NOT NULL CHECK(source_mode IN ('git', 'working-tree')),\n embedding_id INTEGER NOT NULL REFERENCES embeddings(id)\n );\n CREATE TABLE IF NOT EXISTS callable_provenance (\n identity_key TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n first_seen_commit TEXT NOT NULL,\n PRIMARY KEY(identity_key, source_hash)\n );\n CREATE INDEX IF NOT EXISTS functions_path ON functions(path);\n CREATE INDEX IF NOT EXISTS functions_embedding ON functions(embedding_id);\n INSERT OR IGNORE INTO callable_provenance(identity_key, source_hash, first_seen_commit)\n SELECT identity_key, source_hash, first_seen_commit FROM functions WHERE first_seen_commit IS NOT NULL;\n `);\n const fileColumns = this.#db.prepare(\"PRAGMA table_info(files)\").all() as Array<{ name: string }>;\n if (!fileColumns.some((column) => column.name === \"previous_path\")) {\n this.#db.exec(\"ALTER TABLE files ADD COLUMN previous_path TEXT\");\n }\n const functionColumns = this.#db.prepare(\"PRAGMA table_info(functions)\").all() as Array<{ name: string }>;\n const needsLineCount = !functionColumns.some((column) => column.name === \"line_count\");\n const schemaVersion = this.#metadata(\"schema_version\");\n if (needsLineCount || schemaVersion === \"1\") {\n this.#transaction(() => {\n if (needsLineCount) this.#db.exec(\"ALTER TABLE functions ADD COLUMN line_count INTEGER NOT NULL DEFAULT 1\");\n this.#db.exec(\"UPDATE functions SET line_count = end_line - start_line + 1\");\n if (schemaVersion === \"1\") this.#setMetadata(\"schema_version\", SCHEMA_VERSION);\n });\n }\n }\n\n #metadata(key: string): string | null {\n const row = this.#db.prepare(\"SELECT value FROM metadata WHERE key = ?\").get(key) as { value: string } | undefined;\n return row?.value ?? null;\n }\n\n #setMetadata(key: string, value: string): void {\n this.#db.prepare(`\n INSERT INTO metadata(key, value) VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n `).run(key, value);\n }\n\n #deleteMetadata(key: string): void {\n this.#db.prepare(\"DELETE FROM metadata WHERE key = ?\").run(key);\n }\n\n #validateMetadata(readOnly: boolean): void {\n const schemaVersion = this.#metadata(\"schema_version\");\n if (readOnly && !schemaVersion) throw new IncompatibleIndexError(\"Target file is not a slopdex index.\");\n if (schemaVersion && schemaVersion !== SCHEMA_VERSION) {\n throw new IncompatibleIndexError(`Unsupported index schema version ${schemaVersion}.`);\n }\n const storedRoot = this.#metadata(\"root_dir\");\n if (readOnly && !storedRoot) throw new IncompatibleIndexError(\"Target index has no repository identity.\");\n if (storedRoot && path.resolve(storedRoot) !== this.#rootDir) {\n throw new IncompatibleIndexError(`Index belongs to ${storedRoot}, not ${this.#rootDir}.`);\n }\n const profileJson = JSON.stringify(this.#profile);\n const storedProfile = this.#metadata(\"embedding_profile\");\n if (readOnly && !storedProfile) throw new IncompatibleIndexError(\"Target index has no embedding profile.\");\n if (storedProfile && storedProfile !== profileJson) {\n throw new IncompatibleIndexError(\"Embedding provider, model, dimensions, or strategy differs from this index.\");\n }\n if (readOnly) return;\n this.#transaction(() => {\n this.#setMetadata(\"schema_version\", SCHEMA_VERSION);\n this.#setMetadata(\"root_dir\", this.#rootDir);\n this.#setMetadata(\"embedding_profile\", profileJson);\n if (!this.#metadata(\"generation\")) this.#setMetadata(\"generation\", \"0\");\n });\n }\n\n #transaction<T>(operation: () => T): T {\n this.#db.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = operation();\n this.#db.exec(\"COMMIT\");\n return result;\n } catch (error) {\n this.#db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n public getCheckpoint(): string | null {\n return this.#metadata(\"git_checkpoint\");\n }\n\n public getGeneration(): number {\n return Number(this.#metadata(\"generation\") ?? 0);\n }\n\n public getWorkingTreeFiles(): Array<{ path: string; previousPath: string | null }> {\n return this.#db.prepare(`\n SELECT path, previous_path AS previousPath\n FROM files WHERE source_mode = 'working-tree' ORDER BY path\n `).all() as Array<{ path: string; previousPath: string | null }>;\n }\n\n public getFileStates(): IndexedFileState[] {\n return this.#db.prepare(`\n SELECT path, content_hash AS contentHash, blob_oid AS blobOid,\n source_mode AS sourceMode, previous_path AS previousPath\n FROM files ORDER BY path\n `).all() as unknown as IndexedFileState[];\n }\n\n public getEmbeddingKeys(keys: readonly string[]): Set<string> {\n const found = new Set<string>();\n const statement = this.#db.prepare(\"SELECT 1 FROM embeddings WHERE embedding_key = ?\");\n for (const key of keys) {\n if (statement.get(key)) found.add(key);\n }\n return found;\n }\n\n public applyUpdate(options: {\n files: readonly PreparedFile[];\n deletePaths: readonly string[];\n workingTree?: {\n files: readonly PreparedFile[];\n deletePaths: readonly string[];\n };\n checkpoint?: string | null;\n expectedCheckpoint?: string | null;\n expectedGeneration?: number;\n }): UpdateStats {\n return this.#transaction(() => {\n if (options.expectedCheckpoint !== undefined && this.getCheckpoint() !== options.expectedCheckpoint) {\n throw new CodeIndexError(\"Git checkpoint changed while the update was being prepared.\");\n }\n if (options.expectedGeneration !== undefined && this.getGeneration() !== options.expectedGeneration) {\n throw new CodeIndexError(\"Index changed while the update was being prepared; retry the update.\");\n }\n\n const stats: UpdateStats = {\n filesUpdated: 0,\n filesDeleted: 0,\n functionsAdded: 0,\n functionsUpdated: 0,\n functionsDeleted: 0,\n embeddingsCreated: 0,\n checkpoint: options.checkpoint !== undefined ? options.checkpoint : this.getCheckpoint(),\n };\n\n const deleteFile = this.#db.prepare(\"DELETE FROM files WHERE path = ?\");\n const countFunctions = this.#db.prepare(\"SELECT COUNT(*) AS count FROM functions WHERE path = ?\");\n const applyStage = (files: readonly PreparedFile[], deletePaths: readonly string[]): void => {\n stats.filesUpdated += files.length;\n const uniqueDeletes = new Set(deletePaths);\n for (const file of files) {\n uniqueDeletes.delete(file.path);\n if (file.previousPath) uniqueDeletes.delete(file.previousPath);\n if (file.replacePath) uniqueDeletes.delete(file.replacePath);\n }\n for (const filePath of uniqueDeletes) {\n const count = Number((countFunctions.get(filePath) as { count: number }).count);\n const result = deleteFile.run(filePath);\n if (result.changes > 0) {\n stats.filesDeleted += 1;\n stats.functionsDeleted += count;\n }\n }\n\n for (const file of files) this.#replaceFile(file, stats);\n };\n\n applyStage(options.files, options.deletePaths);\n if (options.workingTree) applyStage(options.workingTree.files, options.workingTree.deletePaths);\n\n const generation = this.getGeneration() + 1;\n this.#setMetadata(\"generation\", String(generation));\n if (options.checkpoint === null) this.#deleteMetadata(\"git_checkpoint\");\n else if (options.checkpoint !== undefined) this.#setMetadata(\"git_checkpoint\", options.checkpoint);\n return stats;\n });\n }\n\n #replaceFile(file: PreparedFile, stats: UpdateStats): void {\n const sourcePath = file.replacePath ?? file.previousPath ?? file.path;\n const oldRows = this.#rowsForPath(sourcePath);\n const existingFile = this.#db.prepare(\"SELECT previous_path FROM files WHERE path = ?\").get(sourcePath) as\n | { previous_path: string | null }\n | undefined;\n const oldMatches = reconcileFunctions(file.callables, oldRows);\n\n if (sourcePath !== file.path) {\n const displacedRows = this.#rowsForPath(file.path);\n const displaced = this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(file.path);\n if (displaced.changes > 0) {\n stats.filesDeleted += 1;\n stats.functionsDeleted += displacedRows.length;\n }\n this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(sourcePath);\n } else {\n this.#db.prepare(\"DELETE FROM files WHERE path = ?\").run(file.path);\n }\n this.#db.prepare(`\n INSERT INTO files(path, content_hash, blob_oid, source_mode, indexed_commit, previous_path, language, byte_size)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n file.path,\n file.contentHash,\n file.blobOid,\n file.sourceMode,\n file.indexedCommit,\n file.sourceMode === \"working-tree\" ? file.previousPath ?? existingFile?.previous_path ?? null : null,\n file.language,\n file.byteSize,\n );\n\n const usedIds = new Set<number>();\n const orderedCallables = [\n ...file.callables.filter((callable) => oldMatches.has(callable)),\n ...file.callables.filter((callable) => !oldMatches.has(callable)),\n ];\n for (const callable of orderedCallables) {\n if (callable.vector) {\n const result = this.#db.prepare(\"INSERT OR IGNORE INTO embeddings(embedding_key, vector) VALUES (?, ?)\")\n .run(callable.embeddingKey, vectorBuffer(callable.vector));\n stats.embeddingsCreated += Number(result.changes);\n }\n const embedding = this.#db.prepare(\"SELECT id FROM embeddings WHERE embedding_key = ?\").get(callable.embeddingKey) as { id: number } | undefined;\n if (!embedding) throw new CodeIndexError(`Missing embedding for ${callable.qualifiedName}.`);\n\n const old = oldMatches.get(callable);\n if (old) usedIds.add(old.id);\n const remembered = this.#db.prepare(`\n SELECT first_seen_commit FROM callable_provenance WHERE identity_key = ? AND source_hash = ?\n `).get(callable.identityKey, callable.sourceHash) as { first_seen_commit: string } | undefined;\n const firstSeenCommit = old?.first_seen_commit ?? remembered?.first_seen_commit ?? file.indexedCommit;\n this.#db.prepare(`\n INSERT INTO functions(\n id, path, language, kind, name, qualified_name, signature, identity_key,\n start_line, start_column, end_line, end_column, line_count, source, source_hash,\n embedding_input, first_seen_commit, last_seen_commit, source_mode, embedding_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n old?.id ?? null,\n file.path,\n callable.language,\n callable.kind,\n callable.name,\n callable.qualifiedName,\n callable.signature,\n callable.identityKey,\n callable.startLine,\n callable.startColumn,\n callable.endLine,\n callable.endColumn,\n callable.lineCount,\n callable.source,\n callable.sourceHash,\n callable.embeddingInput,\n firstSeenCommit,\n file.indexedCommit,\n file.sourceMode,\n embedding.id,\n );\n if (old) stats.functionsUpdated += 1;\n else stats.functionsAdded += 1;\n if (firstSeenCommit) {\n this.#db.prepare(`\n INSERT OR IGNORE INTO callable_provenance(identity_key, source_hash, first_seen_commit) VALUES (?, ?, ?)\n `).run(callable.identityKey, callable.sourceHash, firstSeenCommit);\n }\n }\n stats.functionsDeleted += oldRows.length - usedIds.size;\n }\n\n #rowsForPath(filePath: string): FunctionRow[] {\n return this.#db.prepare(\"SELECT * FROM functions WHERE path = ? ORDER BY start_line, start_column, id\").all(filePath) as unknown as FunctionRow[];\n }\n\n public allFunctions(): IndexedFunction[] {\n return (this.#db.prepare(\"SELECT * FROM functions ORDER BY path, start_line, start_column, id\").all() as unknown as FunctionRow[])\n .map(toIndexedFunction);\n }\n\n public allFilePaths(): string[] {\n return (this.#db.prepare(\"SELECT path FROM files ORDER BY path\").all() as Array<{ path: string }>).map((row) => row.path);\n }\n\n public previousPath(filePath: string): string | null {\n const row = this.#db.prepare(\"SELECT previous_path FROM files WHERE path = ?\").get(filePath) as\n | { previous_path: string | null }\n | undefined;\n return row?.previous_path ?? null;\n }\n\n public functionsForPaths(paths: readonly string[]): IndexedFunction[] {\n const results: IndexedFunction[] = [];\n for (const filePath of paths) results.push(...this.#rowsForPath(filePath).map(toIndexedFunction));\n return results;\n }\n\n public searchVector(vector: readonly number[], options: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludeId?: number;\n excludePaths?: readonly string[];\n minLines?: number;\n nameRegex?: string;\n }): Array<{ function: IndexedFunction; similarity: number }> {\n const excludePaths = options.excludePaths ?? [];\n const pathFilter = excludePaths.length > 0\n ? `AND f.path NOT IN (${excludePaths.map(() => \"?\").join(\", \")})`\n : \"\";\n const rows = this.#db.prepare(`\n SELECT f.*, 1.0 - vec_distance_cosine(e.vector, ?) AS similarity\n FROM functions f\n JOIN embeddings e ON e.id = f.embedding_id\n WHERE (? IS NULL OR f.id != ?)\n ${pathFilter}\n AND f.line_count >= ?\n AND (? IS NULL OR slopdex_regexp(?, f.qualified_name))\n AND (1.0 - vec_distance_cosine(e.vector, ?)) >= ?\n AND (? IS NULL OR (1.0 - vec_distance_cosine(e.vector, ?)) < ?)\n ORDER BY similarity DESC, f.id ASC\n LIMIT ?\n `).all(\n vectorBuffer(vector),\n options.excludeId ?? null,\n options.excludeId ?? null,\n ...excludePaths,\n options.minLines ?? 1,\n options.nameRegex ?? null,\n options.nameRegex ?? null,\n vectorBuffer(vector),\n options.minSimilarity,\n options.maxSimilarity ?? null,\n vectorBuffer(vector),\n options.maxSimilarity ?? null,\n options.limit,\n ) as unknown as Array<FunctionRow & { similarity: number }>;\n return rows.map((row) => ({ function: toIndexedFunction(row), similarity: row.similarity }));\n }\n\n public vectorForFunction(id: number): number[] {\n const row = this.#db.prepare(`\n SELECT e.vector FROM functions f JOIN embeddings e ON e.id = f.embedding_id WHERE f.id = ?\n `).get(id) as { vector: Uint8Array } | undefined;\n if (!row) throw new CodeIndexError(`Function ${id} does not exist.`);\n return Array.from(new Float32Array(row.vector.buffer, row.vector.byteOffset, row.vector.byteLength / 4));\n }\n\n public status(): IndexStatus {\n const functionCount = Number((this.#db.prepare(\"SELECT COUNT(*) AS count FROM functions\").get() as { count: number }).count);\n const fileCount = Number((this.#db.prepare(\"SELECT COUNT(*) AS count FROM files\").get() as { count: number }).count);\n return {\n rootDir: this.#rootDir,\n indexPath: this.#indexPath,\n functionCount,\n fileCount,\n generation: this.getGeneration(),\n gitCheckpoint: this.getCheckpoint(),\n embeddingProfile: this.#profile,\n };\n }\n}\n\nfunction vectorBuffer(vector: readonly number[]): Uint8Array {\n const values = Float32Array.from(vector);\n return new Uint8Array(values.buffer);\n}\n\nfunction toIndexedFunction(row: FunctionRow): IndexedFunction {\n return {\n id: row.id,\n path: row.path,\n language: row.language,\n kind: row.kind,\n name: row.name,\n qualifiedName: row.qualified_name,\n signature: row.signature,\n identityKey: row.identity_key,\n startLine: row.start_line,\n startColumn: row.start_column,\n endLine: row.end_line,\n endColumn: row.end_column,\n lineCount: row.line_count,\n source: row.source,\n sourceHash: row.source_hash,\n embeddingInput: row.embedding_input,\n firstSeenCommit: row.first_seen_commit,\n lastSeenCommit: row.last_seen_commit,\n sourceMode: row.source_mode,\n embeddingId: row.embedding_id,\n };\n}\n\nfunction reconcileFunctions(\n current: readonly PreparedCallable[],\n previous: readonly FunctionRow[],\n): Map<PreparedCallable, FunctionRow> {\n const matches = new Map<PreparedCallable, FunctionRow>();\n const keys = new Set([\n ...current.map((callable) => `${callable.qualifiedName}\\0${callable.kind}`),\n ...previous.map((callable) => `${callable.qualified_name}\\0${callable.kind}`),\n ]);\n for (const key of keys) {\n const currentGroup = current.filter((callable) => `${callable.qualifiedName}\\0${callable.kind}` === key);\n const previousGroup = previous.filter((callable) => `${callable.qualified_name}\\0${callable.kind}` === key);\n const unmatchedPrevious = new Set(previousGroup);\n const unmatchedCurrent = new Set(currentGroup);\n for (const callable of currentGroup) {\n const exact = [...unmatchedPrevious].find((old) => old.source_hash === callable.sourceHash);\n if (exact) {\n matches.set(callable, exact);\n unmatchedPrevious.delete(exact);\n unmatchedCurrent.delete(callable);\n }\n }\n for (const callable of unmatchedCurrent) {\n const old = unmatchedPrevious.values().next().value as FunctionRow | undefined;\n if (!old) break;\n matches.set(callable, old);\n unmatchedPrevious.delete(old);\n }\n }\n return matches;\n}\n","import path from \"node:path\";\n\nimport { CodeIndexError } from \"../errors.js\";\nimport type {\n CohesionAnalysisOptions,\n CohesionFileReport,\n CohesionGroup,\n CohesionLocation,\n CohesionPair,\n CohesionReport,\n IndexedFunction,\n SimilarityResult,\n} from \"../types.js\";\nimport { assertPositiveInteger, throwIfAborted } from \"../utils.js\";\n\ninterface CandidateEdge {\n left: IndexedFunction;\n right: IndexedFunction;\n similarity: number;\n}\n\nexport async function analyzeCohesion(options: CohesionAnalysisOptions): Promise<CohesionReport> {\n const neighbors = options.neighbors ?? 20;\n const limit = options.limit ?? 50;\n const minSimilarity = options.minSimilarity ?? 0.8;\n const minLines = options.minLines ?? 2;\n const sourceFilter = options.sourceFilter ?? { type: \"all\" };\n assertPositiveInteger(neighbors, \"neighbors\");\n assertPositiveInteger(limit, \"limit\");\n assertPositiveInteger(minLines, \"minLines\");\n if (!Number.isFinite(minSimilarity) || minSimilarity < -1 || minSimilarity >= 1) {\n throw new CodeIndexError(\"minSimilarity must be at least -1 and less than 1.\");\n }\n if (options.maxSimilarity !== undefined\n && (!Number.isFinite(options.maxSimilarity) || options.maxSimilarity <= minSimilarity)) {\n throw new CodeIndexError(\"maxSimilarity must be greater than minSimilarity.\");\n }\n const nameRegex = compileNameRegex(options.nameRegex);\n const candidateFunctions = options.source.allFunctions()\n .filter((callable) => callable.lineCount >= minLines && (!nameRegex || nameRegex.test(callable.qualifiedName)));\n const candidateIds = new Set(candidateFunctions.map((callable) => callable.id));\n const sourceFunctions = (await options.source.sourceFunctions(sourceFilter))\n .filter((callable) => candidateIds.has(callable.id));\n\n const neighborCache = new Map<number, Set<number>>();\n const neighborsFor = (callable: IndexedFunction): SimilarityResult[] => {\n throwIfAborted(options.signal);\n const matches = options.source.similarToFunction(callable.id, {\n limit: neighbors,\n minSimilarity,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n minLines,\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n }).filter((match) => candidateIds.has(match.function.id));\n neighborCache.set(callable.id, new Set(matches.map((match) => match.function.id)));\n return matches;\n };\n\n const edges = new Map<string, CandidateEdge>();\n for (let index = 0; index < sourceFunctions.length; index += 1) {\n const source = sourceFunctions[index]!;\n for (const match of neighborsFor(source)) {\n const [left, right] = orderedFunctions(source, match.function);\n const key = pairKey(left.id, right.id);\n const existing = edges.get(key);\n if (!existing || match.similarity > existing.similarity) {\n edges.set(key, { left, right, similarity: match.similarity });\n }\n }\n options.onProgress?.({ completed: index + 1, total: sourceFunctions.length });\n }\n\n const scoredPairs = [...edges.values()].map((edge) => {\n const leftNeighbors = neighborCache.get(edge.left.id);\n const rightNeighbors = neighborCache.get(edge.right.id);\n const reciprocal = leftNeighbors && rightNeighbors\n ? leftNeighbors.has(edge.right.id) && rightNeighbors.has(edge.left.id)\n : null;\n return scorePair(edge, reciprocal, minSimilarity);\n }).sort(comparePairs);\n scoredPairs.forEach((pair, index) => {\n pair.rank = index + 1;\n });\n\n const repositoryScope = sourceFilter.type === \"all\" && sourceFilter.path === undefined;\n const summary = summarize(\n repositoryScope ? \"repository\" : \"selected-sources\",\n sourceFunctions.length,\n candidateFunctions.length,\n scoredPairs,\n );\n const reportedPairs = scoredPairs.slice(0, limit);\n const files = summarizeFiles(sourceFunctions, scoredPairs)\n .filter((file) => file.internalAffinity + file.sameFolderAffinity + file.externalAffinity > 0)\n .slice(0, limit);\n const groups = buildGroups(reportedPairs);\n const status = options.source.status();\n return {\n schemaVersion: 1,\n repository: {\n generation: status.generation,\n gitCheckpoint: status.gitCheckpoint,\n embeddingProfile: status.embeddingProfile,\n },\n parameters: {\n neighbors,\n limit,\n minSimilarity,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n minLines,\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n sourceFilter,\n },\n summary,\n pairs: reportedPairs,\n files,\n groups,\n };\n}\n\nexport function cohesionLocation(leftPath: string, rightPath: string): CohesionLocation {\n const normalizedLeft = leftPath.replaceAll(\"\\\\\", \"/\");\n const normalizedRight = rightPath.replaceAll(\"\\\\\", \"/\");\n const leftDirectory = directoryParts(normalizedLeft);\n const rightDirectory = directoryParts(normalizedRight);\n let commonLength = 0;\n while (commonLength < leftDirectory.length\n && commonLength < rightDirectory.length\n && leftDirectory[commonLength] === rightDirectory[commonLength]) {\n commonLength += 1;\n }\n const commonParts = leftDirectory.slice(0, commonLength);\n const commonAncestor = commonParts.length > 0 ? commonParts.join(\"/\") : null;\n const sameFile = normalizedLeft === normalizedRight;\n const folderHops = sameFile\n ? 0\n : leftDirectory.length - commonLength + rightDirectory.length - commonLength;\n return {\n category: sameFile ? \"same-file\" : folderHops === 0 ? \"same-folder\" : \"different-folder\",\n physicalDistance: sameFile ? 0 : 1 + folderHops,\n folderHops,\n commonAncestor,\n sourceTestPair: isTestPath(normalizedLeft) !== isTestPath(normalizedRight),\n };\n}\n\nfunction scorePair(edge: CandidateEdge, reciprocal: boolean | null, minSimilarity: number): CohesionPair {\n const location = cohesionLocation(edge.left.path, edge.right.path);\n const semanticWeight = clamp((edge.similarity - minSimilarity) / (1 - minSimilarity));\n const separationWeight = 1 - Math.exp(-location.physicalDistance / 2);\n return {\n rank: 0,\n left: edge.left,\n right: edge.right,\n similarity: edge.similarity,\n reciprocal,\n semanticWeight,\n separationWeight,\n cohesionGap: semanticWeight * separationWeight,\n location,\n };\n}\n\nfunction summarize(\n scope: CohesionReport[\"summary\"][\"scope\"],\n functionsAnalyzed: number,\n candidateFunctions: number,\n pairs: readonly CohesionPair[],\n): CohesionReport[\"summary\"] {\n const totalWeight = pairs.reduce((sum, pair) => sum + pair.semanticWeight, 0);\n const sameFileWeight = pairs\n .filter((pair) => pair.location.category === \"same-file\")\n .reduce((sum, pair) => sum + pair.semanticWeight, 0);\n const sameFolderWeight = pairs\n .filter((pair) => pair.location.category === \"same-folder\")\n .reduce((sum, pair) => sum + pair.semanticWeight, 0);\n const remoteWeight = pairs\n .filter((pair) => pair.location.category === \"different-folder\")\n .reduce((sum, pair) => sum + pair.semanticWeight, 0);\n const weightedDistance = pairs.reduce(\n (sum, pair) => sum + pair.semanticWeight * pair.location.physicalDistance,\n 0,\n );\n return {\n scope,\n functionsAnalyzed,\n candidateFunctions,\n semanticEdges: pairs.length,\n sameFileRatio: ratio(sameFileWeight, totalWeight),\n sameFolderRatio: ratio(sameFolderWeight, totalWeight),\n remoteRatio: ratio(remoteWeight, totalWeight),\n weightedMeanDistance: ratio(weightedDistance, totalWeight),\n };\n}\n\nfunction summarizeFiles(\n sourceFunctions: readonly IndexedFunction[],\n pairs: readonly CohesionPair[],\n): CohesionFileReport[] {\n const sourceIds = new Set(sourceFunctions.map((callable) => callable.id));\n const counts = new Map<string, number>();\n for (const callable of sourceFunctions) counts.set(callable.path, (counts.get(callable.path) ?? 0) + 1);\n const reports = new Map<string, CohesionFileReport>();\n for (const [filePath, functionCount] of counts) {\n reports.set(filePath, {\n path: filePath,\n functionCount,\n internalAffinity: 0,\n sameFolderAffinity: 0,\n externalAffinity: 0,\n externalAffinityRatio: 0,\n });\n }\n for (const pair of pairs) {\n if (sourceIds.has(pair.left.id)) addFileAffinity(reports.get(pair.left.path)!, pair.right, pair);\n if (sourceIds.has(pair.right.id)) addFileAffinity(reports.get(pair.right.path)!, pair.left, pair);\n }\n for (const report of reports.values()) {\n const total = report.internalAffinity + report.sameFolderAffinity + report.externalAffinity;\n report.externalAffinityRatio = ratio(report.externalAffinity, total);\n }\n return [...reports.values()].sort((left, right) => right.externalAffinityRatio - left.externalAffinityRatio\n || right.externalAffinity - left.externalAffinity\n || left.path.localeCompare(right.path));\n}\n\nfunction addFileAffinity(\n report: CohesionFileReport,\n match: IndexedFunction,\n pair: CohesionPair,\n): void {\n if (pair.location.category === \"same-file\") report.internalAffinity += pair.semanticWeight;\n else if (pair.location.category === \"same-folder\") report.sameFolderAffinity += pair.semanticWeight;\n else {\n report.externalAffinity += pair.semanticWeight;\n updateStrongestExternal(report, match, pair);\n }\n}\n\nfunction updateStrongestExternal(\n report: CohesionFileReport,\n callable: IndexedFunction,\n pair: CohesionPair,\n): void {\n if (!report.strongestExternalMatch || pair.cohesionGap > report.strongestExternalMatch.cohesionGap) {\n report.strongestExternalMatch = {\n function: callable,\n similarity: pair.similarity,\n cohesionGap: pair.cohesionGap,\n };\n }\n}\n\nfunction buildGroups(pairs: readonly CohesionPair[]): CohesionGroup[] {\n const functions = new Map<number, IndexedFunction>();\n const neighbors = new Map<number, Set<number>>();\n for (const pair of pairs) {\n functions.set(pair.left.id, pair.left);\n functions.set(pair.right.id, pair.right);\n addNeighbor(neighbors, pair.left.id, pair.right.id);\n addNeighbor(neighbors, pair.right.id, pair.left.id);\n }\n const seen = new Set<number>();\n const groups: CohesionGroup[] = [];\n for (const start of neighbors.keys()) {\n if (seen.has(start)) continue;\n const pending = [start];\n const memberIds = new Set<number>();\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (seen.has(id)) continue;\n seen.add(id);\n memberIds.add(id);\n for (const neighbor of neighbors.get(id) ?? []) pending.push(neighbor);\n }\n const groupPairs = pairs.filter((pair) => memberIds.has(pair.left.id) && memberIds.has(pair.right.id));\n const members = [...memberIds].map((id) => functions.get(id)!).sort(compareFunctions);\n groups.push({\n rank: 0,\n memberCount: members.length,\n fileCount: new Set(members.map((member) => member.path)).size,\n minimumEdgeSimilarity: Math.min(...groupPairs.map((pair) => pair.similarity)),\n maximumEdgeSimilarity: Math.max(...groupPairs.map((pair) => pair.similarity)),\n maximumPhysicalDistance: Math.max(...groupPairs.map((pair) => pair.location.physicalDistance)),\n maximumCohesionGap: Math.max(...groupPairs.map((pair) => pair.cohesionGap)),\n members,\n });\n }\n groups.sort((left, right) => right.maximumCohesionGap - left.maximumCohesionGap\n || right.memberCount - left.memberCount\n || compareFunctions(left.members[0]!, right.members[0]!));\n groups.forEach((group, index) => {\n group.rank = index + 1;\n });\n return groups;\n}\n\nfunction compileNameRegex(pattern: string | undefined): RegExp | undefined {\n if (pattern === undefined) return undefined;\n try {\n return new RegExp(pattern);\n } catch (error) {\n throw new CodeIndexError(`Invalid name regex: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nfunction directoryParts(filePath: string): string[] {\n const directory = path.posix.dirname(filePath.replaceAll(\"\\\\\", \"/\"));\n return directory === \".\" ? [] : directory.split(\"/\").filter(Boolean);\n}\n\nfunction isTestPath(filePath: string): boolean {\n const normalized = filePath.replaceAll(\"\\\\\", \"/\").toLowerCase();\n const segments = normalized.split(\"/\");\n const fileName = segments.at(-1) ?? \"\";\n return segments.some((segment) => segment === \"test\" || segment === \"tests\" || segment === \"__tests__\")\n || /\\.(?:test|spec)\\.[cm]?[jt]sx?$/.test(fileName);\n}\n\nfunction orderedFunctions(left: IndexedFunction, right: IndexedFunction): [IndexedFunction, IndexedFunction] {\n return compareFunctions(left, right) <= 0 ? [left, right] : [right, left];\n}\n\nfunction compareFunctions(left: IndexedFunction, right: IndexedFunction): number {\n return left.path.localeCompare(right.path)\n || left.startLine - right.startLine\n || left.startColumn - right.startColumn\n || left.qualifiedName.localeCompare(right.qualifiedName)\n || left.id - right.id;\n}\n\nfunction comparePairs(left: CohesionPair, right: CohesionPair): number {\n return right.cohesionGap - left.cohesionGap\n || right.similarity - left.similarity\n || Number(right.reciprocal === true) - Number(left.reciprocal === true)\n || compareFunctions(left.left, right.left)\n || compareFunctions(left.right, right.right);\n}\n\nfunction pairKey(leftId: number, rightId: number): string {\n return leftId < rightId ? `${leftId}:${rightId}` : `${rightId}:${leftId}`;\n}\n\nfunction addNeighbor(neighbors: Map<number, Set<number>>, source: number, target: number): void {\n const values = neighbors.get(source) ?? new Set<number>();\n values.add(target);\n neighbors.set(source, values);\n}\n\nfunction ratio(numerator: number, denominator: number): number {\n return denominator === 0 ? 0 : numerator / denominator;\n}\n\nfunction clamp(value: number): number {\n return Math.max(0, Math.min(1, value));\n}\n","import { CodeIndexError } from \"../errors.js\";\nimport { normalizeEmbeddingVector } from \"../utils.js\";\n\ninterface EmbeddingResponse {\n data?: Array<{ index?: number; embedding?: number[] }>;\n}\n\nexport async function requestEmbeddings(options: {\n url: string;\n apiKey: string;\n body: Record<string, unknown>;\n expectedCount: number;\n dimensions: number;\n signal?: AbortSignal;\n}): Promise<number[][]> {\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n const response = await fetch(options.url, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(options.body),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n const detail = (await response.text()).slice(0, 500);\n const error = new CodeIndexError(`Embedding request failed (${response.status}): ${detail}`);\n if (response.status !== 429 && response.status < 500) throw error;\n lastError = error;\n } else {\n const payload = await response.json() as EmbeddingResponse;\n if (!Array.isArray(payload.data) || payload.data.length !== options.expectedCount) {\n throw new CodeIndexError(\"Embedding provider returned an unexpected number of vectors.\");\n }\n const indexes = payload.data.map((item) => item.index);\n if (indexes.some((index) => !Number.isInteger(index))\n || new Set(indexes).size !== options.expectedCount\n || indexes.some((index) => index! < 0 || index! >= options.expectedCount)) {\n throw new CodeIndexError(\"Embedding provider returned invalid vector indexes.\");\n }\n const ordered = new Array<{ index?: number; embedding?: number[] }>(options.expectedCount);\n for (const item of payload.data) ordered[item.index!] = item;\n try {\n return ordered.map((item) => normalizeEmbeddingVector(item.embedding, options.dimensions));\n } catch {\n throw new CodeIndexError(\"Embedding provider returned a malformed vector.\");\n }\n }\n } catch (error) {\n if (options.signal?.aborted) throw error;\n lastError = error;\n if (error instanceof CodeIndexError && !/\\((429|5\\d\\d)\\)/.test(error.message)) throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, 250 * 2 ** attempt));\n }\n throw new CodeIndexError(\"Embedding request failed after three attempts.\", { cause: lastError });\n}\n","import type { EmbeddingProvider } from \"../types.js\";\nimport { requestEmbeddings } from \"./http.js\";\n\nexport interface JinaEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n}\n\nexport class JinaEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #url: string;\n\n public constructor(options: JinaEmbeddingProviderOptions = {}) {\n this.#apiKey = options.apiKey ?? process.env.JINA_API_KEY ?? \"\";\n if (!this.#apiKey) throw new Error(\"JINA_API_KEY is required.\");\n const model = options.model ?? \"jina-embeddings-v4\";\n const dimensions = options.dimensions ?? 1024;\n if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error(\"dimensions must be a positive integer.\");\n this.profile = {\n provider: \"jina\",\n model,\n dimensions,\n strategyVersion: \"callable-v1:code-query-passage\",\n } as const;\n this.#url = options.baseUrl ?? \"https://api.jina.ai/v1/embeddings\";\n }\n\n public embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return Promise.resolve([]);\n return this.#embed(inputs, \"code.passage\", options?.signal);\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n return (await this.#embed([input], \"code.query\", options?.signal))[0]!;\n }\n\n #embed(inputs: readonly string[], task: \"code.passage\" | \"code.query\", signal?: AbortSignal): Promise<number[][]> {\n return requestEmbeddings({\n url: this.#url,\n apiKey: this.#apiKey,\n body: {\n model: this.profile.model,\n dimensions: this.profile.dimensions,\n embedding_type: \"float\",\n truncate: true,\n task,\n input: inputs,\n },\n expectedCount: inputs.length,\n dimensions: this.profile.dimensions,\n ...(signal ? { signal } : {}),\n });\n }\n}\n","import { Tiktoken } from \"js-tiktoken/lite\";\nimport cl100kBase from \"js-tiktoken/ranks/cl100k_base\";\n\nimport type { EmbeddingProvider } from \"../types.js\";\nimport { requestEmbeddings } from \"./http.js\";\n\nconst MAX_INPUT_TOKENS = 8192;\nlet tokenizer: Tiktoken | undefined;\n\nfunction truncateInput(input: string): string {\n tokenizer ??= new Tiktoken(cl100kBase);\n const tokens = tokenizer.encode(input);\n return tokens.length <= MAX_INPUT_TOKENS ? input : tokenizer.decode(tokens.slice(0, MAX_INPUT_TOKENS));\n}\n\nexport interface OpenAIEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n}\n\nexport class OpenAIEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #url: string;\n\n public constructor(options: OpenAIEmbeddingProviderOptions = {}) {\n this.#apiKey = options.apiKey ?? process.env.OPENAI_API_KEY ?? \"\";\n if (!this.#apiKey) throw new Error(\"OPENAI_API_KEY is required.\");\n const model = options.model ?? \"text-embedding-3-large\";\n const dimensions = options.dimensions ?? 3072;\n if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error(\"dimensions must be a positive integer.\");\n this.profile = { provider: \"openai\", model, dimensions, strategyVersion: \"callable-v1\" } as const;\n this.#url = `${(options.baseUrl ?? \"https://api.openai.com/v1\").replace(/\\/$/, \"\")}/embeddings`;\n }\n\n public embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return Promise.resolve([]);\n return this.#embed(inputs, options?.signal);\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n return (await this.#embed([input], options?.signal))[0]!;\n }\n\n #embed(inputs: readonly string[], signal?: AbortSignal): Promise<number[][]> {\n return requestEmbeddings({\n url: this.#url,\n apiKey: this.#apiKey,\n body: {\n model: this.profile.model,\n dimensions: this.profile.dimensions,\n encoding_format: \"float\",\n input: inputs.map(truncateInput),\n },\n expectedCount: inputs.length,\n dimensions: this.profile.dimensions,\n ...(signal ? { signal } : {}),\n });\n }\n}\n","import type { CohesionReport, CrossSearchResult, IndexedFunction, SimilarityResult } from \"./types.js\";\n\nfunction functionName(value: Pick<IndexedFunction, \"path\" | \"qualifiedName\">): string {\n return `${value.path} :: ${value.qualifiedName}`;\n}\n\nexport function formatSimilaritySummary(\n matches: readonly SimilarityResult[],\n source?: IndexedFunction,\n): string {\n const lines = matches.map((match) => `${source ? \" \" : \"\"}${match.similarity.toFixed(4)} ${functionName(match.function)}`);\n if (!source) return lines.length > 0 ? lines.join(\"\\n\") : \"No matches.\";\n return [functionName(source), ...(lines.length > 0 ? lines : [\" No matches.\"])].join(\"\\n\");\n}\n\nexport function formatSimilarityClusters(results: readonly CrossSearchResult[], sameIndex: boolean): string {\n const nodes = new Map<string, { function: IndexedFunction; role: \"source\" | \"target\" }>();\n const neighbors = new Map<string, Set<string>>();\n const edges: Array<{ left: string; right: string; similarity: number }> = [];\n const connect = (left: string, right: string): void => {\n const leftNeighbors = neighbors.get(left) ?? new Set<string>();\n const rightNeighbors = neighbors.get(right) ?? new Set<string>();\n leftNeighbors.add(right);\n rightNeighbors.add(left);\n neighbors.set(left, leftNeighbors);\n neighbors.set(right, rightNeighbors);\n };\n\n for (const result of results) {\n const sourceKey = `${sameIndex ? \"index\" : \"source\"}:${result.source.id}`;\n nodes.set(sourceKey, { function: result.source, role: \"source\" });\n for (const match of result.matches) {\n const matchKey = `${sameIndex ? \"index\" : \"target\"}:${match.function.id}`;\n nodes.set(matchKey, { function: match.function, role: sameIndex ? \"source\" : \"target\" });\n connect(sourceKey, matchKey);\n edges.push({ left: sourceKey, right: matchKey, similarity: match.similarity });\n }\n }\n\n const seen = new Set<string>();\n const clusters: Array<{ members: Array<{ function: IndexedFunction; role: \"source\" | \"target\" }>; min: number; max: number }> = [];\n for (const start of neighbors.keys()) {\n if (seen.has(start)) continue;\n const pending = [start];\n const keys = new Set<string>();\n while (pending.length > 0) {\n const key = pending.pop()!;\n if (seen.has(key)) continue;\n seen.add(key);\n keys.add(key);\n for (const neighbor of neighbors.get(key) ?? []) pending.push(neighbor);\n }\n const similarities = edges\n .filter((edge) => keys.has(edge.left) && keys.has(edge.right))\n .map((edge) => edge.similarity);\n clusters.push({\n members: [...keys].map((key) => nodes.get(key)!).sort((left, right) => (\n clusterFunctionName(left, sameIndex).localeCompare(clusterFunctionName(right, sameIndex))\n )),\n min: Math.min(...similarities),\n max: Math.max(...similarities),\n });\n }\n clusters.sort((left, right) => right.members.length - left.members.length\n || clusterFunctionName(left.members[0]!, sameIndex).localeCompare(clusterFunctionName(right.members[0]!, sameIndex)));\n if (clusters.length === 0) return \"No clusters.\";\n return clusters.map((cluster, index) => {\n const similarity = cluster.min === cluster.max\n ? cluster.min.toFixed(4)\n : `${cluster.min.toFixed(4)}-${cluster.max.toFixed(4)}`;\n return [\n `Cluster ${index + 1} (${cluster.members.length} functions, similarity ${similarity})`,\n ...cluster.members.map((member) => ` ${clusterFunctionName(member, sameIndex)}`),\n ].join(\"\\n\");\n }).join(\"\\n\\n\");\n}\n\nexport function formatCohesionSummary(report: CohesionReport): string {\n const { summary } = report;\n const edgeLabel = summary.semanticEdges === 1 ? \"edge\" : \"edges\";\n const lines = [\n `Cohesion: ${summary.functionsAnalyzed} functions analyzed, ${summary.semanticEdges} semantic ${edgeLabel}`,\n ` same file ${(summary.sameFileRatio * 100).toFixed(1)}% same folder ${(summary.sameFolderRatio * 100).toFixed(1)}% remote ${(summary.remoteRatio * 100).toFixed(1)}% mean distance ${summary.weightedMeanDistance.toFixed(2)}`,\n ];\n if (report.pairs.length === 0) return [...lines, \"No cohesion gaps.\"].join(\"\\n\");\n lines.push(\"\");\n for (const pair of report.pairs) {\n lines.push(\n `${pair.rank}. gap ${pair.cohesionGap.toFixed(4)} similarity ${pair.similarity.toFixed(4)} distance ${pair.location.physicalDistance}${pair.reciprocal ? \" reciprocal\" : \"\"}`,\n ` ${functionLocation(pair.left)}`,\n ` ${functionLocation(pair.right)}`,\n );\n }\n return lines.join(\"\\n\");\n}\n\nfunction clusterFunctionName(\n member: { function: IndexedFunction; role: \"source\" | \"target\" },\n sameIndex: boolean,\n): string {\n const role = sameIndex ? \"\" : `[${member.role}] `;\n return `${role}${member.function.path}:${member.function.startLine}:${member.function.startColumn} :: ${member.function.qualifiedName}`;\n}\n\nfunction functionLocation(value: IndexedFunction): string {\n return `${value.path}:${value.startLine}:${value.startColumn} :: ${value.qualifiedName}`;\n}\n","import { realpath, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { CodeIndexError, IncompatibleIndexError } from \"../errors.js\";\nimport type { CrossSearchOptions, CrossSearchResult } from \"../types.js\";\nimport { assertPositiveInteger, throwIfAborted } from \"../utils.js\";\n\nexport async function* crossSearch(options: CrossSearchOptions): AsyncGenerator<CrossSearchResult> {\n const target = options.target ?? options.source;\n const sourceProfile = JSON.stringify(options.source.status().embeddingProfile);\n const targetProfile = JSON.stringify(target.status().embeddingProfile);\n if (sourceProfile !== targetProfile) {\n throw new IncompatibleIndexError(\"Cross-search requires identical embedding profiles.\");\n }\n\n const limit = options.limitPerFunction ?? 5;\n assertPositiveInteger(limit, \"limitPerFunction\");\n const minLines = options.minLines ?? 2;\n assertPositiveInteger(minLines, \"minLines\");\n const nameRegex = compileNameRegex(options.nameRegex);\n const sourceFunctions = (await options.source.sourceFunctions(options.sourceFilter ?? { type: \"all\" }))\n .filter((callable) => callable.lineCount >= minLines && (!nameRegex || nameRegex.test(callable.qualifiedName)));\n const sameIndex = target.indexPath === options.source.indexPath\n || await fileIdentity(target.indexPath) === await fileIdentity(options.source.indexPath);\n const sourceRoot = options.crossFileOnly ? await canonicalRoot(options.source.rootDir) : undefined;\n const targetRoot = options.crossFileOnly\n ? sameIndex ? sourceRoot! : await canonicalRoot(target.rootDir)\n : undefined;\n const canonicalFiles = new Map<string, Promise<string>>();\n const canonicalFile = (root: string, filePath: string): Promise<string> => {\n const absolutePath = path.resolve(root, filePath);\n let result = canonicalFiles.get(absolutePath);\n if (!result) {\n result = fileIdentity(absolutePath);\n canonicalFiles.set(absolutePath, result);\n }\n return result;\n };\n const targetPathsByCanonicalFile = new Map<string, string[]>();\n if (targetRoot) {\n const targetPaths = [...new Set(target.allFunctions().map((callable) => callable.path))];\n await Promise.all(targetPaths.map(async (targetPath) => {\n const canonicalPath = await canonicalFile(targetRoot, targetPath);\n const paths = targetPathsByCanonicalFile.get(canonicalPath) ?? [];\n paths.push(targetPath);\n targetPathsByCanonicalFile.set(canonicalPath, paths);\n }));\n }\n const seenPairs = new Set<string>();\n for (let index = 0; index < sourceFunctions.length; index += 1) {\n throwIfAborted(options.signal);\n const source = sourceFunctions[index]!;\n const vector = options.source.vectorForFunction(source.id);\n const canonicalSourceFile = sourceRoot ? await canonicalFile(sourceRoot, source.path) : undefined;\n const excludedTargetPaths = canonicalSourceFile ? targetPathsByCanonicalFile.get(canonicalSourceFile) : undefined;\n const excludePaths = excludedTargetPaths ? { excludePaths: excludedTargetPaths } : {};\n const candidates = sameIndex\n ? options.source.similarToFunction(source.id, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n minLines,\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n ...excludePaths,\n })\n : target.searchByVector(vector, {\n limit,\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n minLines,\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n ...excludePaths,\n });\n const matches = sameIndex && !options.includeSymmetricDuplicates\n ? candidates.filter((match) => {\n const pair = source.id < match.function.id\n ? `${source.id}:${match.function.id}`\n : `${match.function.id}:${source.id}`;\n if (seenPairs.has(pair)) return false;\n seenPairs.add(pair);\n return true;\n })\n : candidates;\n if (matches.length > 0) yield { source, matches };\n options.onProgress?.({ completed: index + 1, total: sourceFunctions.length });\n }\n}\n\nfunction compileNameRegex(pattern: string | undefined): RegExp | undefined {\n if (pattern === undefined) return undefined;\n try {\n return new RegExp(pattern);\n } catch (error) {\n throw new CodeIndexError(`Invalid name regex: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nasync function canonicalRoot(root: string): Promise<string> {\n try {\n return await realpath(root);\n } catch {\n return path.resolve(root);\n }\n}\n\nasync function fileIdentity(filePath: string): Promise<string> {\n try {\n const metadata = await stat(filePath);\n return `inode:${metadata.dev}:${metadata.ino}`;\n } catch {\n return `path:${path.resolve(filePath)}`;\n }\n}\n"],"mappings":";;;AAEA,SAAS,YAAY,cAAc,cAAc;AACjD,OAAOA,WAAU;AACjB,SAAS,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;AAEA,SAAS,UAAU,OAAsB;AACvC,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,CAAI;AAC5D;AAEA,SAAS,YAAkB;AACzB,UAAQ,OAAO,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CA6HtB;AACD;","names":["path","lstat","path","path","path","path","path","path","path","path","path","path","lstat","entry","path","path","path","compileNameRegex","path","path"]}
|