@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
@@ -0,0 +1,526 @@
1
+ import * as path from "node:path";
2
+ import * as fs from "node:fs";
3
+ import { TreeSitterEngine } from "./tree_sitter_engine";
4
+ import { computeHash, type CodeChunk } from "./search_chunker";
5
+ import { kernelDebug } from "../safety/kernel_debug";
6
+
7
+ export interface TreeSitterNode {
8
+ type: string;
9
+ text: string;
10
+ startPosition: { row: number; column: number };
11
+ endPosition: { row: number; column: number };
12
+ parent?: TreeSitterNode | null;
13
+ namedChildCount?: number;
14
+ namedChildren?: TreeSitterNode[];
15
+ namedChild: (index: number) => TreeSitterNode | null;
16
+ }
17
+
18
+ export interface TreeSitterTree {
19
+ rootNode: TreeSitterNode;
20
+ delete(): void;
21
+ }
22
+
23
+ export interface HtmlMetadata {
24
+ tag: string;
25
+ id?: string;
26
+ classes: string[];
27
+ role?: string;
28
+ ariaLabel?: string;
29
+ ariaLabelledBy?: string;
30
+ placeholder?: string;
31
+ name?: string;
32
+ type?: string;
33
+ for?: string;
34
+ }
35
+
36
+ export interface HtmlGroup {
37
+ file: string;
38
+ node: TreeSitterNode;
39
+ metadata: HtmlMetadata;
40
+ symbolName: string;
41
+ startLine: number;
42
+ endLine: number;
43
+ content: string;
44
+ breadcrumb: string;
45
+ details: string;
46
+ visibleText: string;
47
+ }
48
+
49
+ export interface ParsedHtml {
50
+ file: string;
51
+ lines: string[];
52
+ root: TreeSitterNode;
53
+ tree: TreeSitterTree;
54
+ bodyStartLine: number;
55
+ bodyEndLine: number;
56
+ rawRanges: Array<{ startLine: number; endLine: number; type: "style" | "script" }>;
57
+ }
58
+
59
+ export interface GroupChunkerOptions {
60
+ minimumLines: number;
61
+ maximumLines: number;
62
+ rawBoundaryMinimumLines: number;
63
+ }
64
+
65
+ export const DEFAULT_HTML_CHUNKER_OPTIONS: GroupChunkerOptions = {
66
+ minimumLines: 6,
67
+ maximumLines: 70,
68
+ rawBoundaryMinimumLines: 3,
69
+ };
70
+
71
+ const SEMANTIC_TAGS = new Set([
72
+ "header", "nav", "main", "section", "article", "aside", "footer", "form", "dialog", "template", "table", "thead", "tbody"
73
+ ]);
74
+ const SHORT_SEMANTIC_GROUPS = new Set([
75
+ "header", "nav", "footer", "form", "dialog", "template"
76
+ ]);
77
+ const INTERACTIVE_TAGS = new Set([
78
+ "button", "input", "select", "textarea", "a", "label"
79
+ ]);
80
+ const GENERIC_CLASSES = new Set([
81
+ "container", "content", "wrapper", "row", "col", "grid", "panel", "body", "header", "footer", "main", "section", "tab"
82
+ ]);
83
+ const MIN_INTERACTIVE_GROUP_LINES = 3;
84
+
85
+ function range(node: TreeSitterNode): { startLine: number; endLine: number } {
86
+ const startLine = node.startPosition.row + 1;
87
+ const endLine = node.endPosition.column === 0 ? node.endPosition.row : node.endPosition.row + 1;
88
+ return { startLine, endLine: Math.max(startLine, endLine) };
89
+ }
90
+
91
+ function text(node: TreeSitterNode | null | undefined): string {
92
+ return node?.text || "";
93
+ }
94
+
95
+ function elementChildren(node: TreeSitterNode | null | undefined): TreeSitterNode[] {
96
+ if (!node) return [];
97
+ const count = node.namedChildCount ?? 0;
98
+ const children: TreeSitterNode[] = [];
99
+ for (let i = 0; i < count; i++) {
100
+ const child = node.namedChild(i);
101
+ if (child && (child.type === "element" || child.type === "script_element" || child.type === "style_element")) {
102
+ children.push(child);
103
+ }
104
+ }
105
+ return children;
106
+ }
107
+
108
+ function attr(attribute: TreeSitterNode): [string, string] | null {
109
+ const nameNode = attribute.namedChildren?.find((child) => child.type === "attribute_name");
110
+ const valueNode = attribute.namedChildren?.find((child) => child.type === "quoted_attribute_value" || child.type === "attribute_value");
111
+ const name = text(nameNode).toLowerCase();
112
+ if (!name) return null;
113
+ const value = text(valueNode).trim().replace(/^['"]|['"]$/g, "");
114
+ return [name, value];
115
+ }
116
+
117
+ export function metadata(node: TreeSitterNode): HtmlMetadata | null {
118
+ if (node.type !== "element" && node.type !== "script_element" && node.type !== "style_element") return null;
119
+ const startTag = node.namedChildren?.find((child) => child.type === "start_tag" || child.type === "self_closing_tag");
120
+ const tag = text(startTag?.namedChildren?.find((child) => child.type === "tag_name")).toLowerCase();
121
+ if (!tag) return null;
122
+ const values = new Map<string, string>();
123
+ for (const child of startTag?.namedChildren?.filter((item) => item.type === "attribute") ?? []) {
124
+ const pair = attr(child);
125
+ if (pair) values.set(pair[0], pair[1]);
126
+ }
127
+ return {
128
+ tag,
129
+ id: values.get("id") || undefined,
130
+ classes: (values.get("class") || "").split(/\s+/).filter(Boolean),
131
+ role: values.get("role") || undefined,
132
+ ariaLabel: values.get("aria-label") || undefined,
133
+ ariaLabelledBy: values.get("aria-labelledby") || undefined,
134
+ placeholder: values.get("placeholder") || undefined,
135
+ name: values.get("name") || undefined,
136
+ type: values.get("type") || undefined,
137
+ for: values.get("for") || undefined,
138
+ };
139
+ }
140
+
141
+ export function identity(value: HtmlMetadata): string {
142
+ const classPart = value.classes.filter((name) => !GENERIC_CLASSES.has(name)).slice(0, 2).map((name) => `.${name}`).join("");
143
+ const idPart = value.id ? `#${value.id}` : "";
144
+ const rolePart = !idPart && value.role ? `[role=${value.role}]` : "";
145
+ return `${value.tag}${idPart}${classPart}${rolePart}`;
146
+ }
147
+
148
+ function isInteractive(value: HtmlMetadata): boolean {
149
+ return INTERACTIVE_TAGS.has(value.tag);
150
+ }
151
+
152
+ function sourceLines(node: TreeSitterNode): number {
153
+ const span = range(node);
154
+ return span.endLine - span.startLine + 1;
155
+ }
156
+
157
+ function hasLargeRawDescendant(node: TreeSitterNode, options: GroupChunkerOptions): boolean {
158
+ const visit = (current: TreeSitterNode): boolean => {
159
+ if ((current.type === "style_element" || current.type === "script_element") && sourceLines(current) >= options.rawBoundaryMinimumLines) return true;
160
+ return elementChildren(current).some(visit);
161
+ };
162
+ return elementChildren(node).some(visit);
163
+ }
164
+
165
+ function descendantInteractiveCount(node: TreeSitterNode): number {
166
+ let count = 0;
167
+ const visit = (current: TreeSitterNode) => {
168
+ const value = metadata(current);
169
+ if (value && isInteractive(value)) count++;
170
+ for (const child of elementChildren(current)) visit(child);
171
+ };
172
+ visit(node);
173
+ return count;
174
+ }
175
+
176
+ function hasStrongDescendantIdentity(node: TreeSitterNode): boolean {
177
+ let found = false;
178
+ const visit = (current: TreeSitterNode) => {
179
+ const value = metadata(current);
180
+ if (value && (Boolean(value.id) || Boolean(value.role) || Boolean(value.ariaLabel) || Boolean(value.ariaLabelledBy))) found = true;
181
+ for (const child of elementChildren(current)) visit(child);
182
+ };
183
+ visit(node);
184
+ return found;
185
+ }
186
+
187
+ function isGroupCandidate(node: TreeSitterNode, value: HtmlMetadata, options: GroupChunkerOptions): boolean {
188
+ if (["html", "body", "style", "script"].includes(value.tag) || isInteractive(value)) return false;
189
+ const lines = sourceLines(node);
190
+ const hasInteractiveOrIdentity = Boolean(value.id) || Boolean(value.role) || Boolean(value.ariaLabel) || Boolean(value.ariaLabelledBy) || descendantInteractiveCount(node) > 0 || hasStrongDescendantIdentity(node);
191
+ if (hasInteractiveOrIdentity && lines >= MIN_INTERACTIVE_GROUP_LINES) return true;
192
+ if (SEMANTIC_TAGS.has(value.tag)) return lines >= options.minimumLines || SHORT_SEMANTIC_GROUPS.has(value.tag);
193
+ return false;
194
+ }
195
+
196
+ export function visibleText(node: TreeSitterNode): string {
197
+ const parts: string[] = [];
198
+ const visit = (current: TreeSitterNode) => {
199
+ if (current.type === "style_element" || current.type === "script_element" || current.type === "raw_text") return;
200
+ if (current.type === "text") {
201
+ parts.push(text(current));
202
+ return;
203
+ }
204
+ const count = current.namedChildCount ?? 0;
205
+ for (let i = 0; i < count; i++) {
206
+ const child = current.namedChild(i);
207
+ if (child) visit(child);
208
+ }
209
+ };
210
+ visit(node);
211
+ return parts.join(" ").replace(/\s+/g, " ").trim().slice(0, 700);
212
+ }
213
+
214
+ function controlDetails(node: TreeSitterNode): string[] {
215
+ const details = new Set<string>();
216
+ const visit = (current: TreeSitterNode) => {
217
+ const value = metadata(current);
218
+ if (value && isInteractive(value)) {
219
+ const tokens = [
220
+ identity(value),
221
+ value.id ? `id ${value.id}` : "",
222
+ value.role ? `role ${value.role}` : "",
223
+ value.ariaLabel ? `label ${value.ariaLabel}` : "",
224
+ value.placeholder ? `placeholder ${value.placeholder}` : "",
225
+ value.type ? `type ${value.type}` : "",
226
+ value.for ? `for ${value.for}` : "",
227
+ ].filter(Boolean).join("; ");
228
+ if (tokens) details.add(tokens);
229
+ }
230
+ for (const child of elementChildren(current)) visit(child);
231
+ };
232
+ visit(node);
233
+ return [...details].sort((a, b) => a.localeCompare(b));
234
+ }
235
+
236
+ export function breadcrumb(node: TreeSitterNode, file: string): string {
237
+ const parts: string[] = [];
238
+ let current: TreeSitterNode | null | undefined = node;
239
+ while (current) {
240
+ const value = metadata(current);
241
+ if (value && !["html", "body", "style", "script"].includes(value.tag)) parts.push(identity(value));
242
+ current = current.parent;
243
+ }
244
+ const reversed: string[] = [];
245
+ for (let i = parts.length - 1; i >= 0; i--) {
246
+ reversed.push(parts[i]);
247
+ }
248
+ return `HTML: ${file}${reversed.length ? ` > ${reversed.join(" > ")}` : ""}`;
249
+ }
250
+
251
+ function groupDetails(node: TreeSitterNode, value: HtmlMetadata): string {
252
+ return [
253
+ `tag ${value.tag}`,
254
+ value.id ? `id ${value.id}` : "",
255
+ value.classes.length ? `classes ${value.classes.join(" ")}` : "",
256
+ value.role ? `role ${value.role}` : "",
257
+ value.ariaLabel ? `label ${value.ariaLabel}` : "",
258
+ value.ariaLabelledBy ? `labelledby ${value.ariaLabelledBy}` : "",
259
+ visibleText(node) ? `text ${visibleText(node)}` : "",
260
+ ...controlDetails(node),
261
+ ].filter(Boolean).join("; ");
262
+ }
263
+
264
+ function hasMultipleChildLandmarks(node: TreeSitterNode, options: GroupChunkerOptions): boolean {
265
+ const children = elementChildren(node);
266
+ let count = 0;
267
+ for (const child of children) {
268
+ const m = metadata(child);
269
+ if (!m || isInteractive(m)) continue;
270
+ const isLandmark = SEMANTIC_TAGS.has(m.tag) && (sourceLines(child) >= options.minimumLines || SHORT_SEMANTIC_GROUPS.has(m.tag));
271
+ const isInteractiveBlock = (descendantInteractiveCount(child) > 0 || hasStrongDescendantIdentity(child)) && sourceLines(child) >= MIN_INTERACTIVE_GROUP_LINES;
272
+ if (isLandmark || isInteractiveBlock) {
273
+ count++;
274
+ if (count >= 2) return true;
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+
280
+ function fallbackPartition(node: TreeSitterNode, parsed: ParsedHtml, options: GroupChunkerOptions): HtmlGroup[] {
281
+ const children = elementChildren(node).filter((c) => c.type !== "style_element" && c.type !== "script_element");
282
+ const val = metadata(node) || { tag: node.type || "element", classes: [] };
283
+ const trail = breadcrumb(node, parsed.file);
284
+
285
+ if (children.length === 0) {
286
+ const { startLine, endLine } = range(node);
287
+ const groups: HtmlGroup[] = [];
288
+ const step = options.maximumLines;
289
+ for (let s = startLine; s <= endLine; s += step) {
290
+ const e = Math.min(endLine, s + step - 1);
291
+ const content = parsed.lines.slice(s - 1, e).join("\n");
292
+ const partIdentity = `${identity(val)}:lines-${s}-${e}`;
293
+ groups.push({
294
+ file: parsed.file,
295
+ node,
296
+ metadata: val,
297
+ symbolName: partIdentity,
298
+ startLine: s,
299
+ endLine: e,
300
+ content,
301
+ breadcrumb: trail,
302
+ details: `tag ${val.tag}; part lines ${s}-${e}; ${visibleText(node).slice(0, 200)}`,
303
+ visibleText: visibleText(node).slice(0, 300),
304
+ });
305
+ }
306
+ return groups;
307
+ }
308
+
309
+ const groups: HtmlGroup[] = [];
310
+ let currentStart = -1;
311
+ let currentEnd = -1;
312
+ let currentKids: TreeSitterNode[] = [];
313
+
314
+ const flush = () => {
315
+ if (currentStart === -1 || currentEnd === -1) return;
316
+ const content = parsed.lines.slice(currentStart - 1, currentEnd).join("\n");
317
+ const partName = `${identity(val)}:part-${currentStart}-${currentEnd}`;
318
+ const kidText = currentKids.map((k) => visibleText(k)).filter(Boolean).join(" ").slice(0, 300);
319
+ groups.push({
320
+ file: parsed.file,
321
+ node,
322
+ metadata: val,
323
+ symbolName: partName,
324
+ startLine: currentStart,
325
+ endLine: currentEnd,
326
+ content,
327
+ breadcrumb: trail,
328
+ details: `tag ${val.tag}; part lines ${currentStart}-${currentEnd}; ${kidText}`,
329
+ visibleText: kidText,
330
+ });
331
+ currentStart = -1;
332
+ currentEnd = -1;
333
+ currentKids = [];
334
+ };
335
+
336
+ for (const child of children) {
337
+ const cSpan = range(child);
338
+ const cLines = cSpan.endLine - cSpan.startLine + 1;
339
+ if (cLines > options.maximumLines) {
340
+ flush();
341
+ groups.push(...fallbackPartition(child, parsed, options));
342
+ continue;
343
+ }
344
+
345
+ if (currentStart === -1) {
346
+ currentStart = cSpan.startLine;
347
+ currentEnd = cSpan.endLine;
348
+ currentKids.push(child);
349
+ } else {
350
+ const candidateEnd = Math.max(currentEnd, cSpan.endLine);
351
+ if (candidateEnd - currentStart + 1 > options.maximumLines) {
352
+ flush();
353
+ currentStart = cSpan.startLine;
354
+ currentEnd = cSpan.endLine;
355
+ currentKids.push(child);
356
+ } else {
357
+ currentEnd = candidateEnd;
358
+ currentKids.push(child);
359
+ }
360
+ }
361
+ }
362
+ flush();
363
+ return groups;
364
+ }
365
+
366
+ export function selectGroups(node: TreeSitterNode, parsed: ParsedHtml, options: GroupChunkerOptions = DEFAULT_HTML_CHUNKER_OPTIONS): HtmlGroup[] {
367
+ const value = metadata(node);
368
+ if (!value || !isGroupCandidate(node, value, options)) {
369
+ return elementChildren(node).flatMap((child) => selectGroups(child, parsed, options));
370
+ }
371
+
372
+ const isContainer = ["div", "main", "article"].includes(value.tag);
373
+ const shouldSplitGenericWrapper = isContainer && hasMultipleChildLandmarks(node, options);
374
+
375
+ if (!shouldSplitGenericWrapper && sourceLines(node) <= options.maximumLines && !hasLargeRawDescendant(node, options)) {
376
+ const { startLine, endLine } = range(node);
377
+ return [{
378
+ file: parsed.file,
379
+ node,
380
+ metadata: value,
381
+ symbolName: identity(value),
382
+ startLine,
383
+ endLine,
384
+ content: parsed.lines.slice(startLine - 1, endLine).join("\n"),
385
+ breadcrumb: breadcrumb(node, parsed.file),
386
+ details: groupDetails(node, value),
387
+ visibleText: visibleText(node),
388
+ }];
389
+ }
390
+ // Parent suppression: a large or raw-boundary parent is metadata only. Its
391
+ // eligible children inherit that context through their breadcrumbs.
392
+ const childGroups = elementChildren(node).flatMap((child) => selectGroups(child, parsed, options));
393
+ if (childGroups.length > 0) {
394
+ return childGroups;
395
+ }
396
+
397
+ // Fallback for oversized nodes with no eligible children:
398
+ // Do not drop the subtree! Partition its children or lines into <= maximumLines chunks.
399
+ if (sourceLines(node) > options.maximumLines) {
400
+ return fallbackPartition(node, parsed, options);
401
+ }
402
+
403
+ return [];
404
+ }
405
+
406
+ export function rawRegions(root: TreeSitterNode): Array<{ startLine: number; endLine: number; type: "style" | "script" }> {
407
+ const regions: Array<{ startLine: number; endLine: number; type: "style" | "script" }> = [];
408
+ const visit = (node: TreeSitterNode) => {
409
+ if (node.type === "style_element" || node.type === "script_element") {
410
+ regions.push({ ...range(node), type: node.type === "style_element" ? "style" : "script" });
411
+ }
412
+ for (const child of elementChildren(node)) visit(child);
413
+ };
414
+ visit(root);
415
+ return regions;
416
+ }
417
+
418
+ /**
419
+ * Chunk a single HTML file into logical, syntax-bounded DOM chunks.
420
+ */
421
+ export function chunkHtmlFile(
422
+ rootDir: string,
423
+ filePath: string,
424
+ content?: string,
425
+ options: GroupChunkerOptions = DEFAULT_HTML_CHUNKER_OPTIONS,
426
+ ): CodeChunk[] {
427
+ const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath);
428
+ const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/");
429
+
430
+ let fileContent = content;
431
+ if (fileContent === undefined) {
432
+ try {
433
+ fileContent = fs.readFileSync(absPath, "utf8");
434
+ } catch {
435
+ return [];
436
+ }
437
+ }
438
+
439
+ const lines = fileContent.split(/\r?\n/);
440
+ if (lines.length === 0) return [];
441
+
442
+ const ext = path.extname(absPath).toLowerCase();
443
+ const parser = TreeSitterEngine.getInstance().getParser(ext);
444
+
445
+ if (!parser) {
446
+ const hash = computeHash(fileContent);
447
+ return [{
448
+ id: `${relPath}:1-${lines.length}`,
449
+ filePath: relPath,
450
+ absolutePath: absPath,
451
+ startLine: 1,
452
+ endLine: lines.length,
453
+ symbolName: path.basename(relPath),
454
+ kind: "file",
455
+ signature: `HTML file: ${path.basename(relPath)}`,
456
+ breadcrumb: `HTML: ${relPath}`,
457
+ content: fileContent,
458
+ textForEmbedding: `HTML: ${relPath}\n${fileContent.slice(0, 1500)}`,
459
+ hash,
460
+ }];
461
+ }
462
+
463
+ let tree: TreeSitterTree | null = null;
464
+ try {
465
+ tree = parser.parse(fileContent);
466
+ if (!tree?.rootNode) return [];
467
+
468
+ let bodyNode: TreeSitterNode | null = null;
469
+ const findBody = (node: TreeSitterNode) => {
470
+ const val = metadata(node);
471
+ if (val?.tag === "body") bodyNode = node;
472
+ for (const child of elementChildren(node)) findBody(child);
473
+ };
474
+ findBody(tree.rootNode);
475
+ const bodyRange = bodyNode ? range(bodyNode) : { startLine: 1, endLine: lines.length };
476
+
477
+ const parsed: ParsedHtml = {
478
+ file: relPath,
479
+ lines,
480
+ root: tree.rootNode,
481
+ tree,
482
+ bodyStartLine: bodyRange.startLine,
483
+ bodyEndLine: bodyRange.endLine,
484
+ rawRanges: rawRegions(tree.rootNode),
485
+ };
486
+
487
+ const groups = selectGroups(tree.rootNode, parsed, options);
488
+ if (groups.length === 0) {
489
+ const hash = computeHash(fileContent);
490
+ return [{
491
+ id: `${relPath}:1-${lines.length}`,
492
+ filePath: relPath,
493
+ absolutePath: absPath,
494
+ startLine: 1,
495
+ endLine: lines.length,
496
+ symbolName: path.basename(relPath),
497
+ kind: "file",
498
+ signature: `HTML file: ${path.basename(relPath)}`,
499
+ breadcrumb: `HTML: ${relPath}`,
500
+ content: fileContent,
501
+ textForEmbedding: `HTML: ${relPath}\n${fileContent.slice(0, 1500)}`,
502
+ hash,
503
+ }];
504
+ }
505
+
506
+ return groups.map((g) => ({
507
+ id: `${relPath}:${g.startLine}-${g.endLine}#${g.symbolName}`,
508
+ filePath: relPath,
509
+ absolutePath: absPath,
510
+ startLine: g.startLine,
511
+ endLine: g.endLine,
512
+ symbolName: g.symbolName,
513
+ kind: "html",
514
+ signature: g.details,
515
+ breadcrumb: g.breadcrumb,
516
+ content: g.content,
517
+ textForEmbedding: `${g.breadcrumb}\n${g.details}\n${g.content.slice(0, 1500)}`,
518
+ hash: computeHash(g.content),
519
+ }));
520
+ } catch (e) {
521
+ kernelDebug(`Error chunking HTML file ${relPath}: ${e}`);
522
+ return [];
523
+ } finally {
524
+ tree?.delete();
525
+ }
526
+ }
@@ -44,7 +44,8 @@ export function tokenizeCode(text: string): string[] {
44
44
  }
45
45
 
46
46
  const COMMON_QUERY_STOPWORDS = new Set([
47
- "a", "an", "the", "and", "or", "in", "on", "at", "to", "for", "with", "by", "of", "is", "as", "it", "from", "be"
47
+ "a", "an", "the", "and", "or", "in", "on", "at", "to", "for", "with", "by", "of", "is", "as", "it", "from", "be",
48
+ "are", "was", "were", "which", "whose", "whether", "shown", "showing", "over"
48
49
  ]);
49
50
 
50
51
  /**
@@ -67,17 +68,23 @@ export class BM25Engine {
67
68
  private termDocFreqs: Map<string, number> = new Map();
68
69
  // term -> Set of chunkIds (Inverted index for O(Σ matches) query scanning)
69
70
  private postings: Map<string, Set<string>> = new Map();
71
+ // filePath -> chunkIds, so removeFile touches only that file's chunks
72
+ private docIdsByFile: Map<string, Set<string>> = new Map();
70
73
 
71
74
  private totalDocs = 0;
72
75
  private avgDocLength = 0;
76
+ // Running sum of docLengths, so recalculateStats is O(1)
77
+ private totalLength = 0;
73
78
 
74
79
  public clear(): void {
75
80
  this.docTermFreqs.clear();
76
81
  this.docLengths.clear();
77
82
  this.termDocFreqs.clear();
78
83
  this.postings.clear();
84
+ this.docIdsByFile.clear();
79
85
  this.totalDocs = 0;
80
86
  this.avgDocLength = 0;
87
+ this.totalLength = 0;
81
88
  }
82
89
 
83
90
  /**
@@ -101,7 +108,14 @@ export class BM25Engine {
101
108
  }
102
109
 
103
110
  this.docTermFreqs.set(chunk.id, tfMap);
111
+ this.totalLength += tokens.length - (this.docLengths.get(chunk.id) ?? 0);
104
112
  this.docLengths.set(chunk.id, tokens.length);
113
+ let fileIds = this.docIdsByFile.get(chunk.filePath);
114
+ if (!fileIds) {
115
+ fileIds = new Set();
116
+ this.docIdsByFile.set(chunk.filePath, fileIds);
117
+ }
118
+ fileIds.add(chunk.id);
105
119
 
106
120
  for (const term of tfMap.keys()) {
107
121
  this.termDocFreqs.set(term, (this.termDocFreqs.get(term) || 0) + 1);
@@ -120,42 +134,37 @@ export class BM25Engine {
120
134
  * Remove all chunks associated with a specific relative file path.
121
135
  */
122
136
  public removeFile(filePath: string): void {
123
- const prefix = `${filePath}:`;
124
- for (const chunkId of Array.from(this.docTermFreqs.keys())) {
125
- if (chunkId.startsWith(prefix)) {
126
- const tfMap = this.docTermFreqs.get(chunkId);
127
- if (tfMap) {
128
- for (const term of tfMap.keys()) {
129
- const count = (this.termDocFreqs.get(term) || 1) - 1;
130
- if (count <= 0) {
131
- this.termDocFreqs.delete(term);
132
- } else {
133
- this.termDocFreqs.set(term, count);
134
- }
135
- const chunkSet = this.postings.get(term);
136
- if (chunkSet) {
137
- chunkSet.delete(chunkId);
138
- if (chunkSet.size === 0) {
139
- this.postings.delete(term);
140
- }
137
+ for (const chunkId of this.docIdsByFile.get(filePath) ?? []) {
138
+ const tfMap = this.docTermFreqs.get(chunkId);
139
+ if (tfMap) {
140
+ for (const term of tfMap.keys()) {
141
+ const count = (this.termDocFreqs.get(term) || 1) - 1;
142
+ if (count <= 0) {
143
+ this.termDocFreqs.delete(term);
144
+ } else {
145
+ this.termDocFreqs.set(term, count);
146
+ }
147
+ const chunkSet = this.postings.get(term);
148
+ if (chunkSet) {
149
+ chunkSet.delete(chunkId);
150
+ if (chunkSet.size === 0) {
151
+ this.postings.delete(term);
141
152
  }
142
153
  }
143
154
  }
144
- this.docTermFreqs.delete(chunkId);
145
- this.docLengths.delete(chunkId);
146
- this.totalDocs--;
147
155
  }
156
+ this.docTermFreqs.delete(chunkId);
157
+ this.totalLength -= this.docLengths.get(chunkId) ?? 0;
158
+ this.docLengths.delete(chunkId);
159
+ this.totalDocs--;
148
160
  }
161
+ this.docIdsByFile.delete(filePath);
149
162
  this.recalculateStats();
150
163
  }
151
164
 
152
165
  public recalculateStats(): void {
153
- let totalLength = 0;
154
- for (const len of this.docLengths.values()) {
155
- totalLength += len;
156
- }
157
166
  this.totalDocs = this.docLengths.size;
158
- this.avgDocLength = this.totalDocs > 0 ? totalLength / this.totalDocs : 0;
167
+ this.avgDocLength = this.totalDocs > 0 ? this.totalLength / this.totalDocs : 0;
159
168
  }
160
169
 
161
170
  /**
@@ -204,7 +213,9 @@ export class BM25Engine {
204
213
  .map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches }))
205
214
  .sort((a, b) => {
206
215
  if (b.score !== a.score) return b.score - a.score;
207
- return a.chunkId < b.chunkId ? -1 : a.chunkId > b.chunkId ? 1 : 0;
216
+ if (a.chunkId < b.chunkId) return -1;
217
+ if (a.chunkId > b.chunkId) return 1;
218
+ return 0;
208
219
  })
209
220
  .slice(0, limit);
210
221
  }