@criogaid/pi-hashline-edit 0.1.3 → 0.3.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 (44) hide show
  1. package/README.md +77 -23
  2. package/package.json +1 -1
  3. package/src/core/apply.test.ts +87 -10
  4. package/src/core/apply.ts +106 -84
  5. package/src/core/lines.test.ts +12 -1
  6. package/src/core/lines.ts +43 -1
  7. package/src/core/ranges.test.ts +28 -0
  8. package/src/core/ranges.ts +25 -0
  9. package/src/core/text.ts +5 -0
  10. package/src/core/types.ts +37 -20
  11. package/src/integration/grep-rg.test.ts +188 -1
  12. package/src/pi/action-fusion.test.ts +3 -1
  13. package/src/pi/action-fusion.ts +38 -35
  14. package/src/pi/anchor-format.test.ts +30 -0
  15. package/src/pi/anchor-format.ts +28 -0
  16. package/src/pi/config.ts +1 -1
  17. package/src/pi/edit-tool.ts +91 -100
  18. package/src/pi/execute.test.ts +239 -14
  19. package/src/pi/failure-context.test.ts +99 -62
  20. package/src/pi/failure-context.ts +67 -64
  21. package/src/pi/failure-path.test.ts +20 -2
  22. package/src/pi/file-commit.test.ts +21 -0
  23. package/src/pi/file-commit.ts +35 -3
  24. package/src/pi/fusion-card.test.ts +38 -1
  25. package/src/pi/fusion-card.ts +41 -17
  26. package/src/pi/grep-tool.ts +84 -55
  27. package/src/pi/grep.test.ts +77 -6
  28. package/src/pi/mutation-result.ts +48 -9
  29. package/src/pi/path.ts +22 -0
  30. package/src/pi/pi.test.ts +64 -2
  31. package/src/pi/read-tool.ts +9 -30
  32. package/src/pi/registration.test.ts +28 -1
  33. package/src/pi/render.test.ts +111 -0
  34. package/src/pi/render.ts +30 -6
  35. package/src/pi/replace-tool.ts +144 -140
  36. package/src/pi/replace.test.ts +193 -1
  37. package/src/pi/result-safety.test.ts +241 -8
  38. package/src/pi/rg-line-filter.test.ts +7 -1
  39. package/src/pi/rg-line-filter.ts +10 -12
  40. package/src/pi/rg-line-ranges.test.ts +10 -0
  41. package/src/pi/rg-line-ranges.ts +21 -15
  42. package/src/pi/rg-text-view.ts +88 -0
  43. package/src/pi/write-tool.ts +13 -47
  44. package/src/pi/write.test.ts +25 -36
@@ -2,87 +2,124 @@ import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
4
  import type { AnchorFailure } from "../core/types.ts";
5
- import { formatFailureContext } from "./failure-context.ts";
5
+ import { createAnchorFormatter } from "./anchor-format.ts";
6
+ import { formatAmbiguousCandidateNeighborhoods } from "./failure-context.ts";
6
7
 
7
- function unresolved(line: number): AnchorFailure {
8
- return {
9
- opIndex: 0,
10
- which: "anchor",
11
- op: "replace",
12
- cited: { line, hash: "OLD" },
13
- recovery: { kind: "none" },
14
- current: null,
15
- };
8
+ function failure(recovery: AnchorFailure["recovery"]): AnchorFailure {
9
+ return { opIndex: 0, which: "anchor", op: "replace", cited: { line: 1, hash: "OLD" }, recovery, current: null };
16
10
  }
17
11
 
18
- test("failure context is omitted when every anchor was recovered", () => {
19
- const found: AnchorFailure = { ...unresolved(2), recovery: { kind: "found", newLine: 3, newHash: "NEW" } };
20
- assert.equal(formatFailureContext("a\nb\nc\n", [found], 4), "");
12
+ function ambiguous(lines: readonly string[], positions: number[], hashLen = 4): AnchorFailure {
13
+ return failure({ kind: "ambiguous", scope: "local", candidates: positions.map(line => ({ line, hash: computeLineHash(line, lines[line - 1], hashLen) })) });
14
+ }
15
+
16
+ function format(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
17
+ return formatAmbiguousCandidateNeighborhoods(text, failures, createAnchorFormatter(hashLen));
18
+ }
19
+
20
+ test("unique and unresolved failures produce no neighborhoods", () => {
21
+ const failures = [failure({ kind: "found", scope: "local", newLine: 2, newHash: "NEW" }), failure({ kind: "none" })];
22
+ assert.deepEqual(format("a\nb\nc\n", failures), { text: "", shownLines: new Set() });
23
+ assert.deepEqual(format("", [failure({ kind: "none" })]), { text: "", shownLines: new Set() });
21
24
  });
22
25
 
23
- test("failure context merges adjacent windows and emits each anchored line once", () => {
24
- const lines = Array.from({ length: 14 }, (_, index) => `line ${index + 1}`);
25
- const result = formatFailureContext(`${lines.join("\n")}\n`, [unresolved(5), unresolved(9)], 4);
26
- assert.match(result, /@@ lines 2-12 @@/);
27
- assert.match(result, /Context rows: 11\/11; 0 omitted/);
28
- for (let line = 2; line <= 12; line++) {
29
- const row = `${line}#${computeLineHash(line, lines[line - 1])}│${lines[line - 1]}`;
26
+ test("ambiguous context merges and sorts windows with CRLF and BOM-aware anchors", () => {
27
+ const lines = ["\uFEFFfirst", "a", "", "c", "d", "e", "f", "last"];
28
+ const { text: result, shownLines } = format(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
29
+ assert.deepEqual([...shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
30
+ assert.match(result, /@@ candidate-neighborhood lines 1-8 @@/);
31
+ assert.match(result, /Ambiguous-candidate neighborhoods.*observation only/);
32
+ for (let line = 1; line <= lines.length; line++) {
33
+ const row = `${line}#${computeLineHash(line, lines[line - 1], 6)}│${lines[line - 1]}`;
30
34
  assert.equal(result.split(row).length - 1, 1);
31
35
  }
36
+ assert.doesNotMatch(result, /\r|omitted|truncated/);
32
37
  });
33
38
 
34
- test("failure context clamps BOF, EOF, and out-of-range anchors without padding", () => {
35
- const text = Array.from({ length: 10 }, (_, index) => `${index + 1}`).join("\n");
36
- const result = formatFailureContext(text, [unresolved(1000), unresolved(-10)], 4);
37
- assert.match(result, /@@ lines 1-4 @@/);
38
- assert.match(result, /@@ lines 7-10 @@/);
39
- assert.match(result, /Context rows: 8\/8; 0 omitted/);
39
+ test("ambiguous context clips windows at BOF and EOF without padding", () => {
40
+ const lines = Array.from({ length: 10 }, (_, index) => `${index + 1}`);
41
+ const result = format(lines.join("\n"), [ambiguous(lines, [1, 10])]).text;
42
+ assert.match(result, /@@ candidate-neighborhood lines 1-4 @@/);
43
+ assert.match(result, /@@ candidate-neighborhood lines 7-10 @@/);
44
+ assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
45
+ assert.doesNotMatch(result, /omitted/);
40
46
  });
41
47
 
42
- test("failure context returns no invented anchor for an empty file", () => {
43
- const result = formatFailureContext("", [unresolved(1)], 4);
44
- assert.match(result, /file is empty/i);
45
- assert.doesNotMatch(result, /\d+#[0-9A-Z]+│/);
48
+ test("ambiguous context exceeds forty rows and merges repeated candidate windows", () => {
49
+ const lines = Array.from({ length: 60 }, (_, index) => `line-${index + 1}`);
50
+ const result = format(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]).text;
51
+ assert.doesNotMatch(result, /omitted|truncated/);
52
+ assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 42);
53
+ const repeated = format(lines.join("\n"), Array.from({ length: 50 }, (_, opIndex) => ({ ...ambiguous(lines, [4, 5]), opIndex }))).text;
54
+ assert.equal((repeated.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
55
+ assert.doesNotMatch(repeated, /omitted|truncated/);
46
56
  });
47
57
 
48
- test("failure context keeps the lowest 40 rows and reports row truncation", () => {
49
- const text = Array.from({ length: 100 }, (_, index) => `line ${index + 1}`).join("\n");
50
- const result = formatFailureContext(text, [4, 20, 36, 52, 68, 84].map(unresolved), 4);
51
- assert.match(result, /Context rows: 40\/42; 2 omitted/);
52
- assert.match(result, /Context truncated: row limit/);
53
- assert.match(result, /85#[0-9A-Z]+│line 85/);
54
- assert.doesNotMatch(result, /86#[0-9A-Z]+│line 86/);
58
+ test("ambiguous context uses the same first eight candidates as the detail list", () => {
59
+ const lines = Array.from({ length: 90 }, (_, index) => `line-${index + 1}`);
60
+ const result = format(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54, 64, 74, 84])]).text;
61
+ assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 56);
62
+ assert.match(result, /^77#[0-9A-Z]+│line-77$/m);
63
+ assert.doesNotMatch(result, /^8[1-7]#[0-9A-Z]+│/m);
55
64
  });
56
65
 
57
- test("failure context never truncates or skips an oversized first row", () => {
58
- const oversized = "界".repeat(16 * 1024);
59
- const result = formatFailureContext(`${oversized}\nshort\n`, [unresolved(1)], 4);
60
- assert.match(result, /No context row fits the byte budget/);
61
- assert.match(result, /Context rows: 0\/2; 2 omitted/);
62
- assert.match(result, /Context truncated: byte limit/);
63
- assert.doesNotMatch(result, /│short/);
66
+ test("ambiguous context preserves complete rows at the byte budget", () => {
67
+ const exact = "x".repeat(16 * 1024 - Buffer.byteLength("1#XXXX│\n"));
68
+ const lines = [exact, "target", "last"];
69
+ const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
70
+ assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact)}│${exact}\n`));
71
+ assert.match(byteLimited, /Candidate-neighborhood rows: 1\/3; 2 omitted/);
72
+ assert.match(byteLimited, /truncated: byte limit/);
73
+ assert.doesNotMatch(byteLimited, /^2#[0-9A-Z]+│/m);
74
+ const oversizedFirst = ["界".repeat(6000), "target", "last"];
75
+ const skippedFirst = format(oversizedFirst.join("\n"), [ambiguous(oversizedFirst, [2, 3])]).text;
76
+ assert.match(skippedFirst, /Candidate-neighborhood rows: 2\/3; 1 omitted/);
77
+ assert.doesNotMatch(skippedFirst, /^1#[0-9A-Z]+│/m);
78
+ assert.match(skippedFirst, /^2#[0-9A-Z]+│target$/m);
79
+ assert.match(skippedFirst, /^3#[0-9A-Z]+│last$/m);
80
+ const oversizedMiddle = ["short", "界".repeat(6000), "target", "last"];
81
+ const partial = format(oversizedMiddle.join("\n"), [ambiguous(oversizedMiddle, [3, 4])]).text;
82
+ assert.match(partial, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
83
+ assert.doesNotMatch(partial, /^2#[0-9A-Z]+│/m);
84
+ assert.match(partial, /@@ candidate-neighborhood lines 1-1 @@/);
85
+ assert.match(partial, /@@ candidate-neighborhood lines 3-4 @@/);
86
+ const allOversized = ["x".repeat(4096), "y".repeat(4096)];
87
+ const empty = format(allOversized.join("\n"), [ambiguous(allOversized, [1, 2])]).text;
88
+ assert.match(empty, /No complete neighborhood row fits the limits/);
89
+ assert.match(empty, /Candidate-neighborhood rows: 0\/2; 2 omitted/);
64
90
  });
65
91
 
66
- test("failure context accepts an exact 16 KiB row and then stops at the next row", () => {
67
- const exact = "x".repeat(16 * 1024 - 10);
68
- const result = formatFailureContext(`${exact}\nlater\n`, [unresolved(1)], 4);
69
- assert.match(result, /Context rows: 1\/2; 1 omitted/);
70
- assert.match(result, /Context truncated: byte limit/);
71
- assert.match(result, new RegExp(`1#${computeLineHash(1, exact)}│x`));
72
- assert.doesNotMatch(result, /│later/);
92
+ test("ambiguous context enforces the complete candidate row byte limit", () => {
93
+ for (const extra of [0, 1]) {
94
+ const candidate = "x".repeat(4096 - Buffer.byteLength("2#XXXXXX│") + extra);
95
+ const lines = ["prefix", candidate, "tail", "other"];
96
+ const output = format(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6).text;
97
+ if (extra === 0) {
98
+ assert.ok(output.includes(`2#${computeLineHash(2, candidate, 6)}│${candidate}\n`));
99
+ assert.doesNotMatch(output, /omitted/);
100
+ } else {
101
+ assert.match(output, /truncated: candidate row limit/);
102
+ assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
103
+ assert.match(output, /^4#[0-9A-Z]+│other$/m);
104
+ }
105
+ }
73
106
  });
74
107
 
75
- test("failure context stops at an oversized middle row without skipping it", () => {
76
- const oversized = "界".repeat(16 * 1024);
77
- const result = formatFailureContext(`short\n${oversized}\nlater\n`, [unresolved(2)], 4);
78
- assert.match(result, /1#[0-9A-Z]+│short/);
79
- assert.match(result, /Context rows: 1\/3; 2 omitted/);
80
- assert.doesNotMatch(result, /3#[0-9A-Z]+│later/);
108
+ test("unique candidates inside ambiguous neighborhoods retain the candidate row limit", () => {
109
+ const lines = ["prefix", "x".repeat(4096), "match", "match"];
110
+ const output = format(lines.join("\n"), [
111
+ ambiguous(lines, [3, 4]),
112
+ failure({ kind: "found", scope: "local", newLine: 2, newHash: computeLineHash(2, lines[1]) }),
113
+ ]).text;
114
+ assert.match(output, /truncated: candidate row limit/);
115
+ assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
81
116
  });
82
117
 
83
- test("failure context hashes canonical CRLF lines with the captured hash length", () => {
84
- const result = formatFailureContext("alpha\r\n\r\nomega\r\n", [unresolved(2)], 6);
85
- assert.match(result, new RegExp(`1#${computeLineHash(1, "alpha", 6)}│alpha`));
86
- assert.match(result, new RegExp(`2#${computeLineHash(2, "", 6)}│(?:\\n|$)`));
87
- assert.match(result, new RegExp(`3#${computeLineHash(3, "omega", 6)}│omega`));
118
+ test("neighborhoods keep shorter later rows when the remaining budget cannot fit a row", () => {
119
+ const lines = ["x".repeat(16 * 1024 - 100), "y".repeat(200), "target", "other"];
120
+ const output = format(lines.join("\n"), [ambiguous(lines, [3, 4])]);
121
+ assert.deepEqual([...output.shownLines], [1, 3, 4]);
122
+ assert.match(output.text, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
123
+ const rows = output.text.match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
124
+ assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <= 16 * 1024);
88
125
  });
@@ -1,24 +1,16 @@
1
- import { computeLineHash } from "../core/hash.ts";
1
+ import type { AnchorFormatter } from "./anchor-format.ts";
2
2
  import { splitLines } from "../core/lines.ts";
3
3
  import type { AnchorFailure } from "../core/types.ts";
4
+ import { mergeRanges } from "../core/ranges.ts";
4
5
 
5
6
  const CONTEXT_RADIUS = 3;
6
- const MAX_CONTEXT_ROWS = 40;
7
7
  const MAX_CONTEXT_BYTES = 16 * 1024;
8
+ export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
9
+ export const MAX_AMBIGUOUS_CANDIDATES = 8;
8
10
 
9
11
  type Interval = { lo: number; hi: number };
10
12
  type ContextRow = { line: number; text: string };
11
13
 
12
- function mergeIntervals(intervals: Interval[]): Interval[] {
13
- const sorted = intervals.sort((a, b) => a.lo - b.lo || a.hi - b.hi);
14
- const merged: Interval[] = [];
15
- for (const interval of sorted) {
16
- const previous = merged.at(-1);
17
- if (previous && interval.lo <= previous.hi + 1) previous.hi = Math.max(previous.hi, interval.hi);
18
- else merged.push({ ...interval });
19
- }
20
- return merged;
21
- }
22
14
 
23
15
  function shownIntervals(rows: readonly ContextRow[]): Interval[] {
24
16
  const intervals: Interval[] = [];
@@ -30,69 +22,80 @@ function shownIntervals(rows: readonly ContextRow[]): Interval[] {
30
22
  return intervals;
31
23
  }
32
24
 
33
- /**
34
- * Format bounded current-file anchors for unrecoverable anchor failures.
35
- * @internal Used by the edit tool and focused tests; performs no I/O.
36
- */
37
- export function formatFailureContext(
38
- currentText: string,
39
- failures: readonly AnchorFailure[],
40
- hashLen: number,
41
- ): string {
42
- const unresolved = failures.filter((failure) => failure.recovery.kind === "none");
43
- if (unresolved.length === 0) return "";
44
-
45
- const lines = splitLines(currentText);
46
- const heading = [
47
- "Current-file context from the snapshot used for this check:",
48
- "Window: +/-3 lines around each clamped unresolved anchor.",
49
- "Limits: 40 rows; 16384 UTF-8 bytes of anchored row text.",
50
- ];
51
- if (lines.length === 0) {
52
- return `\n${heading.join("\n")}\nThe file is empty in the validation snapshot; no context anchors are available.`;
53
- }
54
-
55
- const windows = mergeIntervals(unresolved.map((failure) => {
56
- const center = Math.min(lines.length, Math.max(1, failure.cited.line));
57
- return { lo: Math.max(1, center - CONTEXT_RADIUS), hi: Math.min(lines.length, center + CONTEXT_RADIUS) };
25
+ function collectContextRows(
26
+ lines: readonly string[],
27
+ centers: readonly number[],
28
+ anchors: AnchorFormatter,
29
+ candidateLines: ReadonlySet<number>,
30
+ ) {
31
+ const windows = mergeRanges(centers.map((center) => {
32
+ const line = Math.min(lines.length, Math.max(1, center));
33
+ return [Math.max(1, line - CONTEXT_RADIUS), Math.min(lines.length, line + CONTEXT_RADIUS) + 1];
58
34
  }));
59
- const total = windows.reduce((sum, window) => sum + window.hi - window.lo + 1, 0);
35
+ const total = windows.reduce((sum, [start, end]) => sum + end - start, 0);
60
36
  const rows: ContextRow[] = [];
61
37
  let bytes = 0;
62
- let truncatedBy: "row limit" | "byte limit" | undefined;
38
+ const omissions = new Set<"byte limit" | "candidate row limit">();
63
39
 
64
- outer: for (const window of windows) {
65
- for (let line = window.lo; line <= window.hi; line++) {
66
- if (rows.length >= MAX_CONTEXT_ROWS) {
67
- truncatedBy = "row limit";
68
- break outer;
69
- }
40
+ for (const [start, end] of windows) {
41
+ for (let line = start; line < end; line++) {
70
42
  const content = lines[line - 1];
71
- const text = `${line}#${computeLineHash(line, content, hashLen)}│${content}`;
72
- const rowBytes = Buffer.byteLength(`${text}\n`, "utf8");
73
- if (bytes + rowBytes > MAX_CONTEXT_BYTES) {
74
- truncatedBy = "byte limit";
75
- break outer;
43
+ const text = anchors.row(line, content);
44
+ const rowBytes = Buffer.byteLength(text, "utf8");
45
+ // Neighborhoods must not bypass the standalone candidate's complete-row limit.
46
+ if (candidateLines.has(line) && rowBytes > MAX_RECOVERY_CANDIDATE_BYTES) {
47
+ omissions.add("candidate row limit");
48
+ continue;
49
+ }
50
+ if (bytes + rowBytes + 1 > MAX_CONTEXT_BYTES) {
51
+ omissions.add("byte limit");
52
+ continue;
76
53
  }
77
54
  rows.push({ line, text });
78
- bytes += rowBytes;
55
+ bytes += rowBytes + 1;
79
56
  }
80
57
  }
58
+ return { rows, total, truncatedBy: [...omissions].join(" and ") || undefined };
59
+ }
81
60
 
82
- const body: string[] = [...heading];
61
+ function formatContextRows(rows: readonly ContextRow[]): string[] {
62
+ const body: string[] = [];
63
+ let index = 0;
64
+ for (const interval of shownIntervals(rows)) {
65
+ body.push(`@@ candidate-neighborhood lines ${interval.lo}-${interval.hi} @@`);
66
+ while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
67
+ }
68
+ return body;
69
+ }
70
+
71
+ /**
72
+ * Format observation rows around listed ambiguous candidates and report rows actually shown.
73
+ * @internal Performs no I/O; the edit diagnostic uses shownLines to avoid repeating content.
74
+ */
75
+ export function formatAmbiguousCandidateNeighborhoods(
76
+ currentText: string,
77
+ failures: readonly AnchorFailure[],
78
+ anchors: AnchorFormatter,
79
+ ): { text: string; shownLines: ReadonlySet<number> } {
80
+ const centers = failures.flatMap((failure) => failure.recovery.kind === "ambiguous"
81
+ ? failure.recovery.candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES).map(candidate => candidate.line) : []);
82
+ if (centers.length === 0) return { text: "", shownLines: new Set() };
83
+
84
+ const lines = splitLines(currentText);
85
+ const candidateLines = new Set(centers);
86
+ for (const failure of failures) {
87
+ if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
88
+ }
89
+ const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
90
+ const body = ["Ambiguous-candidate neighborhoods (+/-3; observation only):"];
83
91
  if (rows.length === 0) {
84
- body.push("No context row fits the byte budget. Use read or grep for additional context.");
92
+ body.push("No complete neighborhood row fits the limits.");
85
93
  } else {
86
- let index = 0;
87
- for (const interval of shownIntervals(rows)) {
88
- body.push(`@@ lines ${interval.lo}-${interval.hi} @@`);
89
- while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
90
- }
94
+ body.push(...formatContextRows(rows));
95
+ }
96
+ if (truncatedBy) {
97
+ body.push(`Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`);
98
+ body.push(`Candidate neighborhoods truncated: ${truncatedBy} (16384 bytes; candidate row 4096 bytes; lowest lines first).`);
91
99
  }
92
- const omitted = total - rows.length;
93
- body.push(`Context rows: ${rows.length}/${total}; ${omitted} omitted.`);
94
- if (truncatedBy) body.push(`Context truncated: ${truncatedBy}. Lowest-line rows were kept first.`);
95
- body.push("Re-evaluate the edit against these lines; do not blindly replace the old anchor.");
96
- body.push("Use read or grep if the relevant lines are omitted or more context is needed.");
97
- return `\n${body.join("\n")}`;
100
+ return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
98
101
  }
@@ -22,7 +22,7 @@ test("published post-processing failure skips command and preserves publication
22
22
  const fusion = createActionFusionExecutor(async () => { commanded = true; return "never"; });
23
23
  await assert.rejects(
24
24
  fusion({ toolCallId: "published", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { throw new FileMutationError("post_process", "PUBLISHED", "file was published but result generation failed"); }, signal: undefined, ctx: context(dir), onUpdate: (update) => updates.push(update) }),
25
- (error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded,
25
+ (error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded && /Re-read before retrying/.test(error.message),
26
26
  );
27
27
  assert.ok(updates.every((update) => update.details.actionFusion.mutationCompleted === false));
28
28
  assert.equal(updates.at(-1).details.actionFusion.publication, "PUBLISHED");
@@ -34,7 +34,8 @@ test("command failure still reports final changed freshness", async () => withTe
34
34
  const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); throw new Error("command failed"); });
35
35
  const outcome: any = await fusion({ toolCallId: "failed", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { await writeFile(target, "mutation\n"); return result("mutation\n"); }, signal: undefined, ctx: context(dir) });
36
36
  assert.deepEqual(outcome.details.actionFusion, { publication: "PUBLISHED", command: "failed", freshness: "changed" });
37
- assert.match(outcome.content[1].text, /Re-read the file/);
37
+ assert.equal((outcome.content[1].text.match(/Re-read/g) ?? []).length, 1);
38
+ assert.match(outcome.content[1].text, /then_run:stale/);
38
39
  }));
39
40
 
40
41
  test("timeout and cancellation do not rerun mutation and still inspect freshness", async () => withTemp(async (dir) => {
@@ -61,3 +62,20 @@ test("queue is released after a failed command", async () => withTemp(async (dir
61
62
  assert.equal(calls, 2);
62
63
  assert.match(second.content[1].type === "text" ? second.content[1].text : "", /then_run:succeeded/);
63
64
  }));
65
+
66
+ test("result generation failure cannot overwrite an already successful command", async () => withTemp(async (dir) => {
67
+ const target = join(dir, "finalize.txt");
68
+ const progress: any[] = [];
69
+ const fusion = createActionFusionExecutor(async () => "command finished", (event) => progress.push(event));
70
+ await assert.rejects(fusion({
71
+ toolCallId: "finalize", absolutePath: target, thenRun: { command: "check" }, signal: undefined, ctx: context(dir),
72
+ mutate: async () => { await writeFile(target, "saved\n"); return result("saved\n"); },
73
+ finalizeMutation: () => { throw new Error("mutation result failure"); },
74
+ }), /mutation result failure/);
75
+ assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
76
+ assert.equal(progress.at(-1).publication, "PUBLISHED");
77
+ assert.equal(progress.at(-1).freshness, "unchanged");
78
+ assert.equal(progress.at(-1).command, "succeeded");
79
+ assert.equal(progress.at(-1).output, "command finished");
80
+ assert.equal(progress.at(-1).reason, undefined);
81
+ }));
@@ -226,3 +226,24 @@ test("commit rejects lossy UTF-8 output before modifying or creating files", asy
226
226
  assert.deepEqual(await readFile(existing), Buffer.from(content));
227
227
  assert.equal(result.publishedRevision, byteRevision(Buffer.from(content)));
228
228
  }));
229
+
230
+ test("identical commits preserve the file and still enforce mode, revision, and cancellation", async () => withTemp(async (dir) => {
231
+ const target = join(dir, "same.txt");
232
+ const content = "\uFEFFsame\r\nbytes\n";
233
+ await writeFile(target, content);
234
+ const before = await stat(target);
235
+ const revision = await fileRevision(target);
236
+ for (const mode of [undefined, "overwrite"] as const) {
237
+ const result = await commitFile(target, content, { mode, expectedRevision: revision });
238
+ assert.deepEqual(result, { created: false, baseRevision: revision, publishedRevision: revision, observedRevision: revision, revision, publication: "NOT_PUBLISHED" });
239
+ }
240
+ const after = await stat(target);
241
+ assert.deepEqual([after.ino, after.mtimeMs, after.ctimeMs], [before.ino, before.mtimeMs, before.ctimeMs]);
242
+ await assert.rejects(commitFile(target, content, { mode: "create" }), /already exists/);
243
+ await assert.rejects(commitFile(target, content, { expectedRevision: "stale" }), /expectedRevision/);
244
+ await assert.rejects(commitFile(target, content, { signal: AbortSignal.abort() }), (error: unknown) => error instanceof FileMutationError && error.publication === "NOT_PUBLISHED");
245
+ await assert.rejects(commitFile(join(dir, "missing"), "", { mode: "overwrite" }), /does not exist/);
246
+ const created = await commitFile(join(dir, "empty"), "");
247
+ assert.equal(created.created, true);
248
+ assert.equal(created.publication, "PUBLISHED");
249
+ }));
@@ -1,6 +1,7 @@
1
1
  import { chmod, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, link } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
+ import { decodeEditableText } from "../core/text.ts";
4
5
 
5
6
  export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
6
7
  export type CommitMode = "create" | "overwrite";
@@ -21,7 +22,7 @@ export interface CommitResult extends MutationVersions {
21
22
  created: boolean;
22
23
  /** Backward-compatible alias for publishedRevision. */
23
24
  revision: string;
24
- publication: "PUBLISHED";
25
+ publication: "NOT_PUBLISHED" | "PUBLISHED";
25
26
  }
26
27
 
27
28
  export class FileMutationError extends Error {
@@ -44,6 +45,26 @@ export async function fileRevision(path: string): Promise<string> {
44
45
  return byteRevision(await readFile(path));
45
46
  }
46
47
 
48
+ /** Decode and bind a mutation snapshot to the exact bytes read. */
49
+ export async function readEditableSnapshot(path: string, displayPath: string) {
50
+ try {
51
+ const bytes = await readFile(path);
52
+ return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
53
+ } catch (error) {
54
+ throw new Error(`Error reading ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
55
+ }
56
+ }
57
+
58
+ /** Publish a read-modify-write result against its source revision. Callers own the queue. */
59
+ export async function commitReplacement(path: string, displayPath: string, text: string, baseRevision: string, signal?: AbortSignal) {
60
+ try {
61
+ return await commitFile(path, text, { mode: "overwrite", expectedRevision: baseRevision, signal });
62
+ } catch (error) {
63
+ if (error instanceof FileMutationError) throw error;
64
+ throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
65
+ }
66
+ }
67
+
47
68
  function prepareError(message: string, cause?: unknown): FileMutationError {
48
69
  return new FileMutationError("prepare", "NOT_PUBLISHED", message, { cause });
49
70
  }
@@ -145,7 +166,7 @@ async function syncDirectory(path: string): Promise<void> {
145
166
  }
146
167
  }
147
168
 
148
- /** Prepare and sync exact UTF-8 bytes before publication; callers own the outer file queue. */
169
+ /** Validate the target, skip identical content, otherwise sync and publish. Callers own the file queue. */
149
170
  export async function commitFile(path: string, content: string, options: CommitOptions = {}): Promise<CommitResult> {
150
171
  if (content.includes("\0")) throw prepareError("UNSUPPORTED_TEXT: NUL bytes are not editable.");
151
172
  const bytes = Buffer.from(content, "utf8");
@@ -159,6 +180,18 @@ export async function commitFile(path: string, content: string, options: CommitO
159
180
  throw prepareError("expectedRevision does not match the current file");
160
181
  }
161
182
  try { options.signal?.throwIfAborted(); } catch (error) { throw prepareError("mutation was cancelled before publication", error); }
183
+ const publishedRevision = byteRevision(bytes);
184
+ // Mode, revision, target safety, and cancellation checks still apply to no-ops.
185
+ if (target.beforeRevision === publishedRevision) {
186
+ return {
187
+ created: false,
188
+ baseRevision: target.beforeRevision,
189
+ publishedRevision,
190
+ observedRevision: target.beforeRevision,
191
+ revision: publishedRevision,
192
+ publication: "NOT_PUBLISHED",
193
+ };
194
+ }
162
195
 
163
196
  const publishPath = target.publishPath;
164
197
  const publishDirectory = dirname(publishPath);
@@ -188,7 +221,6 @@ export async function commitFile(path: string, content: string, options: CommitO
188
221
  published = true;
189
222
  await syncDirectory(publishDirectory);
190
223
  try {
191
- const publishedRevision = byteRevision(bytes);
192
224
  const observedRevision = await fileRevision(publishPath);
193
225
  return {
194
226
  created: mode === "create",
@@ -49,7 +49,8 @@ test("one independent card updates live and only persists its endpoints", () =>
49
49
  assert.equal(h.entries.length, 2);
50
50
  assert.equal(h.entries[0].data.command, "waiting");
51
51
  const collapsed = card.render(100).join("\n");
52
- assert.match(collapsed, /succeeded[\s\S]*Anchors are stale/);
52
+ assert.match(collapsed, /succeeded/);
53
+ assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
53
54
  assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
54
55
  assert.match(collapsed, /output line 19/);
55
56
  assert.doesNotMatch(collapsed, /output line 0\b/);
@@ -67,3 +68,39 @@ test("session restore uses final snapshots and marks unfinished calls unknown",
67
68
  resumed.restore("session_tree", [h.entries[0]]);
68
69
  assert.match(resumed.card(h.entries[0]).render(100).join("\n"), /interrupted \(final status unknown\)/);
69
70
  });
71
+
72
+ test("skips and cancellations stay neutral and restore their own reason", () => {
73
+ for (const command of ["skipped", "cancelled"] as const) {
74
+ const h = harness();
75
+ h.report(waiting);
76
+ h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
77
+ for (const restored of [false, true]) {
78
+ const view = restored ? harness(h.entries) : h;
79
+ if (restored) view.restore();
80
+ const output = view.card(h.entries[0], true).render(160).join("\n");
81
+ assert.match(output, /Not run because the mutation did not complete/);
82
+ assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
83
+ assert.ok(!view.backgrounds.includes("toolErrorBg"));
84
+ assert.ok(!view.backgrounds.includes("toolSuccessBg"));
85
+ assert.equal(view.backgrounds.at(-1), "customMessageBg");
86
+ }
87
+ }
88
+ });
89
+
90
+ test("legacy snapshots separate known command failures and suppress mutation diagnostics", () => {
91
+ for (const command of ["skipped", "failed", "cancelled"] as const) {
92
+ const output = command === "skipped"
93
+ ? "mutation failed; the command was not run [then_run:skipped]\nNo file changes were published. Command skipped.\nAnchor mismatch: 1 shifted.\nInput-anchor checks"
94
+ : `mutation completed; then_run did not complete successfully [then_run:${command === "cancelled" ? "skipped" : "failed"}]\nFile changes are saved. Command ${command}.\nactual command diagnostic`;
95
+ const entries = [
96
+ { type: "custom", customType: "hashline-then-run", data: waiting },
97
+ { type: "custom", customType: "hashline-then-run-result", data: { ...waiting, command, publication: "PUBLISHED", output } },
98
+ ];
99
+ const h = harness(entries);
100
+ h.restore();
101
+ const text = h.card(entries[0], true).render(160).join("\n");
102
+ assert.doesNotMatch(text, /Anchor mismatch|Input-anchor|publication=|freshness=|File changes are saved|mutation completed/);
103
+ assert.match(text, command === "skipped" ? /Command was not run/ : /actual command diagnostic/);
104
+ assert.equal(entries[1].data.output, output, "restoring must not rewrite persisted evidence");
105
+ }
106
+ });