@floydous/pi-agent-kernel 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT_KERNEL_SYS_PROMPT.md +10 -0
- package/CHANGELOG.md +44 -10
- package/README.md +61 -78
- package/config.toml +8 -2
- package/package.json +3 -1
- package/src/config/kernel_config.ts +24 -6
- package/src/editing/auto_heal.ts +232 -0
- package/src/editing/patch.ts +214 -17
- package/src/editing/post_edit_verification.ts +3 -2
- package/src/editing/smart_anchor.ts +420 -0
- package/src/index.ts +212 -152
- package/src/retrieval/repomap.ts +2 -1
- package/src/retrieval/search_bm25.ts +14 -1
- package/src/retrieval/search_chunker.ts +69 -3
- package/src/retrieval/search_config.ts +5 -6
- package/src/retrieval/search_index.ts +208 -82
- package/src/retrieval/symbol_reader.ts +34 -4
- package/src/safety/epistemic_guard.ts +304 -38
- package/src/safety/output_clamper.ts +28 -4
- package/src/tools/ast_search_tool.ts +19 -8
- package/src/tools/code_search_tool.ts +43 -29
- package/src/tools/edit_tool.ts +510 -197
- package/src/tools/read_tool.ts +265 -28
- package/src/ui/footer.ts +45 -19
- package/src/dedup/content_store.ts +0 -365
- package/src/dedup/recall_tool.ts +0 -155
|
@@ -260,7 +260,7 @@ function mergeEvidence(
|
|
|
260
260
|
provenance: EvidenceProvenance,
|
|
261
261
|
query?: string,
|
|
262
262
|
): InspectionEvidence {
|
|
263
|
-
if (previous.fingerprint !== fingerprint
|
|
263
|
+
if (previous.fingerprint !== fingerprint) {
|
|
264
264
|
return {
|
|
265
265
|
kind,
|
|
266
266
|
fingerprint,
|
|
@@ -269,14 +269,210 @@ function mergeEvidence(
|
|
|
269
269
|
...(query === undefined ? {} : { query }),
|
|
270
270
|
};
|
|
271
271
|
}
|
|
272
|
+
// Once marked read, retain read kind unless reset
|
|
273
|
+
const mergedKind = previous.kind === "read" || kind === "read" ? "read" : "search";
|
|
272
274
|
return {
|
|
273
275
|
...previous,
|
|
276
|
+
kind: mergedKind,
|
|
274
277
|
coverage: mergeCoverage(previous.coverage, coverage),
|
|
275
278
|
provenance,
|
|
276
279
|
...(query === undefined ? {} : { query }),
|
|
277
280
|
};
|
|
278
281
|
}
|
|
279
282
|
|
|
283
|
+
/** Convert a collection of line numbers into sorted, merged 1-based line ranges. */
|
|
284
|
+
export function linesToRanges(lines: Iterable<number>): EvidenceRange[] {
|
|
285
|
+
const sorted = Array.from(lines)
|
|
286
|
+
.filter((n) => Number.isFinite(n) && n >= 1)
|
|
287
|
+
.map((n) => Math.floor(n))
|
|
288
|
+
.sort((a, b) => a - b);
|
|
289
|
+
if (sorted.length === 0) return [];
|
|
290
|
+
|
|
291
|
+
const ranges: EvidenceRange[] = [];
|
|
292
|
+
let start = sorted[0];
|
|
293
|
+
let prev = sorted[0];
|
|
294
|
+
|
|
295
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
296
|
+
const curr = sorted[i];
|
|
297
|
+
if (curr === prev) continue;
|
|
298
|
+
if (curr === prev + 1) {
|
|
299
|
+
prev = curr;
|
|
300
|
+
} else {
|
|
301
|
+
ranges.push({ startLine: start, endLine: prev });
|
|
302
|
+
start = curr;
|
|
303
|
+
prev = curr;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
ranges.push({ startLine: start, endLine: prev });
|
|
307
|
+
return ranges;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Parse stdout from grep / ripgrep, capturing file paths and line numbers. */
|
|
311
|
+
export function parseGrepOutput(
|
|
312
|
+
outputText: string,
|
|
313
|
+
candidateFiles: string[],
|
|
314
|
+
cwd = process.cwd(),
|
|
315
|
+
): Map<string, number[]> {
|
|
316
|
+
const fileLinesMap = new Map<string, Set<number>>();
|
|
317
|
+
if (!outputText || typeof outputText !== "string") return new Map();
|
|
318
|
+
|
|
319
|
+
const normalizedCandidates = new Map<string, string>();
|
|
320
|
+
for (const cand of candidateFiles) {
|
|
321
|
+
const abs = path.isAbsolute(cand) ? path.normalize(cand) : path.resolve(cwd, cand);
|
|
322
|
+
normalizedCandidates.set(cand, abs);
|
|
323
|
+
normalizedCandidates.set(abs, abs);
|
|
324
|
+
const rel = path.relative(cwd, abs).replace(/\\/g, "/");
|
|
325
|
+
normalizedCandidates.set(rel, abs);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const lines = outputText.split(/\r?\n/);
|
|
329
|
+
for (const line of lines) {
|
|
330
|
+
const trimmed = line.trim();
|
|
331
|
+
if (!trimmed) continue;
|
|
332
|
+
|
|
333
|
+
// 1. Single file: "123:code" or "123-context"
|
|
334
|
+
const singleMatch = line.match(/^(\d+)[:-]/);
|
|
335
|
+
if (singleMatch && candidateFiles.length === 1) {
|
|
336
|
+
const lineNum = parseInt(singleMatch[1], 10);
|
|
337
|
+
const targetPath = normalizedCandidates.get(candidateFiles[0]) || path.resolve(cwd, candidateFiles[0]);
|
|
338
|
+
if (!fileLinesMap.has(targetPath)) fileLinesMap.set(targetPath, new Set());
|
|
339
|
+
fileLinesMap.get(targetPath)!.add(lineNum);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// 2. Multi-file: "path/to/file.ts:123:code" or "path/to/file.ts-123-context"
|
|
344
|
+
const multiMatch = line.match(/^([^:\-\n\r]+(?:\.[a-zA-Z0-9]+)?)(?::(\d+):|-(\d+)-)/);
|
|
345
|
+
if (multiMatch) {
|
|
346
|
+
const rawPath = multiMatch[1].trim();
|
|
347
|
+
const lineNum = parseInt(multiMatch[2] || multiMatch[3], 10);
|
|
348
|
+
let absPath =
|
|
349
|
+
normalizedCandidates.get(rawPath) ||
|
|
350
|
+
normalizedCandidates.get(path.resolve(cwd, rawPath)) ||
|
|
351
|
+
(fs.existsSync(path.resolve(cwd, rawPath)) ? path.resolve(cwd, rawPath) : null);
|
|
352
|
+
|
|
353
|
+
if (!absPath) {
|
|
354
|
+
for (const cand of candidateFiles) {
|
|
355
|
+
const candNorm = (path.isAbsolute(cand) ? cand : path.resolve(cwd, cand)).replace(/\\/g, "/");
|
|
356
|
+
if (candNorm.endsWith("/" + rawPath) || candNorm.endsWith(rawPath)) {
|
|
357
|
+
absPath = candNorm;
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (absPath && Number.isFinite(lineNum) && lineNum >= 1) {
|
|
364
|
+
if (!fileLinesMap.has(absPath)) fileLinesMap.set(absPath, new Set());
|
|
365
|
+
fileLinesMap.get(absPath)!.add(lineNum);
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// 3. Polyglot compiler error / test runner stack traces
|
|
371
|
+
// - Rust: " --> src/upstream.rs:736:9"
|
|
372
|
+
// - Python: " File \"src/app.py\", line 45, in test"
|
|
373
|
+
// - Vitest / Jest: " ❯ src/checks.ts:288:61" or " at Object.<anonymous> (file.ts:12:3)"
|
|
374
|
+
// - Go / GCC: "main.go:12:3: error"
|
|
375
|
+
// - C# / MSBuild: "file.cs(12,3): error"
|
|
376
|
+
const traceMatch =
|
|
377
|
+
line.match(/(?:-->|\s+at|\s+❯|File\s+["']?)\s*([^\s"(),]+\.[a-zA-Z0-9]+)(?:["']?)(?:[:(]|\s*,?\s*line\s+)(\d+)/i) ||
|
|
378
|
+
line.match(/(?:^|[\s(])([^\s()]+\.[a-zA-Z0-9]+)[:(](\d+)(?:[:,\s)]|$)/);
|
|
379
|
+
|
|
380
|
+
if (traceMatch) {
|
|
381
|
+
const rawPath = traceMatch[1].trim();
|
|
382
|
+
const lineNum = parseInt(traceMatch[2], 10);
|
|
383
|
+
let absPath =
|
|
384
|
+
normalizedCandidates.get(rawPath) ||
|
|
385
|
+
normalizedCandidates.get(path.resolve(cwd, rawPath)) ||
|
|
386
|
+
(fs.existsSync(path.resolve(cwd, rawPath)) && fs.statSync(path.resolve(cwd, rawPath)).isFile()
|
|
387
|
+
? path.resolve(cwd, rawPath)
|
|
388
|
+
: null);
|
|
389
|
+
|
|
390
|
+
if (!absPath) {
|
|
391
|
+
for (const cand of candidateFiles) {
|
|
392
|
+
const candNorm = (path.isAbsolute(cand) ? cand : path.resolve(cwd, cand)).replace(/\\/g, "/");
|
|
393
|
+
if (candNorm.endsWith("/" + rawPath) || candNorm.endsWith(rawPath)) {
|
|
394
|
+
absPath = candNorm;
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (absPath && Number.isFinite(lineNum) && lineNum >= 1) {
|
|
401
|
+
if (!fileLinesMap.has(absPath)) fileLinesMap.set(absPath, new Set());
|
|
402
|
+
// Ingest compiler error line locus and surrounding window [L-2, L+2]
|
|
403
|
+
for (let i = Math.max(1, lineNum - 2); i <= lineNum + 2; i++) {
|
|
404
|
+
fileLinesMap.get(absPath)!.add(i);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const result = new Map<string, number[]>();
|
|
411
|
+
for (const [file, set] of fileLinesMap.entries()) {
|
|
412
|
+
result.set(file, Array.from(set).sort((a, b) => a - b));
|
|
413
|
+
}
|
|
414
|
+
return result;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Parse shell paging / slicing commands (head, tail, sed). */
|
|
418
|
+
export function parsePagingAndDiffOutput(
|
|
419
|
+
command: string,
|
|
420
|
+
outputText: string,
|
|
421
|
+
candidateFiles: string[],
|
|
422
|
+
cwd = process.cwd(),
|
|
423
|
+
): Map<string, number[]> {
|
|
424
|
+
const result = new Map<string, number[]>();
|
|
425
|
+
if (candidateFiles.length === 0) return result;
|
|
426
|
+
|
|
427
|
+
const targetPath = path.isAbsolute(candidateFiles[0])
|
|
428
|
+
? path.normalize(candidateFiles[0])
|
|
429
|
+
: path.resolve(cwd, candidateFiles[0]);
|
|
430
|
+
|
|
431
|
+
let totalLines = 0;
|
|
432
|
+
if (fs.existsSync(targetPath)) {
|
|
433
|
+
try {
|
|
434
|
+
totalLines = fs.readFileSync(targetPath, "utf8").split(/\r?\n/).length;
|
|
435
|
+
} catch {
|
|
436
|
+
totalLines = 0;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// 1. head -n <N>
|
|
441
|
+
const headMatch = command.match(/\bhead\b.*?-n\s*(\d+)/i);
|
|
442
|
+
if (headMatch) {
|
|
443
|
+
const count = Math.min(parseInt(headMatch[1], 10), totalLines || 1000);
|
|
444
|
+
const lines: number[] = [];
|
|
445
|
+
for (let i = 1; i <= count; i++) lines.push(i);
|
|
446
|
+
result.set(targetPath, lines);
|
|
447
|
+
return result;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// 2. tail -n <N>
|
|
451
|
+
const tailMatch = command.match(/\btail\b.*?-n\s*(\d+)/i);
|
|
452
|
+
if (tailMatch) {
|
|
453
|
+
const count = parseInt(tailMatch[1], 10);
|
|
454
|
+
const start = Math.max(1, (totalLines || count) - count + 1);
|
|
455
|
+
const end = totalLines || count;
|
|
456
|
+
const lines: number[] = [];
|
|
457
|
+
for (let i = start; i <= end; i++) lines.push(i);
|
|
458
|
+
result.set(targetPath, lines);
|
|
459
|
+
return result;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// 3. sed -n '<start>,<end>p'
|
|
463
|
+
const sedMatch = command.match(/\bsed\b.*?-n\s*['"]?(\d+),(\d+)p['"]?/i);
|
|
464
|
+
if (sedMatch) {
|
|
465
|
+
const start = parseInt(sedMatch[1], 10);
|
|
466
|
+
const end = parseInt(sedMatch[2], 10);
|
|
467
|
+
const lines: number[] = [];
|
|
468
|
+
for (let i = start; i <= end; i++) lines.push(i);
|
|
469
|
+
result.set(targetPath, lines);
|
|
470
|
+
return result;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
return result;
|
|
474
|
+
}
|
|
475
|
+
|
|
280
476
|
function coversRanges(
|
|
281
477
|
coverage: EvidenceCoverage,
|
|
282
478
|
targetRanges: EvidenceRange[],
|
|
@@ -542,41 +738,62 @@ export class EpistemicGuard {
|
|
|
542
738
|
outputComplete: boolean,
|
|
543
739
|
outputText = "",
|
|
544
740
|
): void {
|
|
545
|
-
const
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
741
|
+
const isGrepOrRg =
|
|
742
|
+
/^\s*(?:grep|rg)(?:\.exe)?(?:\s|$)/i.test(command) ||
|
|
743
|
+
/\b(grep|rg)\b/i.test(command);
|
|
744
|
+
const isPaging = /\b(head|tail|sed)\b/i.test(command);
|
|
745
|
+
const isCat = /\bcat\b/i.test(command);
|
|
746
|
+
|
|
747
|
+
if (isCat) {
|
|
748
|
+
for (const filePath of files) {
|
|
749
|
+
try {
|
|
750
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
751
|
+
const observedContent = fs.readFileSync(filePath, "utf8");
|
|
752
|
+
if (
|
|
753
|
+
(outputComplete && files.length === 1 && outputText === observedContent) ||
|
|
754
|
+
outputText.trim() === observedContent.trim() ||
|
|
755
|
+
outputText.includes(observedContent.trim())
|
|
756
|
+
) {
|
|
757
|
+
this.recordFileRead(filePath, sessionId, cwd, observedContent, {
|
|
758
|
+
coverage: { complete: true, ranges: [] },
|
|
759
|
+
provenance: "bash",
|
|
760
|
+
query: command,
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
} catch (error) {
|
|
765
|
+
kernelDebug(error);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
let parsed: Map<string, number[]>;
|
|
771
|
+
if (isPaging) {
|
|
772
|
+
parsed = parsePagingAndDiffOutput(command, outputText, files, cwd);
|
|
773
|
+
} else {
|
|
774
|
+
parsed = parseGrepOutput(outputText, files, cwd);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
for (const [filePath, lineNumbers] of parsed.entries()) {
|
|
778
|
+
const ranges = linesToRanges(lineNumbers);
|
|
779
|
+
if (ranges.length > 0) {
|
|
780
|
+
this.recordFileRead(filePath, sessionId, cwd, undefined, {
|
|
781
|
+
coverage: { complete: false, ranges },
|
|
782
|
+
provenance: "bash",
|
|
783
|
+
query: command,
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
549
788
|
for (const filePath of files) {
|
|
550
|
-
|
|
789
|
+
const evidence = this.getSessionEvidence(sessionId).get(this.normalize(filePath, cwd));
|
|
790
|
+
if (!evidence) {
|
|
551
791
|
this.recordFileSearched(filePath, sessionId, cwd, {
|
|
552
792
|
coverage: { complete: false, ranges: [] },
|
|
553
793
|
provenance: "bash",
|
|
554
794
|
query: command,
|
|
555
795
|
});
|
|
556
|
-
continue;
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
let observedContent: string | undefined;
|
|
560
|
-
if (isPlainCat && files.length === 1) {
|
|
561
|
-
try {
|
|
562
|
-
observedContent = fs.readFileSync(filePath, "utf8");
|
|
563
|
-
} catch {
|
|
564
|
-
observedContent = undefined;
|
|
565
|
-
}
|
|
566
796
|
}
|
|
567
|
-
this.recordFileRead(filePath, sessionId, cwd, observedContent, {
|
|
568
|
-
coverage: {
|
|
569
|
-
complete:
|
|
570
|
-
outputComplete &&
|
|
571
|
-
isPlainCat &&
|
|
572
|
-
files.length === 1 &&
|
|
573
|
-
observedContent !== undefined &&
|
|
574
|
-
outputText === observedContent,
|
|
575
|
-
ranges: [],
|
|
576
|
-
},
|
|
577
|
-
provenance: "bash",
|
|
578
|
-
query: command,
|
|
579
|
-
});
|
|
580
797
|
}
|
|
581
798
|
}
|
|
582
799
|
|
|
@@ -602,6 +819,18 @@ export class EpistemicGuard {
|
|
|
602
819
|
outputText,
|
|
603
820
|
);
|
|
604
821
|
}
|
|
822
|
+
// Also scan outputText for polyglot compiler/test traces across the workspace
|
|
823
|
+
const traces = parseGrepOutput(outputText, files, cwd);
|
|
824
|
+
for (const [filePath, lineNumbers] of traces.entries()) {
|
|
825
|
+
const ranges = linesToRanges(lineNumbers);
|
|
826
|
+
if (ranges.length > 0) {
|
|
827
|
+
this.recordFileRead(filePath, sessionId, cwd, undefined, {
|
|
828
|
+
coverage: { complete: false, ranges },
|
|
829
|
+
provenance: "bash",
|
|
830
|
+
query: command,
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
}
|
|
605
834
|
return files;
|
|
606
835
|
}
|
|
607
836
|
|
|
@@ -618,7 +847,8 @@ export class EpistemicGuard {
|
|
|
618
847
|
cwd?: string,
|
|
619
848
|
enforceInspection = true,
|
|
620
849
|
targetRanges: EvidenceRange[] = [],
|
|
621
|
-
|
|
850
|
+
searchBlocks: string[] = [],
|
|
851
|
+
): { allowed: boolean; reason?: string; tier?: 1 | 2 } {
|
|
622
852
|
if (!filePath) {
|
|
623
853
|
return {
|
|
624
854
|
allowed: false,
|
|
@@ -664,29 +894,65 @@ export class EpistemicGuard {
|
|
|
664
894
|
const normalized = this.normalize(resolvedPath, workspace);
|
|
665
895
|
const evidence = this.getSessionEvidence(sessionId).get(normalized);
|
|
666
896
|
const relPath = (path.relative(workspace, resolvedPath) || filePath).replace(/\\/g, "/");
|
|
667
|
-
|
|
897
|
+
|
|
898
|
+
// 1. Session inspection check
|
|
899
|
+
if (!evidence) {
|
|
668
900
|
return {
|
|
669
901
|
allowed: false,
|
|
670
|
-
reason: `[BLOCKED:
|
|
902
|
+
reason: `[BLOCKED: Uninspected File] The agent has never inspected '${relPath}' in this session -> read({ path: "${relPath}" })`,
|
|
671
903
|
};
|
|
672
904
|
}
|
|
673
905
|
|
|
674
|
-
|
|
906
|
+
// 2. Stale file drift check
|
|
907
|
+
const currentFingerprint = this.fingerprint(resolvedPath, workspace);
|
|
908
|
+
if (!currentFingerprint || currentFingerprint !== evidence.fingerprint) {
|
|
675
909
|
return {
|
|
676
910
|
allowed: false,
|
|
677
|
-
reason: `[BLOCKED:
|
|
911
|
+
reason: `[BLOCKED: Stale File Drift] File '${relPath}' changed on disk since last observed -> read({ path: "${relPath}" })`,
|
|
678
912
|
};
|
|
679
913
|
}
|
|
680
914
|
|
|
681
|
-
|
|
682
|
-
if (
|
|
915
|
+
// 3. Write operations require prior read or complete coverage
|
|
916
|
+
if (operation === "write") {
|
|
917
|
+
if (evidence.kind !== "read" && !evidence.coverage.complete) {
|
|
918
|
+
return {
|
|
919
|
+
allowed: false,
|
|
920
|
+
reason: `[BLOCKED: Read before write -> read({ path: "${relPath}" })]`,
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
return { allowed: true };
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// 4. Edit operations: Dual-Tier Authorization
|
|
927
|
+
// Tier 1: Strict range coverage
|
|
928
|
+
if (evidence.kind === "read" && coversRanges(evidence.coverage, targetRanges)) {
|
|
929
|
+
return { allowed: true, tier: 1 };
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// Tier 2: Substantive unique block authorization
|
|
933
|
+
// If range math has gaps (e.g. grep context, compiler traces, symbol extraction boundaries),
|
|
934
|
+
// authorize if every search block is substantive (>=2 lines and >=35 chars, or >=50 chars).
|
|
935
|
+
if (searchBlocks && searchBlocks.length > 0) {
|
|
936
|
+
const allSubstantive = searchBlocks.every((sb) => {
|
|
937
|
+
const lineCount = sb.replace(/\r\n/g, "\n").split("\n").length;
|
|
938
|
+
const charCount = sb.length;
|
|
939
|
+
return (lineCount >= 2 && charCount >= 35) || charCount >= 50;
|
|
940
|
+
});
|
|
941
|
+
|
|
942
|
+
if (allSubstantive) {
|
|
943
|
+
return { allowed: true, tier: 2 };
|
|
944
|
+
}
|
|
945
|
+
|
|
683
946
|
return {
|
|
684
947
|
allowed: false,
|
|
685
|
-
reason: `[BLOCKED:
|
|
948
|
+
reason: `[BLOCKED: Target lines not covered by visible read and search block is non-substantive (<2 lines / <35 chars) -> read({ path: "${relPath}" })]`,
|
|
686
949
|
};
|
|
687
950
|
}
|
|
688
951
|
|
|
689
|
-
return {
|
|
952
|
+
return {
|
|
953
|
+
allowed: false,
|
|
954
|
+
reason: `[BLOCKED: Target lines not covered by visible read -> read({ path: "${relPath}" })]`,
|
|
955
|
+
};
|
|
690
956
|
}
|
|
691
957
|
|
|
692
958
|
/** Check whether the current session has any inspection evidence for a file. */
|
|
@@ -64,6 +64,9 @@ export function clampCommandOutput(
|
|
|
64
64
|
const maxLineLength = options?.maxLineLength ?? 300;
|
|
65
65
|
const maxLines = options?.maxLines ?? 40;
|
|
66
66
|
const maxTotalBytes = options?.maxTotalBytes ?? 20 * 1024;
|
|
67
|
+
if (!Number.isSafeInteger(maxTotalBytes) || maxTotalBytes < 0) {
|
|
68
|
+
throw new RangeError("maxTotalBytes must be a nonnegative safe integer");
|
|
69
|
+
}
|
|
67
70
|
|
|
68
71
|
const originalBytes = Buffer.byteLength(rawText, "utf8");
|
|
69
72
|
|
|
@@ -139,8 +142,9 @@ export function clampCommandOutput(
|
|
|
139
142
|
} catch {}
|
|
140
143
|
|
|
141
144
|
const hash = crypto.randomBytes(4).toString("hex");
|
|
142
|
-
|
|
143
|
-
fs.writeFileSync(
|
|
145
|
+
const candidatePath = path.join(tempDir, `pi_bash_spillover_${hash}.log`);
|
|
146
|
+
fs.writeFileSync(candidatePath, rawText, "utf8");
|
|
147
|
+
spilloverPath = candidatePath;
|
|
144
148
|
} catch (e) {
|
|
145
149
|
kernelDebug(e);
|
|
146
150
|
}
|
|
@@ -150,7 +154,10 @@ export function clampCommandOutput(
|
|
|
150
154
|
|
|
151
155
|
const formatLine = (line: string, idx: number): string => {
|
|
152
156
|
if (line.length > maxLineLength) {
|
|
153
|
-
|
|
157
|
+
let end = Math.max(10, maxLineLength - 60);
|
|
158
|
+
// Do not split a valid UTF-16 surrogate pair.
|
|
159
|
+
if (/[\uD800-\uDBFF]/.test(line.charAt(end - 1)) && /[\uDC00-\uDFFF]/.test(line.charAt(end))) end--;
|
|
160
|
+
const kept = line.slice(0, end);
|
|
154
161
|
const omitted = line.length - kept.length;
|
|
155
162
|
return `${kept}... <line ${idx + 1} truncated: ${omitted.toLocaleString()} chars omitted>`;
|
|
156
163
|
}
|
|
@@ -197,7 +204,24 @@ export function clampCommandOutput(
|
|
|
197
204
|
footer += `]`;
|
|
198
205
|
}
|
|
199
206
|
|
|
200
|
-
resultText
|
|
207
|
+
if (Buffer.byteLength(resultText + footer, "utf8") > maxTotalBytes) {
|
|
208
|
+
const marker = clampedLines.findIndex(line => /^\n\[\.\.\. /.test(line));
|
|
209
|
+
if (marker !== -1) clampedLines.splice(marker, 1);
|
|
210
|
+
}
|
|
211
|
+
// Enforce the byte budget on the complete returned text: retain whole lines,
|
|
212
|
+
// removing from the middle first so head and tail context survive.
|
|
213
|
+
while (clampedLines.length && Buffer.byteLength(clampedLines.join("\n") + footer, "utf8") > maxTotalBytes) {
|
|
214
|
+
const [removed] = clampedLines.splice(Math.floor(clampedLines.length / 2), 1);
|
|
215
|
+
if (!removed.startsWith("\n[... ")) shownLines--;
|
|
216
|
+
footer = "\n\n[Truncated: " + shownLines + "/" + totalLines + " lines." +
|
|
217
|
+
(spilloverPath ? " Full: " + spilloverPath + "]" : "]");
|
|
218
|
+
}
|
|
219
|
+
resultText = clampedLines.join("\n") + footer;
|
|
220
|
+
if (Buffer.byteLength(resultText, "utf8") > maxTotalBytes) {
|
|
221
|
+
// Budget too small for any recovery pointer: emit a bounded indication
|
|
222
|
+
// without a chopped, unusable path.
|
|
223
|
+
resultText = "[Truncated]".slice(0, maxTotalBytes);
|
|
224
|
+
}
|
|
201
225
|
|
|
202
226
|
const returnedBytes = Buffer.byteLength(resultText, "utf8");
|
|
203
227
|
|
|
@@ -74,14 +74,25 @@ export function registerAstSearchTool(
|
|
|
74
74
|
const visibleRange = r.codeBlock && r.visibleEndLine
|
|
75
75
|
? { startLine: r.line, endLine: r.visibleEndLine }
|
|
76
76
|
: null;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
77
|
+
if (visibleRange) {
|
|
78
|
+
globalEpistemicGuard.recordFileRead(r.filePath, sessionId, ctx.cwd, undefined, {
|
|
79
|
+
coverage: {
|
|
80
|
+
complete: false,
|
|
81
|
+
ranges: [visibleRange],
|
|
82
|
+
},
|
|
83
|
+
provenance: "ast_search",
|
|
84
|
+
query: params.name,
|
|
85
|
+
});
|
|
86
|
+
} else {
|
|
87
|
+
globalEpistemicGuard.recordFileSearched(r.filePath, sessionId, ctx.cwd, {
|
|
88
|
+
coverage: {
|
|
89
|
+
complete: false,
|
|
90
|
+
ranges: [],
|
|
91
|
+
},
|
|
92
|
+
provenance: "ast_search",
|
|
93
|
+
query: params.name,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
85
96
|
}
|
|
86
97
|
|
|
87
98
|
if (results.length === 0) {
|
|
@@ -15,12 +15,12 @@ export function registerCodeSearchTool(
|
|
|
15
15
|
name: "code_search",
|
|
16
16
|
label: "Codebase Search",
|
|
17
17
|
description:
|
|
18
|
-
"
|
|
18
|
+
"Fast BM25 & AST semantic search across code chunks. Best for conceptual questions, finding unfamiliar features, and searching when exact symbol names or file paths are unknown (prefer rg for exact text literals).",
|
|
19
19
|
promptSnippet: "Search codebase conceptually or by keywords via hybrid AST index",
|
|
20
20
|
renderShell: "default",
|
|
21
21
|
parameters: Type.Object({
|
|
22
22
|
query: Type.String({
|
|
23
|
-
description: "
|
|
23
|
+
description: "Conceptual keywords or natural phrase (e.g., 'connection idle timeout', 'auth middleware')",
|
|
24
24
|
}),
|
|
25
25
|
file_pattern: Type.Optional(
|
|
26
26
|
Type.String({
|
|
@@ -32,21 +32,6 @@ export function registerCodeSearchTool(
|
|
|
32
32
|
description: "Max results (default: 5, max: 15)",
|
|
33
33
|
}),
|
|
34
34
|
),
|
|
35
|
-
rrf_k: Type.Optional(
|
|
36
|
-
Type.Number({
|
|
37
|
-
description: "RRF constant (default: 60)",
|
|
38
|
-
}),
|
|
39
|
-
),
|
|
40
|
-
mode: Type.Optional(
|
|
41
|
-
Type.Union(CODE_SEARCH_MODES.map((mode) => Type.Literal(mode))),
|
|
42
|
-
),
|
|
43
|
-
scope: Type.Optional(
|
|
44
|
-
Type.Union([
|
|
45
|
-
Type.Literal("code"),
|
|
46
|
-
Type.Literal("all"),
|
|
47
|
-
Type.Literal("prose"),
|
|
48
|
-
]),
|
|
49
|
-
),
|
|
50
35
|
}),
|
|
51
36
|
async execute(
|
|
52
37
|
_toolCallId: string,
|
|
@@ -107,24 +92,53 @@ export function registerCodeSearchTool(
|
|
|
107
92
|
|
|
108
93
|
const sessionId = deps.getSessionId(ctx);
|
|
109
94
|
for (const hit of hits) {
|
|
110
|
-
|
|
111
|
-
hit.chunk.
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
95
|
+
const chunkRange =
|
|
96
|
+
Number.isFinite(hit.chunk.startLine) && Number.isFinite(hit.chunk.endLine)
|
|
97
|
+
? [{ startLine: hit.chunk.startLine, endLine: hit.chunk.endLine }]
|
|
98
|
+
: [];
|
|
99
|
+
if (chunkRange.length > 0) {
|
|
100
|
+
globalEpistemicGuard.recordFileRead(
|
|
101
|
+
hit.chunk.absolutePath,
|
|
102
|
+
sessionId,
|
|
103
|
+
ctx.cwd,
|
|
104
|
+
undefined,
|
|
105
|
+
{
|
|
106
|
+
coverage: { complete: false, ranges: chunkRange },
|
|
107
|
+
provenance: "code_search",
|
|
108
|
+
query,
|
|
109
|
+
},
|
|
110
|
+
);
|
|
111
|
+
} else {
|
|
112
|
+
globalEpistemicGuard.recordFileSearched(
|
|
113
|
+
hit.chunk.absolutePath,
|
|
114
|
+
sessionId,
|
|
115
|
+
ctx.cwd,
|
|
116
|
+
{
|
|
117
|
+
coverage: { complete: false, ranges: [] },
|
|
118
|
+
provenance: "code_search",
|
|
119
|
+
query,
|
|
120
|
+
},
|
|
121
|
+
);
|
|
122
|
+
}
|
|
120
123
|
}
|
|
121
124
|
|
|
125
|
+
const indexStatus = typeof index.getStatus === "function" ? index.getStatus() : undefined;
|
|
126
|
+
const wantsVectors =
|
|
127
|
+
indexStatus?.effectiveProfile === "hybrid" ||
|
|
128
|
+
indexStatus?.effectiveProfile === "full";
|
|
129
|
+
const vectorNotice =
|
|
130
|
+
wantsVectors &&
|
|
131
|
+
indexStatus &&
|
|
132
|
+
indexStatus.vectorCount < indexStatus.chunkCount
|
|
133
|
+
? `[Notice: Vector embeddings are incomplete (${indexStatus.vectorCount}/${indexStatus.chunkCount} chunks); searched via BM25]\n\n`
|
|
134
|
+
: "";
|
|
135
|
+
|
|
122
136
|
if (hits.length === 0) {
|
|
123
137
|
return {
|
|
124
138
|
content: [
|
|
125
139
|
{
|
|
126
140
|
type: "text",
|
|
127
|
-
text:
|
|
141
|
+
text: `${vectorNotice}No code chunks found matching "${query}". (Tips: Try 'ast_search' for exact symbol names or 'rg' for exact text literals).`,
|
|
128
142
|
},
|
|
129
143
|
],
|
|
130
144
|
details: { count: 0 },
|
|
@@ -141,7 +155,7 @@ export function registerCodeSearchTool(
|
|
|
141
155
|
content: [
|
|
142
156
|
{
|
|
143
157
|
type: "text",
|
|
144
|
-
text: formatted.text
|
|
158
|
+
text: `${vectorNotice}${formatted.text}`,
|
|
145
159
|
},
|
|
146
160
|
],
|
|
147
161
|
details: {
|