@floydous/pi-agent-kernel 0.6.0 → 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.
@@ -280,7 +280,11 @@ export class TreeSitterEngine {
280
280
  }
281
281
  }
282
282
 
283
- public extractTags(filePath: string, content: string): FileTags | null {
283
+ public extractTags(
284
+ filePath: string,
285
+ content: string,
286
+ options: { includeJsTestBlocks?: boolean; collectReferences?: boolean } = {},
287
+ ): FileTags | null {
284
288
  const ext = path.extname(filePath).toLowerCase();
285
289
  let parser = this.getParser(ext);
286
290
  if (!parser) {
@@ -896,20 +900,72 @@ export class TreeSitterEngine {
896
900
 
897
901
  visit(root, false);
898
902
 
899
- // Extract clean AST identifiers for PageRank graph (skips comments, docstrings, and strings)
900
- function collectAstReferences(n: any) {
901
- const t = n.type;
902
- if (t === "identifier" || t === "property_identifier" || t === "type_identifier" || t === "field_identifier" || t === "word") {
903
- const text = n.text;
904
- if (text && text.length >= 3 && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(text)) {
905
- references.add(text);
903
+ // For JS/TS test files, extract top-level describe/it/test/suite blocks from the same AST
904
+ // instead of re-parsing the file in search_chunker.
905
+ if (options.includeJsTestBlocks && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx")) {
906
+ for (let i = 0; i < root.childCount; i++) {
907
+ const child = root.child(i);
908
+ if (child.type !== "expression_statement") continue;
909
+ let expr = child.firstNamedChild;
910
+ let callee: any = null;
911
+ let argsNode: any = null;
912
+ while (expr && expr.type === "call_expression") {
913
+ const fn = expr.childForFieldName("function");
914
+ const args = expr.childForFieldName("arguments");
915
+ if (args && !argsNode) argsNode = args;
916
+ if (fn) {
917
+ callee = fn;
918
+ if (fn.type === "call_expression") {
919
+ expr = fn;
920
+ } else {
921
+ break;
922
+ }
923
+ } else {
924
+ break;
925
+ }
906
926
  }
927
+ if (!callee) continue;
928
+ const calleeText = callee.text;
929
+ const match = calleeText.match(/^(?:(?:suite|describe|context|it|test)(?:\.(?:only|skip|each|todo|concurrent|serial))?)/);
930
+ if (!match) continue;
931
+ let title = "";
932
+ if (argsNode) {
933
+ for (const arg of argsNode.namedChildren) {
934
+ if (arg.type === "string" || arg.type === "template_string") {
935
+ title = arg.text.replace(/^['"`]|['"`]$/g, "");
936
+ break;
937
+ }
938
+ }
939
+ }
940
+ const testName = title ? `${match[0]}('${title}')` : match[0];
941
+ const newlineIdx = content.indexOf("\n", child.startIndex);
942
+ const firstLine = (newlineIdx === -1 ? content.slice(child.startIndex) : content.slice(child.startIndex, newlineIdx)).trim();
943
+ definitions.push({
944
+ name: testName,
945
+ kind: "test",
946
+ signature: firstLine.length < 120 ? firstLine : testName,
947
+ line: child.startPosition.row + 1,
948
+ endLine: child.endPosition.row + 1,
949
+ });
907
950
  }
908
- for (const child of n.namedChildren) {
909
- collectAstReferences(child);
951
+ }
952
+
953
+ // Extract clean AST identifiers for PageRank graph (skips comments, docstrings, and strings)
954
+ if (options.collectReferences !== false) {
955
+ function collectAstReferences(n: any) {
956
+ const t = n.type;
957
+ if (t === "identifier" || t === "property_identifier" || t === "type_identifier" || t === "field_identifier" || t === "word") {
958
+ const text = n.text;
959
+ if (text && text.length >= 3 && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(text)) {
960
+ references.add(text);
961
+ }
962
+ }
963
+ for (const child of n.namedChildren) {
964
+ collectAstReferences(child);
965
+ }
910
966
  }
967
+ collectAstReferences(root);
911
968
  }
912
- collectAstReferences(root);
913
969
  if (ext === ".rs") markRustTests(root, definitions);
914
970
 
915
971
  return {
@@ -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).
@@ -54,10 +54,20 @@ interface LinuxDistroInfo {
54
54
  idLike?: string;
55
55
  }
56
56
 
57
+ function sanitizeHostMetadataText(value: string): string {
58
+ return value
59
+ .replace(/[\r\n\t]+/g, " ")
60
+ .replace(/[\x00-\x1f\x7f]/g, "")
61
+ .replace(/&/g, "&amp;")
62
+ .replace(/</g, "&lt;")
63
+ .replace(/>/g, "&gt;")
64
+ .trim() || "Linux";
65
+ }
66
+
57
67
  function resolveLinuxDistro(options?: HostEnvironmentOptions): LinuxDistroInfo {
58
68
  if (options?.osReleaseContent) {
59
69
  const parsed = parseOSRelease(options.osReleaseContent);
60
- const name = parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux";
70
+ const name = sanitizeHostMetadataText(parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux");
61
71
  return { name, id: parsed.ID?.toLowerCase(), idLike: parsed.ID_LIKE?.toLowerCase() };
62
72
  }
63
73
 
@@ -66,7 +76,7 @@ function resolveLinuxDistro(options?: HostEnvironmentOptions): LinuxDistroInfo {
66
76
  if (fs.existsSync(p)) {
67
77
  const content = fs.readFileSync(p, "utf8");
68
78
  const parsed = parseOSRelease(content);
69
- const name = parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux";
79
+ const name = sanitizeHostMetadataText(parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux");
70
80
  return { name, id: parsed.ID?.toLowerCase(), idLike: parsed.ID_LIKE?.toLowerCase() };
71
81
  }
72
82
  } catch {}
@@ -134,7 +144,7 @@ export function renderHostEnvironment(options?: HostEnvironmentOptions): string
134
144
  "Shell: bash (macOS /bin/bash v3.2)",
135
145
  "Line Endings: Preserved per-file (auto-detects CRLF / LF)",
136
146
  "Platform Guidance:",
137
- "- Stock /bin/bash is Bash 3.2: avoid Bash 4+ features (declare -A, mapfile/readarray, ${var^^}).",
147
+ "- Stock /bin/bash is Bash 3.2: use POSIX sh / Bash 3.2 constructs (indexed arrays, while read loops, tr/awk); avoid Bash 4+ features (declare -A, mapfile/readarray, ${var^^}).",
138
148
  "- BSD userland: use portable POSIX flags (e.g. sed -i '' for in-place edit, not GNU sed -i).",
139
149
  "</host_environment>",
140
150
  ];