@ninjaxtools/slopdex 0.19.0 → 0.20.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/.gitignore +2 -0
- package/README.md +134 -46
- package/binary-install.js +348 -0
- package/binary.js +124 -0
- package/install.js +4 -0
- package/npm-shrinkwrap.json +52 -0
- package/package.json +78 -61
- package/run-slopdex.js +4 -0
- package/dist/chunk-5BO2LLXC.js +0 -15
- package/dist/chunk-5BO2LLXC.js.map +0 -1
- package/dist/chunk-BXWO2KMC.js +0 -20
- package/dist/chunk-BXWO2KMC.js.map +0 -1
- package/dist/chunk-DKRB2XT5.js +0 -33
- package/dist/chunk-DKRB2XT5.js.map +0 -1
- package/dist/chunk-DTI7SXGL.js +0 -109
- package/dist/chunk-DTI7SXGL.js.map +0 -1
- package/dist/chunk-GBEJHETS.js +0 -1117
- package/dist/chunk-GBEJHETS.js.map +0 -1
- package/dist/chunk-HMKVMRLF.js +0 -2221
- package/dist/chunk-HMKVMRLF.js.map +0 -1
- package/dist/chunk-IQU3YVZ3.js +0 -85
- package/dist/chunk-IQU3YVZ3.js.map +0 -1
- package/dist/chunk-JAVPHCZH.js +0 -24
- package/dist/chunk-JAVPHCZH.js.map +0 -1
- package/dist/chunk-MKUTTXZB.js +0 -74
- package/dist/chunk-MKUTTXZB.js.map +0 -1
- package/dist/chunk-OIKBO3NJ.js +0 -133
- package/dist/chunk-OIKBO3NJ.js.map +0 -1
- package/dist/chunk-P57ZJREE.js +0 -426
- package/dist/chunk-P57ZJREE.js.map +0 -1
- package/dist/chunk-S225GYCL.js +0 -79
- package/dist/chunk-S225GYCL.js.map +0 -1
- package/dist/chunk-TSURHRFF.js +0 -240
- package/dist/chunk-TSURHRFF.js.map +0 -1
- package/dist/chunk-VH5VGRCI.js +0 -103
- package/dist/chunk-VH5VGRCI.js.map +0 -1
- package/dist/cli.d.ts +0 -1
- package/dist/cli.js +0 -1130
- package/dist/cli.js.map +0 -1
- package/dist/code-index-MWSJKV3G.js +0 -14
- package/dist/code-index-MWSJKV3G.js.map +0 -1
- package/dist/cross-search-ERBFC25T.js +0 -10
- package/dist/cross-search-ERBFC25T.js.map +0 -1
- package/dist/database-P5XWJWQL.js +0 -14
- package/dist/database-P5XWJWQL.js.map +0 -1
- package/dist/hosted-GHIUHKOU.js +0 -13
- package/dist/hosted-GHIUHKOU.js.map +0 -1
- package/dist/index.d.ts +0 -681
- package/dist/index.js +0 -102
- package/dist/index.js.map +0 -1
- package/dist/jina-43RL7C6M.js +0 -12
- package/dist/jina-43RL7C6M.js.map +0 -1
- package/dist/openai-CYUPNBGB.js +0 -12
- package/dist/openai-CYUPNBGB.js.map +0 -1
- package/dist/openai-EC6THXKV.js +0 -21
- package/dist/openai-EC6THXKV.js.map +0 -1
- package/dist/openai-TCRXM66O.js +0 -11
- package/dist/openai-TCRXM66O.js.map +0 -1
- package/docs/implementation.md +0 -162
- package/docs/reference.md +0 -187
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/code-index.ts","../src/git/repository.ts","../src/gitignore.ts","../src/parser/callable-parser.ts","../src/parser/native-callables.ts","../src/parser/diagnostics.ts","../src/source-policy.ts"],"sourcesContent":["import { lstat, readFile, readdir } from \"node:fs/promises\";\nimport { lstatSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { CodeIndexError, GitDivergenceError } from \"./errors.js\";\nimport { GitRepository, type GitChange, type GitTreeEntry } from \"./git/repository.js\";\nimport { GitignoreRules } from \"./gitignore.js\";\nimport { CALLABLE_PARSER_CACHE_VERSION, languageForPath, parseCallables, parseFileCallables } from \"./parser/callable-parser.js\";\nimport { analysisSimilarity } from \"./search/similarity.js\";\nimport { SourcePolicy } from \"./source-policy.js\";\nimport { IndexDatabase, type IndexedFileState, type PreparedCallable, type PreparedDescription, type PreparedFile } from \"./storage/database.js\";\nimport { isDescriptionProviderName, OpenAIDescriptionProvider } from \"./descriptions/openai.js\";\nimport type {\n CodeIndexOptions,\n CrossSearchSourceFilter,\n EmbeddingProfile,\n IndexProgress,\n IndexProgressPhase,\n IndexStatus,\n IndexedFunction,\n IndexingError,\n SimilarityResult,\n SimilaritySearchOptions,\n DescriptionProvider,\n DescriptionStats,\n ReindexFilesOptions,\n ReindexFilesStats,\n UpdateFilesOptions,\n UpdateFromGitOptions,\n UpdateFromWorkingTreeOptions,\n UpdateStats,\n} from \"./types.js\";\nimport {\n assertPositiveInteger,\n chunk,\n compileNameRegex,\n DEFAULT_PARALLELISM,\n forEachConcurrent,\n normalizeEmbeddingVector,\n normalizeRelativePath,\n sha256,\n throwIfAborted,\n} from \"./utils.js\";\n\nconst DEFAULT_MAX_FILE_SIZE = 1024 * 1024;\nconst DEFAULT_BATCH_SIZE = 32;\nconst RERANK_CANDIDATE_MULTIPLIER = 5;\nconst DEFAULT_SIMILARITY_CACHE_WIDTH = 50;\nconst MAX_SIMILARITY_CACHE_WIDTH = 200;\n\nexport class CodeIndex {\n public readonly rootDir: string;\n public readonly indexPath: string;\n public readonly provider;\n public readonly reranker;\n public readonly descriptionProvider: DescriptionProvider;\n readonly #database: IndexDatabase;\n readonly #policy: SourcePolicy;\n readonly #maxFileSize: number;\n readonly #embeddingBatchSize: number;\n readonly #parallelism: number;\n readonly #onProgress: ((progress: IndexProgress) => void) | undefined;\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 this.reranker = options.reranker;\n if (this.reranker?.candidateCount !== undefined) {\n assertPositiveInteger(this.reranker.candidateCount, \"reranker candidate count\");\n }\n if (this.reranker?.maximumCandidateCount !== undefined) {\n assertPositiveInteger(this.reranker.maximumCandidateCount, \"reranker maximum candidate count\");\n if (this.reranker.candidateCount !== undefined && this.reranker.candidateCount > this.reranker.maximumCandidateCount) {\n throw new CodeIndexError(\"reranker candidate count must not exceed its maximum candidate count.\");\n }\n }\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.#parallelism = options.parallelism ?? DEFAULT_PARALLELISM;\n assertPositiveInteger(this.#parallelism, \"parallelism\");\n this.#onProgress = options.onProgress;\n const storedDescriptionProfile = this.#database.descriptionProfile();\n this.descriptionProvider = options.descriptionProvider ?? new OpenAIDescriptionProvider({\n ...(storedDescriptionProfile && isDescriptionProviderName(storedDescriptionProfile.provider)\n ? { provider: storedDescriptionProfile.provider, model: storedDescriptionProfile.model }\n : {}),\n parallelism: this.#parallelism,\n ...(options.verbose ? { verbose: true } : {}),\n });\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 #progress(phase: IndexProgressPhase, completed: number, total: number): void {\n this.#onProgress?.({ phase, completed, total });\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 indexErrors(): IndexingError[] {\n return this.#database.indexErrors();\n }\n\n public async updateFiles(options: UpdateFilesOptions): Promise<UpdateStats> {\n throwIfAborted(options.signal);\n const gitignore = GitignoreRules.workingTree(this.rootDir);\n const generation = this.#database.getGeneration();\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) || await gitignore.ignores(relativePath)) {\n throw new CodeIndexError(`Unsupported or excluded source file: ${relativePath}`);\n }\n const renameSource = renameMap.get(relativePath);\n const originalPath = renameSource ? this.#database.previousPath(renameSource) ?? renameSource : undefined;\n const file = await this.#prepareWorkingFile(relativePath, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(originalPath ? { previousPath: originalPath } : {}),\n ...(renameSource ? { replacePath: renameSource } : {}),\n }, true);\n if (file) prepared.push(file);\n }\n let embeddingsCreated = await this.#attachEmbeddings(prepared, options.signal);\n for (let attempt = 0; ; attempt += 1) {\n await gitignore.assertUnchanged(options.signal);\n const changed: PreparedFile[] = [];\n for (let index = 0; index < prepared.length; index += 1) {\n const file = prepared[index]!;\n if (!this.#workingFileChangedSynchronously(file)) continue;\n if (attempt >= 2) throw new CodeIndexError(`Source changed repeatedly while indexing: ${file.path}; retry the update.`);\n const refreshed = await this.#prepareWorkingFile(file.path, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(file.previousPath ? { previousPath: file.previousPath } : {}),\n ...(file.replacePath ? { replacePath: file.replacePath } : {}),\n }, true);\n if (!refreshed) throw new CodeIndexError(`Source changed while indexing: ${file.path}; retry the update.`);\n prepared[index] = refreshed;\n changed.push(refreshed);\n }\n if (changed.length === 0) break;\n embeddingsCreated += await this.#attachEmbeddings(changed, options.signal);\n }\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: [...deletePaths, ...renameMap.values()],\n expectedGeneration: generation,\n embeddingsCreated,\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 gitignore = GitignoreRules.workingTree(this.rootDir);\n let sourcePaths = await this.#workingTreeSourcePaths(gitignore, options.signal);\n let prepared = await this.#prepareWorkingPaths(sourcePaths, options.signal);\n let embeddingsCreated = await this.#attachEmbeddings(prepared, options.signal);\n\n while (true) {\n await gitignore.assertUnchanged(options.signal);\n const pathsAgain = await this.#workingTreeSourcePaths(gitignore, options.signal);\n if (JSON.stringify(pathsAgain) !== JSON.stringify(sourcePaths)) {\n sourcePaths = pathsAgain;\n prepared = await this.#prepareWorkingPaths(sourcePaths, options.signal);\n embeddingsCreated += await this.#attachEmbeddings(prepared, options.signal);\n continue;\n }\n const changed: PreparedFile[] = [];\n for (let index = 0; index < prepared.length; index += 1) {\n const file = prepared[index]!;\n if (!await this.#workingFileChanged(file)) continue;\n const refreshed = await this.#prepareWorkingFile(file.path, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n });\n if (!refreshed) {\n sourcePaths = await this.#workingTreeSourcePaths(gitignore, options.signal);\n prepared = await this.#prepareWorkingPaths(sourcePaths, options.signal);\n changed.push(...prepared);\n break;\n }\n prepared[index] = refreshed;\n changed.push(refreshed);\n }\n if (changed.length === 0) break;\n embeddingsCreated += await this.#attachEmbeddings(changed, options.signal);\n }\n\n await gitignore.assertUnchanged(options.signal);\n if (this.#isWorkingTreeClean(indexedFiles, prepared)) {\n return emptyStats(this.#database.getCheckpoint());\n }\n return this.#database.applyUpdate({\n files: prepared,\n deletePaths: indexedFiles.map((file) => file.path),\n checkpoint: null,\n expectedGeneration: generation,\n completeDiagnosticsScan: true,\n embeddingsCreated,\n });\n }\n\n /**\n * Whether a working-tree refresh changed nothing: same file set, same\n * content, same language, and still working-tree rows, with no checkout to\n * clear. Recorded indexing errors never force a refresh on their own; a\n * file with errors is retried only when its content changes or via an\n * explicit updateFiles upsert. Skipping the write avoids a generation\n * bump and, via foreign-key cascades, needlessly invalidating the\n * similarity cache for unchanged files. Description state must already be\n * quiescent: a refresh is what lazily clears stored descriptions after\n * disableDescriptions, so a stale description count must fall through to\n * the rewrite, and enabled indexes keep the legacy behavior.\n */\n #isWorkingTreeClean(indexedFiles: IndexedFileState[], prepared: PreparedFile[]): boolean {\n if (this.#database.getCheckpoint() !== null) return false;\n if (this.#database.descriptionsEnabled()) return false;\n if (indexedFiles.length !== prepared.length) return false;\n const status = this.status();\n if (status.descriptionCount > 0 || status.fileDescriptionCount > 0) return false;\n const indexedByPath = new Map(indexedFiles.map((file) => [file.path, file]));\n return prepared.every((file) => {\n const indexed = indexedByPath.get(file.path);\n return !!indexed\n && indexed.sourceMode === \"working-tree\"\n && indexed.blobOid === file.blobOid\n && indexed.language === file.language\n && indexed.contentHash === file.contentHash;\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 // Only file-too-large state transitions (e.g. maxFileSize config change)\n // re-evaluate an unchanged blob; all other recorded errors never force a\n // retry on their own.\n const tooLargePaths = new Set(this.#database.filesWithFileTooLargeErrors());\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 gitignore = overlayWorkingTree ? GitignoreRules.workingTree(this.rootDir) : new GitignoreRules(async (filePath) => {\n const entry = tree.get(filePath);\n return entry ? (await this.#git.readBlob(entry.oid)).toString(\"utf8\") : null;\n });\n const allowedPaths = new Set<string>();\n const candidatePaths = new Set([\n ...tree.keys(), ...workingChanges.map((change) => change.path), ...indexedFiles.map((file) => file.path),\n ]);\n for (const filePath of candidatePaths) {\n throwIfAborted(options.signal);\n if (this.#policy.includes(filePath) && !await gitignore.ignores(filePath)) allowedPaths.add(filePath);\n }\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) => allowedPaths.has(entry.path));\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 // Recorded indexing errors never force a retry on their own; an\n // unchanged blob is skipped unless its file-too-large state flipped\n // (e.g. maxFileSize config change). Other errors are retried only\n // when the blob changes or via an explicit updateFiles upsert.\n if (indexed?.sourceMode === \"git\" && indexed.blobOid === entry.oid\n && (entry.size > this.#maxFileSize) === tooLargePaths.has(entry.path)) 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, allowedPaths);\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 const sizeStateFlipped = indexed?.sourceMode === \"git\" && indexed.blobOid === entry.oid\n && (entry.size > this.#maxFileSize) !== tooLargePaths.has(targetPath);\n if (\n (!indexed || (indexed.sourceMode === \"git\" && indexed.blobOid !== entry.oid) || sizeStateFlipped)\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 && allowedPaths.has(previousEntry.path)\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 && allowedPaths.has(entry.path)) {\n upserts.set(dirtyFile.path, currentPlan ?? { entry });\n }\n continue;\n }\n if (entry && allowedPaths.has(dirtyFile.path)) {\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 && allowedPaths.has(previousEntry.path)) {\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\n && (entry.size > this.#maxFileSize) === tooLargePaths.has(filePath)) 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 (!allowedPaths.has(relativePath)) {\n if (replacePath) workingDeletes.add(replacePath);\n workingDeletes.add(relativePath);\n continue;\n }\n const file = await this.#prepareWorkingFile(relativePath, {\n blobOid: null, sourceMode: \"working-tree\", indexedCommit: null,\n });\n if (!file) {\n if (replacePath) workingDeletes.add(replacePath);\n workingDeletes.add(relativePath);\n skippedWorkingPaths.add(relativePath);\n continue;\n }\n if (!file.unavailable && !replacePath && change.status === \"A\") {\n const contentHash = file.contentHash;\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({\n ...file,\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 provenance = {\n blobOid: entry.oid,\n sourceMode: \"git\" as const,\n indexedCommit: target,\n ...(previousPath ? { replacePath: previousPath } : {}),\n };\n if (entry.size > this.#maxFileSize) {\n prepared.push(this.#failedFile(entry.path, \"file-too-large\", `File exceeds maxFileSize (${this.#maxFileSize} bytes).`, provenance, entry.size));\n continue;\n }\n try {\n const content = await this.#git.readBlob(entry.oid);\n prepared.push(this.#prepareFile(entry.path, content, provenance));\n } catch (error) {\n prepared.push(this.#failedFile(entry.path, \"read-error\", error instanceof Error ? error.message : String(error), provenance, entry.size));\n }\n }\n let embeddingsCreated = 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 while (true) {\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) break;\n const headAgain = await this.#git.resolveCommit(\"HEAD\");\n const workingChangesAgain = await this.#git.workTreeChanges(target, indexArtifacts);\n if (headAgain !== head) throw new CodeIndexError(\"Git HEAD changed while indexing; retry the update.\");\n if (JSON.stringify(workingChangesAgain) !== JSON.stringify(workingChanges)) return await this.updateFromGit(options);\n const changed: PreparedFile[] = [];\n for (let index = 0; index < workingPrepared.length; index += 1) {\n const file = workingPrepared[index]!;\n if (!await this.#workingFileChanged(file)) continue;\n const refreshed = await this.#prepareWorkingFile(file.path, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n ...(file.previousPath ? { previousPath: file.previousPath } : {}),\n ...(file.replacePath ? { replacePath: file.replacePath } : {}),\n });\n if (!refreshed) return await this.updateFromGit(options);\n workingPrepared[index] = refreshed;\n changed.push(refreshed);\n }\n for (const relativePath of skippedWorkingPaths) {\n const refreshed = await this.#prepareWorkingFile(relativePath, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n });\n if (refreshed && !refreshed.unavailable) return await this.updateFromGit(options);\n }\n if (changed.length > 0) {\n embeddingsCreated += await this.#attachEmbeddings(changed, options.signal);\n continue;\n }\n await gitignore.assertUnchanged(options.signal);\n break;\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 completeDiagnosticsScan: true,\n embeddingsCreated,\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 allowedPaths: ReadonlySet<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 && allowedPaths.has(change.path)) {\n upserts.set(change.path, { entry, previousPath: change.oldPath });\n }\n continue;\n }\n const entry = tree.get(change.path);\n if (entry && allowedPaths.has(change.path)) upserts.set(change.path, { entry });\n else deletes.add(change.path);\n }\n }\n\n async #workingTreeSourcePaths(gitignore: GitignoreRules, 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) && !await gitignore.ignores(relativePath, true)) directories.push(relativePath);\n } else if (entry.isFile() && !indexArtifacts.has(relativePath) && this.#policy.includes(relativePath) && !await gitignore.ignores(relativePath)) {\n sourcePaths.push(relativePath);\n }\n }\n }\n sourcePaths.sort();\n return sourcePaths;\n }\n\n async #prepareWorkingPaths(relativePaths: readonly string[], signal?: AbortSignal): Promise<PreparedFile[]> {\n const prepared: PreparedFile[] = [];\n for (const relativePath of relativePaths) {\n throwIfAborted(signal);\n const file = await this.#prepareWorkingFile(relativePath, {\n blobOid: null,\n sourceMode: \"working-tree\",\n indexedCommit: null,\n });\n if (file) prepared.push(file);\n }\n return prepared;\n }\n\n async #workingFileChanged(file: PreparedFile): Promise<boolean> {\n try {\n const info = await lstat(path.join(this.rootDir, file.path));\n if (!info.isFile() || info.isSymbolicLink() || info.size !== file.byteSize) return true;\n if (info.size > this.#maxFileSize) return !file.errors.some((error) => error.code === \"file-too-large\");\n const content = await readFile(path.join(this.rootDir, file.path));\n return file.unavailable === true || sha256(content.toString(\"utf8\")) !== file.contentHash;\n } catch {\n return file.unavailable !== true;\n }\n }\n\n #workingFileChangedSynchronously(file: PreparedFile): boolean {\n try {\n const absolutePath = path.join(this.rootDir, file.path);\n const info = lstatSync(absolutePath);\n if (!info.isFile() || info.isSymbolicLink() || info.size !== file.byteSize) return true;\n if (info.size > this.#maxFileSize) return !file.errors.some((error) => error.code === \"file-too-large\");\n const contentHash = sha256(readFileSync(absolutePath, \"utf8\"));\n return file.unavailable === true || contentHash !== file.contentHash;\n } catch {\n return file.unavailable !== true;\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 contentHash = sha256(content);\n const parseKey = sha256(`${CALLABLE_PARSER_CACHE_VERSION}\\0${relativePath}\\0${contentHash}`);\n let parsed = this.#database.cachedParse(parseKey);\n if (!parsed) {\n parsed = parseFileCallables(relativePath, content, this.#onWarning);\n if (!parsed.errors.some((error) => error.code === \"parse-failed\" || error.code === \"extraction-error\")) {\n this.#database.storeParse(parseKey, parsed);\n }\n } else if (parsed.errors.length > 0) {\n this.#onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);\n }\n const language = languageForPath(relativePath) ?? path.extname(relativePath).slice(1);\n return {\n path: relativePath,\n contentHash,\n blobOid: provenance.blobOid,\n sourceMode: provenance.sourceMode,\n indexedCommit: provenance.indexedCommit,\n language,\n byteSize: buffer.byteLength,\n source: content,\n ...(provenance.previousPath ? { previousPath: provenance.previousPath } : {}),\n ...(provenance.replacePath ? { replacePath: provenance.replacePath } : {}),\n callables: parsed.callables as PreparedCallable[],\n errors: parsed.errors,\n };\n }\n\n async #prepareWorkingFile(\n relativePath: string,\n provenance: Pick<PreparedFile, \"blobOid\" | \"sourceMode\" | \"indexedCommit\" | \"previousPath\" | \"replacePath\">,\n strict = false,\n ): Promise<PreparedFile | null> {\n let size = 0;\n try {\n const absolutePath = path.join(this.rootDir, relativePath);\n const info = await lstat(absolutePath);\n if (info.isSymbolicLink() || !info.isFile()) {\n if (strict) throw new CodeIndexError(`Not a regular file or symbolic links are not supported: ${relativePath}`);\n return null;\n }\n size = info.size;\n if (size > this.#maxFileSize) {\n return this.#failedFile(relativePath, \"file-too-large\", `File exceeds maxFileSize (${this.#maxFileSize} bytes).`, provenance, size);\n }\n return this.#prepareFile(relativePath, await readFile(absolutePath), provenance);\n } catch (error) {\n if (error instanceof CodeIndexError) throw error;\n return this.#failedFile(relativePath, \"read-error\", error instanceof Error ? error.message : String(error), provenance, size);\n }\n }\n\n #failedFile(\n relativePath: string, code: \"read-error\" | \"file-too-large\", message: string,\n provenance: Pick<PreparedFile, \"blobOid\" | \"sourceMode\" | \"indexedCommit\" | \"previousPath\" | \"replacePath\">,\n byteSize: number,\n ): PreparedFile {\n this.#onWarning(`Cannot index ${relativePath}: ${message}`);\n return {\n ...provenance, path: relativePath, contentHash: sha256(\"\"), source: \"\", byteSize,\n language: languageForPath(relativePath) ?? \"unknown\", callables: [], unavailable: true,\n errors: [{\n path: relativePath, language: languageForPath(relativePath), scope: \"file\", code, message,\n qualifiedName: null, startLine: null, startColumn: null, endLine: null, endColumn: null, source: null,\n }],\n };\n }\n\n async #attachEmbeddings(files: PreparedFile[], signal?: AbortSignal): Promise<number> {\n if (this.#database.descriptionsEnabled()) {\n await this.#attachDescriptions(files.filter((file) => !file.unavailable), signal);\n }\n throwIfAborted(signal);\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 = embeddingKey(profile, \"document\", callable.embeddingInput);\n const values = unique.get(callable.embeddingKey) ?? [];\n values.push(callable);\n unique.set(callable.embeddingKey, values);\n }\n }\n const missing: Array<[string, PreparedCallable[]]> = [];\n for (const [key, callables] of unique) {\n const vector = this.#database.cachedEmbedding(key);\n if (vector) {\n for (const callable of callables) callable.vector = vector;\n } else {\n missing.push([key, callables]);\n }\n }\n if (missing.length === 0) return 0;\n let completed = 0;\n this.#progress(\"vectors\", 0, missing.length);\n await forEachConcurrent(chunk(missing, this.#embeddingBatchSize), this.#parallelism, async (batch, _index, workerSignal) => {\n const vectors = await this.provider.embedDocuments(\n batch.map(([, callables]) => callables[0]!.embeddingInput),\n { signal: workerSignal },\n );\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 this.#database.storeEmbedding(batch[index]![0], converted);\n for (const callable of batch[index]![1]) callable.vector = converted;\n });\n completed += batch.length;\n this.#progress(\"vectors\", completed, missing.length);\n }, signal);\n throwIfAborted(signal);\n return missing.length;\n }\n\n async #attachDescriptions(\n files: PreparedFile[],\n signal?: AbortSignal,\n options: { refreshFileDescriptions?: boolean; forceCallableDescriptions?: boolean; reindexCache?: boolean; skipCallables?: boolean; ignoreLiveDescriptions?: boolean } = {},\n ): Promise<{ descriptionsCreated: number; fileDescriptionsCreated: number }> {\n const profile = descriptionProfileJson(this.descriptionProvider.profile);\n const embeddingProfile = JSON.stringify(normalizeProfile(this.provider.profile));\n const prepared = new Map<string, PreparedDescription>();\n const repository = path.basename(this.rootDir);\n let descriptionsCreated = 0;\n let fileDescriptionsCreated = 0;\n let pending = 0;\n const tasks: DescriptionTask[] = [];\n const strategy = this.descriptionProvider.profile.strategyVersion;\n const useLiveReuse = !options.skipCallables && !options.reindexCache && !options.forceCallableDescriptions && !options.ignoreLiveDescriptions;\n const liveCallableDescriptions = useLiveReuse\n ? this.#database.liveFunctionDescriptions(files.flatMap((file) => file.callables.map((callable) => callable.identityKey)))\n : new Map<string, { description: string | null; sourceHash: string }>();\n const liveFileHashes = useLiveReuse && files.length > 0\n ? this.#database.liveFileContentHashes(files.map((file) => file.replacePath ?? file.previousPath ?? file.path))\n : new Map<string, string>();\n for (const file of files) {\n const lookupPath = file.replacePath ?? file.previousPath ?? file.path;\n const storedFileDescription = this.#database.fileDescription(lookupPath);\n const fileDescriptionKey = sha256(`${profile}\\0${repository}\\0${file.path}\\0${file.contentHash}\\0file`);\n const fileAgnosticKey = sha256(`${strategy}\\0${repository}\\0${file.path}\\0${file.contentHash}\\0file`);\n const fileCacheKey = options.reindexCache\n ? sha256(`${fileDescriptionKey}\\0reindex\\0${storedFileDescription?.description ?? \"\"}`)\n : fileDescriptionKey;\n const refreshFileDescription = options.refreshFileDescriptions || !storedFileDescription;\n const fileDescription = refreshFileDescription\n ? this.#database.cachedDescription(fileCacheKey)\n ?? (!options.reindexCache ? this.#database.cachedDescription(fileAgnosticKey) : undefined)\n : storedFileDescription.description;\n const fileUnchanged = liveFileHashes.get(lookupPath) === file.contentHash;\n const descriptions = (options.skipCallables ? [] : file.callables).map((callable) => {\n const descriptionKey = sha256(`${profile}\\0${repository}\\0${file.path}\\0${file.contentHash}\\0${callable.identityKey}\\0${callable.sourceHash}`);\n const agnosticKey = sha256(`${strategy}\\0${repository}\\0${file.path}\\0${file.contentHash}\\0${callable.identityKey}\\0${callable.sourceHash}`);\n const cacheKey = options.reindexCache\n ? sha256(`${descriptionKey}\\0reindex\\0${this.#database.functionDescription(callable.identityKey) ?? \"\"}`)\n : descriptionKey;\n if (useLiveReuse && fileUnchanged) {\n const live = liveCallableDescriptions.get(callable.identityKey);\n if (live?.description && live.sourceHash === callable.sourceHash) {\n return {\n callable,\n descriptionKey,\n cacheKey,\n agnosticKey,\n description: live.description,\n };\n }\n }\n const description = options.forceCallableDescriptions || options.reindexCache\n ? this.#database.cachedDescription(cacheKey)\n : this.#database.cachedDescription(descriptionKey)\n ?? this.#database.cachedDescription(agnosticKey);\n return {\n callable,\n descriptionKey,\n cacheKey,\n agnosticKey,\n ...(description ? { description } : {}),\n };\n });\n pending += (refreshFileDescription && !fileDescription ? 1 : 0)\n + descriptions.filter(({ description }) => !description).length;\n tasks.push({\n file,\n fileCacheKey,\n fileAgnosticKey,\n fileDescriptionKey,\n refreshFileDescription,\n ...(fileDescription ? { fileDescription } : {}),\n fileDescriptionPath: refreshFileDescription ? file.path : storedFileDescription.path,\n fileDescriptionContentHash: refreshFileDescription ? file.contentHash : storedFileDescription.contentHash,\n descriptions,\n });\n }\n let completed = 0;\n if (pending > 0) this.#progress(\"descriptions\", 0, pending);\n await forEachConcurrent(tasks, this.#parallelism, async (task, _index, workerSignal) => {\n const { file } = task;\n const session = task.refreshFileDescription || task.descriptions.some(({ description }) => !description)\n ? this.descriptionProvider.startFile?.({ repository, path: file.path, fileSource: file.source })\n : undefined;\n let fileDescription = task.fileDescription;\n let fileDescriptionAddedToSession = false;\n if (task.refreshFileDescription && !fileDescription) {\n const generated = session\n ? await session.describeFile({ signal: workerSignal })\n : await this.descriptionProvider.describeFile(\n { repository, path: file.path, fileSource: file.source },\n { signal: workerSignal },\n );\n if (typeof generated !== \"string\" || !generated.trim()) {\n throw new CodeIndexError(\"Description provider does not support file descriptions or returned an empty description.\");\n }\n fileDescription = this.#database.storeDescription(task.fileCacheKey, generated.trim());\n this.#database.storeDescription(task.fileAgnosticKey, fileDescription);\n fileDescriptionsCreated += 1;\n fileDescriptionAddedToSession = session !== undefined;\n completed += 1;\n this.#progress(\"descriptions\", completed, pending);\n }\n if (session && fileDescription && !fileDescriptionAddedToSession) session.replayFile(fileDescription);\n if (fileDescription) {\n const value = prepareDescription(prepared, embeddingProfile, fileDescription, this.#database);\n file.fileDescription = {\n path: task.fileDescriptionPath,\n contentHash: task.fileDescriptionContentHash,\n descriptionKey: task.fileDescriptionKey,\n value,\n };\n }\n for (const entry of task.descriptions) {\n throwIfAborted(workerSignal);\n const { callable, descriptionKey, cacheKey, agnosticKey } = entry;\n let { description } = entry;\n if (!description) {\n const generated = session\n ? await session.describe(callable, { signal: workerSignal })\n : await this.descriptionProvider.describe({ repository, callable, fileSource: file.source }, { signal: workerSignal });\n if (typeof generated !== \"string\" || !generated.trim()) throw new CodeIndexError(\"Description provider returned an empty description.\");\n description = this.#database.storeDescription(cacheKey, generated.trim());\n this.#database.storeDescription(agnosticKey, description);\n descriptionsCreated += 1;\n completed += 1;\n this.#progress(\"descriptions\", completed, pending);\n } else {\n session?.replay(callable, description);\n }\n callable.descriptionKey = descriptionKey;\n callable.description = prepareDescription(prepared, embeddingProfile, description, this.#database);\n }\n }, signal);\n const missing = [...prepared.values()].filter((description) => !description.vector);\n if (missing.length > 0) {\n let embedded = 0;\n this.#progress(\"description-vectors\", 0, missing.length);\n await forEachConcurrent(chunk(missing, this.#embeddingBatchSize), this.#parallelism, async (batch, _index, workerSignal) => {\n const vectors = await this.provider.embedDocuments(batch.map((value) => value.description), { signal: workerSignal });\n if (vectors.length !== batch.length) throw new CodeIndexError(\"Embedding provider returned an unexpected number of description vectors.\");\n vectors.forEach((vector, index) => {\n const converted = normalizeEmbeddingVector(vector, this.provider.profile.dimensions);\n this.#database.storeEmbedding(batch[index]!.key, converted);\n batch[index]!.vector = converted;\n });\n embedded += batch.length;\n this.#progress(\"description-vectors\", embedded, missing.length);\n }, signal);\n }\n throwIfAborted(signal);\n return { descriptionsCreated, fileDescriptionsCreated };\n }\n\n public async useDescriptions(options: { signal?: AbortSignal } = {}): Promise<DescriptionStats> {\n throwIfAborted(options.signal);\n const generation = this.#database.getGeneration();\n const functions = this.allFunctions();\n const status = this.status();\n const storedProfile = this.#database.descriptionProfile();\n const strategyChanged = (storedProfile?.strategyVersion ?? this.descriptionProvider.profile.strategyVersion)\n !== this.descriptionProvider.profile.strategyVersion;\n const profileChanged = descriptionProfileJson(storedProfile ?? this.descriptionProvider.profile)\n !== descriptionProfileJson(this.descriptionProvider.profile);\n if (this.#database.descriptionsEnabled()\n && !strategyChanged\n && functions.every((callable) => callable.descriptionEmbeddingId !== null)\n && status.fileDescriptionCount === status.describableFileCount) {\n if (profileChanged) this.#database.updateDescriptionProfile(this.descriptionProvider.profile, generation);\n return { descriptionsCreated: 0, fileDescriptionsCreated: 0, descriptionsEnabled: true };\n }\n const files = await this.#descriptionFiles(this.#database.getFileStates().filter((file) => file.describable), functions, options.signal);\n const { descriptionsCreated, fileDescriptionsCreated } = await this.#attachDescriptions(files, options.signal, {\n refreshFileDescriptions: strategyChanged,\n ...(strategyChanged ? { ignoreLiveDescriptions: true } : {}),\n });\n const ids = new Map(functions.map((callable) => [callable.identityKey, callable.id]));\n this.#database.enableDescriptions(files.flatMap((file) => file.callables.map((callable) => ({\n id: ids.get(callable.identityKey)!, description: callable.description!,\n }))), files, this.descriptionProvider.profile, generation);\n return { descriptionsCreated, fileDescriptionsCreated, descriptionsEnabled: true };\n }\n\n public async reindexFiles(options: ReindexFilesOptions = {}): Promise<ReindexFilesStats> {\n throwIfAborted(options.signal);\n if (!this.#database.descriptionsEnabled()) throw new CodeIndexError(\"Descriptions are not enabled; run descriptions enable first.\");\n const generation = this.#database.getGeneration();\n const states = this.#database.getFileStates()\n .filter((file) => file.describable\n && (file.fileDescriptionPath !== file.path || file.fileDescriptionContentHash !== file.contentHash));\n const files = await this.#descriptionFiles(states, this.allFunctions(), options.signal);\n const created = await this.#attachDescriptions(files, options.signal, {\n refreshFileDescriptions: true,\n ...(options.includeCallables !== undefined ? { forceCallableDescriptions: options.includeCallables } : {}),\n reindexCache: true,\n skipCallables: !options.includeCallables,\n });\n this.#database.updateDescriptions(files, options.includeCallables ?? false, generation, this.descriptionProvider.profile);\n return { filesReindexed: files.length, ...created };\n }\n\n async #descriptionFiles(\n states: readonly IndexedFileState[],\n functions: readonly IndexedFunction[],\n signal?: AbortSignal,\n ): Promise<PreparedFile[]> {\n const byPath = groupBy(functions, (callable) => callable.path);\n const files: PreparedFile[] = [];\n for (const file of states) {\n throwIfAborted(signal);\n const buffer = file.sourceMode === \"git\" && file.blobOid\n ? await this.#git.readBlob(file.blobOid)\n : await readFile(path.join(this.rootDir, file.path));\n const source = buffer.toString(\"utf8\");\n if (sha256(source) !== file.contentHash) {\n throw new CodeIndexError(`Source changed since indexing: ${file.path}; update the index first.`);\n }\n const callables = byPath.get(file.path) ?? [];\n files.push({\n path: file.path, contentHash: file.contentHash, blobOid: file.blobOid,\n sourceMode: file.sourceMode, indexedCommit: null, language: file.language,\n byteSize: buffer.byteLength, source,\n errors: [],\n callables: callables.map(({ description: _description, descriptionEmbeddingId: _descriptionEmbeddingId, ...callable }) => ({\n ...callable,\n embeddingKey: \"\",\n })),\n });\n }\n return files;\n }\n\n public disableDescriptions(): DescriptionStats {\n this.#database.disableDescriptions();\n return { descriptionsCreated: 0, fileDescriptionsCreated: 0, descriptionsEnabled: false };\n }\n\n public async searchDescription(options: SimilaritySearchOptions): Promise<SimilarityResult[]> {\n if (!this.#database.descriptionsEnabled()) throw new CodeIndexError(\"Descriptions are not enabled; run descriptions enable first.\");\n if (!options.query.trim()) throw new CodeIndexError(\"query must not be empty.\");\n const limit = options.limit;\n if (limit !== undefined) assertPositiveInteger(limit, \"limit\");\n const candidateLimit = this.#candidateLimit(limit);\n compileNameRegex(options.nameRegex);\n throwIfAborted(options.signal);\n const vector = await this.#queryEmbedding(options.query, options.signal);\n throwIfAborted(options.signal);\n const includeFileDescriptions = this.#descriptionScoringAvailable();\n const results = this.#database.searchVector(vector, {\n descriptions: true,\n ...(candidateLimit === undefined ? {} : { limit: candidateLimit }),\n minSimilarity: options.minSimilarity ?? -1,\n ...(includeFileDescriptions ? { fileDescriptionVector: vector } : {}),\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n return await this.#rerank(options.query, results, limit, options.signal);\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;\n if (limit !== undefined) assertPositiveInteger(limit, \"limit\");\n const candidateLimit = this.#candidateLimit(limit);\n compileNameRegex(options.nameRegex);\n throwIfAborted(options.signal);\n const vector = await this.#queryEmbedding(options.query, options.signal);\n const includeDescriptions = this.#descriptionScoringAvailable();\n const results = this.searchByVector(vector, {\n ...(includeDescriptions ? { descriptionVector: vector, fileDescriptionVector: vector } : {}),\n ...(candidateLimit === undefined ? {} : { limit: candidateLimit }),\n ...(options.nameRegex !== undefined ? { nameRegex: options.nameRegex } : {}),\n minSimilarity: options.minSimilarity ?? -1,\n ...(options.maxSimilarity !== undefined ? { maxSimilarity: options.maxSimilarity } : {}),\n });\n return await this.#rerank(options.query, results, limit, options.signal);\n }\n\n #candidateLimit(limit: number | undefined): number | undefined {\n if (limit === undefined) return undefined;\n if (!this.reranker) return limit;\n if (this.reranker.maximumCandidateCount !== undefined && limit > this.reranker.maximumCandidateCount) {\n throw new CodeIndexError(`${this.reranker.profile.provider} reranker supports at most ${this.reranker.maximumCandidateCount} results.`);\n }\n const preferred = this.reranker.candidateCount === undefined\n ? limit * RERANK_CANDIDATE_MULTIPLIER\n : Math.max(limit, this.reranker.candidateCount);\n return this.reranker.maximumCandidateCount === undefined\n ? preferred\n : Math.min(preferred, this.reranker.maximumCandidateCount);\n }\n\n async #rerank(\n query: string,\n candidates: SimilarityResult[],\n limit: number | undefined,\n signal?: AbortSignal,\n ): Promise<SimilarityResult[]> {\n if (!this.reranker || candidates.length === 0) return limit === undefined ? candidates : candidates.slice(0, limit);\n const documents = candidates.map(({ function: callable }) => [\n `path: ${callable.path}`,\n callable.description ? `description:\\n${callable.description}` : null,\n callable.embeddingInput,\n ].filter((value): value is string => value !== null).join(\"\\n\"));\n const rerankLimit = limit === undefined ? candidates.length : Math.min(limit, candidates.length);\n const rankings = await this.reranker.rerank(query, documents, signal ? { limit: rerankLimit, signal } : { limit: rerankLimit });\n throwIfAborted(signal);\n const seen = new Set<number>();\n if (rankings.length !== rerankLimit) {\n throw new CodeIndexError(`${this.reranker.profile.provider} returned invalid reranking results.`);\n }\n for (const { index, score } of rankings) {\n if (!Number.isInteger(index) || index < 0 || index >= candidates.length\n || typeof score !== \"number\" || !Number.isFinite(score) || seen.has(index)) {\n throw new CodeIndexError(`${this.reranker.profile.provider} returned invalid reranking results.`);\n }\n seen.add(index);\n }\n return rankings.map(({ index, score }) => ({ ...candidates[index]!, rerankScore: score }));\n }\n\n async #queryEmbedding(query: string, signal?: AbortSignal): Promise<number[]> {\n const profile = JSON.stringify(normalizeProfile(this.provider.profile));\n const key = embeddingKey(profile, \"query\", query);\n const cached = this.#database.cachedEmbedding(key);\n if (cached) return cached;\n const vector = normalizeEmbeddingVector(\n await this.provider.embedQuery(query, signal ? { signal } : undefined),\n this.provider.profile.dimensions,\n );\n this.#database.storeEmbedding(key, vector);\n return vector;\n }\n\n public similarToFunction(functionId: number, options: {\n includeDescriptions?: boolean;\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 ...(options.includeDescriptions ? { descriptionVector: this.#database.vectorForFunction(functionId, \"description\") } : {}),\n ...(options.includeDescriptions ? { fileDescriptionVector: this.#database.fileVectorForFunction(functionId) } : {}),\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, kind: \"code\" | \"description\" = \"code\"): number[] {\n return this.#database.vectorForFunction(functionId, kind);\n }\n\n public get readOnly(): boolean {\n return this.#database.isReadOnly;\n }\n\n public similarityCacheInfo(): { cachedSources: number; cachedPairs: number } {\n return this.#database.similarityCacheInfo();\n }\n\n /**\n * Incrementally refresh the persisted pairwise-similarity cache for same-index\n * analysis. Only pairs scoring at or above `minSimilarity` (the caller's\n * effective threshold) are stored; queries below the cached floor fall back to\n * live vector search. Only functions whose embeddings changed (plus a merge\n * pass over the remaining functions when the changed set is small) are\n * re-queried; unchanged pairs are reused. Lowering the floor below what is\n * cached re-queries every function, since the missing band cannot be rebuilt\n * incrementally; raising it reuses the cache for free. A per-function state\n * row records the embedding triple, floor, row count, and a completeness flag,\n * so a sparse row set is never mistaken for an unfinished computation. Call\n * before cross-search/cohesion, then read through\n * {@link cachedSimilarToFunction}. Best-effort under concurrent writers: a\n * later refresh repairs any rows raced by an overlapping update.\n */\n public async refreshSimilarityCache(options: {\n width?: number;\n /** Minimum similarity stored; pairs below it are never cached. Defaults to -1 (cache everything). */\n minSimilarity?: number;\n signal?: AbortSignal;\n /** Overrides the index-level onProgress for the cache-fill bar. */\n onProgress?: (progress: IndexProgress) => void;\n } = {}): Promise<{\n similarityMode: string;\n width: number;\n minSimilarity: number;\n sourcesRefreshed: number;\n pairsStored: number;\n skipped: boolean;\n }> {\n const width = Math.min(\n MAX_SIMILARITY_CACHE_WIDTH,\n Math.max(1, Math.floor(options.width ?? DEFAULT_SIMILARITY_CACHE_WIDTH)),\n );\n const floor = options.minSimilarity ?? -1;\n const mode = analysisSimilarity(this.status()).similarityMode;\n const includeDescriptions = mode !== \"code\";\n if (this.#database.isReadOnly) {\n return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed: 0, pairsStored: 0, skipped: true };\n }\n throwIfAborted(options.signal);\n const generation = this.#database.getGeneration();\n const triples = this.#database.similarityCacheTriples();\n if (triples.length <= 1) {\n return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed: 0, pairsStored: 0, skipped: false };\n }\n const states = this.#database.similarityCacheStates(mode);\n const tripleById = new Map(triples.map((triple) => [triple.functionId, triple]));\n const dirty = new Set<number>();\n let expanding = false;\n for (const triple of triples) {\n throwIfAborted(options.signal);\n const state = states.get(triple.functionId);\n if (!state\n || state.codeEmbeddingId !== triple.codeEmbeddingId\n || state.descriptionEmbeddingId !== triple.descriptionEmbeddingId\n || state.fileDescriptionEmbeddingId !== triple.fileDescriptionEmbeddingId\n || (state.cachedWidth < width && !state.complete)) {\n dirty.add(triple.functionId);\n } else if (state.floor > floor) {\n expanding = true;\n dirty.add(triple.functionId);\n }\n }\n if (dirty.size === 0 && !expanding) {\n const counts = this.#database.similarityCacheCounts(mode);\n for (const triple of triples) {\n if ((counts.get(triple.functionId) ?? 0) < (states.get(triple.functionId)?.storedCount ?? 0)) {\n dirty.add(triple.functionId);\n }\n }\n }\n let sourcesRefreshed = 0;\n let pairsStored = 0;\n if (dirty.size === 0) {\n return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed, pairsStored, skipped: false };\n }\n const report = options.onProgress ?? this.#onProgress;\n const total = triples.length;\n let completed = 0;\n report?.({ phase: \"similarity-cache\", completed, total });\n const fullRefresh = states.size === 0 || expanding || dirty.size > Math.max(8, Math.ceil(triples.length * 0.25));\n if (fullRefresh) {\n for (const triple of triples) {\n throwIfAborted(options.signal);\n const scanned = this.similarToFunction(triple.functionId, {\n ...(includeDescriptions ? { includeDescriptions: true } : {}),\n limit: Math.min(width + 1, triples.length - 1),\n minSimilarity: floor,\n });\n const neighbors = scanned.slice(0, width);\n this.#database.storeSimilarityNeighbors(triple.functionId, mode, neighbors, {\n codeEmbeddingId: triple.codeEmbeddingId,\n descriptionEmbeddingId: triple.descriptionEmbeddingId,\n fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,\n cachedWidth: width,\n generation,\n floor,\n complete: scanned.length <= width,\n });\n sourcesRefreshed += 1;\n pairsStored += neighbors.length;\n completed += 1;\n report?.({ phase: \"similarity-cache\", completed, total });\n }\n return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed, pairsStored, skipped: false };\n }\n const functionsById = new Map(this.allFunctions().map((callable) => [callable.id, callable]));\n const lean = new Map<number, Map<number, SimilarityResult>>();\n // Dirty scans must cover the widest band any clean row keeps, or merged\n // rows would silently lose pairs below the request floor.\n let scanFloor = floor;\n for (const state of states.values()) scanFloor = Math.min(scanFloor, state.floor);\n for (const dirtyId of dirty) {\n throwIfAborted(options.signal);\n const prior = states.get(dirtyId);\n const keepWidth = Math.max(width, prior?.cachedWidth ?? width);\n const full = this.similarToFunction(dirtyId, {\n ...(includeDescriptions ? { includeDescriptions: true } : {}),\n limit: triples.length - 1,\n minSimilarity: scanFloor,\n });\n const byTarget = new Map<number, SimilarityResult>();\n for (const match of full) byTarget.set(match.function.id, match);\n lean.set(dirtyId, byTarget);\n const triple = tripleById.get(dirtyId)!;\n const top = full.slice(0, keepWidth);\n this.#database.storeSimilarityNeighbors(dirtyId, mode, top, {\n codeEmbeddingId: triple.codeEmbeddingId,\n descriptionEmbeddingId: triple.descriptionEmbeddingId,\n fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,\n cachedWidth: keepWidth,\n generation,\n floor: scanFloor,\n complete: full.length <= keepWidth,\n });\n sourcesRefreshed += 1;\n pairsStored += top.length;\n completed += 1;\n report?.({ phase: \"similarity-cache\", completed, total });\n }\n for (const triple of triples) {\n throwIfAborted(options.signal);\n if (dirty.has(triple.functionId)) continue;\n // Never narrow a row the read-repair path widened: keep the lowest\n // floor served and the widest entry stored, or every refresh demotes\n // repaired rows and every analysis run re-repairs them with full scans.\n const prior = states.get(triple.functionId);\n const keepFloor = Math.min(floor, prior?.floor ?? floor);\n const keepWidth = Math.max(width, prior?.cachedWidth ?? width);\n const cached = this.#database.cachedSimilarityNeighbors(triple.functionId, mode);\n const kept = cached.filter((match) => match.similarity >= keepFloor\n && !dirty.has(match.function.id) && functionsById.has(match.function.id));\n const added: SimilarityResult[] = [];\n for (const [dirtyId, byTarget] of lean) {\n if (dirtyId === triple.functionId) continue;\n const match = byTarget.get(triple.functionId);\n const dirtyFunction = functionsById.get(dirtyId);\n if (match && match.similarity >= keepFloor && dirtyFunction) {\n const { function: _function, ...scores } = match;\n added.push({ ...scores, function: dirtyFunction });\n }\n }\n const plusOne = [...kept, ...added]\n .sort((left, right) => right.similarity - left.similarity || left.function.id - right.function.id)\n .slice(0, keepWidth + 1);\n const merged = plusOne.slice(0, keepWidth);\n // Completeness is per-row: the merge reuses this row's own pairs and\n // exact dirty scans covering its whole band, so it stays complete\n // exactly when it was complete and nothing was truncated. A global\n // check here would let one incomplete row flip the entire index to\n // incomplete on every refresh, and every later lookup would re-scan.\n const complete = plusOne.length <= keepWidth && (prior?.complete ?? false);\n const unchanged = merged.length === cached.length\n && merged.every((match, index) => match.function.id === cached[index]!.function.id\n && match.similarity === cached[index]!.similarity);\n if (unchanged) {\n // Rows are untouched: record the preserved floor and width without\n // rewriting the neighbor rows.\n this.#database.touchSimilarityCacheState(triple.functionId, mode, {\n codeEmbeddingId: triple.codeEmbeddingId,\n descriptionEmbeddingId: triple.descriptionEmbeddingId,\n fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,\n cachedWidth: keepWidth,\n generation,\n floor: keepFloor,\n storedCount: merged.length,\n complete,\n });\n } else {\n this.#database.storeSimilarityNeighbors(triple.functionId, mode, merged, {\n codeEmbeddingId: triple.codeEmbeddingId,\n descriptionEmbeddingId: triple.descriptionEmbeddingId,\n fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,\n cachedWidth: keepWidth,\n generation,\n floor: keepFloor,\n complete,\n });\n pairsStored += merged.length;\n }\n sourcesRefreshed += 1;\n completed += 1;\n report?.({ phase: \"similarity-cache\", completed, total });\n }\n return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed, pairsStored, skipped: false };\n }\n\n /**\n * Same-index neighbor lookup backed by {@link refreshSimilarityCache}.\n * Returns cache rows filtered exactly like {@link similarToFunction} and falls\n * back to a live vector query whenever the cache entry is missing, stale,\n * computed at a higher floor than requested, or too truncated to satisfy the\n * filters. A cache entry flagged complete holds every pair above its floor,\n * so short results from it are exact and need no live query.\n *\n * Prefer {@link cachedSimilarityReader} inside per-function loops: it loads\n * the validity snapshot once instead of re-reading it for every function.\n */\n public cachedSimilarToFunction(functionId: number, options: {\n includeDescriptions?: boolean;\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludePaths?: readonly string[];\n minLines?: number;\n nameRegex?: string;\n }): SimilarityResult[] {\n return this.cachedSimilarityReader({\n ...(options.includeDescriptions ? { includeDescriptions: true } : {}),\n }).similarToFunction(functionId, options);\n }\n\n /**\n * Snapshot the similarity-cache validity state (per-mode states, embedding\n * triples, generation) once for a run of neighbor lookups. The returned\n * lookup behaves exactly like {@link cachedSimilarToFunction} but avoids\n * re-reading whole tables per function; refresh the cache first and create\n * one reader per analysis run. Best-effort under concurrent writers, like the\n * refresh itself: a concurrent mutation mid-run is picked up by the next run.\n *\n * A fallback scan doubles as a read-repair: when the entry is fresh but\n * unusable (missing, recorded at a higher floor, or incomplete), the scan is\n * widened to the full cache width and written back, so later lookups hit.\n * Stale entries are left for the refresh, dense-at-max-width entries cannot\n * be improved, and read-only indexes never write.\n */\n public cachedSimilarityReader(options: {\n includeDescriptions?: boolean;\n } = {}): {\n similarToFunction: (functionId: number, query: {\n includeDescriptions?: boolean;\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludePaths?: readonly string[];\n minLines?: number;\n nameRegex?: string;\n }) => SimilarityResult[];\n } {\n const mode = options.includeDescriptions ? \"code-description-file-average\" : \"code\";\n const states = this.#database.similarityCacheStates(mode);\n const triples = this.#database.similarityCacheTriples();\n const tripleById = new Map(triples.map((triple) => [triple.functionId, triple]));\n const generation = this.#database.getGeneration();\n const readFiltered = (functionId: number, query: {\n limit: number;\n minSimilarity: number;\n maxSimilarity?: number;\n excludePaths?: readonly string[];\n minLines?: number;\n nameRegex?: string;\n }): SimilarityResult[] => this.#database.cachedSimilarityNeighbors(functionId, mode, {\n limit: query.limit,\n minSimilarity: query.minSimilarity,\n ...(query.maxSimilarity !== undefined ? { maxSimilarity: query.maxSimilarity } : {}),\n ...(query.minLines !== undefined ? { minLines: query.minLines } : {}),\n ...(query.nameRegex !== undefined ? { nameRegex: query.nameRegex } : {}),\n ...(query.excludePaths !== undefined ? { excludePaths: query.excludePaths } : {}),\n });\n return {\n similarToFunction: (functionId, query) => {\n const live = (): SimilarityResult[] => this.similarToFunction(functionId, query);\n // The reader is fixed to one scoring mode; a mismatched query cannot be\n // served from this snapshot and falls back to a live query.\n if ((query.includeDescriptions === true) !== (mode !== \"code\")) {\n return live();\n }\n compileNameRegex(query.nameRegex);\n const triple = tripleById.get(functionId);\n if (!triple) {\n return live();\n }\n const state = states.get(functionId);\n const tripleMatches = !!state\n && triple.codeEmbeddingId === state.codeEmbeddingId\n && triple.descriptionEmbeddingId === state.descriptionEmbeddingId\n && triple.fileDescriptionEmbeddingId === state.fileDescriptionEmbeddingId;\n if (state && (!tripleMatches || state.generation !== generation)) {\n return live();\n }\n if (state && state.floor <= query.minSimilarity) {\n const cached = readFiltered(functionId, query);\n if (cached.length >= query.limit) return cached;\n if (state.complete) return cached;\n if (state.storedCount >= MAX_SIMILARITY_CACHE_WIDTH) return live();\n } else if (this.#database.isReadOnly || this.#database.getGeneration() !== generation) {\n return live();\n }\n // Repair never narrows: entries keep the lowest floor they have served,\n // so alternating thresholds cannot thrash the cache.\n const repairFloor = Math.min(query.minSimilarity, state?.floor ?? query.minSimilarity);\n const width = MAX_SIMILARITY_CACHE_WIDTH;\n const scanned = this.similarToFunction(functionId, {\n ...(mode !== \"code\" ? { includeDescriptions: true } : {}),\n limit: Math.min(width + 1, tripleById.size - 1),\n minSimilarity: repairFloor,\n });\n const neighbors = scanned.slice(0, width);\n const complete = scanned.length <= width;\n this.#database.storeSimilarityNeighbors(functionId, mode, neighbors, {\n codeEmbeddingId: triple.codeEmbeddingId,\n descriptionEmbeddingId: triple.descriptionEmbeddingId,\n fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,\n cachedWidth: width,\n generation,\n floor: repairFloor,\n complete,\n });\n states.set(functionId, {\n codeEmbeddingId: triple.codeEmbeddingId,\n descriptionEmbeddingId: triple.descriptionEmbeddingId,\n fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,\n cachedWidth: width,\n generation,\n floor: repairFloor,\n storedCount: neighbors.length,\n complete,\n });\n const cached = readFiltered(functionId, query);\n if (cached.length >= query.limit) return cached;\n if (complete) return cached;\n return live();\n },\n };\n }\n\n public vectorForFile(filePath: string): number[] {\n return this.#database.vectorForFile(filePath);\n }\n\n public searchByVector(vector: readonly number[], options: {\n descriptionVector?: readonly number[];\n fileDescriptionVector?: readonly number[];\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), {\n ...options,\n ...(options.descriptionVector !== undefined\n ? { descriptionVector: normalizeEmbeddingVector(options.descriptionVector, this.provider.profile.dimensions) } : {}),\n ...(options.fileDescriptionVector !== undefined\n ? { fileDescriptionVector: normalizeEmbeddingVector(options.fileDescriptionVector, this.provider.profile.dimensions) } : {}),\n });\n }\n\n #descriptionScoringAvailable(): boolean {\n const status = this.status();\n return status.descriptionsEnabled\n && status.descriptionCount === status.functionCount\n && status.fileDescriptionCount === status.describableFileCount;\n }\n\n public async sourceFunctions(filter: CrossSearchSourceFilter): Promise<IndexedFunction[]> {\n const nameRegex = compileNameRegex(filter.nameRegex);\n const sourcePath = filter.path ? normalizeRelativePath(this.rootDir, filter.path) : undefined;\n const uncommitted = filter.type === \"uncommitted\" || (filter.type === \"changed-since\" && filter.uncommitted);\n const functions = filter.type === \"changed-since\"\n ? await this.#functionsChangedSince(filter.commit)\n : this.allFunctions();\n return functions.filter((callable) =>\n (!uncommitted || callable.sourceMode === \"working-tree\")\n && (!sourcePath || callable.path === sourcePath || callable.path.startsWith(`${sourcePath}/`))\n && (!nameRegex || nameRegex.test(callable.qualifiedName)));\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\ninterface DescriptionTaskEntry {\n callable: PreparedCallable;\n descriptionKey: string;\n cacheKey: string;\n agnosticKey: string;\n description?: string;\n}\n\ninterface DescriptionTask {\n file: PreparedFile;\n fileCacheKey: string;\n fileAgnosticKey: string;\n fileDescriptionKey: string;\n refreshFileDescription: boolean;\n fileDescription?: string;\n fileDescriptionPath: string;\n fileDescriptionContentHash: string;\n descriptions: DescriptionTaskEntry[];\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-v2\",\n };\n}\n\nfunction descriptionProfileJson(profile: DescriptionProvider[\"profile\"]): string {\n return JSON.stringify({\n provider: profile.provider,\n model: profile.model,\n strategyVersion: profile.strategyVersion,\n });\n}\n\nfunction embeddingKey(profile: string, operation: \"document\" | \"query\", input: string): string {\n return sha256(`${profile}\\0${operation}\\0${input}`);\n}\n\nfunction prepareDescription(\n prepared: Map<string, PreparedDescription>,\n embeddingProfile: string,\n description: string,\n database: IndexDatabase,\n): PreparedDescription {\n const key = embeddingKey(embeddingProfile, \"document\", description);\n let value = prepared.get(key);\n if (!value) {\n value = { key, description };\n const vector = database.cachedEmbedding(key);\n if (vector) value.vector = vector;\n prepared.set(key, value);\n }\n return value;\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","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 { lstat, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport ignore, { type Ignore } from \"ignore\";\n\nimport { CodeIndexError } from \"./errors.js\";\nimport { throwIfAborted } from \"./utils.js\";\n\nexport class GitignoreRules {\n readonly #directories = new Map<string, Promise<Ignore | null>>();\n readonly #contents = new Map<string, string | null>();\n\n public constructor(private readonly readIgnore: (relativePath: string) => Promise<string | null>) {}\n\n public static workingTree(rootDir: string): GitignoreRules {\n return new GitignoreRules(async (relativePath) => {\n const absolutePath = path.join(rootDir, relativePath);\n try {\n const info = await lstat(absolutePath);\n // Git does not follow symlinks when reading .gitignore files.\n if (!info.isFile() || info.isSymbolicLink()) return null;\n return await readFile(absolutePath, \"utf8\");\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return null;\n throw error;\n }\n });\n }\n\n public async ignores(relativePath: string, directory = false): Promise<boolean> {\n const parent = path.posix.dirname(relativePath);\n const rules = await this.#directory(parent === \".\" ? \"\" : parent);\n return rules === null || rules.ignores(directory ? `${relativePath}/` : relativePath);\n }\n\n public async assertUnchanged(signal?: AbortSignal): Promise<void> {\n for (const [filePath, content] of this.#contents) {\n throwIfAborted(signal);\n if (await this.readIgnore(filePath) !== content) {\n throw new CodeIndexError(`Gitignore rules changed while indexing: ${filePath}; retry the update.`);\n }\n }\n }\n\n #directory(directory: string): Promise<Ignore | null> {\n let result = this.#directories.get(directory);\n if (!result) {\n result = this.#loadDirectory(directory);\n this.#directories.set(directory, result);\n }\n return result;\n }\n\n async #loadDirectory(directory: string): Promise<Ignore | null> {\n let parentRules: Ignore | undefined;\n if (directory) {\n const parent = path.posix.dirname(directory);\n const rules = await this.#directory(parent === \".\" ? \"\" : parent);\n // A child .gitignore cannot re-include a directory excluded by its parent.\n if (rules === null || rules.ignores(`${directory}/`)) return null;\n parentRules = rules;\n }\n const filePath = directory ? `${directory}/.gitignore` : \".gitignore\";\n const content = await this.readIgnore(filePath);\n this.#contents.set(filePath, content);\n if (content === null && parentRules) return parentRules;\n const rules = ignore({ ignorecase: false });\n if (parentRules) rules.add(parentRules);\n if (content !== null) rules.add(directory ? scopedPatterns(content, directory) : content);\n return rules;\n }\n}\n\nfunction scopedPatterns(content: string, directory: string): string[] {\n // Prefix nested rules into the root-relative namespace. The ignore package\n // handles wildcard syntax, escapes, precedence, and excluded-parent semantics.\n const prefix = directory.replace(/[\\\\*?\\[\\]#!]/g, \"\\\\$&\");\n return content.split(/\\r?\\n/).map((line) => {\n const pattern = line.replace(/^\\uFEFF/, \"\");\n if (/^ *$/.test(pattern) || pattern.startsWith(\"#\")) return pattern;\n const negative = pattern.startsWith(\"!\");\n const body = negative ? pattern.slice(1) : pattern;\n if (/^\\/? *$/.test(body)) return \"\";\n // A slash only at the end denotes a directory basename, not an anchored path.\n const anchored = body.startsWith(\"/\") || body.replace(/\\/ *$/, \"\").includes(\"/\");\n return `${negative ? \"!\" : \"\"}/${prefix}/${anchored ? \"\" : \"**/\"}${body.replace(/^\\//, \"\")}`;\n });\n}\n","import path from \"node:path\";\n\nimport Parser from \"tree-sitter\";\nimport C from \"tree-sitter-c\";\nimport Go from \"tree-sitter-go\";\nimport Java from \"tree-sitter-java\";\nimport JavaScript from \"tree-sitter-javascript\";\nimport Python from \"tree-sitter-python\";\nimport Rust from \"tree-sitter-rust\";\nimport TypeScript from \"tree-sitter-typescript\";\n\nimport { CodeIndexError } from \"../errors.js\";\nimport type { CallableKind, IndexingIssue, ParsedCallable, SupportedLanguage } from \"../types.js\";\nimport { sha256 } from \"../utils.js\";\nimport type { CallableCandidate } from \"./candidate.js\";\nimport { collectNativeCallables } from \"./native-callables.js\";\nimport { parseDiagnostics } from \"./diagnostics.js\";\n\nconst parsers = new Map<SupportedLanguage, Parser>();\nexport const CALLABLE_PARSER_CACHE_VERSION = \"callable-parser-v1\";\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 case \".py\":\n case \".pyw\":\n return \"python\";\n case \".rs\":\n return \"rust\";\n case \".go\":\n return \"go\";\n case \".java\":\n return \"java\";\n case \".c\":\n case \".h\":\n return \"c\";\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 if (language === \"python\") parser.setLanguage(Python);\n else if (language === \"rust\") parser.setLanguage(Rust);\n else if (language === \"go\") parser.setLanguage(Go);\n else if (language === \"java\") parser.setLanguage(Java);\n else if (language === \"c\") parser.setLanguage(C);\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 (node.type === \"method_definition\" && 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 ([\"class_declaration\", \"abstract_class_declaration\", \"class\"].includes(node.type)) {\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 || node.hasError)) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n if (body) 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 || node.hasError)) {\n candidates.push({ node, name, kind: callableKind(node, name), scope });\n if (body) walk(body, content, [...scope, name], candidates);\n }\n return;\n }\n\n if ([\"public_field_definition\", \"property_definition\", \"field_definition\"].includes(node.type)) {\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 const parameter = node.childForFieldName(\"parameter\");\n const typeParameters = node.childForFieldName(\"type_parameters\");\n const returnType = node.childForFieldName(\"return_type\");\n const async = node.children.some((child) => child.type === \"async\") ? \"async \" : \"\";\n const generator = node.children.some((child) => child.type === \"*\") ? \"*\" : \"\";\n const parameterText = parameters ? textFor(content, parameters) : parameter ? `(${textFor(content, parameter)})` : \"\";\n return `${async}${generator}${name}${typeParameters ? textFor(content, typeParameters) : \"\"}${parameterText}${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 return parseFileCallables(relativePath, content, onWarning).callables;\n}\n\nexport function parseFileCallables(\n relativePath: string,\n content: string,\n onWarning: (message: string) => void = console.warn,\n): { callables: ParsedCallable[]; errors: IndexingIssue[] } {\n let result: { callables: ParsedCallable[]; errors: IndexingIssue[] };\n try {\n result = extractCallables(relativePath, content);\n } catch (error) {\n const message = `Cannot index ${relativePath}: ${error instanceof Error ? error.message : String(error)}`;\n onWarning(message);\n return { callables: [], errors: [{\n path: relativePath, language: languageForPath(relativePath), scope: \"file\", code: \"parse-failed\", message,\n qualifiedName: null, startLine: null, startColumn: null, endLine: null, endColumn: null, source: content,\n }] };\n }\n if (result.errors.length > 0) {\n onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);\n }\n return result;\n}\n\nfunction extractCallables(relativePath: string, content: string): { callables: ParsedCallable[]; errors: IndexingIssue[] } {\n const language = languageForPath(relativePath);\n if (!language) return { callables: [], errors: [] };\n\n const parser = getParser(language);\n const parsedTree = parseTree(parser, content, relativePath);\n const tree = parsedTree.rootNode.hasError && (language === \"typescript\" || language === \"tsx\")\n ? recoverUnsupportedTypeScriptSyntax(parser, parsedTree, content, relativePath) ?? parsedTree\n : parsedTree;\n const candidates: CallableCandidate[] = [];\n if ([\"typescript\", \"tsx\", \"javascript\", \"jsx\"].includes(language)) {\n walk(tree.rootNode, content, [], candidates);\n } else {\n candidates.push(...collectNativeCallables(tree.rootNode, content, language));\n }\n candidates.sort((left, right) => left.node.startIndex - right.node.startIndex);\n const errors = parseDiagnostics(tree.rootNode, content, relativePath, language, candidates);\n\n const occurrences = new Map<string, number>();\n const callables: ParsedCallable[] = [];\n for (const { node, name, kind, scope, signature: candidateSignature, documentation } of candidates) {\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 if (node.hasError) continue;\n try {\n const identityKey = sha256(`${baseIdentity}\\0${occurrence}`);\n const source = textFor(content, node);\n const signature = candidateSignature ?? signatureFor(content, node, name);\n const embeddingInput = [\n `language: ${language}`,\n `kind: ${kind}`,\n `symbol: ${qualifiedName}`,\n signature ? `signature: ${signature}` : null,\n documentation ? `documentation:\\n${documentation}` : null,\n \"source:\",\n source,\n ].filter((value): value is string => value !== null).join(\"\\n\");\n\n callables.push({\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 } catch (error) {\n errors.push({\n path: relativePath, language, scope: \"function\", code: \"extraction-error\", qualifiedName,\n message: `Cannot extract ${qualifiedName}: ${error instanceof Error ? error.message : String(error)}`,\n startLine: node.startPosition.row + 1, startColumn: node.startPosition.column + 1,\n endLine: node.endPosition.row + 1, endColumn: node.endPosition.column + 1, source: textFor(content, node),\n });\n }\n }\n return { callables, errors };\n}\n","import type Parser from \"tree-sitter\";\n\nimport type { CallableKind, SupportedLanguage } from \"../types.js\";\nimport type { CallableCandidate } from \"./candidate.js\";\n\ntype Node = Parser.SyntaxNode;\n\n// Follow the declarator spine, not parameter lists: C functions can return\n// pointers, including pointers to other functions.\nfunction cFunctionName(node: Node | null): string | null {\n if (!node) return null;\n if (node.type === \"identifier\") return node.text;\n return cFunctionName(node.childForFieldName(\"declarator\")\n ?? (node.type === \"parenthesized_declarator\" ? node.namedChildren[0] ?? null : null));\n}\n\nfunction containsYield(node: Node): boolean {\n if (node.type === \"yield\") return true;\n if ([\"function_definition\", \"class_definition\", \"lambda\"].includes(node.type)) return false;\n return node.namedChildren.some(containsYield);\n}\n\nfunction unwrap(node: Node | null): Node | null {\n while (node?.type === \"parenthesized_expression\" && node.namedChildCount === 1) {\n node = node.namedChildren[0]!;\n }\n return node;\n}\n\nfunction pythonIsMethod(node: Node): boolean {\n const definition = node.parent?.type === \"decorated_definition\" ? node.parent : node;\n return definition.parent?.parent?.type === \"class_definition\";\n}\n\nfunction pythonDocstring(body: Node | null, content: string): string | null {\n const statement = body?.namedChildren[0];\n if (statement?.type !== \"expression_statement\") return null;\n const value = statement.namedChildren[0];\n if (value?.type !== \"string\" && value?.type !== \"concatenated_string\") return null;\n return content.slice(value.startIndex, value.endIndex);\n}\n\nfunction goReceiver(node: Node): string | null {\n let type = node.childForFieldName(\"receiver\")?.namedChildren[0]?.childForFieldName(\"type\");\n while (type?.type === \"pointer_type\") type = type.namedChildren[0] ?? null;\n return type?.text ?? null;\n}\n\nexport function collectNativeCallables(root: Node, content: string, language: SupportedLanguage): CallableCandidate[] {\n const candidates: CallableCandidate[] = [];\n const text = (node: Node): string => content.slice(node.startIndex, node.endIndex);\n\n const add = (node: Node, name: string, kind: CallableKind, scope: readonly string[], bound = false): boolean => {\n const body = node.childForFieldName(\"body\");\n if ((!body || body.isMissing) && !node.hasError) return false;\n const sourceNode = language === \"python\" && node.parent?.type === \"decorated_definition\" ? node.parent : node;\n const header = content.slice(node.startIndex, body?.startIndex ?? node.endIndex).trimEnd();\n const documentation = language === \"python\" && body ? pythonDocstring(body, content) : null;\n candidates.push({\n node: sourceNode, name, kind, scope,\n signature: bound ? `${name} = ${header}` : header,\n ...(documentation ? { documentation } : {}),\n });\n if (body) walk(body, [...scope, name]);\n return true;\n };\n\n const addBound = (value: Node | null, name: Node | null, scope: readonly string[]): boolean => {\n const callable = unwrap(value);\n if (!callable || !name || ![\"identifier\", \"attribute\", \"selector_expression\"].includes(name.type)) return false;\n const closureType = { python: \"lambda\", rust: \"closure_expression\", go: \"func_literal\", java: \"lambda_expression\" };\n if (!(language in closureType) || callable.type !== closureType[language as keyof typeof closureType]) return false;\n return add(callable, text(name), \"function\", scope, true);\n };\n\n const walk = (node: Node, scope: readonly string[]): void => {\n if (language === \"python\") {\n if (node.type === \"class_definition\") {\n const name = node.childForFieldName(\"name\");\n const body = node.childForFieldName(\"body\");\n if (body) walk(body, name ? [...scope, text(name)] : scope);\n return;\n }\n if (node.type === \"function_definition\") {\n const name = node.childForFieldName(\"name\");\n const body = node.childForFieldName(\"body\");\n const method = pythonIsMethod(node);\n const kind = method && [\"__init__\", \"__new__\"].includes(name?.text ?? \"\") ? \"constructor\"\n : body && containsYield(body) ? \"generator\" : method ? \"method\" : \"function\";\n if (name) add(node, text(name), kind, scope);\n return;\n }\n if (node.type === \"assignment\" || node.type === \"named_expression\") {\n if (addBound(node.childForFieldName(\"right\") ?? node.childForFieldName(\"value\"),\n node.childForFieldName(\"left\") ?? node.childForFieldName(\"name\"), scope)) return;\n }\n } else if (language === \"rust\") {\n if ([\"mod_item\", \"trait_item\", \"impl_item\"].includes(node.type)) {\n const body = node.childForFieldName(\"body\");\n const type = node.childForFieldName(\"type\");\n const trait = node.childForFieldName(\"trait\");\n const name = node.type === \"impl_item\"\n ? type && (trait ? `<${text(type)} as ${text(trait)}>` : text(type))\n : node.childForFieldName(\"name\")?.text;\n if (body) walk(body, name ? [...scope, name] : scope);\n return;\n }\n if (node.type === \"function_item\") {\n const name = node.childForFieldName(\"name\");\n const owner = node.parent?.parent?.type;\n if (name) add(node, text(name), owner === \"impl_item\" || owner === \"trait_item\" ? \"method\" : \"function\", scope);\n return;\n }\n if (node.type === \"let_declaration\"\n && addBound(node.childForFieldName(\"value\"), node.childForFieldName(\"pattern\"), scope)) return;\n } else if (language === \"go\") {\n if (node.type === \"function_declaration\" || node.type === \"method_declaration\") {\n const name = node.childForFieldName(\"name\");\n const receiver = goReceiver(node);\n if (name) add(node, text(name), receiver ? \"method\" : \"function\", receiver ? [...scope, receiver] : scope);\n return;\n }\n if ([\"short_var_declaration\", \"assignment_statement\", \"var_spec\"].includes(node.type)) {\n const names = node.type === \"var_spec\" ? node.childrenForFieldName(\"name\")\n : node.childForFieldName(\"left\")?.namedChildren ?? [];\n const values = (node.childForFieldName(\"right\") ?? node.childForFieldName(\"value\"))?.namedChildren ?? [];\n // A one-to-one binding avoids inventing names for multiple return values.\n if (names.length === values.length) {\n for (let i = 0; i < names.length; i += 1) {\n if (!addBound(values[i]!, names[i]!, scope)) walk(values[i]!, scope);\n }\n return;\n }\n }\n } else if (language === \"java\") {\n if ([\"class_declaration\", \"interface_declaration\", \"enum_declaration\", \"record_declaration\", \"annotation_type_declaration\", \"enum_constant\"].includes(node.type)) {\n const name = node.childForFieldName(\"name\");\n for (const child of node.namedChildren) walk(child, name ? [...scope, text(name)] : scope);\n return;\n }\n if (node.type === \"class_body\" && node.parent?.type === \"object_creation_expression\") {\n const anonymousScope = [...scope, `<anonymous@${node.startPosition.row + 1}:${node.startPosition.column + 1}>`];\n for (const child of node.namedChildren) walk(child, anonymousScope);\n return;\n }\n if ([\"method_declaration\", \"constructor_declaration\", \"compact_constructor_declaration\"].includes(node.type)) {\n const name = node.childForFieldName(\"name\");\n if (name) add(node, text(name), node.type === \"method_declaration\" ? \"method\" : \"constructor\", scope);\n return;\n }\n if (node.type === \"variable_declarator\"\n && addBound(node.childForFieldName(\"value\"), node.childForFieldName(\"name\"), scope)) return;\n } else if (language === \"c\" && node.type === \"function_definition\") {\n const name = cFunctionName(node.childForFieldName(\"declarator\"));\n if (name) add(node, name, \"function\", scope);\n return;\n }\n\n // Anonymous callbacks have no stable symbol to index.\n if ([\"lambda\", \"closure_expression\", \"func_literal\", \"lambda_expression\"].includes(node.type)) return;\n for (const child of node.namedChildren) walk(child, scope);\n };\n\n walk(root, []);\n return candidates;\n}\n","import type Parser from \"tree-sitter\";\n\nimport type { IndexingIssue, SupportedLanguage } from \"../types.js\";\nimport type { CallableCandidate } from \"./candidate.js\";\n\nexport function parseDiagnostics(\n root: Parser.SyntaxNode, content: string, filePath: string, language: SupportedLanguage,\n candidates: readonly CallableCandidate[],\n): IndexingIssue[] {\n if (!root.hasError) return [];\n const errors: IndexingIssue[] = [];\n const brokenNodes = new Set<number>();\n const issue = (node: Parser.SyntaxNode, qualifiedName: string | null, message: string): IndexingIssue => ({\n path: filePath, language, scope: qualifiedName === null ? \"file\" : \"function\", code: \"parse-error\", message,\n qualifiedName, startLine: node.startPosition.row + 1, startColumn: node.startPosition.column + 1,\n endLine: node.endPosition.row + 1, endColumn: node.endPosition.column + 1,\n source: content.slice(node.startIndex, node.endIndex),\n });\n for (const candidate of candidates) {\n if (!candidate.node.hasError) continue;\n const name = [...candidate.scope, candidate.name].join(\".\");\n errors.push(issue(candidate.node, name, `Cannot fully parse callable ${name}; omitted from the searchable index.`));\n brokenNodes.add(candidate.node.id);\n }\n const walk = (node: Parser.SyntaxNode, insideBrokenCallable: boolean): void => {\n const inside = insideBrokenCallable || brokenNodes.has(node.id);\n if (node.isError || node.isMissing) {\n if (!inside) errors.push(issue(node, null, node.isMissing\n ? `Tree-sitter expected ${node.type}.`\n : \"Tree-sitter could not parse this source region.\"));\n // A malformed declaration can be reduced to an ERROR node instead of a\n // callable node. Recover names from declaration tokens, without guessing\n // function names from arbitrary identifiers or source text.\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n if (![\"function\", \"def\", \"fn\", \"func\"].includes(children[index]!.type)) continue;\n let next = index + 1;\n if (children[next]?.type === \"*\") next += 1;\n const name = children[next];\n if (name && [\"identifier\", \"field_identifier\"].includes(name.type)) {\n errors.push(issue(node, name.text, `Cannot parse declaration for ${name.text}; name recovered from an error node.`));\n }\n }\n // The whole unparsed region is retained; nested error nodes would repeat it.\n return;\n }\n for (const child of node.children) if (child.hasError || child.isError || child.isMissing) walk(child, inside);\n };\n walk(root, false);\n return errors;\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 \".venv\",\n \"venv\",\n \"__pycache__\",\n \".tox\",\n \".mypy_cache\",\n \".pytest_cache\",\n \"target\",\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAAA,QAAO,YAAAC,WAAU,eAAe;AACzC,SAAS,WAAW,oBAAoB;AACxC,OAAOC,WAAU;;;ACFjB,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,OAAO,UAAU;AAeV,IAAM,gBAAN,MAAoB;AAAA,EAClB,YAA4B,SAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA,EAEnC,MAAM,KAAK,MAAyB,eAAe,OAAkD;AACnG,WAAO,MAAM,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC5C,YAAM,QAAQ,MAAM,OAAO,CAAC,MAAM,KAAK,SAAS,GAAG,IAAI,GAAG,EAAE,OAAO,CAAC,UAAU,QAAQ,MAAM,EAAE,CAAC;AAC/F,YAAM,SAAmB,CAAC;AAC1B,YAAM,SAAmB,CAAC;AAC1B,YAAM,OAAO,GAAG,QAAQ,CAAC,UAAkB,OAAO,KAAK,KAAK,CAAC;AAC7D,YAAM,OAAO,GAAG,QAAQ,CAAC,UAAkB,OAAO,KAAK,KAAK,CAAC;AAC7D,YAAM,GAAG,SAAS,CAAC,UAAU;AAC3B,YAAK,MAAgC,SAAS,UAAU;AACtD,i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AAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,UAAM,QAAQ,OAAO,IAAI,GAAG,KAAK,CAAC;AAClC,UAAM,KAAK,KAAK;AAChB,WAAO,IAAI,KAAK,KAAK;AAAA,EACvB;AACA,SAAO;AACT;","names":["lstat","readFile","path","lstat","path","path","lstat","rules","path","walk","walk","path","path","path","path","file","entry","lstat","readFile","cached"]}
|
package/dist/chunk-IQU3YVZ3.js
DELETED
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
requestEmbeddings
|
|
3
|
-
} from "./chunk-JAVPHCZH.js";
|
|
4
|
-
import {
|
|
5
|
-
reportModelCall
|
|
6
|
-
} from "./chunk-BXWO2KMC.js";
|
|
7
|
-
import {
|
|
8
|
-
DEFAULT_PARALLELISM
|
|
9
|
-
} from "./chunk-VH5VGRCI.js";
|
|
10
|
-
|
|
11
|
-
// src/embeddings/jina.ts
|
|
12
|
-
import { createOpenAI } from "@ai-sdk/openai";
|
|
13
|
-
import { embed, embedMany } from "ai";
|
|
14
|
-
var JinaEmbeddingProvider = class {
|
|
15
|
-
profile;
|
|
16
|
-
#apiKey;
|
|
17
|
-
#baseUrl;
|
|
18
|
-
#verbose;
|
|
19
|
-
#parallelism;
|
|
20
|
-
constructor(options = {}) {
|
|
21
|
-
this.#apiKey = options.apiKey ?? process.env.JINA_API_KEY ?? "";
|
|
22
|
-
if (!this.#apiKey) throw new Error("JINA_API_KEY is required.");
|
|
23
|
-
const model = options.model ?? "jina-embeddings-v4";
|
|
24
|
-
const dimensions = options.dimensions ?? 1024;
|
|
25
|
-
if (!Number.isInteger(dimensions) || dimensions < 1) throw new Error("dimensions must be a positive integer.");
|
|
26
|
-
this.profile = {
|
|
27
|
-
provider: "jina",
|
|
28
|
-
model,
|
|
29
|
-
dimensions,
|
|
30
|
-
strategyVersion: "callable-v2:code-query-passage"
|
|
31
|
-
};
|
|
32
|
-
this.#verbose = options.verbose ?? false;
|
|
33
|
-
this.#parallelism = options.parallelism ?? DEFAULT_PARALLELISM;
|
|
34
|
-
const url = (options.baseUrl ?? "https://api.jina.ai/v1/embeddings").replace(/\/$/, "");
|
|
35
|
-
this.#baseUrl = url.endsWith("/embeddings") ? url.slice(0, -"/embeddings".length) : url;
|
|
36
|
-
}
|
|
37
|
-
async embedDocuments(inputs, options) {
|
|
38
|
-
if (inputs.length === 0) return [];
|
|
39
|
-
reportModelCall("vectors", this.profile, this.#verbose, this.#parallelism);
|
|
40
|
-
return requestEmbeddings(
|
|
41
|
-
embedMany({
|
|
42
|
-
model: this.#model("code.passage"),
|
|
43
|
-
values: [...inputs],
|
|
44
|
-
providerOptions: { openai: { dimensions: this.profile.dimensions } },
|
|
45
|
-
...options?.signal ? { abortSignal: options.signal } : {}
|
|
46
|
-
}).then(({ embeddings }) => embeddings),
|
|
47
|
-
this.profile.dimensions,
|
|
48
|
-
options?.signal
|
|
49
|
-
);
|
|
50
|
-
}
|
|
51
|
-
async embedQuery(input, options) {
|
|
52
|
-
reportModelCall("vectors", this.profile, this.#verbose, 1);
|
|
53
|
-
return (await requestEmbeddings(
|
|
54
|
-
embed({
|
|
55
|
-
model: this.#model("code.query"),
|
|
56
|
-
value: input,
|
|
57
|
-
providerOptions: { openai: { dimensions: this.profile.dimensions } },
|
|
58
|
-
...options?.signal ? { abortSignal: options.signal } : {}
|
|
59
|
-
}).then(({ embedding }) => [embedding]),
|
|
60
|
-
this.profile.dimensions,
|
|
61
|
-
options?.signal
|
|
62
|
-
))[0];
|
|
63
|
-
}
|
|
64
|
-
#model(task) {
|
|
65
|
-
const request = (input, init) => {
|
|
66
|
-
const body = JSON.parse(String(init?.body));
|
|
67
|
-
delete body.encoding_format;
|
|
68
|
-
return fetch(input, {
|
|
69
|
-
...init,
|
|
70
|
-
body: JSON.stringify({ ...body, embedding_type: "float", truncate: true, task })
|
|
71
|
-
});
|
|
72
|
-
};
|
|
73
|
-
return createOpenAI({
|
|
74
|
-
apiKey: this.#apiKey,
|
|
75
|
-
baseURL: this.#baseUrl,
|
|
76
|
-
name: "jina",
|
|
77
|
-
fetch: request
|
|
78
|
-
}).embeddingModel(this.profile.model);
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
export {
|
|
83
|
-
JinaEmbeddingProvider
|
|
84
|
-
};
|
|
85
|
-
//# sourceMappingURL=chunk-IQU3YVZ3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embeddings/jina.ts"],"sourcesContent":["import { createOpenAI } from \"@ai-sdk/openai\";\nimport { embed, embedMany } from \"ai\";\n\nimport type { EmbeddingProvider } from \"../types.js\";\nimport { reportModelCall } from \"../model-call-notice.js\";\nimport { DEFAULT_PARALLELISM } from \"../utils.js\";\nimport { requestEmbeddings } from \"./ai-sdk.js\";\n\nexport interface JinaEmbeddingProviderOptions {\n apiKey?: string;\n model?: string;\n dimensions?: number;\n baseUrl?: string;\n verbose?: boolean;\n parallelism?: number;\n}\n\nexport class JinaEmbeddingProvider implements EmbeddingProvider {\n public readonly profile;\n readonly #apiKey: string;\n readonly #baseUrl: string;\n readonly #verbose: boolean;\n readonly #parallelism: number;\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-v2:code-query-passage\",\n } as const;\n this.#verbose = options.verbose ?? false;\n this.#parallelism = options.parallelism ?? DEFAULT_PARALLELISM;\n const url = (options.baseUrl ?? \"https://api.jina.ai/v1/embeddings\").replace(/\\/$/, \"\");\n this.#baseUrl = url.endsWith(\"/embeddings\") ? url.slice(0, -\"/embeddings\".length) : url;\n }\n\n public async embedDocuments(inputs: readonly string[], options?: { signal?: AbortSignal }): Promise<number[][]> {\n if (inputs.length === 0) return [];\n reportModelCall(\"vectors\", this.profile, this.#verbose, this.#parallelism);\n return requestEmbeddings(\n embedMany({\n model: this.#model(\"code.passage\"),\n values: [...inputs],\n providerOptions: { openai: { dimensions: this.profile.dimensions } },\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n }).then(({ embeddings }) => embeddings),\n this.profile.dimensions,\n options?.signal,\n );\n }\n\n public async embedQuery(input: string, options?: { signal?: AbortSignal }): Promise<number[]> {\n reportModelCall(\"vectors\", this.profile, this.#verbose, 1);\n return (await requestEmbeddings(\n embed({\n model: this.#model(\"code.query\"),\n value: input,\n providerOptions: { openai: { dimensions: this.profile.dimensions } },\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n }).then(({ embedding }) => [embedding]),\n this.profile.dimensions,\n options?.signal,\n ))[0]!;\n }\n\n #model(task: \"code.passage\" | \"code.query\") {\n const request: typeof fetch = (input, init) => {\n const body = JSON.parse(String(init?.body)) as Record<string, unknown>;\n delete body.encoding_format;\n return fetch(input, {\n ...init,\n body: JSON.stringify({ ...body, embedding_type: \"float\", truncate: true, task }),\n });\n };\n return createOpenAI({\n apiKey: this.#apiKey,\n baseURL: this.#baseUrl,\n name: \"jina\",\n fetch: request,\n }).embeddingModel(this.profile.model);\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,OAAO,iBAAiB;AAgB1B,IAAM,wBAAN,MAAyD;AAAA,EAC9C;AAAA,EACP;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEF,YAAY,UAAwC,CAAC,GAAG;AAC7D,SAAK,UAAU,QAAQ,UAAU,QAAQ,IAAI,gBAAgB;AAC7D,QAAI,CAAC,KAAK,QAAS,OAAM,IAAI,MAAM,2BAA2B;AAC9D,UAAM,QAAQ,QAAQ,SAAS;AAC/B,UAAM,aAAa,QAAQ,cAAc;AACzC,QAAI,CA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EAAE,UAAU,MAAM,CAAC,SAAS,CAAC;AAAA,MACtC,KAAK,QAAQ;AAAA,MACb,SAAS;AAAA,IACX,GAAG,CAAC;AAAA,EACN;AAAA,EAEA,OAAO,MAAqC;AAC1C,UAAM,UAAwB,CAAC,OAAO,SAAS;AAC7C,YAAM,OAAO,KAAK,MAAM,OAAO,MAAM,IAAI,CAAC;AAC1C,aAAO,KAAK;AACZ,aAAO,MAAM,OAAO;AAAA,QAClB,GAAG;AAAA,QACH,MAAM,KAAK,UAAU,EAAE,GAAG,MAAM,gBAAgB,SAAS,UAAU,MAAM,KAAK,CAAC;AAAA,MACjF,CAAC;AAAA,IACH;AACA,WAAO,aAAa;AAAA,MAClB,QAAQ,KAAK;AAAA,MACb,SAAS,KAAK;AAAA,MACd,MAAM;AAAA,MACN,OAAO;AAAA,IACT,CAAC,EAAE,eAAe,KAAK,QAAQ,KAAK;AAAA,EACtC;AACF;","names":[]}
|
package/dist/chunk-JAVPHCZH.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
normalizeEmbeddingVector
|
|
3
|
-
} from "./chunk-VH5VGRCI.js";
|
|
4
|
-
import {
|
|
5
|
-
CodeIndexError
|
|
6
|
-
} from "./chunk-DKRB2XT5.js";
|
|
7
|
-
|
|
8
|
-
// src/embeddings/ai-sdk.ts
|
|
9
|
-
import { APICallError } from "ai";
|
|
10
|
-
async function requestEmbeddings(request, dimensions, signal) {
|
|
11
|
-
try {
|
|
12
|
-
const embeddings = await request;
|
|
13
|
-
return embeddings.map((embedding) => normalizeEmbeddingVector(embedding, dimensions));
|
|
14
|
-
} catch (error) {
|
|
15
|
-
if (signal?.aborted) throw error;
|
|
16
|
-
const detail = APICallError.isInstance(error) && error.responseBody ? error.responseBody.slice(0, 500) : error instanceof Error ? error.message : String(error);
|
|
17
|
-
throw new CodeIndexError(`Embedding request failed: ${detail}`, { cause: error });
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export {
|
|
22
|
-
requestEmbeddings
|
|
23
|
-
};
|
|
24
|
-
//# sourceMappingURL=chunk-JAVPHCZH.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embeddings/ai-sdk.ts"],"sourcesContent":["import { APICallError } from \"ai\";\n\nimport { CodeIndexError } from \"../errors.js\";\nimport { normalizeEmbeddingVector } from \"../utils.js\";\n\nexport async function requestEmbeddings(\n request: Promise<readonly unknown[]>,\n dimensions: number,\n signal?: AbortSignal,\n): Promise<number[][]> {\n try {\n const embeddings = await request;\n return embeddings.map((embedding) => normalizeEmbeddingVector(embedding, dimensions));\n } catch (error) {\n if (signal?.aborted) throw error;\n const detail = APICallError.isInstance(error) && error.responseBody\n ? error.responseBody.slice(0, 500)\n : error instanceof Error ? error.message : String(error);\n throw new CodeIndexError(`Embedding request failed: ${detail}`, { cause: error });\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,oBAAoB;AAK7B,eAAsB,kBACpB,SACA,YACA,QACqB;AACrB,MAAI;AACF,UAAM,aAAa,MAAM;AACzB,WAAO,WAAW,IAAI,CAAC,cAAc,yBAAyB,WAAW,UAAU,CAAC;AAAA,EACtF,SAAS,OAAO;AACd,QAAI,QAAQ,QAAS,OAAM;AAC3B,UAAM,SAAS,aAAa,WAAW,KAAK,KAAK,MAAM,eACnD,MAAM,aAAa,MAAM,GAAG,GAAG,IAC/B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACzD,UAAM,IAAI,eAAe,6BAA6B,MAAM,IAAI,EAAE,OAAO,MAAM,CAAC;AAAA,EAClF;AACF;","names":[]}
|