@floydous/pi-agent-kernel 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -1,6 +1,6 @@
1
1
  import * as path from "node:path";
2
2
  import * as fs from "node:fs";
3
- import { type SymbolDef, type FileTags } from "./repomap";
3
+ import { type SymbolDef, type FileTags } from "./tag_extractor";
4
4
  import { kernelDebug } from "../safety/kernel_debug";
5
5
 
6
6
  type WtsParser = any;
@@ -32,6 +32,9 @@ const EXTENSION_TO_GRAMMAR: Record<string, LanguageGrammarSpec> = {
32
32
  ".cpp": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
33
33
  ".hpp": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
34
34
  ".cc": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
35
+ ".cxx": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
36
+ ".hh": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
37
+ ".hxx": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
35
38
  // Java
36
39
  ".java": { wasmFile: "tree-sitter-java.wasm", langKey: "java" },
37
40
  // C#
@@ -43,8 +46,42 @@ const EXTENSION_TO_GRAMMAR: Record<string, LanguageGrammarSpec> = {
43
46
  ".rb": { wasmFile: "tree-sitter-ruby.wasm", langKey: "ruby" },
44
47
  // PHP
45
48
  ".php": { wasmFile: "tree-sitter-php.wasm", langKey: "php" },
49
+ // HTML
50
+ ".html": { wasmFile: "tree-sitter-html.wasm", langKey: "html" },
51
+ ".htm": { wasmFile: "tree-sitter-html.wasm", langKey: "html" },
46
52
  };
47
53
 
54
+ // `.h` is shared by C and C++. A header is parsed as C++ only when it has a C++ marker and the C parse has errors
55
+ // that the C++ parse reduces (measured on jq/libuv/ninja/fmt headers: switches no C header, nearly every C++ one).
56
+ const CPP_HEADER_MARKER = /^\s*namespace\s+[\w:]*\s*\{|^\s*template\s*<|^\s*class\s+\w+|^\s*(public|private|protected)\s*:|\w::\w|\bconstexpr\b|\btypename\b/m;
57
+
58
+ // Rust keeps unit tests inside source files. Items under these attributes are test code: #[test], #[cfg(test)],
59
+ // #[cfg(all(test, …))], #[rstest], #[<path>::test] (e.g. tokio::test). #[cfg(not(test))] is not.
60
+ const RUST_TEST_ATTRIBUTE = /^#\[(?:test\]|cfg\((?:all\()?test\b|rstest\b|[\w:]+::test\b)/;
61
+
62
+ /** Marks Rust definitions inside an item that carries a test attribute as kind "test" (for source/test separation). */
63
+ function markRustTests(root: any, definitions: SymbolDef[]): void {
64
+ const ranges: Array<[number, number]> = [];
65
+ const walk = (node: any) => {
66
+ if (node.type === "attribute_item" && RUST_TEST_ATTRIBUTE.test(node.text.replace(/\s+/g, ""))) {
67
+ let item = node.nextNamedSibling;
68
+ while (item && (item.type === "attribute_item" || item.type === "line_comment" || item.type === "block_comment")) item = item.nextNamedSibling;
69
+ if (item) ranges.push([item.startPosition.row + 1, item.endPosition.row + 1]);
70
+ }
71
+ for (let i = 0; i < node.namedChildCount; i++) walk(node.namedChild(i));
72
+ };
73
+ walk(root);
74
+ for (const def of definitions) {
75
+ if (ranges.some(([start, end]) => def.line >= start && def.line <= end)) def.kind = "test";
76
+ }
77
+ }
78
+
79
+ function countErrorNodes(node: any): number {
80
+ let count = node.type === "ERROR" || (typeof node.isMissing === "function" ? node.isMissing() : node.isMissing) ? 1 : 0;
81
+ for (let i = 0; i < node.childCount; i++) count += countErrorNodes(node.child(i));
82
+ return count;
83
+ }
84
+
48
85
  function getGrammarsDir(): string {
49
86
  // Root of agent-kernel extension: ../../grammars relative to src/retrieval or dist/retrieval
50
87
  const candidate1 = path.join(__dirname, "..", "..", "grammars");
@@ -69,6 +106,8 @@ export class TreeSitterEngine {
69
106
  private languages = new Map<string, WtsLanguage>();
70
107
  private ParserClass: any = null;
71
108
  private LanguageClass: any = null;
109
+ // Why a grammar could not be used, by language ("*" = the engine itself), so the fallback is reported, not hidden.
110
+ private loadIssues = new Map<string, string>();
72
111
 
73
112
  public static getInstance(): TreeSitterEngine {
74
113
  if (!TreeSitterEngine.instance) {
@@ -86,15 +125,34 @@ export class TreeSitterEngine {
86
125
  return Object.keys(EXTENSION_TO_GRAMMAR);
87
126
  }
88
127
 
128
+ /** Languages whose grammar could not be used: file not found, failed to load, or the engine failed to start. */
129
+ public getLoadIssues(): Array<{ language: string; extensions: string[]; reason: string }> {
130
+ return [...this.loadIssues].map(([language, reason]) => ({
131
+ language,
132
+ extensions: Object.keys(EXTENSION_TO_GRAMMAR).filter((ext) => language === "*" || EXTENSION_TO_GRAMMAR[ext].langKey === language),
133
+ reason,
134
+ }));
135
+ }
136
+
89
137
  public async init(): Promise<boolean> {
90
138
  if (this.initialized) return true;
91
139
  if (this.initPromise) return this.initPromise;
92
140
 
93
141
  this.initPromise = (async () => {
94
142
  try {
95
- const wts = await import("web-tree-sitter");
96
- this.ParserClass = (wts as any).Parser || (wts as any).default?.Parser || wts;
97
- this.LanguageClass = (wts as any).Language || (wts as any).default?.Language;
143
+ interface WtsModule {
144
+ Parser?: any;
145
+ Language?: any;
146
+ default?: {
147
+ Parser?: any;
148
+ Language?: any;
149
+ };
150
+ }
151
+ // SAFETY: web-tree-sitter exports its Parser and Language classes either directly
152
+ // or on the default export depending on whether it is imported via CJS or ESM loader.
153
+ const wts = (await import("web-tree-sitter")) as unknown as WtsModule;
154
+ this.ParserClass = wts.Parser || wts.default?.Parser || wts;
155
+ this.LanguageClass = wts.Language || wts.default?.Language;
98
156
 
99
157
  let wtsDir = getGrammarsDir();
100
158
  const localWtsWasm = path.join(wtsDir, "web-tree-sitter.wasm");
@@ -115,6 +173,7 @@ export class TreeSitterEngine {
115
173
  return true;
116
174
  } catch (e) {
117
175
  kernelDebug(`TreeSitterEngine init failed: ${e}`);
176
+ this.loadIssues.set("*", `tree-sitter failed to start: ${String(e).split("\n")[0]}`);
118
177
  this.initialized = false;
119
178
  return false;
120
179
  }
@@ -131,6 +190,8 @@ export class TreeSitterEngine {
131
190
  if (!this.initialized || !this.ParserClass || !this.LanguageClass) return;
132
191
 
133
192
  const pending: Promise<void>[] = [];
193
+ // C++ headers named .h need the C++ grammar too (see CPP_HEADER_MARKER).
194
+ if (extensions.includes(".h") && !extensions.includes(".hpp")) extensions = [...extensions, ".hpp"];
134
195
  for (const ext of extensions) {
135
196
  const spec = EXTENSION_TO_GRAMMAR[ext];
136
197
  if (!spec) continue;
@@ -142,11 +203,15 @@ export class TreeSitterEngine {
142
203
  this.LanguageClass.load(wasmPath)
143
204
  .then((lang: any) => {
144
205
  this.languages.set(spec.langKey, lang);
206
+ this.loadIssues.delete(spec.langKey);
145
207
  })
146
208
  .catch((e: any) => {
147
209
  kernelDebug(`Failed to load grammar for ${spec.langKey}: ${e}`);
210
+ this.loadIssues.set(spec.langKey, `grammar failed to load: ${String(e).split("\n")[0]}`);
148
211
  }),
149
212
  );
213
+ } else {
214
+ this.loadIssues.set(spec.langKey, `grammar file ${spec.wasmFile} not found`);
150
215
  }
151
216
  }
152
217
  }
@@ -188,6 +253,33 @@ export class TreeSitterEngine {
188
253
  return null;
189
254
  }
190
255
 
256
+ /**
257
+ * Syntax errors in `content`: ERROR and MISSING nodes (outermost only), with 1-based positions. Both kinds are
258
+ * needed: a missing `)` can recover with a MISSING node and no ERROR node. Null when no grammar is loaded.
259
+ */
260
+ public findSyntaxErrors(ext: string, content: string): Array<{ line: number; column: number; endLine: number; missing?: string; text?: string }> | null {
261
+ const parser = this.getParser(ext);
262
+ if (!parser) return null;
263
+ let tree: any = null;
264
+ try {
265
+ tree = parser.parse(content);
266
+ const errors: Array<{ line: number; column: number; endLine: number; missing?: string; text?: string }> = [];
267
+ const visit = (node: any) => {
268
+ const at = { line: node.startPosition.row + 1, column: node.startPosition.column + 1, endLine: node.endPosition.row + 1 };
269
+ if (typeof node.isMissing === "function" ? node.isMissing() : node.isMissing) errors.push({ ...at, missing: node.type });
270
+ else if (node.type === "ERROR") errors.push({ ...at, text: node.text.trim().split("\n")[0].slice(0, 40) });
271
+ else if (node.hasError) for (let i = 0; i < node.childCount; i++) visit(node.child(i));
272
+ };
273
+ visit(tree.rootNode);
274
+ return errors;
275
+ } catch (e) {
276
+ kernelDebug(`TreeSitterEngine findSyntaxErrors error (${ext}): ${e}`);
277
+ return null;
278
+ } finally {
279
+ tree?.delete();
280
+ }
281
+ }
282
+
191
283
  public extractTags(filePath: string, content: string): FileTags | null {
192
284
  const ext = path.extname(filePath).toLowerCase();
193
285
  let parser = this.getParser(ext);
@@ -198,6 +290,16 @@ export class TreeSitterEngine {
198
290
  let tree: any = null;
199
291
  try {
200
292
  tree = parser.parse(content);
293
+ if (ext === ".h" && tree.rootNode.hasError && CPP_HEADER_MARKER.test(content)) {
294
+ const cppParser = this.getParser(".hpp");
295
+ const cppTree = cppParser ? cppParser.parse(content) : null;
296
+ if (cppTree && countErrorNodes(cppTree.rootNode) < countErrorNodes(tree.rootNode)) {
297
+ tree.delete();
298
+ tree = cppTree;
299
+ } else {
300
+ cppTree?.delete();
301
+ }
302
+ }
201
303
  const root = tree.rootNode;
202
304
  const hasSyntaxError = root.hasError;
203
305
  const definitions: SymbolDef[] = [];
@@ -265,7 +367,8 @@ export class TreeSitterEngine {
265
367
  }
266
368
  // Stop traversal into function body
267
369
  return;
268
- } else if (type === "class_declaration" || type === "abstract_class_declaration") {
370
+ }
371
+ if (type === "class_declaration" || type === "abstract_class_declaration") {
269
372
  const nameNode = node.childForFieldName("name");
270
373
  if (nameNode) {
271
374
  definitions.push({
@@ -284,13 +387,15 @@ export class TreeSitterEngine {
284
387
  }
285
388
  }
286
389
  return;
287
- } else if (type === "ambient_declaration") {
390
+ }
391
+ if (type === "ambient_declaration") {
288
392
  // Unwrap ambient_declaration (e.g. declare function foo(), declare const X)
289
393
  for (const child of node.namedChildren) {
290
394
  visit(child, inFunctionScope);
291
395
  }
292
396
  return;
293
- } else if (type === "function_signature") {
397
+ }
398
+ if (type === "function_signature") {
294
399
  const nameNode = node.childForFieldName("name");
295
400
  if (nameNode) {
296
401
  definitions.push({
@@ -302,7 +407,8 @@ export class TreeSitterEngine {
302
407
  });
303
408
  }
304
409
  return;
305
- } else if (type === "interface_declaration") {
410
+ }
411
+ if (type === "interface_declaration") {
306
412
  const nameNode = node.childForFieldName("name");
307
413
  if (nameNode) {
308
414
  definitions.push({
@@ -320,7 +426,8 @@ export class TreeSitterEngine {
320
426
  }
321
427
  }
322
428
  return;
323
- } else if (type === "method_signature" || type === "abstract_method_signature") {
429
+ }
430
+ if (type === "method_signature" || type === "abstract_method_signature") {
324
431
  const nameNode = node.childForFieldName("name");
325
432
  if (nameNode) {
326
433
  definitions.push({
@@ -332,7 +439,8 @@ export class TreeSitterEngine {
332
439
  });
333
440
  }
334
441
  return;
335
- } else if (type === "type_alias_declaration") {
442
+ }
443
+ if (type === "type_alias_declaration") {
336
444
  const nameNode = node.childForFieldName("name");
337
445
  if (nameNode) {
338
446
  definitions.push({
@@ -344,7 +452,8 @@ export class TreeSitterEngine {
344
452
  });
345
453
  }
346
454
  return;
347
- } else if (type === "enum_declaration") {
455
+ }
456
+ if (type === "enum_declaration") {
348
457
  const nameNode = node.childForFieldName("name");
349
458
  if (nameNode) {
350
459
  definitions.push({
@@ -356,7 +465,8 @@ export class TreeSitterEngine {
356
465
  });
357
466
  }
358
467
  return;
359
- } else if (type === "method_definition") {
468
+ }
469
+ if (type === "method_definition") {
360
470
  const nameNode = node.childForFieldName("name");
361
471
  if (nameNode) {
362
472
  definitions.push({
@@ -369,7 +479,8 @@ export class TreeSitterEngine {
369
479
  }
370
480
  // Method definition has been recorded; do not traverse inside method body
371
481
  return;
372
- } else if ((type === "lexical_declaration" || type === "variable_declaration") && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx" || ext === ".mjs" || ext === ".cjs")) {
482
+ }
483
+ if ((type === "lexical_declaration" || type === "variable_declaration") && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx" || ext === ".mjs" || ext === ".cjs")) {
373
484
  // Only top-level variable declarations (in program or export statement)
374
485
  const isTopLevel = node.parent?.type === "program" || node.parent?.type === "export_statement";
375
486
  if (isTopLevel) {
@@ -380,9 +491,15 @@ export class TreeSitterEngine {
380
491
  if (nameNode) {
381
492
  const isFn = valueNode && (valueNode.type === "arrow_function" || valueNode.type === "function");
382
493
  const isAllUpper = /^[A-Z0-9_]{2,}$/.test(nameNode.text);
494
+ let kind: "function" | "constant" | "variable" = "variable";
495
+ if (isFn) {
496
+ kind = "function";
497
+ } else if (isAllUpper) {
498
+ kind = "constant";
499
+ }
383
500
  definitions.push({
384
501
  name: nameNode.text,
385
- kind: isFn ? "function" : isAllUpper ? "constant" : "variable",
502
+ kind,
386
503
  signature: getCleanSignature(node).replace(/^export\s+/, ""),
387
504
  line: node.startPosition.row + 1,
388
505
  endLine: node.endPosition.row + 1,
@@ -395,7 +512,7 @@ export class TreeSitterEngine {
395
512
  }
396
513
 
397
514
  // --- Python ---
398
- else if (type === "function_definition" && (ext === ".py")) {
515
+ if (type === "function_definition" && (ext === ".py")) {
399
516
  const nameNode = node.childForFieldName("name");
400
517
  if (nameNode) {
401
518
  let isMethod = false;
@@ -416,14 +533,16 @@ export class TreeSitterEngine {
416
533
  });
417
534
  }
418
535
  return;
419
- } else if (type === "decorated_definition" && (ext === ".py")) {
536
+ }
537
+ if (type === "decorated_definition" && (ext === ".py")) {
420
538
  // Unwrap python decorator to find inner function or class definition
421
539
  const defNode = node.childForFieldName("definition") || node.namedChildren.find((c: any) => c.type === "function_definition" || c.type === "class_definition");
422
540
  if (defNode) {
423
541
  visit(defNode, inFunctionScope);
424
542
  }
425
543
  return;
426
- } else if (type === "class_definition" && (ext === ".py")) {
544
+ }
545
+ if (type === "class_definition" && (ext === ".py")) {
427
546
  const nameNode = node.childForFieldName("name");
428
547
  if (nameNode) {
429
548
  definitions.push({
@@ -441,13 +560,14 @@ export class TreeSitterEngine {
441
560
  }
442
561
  }
443
562
  return;
444
- } else if (type === "expression_statement" && (ext === ".py")) {
563
+ }
564
+ if (type === "expression_statement" && (ext === ".py")) {
445
565
  // Expression statements in Python do not define repository symbols
446
566
  return;
447
567
  }
448
568
 
449
569
  // --- Rust ---
450
- else if (type === "function_item") {
570
+ if (type === "function_item") {
451
571
  const nameNode = node.childForFieldName("name");
452
572
  if (nameNode) {
453
573
  const isMethod = node.parent && node.parent.type === "declaration_list" && node.parent.parent && node.parent.parent.type === "impl_item";
@@ -460,7 +580,8 @@ export class TreeSitterEngine {
460
580
  });
461
581
  }
462
582
  return;
463
- } else if (type === "struct_item" || type === "enum_item" || type === "trait_item") {
583
+ }
584
+ if (type === "struct_item" || type === "enum_item" || type === "trait_item") {
464
585
  const nameNode = node.childForFieldName("name");
465
586
  if (nameNode) {
466
587
  definitions.push({
@@ -489,7 +610,8 @@ export class TreeSitterEngine {
489
610
  }
490
611
  }
491
612
  return;
492
- } else if (type === "type_item") {
613
+ }
614
+ if (type === "type_item") {
493
615
  const nameNode = node.childForFieldName("name");
494
616
  if (nameNode) {
495
617
  definitions.push({
@@ -501,7 +623,8 @@ export class TreeSitterEngine {
501
623
  });
502
624
  }
503
625
  return;
504
- } else if (type === "const_item" || type === "static_item") {
626
+ }
627
+ if (type === "const_item" || type === "static_item") {
505
628
  const isTopLevel = node.parent?.type === "source_file" || node.parent?.type === "declaration_list";
506
629
  if (isTopLevel) {
507
630
  const nameNode = node.childForFieldName("name");
@@ -519,7 +642,7 @@ export class TreeSitterEngine {
519
642
  }
520
643
 
521
644
  // --- Go ---
522
- else if (type === "function_declaration") {
645
+ if (type === "function_declaration") {
523
646
  const nameNode = node.childForFieldName("name");
524
647
  if (nameNode) {
525
648
  definitions.push({
@@ -531,7 +654,8 @@ export class TreeSitterEngine {
531
654
  });
532
655
  }
533
656
  return;
534
- } else if (type === "method_declaration") {
657
+ }
658
+ if (type === "method_declaration") {
535
659
  const nameNode = node.childForFieldName("name");
536
660
  if (nameNode) {
537
661
  definitions.push({
@@ -543,7 +667,8 @@ export class TreeSitterEngine {
543
667
  });
544
668
  }
545
669
  return;
546
- } else if (type === "type_declaration") {
670
+ }
671
+ if (type === "type_declaration") {
547
672
  for (const child of node.namedChildren) {
548
673
  if (child.type === "type_spec") {
549
674
  const nameNode = child.childForFieldName("name");
@@ -580,7 +705,7 @@ export class TreeSitterEngine {
580
705
  }
581
706
 
582
707
  // --- C / C++ ---
583
- else if (type === "function_definition" && (ext === ".c" || ext === ".cpp" || ext === ".h" || ext === ".hpp" || ext === ".cc")) {
708
+ if (type === "function_definition" && (ext === ".c" || ext === ".cpp" || ext === ".h" || ext === ".hpp" || ext === ".cc" || ext === ".cxx" || ext === ".hh" || ext === ".hxx")) {
584
709
  let isMethod = false;
585
710
  let p = node.parent;
586
711
  while (p) {
@@ -614,9 +739,12 @@ export class TreeSitterEngine {
614
739
  });
615
740
  }
616
741
  return;
617
- } else if (type === "class_specifier" || type === "struct_specifier") {
742
+ }
743
+ if (type === "class_specifier" || type === "struct_specifier") {
618
744
  const nameNode = node.childForFieldName("name");
619
- if (nameNode) {
745
+ const body = node.childForFieldName("body");
746
+ // Without a body this is a type reference (`struct foo *p`) or forward declaration, not a definition.
747
+ if (nameNode && body) {
620
748
  definitions.push({
621
749
  name: nameNode.text,
622
750
  kind: "class",
@@ -625,7 +753,6 @@ export class TreeSitterEngine {
625
753
  endLine: node.endPosition.row + 1,
626
754
  });
627
755
  }
628
- const body = node.childForFieldName("body");
629
756
  if (body) {
630
757
  for (const member of body.namedChildren) {
631
758
  visit(member, false);
@@ -635,7 +762,7 @@ export class TreeSitterEngine {
635
762
  }
636
763
 
637
764
  // --- Java / C# ---
638
- else if (type === "constructor_declaration" || type === "method_declaration") {
765
+ if (type === "constructor_declaration" || type === "method_declaration") {
639
766
  const nameNode = node.childForFieldName("name");
640
767
  if (nameNode) {
641
768
  definitions.push({
@@ -647,7 +774,8 @@ export class TreeSitterEngine {
647
774
  });
648
775
  }
649
776
  return;
650
- } else if (type === "enum_declaration" && (ext === ".cs" || ext === ".java")) {
777
+ }
778
+ if (type === "enum_declaration" && (ext === ".cs" || ext === ".java")) {
651
779
  const nameNode = node.childForFieldName("name");
652
780
  if (nameNode) {
653
781
  definitions.push({
@@ -662,7 +790,7 @@ export class TreeSitterEngine {
662
790
  }
663
791
 
664
792
  // --- Ruby ---
665
- else if (type === "method" || type === "singleton_method") {
793
+ if (type === "method" || type === "singleton_method") {
666
794
  const nameNode = node.childForFieldName("name");
667
795
  if (nameNode) {
668
796
  let isMethod = false;
@@ -683,7 +811,8 @@ export class TreeSitterEngine {
683
811
  });
684
812
  }
685
813
  return;
686
- } else if ((type === "class" || type === "module") && ext === ".rb") {
814
+ }
815
+ if ((type === "class" || type === "module") && ext === ".rb") {
687
816
  const nameNode = node.childForFieldName("name");
688
817
  if (nameNode) {
689
818
  definitions.push({
@@ -704,7 +833,7 @@ export class TreeSitterEngine {
704
833
  }
705
834
 
706
835
  // --- PHP ---
707
- else if (type === "method_declaration") {
836
+ if (type === "method_declaration") {
708
837
  const nameNode = node.childForFieldName("name");
709
838
  if (nameNode) {
710
839
  definitions.push({
@@ -719,7 +848,7 @@ export class TreeSitterEngine {
719
848
  }
720
849
 
721
850
  // --- Bash ---
722
- else if (type === "function_definition" && (ext === ".sh" || ext === ".bash")) {
851
+ if (type === "function_definition" && (ext === ".sh" || ext === ".bash")) {
723
852
  const nameNode = node.childForFieldName("name") || node.namedChildren.find((c: any) => c.type === "word");
724
853
  if (nameNode) {
725
854
  definitions.push({
@@ -734,7 +863,12 @@ export class TreeSitterEngine {
734
863
  }
735
864
 
736
865
  // --- Imports / Exports Aliases (TS/JS) ---
737
- else if (type === "export_statement" || type === "import_statement") {
866
+ // An export with a declaration or default value (`export function f() {…}`) spans the whole
867
+ // body, where any "x as y" text is not an alias; only clause-style statements carry aliases.
868
+ const isAliasStatement =
869
+ type === "import_statement" ||
870
+ (type === "export_statement" && !node.childForFieldName("declaration") && !node.childForFieldName("value"));
871
+ if (isAliasStatement) {
738
872
  const text = node.text;
739
873
  if (text.includes(" as ")) {
740
874
  const asMatch = text.match(/\b([a-zA-Z0-9_]+)\s+as\s+([a-zA-Z0-9_]+)\b/);
@@ -776,6 +910,7 @@ export class TreeSitterEngine {
776
910
  }
777
911
  }
778
912
  collectAstReferences(root);
913
+ if (ext === ".rs") markRustTests(root, definitions);
779
914
 
780
915
  return {
781
916
  filePath,
@@ -50,7 +50,9 @@ export function loadIgnoreFile(filePath: string): Ignore | null {
50
50
  if (!fs.existsSync(filePath)) return null;
51
51
  try {
52
52
  const content = fs.readFileSync(filePath, "utf-8");
53
- const ig = typeof ignore === "function" ? ignore() : (ignore as any).default();
53
+ const ignoreFn = typeof ignore === "function" ? ignore : (ignore as { default?: () => Ignore }).default;
54
+ if (typeof ignoreFn !== "function") return null;
55
+ const ig = ignoreFn();
54
56
  return ig.add(content);
55
57
  } catch {
56
58
  return null;
@@ -69,7 +71,9 @@ export function isPathIgnored(stack: IgnoreFrame[], relPath: string, isDirectory
69
71
  if (relToFrame.startsWith("/")) relToFrame = relToFrame.slice(1);
70
72
  if (!relToFrame) continue;
71
73
 
72
- const res = (frame.ig as any).test(relToFrame);
74
+ // SAFETY: the 'ignore' library instance provides .test() returning { ignored, unignored }
75
+ // which is omitted from older @types/ignore declarations.
76
+ const res = (frame.ig as unknown as { test: (p: string) => { ignored: boolean; unignored: boolean } }).test(relToFrame);
73
77
  if (res.unignored) return false;
74
78
  if (res.ignored) return true;
75
79
  }
@@ -82,6 +86,8 @@ export interface WalkWorkspaceOptions {
82
86
  extensions?: Set<string>;
83
87
  includeGithub?: boolean;
84
88
  onFile?: (filePath: string) => boolean | void;
89
+ /** Called for each directory whose ignore files are consulted, before it is read. */
90
+ onDirectory?: (dirPath: string) => void;
85
91
  }
86
92
 
87
93
  /**
@@ -136,6 +142,7 @@ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
136
142
  }
137
143
 
138
144
  for (const dir of initialDirs) {
145
+ options.onDirectory?.(dir);
139
146
  const dirRel = path.relative(baseRoot, dir).replace(/\\/g, "/");
140
147
  const localGit = loadIgnoreFile(path.join(dir, ".gitignore"));
141
148
  if (localGit) {
@@ -150,6 +157,7 @@ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
150
157
  function scan(dir: string, gitStack: IgnoreFrame[], piStack: IgnoreFrame[]): boolean {
151
158
  if (files.length >= maxFiles) return false;
152
159
 
160
+ options.onDirectory?.(dir);
153
161
  let entries: fs.Dirent[];
154
162
  try {
155
163
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -260,3 +268,71 @@ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
260
268
  scan(rootDir, rootGitFrames, rootPiFrames);
261
269
  return files;
262
270
  }
271
+
272
+ interface WalkProbe {
273
+ path: string;
274
+ /** `.git` probes only matter for existence: git operations touch .git constantly. */
275
+ existenceOnly: boolean;
276
+ stats?: fs.Stats;
277
+ }
278
+
279
+ const WALK_RACY_WINDOW_MS = 2_000;
280
+
281
+ function takeProbe(probePath: string, existenceOnly: boolean): WalkProbe {
282
+ return { path: probePath, existenceOnly, stats: fs.statSync(probePath, { throwIfNoEntry: false }) };
283
+ }
284
+
285
+ function probeUnchanged(probe: WalkProbe): boolean {
286
+ const now = fs.statSync(probe.path, { throwIfNoEntry: false });
287
+ if (!probe.stats || !now) return !probe.stats && !now;
288
+ if (probe.existenceOnly) return true;
289
+ return probe.stats.dev === now.dev && probe.stats.ino === now.ino && probe.stats.size === now.size
290
+ && probe.stats.mtimeMs === now.mtimeMs && probe.stats.isDirectory() === now.isDirectory();
291
+ }
292
+
293
+ /**
294
+ * Reuses a workspace walk until something it depended on changes: a visited directory (entry
295
+ * add/remove/rename updates its mtime), a consulted .gitignore/.piignore, or the `.git` ancestors
296
+ * that decide the ignore root. Walks recorded within the mtime-granularity window are not reused.
297
+ */
298
+ export class WorkspaceWalkCache {
299
+ private key = "";
300
+ private files: string[] = [];
301
+ private probes: WalkProbe[] = [];
302
+ private racy = true;
303
+
304
+ walk(options: WalkWorkspaceOptions): string[] {
305
+ if (options.onFile) return walkWorkspaceFiles(options);
306
+ const key = JSON.stringify([
307
+ path.resolve(options.rootDir),
308
+ options.maxFiles ?? 500,
309
+ options.includeGithub ?? true,
310
+ options.extensions ? [...options.extensions].sort() : null,
311
+ ]);
312
+ if (key === this.key && !this.racy && this.probes.every(probeUnchanged)) return this.files.slice();
313
+
314
+ const started = Date.now();
315
+ const probes = new Map<string, WalkProbe>();
316
+ const record = (probePath: string, existenceOnly = false) => {
317
+ if (!probes.has(probePath)) probes.set(probePath, takeProbe(probePath, existenceOnly));
318
+ };
319
+ for (let dir = path.resolve(options.rootDir); ; dir = path.dirname(dir)) {
320
+ record(path.join(dir, ".git"), true);
321
+ if (probes.get(path.join(dir, ".git"))!.stats || path.dirname(dir) === dir) break;
322
+ }
323
+ const files = walkWorkspaceFiles({
324
+ ...options,
325
+ onDirectory: (dir) => {
326
+ options.onDirectory?.(dir);
327
+ record(dir);
328
+ record(path.join(dir, ".gitignore"));
329
+ record(path.join(dir, ".piignore"));
330
+ },
331
+ });
332
+ this.key = key;
333
+ this.files = files;
334
+ this.probes = [...probes.values()];
335
+ this.racy = this.probes.some((p) => !p.existenceOnly && p.stats && p.stats.mtimeMs >= started - WALK_RACY_WINDOW_MS);
336
+ return files.slice();
337
+ }
338
+ }
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { randomBytes } from "node:crypto";
4
- import { kernelDebug } from "./kernel_debug";
4
+ import { kernelDebug } from "./kernel_debug.js";
5
5
 
6
6
  function syncDirectory(directory: string): void {
7
7
  if (process.platform === "win32") return;