@floydous/pi-agent-kernel 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
@@ -0,0 +1,733 @@
1
+ /**
2
+ * Epistemic Read-Before-Write Guard
3
+ *
4
+ * Enforces the cognitive invariant that an agent must inspect and ground itself
5
+ * in real file contents before attempting to mutate code.
6
+ */
7
+
8
+ import * as crypto from "node:crypto";
9
+ import * as fs from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { kernelDebug } from "./kernel_debug";
13
+
14
+ /**
15
+ * Extract file paths used as inputs by known shell content-reader commands.
16
+ * This is command-shape evidence recorded during tool-call preflight; it does
17
+ * not claim that a shell command produced output or that the agent understood it.
18
+ */
19
+ const CONTENT_READING_COMMANDS = new Set([
20
+ "cat",
21
+ "head",
22
+ "tail",
23
+ "sed",
24
+ "awk",
25
+ "grep",
26
+ "rg",
27
+ "less",
28
+ "more",
29
+ ]);
30
+
31
+ const NON_CONTENT_SEARCH_FLAGS = new Set(["c", "l", "L", "q"]);
32
+
33
+ function commandName(token: string): string {
34
+ return path
35
+ .basename(token)
36
+ .toLowerCase()
37
+ .replace(/\.exe$/, "");
38
+ }
39
+
40
+ /** Resolve the path forms accepted by Pi's file tools, including ~ paths. */
41
+ export function resolveUserPath(
42
+ filePath: string,
43
+ cwd = process.cwd(),
44
+ ): string {
45
+ const normalized = filePath.trim();
46
+ const expanded =
47
+ normalized === "~"
48
+ ? os.homedir()
49
+ : normalized.startsWith("~/") || normalized.startsWith("~\\")
50
+ ? path.join(os.homedir(), normalized.slice(2))
51
+ : normalized;
52
+ return path.isAbsolute(expanded)
53
+ ? path.resolve(expanded)
54
+ : path.resolve(cwd, expanded);
55
+ }
56
+
57
+ export function extractInspectedFilesFromCommand(
58
+ command: string,
59
+ cwd: string = process.cwd(),
60
+ ): string[] {
61
+ if (!command || typeof command !== "string") return [];
62
+
63
+ const inspected: string[] = [];
64
+ const subCommands = command.split(/[|;&\n]+/);
65
+
66
+ for (const sub of subCommands) {
67
+ const trimmed = sub.trim();
68
+ if (!trimmed) continue;
69
+
70
+ const regex = /(?:[^\s"']+|"[^"]*"|'[^']*')+/g;
71
+ const tokens: string[] = [];
72
+ let match: RegExpExecArray | null;
73
+
74
+ while ((match = regex.exec(trimmed)) !== null) {
75
+ let token = match[0].trim();
76
+ if (
77
+ (token.startsWith('"') && token.endsWith('"')) ||
78
+ (token.startsWith("'") && token.endsWith("'"))
79
+ ) {
80
+ token = token.slice(1, -1);
81
+ }
82
+ if (token) tokens.push(token);
83
+ }
84
+
85
+ if (tokens.length === 0) continue;
86
+
87
+ const command = commandName(tokens[0]);
88
+ if (!CONTENT_READING_COMMANDS.has(command)) continue;
89
+
90
+ if (
91
+ (command === "grep" || command === "rg") &&
92
+ tokens.slice(1).some((token) => {
93
+ if (
94
+ token === "--count" ||
95
+ token === "--files-with-matches" ||
96
+ token === "--files-without-match" ||
97
+ token === "--quiet" ||
98
+ token === "--silent"
99
+ ) {
100
+ return true;
101
+ }
102
+ return (
103
+ token.startsWith("-") &&
104
+ !token.startsWith("--") &&
105
+ [...token.slice(1)].some((flag) => NON_CONTENT_SEARCH_FLAGS.has(flag))
106
+ );
107
+ })
108
+ ) {
109
+ continue;
110
+ }
111
+
112
+ const positional = tokens
113
+ .slice(1)
114
+ .filter(
115
+ (token) =>
116
+ !token.startsWith("-") && ![">", ">>", "<", "2>", "2>&1"].includes(token),
117
+ );
118
+ let candidates: string[];
119
+ if (command === "grep" || command === "rg" || command === "awk") {
120
+ candidates = positional.slice(1);
121
+ } else if (command === "sed") {
122
+ candidates = positional.slice(1);
123
+ } else {
124
+ candidates = positional;
125
+ }
126
+
127
+ for (const token of candidates) {
128
+ try {
129
+ const resolved = resolveUserPath(token, cwd);
130
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
131
+ inspected.push(resolved);
132
+ }
133
+ } catch (error) {
134
+ kernelDebug(error);
135
+ }
136
+ }
137
+ }
138
+
139
+ return Array.from(new Set(inspected));
140
+ }
141
+
142
+ export interface EvidenceRange {
143
+ /** Inclusive 1-based source line. */
144
+ startLine: number;
145
+ /** Inclusive 1-based source line. */
146
+ endLine: number;
147
+ }
148
+
149
+ export interface EvidenceCoverage {
150
+ /** True only when the model-visible result represented the complete file. */
151
+ complete: boolean;
152
+ ranges: EvidenceRange[];
153
+ totalLines?: number;
154
+ }
155
+
156
+ export type EvidenceProvenance =
157
+ | "read"
158
+ | "symbol"
159
+ | "search"
160
+ | "lsp"
161
+ | "bash"
162
+ | "ast_search"
163
+ | "code_search"
164
+ | "edit"
165
+ | "write";
166
+
167
+ export interface EvidenceOptions {
168
+ coverage?: EvidenceCoverage;
169
+ provenance?: EvidenceProvenance;
170
+ query?: string;
171
+ }
172
+
173
+ export interface ContextEvidence {
174
+ sessionId: string;
175
+ filePath: string;
176
+ kind: "read" | "search";
177
+ /** SHA-256 snapshot of the file version observed by the tool. */
178
+ snapshot: string;
179
+ coverage: EvidenceCoverage;
180
+ provenance: EvidenceProvenance;
181
+ query?: string;
182
+ }
183
+
184
+ interface InspectionEvidence {
185
+ kind: "read" | "search";
186
+ fingerprint: string;
187
+ coverage: EvidenceCoverage;
188
+ provenance: EvidenceProvenance;
189
+ query?: string;
190
+ }
191
+
192
+ function normalizeRanges(
193
+ ranges: EvidenceRange[],
194
+ totalLines?: number,
195
+ ): EvidenceRange[] {
196
+ const valid = ranges
197
+ .filter(
198
+ (range) =>
199
+ Number.isFinite(range.startLine) &&
200
+ Number.isFinite(range.endLine) &&
201
+ range.startLine >= 1 &&
202
+ range.endLine >= range.startLine,
203
+ )
204
+ .map((range) => ({
205
+ startLine: Math.floor(range.startLine),
206
+ endLine: Math.floor(
207
+ totalLines === undefined
208
+ ? range.endLine
209
+ : Math.min(range.endLine, totalLines),
210
+ ),
211
+ }))
212
+ .filter((range) => range.endLine >= range.startLine)
213
+ .sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine);
214
+
215
+ const merged: EvidenceRange[] = [];
216
+ for (const range of valid) {
217
+ const previous = merged[merged.length - 1];
218
+ if (previous && range.startLine <= previous.endLine + 1) {
219
+ previous.endLine = Math.max(previous.endLine, range.endLine);
220
+ } else {
221
+ merged.push({ ...range });
222
+ }
223
+ }
224
+ return merged;
225
+ }
226
+
227
+ function normalizeCoverage(coverage?: EvidenceCoverage): EvidenceCoverage {
228
+ const totalLines =
229
+ coverage?.totalLines === undefined
230
+ ? undefined
231
+ : Math.max(0, Math.floor(coverage.totalLines));
232
+ return {
233
+ complete: coverage?.complete ?? true,
234
+ ranges: normalizeRanges(coverage?.ranges || [], totalLines),
235
+ ...(totalLines === undefined ? {} : { totalLines }),
236
+ };
237
+ }
238
+
239
+ function mergeCoverage(
240
+ first: EvidenceCoverage,
241
+ second: EvidenceCoverage,
242
+ ): EvidenceCoverage {
243
+ const totalLines = second.totalLines ?? first.totalLines;
244
+ const complete = first.complete || second.complete;
245
+ return {
246
+ complete,
247
+ ranges: normalizeRanges(
248
+ [...first.ranges, ...second.ranges],
249
+ totalLines,
250
+ ),
251
+ ...(totalLines === undefined ? {} : { totalLines }),
252
+ };
253
+ }
254
+
255
+ function mergeEvidence(
256
+ previous: InspectionEvidence,
257
+ fingerprint: string,
258
+ kind: "read" | "search",
259
+ coverage: EvidenceCoverage,
260
+ provenance: EvidenceProvenance,
261
+ query?: string,
262
+ ): InspectionEvidence {
263
+ if (previous.fingerprint !== fingerprint || previous.kind !== kind) {
264
+ return {
265
+ kind,
266
+ fingerprint,
267
+ coverage,
268
+ provenance,
269
+ ...(query === undefined ? {} : { query }),
270
+ };
271
+ }
272
+ return {
273
+ ...previous,
274
+ coverage: mergeCoverage(previous.coverage, coverage),
275
+ provenance,
276
+ ...(query === undefined ? {} : { query }),
277
+ };
278
+ }
279
+
280
+ function coversRanges(
281
+ coverage: EvidenceCoverage,
282
+ targetRanges: EvidenceRange[],
283
+ ): boolean {
284
+ if (coverage.complete) return true;
285
+ const normalizedTargets = normalizeRanges(targetRanges, coverage.totalLines);
286
+ return normalizedTargets.length > 0 && normalizedTargets.every((target) =>
287
+ coverage.ranges.some(
288
+ (range) =>
289
+ range.startLine <= target.startLine && range.endLine >= target.endLine,
290
+ ),
291
+ );
292
+ }
293
+
294
+ export class EpistemicGuard {
295
+ private inspectedFilesBySession: Map<string, Map<string, InspectionEvidence>> =
296
+ new Map();
297
+
298
+ private resolvePath(filePath: string, cwd = process.cwd()): string {
299
+ return resolveUserPath(filePath, cwd);
300
+ }
301
+
302
+ /**
303
+ * Resolve existing symlinks while retaining missing path segments. Broken
304
+ * symlinks throw so callers can fail closed instead of writing through one.
305
+ */
306
+ private canonicalPath(resolvedPath: string): string {
307
+ const missing: string[] = [];
308
+ let current = path.normalize(resolvedPath);
309
+
310
+ while (!fs.existsSync(current)) {
311
+ try {
312
+ if (fs.lstatSync(current).isSymbolicLink()) {
313
+ throw new Error(`Broken symbolic link: ${current}`);
314
+ }
315
+ } catch (error: any) {
316
+ if (error?.code !== "ENOENT") throw error;
317
+ }
318
+
319
+ const parent = path.dirname(current);
320
+ if (parent === current) return path.normalize(resolvedPath);
321
+ missing.unshift(path.basename(current));
322
+ current = parent;
323
+ }
324
+
325
+ return path.join(fs.realpathSync(current), ...missing);
326
+ }
327
+
328
+ /** Normalize a path for tracking across relative/absolute and symlink forms. */
329
+ private normalize(filePath: string, cwd = process.cwd()): string {
330
+ const isWindows = process.platform === "win32";
331
+ try {
332
+ const normalized = path.normalize(
333
+ this.canonicalPath(this.resolvePath(filePath, cwd)),
334
+ );
335
+ return isWindows ? normalized.toLowerCase() : normalized;
336
+ } catch {
337
+ const normalized = path.normalize(this.resolvePath(filePath, cwd));
338
+ return isWindows ? normalized.toLowerCase() : normalized;
339
+ }
340
+ }
341
+
342
+ private fingerprint(
343
+ filePath: string,
344
+ cwd = process.cwd(),
345
+ content?: string | Buffer,
346
+ ): string | null {
347
+ try {
348
+ const resolved = this.resolvePath(filePath, cwd);
349
+ if (content === undefined) {
350
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
351
+ return null;
352
+ }
353
+ content = fs.readFileSync(resolved);
354
+ }
355
+ return crypto.createHash("sha256").update(content).digest("hex");
356
+ } catch {
357
+ return null;
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Enforce workspace containment, including symlink resolution. This check is
363
+ * independent of the optional inspection setting.
364
+ */
365
+ private isWithinRoot(filePath: string, rootPath: string): boolean {
366
+ try {
367
+ const isWindows = process.platform === "win32";
368
+ const root = path.normalize(this.canonicalPath(path.resolve(rootPath)));
369
+ const target = path.normalize(
370
+ this.canonicalPath(this.resolvePath(filePath, rootPath)),
371
+ );
372
+ const normalizedRoot = isWindows ? root.toLowerCase() : root;
373
+ const normalizedTarget = isWindows ? target.toLowerCase() : target;
374
+ const relative = path.relative(normalizedRoot, normalizedTarget);
375
+ return (
376
+ relative === "" ||
377
+ (!relative.startsWith(`..${path.sep}`) &&
378
+ relative !== ".." &&
379
+ !path.isAbsolute(relative))
380
+ );
381
+ } catch {
382
+ return false;
383
+ }
384
+ }
385
+
386
+ private isWithinWorkspace(filePath: string, cwd: string): boolean {
387
+ // The OS temp directory is the narrow, disposable scratch area allowed for
388
+ // measurements and generated intermediates. Existing files there still pass
389
+ // through the normal read-before-write and freshness checks below.
390
+ return (
391
+ this.isWithinRoot(filePath, cwd) ||
392
+ this.isWithinRoot(filePath, os.tmpdir())
393
+ );
394
+ }
395
+
396
+ private getSessionEvidence(
397
+ sessionId: string,
398
+ ): Map<string, InspectionEvidence> {
399
+ let evidence = this.inspectedFilesBySession.get(sessionId);
400
+ if (!evidence) {
401
+ evidence = new Map();
402
+ this.inspectedFilesBySession.set(sessionId, evidence);
403
+ }
404
+ return evidence;
405
+ }
406
+
407
+ /** Record a successful file read together with its observed content hash. */
408
+ public recordFileRead(
409
+ filePath: string,
410
+ sessionId: string,
411
+ cwd = process.cwd(),
412
+ content?: string | Buffer,
413
+ options: EvidenceOptions = {},
414
+ ): void {
415
+ if (!filePath) return;
416
+ const fingerprint = this.fingerprint(filePath, cwd, content);
417
+ if (!fingerprint) return;
418
+ const normalized = this.normalize(filePath, cwd);
419
+ const coverage = normalizeCoverage(options.coverage);
420
+ const evidence = this.getSessionEvidence(sessionId);
421
+ const previous = evidence.get(normalized);
422
+ evidence.set(
423
+ normalized,
424
+ mergeEvidence(
425
+ previous || {
426
+ kind: "read",
427
+ fingerprint,
428
+ coverage: { complete: false, ranges: [] },
429
+ provenance: options.provenance || "read",
430
+ },
431
+ fingerprint,
432
+ "read",
433
+ coverage,
434
+ options.provenance || "read",
435
+ options.query,
436
+ ),
437
+ );
438
+ }
439
+
440
+ /**
441
+ * Record a successful mutation performed by the session itself (e.g. through `edit` or `write`).
442
+ * Refreshes the session's fingerprint against the mutated file content on disk so sequential
443
+ * edits do not trigger spurious drift rejections, while adjusting or preserving coverage.
444
+ */
445
+ public recordFileMutation(
446
+ filePath: string,
447
+ sessionId: string,
448
+ cwd = process.cwd(),
449
+ content?: string | Buffer,
450
+ options: {
451
+ complete?: boolean;
452
+ targetRanges?: EvidenceRange[];
453
+ deltaLines?: number;
454
+ } = {},
455
+ ): void {
456
+ if (!filePath) return;
457
+ const fingerprint = this.fingerprint(filePath, cwd, content);
458
+ if (!fingerprint) return;
459
+ const normalized = this.normalize(filePath, cwd);
460
+ const evidence = this.getSessionEvidence(sessionId);
461
+ const previous = evidence.get(normalized);
462
+
463
+ const isComplete = options.complete ?? previous?.coverage?.complete ?? false;
464
+ let updatedRanges = previous?.coverage?.ranges ? [...previous.coverage.ranges] : [];
465
+ const deltaLines = options.deltaLines ?? 0;
466
+
467
+ if (!isComplete && deltaLines !== 0 && options.targetRanges && options.targetRanges.length > 0) {
468
+ const maxEditEnd = Math.max(...options.targetRanges.map((r) => r.endLine));
469
+ updatedRanges = updatedRanges.map((r) => {
470
+ if (r.startLine > maxEditEnd) {
471
+ return {
472
+ startLine: r.startLine + deltaLines,
473
+ endLine: r.endLine + deltaLines,
474
+ };
475
+ }
476
+ return r;
477
+ });
478
+ }
479
+
480
+ let totalLines: number | undefined;
481
+ if (content !== undefined) {
482
+ totalLines =
483
+ typeof content === "string"
484
+ ? content.split("\n").length
485
+ : content.toString("utf8").split("\n").length;
486
+ }
487
+
488
+ evidence.set(normalized, {
489
+ kind: "read",
490
+ fingerprint,
491
+ coverage: normalizeCoverage({
492
+ complete: isComplete,
493
+ ranges: isComplete ? [] : updatedRanges,
494
+ ...(totalLines !== undefined
495
+ ? { totalLines }
496
+ : previous?.coverage?.totalLines !== undefined
497
+ ? { totalLines: previous.coverage.totalLines + deltaLines }
498
+ : {}),
499
+ }),
500
+ provenance: "edit",
501
+ });
502
+ }
503
+
504
+ /** Search results are weaker evidence and never authorize a mutation. */
505
+ public recordFileSearched(
506
+ filePath: string,
507
+ sessionId: string,
508
+ cwd = process.cwd(),
509
+ options: EvidenceOptions = {},
510
+ ): void {
511
+ if (!filePath) return;
512
+ const fingerprint = this.fingerprint(filePath, cwd);
513
+ if (!fingerprint) return;
514
+ const evidence = this.getSessionEvidence(sessionId);
515
+ const normalized = this.normalize(filePath, cwd);
516
+ const previous = evidence.get(normalized);
517
+ if (previous?.kind === "read") return;
518
+ const provenance = options.provenance || "search";
519
+ evidence.set(
520
+ normalized,
521
+ mergeEvidence(
522
+ previous || {
523
+ kind: "search",
524
+ fingerprint,
525
+ coverage: { complete: false, ranges: [] },
526
+ provenance,
527
+ },
528
+ fingerprint,
529
+ "search",
530
+ normalizeCoverage(options.coverage ?? { complete: false, ranges: [] }),
531
+ provenance,
532
+ options.query,
533
+ ),
534
+ );
535
+ }
536
+
537
+ private recordShellEvidence(
538
+ command: string,
539
+ cwd: string,
540
+ sessionId: string,
541
+ files: string[],
542
+ outputComplete: boolean,
543
+ outputText = "",
544
+ ): void {
545
+ const isSearch = /^\s*(?:grep|rg)(?:\.exe)?(?:\s|$)/i.test(command);
546
+ const isPlainCat =
547
+ /^\s*cat(?:\.exe)?\s+[^|;&><]+$/i.test(command) &&
548
+ !/^\s*cat(?:\.exe)?\s+-/i.test(command);
549
+ for (const filePath of files) {
550
+ if (isSearch) {
551
+ this.recordFileSearched(filePath, sessionId, cwd, {
552
+ coverage: { complete: false, ranges: [] },
553
+ provenance: "bash",
554
+ query: command,
555
+ });
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
+ }
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
+ }
581
+ }
582
+
583
+ /** Record classified shell content-reader evidence after a successful result. */
584
+ public recordCommandExecution(
585
+ command: string,
586
+ cwd = process.cwd(),
587
+ sessionId: string,
588
+ outputComplete = true,
589
+ outputText = "",
590
+ ): string[] {
591
+ const files = extractInspectedFilesFromCommand(command, cwd);
592
+ const isCompound = /[|;&\n><]/.test(command);
593
+ for (const subCommand of command.split(/[|;&\n]+/)) {
594
+ const trimmed = subCommand.trim();
595
+ if (!trimmed) continue;
596
+ this.recordShellEvidence(
597
+ trimmed,
598
+ cwd,
599
+ sessionId,
600
+ extractInspectedFilesFromCommand(trimmed, cwd),
601
+ outputComplete && !isCompound,
602
+ outputText,
603
+ );
604
+ }
605
+ return files;
606
+ }
607
+
608
+ /**
609
+ * Check workspace containment and require a fresh native read before editing
610
+ * or overwriting an existing file when inspection enforcement is enabled.
611
+ * The workspace defaults to the current process directory when callers do
612
+ * not provide an explicit cwd.
613
+ */
614
+ public checkReadPrecondition(
615
+ filePath: string,
616
+ operation: "edit" | "write",
617
+ sessionId: string,
618
+ cwd?: string,
619
+ enforceInspection = true,
620
+ targetRanges: EvidenceRange[] = [],
621
+ ): { allowed: boolean; reason?: string } {
622
+ if (!filePath) {
623
+ return {
624
+ allowed: false,
625
+ reason: "[EPISTEMIC GUARD]: Invalid or empty file path.",
626
+ };
627
+ }
628
+
629
+ const workspace = cwd || process.cwd();
630
+ const resolvedPath = this.resolvePath(filePath, workspace);
631
+ if (cwd !== undefined && !this.isWithinWorkspace(resolvedPath, workspace)) {
632
+ return {
633
+ allowed: false,
634
+ reason: `[WORKSPACE BOUNDARY REJECTION]: Path '${filePath}' resolves outside the workspace '${workspace}'.`,
635
+ };
636
+ }
637
+
638
+ let exists = false;
639
+ try {
640
+ exists = fs.existsSync(resolvedPath);
641
+ if (exists && !fs.statSync(resolvedPath).isFile()) {
642
+ return {
643
+ allowed: false,
644
+ reason: `[EPISTEMIC GUARD]: Target '${filePath}' is not a regular file.`,
645
+ };
646
+ }
647
+ } catch (error) {
648
+ return {
649
+ allowed: false,
650
+ reason: `[EPISTEMIC GUARD]: Could not inspect target '${filePath}': ${error instanceof Error ? error.message : String(error)}`,
651
+ };
652
+ }
653
+
654
+ // A new file has no prior contents to inspect. Containment still applies.
655
+ if (!enforceInspection || !exists) return { allowed: true };
656
+
657
+ const normalized = this.normalize(resolvedPath, workspace);
658
+ const evidence = this.getSessionEvidence(sessionId).get(normalized);
659
+ const relPath = (path.relative(workspace, resolvedPath) || filePath).replace(/\\/g, "/");
660
+ if (!evidence || evidence.kind !== "read") {
661
+ return {
662
+ allowed: false,
663
+ reason: `[BLOCKED: Read before ${operation} -> read({ path: "${relPath}" })]`,
664
+ };
665
+ }
666
+
667
+ if (!coversRanges(evidence.coverage, targetRanges)) {
668
+ return {
669
+ allowed: false,
670
+ reason: `[BLOCKED: Target lines not covered by visible read -> read({ path: "${relPath}" })]`,
671
+ };
672
+ }
673
+
674
+ const currentFingerprint = this.fingerprint(resolvedPath, workspace);
675
+ if (!currentFingerprint || currentFingerprint !== evidence.fingerprint) {
676
+ return {
677
+ allowed: false,
678
+ reason: `[BLOCKED: File changed since read -> read({ path: "${relPath}" })]`,
679
+ };
680
+ }
681
+
682
+ return { allowed: true };
683
+ }
684
+
685
+ /** Check whether the current session has any inspection evidence for a file. */
686
+ public isFileInspected(
687
+ filePath: string,
688
+ sessionId: string,
689
+ cwd = process.cwd(),
690
+ ): boolean {
691
+ return this.getSessionEvidence(sessionId).has(this.normalize(filePath, cwd));
692
+ }
693
+
694
+ /** Return a stable, non-content ledger view for diagnostics and tests. */
695
+ public getEvidence(
696
+ filePath: string,
697
+ sessionId: string,
698
+ cwd = process.cwd(),
699
+ ): ContextEvidence | null {
700
+ const normalized = this.normalize(filePath, cwd);
701
+ const evidence = this.getSessionEvidence(sessionId).get(normalized);
702
+ if (!evidence) return null;
703
+ return {
704
+ sessionId,
705
+ filePath: normalized,
706
+ kind: evidence.kind,
707
+ snapshot: evidence.fingerprint,
708
+ coverage: {
709
+ complete: evidence.coverage.complete,
710
+ ranges: evidence.coverage.ranges.map((range) => ({ ...range })),
711
+ ...(evidence.coverage.totalLines === undefined
712
+ ? {}
713
+ : { totalLines: evidence.coverage.totalLines }),
714
+ },
715
+ provenance: evidence.provenance,
716
+ ...(evidence.query === undefined ? {} : { query: evidence.query }),
717
+ };
718
+ }
719
+
720
+ public getInspectedFiles(sessionId: string): string[] {
721
+ return Array.from(this.getSessionEvidence(sessionId).keys());
722
+ }
723
+
724
+ public resetSession(sessionId: string): void {
725
+ this.inspectedFilesBySession.delete(sessionId);
726
+ }
727
+
728
+ public reset(): void {
729
+ this.inspectedFilesBySession.clear();
730
+ }
731
+ }
732
+
733
+ export const globalEpistemicGuard = new EpistemicGuard();