@ninjaxtools/slopdex 0.19.0 → 0.21.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.
Files changed (60) hide show
  1. package/.gitignore +2 -0
  2. package/README.md +154 -46
  3. package/binary-install.js +348 -0
  4. package/binary.js +124 -0
  5. package/install.js +4 -0
  6. package/npm-shrinkwrap.json +52 -0
  7. package/package.json +78 -61
  8. package/run-slopdex.js +4 -0
  9. package/dist/chunk-5BO2LLXC.js +0 -15
  10. package/dist/chunk-5BO2LLXC.js.map +0 -1
  11. package/dist/chunk-BXWO2KMC.js +0 -20
  12. package/dist/chunk-BXWO2KMC.js.map +0 -1
  13. package/dist/chunk-DKRB2XT5.js +0 -33
  14. package/dist/chunk-DKRB2XT5.js.map +0 -1
  15. package/dist/chunk-DTI7SXGL.js +0 -109
  16. package/dist/chunk-DTI7SXGL.js.map +0 -1
  17. package/dist/chunk-GBEJHETS.js +0 -1117
  18. package/dist/chunk-GBEJHETS.js.map +0 -1
  19. package/dist/chunk-HMKVMRLF.js +0 -2221
  20. package/dist/chunk-HMKVMRLF.js.map +0 -1
  21. package/dist/chunk-IQU3YVZ3.js +0 -85
  22. package/dist/chunk-IQU3YVZ3.js.map +0 -1
  23. package/dist/chunk-JAVPHCZH.js +0 -24
  24. package/dist/chunk-JAVPHCZH.js.map +0 -1
  25. package/dist/chunk-MKUTTXZB.js +0 -74
  26. package/dist/chunk-MKUTTXZB.js.map +0 -1
  27. package/dist/chunk-OIKBO3NJ.js +0 -133
  28. package/dist/chunk-OIKBO3NJ.js.map +0 -1
  29. package/dist/chunk-P57ZJREE.js +0 -426
  30. package/dist/chunk-P57ZJREE.js.map +0 -1
  31. package/dist/chunk-S225GYCL.js +0 -79
  32. package/dist/chunk-S225GYCL.js.map +0 -1
  33. package/dist/chunk-TSURHRFF.js +0 -240
  34. package/dist/chunk-TSURHRFF.js.map +0 -1
  35. package/dist/chunk-VH5VGRCI.js +0 -103
  36. package/dist/chunk-VH5VGRCI.js.map +0 -1
  37. package/dist/cli.d.ts +0 -1
  38. package/dist/cli.js +0 -1130
  39. package/dist/cli.js.map +0 -1
  40. package/dist/code-index-MWSJKV3G.js +0 -14
  41. package/dist/code-index-MWSJKV3G.js.map +0 -1
  42. package/dist/cross-search-ERBFC25T.js +0 -10
  43. package/dist/cross-search-ERBFC25T.js.map +0 -1
  44. package/dist/database-P5XWJWQL.js +0 -14
  45. package/dist/database-P5XWJWQL.js.map +0 -1
  46. package/dist/hosted-GHIUHKOU.js +0 -13
  47. package/dist/hosted-GHIUHKOU.js.map +0 -1
  48. package/dist/index.d.ts +0 -681
  49. package/dist/index.js +0 -102
  50. package/dist/index.js.map +0 -1
  51. package/dist/jina-43RL7C6M.js +0 -12
  52. package/dist/jina-43RL7C6M.js.map +0 -1
  53. package/dist/openai-CYUPNBGB.js +0 -12
  54. package/dist/openai-CYUPNBGB.js.map +0 -1
  55. package/dist/openai-EC6THXKV.js +0 -21
  56. package/dist/openai-EC6THXKV.js.map +0 -1
  57. package/dist/openai-TCRXM66O.js +0 -11
  58. package/dist/openai-TCRXM66O.js.map +0 -1
  59. package/docs/implementation.md +0 -162
  60. package/docs/reference.md +0 -187
@@ -1,2221 +0,0 @@
1
- import {
2
- IndexDatabase
3
- } from "./chunk-GBEJHETS.js";
4
- import {
5
- OpenAIDescriptionProvider,
6
- isDescriptionProviderName
7
- } from "./chunk-TSURHRFF.js";
8
- import {
9
- analysisSimilarity
10
- } from "./chunk-5BO2LLXC.js";
11
- import {
12
- DEFAULT_PARALLELISM,
13
- assertPositiveInteger,
14
- chunk,
15
- compileNameRegex,
16
- forEachConcurrent,
17
- normalizeEmbeddingVector,
18
- normalizeRelativePath,
19
- sha256,
20
- throwIfAborted
21
- } from "./chunk-VH5VGRCI.js";
22
- import {
23
- CodeIndexError,
24
- GitDivergenceError,
25
- GitUnavailableError
26
- } from "./chunk-DKRB2XT5.js";
27
-
28
- // src/code-index.ts
29
- import { lstat as lstat3, readFile as readFile2, readdir } from "node:fs/promises";
30
- import { lstatSync, readFileSync } from "node:fs";
31
- import path5 from "node:path";
32
-
33
- // src/git/repository.ts
34
- import { spawn } from "node:child_process";
35
- import { lstat } from "node:fs/promises";
36
- import path from "node:path";
37
- var GitRepository = class {
38
- constructor(rootDir) {
39
- this.rootDir = rootDir;
40
- }
41
- rootDir;
42
- async #run(args, allowExitOne = false) {
43
- return await new Promise((resolve, reject) => {
44
- const child = spawn("git", ["-C", this.rootDir, ...args], { stdio: ["ignore", "pipe", "pipe"] });
45
- const stdout = [];
46
- const stderr = [];
47
- child.stdout.on("data", (value) => stdout.push(value));
48
- child.stderr.on("data", (value) => stderr.push(value));
49
- child.on("error", (error) => {
50
- if (error.code === "ENOENT") {
51
- reject(new GitUnavailableError("Git executable is not available.", { cause: error }));
52
- return;
53
- }
54
- reject(error);
55
- });
56
- child.on("close", (code) => {
57
- const exitCode = code ?? -1;
58
- if (exitCode === 0 || allowExitOne && exitCode === 1) {
59
- resolve({ stdout: Buffer.concat(stdout), code: exitCode });
60
- return;
61
- }
62
- reject(new CodeIndexError(`Git command failed: ${Buffer.concat(stderr).toString("utf8").trim()}`));
63
- });
64
- });
65
- }
66
- async assertRepository() {
67
- let result;
68
- try {
69
- result = await this.#run(["rev-parse", "--is-inside-work-tree"]);
70
- } catch (error) {
71
- if (error instanceof GitUnavailableError) throw error;
72
- try {
73
- await lstat(path.join(this.rootDir, ".git"));
74
- } catch (markerError) {
75
- if (markerError.code === "ENOENT") {
76
- throw new GitUnavailableError(`${this.rootDir} is not a Git worktree.`, { cause: error });
77
- }
78
- throw markerError;
79
- }
80
- throw error;
81
- }
82
- if (result.stdout.toString("utf8").trim() !== "true") {
83
- throw new GitUnavailableError(`${this.rootDir} is not a Git worktree.`);
84
- }
85
- const topLevel = (await this.#run(["rev-parse", "--show-toplevel"])).stdout.toString("utf8").trim();
86
- if (path.resolve(topLevel) !== path.resolve(this.rootDir)) {
87
- throw new CodeIndexError(`rootDir must be the Git worktree root: ${topLevel}`);
88
- }
89
- }
90
- async workTreeChanges(base, excludePaths = []) {
91
- const pathspecs = [".", ...excludePaths.map((filePath) => `:(top,literal,exclude)${filePath}`)];
92
- const result = await this.#run([
93
- "diff",
94
- "--name-status",
95
- "-z",
96
- "--find-renames",
97
- base,
98
- "--",
99
- ...pathspecs
100
- ]);
101
- const changes = parseChanges(splitNull(result.stdout));
102
- const untracked = await this.#run([
103
- "ls-files",
104
- "--others",
105
- "--exclude-standard",
106
- "-z",
107
- "--",
108
- ...pathspecs
109
- ]);
110
- for (const filePath of splitNull(untracked.stdout)) changes.push({ status: "A", path: filePath });
111
- return changes;
112
- }
113
- async resolveCommit(ref) {
114
- const result = await this.#run(["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`]);
115
- const oid = result.stdout.toString("ascii").trim();
116
- if (!/^[0-9a-f]{40,64}$/.test(oid)) throw new CodeIndexError(`Could not resolve Git commit: ${ref}`);
117
- return oid;
118
- }
119
- async isAncestor(ancestor, descendant) {
120
- const result = await this.#run(["merge-base", "--is-ancestor", ancestor, descendant], true);
121
- return result.code === 0;
122
- }
123
- async listTree(commit) {
124
- const result = await this.#run(["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"]);
125
- const entries = /* @__PURE__ */ new Map();
126
- for (const record of splitNull(result.stdout)) {
127
- const tab = record.indexOf(" ");
128
- if (tab < 0) continue;
129
- const [mode, type, oid, sizeText] = record.slice(0, tab).trim().split(/\s+/);
130
- const filePath = record.slice(tab + 1);
131
- const size = Number(sizeText);
132
- if ((mode === "100644" || mode === "100755") && type === "blob" && oid && Number.isSafeInteger(size)) {
133
- entries.set(filePath, { path: filePath, oid, mode, size });
134
- }
135
- }
136
- return entries;
137
- }
138
- async readBlob(oid) {
139
- return (await this.#run(["cat-file", "blob", oid])).stdout;
140
- }
141
- async diff(base, target) {
142
- const result = await this.#run(["diff", "--name-status", "-z", "--find-renames", `${base}..${target}`, "--"]);
143
- return parseChanges(splitNull(result.stdout));
144
- }
145
- };
146
- function parseChanges(values) {
147
- const changes = [];
148
- for (let index = 0; index < values.length; ) {
149
- const rawStatus = values[index++];
150
- if (!rawStatus) continue;
151
- const status = rawStatus[0];
152
- if (status === "R" || status === "C") {
153
- const oldPath = values[index++];
154
- const filePath = values[index++];
155
- if (oldPath && filePath) changes.push({ status, oldPath, path: filePath });
156
- } else if (status === "A" || status === "M" || status === "D" || status === "T") {
157
- const filePath = values[index++];
158
- if (filePath) changes.push({ status, path: filePath });
159
- } else {
160
- throw new CodeIndexError(`Unsupported Git diff status: ${rawStatus}`);
161
- }
162
- }
163
- return changes;
164
- }
165
- function splitNull(buffer) {
166
- const value = buffer.toString("utf8");
167
- const parts = value.split("\0");
168
- if (parts.at(-1) === "") parts.pop();
169
- return parts;
170
- }
171
-
172
- // src/gitignore.ts
173
- import { lstat as lstat2, readFile } from "node:fs/promises";
174
- import path2 from "node:path";
175
- import ignore from "ignore";
176
- var GitignoreRules = class _GitignoreRules {
177
- constructor(readIgnore) {
178
- this.readIgnore = readIgnore;
179
- }
180
- readIgnore;
181
- #directories = /* @__PURE__ */ new Map();
182
- #contents = /* @__PURE__ */ new Map();
183
- static workingTree(rootDir) {
184
- return new _GitignoreRules(async (relativePath) => {
185
- const absolutePath = path2.join(rootDir, relativePath);
186
- try {
187
- const info = await lstat2(absolutePath);
188
- if (!info.isFile() || info.isSymbolicLink()) return null;
189
- return await readFile(absolutePath, "utf8");
190
- } catch (error) {
191
- if (["ENOENT", "ENOTDIR"].includes(error.code ?? "")) return null;
192
- throw error;
193
- }
194
- });
195
- }
196
- async ignores(relativePath, directory = false) {
197
- const parent = path2.posix.dirname(relativePath);
198
- const rules = await this.#directory(parent === "." ? "" : parent);
199
- return rules === null || rules.ignores(directory ? `${relativePath}/` : relativePath);
200
- }
201
- async assertUnchanged(signal) {
202
- for (const [filePath, content] of this.#contents) {
203
- throwIfAborted(signal);
204
- if (await this.readIgnore(filePath) !== content) {
205
- throw new CodeIndexError(`Gitignore rules changed while indexing: ${filePath}; retry the update.`);
206
- }
207
- }
208
- }
209
- #directory(directory) {
210
- let result = this.#directories.get(directory);
211
- if (!result) {
212
- result = this.#loadDirectory(directory);
213
- this.#directories.set(directory, result);
214
- }
215
- return result;
216
- }
217
- async #loadDirectory(directory) {
218
- let parentRules;
219
- if (directory) {
220
- const parent = path2.posix.dirname(directory);
221
- const rules2 = await this.#directory(parent === "." ? "" : parent);
222
- if (rules2 === null || rules2.ignores(`${directory}/`)) return null;
223
- parentRules = rules2;
224
- }
225
- const filePath = directory ? `${directory}/.gitignore` : ".gitignore";
226
- const content = await this.readIgnore(filePath);
227
- this.#contents.set(filePath, content);
228
- if (content === null && parentRules) return parentRules;
229
- const rules = ignore({ ignorecase: false });
230
- if (parentRules) rules.add(parentRules);
231
- if (content !== null) rules.add(directory ? scopedPatterns(content, directory) : content);
232
- return rules;
233
- }
234
- };
235
- function scopedPatterns(content, directory) {
236
- const prefix = directory.replace(/[\\*?\[\]#!]/g, "\\$&");
237
- return content.split(/\r?\n/).map((line) => {
238
- const pattern = line.replace(/^\uFEFF/, "");
239
- if (/^ *$/.test(pattern) || pattern.startsWith("#")) return pattern;
240
- const negative = pattern.startsWith("!");
241
- const body = negative ? pattern.slice(1) : pattern;
242
- if (/^\/? *$/.test(body)) return "";
243
- const anchored = body.startsWith("/") || body.replace(/\/ *$/, "").includes("/");
244
- return `${negative ? "!" : ""}/${prefix}/${anchored ? "" : "**/"}${body.replace(/^\//, "")}`;
245
- });
246
- }
247
-
248
- // src/parser/callable-parser.ts
249
- import path3 from "node:path";
250
- import Parser from "tree-sitter";
251
- import C from "tree-sitter-c";
252
- import Go from "tree-sitter-go";
253
- import Java from "tree-sitter-java";
254
- import JavaScript from "tree-sitter-javascript";
255
- import Python from "tree-sitter-python";
256
- import Rust from "tree-sitter-rust";
257
- import TypeScript from "tree-sitter-typescript";
258
-
259
- // src/parser/native-callables.ts
260
- function cFunctionName(node) {
261
- if (!node) return null;
262
- if (node.type === "identifier") return node.text;
263
- return cFunctionName(node.childForFieldName("declarator") ?? (node.type === "parenthesized_declarator" ? node.namedChildren[0] ?? null : null));
264
- }
265
- function containsYield(node) {
266
- if (node.type === "yield") return true;
267
- if (["function_definition", "class_definition", "lambda"].includes(node.type)) return false;
268
- return node.namedChildren.some(containsYield);
269
- }
270
- function unwrap(node) {
271
- while (node?.type === "parenthesized_expression" && node.namedChildCount === 1) {
272
- node = node.namedChildren[0];
273
- }
274
- return node;
275
- }
276
- function pythonIsMethod(node) {
277
- const definition = node.parent?.type === "decorated_definition" ? node.parent : node;
278
- return definition.parent?.parent?.type === "class_definition";
279
- }
280
- function pythonDocstring(body, content) {
281
- const statement = body?.namedChildren[0];
282
- if (statement?.type !== "expression_statement") return null;
283
- const value = statement.namedChildren[0];
284
- if (value?.type !== "string" && value?.type !== "concatenated_string") return null;
285
- return content.slice(value.startIndex, value.endIndex);
286
- }
287
- function goReceiver(node) {
288
- let type = node.childForFieldName("receiver")?.namedChildren[0]?.childForFieldName("type");
289
- while (type?.type === "pointer_type") type = type.namedChildren[0] ?? null;
290
- return type?.text ?? null;
291
- }
292
- function collectNativeCallables(root, content, language) {
293
- const candidates = [];
294
- const text = (node) => content.slice(node.startIndex, node.endIndex);
295
- const add = (node, name, kind, scope, bound = false) => {
296
- const body = node.childForFieldName("body");
297
- if ((!body || body.isMissing) && !node.hasError) return false;
298
- const sourceNode = language === "python" && node.parent?.type === "decorated_definition" ? node.parent : node;
299
- const header = content.slice(node.startIndex, body?.startIndex ?? node.endIndex).trimEnd();
300
- const documentation = language === "python" && body ? pythonDocstring(body, content) : null;
301
- candidates.push({
302
- node: sourceNode,
303
- name,
304
- kind,
305
- scope,
306
- signature: bound ? `${name} = ${header}` : header,
307
- ...documentation ? { documentation } : {}
308
- });
309
- if (body) walk2(body, [...scope, name]);
310
- return true;
311
- };
312
- const addBound = (value, name, scope) => {
313
- const callable = unwrap(value);
314
- if (!callable || !name || !["identifier", "attribute", "selector_expression"].includes(name.type)) return false;
315
- const closureType = { python: "lambda", rust: "closure_expression", go: "func_literal", java: "lambda_expression" };
316
- if (!(language in closureType) || callable.type !== closureType[language]) return false;
317
- return add(callable, text(name), "function", scope, true);
318
- };
319
- const walk2 = (node, scope) => {
320
- if (language === "python") {
321
- if (node.type === "class_definition") {
322
- const name = node.childForFieldName("name");
323
- const body = node.childForFieldName("body");
324
- if (body) walk2(body, name ? [...scope, text(name)] : scope);
325
- return;
326
- }
327
- if (node.type === "function_definition") {
328
- const name = node.childForFieldName("name");
329
- const body = node.childForFieldName("body");
330
- const method = pythonIsMethod(node);
331
- const kind = method && ["__init__", "__new__"].includes(name?.text ?? "") ? "constructor" : body && containsYield(body) ? "generator" : method ? "method" : "function";
332
- if (name) add(node, text(name), kind, scope);
333
- return;
334
- }
335
- if (node.type === "assignment" || node.type === "named_expression") {
336
- if (addBound(
337
- node.childForFieldName("right") ?? node.childForFieldName("value"),
338
- node.childForFieldName("left") ?? node.childForFieldName("name"),
339
- scope
340
- )) return;
341
- }
342
- } else if (language === "rust") {
343
- if (["mod_item", "trait_item", "impl_item"].includes(node.type)) {
344
- const body = node.childForFieldName("body");
345
- const type = node.childForFieldName("type");
346
- const trait = node.childForFieldName("trait");
347
- const name = node.type === "impl_item" ? type && (trait ? `<${text(type)} as ${text(trait)}>` : text(type)) : node.childForFieldName("name")?.text;
348
- if (body) walk2(body, name ? [...scope, name] : scope);
349
- return;
350
- }
351
- if (node.type === "function_item") {
352
- const name = node.childForFieldName("name");
353
- const owner = node.parent?.parent?.type;
354
- if (name) add(node, text(name), owner === "impl_item" || owner === "trait_item" ? "method" : "function", scope);
355
- return;
356
- }
357
- if (node.type === "let_declaration" && addBound(node.childForFieldName("value"), node.childForFieldName("pattern"), scope)) return;
358
- } else if (language === "go") {
359
- if (node.type === "function_declaration" || node.type === "method_declaration") {
360
- const name = node.childForFieldName("name");
361
- const receiver = goReceiver(node);
362
- if (name) add(node, text(name), receiver ? "method" : "function", receiver ? [...scope, receiver] : scope);
363
- return;
364
- }
365
- if (["short_var_declaration", "assignment_statement", "var_spec"].includes(node.type)) {
366
- const names = node.type === "var_spec" ? node.childrenForFieldName("name") : node.childForFieldName("left")?.namedChildren ?? [];
367
- const values = (node.childForFieldName("right") ?? node.childForFieldName("value"))?.namedChildren ?? [];
368
- if (names.length === values.length) {
369
- for (let i = 0; i < names.length; i += 1) {
370
- if (!addBound(values[i], names[i], scope)) walk2(values[i], scope);
371
- }
372
- return;
373
- }
374
- }
375
- } else if (language === "java") {
376
- if (["class_declaration", "interface_declaration", "enum_declaration", "record_declaration", "annotation_type_declaration", "enum_constant"].includes(node.type)) {
377
- const name = node.childForFieldName("name");
378
- for (const child of node.namedChildren) walk2(child, name ? [...scope, text(name)] : scope);
379
- return;
380
- }
381
- if (node.type === "class_body" && node.parent?.type === "object_creation_expression") {
382
- const anonymousScope = [...scope, `<anonymous@${node.startPosition.row + 1}:${node.startPosition.column + 1}>`];
383
- for (const child of node.namedChildren) walk2(child, anonymousScope);
384
- return;
385
- }
386
- if (["method_declaration", "constructor_declaration", "compact_constructor_declaration"].includes(node.type)) {
387
- const name = node.childForFieldName("name");
388
- if (name) add(node, text(name), node.type === "method_declaration" ? "method" : "constructor", scope);
389
- return;
390
- }
391
- if (node.type === "variable_declarator" && addBound(node.childForFieldName("value"), node.childForFieldName("name"), scope)) return;
392
- } else if (language === "c" && node.type === "function_definition") {
393
- const name = cFunctionName(node.childForFieldName("declarator"));
394
- if (name) add(node, name, "function", scope);
395
- return;
396
- }
397
- if (["lambda", "closure_expression", "func_literal", "lambda_expression"].includes(node.type)) return;
398
- for (const child of node.namedChildren) walk2(child, scope);
399
- };
400
- walk2(root, []);
401
- return candidates;
402
- }
403
-
404
- // src/parser/diagnostics.ts
405
- function parseDiagnostics(root, content, filePath, language, candidates) {
406
- if (!root.hasError) return [];
407
- const errors = [];
408
- const brokenNodes = /* @__PURE__ */ new Set();
409
- const issue = (node, qualifiedName, message) => ({
410
- path: filePath,
411
- language,
412
- scope: qualifiedName === null ? "file" : "function",
413
- code: "parse-error",
414
- message,
415
- qualifiedName,
416
- startLine: node.startPosition.row + 1,
417
- startColumn: node.startPosition.column + 1,
418
- endLine: node.endPosition.row + 1,
419
- endColumn: node.endPosition.column + 1,
420
- source: content.slice(node.startIndex, node.endIndex)
421
- });
422
- for (const candidate of candidates) {
423
- if (!candidate.node.hasError) continue;
424
- const name = [...candidate.scope, candidate.name].join(".");
425
- errors.push(issue(candidate.node, name, `Cannot fully parse callable ${name}; omitted from the searchable index.`));
426
- brokenNodes.add(candidate.node.id);
427
- }
428
- const walk2 = (node, insideBrokenCallable) => {
429
- const inside = insideBrokenCallable || brokenNodes.has(node.id);
430
- if (node.isError || node.isMissing) {
431
- if (!inside) errors.push(issue(node, null, node.isMissing ? `Tree-sitter expected ${node.type}.` : "Tree-sitter could not parse this source region."));
432
- const children = node.children;
433
- for (let index = 0; index < children.length; index += 1) {
434
- if (!["function", "def", "fn", "func"].includes(children[index].type)) continue;
435
- let next = index + 1;
436
- if (children[next]?.type === "*") next += 1;
437
- const name = children[next];
438
- if (name && ["identifier", "field_identifier"].includes(name.type)) {
439
- errors.push(issue(node, name.text, `Cannot parse declaration for ${name.text}; name recovered from an error node.`));
440
- }
441
- }
442
- return;
443
- }
444
- for (const child of node.children) if (child.hasError || child.isError || child.isMissing) walk2(child, inside);
445
- };
446
- walk2(root, false);
447
- return errors;
448
- }
449
-
450
- // src/parser/callable-parser.ts
451
- var parsers = /* @__PURE__ */ new Map();
452
- var CALLABLE_PARSER_CACHE_VERSION = "callable-parser-v1";
453
- function languageForPath(filePath) {
454
- switch (path3.extname(filePath).toLowerCase()) {
455
- case ".ts":
456
- case ".mts":
457
- case ".cts":
458
- return "typescript";
459
- case ".tsx":
460
- return "tsx";
461
- case ".js":
462
- case ".mjs":
463
- case ".cjs":
464
- return "javascript";
465
- case ".jsx":
466
- return "jsx";
467
- case ".py":
468
- case ".pyw":
469
- return "python";
470
- case ".rs":
471
- return "rust";
472
- case ".go":
473
- return "go";
474
- case ".java":
475
- return "java";
476
- case ".c":
477
- case ".h":
478
- return "c";
479
- default:
480
- return null;
481
- }
482
- }
483
- function getParser(language) {
484
- const existing = parsers.get(language);
485
- if (existing) return existing;
486
- const parser = new Parser();
487
- if (language === "typescript") parser.setLanguage(TypeScript.typescript);
488
- else if (language === "tsx") parser.setLanguage(TypeScript.tsx);
489
- else if (language === "python") parser.setLanguage(Python);
490
- else if (language === "rust") parser.setLanguage(Rust);
491
- else if (language === "go") parser.setLanguage(Go);
492
- else if (language === "java") parser.setLanguage(Java);
493
- else if (language === "c") parser.setLanguage(C);
494
- else parser.setLanguage(JavaScript);
495
- parsers.set(language, parser);
496
- return parser;
497
- }
498
- function parseTree(parser, content, relativePath) {
499
- try {
500
- return parser.parse(content, void 0, { bufferSize: Buffer.byteLength(content) + 1 });
501
- } catch (error) {
502
- const message = error instanceof Error ? error.message : String(error);
503
- throw new CodeIndexError(`Cannot index ${relativePath}: tree-sitter failed: ${message}`, { cause: error });
504
- }
505
- }
506
- function maskSyntax(value, replacement) {
507
- return replacement + value.slice(replacement.length).replace(/[^\r\n]/g, " ");
508
- }
509
- function recoverUnsupportedTypeScriptSyntax(parser, tree, content, relativePath) {
510
- const errors = [];
511
- const collectErrors = (node) => {
512
- if (node.isError || node.isMissing) errors.push(node);
513
- for (const child of node.children) collectErrors(child);
514
- };
515
- collectErrors(tree.rootNode);
516
- if (errors.length === 0) return null;
517
- let recoveredContent = content;
518
- let changed = false;
519
- const taggedTemplateTypeArguments = /* @__PURE__ */ new Map();
520
- for (const error of errors) {
521
- const parent = error.parent;
522
- if (error.isMissing && error.type === "!" && parent?.type === "type_arguments" && /^\s*`/.test(content.slice(parent.endIndex))) {
523
- taggedTemplateTypeArguments.set(parent.startIndex, parent);
524
- }
525
- }
526
- for (const node of [...taggedTemplateTypeArguments.values()].toSorted((left, right) => right.startIndex - left.startIndex)) {
527
- const value = recoveredContent.slice(node.startIndex, node.endIndex);
528
- recoveredContent = `${recoveredContent.slice(0, node.startIndex)}${value.replace(/[^\r\n]/g, " ")}${recoveredContent.slice(node.endIndex)}`;
529
- changed = true;
530
- }
531
- for (const node of errors.filter((candidate) => {
532
- const parent = candidate.parent;
533
- return !candidate.isMissing && candidate.type === "ERROR" && candidate.text === "type" && parent?.type === "export_statement" && content.slice(parent.startIndex, candidate.startIndex).trim() === "export" && /^\s*\*/.test(content.slice(candidate.endIndex, parent.endIndex));
534
- }).toSorted((left, right) => right.startIndex - left.startIndex)) {
535
- recoveredContent = `${recoveredContent.slice(0, node.startIndex)} ${recoveredContent.slice(node.endIndex)}`;
536
- changed = true;
537
- }
538
- recoveredContent = recoveredContent.replace(
539
- /\bimport\s*\(\s*(["'])(?:\\.|(?!\1)[^\\])*\1\s*\)/g,
540
- (value) => {
541
- changed = true;
542
- return maskSyntax(value, "X");
543
- }
544
- );
545
- if (!changed) return null;
546
- const recoveredTree = parseTree(parser, recoveredContent, relativePath);
547
- return recoveredTree.rootNode.hasError ? null : recoveredTree;
548
- }
549
- function textFor(content, node) {
550
- return content.slice(node.startIndex, node.endIndex);
551
- }
552
- function fieldText(content, node, field) {
553
- const child = node.childForFieldName(field);
554
- return child ? textFor(content, child) : null;
555
- }
556
- function callableKind(node, name) {
557
- if (node.type === "method_definition" && name === "constructor") return "constructor";
558
- if (node.type.includes("generator") || /^\s*(?:async\s+)?\*/.test(node.text)) return "generator";
559
- return node.type === "method_definition" ? "method" : "function";
560
- }
561
- function bindingName(content, node) {
562
- const nameNode = node.childForFieldName("name");
563
- if (!nameNode || !["identifier", "property_identifier", "private_property_identifier"].includes(nameNode.type)) {
564
- return null;
565
- }
566
- return textFor(content, nameNode).replace(/^#/, "");
567
- }
568
- function assignmentName(content, node) {
569
- const left = node.childForFieldName("left");
570
- if (!left) return null;
571
- const value = textFor(content, left).trim();
572
- const match = value.match(/(?:^|[.#])([A-Za-z_$][\w$]*)$/);
573
- return match?.[1] ?? null;
574
- }
575
- function objectScopeName(content, node) {
576
- const parent = node.parent;
577
- if (!parent) return null;
578
- if (parent.type === "variable_declarator" && parent.childForFieldName("value")?.id === node.id) {
579
- return bindingName(content, parent);
580
- }
581
- if (parent.type === "pair" && parent.childForFieldName("value")?.id === node.id) {
582
- return fieldText(content, parent, "key")?.replace(/["']/g, "") ?? null;
583
- }
584
- if (parent.type === "assignment_expression" && parent.childForFieldName("right")?.id === node.id) {
585
- return assignmentName(content, parent);
586
- }
587
- return null;
588
- }
589
- function walk(node, content, scope, candidates) {
590
- if (["class_declaration", "abstract_class_declaration", "class"].includes(node.type)) {
591
- const name = fieldText(content, node, "name") ?? objectScopeName(content, node);
592
- const nextScope = name ? [...scope, name] : scope;
593
- for (const child of node.namedChildren) walk(child, content, nextScope, candidates);
594
- return;
595
- }
596
- if (node.type === "internal_module" || node.type === "module") {
597
- const name = fieldText(content, node, "name")?.replace(/["']/g, "");
598
- const nextScope = name ? [...scope, name] : scope;
599
- for (const child of node.namedChildren) walk(child, content, nextScope, candidates);
600
- return;
601
- }
602
- if (node.type === "object") {
603
- const name = objectScopeName(content, node);
604
- const nextScope = name ? [...scope, name] : scope;
605
- for (const child of node.namedChildren) walk(child, content, nextScope, candidates);
606
- return;
607
- }
608
- if (["function_declaration", "generator_function_declaration"].includes(node.type)) {
609
- const name = fieldText(content, node, "name");
610
- const body = node.childForFieldName("body");
611
- if (name && (body || node.hasError)) {
612
- candidates.push({ node, name, kind: callableKind(node, name), scope });
613
- if (body) walk(body, content, [...scope, name], candidates);
614
- }
615
- return;
616
- }
617
- if (node.type === "method_definition") {
618
- const name = fieldText(content, node, "name")?.replace(/^#/, "");
619
- const body = node.childForFieldName("body");
620
- if (name && (body || node.hasError)) {
621
- candidates.push({ node, name, kind: callableKind(node, name), scope });
622
- if (body) walk(body, content, [...scope, name], candidates);
623
- }
624
- return;
625
- }
626
- if (["public_field_definition", "property_definition", "field_definition"].includes(node.type)) {
627
- const name = (fieldText(content, node, "name") ?? fieldText(content, node, "property"))?.replace(/^#/, "");
628
- const value = node.childForFieldName("value");
629
- if (name && value && ["arrow_function", "function_expression", "generator_function"].includes(value.type)) {
630
- const kind = callableKind(value, name) === "generator" ? "generator" : "method";
631
- candidates.push({ node: value, name, kind, scope });
632
- const body = value.childForFieldName("body");
633
- if (body) walk(body, content, [...scope, name], candidates);
634
- return;
635
- }
636
- }
637
- if (node.type === "variable_declarator") {
638
- const name = bindingName(content, node);
639
- const value = node.childForFieldName("value");
640
- if (name && value && ["arrow_function", "function_expression", "generator_function"].includes(value.type)) {
641
- candidates.push({ node: value, name, kind: callableKind(value, name), scope });
642
- const body = value.childForFieldName("body");
643
- if (body) walk(body, content, [...scope, name], candidates);
644
- return;
645
- }
646
- }
647
- if (node.type === "pair") {
648
- const name = fieldText(content, node, "key")?.replace(/["']/g, "");
649
- const value = node.childForFieldName("value");
650
- if (name && value && ["arrow_function", "function_expression", "generator_function"].includes(value.type)) {
651
- candidates.push({ node: value, name, kind: callableKind(value, name), scope });
652
- const body = value.childForFieldName("body");
653
- if (body) walk(body, content, [...scope, name], candidates);
654
- return;
655
- }
656
- }
657
- if (node.type === "assignment_expression") {
658
- const name = assignmentName(content, node);
659
- const value = node.childForFieldName("right");
660
- if (name && value && ["arrow_function", "function_expression", "generator_function"].includes(value.type)) {
661
- candidates.push({ node: value, name, kind: callableKind(value, name), scope });
662
- const body = value.childForFieldName("body");
663
- if (body) walk(body, content, [...scope, name], candidates);
664
- return;
665
- }
666
- }
667
- if (["function_expression", "generator_function"].includes(node.type)) {
668
- const name = fieldText(content, node, "name");
669
- const body = node.childForFieldName("body");
670
- if (name && body) {
671
- candidates.push({ node, name, kind: callableKind(node, name), scope });
672
- walk(body, content, [...scope, name], candidates);
673
- return;
674
- }
675
- }
676
- for (const child of node.namedChildren) walk(child, content, scope, candidates);
677
- }
678
- function signatureFor(content, node, name) {
679
- const parameters = node.childForFieldName("parameters");
680
- const parameter = node.childForFieldName("parameter");
681
- const typeParameters = node.childForFieldName("type_parameters");
682
- const returnType = node.childForFieldName("return_type");
683
- const async = node.children.some((child) => child.type === "async") ? "async " : "";
684
- const generator = node.children.some((child) => child.type === "*") ? "*" : "";
685
- const parameterText = parameters ? textFor(content, parameters) : parameter ? `(${textFor(content, parameter)})` : "";
686
- return `${async}${generator}${name}${typeParameters ? textFor(content, typeParameters) : ""}${parameterText}${returnType ? textFor(content, returnType) : ""}`;
687
- }
688
- function parseCallables(relativePath, content, onWarning = console.warn) {
689
- return parseFileCallables(relativePath, content, onWarning).callables;
690
- }
691
- function parseFileCallables(relativePath, content, onWarning = console.warn) {
692
- let result;
693
- try {
694
- result = extractCallables(relativePath, content);
695
- } catch (error) {
696
- const message = `Cannot index ${relativePath}: ${error instanceof Error ? error.message : String(error)}`;
697
- onWarning(message);
698
- return { callables: [], errors: [{
699
- path: relativePath,
700
- language: languageForPath(relativePath),
701
- scope: "file",
702
- code: "parse-failed",
703
- message,
704
- qualifiedName: null,
705
- startLine: null,
706
- startColumn: null,
707
- endLine: null,
708
- endColumn: null,
709
- source: content
710
- }] };
711
- }
712
- if (result.errors.length > 0) {
713
- onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);
714
- }
715
- return result;
716
- }
717
- function extractCallables(relativePath, content) {
718
- const language = languageForPath(relativePath);
719
- if (!language) return { callables: [], errors: [] };
720
- const parser = getParser(language);
721
- const parsedTree = parseTree(parser, content, relativePath);
722
- const tree = parsedTree.rootNode.hasError && (language === "typescript" || language === "tsx") ? recoverUnsupportedTypeScriptSyntax(parser, parsedTree, content, relativePath) ?? parsedTree : parsedTree;
723
- const candidates = [];
724
- if (["typescript", "tsx", "javascript", "jsx"].includes(language)) {
725
- walk(tree.rootNode, content, [], candidates);
726
- } else {
727
- candidates.push(...collectNativeCallables(tree.rootNode, content, language));
728
- }
729
- candidates.sort((left, right) => left.node.startIndex - right.node.startIndex);
730
- const errors = parseDiagnostics(tree.rootNode, content, relativePath, language, candidates);
731
- const occurrences = /* @__PURE__ */ new Map();
732
- const callables = [];
733
- for (const { node, name, kind, scope, signature: candidateSignature, documentation } of candidates) {
734
- const qualifiedName = [...scope, name].join(".");
735
- const baseIdentity = `${relativePath}\0${qualifiedName}\0${kind}`;
736
- const occurrence = occurrences.get(baseIdentity) ?? 0;
737
- occurrences.set(baseIdentity, occurrence + 1);
738
- if (node.hasError) continue;
739
- try {
740
- const identityKey = sha256(`${baseIdentity}\0${occurrence}`);
741
- const source = textFor(content, node);
742
- const signature = candidateSignature ?? signatureFor(content, node, name);
743
- const embeddingInput = [
744
- `language: ${language}`,
745
- `kind: ${kind}`,
746
- `symbol: ${qualifiedName}`,
747
- signature ? `signature: ${signature}` : null,
748
- documentation ? `documentation:
749
- ${documentation}` : null,
750
- "source:",
751
- source
752
- ].filter((value) => value !== null).join("\n");
753
- callables.push({
754
- path: relativePath,
755
- language,
756
- kind,
757
- name,
758
- qualifiedName,
759
- signature,
760
- identityKey,
761
- startLine: node.startPosition.row + 1,
762
- startColumn: node.startPosition.column + 1,
763
- endLine: node.endPosition.row + 1,
764
- endColumn: node.endPosition.column + 1,
765
- lineCount: node.endPosition.row - node.startPosition.row + 1,
766
- source,
767
- sourceHash: sha256(source),
768
- embeddingInput
769
- });
770
- } catch (error) {
771
- errors.push({
772
- path: relativePath,
773
- language,
774
- scope: "function",
775
- code: "extraction-error",
776
- qualifiedName,
777
- message: `Cannot extract ${qualifiedName}: ${error instanceof Error ? error.message : String(error)}`,
778
- startLine: node.startPosition.row + 1,
779
- startColumn: node.startPosition.column + 1,
780
- endLine: node.endPosition.row + 1,
781
- endColumn: node.endPosition.column + 1,
782
- source: textFor(content, node)
783
- });
784
- }
785
- }
786
- return { callables, errors };
787
- }
788
-
789
- // src/source-policy.ts
790
- import path4 from "node:path";
791
- var DEFAULT_EXCLUDED_SEGMENTS = /* @__PURE__ */ new Set([
792
- ".git",
793
- ".slopdex",
794
- "node_modules",
795
- "dist",
796
- "build",
797
- "coverage",
798
- "vendor",
799
- "generated",
800
- ".venv",
801
- "venv",
802
- "__pycache__",
803
- ".tox",
804
- ".mypy_cache",
805
- ".pytest_cache",
806
- "target"
807
- ]);
808
- var SourcePolicy = class {
809
- #include;
810
- #exclude;
811
- constructor(include = [], exclude = []) {
812
- this.#include = include;
813
- this.#exclude = exclude;
814
- }
815
- includes(relativePath) {
816
- const normalized = relativePath.replaceAll("\\", "/");
817
- if (!languageForPath(normalized)) return false;
818
- if (hasExcludedSegment(normalized)) return false;
819
- if (this.#exclude.some((pattern) => path4.matchesGlob(normalized, pattern))) return false;
820
- return this.#include.length === 0 || this.#include.some((pattern) => path4.matchesGlob(normalized, pattern));
821
- }
822
- traversesDirectory(relativePath) {
823
- return !hasExcludedSegment(relativePath.replaceAll("\\", "/"));
824
- }
825
- };
826
- function hasExcludedSegment(relativePath) {
827
- return relativePath.split("/").some((segment) => DEFAULT_EXCLUDED_SEGMENTS.has(segment));
828
- }
829
-
830
- // src/code-index.ts
831
- var DEFAULT_MAX_FILE_SIZE = 1024 * 1024;
832
- var DEFAULT_BATCH_SIZE = 32;
833
- var RERANK_CANDIDATE_MULTIPLIER = 5;
834
- var DEFAULT_SIMILARITY_CACHE_WIDTH = 50;
835
- var MAX_SIMILARITY_CACHE_WIDTH = 200;
836
- var CodeIndex = class {
837
- rootDir;
838
- indexPath;
839
- provider;
840
- reranker;
841
- descriptionProvider;
842
- #database;
843
- #policy;
844
- #maxFileSize;
845
- #embeddingBatchSize;
846
- #parallelism;
847
- #onProgress;
848
- #git;
849
- #onWarning;
850
- constructor(options) {
851
- this.rootDir = path5.resolve(options.rootDir);
852
- this.indexPath = path5.resolve(options.indexPath ?? path5.join(this.rootDir, ".slopdex", "index.sqlite"));
853
- this.provider = options.provider;
854
- this.reranker = options.reranker;
855
- if (this.reranker?.candidateCount !== void 0) {
856
- assertPositiveInteger(this.reranker.candidateCount, "reranker candidate count");
857
- }
858
- if (this.reranker?.maximumCandidateCount !== void 0) {
859
- assertPositiveInteger(this.reranker.maximumCandidateCount, "reranker maximum candidate count");
860
- if (this.reranker.candidateCount !== void 0 && this.reranker.candidateCount > this.reranker.maximumCandidateCount) {
861
- throw new CodeIndexError("reranker candidate count must not exceed its maximum candidate count.");
862
- }
863
- }
864
- const profile = normalizeProfile(options.provider.profile);
865
- assertPositiveInteger(profile.dimensions, "embedding dimensions");
866
- this.#database = new IndexDatabase(this.indexPath, this.rootDir, profile, options.readOnly ?? false);
867
- this.#parallelism = options.parallelism ?? DEFAULT_PARALLELISM;
868
- assertPositiveInteger(this.#parallelism, "parallelism");
869
- this.#onProgress = options.onProgress;
870
- const storedDescriptionProfile = this.#database.descriptionProfile();
871
- this.descriptionProvider = options.descriptionProvider ?? new OpenAIDescriptionProvider({
872
- ...storedDescriptionProfile && isDescriptionProviderName(storedDescriptionProfile.provider) ? { provider: storedDescriptionProfile.provider, model: storedDescriptionProfile.model } : {},
873
- parallelism: this.#parallelism,
874
- ...options.verbose ? { verbose: true } : {}
875
- });
876
- this.#policy = new SourcePolicy(options.include, options.exclude);
877
- this.#maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
878
- this.#embeddingBatchSize = options.embeddingBatchSize ?? DEFAULT_BATCH_SIZE;
879
- this.#onWarning = options.onWarning ?? console.warn;
880
- assertPositiveInteger(this.#maxFileSize, "maxFileSize");
881
- assertPositiveInteger(this.#embeddingBatchSize, "embeddingBatchSize");
882
- this.#git = new GitRepository(this.rootDir);
883
- }
884
- #progress(phase, completed, total) {
885
- this.#onProgress?.({ phase, completed, total });
886
- }
887
- close() {
888
- this.#database.close();
889
- }
890
- status() {
891
- return this.#database.status();
892
- }
893
- allFunctions() {
894
- return this.#database.allFunctions();
895
- }
896
- indexErrors() {
897
- return this.#database.indexErrors();
898
- }
899
- async updateFiles(options) {
900
- throwIfAborted(options.signal);
901
- const gitignore = GitignoreRules.workingTree(this.rootDir);
902
- const generation = this.#database.getGeneration();
903
- const normalizedRenames = (options.renames ?? []).map(({ from, to }) => ({
904
- from: normalizeRelativePath(this.rootDir, from),
905
- to: normalizeRelativePath(this.rootDir, to)
906
- }));
907
- validateRenames(normalizedRenames);
908
- const upsertPaths = [...new Set((options.upsert ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];
909
- const deletePaths = [...new Set((options.delete ?? []).map((value) => normalizeRelativePath(this.rootDir, value)))];
910
- const renameMap = new Map(
911
- normalizedRenames.map(({ from, to }) => [to, from])
912
- );
913
- for (const target of renameMap.keys()) {
914
- if (!upsertPaths.includes(target)) upsertPaths.push(target);
915
- }
916
- const prepared = [];
917
- for (const relativePath of upsertPaths) {
918
- throwIfAborted(options.signal);
919
- if (!this.#policy.includes(relativePath) || await gitignore.ignores(relativePath)) {
920
- throw new CodeIndexError(`Unsupported or excluded source file: ${relativePath}`);
921
- }
922
- const renameSource = renameMap.get(relativePath);
923
- const originalPath = renameSource ? this.#database.previousPath(renameSource) ?? renameSource : void 0;
924
- const file = await this.#prepareWorkingFile(relativePath, {
925
- blobOid: null,
926
- sourceMode: "working-tree",
927
- indexedCommit: null,
928
- ...originalPath ? { previousPath: originalPath } : {},
929
- ...renameSource ? { replacePath: renameSource } : {}
930
- }, true);
931
- if (file) prepared.push(file);
932
- }
933
- let embeddingsCreated = await this.#attachEmbeddings(prepared, options.signal);
934
- for (let attempt = 0; ; attempt += 1) {
935
- await gitignore.assertUnchanged(options.signal);
936
- const changed = [];
937
- for (let index = 0; index < prepared.length; index += 1) {
938
- const file = prepared[index];
939
- if (!this.#workingFileChangedSynchronously(file)) continue;
940
- if (attempt >= 2) throw new CodeIndexError(`Source changed repeatedly while indexing: ${file.path}; retry the update.`);
941
- const refreshed = await this.#prepareWorkingFile(file.path, {
942
- blobOid: null,
943
- sourceMode: "working-tree",
944
- indexedCommit: null,
945
- ...file.previousPath ? { previousPath: file.previousPath } : {},
946
- ...file.replacePath ? { replacePath: file.replacePath } : {}
947
- }, true);
948
- if (!refreshed) throw new CodeIndexError(`Source changed while indexing: ${file.path}; retry the update.`);
949
- prepared[index] = refreshed;
950
- changed.push(refreshed);
951
- }
952
- if (changed.length === 0) break;
953
- embeddingsCreated += await this.#attachEmbeddings(changed, options.signal);
954
- }
955
- return this.#database.applyUpdate({
956
- files: prepared,
957
- deletePaths: [...deletePaths, ...renameMap.values()],
958
- expectedGeneration: generation,
959
- embeddingsCreated
960
- });
961
- }
962
- async updateFromWorkingTree(options = {}) {
963
- throwIfAborted(options.signal);
964
- const generation = this.#database.getGeneration();
965
- const indexedFiles = this.#database.getFileStates();
966
- const gitignore = GitignoreRules.workingTree(this.rootDir);
967
- let sourcePaths = await this.#workingTreeSourcePaths(gitignore, options.signal);
968
- let prepared = await this.#prepareWorkingPaths(sourcePaths, options.signal);
969
- let embeddingsCreated = await this.#attachEmbeddings(prepared, options.signal);
970
- while (true) {
971
- await gitignore.assertUnchanged(options.signal);
972
- const pathsAgain = await this.#workingTreeSourcePaths(gitignore, options.signal);
973
- if (JSON.stringify(pathsAgain) !== JSON.stringify(sourcePaths)) {
974
- sourcePaths = pathsAgain;
975
- prepared = await this.#prepareWorkingPaths(sourcePaths, options.signal);
976
- embeddingsCreated += await this.#attachEmbeddings(prepared, options.signal);
977
- continue;
978
- }
979
- const changed = [];
980
- for (let index = 0; index < prepared.length; index += 1) {
981
- const file = prepared[index];
982
- if (!await this.#workingFileChanged(file)) continue;
983
- const refreshed = await this.#prepareWorkingFile(file.path, {
984
- blobOid: null,
985
- sourceMode: "working-tree",
986
- indexedCommit: null
987
- });
988
- if (!refreshed) {
989
- sourcePaths = await this.#workingTreeSourcePaths(gitignore, options.signal);
990
- prepared = await this.#prepareWorkingPaths(sourcePaths, options.signal);
991
- changed.push(...prepared);
992
- break;
993
- }
994
- prepared[index] = refreshed;
995
- changed.push(refreshed);
996
- }
997
- if (changed.length === 0) break;
998
- embeddingsCreated += await this.#attachEmbeddings(changed, options.signal);
999
- }
1000
- await gitignore.assertUnchanged(options.signal);
1001
- if (this.#isWorkingTreeClean(indexedFiles, prepared)) {
1002
- return emptyStats(this.#database.getCheckpoint());
1003
- }
1004
- return this.#database.applyUpdate({
1005
- files: prepared,
1006
- deletePaths: indexedFiles.map((file) => file.path),
1007
- checkpoint: null,
1008
- expectedGeneration: generation,
1009
- completeDiagnosticsScan: true,
1010
- embeddingsCreated
1011
- });
1012
- }
1013
- /**
1014
- * Whether a working-tree refresh changed nothing: same file set, same
1015
- * content, same language, and still working-tree rows, with no checkout to
1016
- * clear. Recorded indexing errors never force a refresh on their own; a
1017
- * file with errors is retried only when its content changes or via an
1018
- * explicit updateFiles upsert. Skipping the write avoids a generation
1019
- * bump and, via foreign-key cascades, needlessly invalidating the
1020
- * similarity cache for unchanged files. Description state must already be
1021
- * quiescent: a refresh is what lazily clears stored descriptions after
1022
- * disableDescriptions, so a stale description count must fall through to
1023
- * the rewrite, and enabled indexes keep the legacy behavior.
1024
- */
1025
- #isWorkingTreeClean(indexedFiles, prepared) {
1026
- if (this.#database.getCheckpoint() !== null) return false;
1027
- if (this.#database.descriptionsEnabled()) return false;
1028
- if (indexedFiles.length !== prepared.length) return false;
1029
- const status = this.status();
1030
- if (status.descriptionCount > 0 || status.fileDescriptionCount > 0) return false;
1031
- const indexedByPath = new Map(indexedFiles.map((file) => [file.path, file]));
1032
- return prepared.every((file) => {
1033
- const indexed = indexedByPath.get(file.path);
1034
- return !!indexed && indexed.sourceMode === "working-tree" && indexed.blobOid === file.blobOid && indexed.language === file.language && indexed.contentHash === file.contentHash;
1035
- });
1036
- }
1037
- async updateFromGit(options = {}) {
1038
- throwIfAborted(options.signal);
1039
- await this.#git.assertRepository();
1040
- const relativeIndexPath = path5.relative(this.rootDir, this.indexPath).replaceAll(path5.sep, "/");
1041
- const indexArtifacts = relativeIndexPath && !relativeIndexPath.startsWith("../") ? [relativeIndexPath, `${relativeIndexPath}-shm`, `${relativeIndexPath}-wal`, `${relativeIndexPath}-journal`] : [];
1042
- const target = await this.#git.resolveCommit(options.target ?? "HEAD");
1043
- const head = await this.#git.resolveCommit("HEAD");
1044
- const overlayWorkingTree = target === head && options.includeWorkingTree !== false;
1045
- const checkpoint = this.#database.getCheckpoint();
1046
- const generation = this.#database.getGeneration();
1047
- const tooLargePaths = new Set(this.#database.filesWithFileTooLargeErrors());
1048
- let reconcileAll = checkpoint === null;
1049
- if (checkpoint && !await this.#git.isAncestor(checkpoint, target)) {
1050
- if (!options.rebuildOnDivergence) throw new GitDivergenceError(checkpoint, target);
1051
- reconcileAll = true;
1052
- }
1053
- const tree = await this.#git.listTree(target);
1054
- const indexedFiles = this.#database.getFileStates();
1055
- const indexedByPath = new Map(indexedFiles.map((file) => [file.path, file]));
1056
- const workingFiles = indexedFiles.filter((file) => file.sourceMode === "working-tree");
1057
- const workingChanges = overlayWorkingTree ? await this.#git.workTreeChanges(target, indexArtifacts) : [];
1058
- const gitignore = overlayWorkingTree ? GitignoreRules.workingTree(this.rootDir) : new GitignoreRules(async (filePath) => {
1059
- const entry = tree.get(filePath);
1060
- return entry ? (await this.#git.readBlob(entry.oid)).toString("utf8") : null;
1061
- });
1062
- const allowedPaths = /* @__PURE__ */ new Set();
1063
- const candidatePaths = /* @__PURE__ */ new Set([
1064
- ...tree.keys(),
1065
- ...workingChanges.map((change) => change.path),
1066
- ...indexedFiles.map((file) => file.path)
1067
- ]);
1068
- for (const filePath of candidatePaths) {
1069
- throwIfAborted(options.signal);
1070
- if (this.#policy.includes(filePath) && !await gitignore.ignores(filePath)) allowedPaths.add(filePath);
1071
- }
1072
- const visibleWorkingPaths = new Set(
1073
- workingChanges.filter((change) => change.status !== "D").map((change) => change.path)
1074
- );
1075
- const changes = reconcileAll || !checkpoint ? [] : await this.#git.diff(checkpoint, target);
1076
- const upserts = /* @__PURE__ */ new Map();
1077
- const deletes = /* @__PURE__ */ new Set();
1078
- const eligibleEntries = [...tree.values()].filter((entry) => allowedPaths.has(entry.path));
1079
- const eligibleTargetPaths = new Set(eligibleEntries.map((entry) => entry.path));
1080
- if (reconcileAll) {
1081
- const renameCandidates = indexedFiles.filter((file) => file.sourceMode === "git" && file.blobOid && !eligibleTargetPaths.has(file.path));
1082
- const claimedRenameSources = /* @__PURE__ */ new Set();
1083
- for (const entry of eligibleEntries) {
1084
- const indexed = indexedByPath.get(entry.path);
1085
- if (indexed?.sourceMode === "git" && indexed.blobOid === entry.oid && entry.size > this.#maxFileSize === tooLargePaths.has(entry.path)) continue;
1086
- const matches = renameCandidates.filter((candidate) => candidate.blobOid === entry.oid && !claimedRenameSources.has(candidate.path));
1087
- const previousPath = matches.length === 1 ? matches[0].path : void 0;
1088
- if (previousPath) claimedRenameSources.add(previousPath);
1089
- upserts.set(entry.path, { entry, ...previousPath ? { previousPath } : {} });
1090
- }
1091
- for (const indexed of indexedFiles) {
1092
- if (!eligibleTargetPaths.has(indexed.path)) deletes.add(indexed.path);
1093
- }
1094
- } else {
1095
- this.#classifyGitChanges(changes, tree, upserts, deletes, allowedPaths);
1096
- const indexedPaths = new Set(indexedByPath.keys());
1097
- for (const targetPath of eligibleTargetPaths) {
1098
- const indexed = indexedByPath.get(targetPath);
1099
- const entry = tree.get(targetPath);
1100
- const sizeStateFlipped = indexed?.sourceMode === "git" && indexed.blobOid === entry.oid && entry.size > this.#maxFileSize !== tooLargePaths.has(targetPath);
1101
- if ((!indexed || indexed.sourceMode === "git" && indexed.blobOid !== entry.oid || sizeStateFlipped) && !upserts.has(targetPath)) {
1102
- upserts.set(targetPath, { entry });
1103
- }
1104
- }
1105
- for (const indexedPath of indexedPaths) {
1106
- if (!eligibleTargetPaths.has(indexedPath)) deletes.add(indexedPath);
1107
- }
1108
- }
1109
- for (const dirtyFile of workingFiles) {
1110
- const entry = tree.get(dirtyFile.path);
1111
- const previousEntry = dirtyFile.previousPath ? tree.get(dirtyFile.previousPath) : void 0;
1112
- if (previousEntry && allowedPaths.has(previousEntry.path) && (entry !== void 0 || !visibleWorkingPaths.has(dirtyFile.path))) {
1113
- const currentPlan = entry ? upserts.get(dirtyFile.path) : void 0;
1114
- upserts.delete(dirtyFile.path);
1115
- upserts.delete(previousEntry.path);
1116
- upserts.set(previousEntry.path, { entry: previousEntry, previousPath: dirtyFile.path });
1117
- if (entry && allowedPaths.has(entry.path)) {
1118
- upserts.set(dirtyFile.path, currentPlan ?? { entry });
1119
- }
1120
- continue;
1121
- }
1122
- if (entry && allowedPaths.has(dirtyFile.path)) {
1123
- const planned = upserts.get(dirtyFile.path);
1124
- if (planned?.previousPath && !indexedByPath.has(planned.previousPath)) {
1125
- upserts.set(dirtyFile.path, { entry, previousPath: dirtyFile.path });
1126
- } else if (!planned) {
1127
- upserts.set(dirtyFile.path, { entry });
1128
- }
1129
- continue;
1130
- }
1131
- if (previousEntry && allowedPaths.has(previousEntry.path)) {
1132
- upserts.set(previousEntry.path, { entry: previousEntry, previousPath: dirtyFile.path });
1133
- } else {
1134
- deletes.add(dirtyFile.path);
1135
- }
1136
- }
1137
- for (const [filePath, { entry, previousPath }] of upserts) {
1138
- const indexed = indexedByPath.get(filePath);
1139
- if (!previousPath && indexed?.sourceMode === "git" && indexed.blobOid === entry.oid && entry.size > this.#maxFileSize === tooLargePaths.has(filePath)) upserts.delete(filePath);
1140
- }
1141
- const workingPrepared = [];
1142
- const workingDeletes = /* @__PURE__ */ new Set();
1143
- const skippedWorkingPaths = /* @__PURE__ */ new Set();
1144
- for (const change of workingChanges) {
1145
- throwIfAborted(options.signal);
1146
- if (change.status === "D") {
1147
- upserts.delete(change.path);
1148
- workingDeletes.add(change.path);
1149
- continue;
1150
- }
1151
- let previousPath;
1152
- let replacePath;
1153
- if (change.status === "R") {
1154
- const plannedBase = upserts.get(change.oldPath);
1155
- const existingAtTarget = indexedByPath.get(change.oldPath);
1156
- const existingAtFinal = indexedByPath.get(change.path);
1157
- const continuingRename = existingAtFinal?.sourceMode === "working-tree" && existingAtFinal.previousPath === change.oldPath;
1158
- replacePath = continuingRename ? change.path : existingAtTarget ? change.oldPath : existingAtFinal ? change.path : plannedBase?.previousPath && indexedByPath.has(plannedBase.previousPath) ? plannedBase.previousPath : void 0;
1159
- previousPath = existingAtFinal?.previousPath ?? change.oldPath;
1160
- upserts.delete(change.oldPath);
1161
- upserts.delete(change.path);
1162
- if (replacePath) deletes.delete(replacePath);
1163
- workingDeletes.add(change.oldPath);
1164
- } else {
1165
- const planned = upserts.get(change.path);
1166
- const existing = indexedByPath.get(change.path);
1167
- replacePath = existing ? change.path : planned?.previousPath && indexedByPath.has(planned.previousPath) ? planned.previousPath : void 0;
1168
- previousPath = existing?.previousPath ?? planned?.previousPath;
1169
- upserts.delete(change.path);
1170
- if (replacePath) deletes.delete(replacePath);
1171
- }
1172
- const relativePath = change.path;
1173
- if (!allowedPaths.has(relativePath)) {
1174
- if (replacePath) workingDeletes.add(replacePath);
1175
- workingDeletes.add(relativePath);
1176
- continue;
1177
- }
1178
- const file = await this.#prepareWorkingFile(relativePath, {
1179
- blobOid: null,
1180
- sourceMode: "working-tree",
1181
- indexedCommit: null
1182
- });
1183
- if (!file) {
1184
- if (replacePath) workingDeletes.add(replacePath);
1185
- workingDeletes.add(relativePath);
1186
- skippedWorkingPaths.add(relativePath);
1187
- continue;
1188
- }
1189
- if (!file.unavailable && !replacePath && change.status === "A") {
1190
- const contentHash = file.contentHash;
1191
- const renameCandidates = workingFiles.filter((file2) => file2.path !== relativePath && !visibleWorkingPaths.has(file2.path) && deletes.has(file2.path) && file2.contentHash === contentHash);
1192
- const renamed = renameCandidates.length === 1 ? renameCandidates[0] : void 0;
1193
- if (renamed) {
1194
- replacePath = renamed.path;
1195
- previousPath = renamed.previousPath ?? renamed.path;
1196
- deletes.delete(renamed.path);
1197
- }
1198
- }
1199
- workingPrepared.push({
1200
- ...file,
1201
- ...previousPath ? { previousPath } : {},
1202
- ...replacePath ? { replacePath } : {}
1203
- });
1204
- }
1205
- const prepared = [];
1206
- for (const { entry, previousPath } of upserts.values()) {
1207
- throwIfAborted(options.signal);
1208
- const provenance = {
1209
- blobOid: entry.oid,
1210
- sourceMode: "git",
1211
- indexedCommit: target,
1212
- ...previousPath ? { replacePath: previousPath } : {}
1213
- };
1214
- if (entry.size > this.#maxFileSize) {
1215
- prepared.push(this.#failedFile(entry.path, "file-too-large", `File exceeds maxFileSize (${this.#maxFileSize} bytes).`, provenance, entry.size));
1216
- continue;
1217
- }
1218
- try {
1219
- const content = await this.#git.readBlob(entry.oid);
1220
- prepared.push(this.#prepareFile(entry.path, content, provenance));
1221
- } catch (error) {
1222
- prepared.push(this.#failedFile(entry.path, "read-error", error instanceof Error ? error.message : String(error), provenance, entry.size));
1223
- }
1224
- }
1225
- let embeddingsCreated = await this.#attachEmbeddings([...prepared, ...workingPrepared], options.signal);
1226
- const noChanges = !reconcileAll && checkpoint === target && prepared.length === 0 && deletes.size === 0 && workingPrepared.length === 0 && workingDeletes.size === 0;
1227
- while (true) {
1228
- const resolvedAgain = await this.#git.resolveCommit(options.target ?? "HEAD");
1229
- if (resolvedAgain !== target) throw new CodeIndexError("Target Git ref changed while indexing; retry the update.");
1230
- if (!overlayWorkingTree) break;
1231
- const headAgain = await this.#git.resolveCommit("HEAD");
1232
- const workingChangesAgain = await this.#git.workTreeChanges(target, indexArtifacts);
1233
- if (headAgain !== head) throw new CodeIndexError("Git HEAD changed while indexing; retry the update.");
1234
- if (JSON.stringify(workingChangesAgain) !== JSON.stringify(workingChanges)) return await this.updateFromGit(options);
1235
- const changed = [];
1236
- for (let index = 0; index < workingPrepared.length; index += 1) {
1237
- const file = workingPrepared[index];
1238
- if (!await this.#workingFileChanged(file)) continue;
1239
- const refreshed = await this.#prepareWorkingFile(file.path, {
1240
- blobOid: null,
1241
- sourceMode: "working-tree",
1242
- indexedCommit: null,
1243
- ...file.previousPath ? { previousPath: file.previousPath } : {},
1244
- ...file.replacePath ? { replacePath: file.replacePath } : {}
1245
- });
1246
- if (!refreshed) return await this.updateFromGit(options);
1247
- workingPrepared[index] = refreshed;
1248
- changed.push(refreshed);
1249
- }
1250
- for (const relativePath of skippedWorkingPaths) {
1251
- const refreshed = await this.#prepareWorkingFile(relativePath, {
1252
- blobOid: null,
1253
- sourceMode: "working-tree",
1254
- indexedCommit: null
1255
- });
1256
- if (refreshed && !refreshed.unavailable) return await this.updateFromGit(options);
1257
- }
1258
- if (changed.length > 0) {
1259
- embeddingsCreated += await this.#attachEmbeddings(changed, options.signal);
1260
- continue;
1261
- }
1262
- await gitignore.assertUnchanged(options.signal);
1263
- break;
1264
- }
1265
- if (noChanges) {
1266
- if (this.#database.getCheckpoint() !== checkpoint || this.#database.getGeneration() !== generation) {
1267
- throw new CodeIndexError("Index changed while the update was being prepared; retry the update.");
1268
- }
1269
- return emptyStats(checkpoint);
1270
- }
1271
- return this.#database.applyUpdate({
1272
- files: prepared,
1273
- deletePaths: [...deletes],
1274
- workingTree: {
1275
- files: workingPrepared,
1276
- deletePaths: [...workingDeletes]
1277
- },
1278
- checkpoint: target,
1279
- expectedCheckpoint: checkpoint,
1280
- expectedGeneration: generation,
1281
- completeDiagnosticsScan: true,
1282
- embeddingsCreated
1283
- });
1284
- }
1285
- #classifyGitChanges(changes, tree, upserts, deletes, allowedPaths) {
1286
- for (const change of changes) {
1287
- if (change.status === "D") {
1288
- deletes.add(change.path);
1289
- continue;
1290
- }
1291
- if (change.status === "R") {
1292
- deletes.add(change.oldPath);
1293
- const entry2 = tree.get(change.path);
1294
- if (entry2 && allowedPaths.has(change.path)) {
1295
- upserts.set(change.path, { entry: entry2, previousPath: change.oldPath });
1296
- }
1297
- continue;
1298
- }
1299
- const entry = tree.get(change.path);
1300
- if (entry && allowedPaths.has(change.path)) upserts.set(change.path, { entry });
1301
- else deletes.add(change.path);
1302
- }
1303
- }
1304
- async #workingTreeSourcePaths(gitignore, signal) {
1305
- const relativeIndexPath = path5.relative(this.rootDir, this.indexPath).replaceAll(path5.sep, "/");
1306
- const indexArtifacts = new Set(relativeIndexPath && !relativeIndexPath.startsWith("../") ? [relativeIndexPath, `${relativeIndexPath}-shm`, `${relativeIndexPath}-wal`, `${relativeIndexPath}-journal`] : []);
1307
- const directories = [""];
1308
- const sourcePaths = [];
1309
- while (directories.length > 0) {
1310
- throwIfAborted(signal);
1311
- const relativeDirectory = directories.shift();
1312
- const entries = await readdir(path5.join(this.rootDir, relativeDirectory), { withFileTypes: true });
1313
- entries.sort((left, right) => left.name.localeCompare(right.name));
1314
- for (const entry of entries) {
1315
- const relativePath = relativeDirectory ? `${relativeDirectory.replaceAll(path5.sep, "/")}/${entry.name}` : entry.name;
1316
- if (entry.isDirectory()) {
1317
- if (this.#policy.traversesDirectory(relativePath) && !await gitignore.ignores(relativePath, true)) directories.push(relativePath);
1318
- } else if (entry.isFile() && !indexArtifacts.has(relativePath) && this.#policy.includes(relativePath) && !await gitignore.ignores(relativePath)) {
1319
- sourcePaths.push(relativePath);
1320
- }
1321
- }
1322
- }
1323
- sourcePaths.sort();
1324
- return sourcePaths;
1325
- }
1326
- async #prepareWorkingPaths(relativePaths, signal) {
1327
- const prepared = [];
1328
- for (const relativePath of relativePaths) {
1329
- throwIfAborted(signal);
1330
- const file = await this.#prepareWorkingFile(relativePath, {
1331
- blobOid: null,
1332
- sourceMode: "working-tree",
1333
- indexedCommit: null
1334
- });
1335
- if (file) prepared.push(file);
1336
- }
1337
- return prepared;
1338
- }
1339
- async #workingFileChanged(file) {
1340
- try {
1341
- const info = await lstat3(path5.join(this.rootDir, file.path));
1342
- if (!info.isFile() || info.isSymbolicLink() || info.size !== file.byteSize) return true;
1343
- if (info.size > this.#maxFileSize) return !file.errors.some((error) => error.code === "file-too-large");
1344
- const content = await readFile2(path5.join(this.rootDir, file.path));
1345
- return file.unavailable === true || sha256(content.toString("utf8")) !== file.contentHash;
1346
- } catch {
1347
- return file.unavailable !== true;
1348
- }
1349
- }
1350
- #workingFileChangedSynchronously(file) {
1351
- try {
1352
- const absolutePath = path5.join(this.rootDir, file.path);
1353
- const info = lstatSync(absolutePath);
1354
- if (!info.isFile() || info.isSymbolicLink() || info.size !== file.byteSize) return true;
1355
- if (info.size > this.#maxFileSize) return !file.errors.some((error) => error.code === "file-too-large");
1356
- const contentHash = sha256(readFileSync(absolutePath, "utf8"));
1357
- return file.unavailable === true || contentHash !== file.contentHash;
1358
- } catch {
1359
- return file.unavailable !== true;
1360
- }
1361
- }
1362
- #prepareFile(relativePath, buffer, provenance) {
1363
- const content = buffer.toString("utf8");
1364
- const contentHash = sha256(content);
1365
- const parseKey = sha256(`${CALLABLE_PARSER_CACHE_VERSION}\0${relativePath}\0${contentHash}`);
1366
- let parsed = this.#database.cachedParse(parseKey);
1367
- if (!parsed) {
1368
- parsed = parseFileCallables(relativePath, content, this.#onWarning);
1369
- if (!parsed.errors.some((error) => error.code === "parse-failed" || error.code === "extraction-error")) {
1370
- this.#database.storeParse(parseKey, parsed);
1371
- }
1372
- } else if (parsed.errors.length > 0) {
1373
- this.#onWarning(`Cannot fully parse ${relativePath}: tree-sitter reported syntax errors; indexing recoverable callables only.`);
1374
- }
1375
- const language = languageForPath(relativePath) ?? path5.extname(relativePath).slice(1);
1376
- return {
1377
- path: relativePath,
1378
- contentHash,
1379
- blobOid: provenance.blobOid,
1380
- sourceMode: provenance.sourceMode,
1381
- indexedCommit: provenance.indexedCommit,
1382
- language,
1383
- byteSize: buffer.byteLength,
1384
- source: content,
1385
- ...provenance.previousPath ? { previousPath: provenance.previousPath } : {},
1386
- ...provenance.replacePath ? { replacePath: provenance.replacePath } : {},
1387
- callables: parsed.callables,
1388
- errors: parsed.errors
1389
- };
1390
- }
1391
- async #prepareWorkingFile(relativePath, provenance, strict = false) {
1392
- let size = 0;
1393
- try {
1394
- const absolutePath = path5.join(this.rootDir, relativePath);
1395
- const info = await lstat3(absolutePath);
1396
- if (info.isSymbolicLink() || !info.isFile()) {
1397
- if (strict) throw new CodeIndexError(`Not a regular file or symbolic links are not supported: ${relativePath}`);
1398
- return null;
1399
- }
1400
- size = info.size;
1401
- if (size > this.#maxFileSize) {
1402
- return this.#failedFile(relativePath, "file-too-large", `File exceeds maxFileSize (${this.#maxFileSize} bytes).`, provenance, size);
1403
- }
1404
- return this.#prepareFile(relativePath, await readFile2(absolutePath), provenance);
1405
- } catch (error) {
1406
- if (error instanceof CodeIndexError) throw error;
1407
- return this.#failedFile(relativePath, "read-error", error instanceof Error ? error.message : String(error), provenance, size);
1408
- }
1409
- }
1410
- #failedFile(relativePath, code, message, provenance, byteSize) {
1411
- this.#onWarning(`Cannot index ${relativePath}: ${message}`);
1412
- return {
1413
- ...provenance,
1414
- path: relativePath,
1415
- contentHash: sha256(""),
1416
- source: "",
1417
- byteSize,
1418
- language: languageForPath(relativePath) ?? "unknown",
1419
- callables: [],
1420
- unavailable: true,
1421
- errors: [{
1422
- path: relativePath,
1423
- language: languageForPath(relativePath),
1424
- scope: "file",
1425
- code,
1426
- message,
1427
- qualifiedName: null,
1428
- startLine: null,
1429
- startColumn: null,
1430
- endLine: null,
1431
- endColumn: null,
1432
- source: null
1433
- }]
1434
- };
1435
- }
1436
- async #attachEmbeddings(files, signal) {
1437
- if (this.#database.descriptionsEnabled()) {
1438
- await this.#attachDescriptions(files.filter((file) => !file.unavailable), signal);
1439
- }
1440
- throwIfAborted(signal);
1441
- const profile = JSON.stringify(normalizeProfile(this.provider.profile));
1442
- const unique = /* @__PURE__ */ new Map();
1443
- for (const file of files) {
1444
- for (const callable of file.callables) {
1445
- callable.embeddingKey = embeddingKey(profile, "document", callable.embeddingInput);
1446
- const values = unique.get(callable.embeddingKey) ?? [];
1447
- values.push(callable);
1448
- unique.set(callable.embeddingKey, values);
1449
- }
1450
- }
1451
- const missing = [];
1452
- for (const [key, callables] of unique) {
1453
- const vector = this.#database.cachedEmbedding(key);
1454
- if (vector) {
1455
- for (const callable of callables) callable.vector = vector;
1456
- } else {
1457
- missing.push([key, callables]);
1458
- }
1459
- }
1460
- if (missing.length === 0) return 0;
1461
- let completed = 0;
1462
- this.#progress("vectors", 0, missing.length);
1463
- await forEachConcurrent(chunk(missing, this.#embeddingBatchSize), this.#parallelism, async (batch, _index, workerSignal) => {
1464
- const vectors = await this.provider.embedDocuments(
1465
- batch.map(([, callables]) => callables[0].embeddingInput),
1466
- { signal: workerSignal }
1467
- );
1468
- if (vectors.length !== batch.length) throw new CodeIndexError("Embedding provider returned an unexpected number of vectors.");
1469
- vectors.forEach((vector, index) => {
1470
- const converted = normalizeEmbeddingVector(vector, this.provider.profile.dimensions);
1471
- this.#database.storeEmbedding(batch[index][0], converted);
1472
- for (const callable of batch[index][1]) callable.vector = converted;
1473
- });
1474
- completed += batch.length;
1475
- this.#progress("vectors", completed, missing.length);
1476
- }, signal);
1477
- throwIfAborted(signal);
1478
- return missing.length;
1479
- }
1480
- async #attachDescriptions(files, signal, options = {}) {
1481
- const profile = descriptionProfileJson(this.descriptionProvider.profile);
1482
- const embeddingProfile = JSON.stringify(normalizeProfile(this.provider.profile));
1483
- const prepared = /* @__PURE__ */ new Map();
1484
- const repository = path5.basename(this.rootDir);
1485
- let descriptionsCreated = 0;
1486
- let fileDescriptionsCreated = 0;
1487
- let pending = 0;
1488
- const tasks = [];
1489
- const strategy = this.descriptionProvider.profile.strategyVersion;
1490
- const useLiveReuse = !options.skipCallables && !options.reindexCache && !options.forceCallableDescriptions && !options.ignoreLiveDescriptions;
1491
- const liveCallableDescriptions = useLiveReuse ? this.#database.liveFunctionDescriptions(files.flatMap((file) => file.callables.map((callable) => callable.identityKey))) : /* @__PURE__ */ new Map();
1492
- const liveFileHashes = useLiveReuse && files.length > 0 ? this.#database.liveFileContentHashes(files.map((file) => file.replacePath ?? file.previousPath ?? file.path)) : /* @__PURE__ */ new Map();
1493
- for (const file of files) {
1494
- const lookupPath = file.replacePath ?? file.previousPath ?? file.path;
1495
- const storedFileDescription = this.#database.fileDescription(lookupPath);
1496
- const fileDescriptionKey = sha256(`${profile}\0${repository}\0${file.path}\0${file.contentHash}\0file`);
1497
- const fileAgnosticKey = sha256(`${strategy}\0${repository}\0${file.path}\0${file.contentHash}\0file`);
1498
- const fileCacheKey = options.reindexCache ? sha256(`${fileDescriptionKey}\0reindex\0${storedFileDescription?.description ?? ""}`) : fileDescriptionKey;
1499
- const refreshFileDescription = options.refreshFileDescriptions || !storedFileDescription;
1500
- const fileDescription = refreshFileDescription ? this.#database.cachedDescription(fileCacheKey) ?? (!options.reindexCache ? this.#database.cachedDescription(fileAgnosticKey) : void 0) : storedFileDescription.description;
1501
- const fileUnchanged = liveFileHashes.get(lookupPath) === file.contentHash;
1502
- const descriptions = (options.skipCallables ? [] : file.callables).map((callable) => {
1503
- const descriptionKey = sha256(`${profile}\0${repository}\0${file.path}\0${file.contentHash}\0${callable.identityKey}\0${callable.sourceHash}`);
1504
- const agnosticKey = sha256(`${strategy}\0${repository}\0${file.path}\0${file.contentHash}\0${callable.identityKey}\0${callable.sourceHash}`);
1505
- const cacheKey = options.reindexCache ? sha256(`${descriptionKey}\0reindex\0${this.#database.functionDescription(callable.identityKey) ?? ""}`) : descriptionKey;
1506
- if (useLiveReuse && fileUnchanged) {
1507
- const live = liveCallableDescriptions.get(callable.identityKey);
1508
- if (live?.description && live.sourceHash === callable.sourceHash) {
1509
- return {
1510
- callable,
1511
- descriptionKey,
1512
- cacheKey,
1513
- agnosticKey,
1514
- description: live.description
1515
- };
1516
- }
1517
- }
1518
- const description = options.forceCallableDescriptions || options.reindexCache ? this.#database.cachedDescription(cacheKey) : this.#database.cachedDescription(descriptionKey) ?? this.#database.cachedDescription(agnosticKey);
1519
- return {
1520
- callable,
1521
- descriptionKey,
1522
- cacheKey,
1523
- agnosticKey,
1524
- ...description ? { description } : {}
1525
- };
1526
- });
1527
- pending += (refreshFileDescription && !fileDescription ? 1 : 0) + descriptions.filter(({ description }) => !description).length;
1528
- tasks.push({
1529
- file,
1530
- fileCacheKey,
1531
- fileAgnosticKey,
1532
- fileDescriptionKey,
1533
- refreshFileDescription,
1534
- ...fileDescription ? { fileDescription } : {},
1535
- fileDescriptionPath: refreshFileDescription ? file.path : storedFileDescription.path,
1536
- fileDescriptionContentHash: refreshFileDescription ? file.contentHash : storedFileDescription.contentHash,
1537
- descriptions
1538
- });
1539
- }
1540
- let completed = 0;
1541
- if (pending > 0) this.#progress("descriptions", 0, pending);
1542
- await forEachConcurrent(tasks, this.#parallelism, async (task, _index, workerSignal) => {
1543
- const { file } = task;
1544
- const session = task.refreshFileDescription || task.descriptions.some(({ description }) => !description) ? this.descriptionProvider.startFile?.({ repository, path: file.path, fileSource: file.source }) : void 0;
1545
- let fileDescription = task.fileDescription;
1546
- let fileDescriptionAddedToSession = false;
1547
- if (task.refreshFileDescription && !fileDescription) {
1548
- const generated = session ? await session.describeFile({ signal: workerSignal }) : await this.descriptionProvider.describeFile(
1549
- { repository, path: file.path, fileSource: file.source },
1550
- { signal: workerSignal }
1551
- );
1552
- if (typeof generated !== "string" || !generated.trim()) {
1553
- throw new CodeIndexError("Description provider does not support file descriptions or returned an empty description.");
1554
- }
1555
- fileDescription = this.#database.storeDescription(task.fileCacheKey, generated.trim());
1556
- this.#database.storeDescription(task.fileAgnosticKey, fileDescription);
1557
- fileDescriptionsCreated += 1;
1558
- fileDescriptionAddedToSession = session !== void 0;
1559
- completed += 1;
1560
- this.#progress("descriptions", completed, pending);
1561
- }
1562
- if (session && fileDescription && !fileDescriptionAddedToSession) session.replayFile(fileDescription);
1563
- if (fileDescription) {
1564
- const value = prepareDescription(prepared, embeddingProfile, fileDescription, this.#database);
1565
- file.fileDescription = {
1566
- path: task.fileDescriptionPath,
1567
- contentHash: task.fileDescriptionContentHash,
1568
- descriptionKey: task.fileDescriptionKey,
1569
- value
1570
- };
1571
- }
1572
- for (const entry of task.descriptions) {
1573
- throwIfAborted(workerSignal);
1574
- const { callable, descriptionKey, cacheKey, agnosticKey } = entry;
1575
- let { description } = entry;
1576
- if (!description) {
1577
- const generated = session ? await session.describe(callable, { signal: workerSignal }) : await this.descriptionProvider.describe({ repository, callable, fileSource: file.source }, { signal: workerSignal });
1578
- if (typeof generated !== "string" || !generated.trim()) throw new CodeIndexError("Description provider returned an empty description.");
1579
- description = this.#database.storeDescription(cacheKey, generated.trim());
1580
- this.#database.storeDescription(agnosticKey, description);
1581
- descriptionsCreated += 1;
1582
- completed += 1;
1583
- this.#progress("descriptions", completed, pending);
1584
- } else {
1585
- session?.replay(callable, description);
1586
- }
1587
- callable.descriptionKey = descriptionKey;
1588
- callable.description = prepareDescription(prepared, embeddingProfile, description, this.#database);
1589
- }
1590
- }, signal);
1591
- const missing = [...prepared.values()].filter((description) => !description.vector);
1592
- if (missing.length > 0) {
1593
- let embedded = 0;
1594
- this.#progress("description-vectors", 0, missing.length);
1595
- await forEachConcurrent(chunk(missing, this.#embeddingBatchSize), this.#parallelism, async (batch, _index, workerSignal) => {
1596
- const vectors = await this.provider.embedDocuments(batch.map((value) => value.description), { signal: workerSignal });
1597
- if (vectors.length !== batch.length) throw new CodeIndexError("Embedding provider returned an unexpected number of description vectors.");
1598
- vectors.forEach((vector, index) => {
1599
- const converted = normalizeEmbeddingVector(vector, this.provider.profile.dimensions);
1600
- this.#database.storeEmbedding(batch[index].key, converted);
1601
- batch[index].vector = converted;
1602
- });
1603
- embedded += batch.length;
1604
- this.#progress("description-vectors", embedded, missing.length);
1605
- }, signal);
1606
- }
1607
- throwIfAborted(signal);
1608
- return { descriptionsCreated, fileDescriptionsCreated };
1609
- }
1610
- async useDescriptions(options = {}) {
1611
- throwIfAborted(options.signal);
1612
- const generation = this.#database.getGeneration();
1613
- const functions = this.allFunctions();
1614
- const status = this.status();
1615
- const storedProfile = this.#database.descriptionProfile();
1616
- const strategyChanged = (storedProfile?.strategyVersion ?? this.descriptionProvider.profile.strategyVersion) !== this.descriptionProvider.profile.strategyVersion;
1617
- const profileChanged = descriptionProfileJson(storedProfile ?? this.descriptionProvider.profile) !== descriptionProfileJson(this.descriptionProvider.profile);
1618
- if (this.#database.descriptionsEnabled() && !strategyChanged && functions.every((callable) => callable.descriptionEmbeddingId !== null) && status.fileDescriptionCount === status.describableFileCount) {
1619
- if (profileChanged) this.#database.updateDescriptionProfile(this.descriptionProvider.profile, generation);
1620
- return { descriptionsCreated: 0, fileDescriptionsCreated: 0, descriptionsEnabled: true };
1621
- }
1622
- const files = await this.#descriptionFiles(this.#database.getFileStates().filter((file) => file.describable), functions, options.signal);
1623
- const { descriptionsCreated, fileDescriptionsCreated } = await this.#attachDescriptions(files, options.signal, {
1624
- refreshFileDescriptions: strategyChanged,
1625
- ...strategyChanged ? { ignoreLiveDescriptions: true } : {}
1626
- });
1627
- const ids = new Map(functions.map((callable) => [callable.identityKey, callable.id]));
1628
- this.#database.enableDescriptions(files.flatMap((file) => file.callables.map((callable) => ({
1629
- id: ids.get(callable.identityKey),
1630
- description: callable.description
1631
- }))), files, this.descriptionProvider.profile, generation);
1632
- return { descriptionsCreated, fileDescriptionsCreated, descriptionsEnabled: true };
1633
- }
1634
- async reindexFiles(options = {}) {
1635
- throwIfAborted(options.signal);
1636
- if (!this.#database.descriptionsEnabled()) throw new CodeIndexError("Descriptions are not enabled; run descriptions enable first.");
1637
- const generation = this.#database.getGeneration();
1638
- const states = this.#database.getFileStates().filter((file) => file.describable && (file.fileDescriptionPath !== file.path || file.fileDescriptionContentHash !== file.contentHash));
1639
- const files = await this.#descriptionFiles(states, this.allFunctions(), options.signal);
1640
- const created = await this.#attachDescriptions(files, options.signal, {
1641
- refreshFileDescriptions: true,
1642
- ...options.includeCallables !== void 0 ? { forceCallableDescriptions: options.includeCallables } : {},
1643
- reindexCache: true,
1644
- skipCallables: !options.includeCallables
1645
- });
1646
- this.#database.updateDescriptions(files, options.includeCallables ?? false, generation, this.descriptionProvider.profile);
1647
- return { filesReindexed: files.length, ...created };
1648
- }
1649
- async #descriptionFiles(states, functions, signal) {
1650
- const byPath = groupBy(functions, (callable) => callable.path);
1651
- const files = [];
1652
- for (const file of states) {
1653
- throwIfAborted(signal);
1654
- const buffer = file.sourceMode === "git" && file.blobOid ? await this.#git.readBlob(file.blobOid) : await readFile2(path5.join(this.rootDir, file.path));
1655
- const source = buffer.toString("utf8");
1656
- if (sha256(source) !== file.contentHash) {
1657
- throw new CodeIndexError(`Source changed since indexing: ${file.path}; update the index first.`);
1658
- }
1659
- const callables = byPath.get(file.path) ?? [];
1660
- files.push({
1661
- path: file.path,
1662
- contentHash: file.contentHash,
1663
- blobOid: file.blobOid,
1664
- sourceMode: file.sourceMode,
1665
- indexedCommit: null,
1666
- language: file.language,
1667
- byteSize: buffer.byteLength,
1668
- source,
1669
- errors: [],
1670
- callables: callables.map(({ description: _description, descriptionEmbeddingId: _descriptionEmbeddingId, ...callable }) => ({
1671
- ...callable,
1672
- embeddingKey: ""
1673
- }))
1674
- });
1675
- }
1676
- return files;
1677
- }
1678
- disableDescriptions() {
1679
- this.#database.disableDescriptions();
1680
- return { descriptionsCreated: 0, fileDescriptionsCreated: 0, descriptionsEnabled: false };
1681
- }
1682
- async searchDescription(options) {
1683
- if (!this.#database.descriptionsEnabled()) throw new CodeIndexError("Descriptions are not enabled; run descriptions enable first.");
1684
- if (!options.query.trim()) throw new CodeIndexError("query must not be empty.");
1685
- const limit = options.limit;
1686
- if (limit !== void 0) assertPositiveInteger(limit, "limit");
1687
- const candidateLimit = this.#candidateLimit(limit);
1688
- compileNameRegex(options.nameRegex);
1689
- throwIfAborted(options.signal);
1690
- const vector = await this.#queryEmbedding(options.query, options.signal);
1691
- throwIfAborted(options.signal);
1692
- const includeFileDescriptions = this.#descriptionScoringAvailable();
1693
- const results = this.#database.searchVector(vector, {
1694
- descriptions: true,
1695
- ...candidateLimit === void 0 ? {} : { limit: candidateLimit },
1696
- minSimilarity: options.minSimilarity ?? -1,
1697
- ...includeFileDescriptions ? { fileDescriptionVector: vector } : {},
1698
- ...options.nameRegex !== void 0 ? { nameRegex: options.nameRegex } : {},
1699
- ...options.maxSimilarity !== void 0 ? { maxSimilarity: options.maxSimilarity } : {}
1700
- });
1701
- return await this.#rerank(options.query, results, limit, options.signal);
1702
- }
1703
- async similaritySearch(options) {
1704
- if (!options.query.trim()) throw new CodeIndexError("query must not be empty.");
1705
- const limit = options.limit;
1706
- if (limit !== void 0) assertPositiveInteger(limit, "limit");
1707
- const candidateLimit = this.#candidateLimit(limit);
1708
- compileNameRegex(options.nameRegex);
1709
- throwIfAborted(options.signal);
1710
- const vector = await this.#queryEmbedding(options.query, options.signal);
1711
- const includeDescriptions = this.#descriptionScoringAvailable();
1712
- const results = this.searchByVector(vector, {
1713
- ...includeDescriptions ? { descriptionVector: vector, fileDescriptionVector: vector } : {},
1714
- ...candidateLimit === void 0 ? {} : { limit: candidateLimit },
1715
- ...options.nameRegex !== void 0 ? { nameRegex: options.nameRegex } : {},
1716
- minSimilarity: options.minSimilarity ?? -1,
1717
- ...options.maxSimilarity !== void 0 ? { maxSimilarity: options.maxSimilarity } : {}
1718
- });
1719
- return await this.#rerank(options.query, results, limit, options.signal);
1720
- }
1721
- #candidateLimit(limit) {
1722
- if (limit === void 0) return void 0;
1723
- if (!this.reranker) return limit;
1724
- if (this.reranker.maximumCandidateCount !== void 0 && limit > this.reranker.maximumCandidateCount) {
1725
- throw new CodeIndexError(`${this.reranker.profile.provider} reranker supports at most ${this.reranker.maximumCandidateCount} results.`);
1726
- }
1727
- const preferred = this.reranker.candidateCount === void 0 ? limit * RERANK_CANDIDATE_MULTIPLIER : Math.max(limit, this.reranker.candidateCount);
1728
- return this.reranker.maximumCandidateCount === void 0 ? preferred : Math.min(preferred, this.reranker.maximumCandidateCount);
1729
- }
1730
- async #rerank(query, candidates, limit, signal) {
1731
- if (!this.reranker || candidates.length === 0) return limit === void 0 ? candidates : candidates.slice(0, limit);
1732
- const documents = candidates.map(({ function: callable }) => [
1733
- `path: ${callable.path}`,
1734
- callable.description ? `description:
1735
- ${callable.description}` : null,
1736
- callable.embeddingInput
1737
- ].filter((value) => value !== null).join("\n"));
1738
- const rerankLimit = limit === void 0 ? candidates.length : Math.min(limit, candidates.length);
1739
- const rankings = await this.reranker.rerank(query, documents, signal ? { limit: rerankLimit, signal } : { limit: rerankLimit });
1740
- throwIfAborted(signal);
1741
- const seen = /* @__PURE__ */ new Set();
1742
- if (rankings.length !== rerankLimit) {
1743
- throw new CodeIndexError(`${this.reranker.profile.provider} returned invalid reranking results.`);
1744
- }
1745
- for (const { index, score } of rankings) {
1746
- if (!Number.isInteger(index) || index < 0 || index >= candidates.length || typeof score !== "number" || !Number.isFinite(score) || seen.has(index)) {
1747
- throw new CodeIndexError(`${this.reranker.profile.provider} returned invalid reranking results.`);
1748
- }
1749
- seen.add(index);
1750
- }
1751
- return rankings.map(({ index, score }) => ({ ...candidates[index], rerankScore: score }));
1752
- }
1753
- async #queryEmbedding(query, signal) {
1754
- const profile = JSON.stringify(normalizeProfile(this.provider.profile));
1755
- const key = embeddingKey(profile, "query", query);
1756
- const cached = this.#database.cachedEmbedding(key);
1757
- if (cached) return cached;
1758
- const vector = normalizeEmbeddingVector(
1759
- await this.provider.embedQuery(query, signal ? { signal } : void 0),
1760
- this.provider.profile.dimensions
1761
- );
1762
- this.#database.storeEmbedding(key, vector);
1763
- return vector;
1764
- }
1765
- similarToFunction(functionId, options) {
1766
- const vector = this.#database.vectorForFunction(functionId);
1767
- return this.#database.searchVector(vector, {
1768
- ...options.includeDescriptions ? { descriptionVector: this.#database.vectorForFunction(functionId, "description") } : {},
1769
- ...options.includeDescriptions ? { fileDescriptionVector: this.#database.fileVectorForFunction(functionId) } : {},
1770
- limit: options.limit,
1771
- minSimilarity: options.minSimilarity,
1772
- ...options.maxSimilarity !== void 0 ? { maxSimilarity: options.maxSimilarity } : {},
1773
- excludeId: functionId,
1774
- ...options.excludePaths !== void 0 ? { excludePaths: options.excludePaths } : {},
1775
- ...options.minLines !== void 0 ? { minLines: options.minLines } : {},
1776
- ...options.nameRegex !== void 0 ? { nameRegex: options.nameRegex } : {}
1777
- });
1778
- }
1779
- vectorForFunction(functionId, kind = "code") {
1780
- return this.#database.vectorForFunction(functionId, kind);
1781
- }
1782
- get readOnly() {
1783
- return this.#database.isReadOnly;
1784
- }
1785
- similarityCacheInfo() {
1786
- return this.#database.similarityCacheInfo();
1787
- }
1788
- /**
1789
- * Incrementally refresh the persisted pairwise-similarity cache for same-index
1790
- * analysis. Only pairs scoring at or above `minSimilarity` (the caller's
1791
- * effective threshold) are stored; queries below the cached floor fall back to
1792
- * live vector search. Only functions whose embeddings changed (plus a merge
1793
- * pass over the remaining functions when the changed set is small) are
1794
- * re-queried; unchanged pairs are reused. Lowering the floor below what is
1795
- * cached re-queries every function, since the missing band cannot be rebuilt
1796
- * incrementally; raising it reuses the cache for free. A per-function state
1797
- * row records the embedding triple, floor, row count, and a completeness flag,
1798
- * so a sparse row set is never mistaken for an unfinished computation. Call
1799
- * before cross-search/cohesion, then read through
1800
- * {@link cachedSimilarToFunction}. Best-effort under concurrent writers: a
1801
- * later refresh repairs any rows raced by an overlapping update.
1802
- */
1803
- async refreshSimilarityCache(options = {}) {
1804
- const width = Math.min(
1805
- MAX_SIMILARITY_CACHE_WIDTH,
1806
- Math.max(1, Math.floor(options.width ?? DEFAULT_SIMILARITY_CACHE_WIDTH))
1807
- );
1808
- const floor = options.minSimilarity ?? -1;
1809
- const mode = analysisSimilarity(this.status()).similarityMode;
1810
- const includeDescriptions = mode !== "code";
1811
- if (this.#database.isReadOnly) {
1812
- return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed: 0, pairsStored: 0, skipped: true };
1813
- }
1814
- throwIfAborted(options.signal);
1815
- const generation = this.#database.getGeneration();
1816
- const triples = this.#database.similarityCacheTriples();
1817
- if (triples.length <= 1) {
1818
- return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed: 0, pairsStored: 0, skipped: false };
1819
- }
1820
- const states = this.#database.similarityCacheStates(mode);
1821
- const tripleById = new Map(triples.map((triple) => [triple.functionId, triple]));
1822
- const dirty = /* @__PURE__ */ new Set();
1823
- let expanding = false;
1824
- for (const triple of triples) {
1825
- throwIfAborted(options.signal);
1826
- const state = states.get(triple.functionId);
1827
- if (!state || state.codeEmbeddingId !== triple.codeEmbeddingId || state.descriptionEmbeddingId !== triple.descriptionEmbeddingId || state.fileDescriptionEmbeddingId !== triple.fileDescriptionEmbeddingId || state.cachedWidth < width && !state.complete) {
1828
- dirty.add(triple.functionId);
1829
- } else if (state.floor > floor) {
1830
- expanding = true;
1831
- dirty.add(triple.functionId);
1832
- }
1833
- }
1834
- if (dirty.size === 0 && !expanding) {
1835
- const counts = this.#database.similarityCacheCounts(mode);
1836
- for (const triple of triples) {
1837
- if ((counts.get(triple.functionId) ?? 0) < (states.get(triple.functionId)?.storedCount ?? 0)) {
1838
- dirty.add(triple.functionId);
1839
- }
1840
- }
1841
- }
1842
- let sourcesRefreshed = 0;
1843
- let pairsStored = 0;
1844
- if (dirty.size === 0) {
1845
- return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed, pairsStored, skipped: false };
1846
- }
1847
- const report = options.onProgress ?? this.#onProgress;
1848
- const total = triples.length;
1849
- let completed = 0;
1850
- report?.({ phase: "similarity-cache", completed, total });
1851
- const fullRefresh = states.size === 0 || expanding || dirty.size > Math.max(8, Math.ceil(triples.length * 0.25));
1852
- if (fullRefresh) {
1853
- for (const triple of triples) {
1854
- throwIfAborted(options.signal);
1855
- const scanned = this.similarToFunction(triple.functionId, {
1856
- ...includeDescriptions ? { includeDescriptions: true } : {},
1857
- limit: Math.min(width + 1, triples.length - 1),
1858
- minSimilarity: floor
1859
- });
1860
- const neighbors = scanned.slice(0, width);
1861
- this.#database.storeSimilarityNeighbors(triple.functionId, mode, neighbors, {
1862
- codeEmbeddingId: triple.codeEmbeddingId,
1863
- descriptionEmbeddingId: triple.descriptionEmbeddingId,
1864
- fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,
1865
- cachedWidth: width,
1866
- generation,
1867
- floor,
1868
- complete: scanned.length <= width
1869
- });
1870
- sourcesRefreshed += 1;
1871
- pairsStored += neighbors.length;
1872
- completed += 1;
1873
- report?.({ phase: "similarity-cache", completed, total });
1874
- }
1875
- return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed, pairsStored, skipped: false };
1876
- }
1877
- const functionsById = new Map(this.allFunctions().map((callable) => [callable.id, callable]));
1878
- const lean = /* @__PURE__ */ new Map();
1879
- let scanFloor = floor;
1880
- for (const state of states.values()) scanFloor = Math.min(scanFloor, state.floor);
1881
- for (const dirtyId of dirty) {
1882
- throwIfAborted(options.signal);
1883
- const prior = states.get(dirtyId);
1884
- const keepWidth = Math.max(width, prior?.cachedWidth ?? width);
1885
- const full = this.similarToFunction(dirtyId, {
1886
- ...includeDescriptions ? { includeDescriptions: true } : {},
1887
- limit: triples.length - 1,
1888
- minSimilarity: scanFloor
1889
- });
1890
- const byTarget = /* @__PURE__ */ new Map();
1891
- for (const match of full) byTarget.set(match.function.id, match);
1892
- lean.set(dirtyId, byTarget);
1893
- const triple = tripleById.get(dirtyId);
1894
- const top = full.slice(0, keepWidth);
1895
- this.#database.storeSimilarityNeighbors(dirtyId, mode, top, {
1896
- codeEmbeddingId: triple.codeEmbeddingId,
1897
- descriptionEmbeddingId: triple.descriptionEmbeddingId,
1898
- fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,
1899
- cachedWidth: keepWidth,
1900
- generation,
1901
- floor: scanFloor,
1902
- complete: full.length <= keepWidth
1903
- });
1904
- sourcesRefreshed += 1;
1905
- pairsStored += top.length;
1906
- completed += 1;
1907
- report?.({ phase: "similarity-cache", completed, total });
1908
- }
1909
- for (const triple of triples) {
1910
- throwIfAborted(options.signal);
1911
- if (dirty.has(triple.functionId)) continue;
1912
- const prior = states.get(triple.functionId);
1913
- const keepFloor = Math.min(floor, prior?.floor ?? floor);
1914
- const keepWidth = Math.max(width, prior?.cachedWidth ?? width);
1915
- const cached = this.#database.cachedSimilarityNeighbors(triple.functionId, mode);
1916
- const kept = cached.filter((match) => match.similarity >= keepFloor && !dirty.has(match.function.id) && functionsById.has(match.function.id));
1917
- const added = [];
1918
- for (const [dirtyId, byTarget] of lean) {
1919
- if (dirtyId === triple.functionId) continue;
1920
- const match = byTarget.get(triple.functionId);
1921
- const dirtyFunction = functionsById.get(dirtyId);
1922
- if (match && match.similarity >= keepFloor && dirtyFunction) {
1923
- const { function: _function, ...scores } = match;
1924
- added.push({ ...scores, function: dirtyFunction });
1925
- }
1926
- }
1927
- const plusOne = [...kept, ...added].sort((left, right) => right.similarity - left.similarity || left.function.id - right.function.id).slice(0, keepWidth + 1);
1928
- const merged = plusOne.slice(0, keepWidth);
1929
- const complete = plusOne.length <= keepWidth && (prior?.complete ?? false);
1930
- const unchanged = merged.length === cached.length && merged.every((match, index) => match.function.id === cached[index].function.id && match.similarity === cached[index].similarity);
1931
- if (unchanged) {
1932
- this.#database.touchSimilarityCacheState(triple.functionId, mode, {
1933
- codeEmbeddingId: triple.codeEmbeddingId,
1934
- descriptionEmbeddingId: triple.descriptionEmbeddingId,
1935
- fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,
1936
- cachedWidth: keepWidth,
1937
- generation,
1938
- floor: keepFloor,
1939
- storedCount: merged.length,
1940
- complete
1941
- });
1942
- } else {
1943
- this.#database.storeSimilarityNeighbors(triple.functionId, mode, merged, {
1944
- codeEmbeddingId: triple.codeEmbeddingId,
1945
- descriptionEmbeddingId: triple.descriptionEmbeddingId,
1946
- fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,
1947
- cachedWidth: keepWidth,
1948
- generation,
1949
- floor: keepFloor,
1950
- complete
1951
- });
1952
- pairsStored += merged.length;
1953
- }
1954
- sourcesRefreshed += 1;
1955
- completed += 1;
1956
- report?.({ phase: "similarity-cache", completed, total });
1957
- }
1958
- return { similarityMode: mode, width, minSimilarity: floor, sourcesRefreshed, pairsStored, skipped: false };
1959
- }
1960
- /**
1961
- * Same-index neighbor lookup backed by {@link refreshSimilarityCache}.
1962
- * Returns cache rows filtered exactly like {@link similarToFunction} and falls
1963
- * back to a live vector query whenever the cache entry is missing, stale,
1964
- * computed at a higher floor than requested, or too truncated to satisfy the
1965
- * filters. A cache entry flagged complete holds every pair above its floor,
1966
- * so short results from it are exact and need no live query.
1967
- *
1968
- * Prefer {@link cachedSimilarityReader} inside per-function loops: it loads
1969
- * the validity snapshot once instead of re-reading it for every function.
1970
- */
1971
- cachedSimilarToFunction(functionId, options) {
1972
- return this.cachedSimilarityReader({
1973
- ...options.includeDescriptions ? { includeDescriptions: true } : {}
1974
- }).similarToFunction(functionId, options);
1975
- }
1976
- /**
1977
- * Snapshot the similarity-cache validity state (per-mode states, embedding
1978
- * triples, generation) once for a run of neighbor lookups. The returned
1979
- * lookup behaves exactly like {@link cachedSimilarToFunction} but avoids
1980
- * re-reading whole tables per function; refresh the cache first and create
1981
- * one reader per analysis run. Best-effort under concurrent writers, like the
1982
- * refresh itself: a concurrent mutation mid-run is picked up by the next run.
1983
- *
1984
- * A fallback scan doubles as a read-repair: when the entry is fresh but
1985
- * unusable (missing, recorded at a higher floor, or incomplete), the scan is
1986
- * widened to the full cache width and written back, so later lookups hit.
1987
- * Stale entries are left for the refresh, dense-at-max-width entries cannot
1988
- * be improved, and read-only indexes never write.
1989
- */
1990
- cachedSimilarityReader(options = {}) {
1991
- const mode = options.includeDescriptions ? "code-description-file-average" : "code";
1992
- const states = this.#database.similarityCacheStates(mode);
1993
- const triples = this.#database.similarityCacheTriples();
1994
- const tripleById = new Map(triples.map((triple) => [triple.functionId, triple]));
1995
- const generation = this.#database.getGeneration();
1996
- const readFiltered = (functionId, query) => this.#database.cachedSimilarityNeighbors(functionId, mode, {
1997
- limit: query.limit,
1998
- minSimilarity: query.minSimilarity,
1999
- ...query.maxSimilarity !== void 0 ? { maxSimilarity: query.maxSimilarity } : {},
2000
- ...query.minLines !== void 0 ? { minLines: query.minLines } : {},
2001
- ...query.nameRegex !== void 0 ? { nameRegex: query.nameRegex } : {},
2002
- ...query.excludePaths !== void 0 ? { excludePaths: query.excludePaths } : {}
2003
- });
2004
- return {
2005
- similarToFunction: (functionId, query) => {
2006
- const live = () => this.similarToFunction(functionId, query);
2007
- if (query.includeDescriptions === true !== (mode !== "code")) {
2008
- return live();
2009
- }
2010
- compileNameRegex(query.nameRegex);
2011
- const triple = tripleById.get(functionId);
2012
- if (!triple) {
2013
- return live();
2014
- }
2015
- const state = states.get(functionId);
2016
- const tripleMatches = !!state && triple.codeEmbeddingId === state.codeEmbeddingId && triple.descriptionEmbeddingId === state.descriptionEmbeddingId && triple.fileDescriptionEmbeddingId === state.fileDescriptionEmbeddingId;
2017
- if (state && (!tripleMatches || state.generation !== generation)) {
2018
- return live();
2019
- }
2020
- if (state && state.floor <= query.minSimilarity) {
2021
- const cached2 = readFiltered(functionId, query);
2022
- if (cached2.length >= query.limit) return cached2;
2023
- if (state.complete) return cached2;
2024
- if (state.storedCount >= MAX_SIMILARITY_CACHE_WIDTH) return live();
2025
- } else if (this.#database.isReadOnly || this.#database.getGeneration() !== generation) {
2026
- return live();
2027
- }
2028
- const repairFloor = Math.min(query.minSimilarity, state?.floor ?? query.minSimilarity);
2029
- const width = MAX_SIMILARITY_CACHE_WIDTH;
2030
- const scanned = this.similarToFunction(functionId, {
2031
- ...mode !== "code" ? { includeDescriptions: true } : {},
2032
- limit: Math.min(width + 1, tripleById.size - 1),
2033
- minSimilarity: repairFloor
2034
- });
2035
- const neighbors = scanned.slice(0, width);
2036
- const complete = scanned.length <= width;
2037
- this.#database.storeSimilarityNeighbors(functionId, mode, neighbors, {
2038
- codeEmbeddingId: triple.codeEmbeddingId,
2039
- descriptionEmbeddingId: triple.descriptionEmbeddingId,
2040
- fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,
2041
- cachedWidth: width,
2042
- generation,
2043
- floor: repairFloor,
2044
- complete
2045
- });
2046
- states.set(functionId, {
2047
- codeEmbeddingId: triple.codeEmbeddingId,
2048
- descriptionEmbeddingId: triple.descriptionEmbeddingId,
2049
- fileDescriptionEmbeddingId: triple.fileDescriptionEmbeddingId,
2050
- cachedWidth: width,
2051
- generation,
2052
- floor: repairFloor,
2053
- storedCount: neighbors.length,
2054
- complete
2055
- });
2056
- const cached = readFiltered(functionId, query);
2057
- if (cached.length >= query.limit) return cached;
2058
- if (complete) return cached;
2059
- return live();
2060
- }
2061
- };
2062
- }
2063
- vectorForFile(filePath) {
2064
- return this.#database.vectorForFile(filePath);
2065
- }
2066
- searchByVector(vector, options) {
2067
- return this.#database.searchVector(normalizeEmbeddingVector(vector, this.provider.profile.dimensions), {
2068
- ...options,
2069
- ...options.descriptionVector !== void 0 ? { descriptionVector: normalizeEmbeddingVector(options.descriptionVector, this.provider.profile.dimensions) } : {},
2070
- ...options.fileDescriptionVector !== void 0 ? { fileDescriptionVector: normalizeEmbeddingVector(options.fileDescriptionVector, this.provider.profile.dimensions) } : {}
2071
- });
2072
- }
2073
- #descriptionScoringAvailable() {
2074
- const status = this.status();
2075
- return status.descriptionsEnabled && status.descriptionCount === status.functionCount && status.fileDescriptionCount === status.describableFileCount;
2076
- }
2077
- async sourceFunctions(filter) {
2078
- const nameRegex = compileNameRegex(filter.nameRegex);
2079
- const sourcePath = filter.path ? normalizeRelativePath(this.rootDir, filter.path) : void 0;
2080
- const uncommitted = filter.type === "uncommitted" || filter.type === "changed-since" && filter.uncommitted;
2081
- const functions = filter.type === "changed-since" ? await this.#functionsChangedSince(filter.commit) : this.allFunctions();
2082
- return functions.filter((callable) => (!uncommitted || callable.sourceMode === "working-tree") && (!sourcePath || callable.path === sourcePath || callable.path.startsWith(`${sourcePath}/`)) && (!nameRegex || nameRegex.test(callable.qualifiedName)));
2083
- }
2084
- async #functionsChangedSince(baseRef) {
2085
- await this.#git.assertRepository();
2086
- const checkpoint = this.#database.getCheckpoint();
2087
- if (!checkpoint) throw new CodeIndexError("changed-since requires an index with a Git checkpoint.");
2088
- const base = await this.#git.resolveCommit(baseRef);
2089
- if (!await this.#git.isAncestor(base, checkpoint)) {
2090
- throw new GitDivergenceError(base, checkpoint);
2091
- }
2092
- const changes = await this.#git.diff(base, checkpoint);
2093
- const baseTree = await this.#git.listTree(base);
2094
- const comparisonPaths = /* @__PURE__ */ new Map();
2095
- for (const change of changes) {
2096
- if (change.status === "D") continue;
2097
- if (change.status === "R") comparisonPaths.set(change.path, { basePath: change.oldPath, pathChanged: true });
2098
- else if (change.status === "A" || change.status === "C") comparisonPaths.set(change.path, { basePath: null, pathChanged: false });
2099
- else comparisonPaths.set(change.path, { basePath: change.path, pathChanged: false });
2100
- }
2101
- for (const dirtyFile of this.#database.getWorkingTreeFiles()) {
2102
- const basePath = dirtyFile.previousPath ?? comparisonPaths.get(dirtyFile.path)?.basePath ?? dirtyFile.path;
2103
- comparisonPaths.set(dirtyFile.path, { basePath, pathChanged: basePath !== dirtyFile.path });
2104
- }
2105
- const current = this.#database.functionsForPaths([...comparisonPaths.keys()]);
2106
- const baseFunctionsByCurrentPath = /* @__PURE__ */ new Map();
2107
- for (const [currentPath, { basePath }] of comparisonPaths) {
2108
- if (!basePath) {
2109
- baseFunctionsByCurrentPath.set(currentPath, []);
2110
- continue;
2111
- }
2112
- const entry = baseTree.get(basePath);
2113
- if (!entry) {
2114
- baseFunctionsByCurrentPath.set(currentPath, []);
2115
- continue;
2116
- }
2117
- const content = (await this.#git.readBlob(entry.oid)).toString("utf8");
2118
- baseFunctionsByCurrentPath.set(currentPath, parseCallables(basePath, content, this.#onWarning));
2119
- }
2120
- const currentByPath = groupBy(current, (callable) => callable.path);
2121
- const changedIds = /* @__PURE__ */ new Set();
2122
- for (const [currentPath, currentFunctions] of currentByPath) {
2123
- const comparison = comparisonPaths.get(currentPath);
2124
- for (const id of changedFunctionIds(
2125
- currentFunctions,
2126
- baseFunctionsByCurrentPath.get(currentPath) ?? [],
2127
- comparison.pathChanged
2128
- )) {
2129
- changedIds.add(id);
2130
- }
2131
- }
2132
- return current.filter((callable) => changedIds.has(callable.id));
2133
- }
2134
- };
2135
- function changedFunctionIds(current, base, pathChanged) {
2136
- if (pathChanged) return current.map((callable) => callable.id);
2137
- const currentGroups = groupBy(current, (callable) => `${callable.qualifiedName}\0${callable.kind}`);
2138
- const baseGroups = groupBy(base, (callable) => `${callable.qualifiedName}\0${callable.kind}`);
2139
- const changed = [];
2140
- for (const [key, currentGroup] of currentGroups) {
2141
- const baseGroup = baseGroups.get(key) ?? [];
2142
- const unmatchedBase = new Set(baseGroup.map((_, index) => index));
2143
- const unmatchedCurrent = new Set(currentGroup.map((_, index) => index));
2144
- for (let currentIndex = 0; currentIndex < currentGroup.length; currentIndex += 1) {
2145
- const exactBaseIndex = [...unmatchedBase].find(
2146
- (baseIndex) => baseGroup[baseIndex].sourceHash === currentGroup[currentIndex].sourceHash
2147
- );
2148
- if (exactBaseIndex !== void 0) {
2149
- unmatchedBase.delete(exactBaseIndex);
2150
- unmatchedCurrent.delete(currentIndex);
2151
- }
2152
- }
2153
- for (const currentIndex of unmatchedCurrent) changed.push(currentGroup[currentIndex].id);
2154
- }
2155
- return changed;
2156
- }
2157
- function normalizeProfile(profile) {
2158
- return {
2159
- provider: profile.provider,
2160
- model: profile.model,
2161
- dimensions: profile.dimensions,
2162
- strategyVersion: profile.strategyVersion ?? "callable-v2"
2163
- };
2164
- }
2165
- function descriptionProfileJson(profile) {
2166
- return JSON.stringify({
2167
- provider: profile.provider,
2168
- model: profile.model,
2169
- strategyVersion: profile.strategyVersion
2170
- });
2171
- }
2172
- function embeddingKey(profile, operation, input) {
2173
- return sha256(`${profile}\0${operation}\0${input}`);
2174
- }
2175
- function prepareDescription(prepared, embeddingProfile, description, database) {
2176
- const key = embeddingKey(embeddingProfile, "document", description);
2177
- let value = prepared.get(key);
2178
- if (!value) {
2179
- value = { key, description };
2180
- const vector = database.cachedEmbedding(key);
2181
- if (vector) value.vector = vector;
2182
- prepared.set(key, value);
2183
- }
2184
- return value;
2185
- }
2186
- function emptyStats(checkpoint) {
2187
- return {
2188
- filesUpdated: 0,
2189
- filesDeleted: 0,
2190
- functionsAdded: 0,
2191
- functionsUpdated: 0,
2192
- functionsDeleted: 0,
2193
- embeddingsCreated: 0,
2194
- checkpoint
2195
- };
2196
- }
2197
- function validateRenames(renames) {
2198
- const sources = new Set(renames.map((rename) => rename.from));
2199
- const targets = new Set(renames.map((rename) => rename.to));
2200
- if (sources.size !== renames.length || targets.size !== renames.length) {
2201
- throw new CodeIndexError("Rename sources and targets must be unique.");
2202
- }
2203
- if ([...sources].some((source) => targets.has(source))) {
2204
- throw new CodeIndexError("Chained or cyclic renames must be applied in separate updates.");
2205
- }
2206
- }
2207
- function groupBy(values, keyFor) {
2208
- const groups = /* @__PURE__ */ new Map();
2209
- for (const value of values) {
2210
- const key = keyFor(value);
2211
- const group = groups.get(key) ?? [];
2212
- group.push(value);
2213
- groups.set(key, group);
2214
- }
2215
- return groups;
2216
- }
2217
-
2218
- export {
2219
- CodeIndex
2220
- };
2221
- //# sourceMappingURL=chunk-HMKVMRLF.js.map