@floydous/pi-agent-kernel 0.4.0 → 0.4.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.
@@ -10,6 +10,7 @@ import * as fs from "node:fs";
10
10
  import * as os from "node:os";
11
11
  import * as path from "node:path";
12
12
  import { kernelDebug } from "./kernel_debug";
13
+ import { getPiHomeDir } from "../config/kernel_config";
13
14
 
14
15
  /**
15
16
  * Extract file paths used as inputs by known shell content-reader commands.
@@ -164,10 +165,16 @@ export type EvidenceProvenance =
164
165
  | "edit"
165
166
  | "write";
166
167
 
168
+ export interface SearchHit {
169
+ line: number;
170
+ text?: string;
171
+ }
172
+
167
173
  export interface EvidenceOptions {
168
174
  coverage?: EvidenceCoverage;
169
175
  provenance?: EvidenceProvenance;
170
176
  query?: string;
177
+ searchHits?: SearchHit[];
171
178
  }
172
179
 
173
180
  export interface ContextEvidence {
@@ -179,6 +186,7 @@ export interface ContextEvidence {
179
186
  coverage: EvidenceCoverage;
180
187
  provenance: EvidenceProvenance;
181
188
  query?: string;
189
+ searchHits?: SearchHit[];
182
190
  }
183
191
 
184
192
  interface InspectionEvidence {
@@ -187,6 +195,7 @@ interface InspectionEvidence {
187
195
  coverage: EvidenceCoverage;
188
196
  provenance: EvidenceProvenance;
189
197
  query?: string;
198
+ searchHits?: SearchHit[];
190
199
  }
191
200
 
192
201
  function normalizeRanges(
@@ -259,6 +268,7 @@ function mergeEvidence(
259
268
  coverage: EvidenceCoverage,
260
269
  provenance: EvidenceProvenance,
261
270
  query?: string,
271
+ searchHits?: SearchHit[],
262
272
  ): InspectionEvidence {
263
273
  if (previous.fingerprint !== fingerprint) {
264
274
  return {
@@ -267,16 +277,26 @@ function mergeEvidence(
267
277
  coverage,
268
278
  provenance,
269
279
  ...(query === undefined ? {} : { query }),
280
+ ...(searchHits === undefined || searchHits.length === 0 ? {} : { searchHits }),
270
281
  };
271
282
  }
272
283
  // Once marked read, retain read kind unless reset
273
284
  const mergedKind = previous.kind === "read" || kind === "read" ? "read" : "search";
285
+ const combinedHits = [
286
+ ...(previous.searchHits || []),
287
+ ...(searchHits || []),
288
+ ];
289
+ const uniqueHits = combinedHits.length > 0
290
+ ? Array.from(new Map(combinedHits.map((h) => [h.line, h])).values()).sort((a, b) => a.line - b.line)
291
+ : undefined;
292
+
274
293
  return {
275
294
  ...previous,
276
295
  kind: mergedKind,
277
296
  coverage: mergeCoverage(previous.coverage, coverage),
278
297
  provenance,
279
298
  ...(query === undefined ? {} : { query }),
299
+ ...(uniqueHits ? { searchHits: uniqueHits } : {}),
280
300
  };
281
301
  }
282
302
 
@@ -307,14 +327,25 @@ export function linesToRanges(lines: Iterable<number>): EvidenceRange[] {
307
327
  return ranges;
308
328
  }
309
329
 
310
- /** Parse stdout from grep / ripgrep, capturing file paths and line numbers. */
330
+ export interface GrepParseOutput extends Map<string, number[]> {
331
+ searchHits?: Map<string, SearchHit[]>;
332
+ }
333
+
334
+ /**
335
+ * Parse stdout from grep / ripgrep, capturing file paths, emitted line numbers, and search hits.
336
+ */
311
337
  export function parseGrepOutput(
312
338
  outputText: string,
313
339
  candidateFiles: string[],
314
340
  cwd = process.cwd(),
315
- ): Map<string, number[]> {
341
+ ): GrepParseOutput {
316
342
  const fileLinesMap = new Map<string, Set<number>>();
317
- if (!outputText || typeof outputText !== "string") return new Map();
343
+ const searchHitsMap = new Map<string, SearchHit[]>();
344
+ if (!outputText || typeof outputText !== "string") {
345
+ const empty: GrepParseOutput = new Map();
346
+ empty.searchHits = searchHitsMap;
347
+ return empty;
348
+ }
318
349
 
319
350
  const normalizedCandidates = new Map<string, string>();
320
351
  for (const cand of candidateFiles) {
@@ -327,24 +358,46 @@ export function parseGrepOutput(
327
358
 
328
359
  const lines = outputText.split(/\r?\n/);
329
360
  for (const line of lines) {
330
- const trimmed = line.trim();
331
- if (!trimmed) continue;
361
+ const cleanLine = line.replace(/\x1b\[[0-9;]*m/g, "").trim();
362
+ if (!cleanLine || cleanLine === "--" || cleanLine.startsWith("--") && cleanLine.trim() === "--") continue;
332
363
 
333
- // 1. Single file: "123:code" or "123-context"
334
- const singleMatch = line.match(/^(\d+)[:-]/);
364
+ // 1. Single file: "123:code" (hit) or "123-context" (context)
365
+ const singleMatch = cleanLine.match(/^(\d+)([:-])(.*)$/);
335
366
  if (singleMatch && candidateFiles.length === 1) {
336
367
  const lineNum = parseInt(singleMatch[1], 10);
368
+ const isHit = singleMatch[2] === ":";
369
+ const text = singleMatch[3]?.trim();
337
370
  const targetPath = normalizedCandidates.get(candidateFiles[0]) || path.resolve(cwd, candidateFiles[0]);
338
371
  if (!fileLinesMap.has(targetPath)) fileLinesMap.set(targetPath, new Set());
339
372
  fileLinesMap.get(targetPath)!.add(lineNum);
373
+ if (isHit) {
374
+ if (!searchHitsMap.has(targetPath)) searchHitsMap.set(targetPath, []);
375
+ searchHitsMap.get(targetPath)!.push({ line: lineNum, text });
376
+ }
340
377
  continue;
341
378
  }
342
379
 
343
380
  // 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);
381
+ // Match lines: colons never appear inside path segments (except drive letter prefix).
382
+ const matchHit = cleanLine.match(
383
+ /^((?:[a-zA-Z]:[\\\/])?[^:\r\n]+):(\d+):(?:\d+:)?(.*)$/,
384
+ );
385
+ // Context lines: anchor extension to avoid splitting on "-<digits>-" in folder/file names.
386
+ const contextHit = !matchHit
387
+ ? cleanLine.match(
388
+ /^((?:[a-zA-Z]:[\\\/])?[^:\r\n]+?\.[a-zA-Z0-9_]+)-(\d+)-(.*)$/,
389
+ ) ||
390
+ cleanLine.match(
391
+ /^((?:[a-zA-Z]:[\\\/])?[^:\r\n]+?)-(\d+)-(.*)$/,
392
+ )
393
+ : null;
394
+
395
+ const parsedHit = matchHit || contextHit;
396
+ if (parsedHit) {
397
+ const rawPath = parsedHit[1].trim();
398
+ const lineNum = parseInt(parsedHit[2], 10);
399
+ const isHit = Boolean(matchHit);
400
+ const text = parsedHit[3]?.trim();
348
401
  let absPath =
349
402
  normalizedCandidates.get(rawPath) ||
350
403
  normalizedCandidates.get(path.resolve(cwd, rawPath)) ||
@@ -363,6 +416,10 @@ export function parseGrepOutput(
363
416
  if (absPath && Number.isFinite(lineNum) && lineNum >= 1) {
364
417
  if (!fileLinesMap.has(absPath)) fileLinesMap.set(absPath, new Set());
365
418
  fileLinesMap.get(absPath)!.add(lineNum);
419
+ if (isHit) {
420
+ if (!searchHitsMap.has(absPath)) searchHitsMap.set(absPath, []);
421
+ searchHitsMap.get(absPath)!.push({ line: lineNum, text });
422
+ }
366
423
  continue;
367
424
  }
368
425
  }
@@ -374,8 +431,8 @@ export function parseGrepOutput(
374
431
  // - Go / GCC: "main.go:12:3: error"
375
432
  // - C# / MSBuild: "file.cs(12,3): error"
376
433
  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)]|$)/);
434
+ cleanLine.match(/(?:-->|\s+at|\s+❯|File\s+["']?)\s*([^\s"(),]+\.[a-zA-Z0-9]+)(?:["']?)(?:[:(]|\s*,?\s*line\s+)(\d+)/i) ||
435
+ cleanLine.match(/(?:^|[\s(])([^\s()]+\.[a-zA-Z0-9]+)[:(](\d+)(?:[:,\s)]|$)/);
379
436
 
380
437
  if (traceMatch) {
381
438
  const rawPath = traceMatch[1].trim();
@@ -403,14 +460,17 @@ export function parseGrepOutput(
403
460
  for (let i = Math.max(1, lineNum - 2); i <= lineNum + 2; i++) {
404
461
  fileLinesMap.get(absPath)!.add(i);
405
462
  }
463
+ if (!searchHitsMap.has(absPath)) searchHitsMap.set(absPath, []);
464
+ searchHitsMap.get(absPath)!.push({ line: lineNum });
406
465
  }
407
466
  }
408
467
  }
409
468
 
410
- const result = new Map<string, number[]>();
469
+ const result: GrepParseOutput = new Map<string, number[]>();
411
470
  for (const [file, set] of fileLinesMap.entries()) {
412
471
  result.set(file, Array.from(set).sort((a, b) => a - b));
413
472
  }
473
+ result.searchHits = searchHitsMap;
414
474
  return result;
415
475
  }
416
476
 
@@ -422,52 +482,68 @@ export function parsePagingAndDiffOutput(
422
482
  cwd = process.cwd(),
423
483
  ): Map<string, number[]> {
424
484
  const result = new Map<string, number[]>();
425
- if (candidateFiles.length === 0) return result;
485
+ if (candidateFiles.length === 0 || !outputText) return result;
426
486
 
427
487
  const targetPath = path.isAbsolute(candidateFiles[0])
428
488
  ? path.normalize(candidateFiles[0])
429
489
  : path.resolve(cwd, candidateFiles[0]);
430
490
 
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
- }
491
+ let sourceLines: string[];
492
+ try {
493
+ const sourceText = fs.readFileSync(targetPath, "utf8").replace(/\r\n/g, "\n");
494
+ sourceLines = sourceText.split("\n");
495
+ if (sourceText.endsWith("\n")) sourceLines.pop();
496
+ } catch {
497
+ return result;
438
498
  }
439
499
 
440
- // 1. head -n <N>
500
+ const outputLines = outputText.replace(/\r\n/g, "\n").split("\n");
501
+ if (outputLines.at(-1) === "") outputLines.pop();
502
+ if (outputLines.length === 0) return result;
503
+
504
+ const matchesRange = (start: number, end: number): boolean => {
505
+ if (
506
+ !Number.isSafeInteger(start) ||
507
+ !Number.isSafeInteger(end) ||
508
+ start < 1 ||
509
+ end < start ||
510
+ end > sourceLines.length
511
+ ) {
512
+ return false;
513
+ }
514
+ const expected = sourceLines.slice(start - 1, end);
515
+ return (
516
+ expected.length === outputLines.length &&
517
+ expected.every((line, index) => line === outputLines[index])
518
+ );
519
+ };
520
+
441
521
  const headMatch = command.match(/\bhead\b.*?-n\s*(\d+)/i);
442
522
  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);
523
+ const end = Math.min(parseInt(headMatch[1]!, 10), sourceLines.length);
524
+ if (end > 0 && matchesRange(1, end)) {
525
+ result.set(targetPath, Array.from({ length: end }, (_, index) => index + 1));
526
+ }
447
527
  return result;
448
528
  }
449
529
 
450
- // 2. tail -n <N>
451
530
  const tailMatch = command.match(/\btail\b.*?-n\s*(\d+)/i);
452
531
  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);
532
+ const count = Math.min(parseInt(tailMatch[1]!, 10), sourceLines.length);
533
+ const start = sourceLines.length - count + 1;
534
+ if (count > 0 && matchesRange(start, sourceLines.length)) {
535
+ result.set(targetPath, Array.from({ length: count }, (_, index) => start + index));
536
+ }
459
537
  return result;
460
538
  }
461
539
 
462
- // 3. sed -n '<start>,<end>p'
463
540
  const sedMatch = command.match(/\bsed\b.*?-n\s*['"]?(\d+),(\d+)p['"]?/i);
464
541
  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;
542
+ const start = parseInt(sedMatch[1]!, 10);
543
+ const end = parseInt(sedMatch[2]!, 10);
544
+ if (matchesRange(start, end)) {
545
+ result.set(targetPath, Array.from({ length: end - start + 1 }, (_, index) => start + index));
546
+ }
471
547
  }
472
548
 
473
549
  return result;
@@ -487,6 +563,116 @@ function coversRanges(
487
563
  );
488
564
  }
489
565
 
566
+ export function getInspectionStateFilePath(sessionId: string, cwd = process.cwd()): string {
567
+ const safeSessionId = crypto.createHash("sha256").update(sessionId).digest("hex").slice(0, 24);
568
+ const canonicalWorkspace = fs.existsSync(cwd) ? fs.realpathSync(cwd) : path.resolve(cwd);
569
+ const workspaceId = crypto
570
+ .createHash("sha256")
571
+ .update(process.platform === "win32" ? canonicalWorkspace.toLowerCase() : canonicalWorkspace)
572
+ .digest("hex")
573
+ .slice(0, 24);
574
+ const baseDir = path.join(getPiHomeDir(), "cache", "agent-kernel", "sessions", workspaceId, safeSessionId);
575
+ return path.join(baseDir, "inspection-state.json");
576
+ }
577
+
578
+ export function saveSessionInspectionState(
579
+ sessionId: string,
580
+ evidenceMap: Map<string, InspectionEvidence>,
581
+ cwd = process.cwd(),
582
+ ): void {
583
+ if (!sessionId || evidenceMap.size === 0) return;
584
+ try {
585
+ const filePath = getInspectionStateFilePath(sessionId, cwd);
586
+ const dir = path.dirname(filePath);
587
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
588
+
589
+ const canonicalWorkspace = fs.existsSync(cwd) ? fs.realpathSync(cwd) : path.resolve(cwd);
590
+ const records: Record<string, any> = {};
591
+ for (const [absPath, ev] of evidenceMap.entries()) {
592
+ const rel = path.relative(canonicalWorkspace, absPath).replace(/\\/g, "/");
593
+ if (rel.startsWith("..") || path.isAbsolute(rel)) continue;
594
+ records[rel] = {
595
+ kind: ev.kind,
596
+ fingerprint: ev.fingerprint,
597
+ coverage: ev.coverage,
598
+ provenance: ev.provenance,
599
+ query: ev.query,
600
+ searchHits: ev.searchHits?.map((h) => ({ line: h.line })),
601
+ };
602
+ }
603
+
604
+ const tmpPath = `${filePath}.${crypto.randomBytes(4).toString("hex")}.tmp`;
605
+ fs.writeFileSync(
606
+ tmpPath,
607
+ JSON.stringify({ version: 1, workspace: canonicalWorkspace, records }, null, 2),
608
+ { encoding: "utf8", mode: 0o600 },
609
+ );
610
+ fs.renameSync(tmpPath, filePath);
611
+ } catch (err) {
612
+ kernelDebug(err);
613
+ }
614
+ }
615
+
616
+ export function loadSessionInspectionState(
617
+ sessionId: string,
618
+ cwd = process.cwd(),
619
+ ): Map<string, InspectionEvidence> {
620
+ const result = new Map<string, InspectionEvidence>();
621
+ if (!sessionId) return result;
622
+ try {
623
+ const filePath = getInspectionStateFilePath(sessionId, cwd);
624
+ if (!fs.existsSync(filePath)) return result;
625
+ const stat = fs.statSync(filePath);
626
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return result;
627
+
628
+ const raw = fs.readFileSync(filePath, "utf8");
629
+ let data: any;
630
+ try {
631
+ data = JSON.parse(raw);
632
+ } catch {
633
+ return result;
634
+ }
635
+ if (!data || data.version !== 1 || !data.records || typeof data.records !== "object") return result;
636
+
637
+ const canonicalWorkspace = fs.existsSync(cwd) ? fs.realpathSync(cwd) : path.resolve(cwd);
638
+ for (const [relPath, rec] of Object.entries(data.records as Record<string, any>)) {
639
+ if (!relPath || typeof relPath !== "string" || relPath.includes("\0")) continue;
640
+ const absPath = path.resolve(canonicalWorkspace, relPath);
641
+ const relCheck = path.relative(canonicalWorkspace, absPath).replace(/\\/g, "/");
642
+ if (relCheck.startsWith("..") || path.isAbsolute(relCheck)) continue;
643
+
644
+ if (!fs.existsSync(absPath) || !fs.statSync(absPath).isFile()) continue;
645
+ // Ensure symlinks pointing outside workspace root are rejected
646
+ const canonicalFile = fs.realpathSync(absPath);
647
+ const realRelCheck = path.relative(canonicalWorkspace, canonicalFile).replace(/\\/g, "/");
648
+ if (realRelCheck.startsWith("..") || path.isAbsolute(realRelCheck)) continue;
649
+
650
+ const content = fs.readFileSync(absPath);
651
+ const currentFingerprint = crypto.createHash("sha256").update(content).digest("hex");
652
+ if (currentFingerprint !== rec.fingerprint) continue;
653
+
654
+ const normalized = process.platform === "win32" ? absPath.toLowerCase() : absPath;
655
+ const hits = Array.isArray(rec.searchHits)
656
+ ? rec.searchHits
657
+ .filter((h: any) => h && typeof h.line === "number" && Number.isFinite(h.line) && h.line >= 1)
658
+ .map((h: any) => ({ line: Math.floor(h.line) }))
659
+ : undefined;
660
+
661
+ result.set(normalized, {
662
+ kind: rec.kind === "read" ? "read" : "search",
663
+ fingerprint: rec.fingerprint,
664
+ coverage: normalizeCoverage(rec.coverage),
665
+ provenance: rec.provenance || "read",
666
+ query: rec.query,
667
+ searchHits: hits,
668
+ });
669
+ }
670
+ } catch (err) {
671
+ kernelDebug(err);
672
+ }
673
+ return result;
674
+ }
675
+
490
676
  export class EpistemicGuard {
491
677
  private inspectedFilesBySession: Map<string, Map<string, InspectionEvidence>> =
492
678
  new Map();
@@ -589,12 +775,20 @@ export class EpistemicGuard {
589
775
  );
590
776
  }
591
777
 
778
+ private persistSessionState(sessionId: string, cwd = process.cwd()): void {
779
+ const evidence = this.inspectedFilesBySession.get(sessionId);
780
+ if (evidence) {
781
+ saveSessionInspectionState(sessionId, evidence, cwd);
782
+ }
783
+ }
784
+
592
785
  private getSessionEvidence(
593
786
  sessionId: string,
787
+ cwd = process.cwd(),
594
788
  ): Map<string, InspectionEvidence> {
595
789
  let evidence = this.inspectedFilesBySession.get(sessionId);
596
790
  if (!evidence) {
597
- evidence = new Map();
791
+ evidence = loadSessionInspectionState(sessionId, cwd);
598
792
  this.inspectedFilesBySession.set(sessionId, evidence);
599
793
  }
600
794
  return evidence;
@@ -613,7 +807,7 @@ export class EpistemicGuard {
613
807
  if (!fingerprint) return;
614
808
  const normalized = this.normalize(filePath, cwd);
615
809
  const coverage = normalizeCoverage(options.coverage);
616
- const evidence = this.getSessionEvidence(sessionId);
810
+ const evidence = this.getSessionEvidence(sessionId, cwd);
617
811
  const previous = evidence.get(normalized);
618
812
  evidence.set(
619
813
  normalized,
@@ -623,14 +817,17 @@ export class EpistemicGuard {
623
817
  fingerprint,
624
818
  coverage: { complete: false, ranges: [] },
625
819
  provenance: options.provenance || "read",
820
+ searchHits: options.searchHits,
626
821
  },
627
822
  fingerprint,
628
823
  "read",
629
824
  coverage,
630
825
  options.provenance || "read",
631
826
  options.query,
827
+ options.searchHits,
632
828
  ),
633
829
  );
830
+ this.persistSessionState(sessionId, cwd);
634
831
  }
635
832
 
636
833
  /**
@@ -653,7 +850,7 @@ export class EpistemicGuard {
653
850
  const fingerprint = this.fingerprint(filePath, cwd, content);
654
851
  if (!fingerprint) return;
655
852
  const normalized = this.normalize(filePath, cwd);
656
- const evidence = this.getSessionEvidence(sessionId);
853
+ const evidence = this.getSessionEvidence(sessionId, cwd);
657
854
  const previous = evidence.get(normalized);
658
855
 
659
856
  const isComplete = options.complete ?? previous?.coverage?.complete ?? false;
@@ -695,6 +892,7 @@ export class EpistemicGuard {
695
892
  }),
696
893
  provenance: "edit",
697
894
  });
895
+ this.persistSessionState(sessionId, cwd);
698
896
  }
699
897
 
700
898
  /** Search results are weaker evidence and never authorize a mutation. */
@@ -707,7 +905,7 @@ export class EpistemicGuard {
707
905
  if (!filePath) return;
708
906
  const fingerprint = this.fingerprint(filePath, cwd);
709
907
  if (!fingerprint) return;
710
- const evidence = this.getSessionEvidence(sessionId);
908
+ const evidence = this.getSessionEvidence(sessionId, cwd);
711
909
  const normalized = this.normalize(filePath, cwd);
712
910
  const previous = evidence.get(normalized);
713
911
  if (previous?.kind === "read") return;
@@ -728,6 +926,7 @@ export class EpistemicGuard {
728
926
  options.query,
729
927
  ),
730
928
  );
929
+ this.persistSessionState(sessionId, cwd);
731
930
  }
732
931
 
733
932
  private recordShellEvidence(
@@ -767,7 +966,7 @@ export class EpistemicGuard {
767
966
  }
768
967
  }
769
968
 
770
- let parsed: Map<string, number[]>;
969
+ let parsed: GrepParseOutput;
771
970
  if (isPaging) {
772
971
  parsed = parsePagingAndDiffOutput(command, outputText, files, cwd);
773
972
  } else {
@@ -777,16 +976,18 @@ export class EpistemicGuard {
777
976
  for (const [filePath, lineNumbers] of parsed.entries()) {
778
977
  const ranges = linesToRanges(lineNumbers);
779
978
  if (ranges.length > 0) {
979
+ const hits = parsed.searchHits?.get(filePath);
780
980
  this.recordFileRead(filePath, sessionId, cwd, undefined, {
781
981
  coverage: { complete: false, ranges },
782
982
  provenance: "bash",
783
983
  query: command,
984
+ searchHits: hits,
784
985
  });
785
986
  }
786
987
  }
787
988
 
788
989
  for (const filePath of files) {
789
- const evidence = this.getSessionEvidence(sessionId).get(this.normalize(filePath, cwd));
990
+ const evidence = this.getSessionEvidence(sessionId, cwd).get(this.normalize(filePath, cwd));
790
991
  if (!evidence) {
791
992
  this.recordFileSearched(filePath, sessionId, cwd, {
792
993
  coverage: { complete: false, ranges: [] },
@@ -819,16 +1020,22 @@ export class EpistemicGuard {
819
1020
  outputText,
820
1021
  );
821
1022
  }
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
- });
1023
+ // Also scan outputText for polyglot compiler/test traces across the
1024
+ // workspace. Paging/search output already has stricter attribution above;
1025
+ // feeding it into the generic grep parser would let synthetic `1:line`
1026
+ // text manufacture read evidence.
1027
+ const isPagingOrSearchOutput = /\b(head|tail|sed|grep|rg)\b/i.test(command);
1028
+ if (!isPagingOrSearchOutput) {
1029
+ const traces = parseGrepOutput(outputText, files, cwd);
1030
+ for (const [filePath, lineNumbers] of traces.entries()) {
1031
+ const ranges = linesToRanges(lineNumbers);
1032
+ if (ranges.length > 0) {
1033
+ this.recordFileRead(filePath, sessionId, cwd, undefined, {
1034
+ coverage: { complete: false, ranges },
1035
+ provenance: "bash",
1036
+ query: command,
1037
+ });
1038
+ }
832
1039
  }
833
1040
  }
834
1041
  return files;
@@ -892,7 +1099,7 @@ export class EpistemicGuard {
892
1099
  if (!enforceInspection || !exists) return { allowed: true };
893
1100
 
894
1101
  const normalized = this.normalize(resolvedPath, workspace);
895
- const evidence = this.getSessionEvidence(sessionId).get(normalized);
1102
+ const evidence = this.getSessionEvidence(sessionId, workspace).get(normalized);
896
1103
  const relPath = (path.relative(workspace, resolvedPath) || filePath).replace(/\\/g, "/");
897
1104
 
898
1105
  // 1. Session inspection check
@@ -923,20 +1130,147 @@ export class EpistemicGuard {
923
1130
  return { allowed: true };
924
1131
  }
925
1132
 
926
- // 4. Edit operations: Dual-Tier Authorization
1133
+ // 4. Edit operations: Per-Block Hybrid Authorization
1134
+ // Each block in a multi-block edit must independently satisfy either:
1135
+ // - Tier 1: its resolved target range is covered by visible read evidence, OR
1136
+ // - Tier 2: its search block is substantive (>=2 lines and >=35 chars, or >=50 chars).
1137
+ if (targetRanges && targetRanges.length > 0 && searchBlocks && searchBlocks.length === targetRanges.length) {
1138
+ let allCoveredByRead = true;
1139
+ let failingBlockIndex = -1;
1140
+
1141
+ for (let i = 0; i < targetRanges.length; i++) {
1142
+ const range = targetRanges[i];
1143
+ const sb = searchBlocks[i];
1144
+
1145
+ // Validate range integrity
1146
+ if (
1147
+ !range ||
1148
+ !Number.isFinite(range.startLine) ||
1149
+ !Number.isFinite(range.endLine) ||
1150
+ range.startLine < 1 ||
1151
+ range.endLine < range.startLine ||
1152
+ (evidence.coverage.totalLines !== undefined && range.endLine > evidence.coverage.totalLines)
1153
+ ) {
1154
+ return {
1155
+ allowed: false,
1156
+ reason: `[BLOCKED: Malformed or out-of-bounds target range in block ${i + 1}/${targetRanges.length} -> read({ path: "${relPath}" })]`,
1157
+ };
1158
+ }
1159
+
1160
+ if (!sb || typeof sb !== "string" || sb.trim().length === 0) {
1161
+ return {
1162
+ allowed: false,
1163
+ reason: `[BLOCKED: Empty search block in block ${i + 1}/${targetRanges.length} -> read({ path: "${relPath}" })]`,
1164
+ };
1165
+ }
1166
+
1167
+ const isCovered = coversRanges(evidence.coverage, [range]);
1168
+ let isAuthorized = isCovered;
1169
+
1170
+ // Tier 1.5: Verified Search Overlap
1171
+ if (!isAuthorized && evidence.searchHits && evidence.searchHits.length > 0) {
1172
+ const overlappingHit = evidence.searchHits.find(
1173
+ (h) => h.line >= range.startLine && h.line <= range.endLine,
1174
+ );
1175
+ if (overlappingHit) {
1176
+ const linesBefore = overlappingHit.line - range.startLine;
1177
+ const linesAfter = range.endLine - overlappingHit.line;
1178
+ const totalLines = range.endLine - range.startLine + 1;
1179
+ if (linesBefore <= 3 && linesAfter <= 3 && totalLines <= 10) {
1180
+ isAuthorized = true;
1181
+ }
1182
+ }
1183
+ }
1184
+
1185
+ // Bounded Micro-Hydration for adjacent edits (within 2 lines of an observed search hit)
1186
+ if (!isAuthorized && evidence.searchHits && evidence.searchHits.length > 0) {
1187
+ const adjacentHit = evidence.searchHits.find(
1188
+ (h) =>
1189
+ Math.abs(range.startLine - h.line) <= 2 ||
1190
+ Math.abs(range.endLine - h.line) <= 2,
1191
+ );
1192
+ const totalLines = range.endLine - range.startLine + 1;
1193
+ if (adjacentHit && totalLines <= 5) {
1194
+ try {
1195
+ evidence.coverage = mergeCoverage(evidence.coverage, {
1196
+ complete: false,
1197
+ ranges: [range],
1198
+ });
1199
+ isAuthorized = true;
1200
+ } catch {}
1201
+ }
1202
+ }
1203
+
1204
+ if (!isAuthorized) {
1205
+ allCoveredByRead = false;
1206
+ const contentLines = sb.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim().length > 0);
1207
+ const totalSubstantiveChars = contentLines.reduce((sum, line) => sum + line.trim().length, 0);
1208
+ const isSubstantive = contentLines.length >= 2 && totalSubstantiveChars >= 35;
1209
+ if (!isSubstantive) {
1210
+ failingBlockIndex = i;
1211
+ break;
1212
+ }
1213
+ }
1214
+ }
1215
+
1216
+ if (failingBlockIndex === -1) {
1217
+ return { allowed: true, tier: allCoveredByRead ? 1 : 2 };
1218
+ }
1219
+
1220
+ const failRange = targetRanges[failingBlockIndex];
1221
+ const maxAvailable = evidence.coverage.totalLines !== undefined
1222
+ ? Math.max(1, evidence.coverage.totalLines - failRange.startLine + 1)
1223
+ : Math.max(15, failRange.endLine - failRange.startLine + 5);
1224
+ const hintLimit = Math.min(Math.max(15, failRange.endLine - failRange.startLine + 5), maxAvailable);
1225
+ return {
1226
+ allowed: false,
1227
+ reason: `[BLOCKED: Target lines not covered by visible read and search block is non-substantive (<2 lines / <35 chars) -> read({ path: "${relPath}", offset: ${failRange.startLine}, limit: ${hintLimit} })]`,
1228
+ };
1229
+ }
1230
+
927
1231
  // Tier 1: Strict range coverage
928
1232
  if (evidence.kind === "read" && coversRanges(evidence.coverage, targetRanges)) {
929
1233
  return { allowed: true, tier: 1 };
930
1234
  }
931
1235
 
1236
+ // Tier 1.5: Verified Search Overlap on single range
1237
+ if (
1238
+ evidence.kind === "read" &&
1239
+ targetRanges.length === 1 &&
1240
+ evidence.searchHits &&
1241
+ evidence.searchHits.length > 0
1242
+ ) {
1243
+ const range = targetRanges[0];
1244
+ const overlappingHit = evidence.searchHits.find(
1245
+ (h) => h.line >= range.startLine && h.line <= range.endLine,
1246
+ );
1247
+ if (overlappingHit) {
1248
+ const linesBefore = overlappingHit.line - range.startLine;
1249
+ const linesAfter = range.endLine - overlappingHit.line;
1250
+ const totalLines = range.endLine - range.startLine + 1;
1251
+ if (linesBefore <= 3 && linesAfter <= 3 && totalLines <= 10) {
1252
+ return { allowed: true, tier: 1 };
1253
+ }
1254
+ }
1255
+ }
1256
+
1257
+ // Search metadata is useful for navigation but never authorizes mutation,
1258
+ // regardless of how substantial the proposed replacement text is.
1259
+ if (evidence.kind !== "read") {
1260
+ return {
1261
+ allowed: false,
1262
+ reason: `[BLOCKED: Search metadata does not authorize edits -> read({ path: "${relPath}" })]`,
1263
+ };
1264
+ }
1265
+
932
1266
  // Tier 2: Substantive unique block authorization
933
1267
  // 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).
1268
+ // authorize if every search block is substantive (>=2 non-empty content lines and >=35 chars).
935
1269
  if (searchBlocks && searchBlocks.length > 0) {
936
1270
  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;
1271
+ const contentLines = sb.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim().length > 0);
1272
+ const totalSubstantiveChars = contentLines.reduce((sum, line) => sum + line.trim().length, 0);
1273
+ return contentLines.length >= 2 && totalSubstantiveChars >= 35;
940
1274
  });
941
1275
 
942
1276
  if (allSubstantive) {
@@ -961,7 +1295,37 @@ export class EpistemicGuard {
961
1295
  sessionId: string,
962
1296
  cwd = process.cwd(),
963
1297
  ): boolean {
964
- return this.getSessionEvidence(sessionId).has(this.normalize(filePath, cwd));
1298
+ return this.getSessionEvidence(sessionId, cwd).has(this.normalize(filePath, cwd));
1299
+ }
1300
+
1301
+ public restoreEvidence(
1302
+ filePath: string,
1303
+ sessionId: string,
1304
+ evidence: ContextEvidence | null,
1305
+ cwd = process.cwd(),
1306
+ ): void {
1307
+ const normalized = this.normalize(filePath, cwd);
1308
+ const sessionEvidence = this.inspectedFilesBySession.get(sessionId);
1309
+ if (!sessionEvidence) return;
1310
+ if (!evidence) {
1311
+ sessionEvidence.delete(normalized);
1312
+ return;
1313
+ }
1314
+ sessionEvidence.set(normalized, {
1315
+ kind: evidence.kind,
1316
+ fingerprint: evidence.snapshot,
1317
+ coverage: {
1318
+ complete: evidence.coverage.complete,
1319
+ ranges: evidence.coverage.ranges.map((range) => ({ ...range })),
1320
+ ...(evidence.coverage.totalLines === undefined
1321
+ ? {}
1322
+ : { totalLines: evidence.coverage.totalLines }),
1323
+ },
1324
+ provenance: evidence.provenance,
1325
+ ...(evidence.query === undefined ? {} : { query: evidence.query }),
1326
+ ...(evidence.searchHits ? { searchHits: [...evidence.searchHits] } : {}),
1327
+ });
1328
+ this.persistSessionState(sessionId, cwd);
965
1329
  }
966
1330
 
967
1331
  /** Return a stable, non-content ledger view for diagnostics and tests. */
@@ -971,7 +1335,7 @@ export class EpistemicGuard {
971
1335
  cwd = process.cwd(),
972
1336
  ): ContextEvidence | null {
973
1337
  const normalized = this.normalize(filePath, cwd);
974
- const evidence = this.getSessionEvidence(sessionId).get(normalized);
1338
+ const evidence = this.getSessionEvidence(sessionId, cwd).get(normalized);
975
1339
  if (!evidence) return null;
976
1340
  return {
977
1341
  sessionId,
@@ -987,17 +1351,26 @@ export class EpistemicGuard {
987
1351
  },
988
1352
  provenance: evidence.provenance,
989
1353
  ...(evidence.query === undefined ? {} : { query: evidence.query }),
1354
+ ...(evidence.searchHits ? { searchHits: [...evidence.searchHits] } : {}),
990
1355
  };
991
1356
  }
992
1357
 
993
- public getInspectedFiles(sessionId: string): string[] {
994
- return Array.from(this.getSessionEvidence(sessionId).keys());
1358
+ public getInspectedFiles(sessionId: string, cwd = process.cwd()): string[] {
1359
+ return Array.from(this.getSessionEvidence(sessionId, cwd).keys());
995
1360
  }
996
1361
 
997
1362
  public resetSession(sessionId: string): void {
998
1363
  this.inspectedFilesBySession.delete(sessionId);
999
1364
  }
1000
1365
 
1366
+ public purgeSession(sessionId: string, cwd = process.cwd()): void {
1367
+ this.inspectedFilesBySession.delete(sessionId);
1368
+ try {
1369
+ const filePath = getInspectionStateFilePath(sessionId, cwd);
1370
+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
1371
+ } catch {}
1372
+ }
1373
+
1001
1374
  public reset(): void {
1002
1375
  this.inspectedFilesBySession.clear();
1003
1376
  }