@floydous/pi-agent-kernel 0.4.0 → 0.4.1

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.
@@ -1,26 +1,65 @@
1
1
  import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { randomBytes } from "node:crypto";
2
4
  import { kernelDebug } from "./kernel_debug";
3
5
 
6
+ function syncDirectory(directory: string): void {
7
+ if (process.platform === "win32") return;
8
+ try {
9
+ const fd = fs.openSync(directory, fs.constants.O_RDONLY);
10
+ try {
11
+ fs.fsyncSync(fd);
12
+ } finally {
13
+ fs.closeSync(fd);
14
+ }
15
+ } catch (error) {
16
+ // Directory fsync is not available on every filesystem; rename is still
17
+ // atomic, and the failure is intentionally non-fatal after the rename.
18
+ kernelDebug(error);
19
+ }
20
+ }
21
+
4
22
  /**
5
- * Write a file atomically: write to a sibling temp file, then rename over the
6
- * destination. A plain writeFileSync can leave a truncated/corrupt JSON store
7
- * behind if the process dies mid-write; with tmp+rename the destination either
8
- * holds the old complete file or the new complete file, never a partial one.
23
+ * Write a file through an exclusive sibling temp file, preserving metadata
24
+ * where the platform exposes it. A plain writeFileSync can leave a truncated
25
+ * destination after a crash; fsync + rename prevents that partial state.
9
26
  */
10
- export function writeFileSyncAtomic(
11
- filePath: string,
12
- data: string | Buffer,
13
- ): void {
14
- const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
15
- try {
16
- fs.writeFileSync(tmp, data);
17
- fs.renameSync(tmp, filePath);
18
- } catch (err) {
19
- try {
20
- fs.unlinkSync(tmp);
21
- } catch (cleanupErr) {
22
- kernelDebug(cleanupErr);
23
- }
24
- throw err;
25
- }
27
+ export function writeFileSyncAtomic(filePath: string, data: string | Buffer): void {
28
+ const target = path.resolve(filePath);
29
+ let targetStat: fs.Stats | undefined;
30
+ try {
31
+ targetStat = fs.lstatSync(target);
32
+ if (targetStat.isSymbolicLink()) {
33
+ throw new Error("Refusing to atomically replace a symbolic-link target");
34
+ }
35
+ } catch (error: any) {
36
+ if (error?.code !== "ENOENT") throw error;
37
+ }
38
+
39
+ const mode = targetStat ? (targetStat.mode & 0o7777) : 0o600;
40
+ const temp = `${target}.${process.pid}.${Date.now()}.${randomBytes(6).toString("hex")}.tmp`;
41
+ let fd: number | undefined;
42
+ try {
43
+ fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, mode);
44
+ fs.writeFileSync(fd, data);
45
+ fs.fsyncSync(fd);
46
+ fs.closeSync(fd);
47
+ fd = undefined;
48
+
49
+ if (targetStat && process.platform !== "win32") {
50
+ fs.chmodSync(temp, mode);
51
+ if (targetStat.uid !== process.getuid?.() || targetStat.gid !== process.getgid?.()) {
52
+ fs.chownSync(temp, targetStat.uid, targetStat.gid);
53
+ }
54
+ }
55
+
56
+ fs.renameSync(temp, target);
57
+ syncDirectory(path.dirname(target));
58
+ } catch (error) {
59
+ if (fd !== undefined) {
60
+ try { fs.closeSync(fd); } catch (closeError) { kernelDebug(closeError); }
61
+ }
62
+ try { fs.unlinkSync(temp); } catch (cleanupError) { kernelDebug(cleanupError); }
63
+ throw error;
64
+ }
26
65
  }
@@ -422,52 +422,68 @@ export function parsePagingAndDiffOutput(
422
422
  cwd = process.cwd(),
423
423
  ): Map<string, number[]> {
424
424
  const result = new Map<string, number[]>();
425
- if (candidateFiles.length === 0) return result;
425
+ if (candidateFiles.length === 0 || !outputText) return result;
426
426
 
427
427
  const targetPath = path.isAbsolute(candidateFiles[0])
428
428
  ? path.normalize(candidateFiles[0])
429
429
  : path.resolve(cwd, candidateFiles[0]);
430
430
 
431
- let totalLines = 0;
432
- if (fs.existsSync(targetPath)) {
433
- try {
434
- totalLines = fs.readFileSync(targetPath, "utf8").split(/\r?\n/).length;
435
- } catch {
436
- totalLines = 0;
437
- }
431
+ let sourceLines: string[];
432
+ try {
433
+ const sourceText = fs.readFileSync(targetPath, "utf8").replace(/\r\n/g, "\n");
434
+ sourceLines = sourceText.split("\n");
435
+ if (sourceText.endsWith("\n")) sourceLines.pop();
436
+ } catch {
437
+ return result;
438
438
  }
439
439
 
440
- // 1. head -n <N>
440
+ const outputLines = outputText.replace(/\r\n/g, "\n").split("\n");
441
+ if (outputLines.at(-1) === "") outputLines.pop();
442
+ if (outputLines.length === 0) return result;
443
+
444
+ const matchesRange = (start: number, end: number): boolean => {
445
+ if (
446
+ !Number.isSafeInteger(start) ||
447
+ !Number.isSafeInteger(end) ||
448
+ start < 1 ||
449
+ end < start ||
450
+ end > sourceLines.length
451
+ ) {
452
+ return false;
453
+ }
454
+ const expected = sourceLines.slice(start - 1, end);
455
+ return (
456
+ expected.length === outputLines.length &&
457
+ expected.every((line, index) => line === outputLines[index])
458
+ );
459
+ };
460
+
441
461
  const headMatch = command.match(/\bhead\b.*?-n\s*(\d+)/i);
442
462
  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);
463
+ const end = Math.min(parseInt(headMatch[1]!, 10), sourceLines.length);
464
+ if (end > 0 && matchesRange(1, end)) {
465
+ result.set(targetPath, Array.from({ length: end }, (_, index) => index + 1));
466
+ }
447
467
  return result;
448
468
  }
449
469
 
450
- // 2. tail -n <N>
451
470
  const tailMatch = command.match(/\btail\b.*?-n\s*(\d+)/i);
452
471
  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);
472
+ const count = Math.min(parseInt(tailMatch[1]!, 10), sourceLines.length);
473
+ const start = sourceLines.length - count + 1;
474
+ if (count > 0 && matchesRange(start, sourceLines.length)) {
475
+ result.set(targetPath, Array.from({ length: count }, (_, index) => start + index));
476
+ }
459
477
  return result;
460
478
  }
461
479
 
462
- // 3. sed -n '<start>,<end>p'
463
480
  const sedMatch = command.match(/\bsed\b.*?-n\s*['"]?(\d+),(\d+)p['"]?/i);
464
481
  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;
482
+ const start = parseInt(sedMatch[1]!, 10);
483
+ const end = parseInt(sedMatch[2]!, 10);
484
+ if (matchesRange(start, end)) {
485
+ result.set(targetPath, Array.from({ length: end - start + 1 }, (_, index) => start + index));
486
+ }
471
487
  }
472
488
 
473
489
  return result;
@@ -819,16 +835,22 @@ export class EpistemicGuard {
819
835
  outputText,
820
836
  );
821
837
  }
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
- });
838
+ // Also scan outputText for polyglot compiler/test traces across the
839
+ // workspace. Paging/search output already has stricter attribution above;
840
+ // feeding it into the generic grep parser would let synthetic `1:line`
841
+ // text manufacture read evidence.
842
+ const isPagingOrSearchOutput = /\b(head|tail|sed|grep|rg)\b/i.test(command);
843
+ if (!isPagingOrSearchOutput) {
844
+ const traces = parseGrepOutput(outputText, files, cwd);
845
+ for (const [filePath, lineNumbers] of traces.entries()) {
846
+ const ranges = linesToRanges(lineNumbers);
847
+ if (ranges.length > 0) {
848
+ this.recordFileRead(filePath, sessionId, cwd, undefined, {
849
+ coverage: { complete: false, ranges },
850
+ provenance: "bash",
851
+ query: command,
852
+ });
853
+ }
832
854
  }
833
855
  }
834
856
  return files;
@@ -923,20 +945,90 @@ export class EpistemicGuard {
923
945
  return { allowed: true };
924
946
  }
925
947
 
926
- // 4. Edit operations: Dual-Tier Authorization
948
+ // 4. Edit operations: Per-Block Hybrid Authorization
949
+ // Each block in a multi-block edit must independently satisfy either:
950
+ // - Tier 1: its resolved target range is covered by visible read evidence, OR
951
+ // - Tier 2: its search block is substantive (>=2 lines and >=35 chars, or >=50 chars).
952
+ if (targetRanges && targetRanges.length > 0 && searchBlocks && searchBlocks.length === targetRanges.length) {
953
+ let allCoveredByRead = true;
954
+ let failingBlockIndex = -1;
955
+
956
+ for (let i = 0; i < targetRanges.length; i++) {
957
+ const range = targetRanges[i];
958
+ const sb = searchBlocks[i];
959
+
960
+ // Validate range integrity
961
+ if (
962
+ !range ||
963
+ !Number.isFinite(range.startLine) ||
964
+ !Number.isFinite(range.endLine) ||
965
+ range.startLine < 1 ||
966
+ range.endLine < range.startLine ||
967
+ (evidence.coverage.totalLines !== undefined && range.endLine > evidence.coverage.totalLines)
968
+ ) {
969
+ return {
970
+ allowed: false,
971
+ reason: `[BLOCKED: Malformed or out-of-bounds target range in block ${i + 1}/${targetRanges.length} -> read({ path: "${relPath}" })]`,
972
+ };
973
+ }
974
+
975
+ if (!sb || typeof sb !== "string" || sb.trim().length === 0) {
976
+ return {
977
+ allowed: false,
978
+ reason: `[BLOCKED: Empty search block in block ${i + 1}/${targetRanges.length} -> read({ path: "${relPath}" })]`,
979
+ };
980
+ }
981
+
982
+ const isCovered = coversRanges(evidence.coverage, [range]);
983
+ if (!isCovered) {
984
+ allCoveredByRead = false;
985
+ const contentLines = sb.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim().length > 0);
986
+ const totalSubstantiveChars = contentLines.reduce((sum, line) => sum + line.trim().length, 0);
987
+ const isSubstantive = contentLines.length >= 2 && totalSubstantiveChars >= 35;
988
+ if (!isSubstantive) {
989
+ failingBlockIndex = i;
990
+ break;
991
+ }
992
+ }
993
+ }
994
+
995
+ if (failingBlockIndex === -1) {
996
+ return { allowed: true, tier: allCoveredByRead ? 1 : 2 };
997
+ }
998
+
999
+ const failRange = targetRanges[failingBlockIndex];
1000
+ const maxAvailable = evidence.coverage.totalLines !== undefined
1001
+ ? Math.max(1, evidence.coverage.totalLines - failRange.startLine + 1)
1002
+ : Math.max(15, failRange.endLine - failRange.startLine + 5);
1003
+ const hintLimit = Math.min(Math.max(15, failRange.endLine - failRange.startLine + 5), maxAvailable);
1004
+ return {
1005
+ allowed: false,
1006
+ 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} })]`,
1007
+ };
1008
+ }
1009
+
927
1010
  // Tier 1: Strict range coverage
928
1011
  if (evidence.kind === "read" && coversRanges(evidence.coverage, targetRanges)) {
929
1012
  return { allowed: true, tier: 1 };
930
1013
  }
931
1014
 
1015
+ // Search metadata is useful for navigation but never authorizes mutation,
1016
+ // regardless of how substantial the proposed replacement text is.
1017
+ if (evidence.kind !== "read") {
1018
+ return {
1019
+ allowed: false,
1020
+ reason: `[BLOCKED: Search metadata does not authorize edits -> read({ path: "${relPath}" })]`,
1021
+ };
1022
+ }
1023
+
932
1024
  // Tier 2: Substantive unique block authorization
933
1025
  // 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).
1026
+ // authorize if every search block is substantive (>=2 non-empty content lines and >=35 chars).
935
1027
  if (searchBlocks && searchBlocks.length > 0) {
936
1028
  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;
1029
+ const contentLines = sb.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim().length > 0);
1030
+ const totalSubstantiveChars = contentLines.reduce((sum, line) => sum + line.trim().length, 0);
1031
+ return contentLines.length >= 2 && totalSubstantiveChars >= 35;
940
1032
  });
941
1033
 
942
1034
  if (allSubstantive) {
@@ -964,6 +1056,34 @@ export class EpistemicGuard {
964
1056
  return this.getSessionEvidence(sessionId).has(this.normalize(filePath, cwd));
965
1057
  }
966
1058
 
1059
+ public restoreEvidence(
1060
+ filePath: string,
1061
+ sessionId: string,
1062
+ evidence: ContextEvidence | null,
1063
+ cwd = process.cwd(),
1064
+ ): void {
1065
+ const normalized = this.normalize(filePath, cwd);
1066
+ const sessionEvidence = this.inspectedFilesBySession.get(sessionId);
1067
+ if (!sessionEvidence) return;
1068
+ if (!evidence) {
1069
+ sessionEvidence.delete(normalized);
1070
+ return;
1071
+ }
1072
+ sessionEvidence.set(normalized, {
1073
+ kind: evidence.kind,
1074
+ fingerprint: evidence.snapshot,
1075
+ coverage: {
1076
+ complete: evidence.coverage.complete,
1077
+ ranges: evidence.coverage.ranges.map((range) => ({ ...range })),
1078
+ ...(evidence.coverage.totalLines === undefined
1079
+ ? {}
1080
+ : { totalLines: evidence.coverage.totalLines }),
1081
+ },
1082
+ provenance: evidence.provenance,
1083
+ ...(evidence.query === undefined ? {} : { query: evidence.query }),
1084
+ });
1085
+ }
1086
+
967
1087
  /** Return a stable, non-content ledger view for diagnostics and tests. */
968
1088
  public getEvidence(
969
1089
  filePath: string,