@floydous/pi-agent-kernel 0.6.1 → 0.6.2

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.
@@ -56,6 +56,55 @@ export function resolveUserPath(
56
56
  : path.resolve(cwd, expanded);
57
57
  }
58
58
 
59
+ const REDIRECT_OPERATORS = new Set([">", ">>", "<", "1>", "1>>", "2>", "2>>", "&>", "&>>", "2>&1"]);
60
+ const VALUE_FLAGS_BY_COMMAND: Record<string, { short: Set<string>; long: Set<string>; patternFlags?: Set<string> }> = {
61
+ rg: {
62
+ short: new Set(["A", "B", "C", "m", "g", "e", "f", "t", "T", "E", "M", "j"]),
63
+ long: new Set([
64
+ "--after-context", "--before-context", "--context", "--max-count", "--glob", "--iglob",
65
+ "--regexp", "--file", "--type", "--type-not", "--max-depth", "--encoding", "--color",
66
+ "--colors", "--max-columns", "--threads",
67
+ ]),
68
+ patternFlags: new Set(["-e", "-f", "--regexp", "--file"]),
69
+ },
70
+ grep: {
71
+ short: new Set(["A", "B", "C", "m", "e", "f"]),
72
+ long: new Set([
73
+ "--after-context", "--before-context", "--context", "--max-count", "--regexp", "--file",
74
+ "--include", "--exclude", "--exclude-dir", "--color",
75
+ ]),
76
+ patternFlags: new Set(["-e", "-f", "--regexp", "--file"]),
77
+ },
78
+ head: {
79
+ short: new Set(["n", "c"]),
80
+ long: new Set(["--lines", "--bytes"]),
81
+ },
82
+ tail: {
83
+ short: new Set(["n", "c"]),
84
+ long: new Set(["--lines", "--bytes"]),
85
+ },
86
+ sed: {
87
+ short: new Set(["e", "f"]),
88
+ long: new Set(["--expression", "--file"]),
89
+ patternFlags: new Set(["-e", "-f", "--expression", "--file"]),
90
+ },
91
+ awk: {
92
+ short: new Set(["F", "v", "f"]),
93
+ long: new Set(["--field-separator", "--assign", "--file"]),
94
+ patternFlags: new Set(["-f", "--file"]),
95
+ },
96
+ };
97
+
98
+ function hasOutputRedirection(subCommand: string): boolean {
99
+ // Replace quoted strings with a non-whitespace placeholder so `>` inside patterns
100
+ // is ignored while quoted redirect targets (`> "out.txt"`) remain detectable.
101
+ const unquoted = subCommand.replace(/"[^"]*"|'[^']*'/g, " __Q__ ");
102
+ // Ignore fd-to-fd merges like `2>&1` and stderr-only redirects (`2>/dev/null`);
103
+ // only stdout/combined redirection (`>`, `>>`, `1>`, `&>`) suppresses stdout.
104
+ const withoutFdMerge = unquoted.replace(/\b\d+>&\d+\b/g, " ");
105
+ return /(?:^|\s)(?:1|&)?>>?\s*\S/.test(withoutFdMerge);
106
+ }
107
+
59
108
  export function extractInspectedFilesFromCommand(
60
109
  command: string,
61
110
  cwd: string = process.cwd(),
@@ -111,17 +160,66 @@ export function extractInspectedFilesFromCommand(
111
160
  continue;
112
161
  }
113
162
 
114
- const positional = tokens
115
- .slice(1)
116
- .filter(
117
- (token) =>
118
- !token.startsWith("-") && ![">", ">>", "<", "2>", "2>&1"].includes(token),
119
- );
163
+ const flagSpec = VALUE_FLAGS_BY_COMMAND[command];
164
+ const positional: string[] = [];
165
+ let hasExplicitPattern = false;
166
+ let afterDoubleDash = false;
167
+ for (let i = 1; i < tokens.length; i++) {
168
+ const token = tokens[i]!;
169
+ if (REDIRECT_OPERATORS.has(token)) {
170
+ // Skip redirect target token (e.g. `> out.txt`, `< in.txt`), except `2>&1` which takes no operand.
171
+ if (token !== "2>&1") i++;
172
+ continue;
173
+ }
174
+ // Handle attached redirect tokens like `>out.txt` or `2>/dev/null`.
175
+ if (/^(?:\d?|&)?>>?\S/.test(token) || /^<\S/.test(token)) {
176
+ continue;
177
+ }
178
+ if (afterDoubleDash) {
179
+ positional.push(token);
180
+ continue;
181
+ }
182
+ if (token === "--") {
183
+ afterDoubleDash = true;
184
+ continue;
185
+ }
186
+ if (token.startsWith("--")) {
187
+ const eqIdx = token.indexOf("=");
188
+ const flagName = eqIdx >= 0 ? token.slice(0, eqIdx) : token;
189
+ if (flagSpec?.patternFlags?.has(flagName)) {
190
+ hasExplicitPattern = true;
191
+ }
192
+ if (eqIdx === -1 && flagSpec?.long.has(flagName)) {
193
+ i++; // consume separate value token
194
+ }
195
+ continue;
196
+ }
197
+ if (token.startsWith("-") && token.length > 1) {
198
+ const body = token.slice(1);
199
+ if (flagSpec) {
200
+ // Check short flags; stop as soon as a value-taking flag is encountered.
201
+ for (let j = 0; j < body.length; j++) {
202
+ const ch = body[j]!;
203
+ if (flagSpec.patternFlags?.has(`-${ch}`)) {
204
+ hasExplicitPattern = true;
205
+ }
206
+ if (flagSpec.short.has(ch)) {
207
+ // Value is attached if remaining chars exist (e.g. `-C3`, `-n20`); otherwise consume next token.
208
+ if (j === body.length - 1) {
209
+ i++;
210
+ }
211
+ break;
212
+ }
213
+ }
214
+ }
215
+ continue;
216
+ }
217
+ positional.push(token);
218
+ }
219
+
120
220
  let candidates: string[];
121
- if (command === "grep" || command === "rg" || command === "awk") {
122
- candidates = positional.slice(1);
123
- } else if (command === "sed") {
124
- candidates = positional.slice(1);
221
+ if (command === "grep" || command === "rg" || command === "awk" || command === "sed") {
222
+ candidates = hasExplicitPattern ? positional : positional.slice(1);
125
223
  } else {
126
224
  candidates = positional;
127
225
  }
@@ -479,28 +577,29 @@ export function parsePagingAndDiffOutput(
479
577
  outputText: string,
480
578
  candidateFiles: string[],
481
579
  cwd = process.cwd(),
580
+ allowSubsliceMatch = false,
482
581
  ): Map<string, number[]> {
483
582
  const result = new Map<string, number[]>();
484
- if (candidateFiles.length === 0 || !outputText) return result;
485
-
486
- const targetPath = path.isAbsolute(candidateFiles[0])
487
- ? path.normalize(candidateFiles[0])
488
- : path.resolve(cwd, candidateFiles[0]);
489
-
490
- let sourceLines: string[];
491
- try {
492
- const sourceText = fs.readFileSync(targetPath, "utf8").replace(/\r\n/g, "\n");
493
- sourceLines = sourceText.split("\n");
494
- if (sourceText.endsWith("\n")) sourceLines.pop();
495
- } catch {
496
- return result;
497
- }
583
+ if (candidateFiles.length === 0 || !outputText || hasOutputRedirection(command)) return result;
498
584
 
499
585
  const outputLines = outputText.replace(/\r\n/g, "\n").split("\n");
500
586
  if (outputLines.at(-1) === "") outputLines.pop();
501
587
  if (outputLines.length === 0) return result;
502
588
 
503
- const matchesRange = (start: number, end: number): boolean => {
589
+ const matchSubslice = allowSubsliceMatch || candidateFiles.length > 1;
590
+
591
+ const verifyFileRange = (targetPath: string, resolveSpan: (totalLines: number) => [number, number] | null): void => {
592
+ let sourceLines: string[];
593
+ try {
594
+ const sourceText = fs.readFileSync(targetPath, "utf8").replace(/\r\n/g, "\n");
595
+ sourceLines = sourceText.split("\n");
596
+ if (sourceText.endsWith("\n")) sourceLines.pop();
597
+ } catch {
598
+ return;
599
+ }
600
+ const span = resolveSpan(sourceLines.length);
601
+ if (!span) return;
602
+ const [start, end] = span;
504
603
  if (
505
604
  !Number.isSafeInteger(start) ||
506
605
  !Number.isSafeInteger(end) ||
@@ -508,40 +607,112 @@ export function parsePagingAndDiffOutput(
508
607
  end < start ||
509
608
  end > sourceLines.length
510
609
  ) {
511
- return false;
610
+ return;
512
611
  }
513
612
  const expected = sourceLines.slice(start - 1, end);
514
- return (
613
+ if (expected.length === 0) return;
614
+
615
+ let matched = false;
616
+ if (
515
617
  expected.length === outputLines.length &&
516
618
  expected.every((line, index) => line === outputLines[index])
517
- );
619
+ ) {
620
+ matched = true;
621
+ } else if (matchSubslice && expected.length <= outputLines.length) {
622
+ // In compound/multi-file output, accept an exact contiguous slice only if at least one non-empty line matches.
623
+ const hasNonEmpty = expected.some((line) => line.trim().length > 0);
624
+ if (hasNonEmpty) {
625
+ for (let offset = 0; offset <= outputLines.length - expected.length; offset++) {
626
+ let allMatch = true;
627
+ for (let j = 0; j < expected.length; j++) {
628
+ if (outputLines[offset + j] !== expected[j]) {
629
+ allMatch = false;
630
+ break;
631
+ }
632
+ }
633
+ if (allMatch) {
634
+ matched = true;
635
+ break;
636
+ }
637
+ }
638
+ }
639
+ }
640
+
641
+ if (matched) {
642
+ const existing = result.get(targetPath) ?? [];
643
+ const merged = new Set(existing);
644
+ for (let line = start; line <= end; line++) merged.add(line);
645
+ result.set(targetPath, Array.from(merged).sort((a, b) => a - b));
646
+ }
518
647
  };
519
648
 
520
- const headMatch = command.match(/\bhead\b.*?-n\s*(\d+)/i);
521
- if (headMatch) {
522
- const end = Math.min(parseInt(headMatch[1]!, 10), sourceLines.length);
523
- if (end > 0 && matchesRange(1, end)) {
524
- result.set(targetPath, Array.from({ length: end }, (_, index) => index + 1));
649
+ const targetPaths = candidateFiles.map((cand) =>
650
+ path.isAbsolute(cand) ? path.normalize(cand) : path.resolve(cwd, cand),
651
+ );
652
+
653
+ // head: supports `head -n 20`, `head -n20`, `head --lines=20`, POSIX `head -20`, and default `head` (10 lines)
654
+ if (/\bhead\b/i.test(command)) {
655
+ const headExplicit =
656
+ command.match(/\bhead\b(?:[^|;&\n]*?)(?:-n\s*|--lines[=\s]+)(\d+)/i) ||
657
+ command.match(/\bhead\b(?:[^|;&\n]*?)\s-(\d+)(?:\s|$)/i);
658
+ const requested = headExplicit ? parseInt(headExplicit[1]!, 10) : (/\bhead\b[^|;&\n]*?(?:-c|--bytes)\b/i.test(command) ? 0 : 10);
659
+ if (requested > 0) {
660
+ for (const targetPath of targetPaths) {
661
+ verifyFileRange(targetPath, (total) => {
662
+ const end = Math.min(requested, total);
663
+ return end > 0 ? [1, end] : null;
664
+ });
665
+ }
525
666
  }
526
667
  return result;
527
668
  }
528
669
 
529
- const tailMatch = command.match(/\btail\b.*?-n\s*(\d+)/i);
530
- if (tailMatch) {
531
- const count = Math.min(parseInt(tailMatch[1]!, 10), sourceLines.length);
532
- const start = sourceLines.length - count + 1;
533
- if (count > 0 && matchesRange(start, sourceLines.length)) {
534
- result.set(targetPath, Array.from({ length: count }, (_, index) => start + index));
670
+ // tail: supports `tail -n 20`, `tail -n +20`, `tail --lines=20`, POSIX `tail -20`, and default `tail` (10 lines)
671
+ if (/\btail\b/i.test(command)) {
672
+ const tailFromStart = command.match(/\btail\b(?:[^|;&\n]*?)(?:-n\s*|--lines[=\s]+)\+(\d+)/i);
673
+ if (tailFromStart) {
674
+ const startLine = parseInt(tailFromStart[1]!, 10);
675
+ if (startLine >= 1) {
676
+ for (const targetPath of targetPaths) {
677
+ verifyFileRange(targetPath, (total) => (startLine <= total ? [startLine, total] : null));
678
+ }
679
+ }
680
+ return result;
681
+ }
682
+ const tailExplicit =
683
+ command.match(/\btail\b(?:[^|;&\n]*?)(?:-n\s*|--lines[=\s]+)(\d+)/i) ||
684
+ command.match(/\btail\b(?:[^|;&\n]*?)\s-(\d+)(?:\s|$)/i);
685
+ const requested = tailExplicit ? parseInt(tailExplicit[1]!, 10) : (/\btail\b[^|;&\n]*?(?:-c|--bytes)\b/i.test(command) ? 0 : 10);
686
+ if (requested > 0) {
687
+ for (const targetPath of targetPaths) {
688
+ verifyFileRange(targetPath, (total) => {
689
+ const count = Math.min(requested, total);
690
+ return count > 0 ? [total - count + 1, total] : null;
691
+ });
692
+ }
535
693
  }
536
694
  return result;
537
695
  }
538
696
 
539
- const sedMatch = command.match(/\bsed\b.*?-n\s*['"]?(\d+),(\d+)p['"]?/i);
540
- if (sedMatch) {
541
- const start = parseInt(sedMatch[1]!, 10);
542
- const end = parseInt(sedMatch[2]!, 10);
543
- if (matchesRange(start, end)) {
544
- result.set(targetPath, Array.from({ length: end - start + 1 }, (_, index) => start + index));
697
+ // sed: supports `sed -n '10,20p'`, `sed -n '10,$p'`, `sed -n '10p'`
698
+ const sedRangeMatch = command.match(/\bsed\b[^|;&\n]*?-n\s*(?:-e\s*)?['"]?(\d+),(\d+|\$)p['"]?/i);
699
+ if (sedRangeMatch) {
700
+ const start = parseInt(sedRangeMatch[1]!, 10);
701
+ const rawEnd = sedRangeMatch[2]!;
702
+ for (const targetPath of targetPaths) {
703
+ verifyFileRange(targetPath, (total) => {
704
+ const end = rawEnd === "$" ? total : Math.min(parseInt(rawEnd, 10), total);
705
+ return start >= 1 && end >= start ? [start, end] : null;
706
+ });
707
+ }
708
+ return result;
709
+ }
710
+
711
+ const sedSingleMatch = command.match(/\bsed\b[^|;&\n]*?-n\s*(?:-e\s*)?['"]?(\d+)p['"]?/i);
712
+ if (sedSingleMatch) {
713
+ const lineNum = parseInt(sedSingleMatch[1]!, 10);
714
+ for (const targetPath of targetPaths) {
715
+ verifyFileRange(targetPath, (total) => (lineNum >= 1 && lineNum <= total ? [lineNum, lineNum] : null));
545
716
  }
546
717
  }
547
718
 
@@ -751,6 +922,35 @@ export function loadSessionInspectionState(
751
922
  export class EpistemicGuard {
752
923
  private inspectedFilesBySession: Map<string, Map<string, InspectionEvidence>> =
753
924
  new Map();
925
+ private batchDepthByKey = new Map<string, number>();
926
+ private batchDirtyKeys = new Set<string>();
927
+
928
+ private batchKey(sessionId: string, cwd: string): string {
929
+ const resolved = path.resolve(cwd);
930
+ return `${sessionId}\0${process.platform === "win32" ? resolved.toLowerCase() : resolved}`;
931
+ }
932
+
933
+ /** Coalesce multiple evidence writes within one tool call into a single atomic disk flush. */
934
+ public withBatchPersist<T>(sessionId: string, cwd: string, fn: () => T): T {
935
+ const key = this.batchKey(sessionId, cwd);
936
+ this.batchDepthByKey.set(key, (this.batchDepthByKey.get(key) ?? 0) + 1);
937
+ try {
938
+ return fn();
939
+ } finally {
940
+ const nextDepth = (this.batchDepthByKey.get(key) ?? 1) - 1;
941
+ if (nextDepth <= 0) {
942
+ this.batchDepthByKey.delete(key);
943
+ if (this.batchDirtyKeys.delete(key)) {
944
+ const evidence = this.inspectedFilesBySession.get(sessionId);
945
+ if (evidence) {
946
+ saveSessionInspectionState(sessionId, evidence, cwd);
947
+ }
948
+ }
949
+ } else {
950
+ this.batchDepthByKey.set(key, nextDepth);
951
+ }
952
+ }
953
+ }
754
954
 
755
955
  private resolvePath(filePath: string, cwd = process.cwd()): string {
756
956
  return resolveUserPath(filePath, cwd);
@@ -851,6 +1051,11 @@ export class EpistemicGuard {
851
1051
  }
852
1052
 
853
1053
  private persistSessionState(sessionId: string, cwd = process.cwd()): void {
1054
+ const key = this.batchKey(sessionId, cwd);
1055
+ if ((this.batchDepthByKey.get(key) ?? 0) > 0) {
1056
+ this.batchDirtyKeys.add(key);
1057
+ return;
1058
+ }
854
1059
  const evidence = this.inspectedFilesBySession.get(sessionId);
855
1060
  if (evidence) {
856
1061
  saveSessionInspectionState(sessionId, evidence, cwd);
@@ -1011,11 +1216,12 @@ export class EpistemicGuard {
1011
1216
  files: string[],
1012
1217
  outputComplete: boolean,
1013
1218
  outputText = "",
1219
+ isCompound = false,
1014
1220
  ): void {
1015
1221
  const isPaging = /\b(head|tail|sed)\b/i.test(command);
1016
1222
  const isCat = /\bcat\b/i.test(command);
1017
1223
 
1018
- if (isCat) {
1224
+ if (isCat && !hasOutputRedirection(command)) {
1019
1225
  for (const filePath of files) {
1020
1226
  try {
1021
1227
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
@@ -1023,7 +1229,7 @@ export class EpistemicGuard {
1023
1229
  if (
1024
1230
  (outputComplete && files.length === 1 && outputText === observedContent) ||
1025
1231
  outputText.trim() === observedContent.trim() ||
1026
- outputText.includes(observedContent.trim())
1232
+ (observedContent.trim().length > 0 && outputText.includes(observedContent.trim()))
1027
1233
  ) {
1028
1234
  this.recordFileRead(filePath, sessionId, cwd, observedContent, {
1029
1235
  coverage: { complete: true, ranges: [] },
@@ -1040,7 +1246,7 @@ export class EpistemicGuard {
1040
1246
 
1041
1247
  let parsed: GrepParseOutput;
1042
1248
  if (isPaging) {
1043
- parsed = parsePagingAndDiffOutput(command, outputText, files, cwd);
1249
+ parsed = parsePagingAndDiffOutput(command, outputText, files, cwd, isCompound);
1044
1250
  } else {
1045
1251
  parsed = parseGrepOutput(outputText, files, cwd);
1046
1252
  }
@@ -1078,39 +1284,42 @@ export class EpistemicGuard {
1078
1284
  outputComplete = true,
1079
1285
  outputText = "",
1080
1286
  ): string[] {
1081
- const files = extractInspectedFilesFromCommand(command, cwd);
1082
- const isCompound = /[|;&\n><]/.test(command);
1083
- for (const subCommand of command.split(/[|;&\n]+/)) {
1084
- const trimmed = subCommand.trim();
1085
- if (!trimmed) continue;
1086
- this.recordShellEvidence(
1087
- trimmed,
1088
- cwd,
1089
- sessionId,
1090
- extractInspectedFilesFromCommand(trimmed, cwd),
1091
- outputComplete && !isCompound,
1092
- outputText,
1093
- );
1094
- }
1095
- // Also scan outputText for polyglot compiler/test traces across the
1096
- // workspace. Paging/search output already has stricter attribution above;
1097
- // feeding it into the generic grep parser would let synthetic `1:line`
1098
- // text manufacture read evidence.
1099
- const isPagingOrSearchOutput = /\b(head|tail|sed|grep|rg)\b/i.test(command);
1100
- if (!isPagingOrSearchOutput) {
1101
- const traces = parseGrepOutput(outputText, files, cwd);
1102
- for (const [filePath, lineNumbers] of traces.entries()) {
1103
- const ranges = linesToRanges(lineNumbers);
1104
- if (ranges.length > 0) {
1105
- this.recordFileRead(filePath, sessionId, cwd, undefined, {
1106
- coverage: { complete: false, ranges },
1107
- provenance: "bash",
1108
- query: command,
1109
- });
1287
+ return this.withBatchPersist(sessionId, cwd, () => {
1288
+ const files = extractInspectedFilesFromCommand(command, cwd);
1289
+ const isCompound = /[|;&\n><]/.test(command);
1290
+ for (const subCommand of command.split(/[|;&\n]+/)) {
1291
+ const trimmed = subCommand.trim();
1292
+ if (!trimmed) continue;
1293
+ this.recordShellEvidence(
1294
+ trimmed,
1295
+ cwd,
1296
+ sessionId,
1297
+ extractInspectedFilesFromCommand(trimmed, cwd),
1298
+ outputComplete && !isCompound,
1299
+ outputText,
1300
+ isCompound,
1301
+ );
1302
+ }
1303
+ // Also scan outputText for polyglot compiler/test traces across the
1304
+ // workspace. Paging/search output already has stricter attribution above;
1305
+ // feeding it into the generic grep parser would let synthetic `1:line`
1306
+ // text manufacture read evidence.
1307
+ const isPagingOrSearchOutput = /\b(head|tail|sed|grep|rg)\b/i.test(command);
1308
+ if (!isPagingOrSearchOutput) {
1309
+ const traces = parseGrepOutput(outputText, files, cwd);
1310
+ for (const [filePath, lineNumbers] of traces.entries()) {
1311
+ const ranges = linesToRanges(lineNumbers);
1312
+ if (ranges.length > 0) {
1313
+ this.recordFileRead(filePath, sessionId, cwd, undefined, {
1314
+ coverage: { complete: false, ranges },
1315
+ provenance: "bash",
1316
+ query: command,
1317
+ });
1318
+ }
1110
1319
  }
1111
1320
  }
1112
- }
1113
- return files;
1321
+ return files;
1322
+ });
1114
1323
  }
1115
1324
 
1116
1325
  /**
@@ -1218,7 +1427,17 @@ export class EpistemicGuard {
1218
1427
  return { allowed: true };
1219
1428
  }
1220
1429
 
1221
- // 4. Edit operations: Per-Block Hybrid Authorization
1430
+ // 4. Edit operations require actual read evidence first.
1431
+ // Search metadata is useful for navigation but never authorizes mutation,
1432
+ // regardless of how substantial the proposed replacement text is.
1433
+ if (evidence.kind !== "read") {
1434
+ return {
1435
+ allowed: false,
1436
+ reason: `[BLOCKED: Search metadata does not authorize edits -> read({ path: "${relPath}" })]`,
1437
+ };
1438
+ }
1439
+
1440
+ // Per-Block Hybrid Authorization
1222
1441
  // Each block in a multi-block edit must independently satisfy either:
1223
1442
  // - Tier 1: its resolved target range is covered by visible read evidence, OR
1224
1443
  // - Tier 2: its search block is substantive (>=2 lines and >=35 chars, or >=50 chars).
@@ -1344,15 +1563,6 @@ export class EpistemicGuard {
1344
1563
  }
1345
1564
  }
1346
1565
 
1347
- // Search metadata is useful for navigation but never authorizes mutation,
1348
- // regardless of how substantial the proposed replacement text is.
1349
- if (evidence.kind !== "read") {
1350
- return {
1351
- allowed: false,
1352
- reason: `[BLOCKED: Search metadata does not authorize edits -> read({ path: "${relPath}" })]`,
1353
- };
1354
- }
1355
-
1356
1566
  // Tier 2: Substantive unique block authorization
1357
1567
  // If range math has gaps (e.g. grep context, compiler traces, symbol extraction boundaries),
1358
1568
  // authorize if every search block is substantive (>=2 non-empty content lines and >=35 chars).
@@ -1,12 +1,15 @@
1
1
  import * as path from "node:path";
2
2
  import type { SearchHit } from "../retrieval/search_index";
3
3
  import { tokenizeCode } from "../retrieval/search_bm25";
4
+ import { isTestPath } from "../retrieval/tag_extractor";
4
5
 
5
6
  export const CODE_SEARCH_MODES = ["auto", "full", "preview", "summary"] as const;
6
7
  export type CodeSearchMode = (typeof CODE_SEARCH_MODES)[number];
7
8
 
8
9
  /** Maximum automatic response size in characters (before the tool footer). */
9
10
  export const AUTO_OUTPUT_BUDGET = 8_000;
11
+ /** Hard safety cap in characters for explicit `mode: "full"` responses. */
12
+ export const FULL_OUTPUT_BUDGET = 12_000;
10
13
 
11
14
  const PREVIEW_LINE_LIMIT = 12;
12
15
  const PREVIEW_CHAR_LIMIT = 1_400;
@@ -139,6 +142,7 @@ interface BudgetEntry {
139
142
  function applyBudget(
140
143
  entries: BudgetEntry[],
141
144
  budget: number,
145
+ omissionHint: "full" | "read" = "full",
142
146
  ): { text: string; truncated: boolean; visibleRanges: VisibleCodeRange[] } {
143
147
  const selected: string[] = [];
144
148
  const visibleRanges: VisibleCodeRange[] = [];
@@ -174,7 +178,9 @@ function applyBudget(
174
178
  }
175
179
 
176
180
  if (omitted > 0) {
177
- const notice = `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted; use mode: "full" or a narrower query to inspect them ...`;
181
+ const notice = omissionHint === "read"
182
+ ? `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted (output cap); use read({ path, offset, limit }) or a narrower query to inspect them ...`
183
+ : `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted; use mode: "full" or a narrower query to inspect them ...`;
178
184
  const separator = selected.length > 0 ? "\n\n" : "";
179
185
  const remaining = Math.max(0, budget - used - separator.length);
180
186
  if (remaining > 0) {
@@ -200,6 +206,11 @@ function resolveAutoMode(hits: SearchHit[]): Exclude<CodeSearchMode, "auto"> | "
200
206
  * response. Automatic mode is context-preserving: it previews a small number
201
207
  * of top hits, summarizes the rest, and enforces a total response budget.
202
208
  */
209
+ function mixedPrefix(hitCount: number): string {
210
+ const previewCount = Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount);
211
+ return `${hitCount} matches returned; first ${previewCount} shown as previews, remaining ${hitCount - previewCount} summarized.\n\n`;
212
+ }
213
+
203
214
  function decorateResult(
204
215
  result: FormattedCodeSearchResults,
205
216
  requestedMode: CodeSearchMode,
@@ -209,10 +220,7 @@ function decorateResult(
209
220
  return result;
210
221
  }
211
222
 
212
- const notice = result.mode === "mixed"
213
- ? `${hitCount} matches returned; first ${Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount)} shown as previews, remaining ${hitCount - Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount)} summarized.`
214
- : "";
215
- const prefix = notice ? `${notice}\n\n` : "";
223
+ const prefix = result.mode === "mixed" ? mixedPrefix(hitCount) : "";
216
224
  const available = Math.max(0, AUTO_OUTPUT_BUDGET - prefix.length);
217
225
  const boundedText = clipToBudget(result.text, available);
218
226
  const finalClipped = boundedText.length < result.text.length;
@@ -224,19 +232,50 @@ function decorateResult(
224
232
  };
225
233
  }
226
234
 
235
+ export interface FormatCodeSearchOptions {
236
+ filePattern?: string;
237
+ separateTests?: boolean;
238
+ }
239
+
227
240
  /**
228
- * Format search hits for the model. Explicit full mode preserves the legacy
229
- * response. Automatic mode is context-preserving: it previews a small number
230
- * of top hits, summarizes the rest, and enforces a total response budget.
241
+ * Format search hits for the model. Explicit full mode renders complete bodies
242
+ * up to FULL_OUTPUT_BUDGET and summarizes appended bonus test hits when tests
243
+ * were not targeted. Automatic mode previews top hits and summarizes the rest
244
+ * within AUTO_OUTPUT_BUDGET.
231
245
  */
232
246
  export function formatCodeSearchResults(
233
247
  hits: SearchHit[],
234
248
  query: string,
235
249
  requestedMode: CodeSearchMode = "auto",
250
+ options: FormatCodeSearchOptions = {},
236
251
  ): FormattedCodeSearchResults {
237
252
  const autoMode = requestedMode === "auto" ? resolveAutoMode(hits) : requestedMode;
238
253
 
239
254
  if (autoMode === "full") {
255
+ if (requestedMode === "full") {
256
+ const targetsTests =
257
+ /\b(tests?|specs?)\b/i.test(query) ||
258
+ /test|spec/i.test(options.filePattern ?? "");
259
+ const summarizeBonusTests = Boolean(options.separateTests && !targetsTests);
260
+ const entries: BudgetEntry[] = hits.map((hit) => {
261
+ const isBonusTest =
262
+ summarizeBonusTests &&
263
+ (isTestPath(hit.chunk.filePath) || hit.chunk.kind === "test");
264
+ if (isBonusTest) {
265
+ return { text: summaryHit(hit) };
266
+ }
267
+ return {
268
+ text: fullHit(hit),
269
+ visibleRange: {
270
+ chunkId: hit.chunk.id,
271
+ startLine: hit.chunk.startLine,
272
+ endLine: hit.chunk.endLine,
273
+ },
274
+ };
275
+ });
276
+ const bounded = applyBudget(entries, FULL_OUTPUT_BUDGET, "read");
277
+ return { ...bounded, mode: "full" };
278
+ }
240
279
  return decorateResult(
241
280
  {
242
281
  text: hits.map(fullHit).join("\n\n"),
@@ -277,6 +316,7 @@ export function formatCodeSearchResults(
277
316
  const remainingSummary = hits
278
317
  .slice(AUTO_PREVIEW_HIT_LIMIT)
279
318
  .map((hit) => ({ text: summaryHit(hit) }));
280
- const bounded = applyBudget([...topPreview, ...remainingSummary], AUTO_OUTPUT_BUDGET);
319
+ const mixedBudget = Math.max(0, AUTO_OUTPUT_BUDGET - mixedPrefix(hits.length).length);
320
+ const bounded = applyBudget([...topPreview, ...remainingSummary], mixedBudget);
281
321
  return decorateResult({ ...bounded, mode: "mixed" }, requestedMode, hits.length);
282
322
  }