@criogaid/pi-hashline-edit 0.7.0 → 0.8.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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -20,7 +20,7 @@ import { splitLines } from "../core/lines.ts";
20
20
  import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
21
21
  import { mergeRanges } from "../core/ranges.ts";
22
22
  import { HashlineError } from "../core/errors.ts";
23
- import { DEFAULT_OUTPUT_BUDGETS, formatKiB, type OutputBudgets } from "./budgets.ts";
23
+ import { formatByteSize, type OutputBudgets } from "./budgets.ts";
24
24
  import { boundedFacts } from "./report.ts";
25
25
  import type { AnchorFailureFact, ErrorFacts } from "./report-schema.ts";
26
26
 
@@ -32,7 +32,7 @@ const MAX_AMBIGUOUS_CANDIDATES = 8;
32
32
  type Snapshot = Readonly<{ currentText: string; anchors: AnchorFormatter }>;
33
33
 
34
34
  /** Select the shared candidate prefix for detail lists and observation neighborhoods. */
35
- export function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
35
+ function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
36
36
  return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
37
37
  }
38
38
 
@@ -99,7 +99,7 @@ export function ambiguousCandidateNeighborhoods(
99
99
  currentText: string,
100
100
  failures: readonly AnchorFailure[],
101
101
  anchors: AnchorFormatter,
102
- budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
102
+ budget: OutputBudgets,
103
103
  ): {
104
104
  facts: Pick<MismatchFacts, "candidateNeighborhoods" | "omittedNeighborhoodRows">;
105
105
  shownLines: ReadonlySet<number>;
@@ -141,7 +141,7 @@ function failureEntry(
141
141
  shownLines: Set<number>,
142
142
  budget: OutputBudgets,
143
143
  ): AnchorFailureFact {
144
- const rowTooLarge = `row exceeds ${formatKiB(budget.fieldBytes)}`;
144
+ const rowTooLarge = `row exceeds ${formatByteSize(budget.fieldBytes)}`;
145
145
  const entry: { -readonly [K in keyof AnchorFailureFact]: AnchorFailureFact[K] } = {
146
146
  field: `edits[${f.opIndex}].${f.which}`,
147
147
  op: f.op,
@@ -164,7 +164,7 @@ function failureEntry(
164
164
  entry.content = displayCarriageReturns(content);
165
165
  shownLines.add(newLine);
166
166
  } else {
167
- entry.contentOmitted = rowTooLarge;
167
+ entry.omitted = rowTooLarge;
168
168
  }
169
169
  break;
170
170
  }
@@ -178,10 +178,13 @@ function failureEntry(
178
178
  break;
179
179
  }
180
180
  case "none": {
181
+ if (shownLines.has(f.cited.line)) break;
181
182
  const row = f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
182
- if (row === null) entry.observedOmitted = "cited line is out of range";
183
- else if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) entry.observed = row;
184
- else entry.observedOmitted = rowTooLarge;
183
+ if (row === null) entry.omitted = "cited line is out of range";
184
+ else if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) {
185
+ entry.observed = row;
186
+ shownLines.add(f.cited.line);
187
+ } else entry.omitted = rowTooLarge;
185
188
  break;
186
189
  }
187
190
  }
@@ -212,7 +215,7 @@ export function describeEditFailure(
212
215
  failure: ApplyFailure,
213
216
  snapshot: Snapshot,
214
217
  isBatch: boolean,
215
- budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
218
+ budget: OutputBudgets,
216
219
  ): HashlineError<"ANCHOR_MISMATCH" | "INVALID_RANGE" | "OVERLAPPING_EDITS"> {
217
220
  const matched = isBatch ? matchedAnchorFacts(failure, budget) : {};
218
221
  if (failure.kind === "range")
@@ -1,13 +1,16 @@
1
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import fs, { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { syncBuiltinESMExports } from "node:module";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import assert from "node:assert/strict";
5
6
  import { test } from "node:test";
6
7
  import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
7
8
  import { FileMutationError } from "./file-commit.ts";
9
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
8
10
  import { REREAD } from "./report-schema.ts";
9
- import { CommandNotRun, describeFailure, reportOf } from "./report.ts";
10
- import { createToolContext } from "./tool-call.testing.ts";
11
+ import { CommandNotRun, describeFailure, renderReport, reportOf } from "./report.ts";
12
+ import { callTool, createToolContext } from "./tool-call.testing.ts";
13
+ import { makeWriteOverride } from "./write-tool.ts";
11
14
  import { publishedMutation } from "./mutation-outcome.testing.ts";
12
15
 
13
16
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
@@ -20,49 +23,96 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
20
23
  }
21
24
  const mutation = (content: string) => publishedMutation(content, { content: [], details: {} });
22
25
 
26
+ test("temporary preparation and cleanup failures → preserve the commit failure and target bytes", async (t) =>
27
+ withTemp(async (dir) => {
28
+ const target = join(dir, "unpublished.txt");
29
+ await writeFile(target, "before\n");
30
+ const nativeOpen = fs.open;
31
+ const original = Object.assign(new Error("temporary open failed"), { code: "EIO" });
32
+ let failCleanup = false;
33
+ try {
34
+ t.mock.method(fs, "open", async (...args: Parameters<typeof nativeOpen>) => {
35
+ if (String(args[0]).includes(".hashline-commit-") && args[1] === "w") throw original;
36
+ return nativeOpen(...args);
37
+ });
38
+ const nativeRm = fs.rm;
39
+ t.mock.method(fs, "rm", async (...args: Parameters<typeof nativeRm>) => {
40
+ if (failCleanup && String(args[0]).includes(".hashline-commit-"))
41
+ throw Object.assign(new Error("temporary cleanup failed"), { code: "EACCES" });
42
+ return nativeRm(...args);
43
+ });
44
+ syncBuiltinESMExports();
45
+ for (failCleanup of [false, true]) {
46
+ const result = await callTool(makeWriteOverride(dir), {
47
+ path: target,
48
+ mode: "overwrite",
49
+ content: "after\n",
50
+ });
51
+ const report = reportOf(result, "write");
52
+ assert.equal(result.isError, true);
53
+ assert.equal(report?.error, "PUBLISH_FAILED");
54
+ assert.equal(report.stage, "commit");
55
+ assert.equal(report.publication, "NOT_PUBLISHED");
56
+ assert.deepEqual(report.cause, { code: original.code, message: original.message });
57
+ assert.equal(await readFile(target, "utf8"), "before\n");
58
+ }
59
+ } finally {
60
+ t.mock.restoreAll();
61
+ syncBuiltinESMExports();
62
+ }
63
+ }));
64
+
23
65
  test("published post-processing failure → skips command and preserves publication state", async (t) =>
24
66
  withTemp(async (dir) => {
25
67
  const target = join(dir, "published.txt");
26
68
  await writeFile(target, "content\n");
27
69
  let commanded = false;
28
70
  const progress: ActionFusionProgress[] = [];
71
+ const mutationError = new FileMutationError(
72
+ "POST_PROCESS_FAILED",
73
+ "post_process",
74
+ "PUBLISHED",
75
+ "result generation failed",
76
+ );
29
77
  const fusion = createActionFusionExecutor(
30
78
  async () => {
31
79
  commanded = true;
32
- return { status: "succeeded", output: "never" };
80
+ return { status: "succeeded", result: { content: [{ type: "text", text: "never" }] } };
33
81
  },
34
82
  (update) => progress.push(update),
35
83
  );
36
84
  await assert.rejects(
37
85
  fusion({
86
+ budget: DEFAULT_OUTPUT_BUDGETS,
38
87
  toolCallId: "published",
39
88
  tool: "edit",
40
89
  displayPath: "published.txt",
41
90
  absolutePath: target,
42
91
  thenRun: { command: "check" },
43
92
  mutate: async () => {
44
- throw new FileMutationError(
45
- "POST_PROCESS_FAILED",
46
- "post_process",
47
- "PUBLISHED",
48
- "result generation failed",
49
- );
93
+ throw mutationError;
50
94
  },
51
95
  signal: undefined,
52
96
  ctx: await createToolContext(dir, t),
53
97
  }),
54
98
  (error: unknown) => {
55
99
  assert.ok(error instanceof CommandNotRun);
56
- const report = describeFailure("edit", error, { mutation: true });
100
+ assert.equal(error.status, "skipped");
101
+ assert.equal(error.cause, mutationError);
102
+ assert.equal(Object.hasOwn(error, "error"), false);
103
+ const report = describeFailure("edit", error, { budget: DEFAULT_OUTPUT_BUDGETS });
57
104
  assert.equal(report.publication, "PUBLISHED");
105
+ assert.equal(report.stage, "post_process");
58
106
  assert.equal(report.then_run?.status, "skipped");
59
107
  assert.match(report.next ?? "", /change is saved; do not repeat/);
108
+ const diagnostic = renderReport(report);
109
+ assert.equal(diagnostic.split(mutationError.message).length - 1, 1);
110
+ assert.equal(diagnostic.split('"status": "skipped"').length - 1, 1);
60
111
  return true;
61
112
  },
62
113
  );
63
114
  assert.equal(commanded, false);
64
115
  assert.ok(progress.every((update) => update.mutationCompleted === false));
65
- assert.equal(progress.at(-1)?.publication, "PUBLISHED");
66
116
  assert.equal(await readFile(target, "utf8"), "content\n");
67
117
  }));
68
118
 
@@ -74,6 +124,7 @@ test("command fails and modifies the target → reports changed freshness and co
74
124
  throw new Error("command failed");
75
125
  });
76
126
  const outcome = await fusion({
127
+ budget: DEFAULT_OUTPUT_BUDGETS,
77
128
  toolCallId: "failed",
78
129
  tool: "edit",
79
130
  displayPath: "failed.txt",
@@ -86,12 +137,9 @@ test("command fails and modifies the target → reports changed freshness and co
86
137
  signal: undefined,
87
138
  ctx: await createToolContext(dir, t),
88
139
  });
89
- assert.deepEqual(outcome.details.actionFusion, {
90
- publication: "PUBLISHED",
91
- command: "failed",
92
- freshness: "changed",
93
- });
94
- const report = reportOf(outcome);
140
+ const report = reportOf(outcome, "edit");
141
+ assert.equal(report?.publication, "PUBLISHED");
142
+ assert.equal(report?.then_run?.status, "failed");
95
143
  assert.equal(report?.freshness, "changed");
96
144
  assert.equal(report?.next, REREAD);
97
145
  assert.equal(report?.then_run?.output, "command failed");
@@ -104,31 +152,39 @@ test("command fails and modifies the target → reports changed freshness and co
104
152
 
105
153
  test("cancellation after publication → does not rerun mutation and still inspects freshness", async (t) =>
106
154
  withTemp(async (dir) => {
107
- const target = join(dir, "cancelled.txt");
108
- let mutations = 0;
109
- const controller = new AbortController();
110
- const fusion = createActionFusionExecutor(async () => {
111
- controller.abort();
112
- throw new Error("timed out");
113
- });
114
- const outcome = await fusion({
115
- toolCallId: "cancelled",
116
- tool: "edit",
117
- displayPath: "cancelled.txt",
118
- absolutePath: target,
119
- thenRun: { command: "check" },
120
- mutate: async () => {
121
- mutations++;
122
- await writeFile(target, "mutation\n");
123
- return mutation("mutation\n");
124
- },
125
- signal: controller.signal,
126
- ctx: await createToolContext(dir, t),
127
- });
128
- assert.equal(outcome.details.actionFusion.command, "cancelled");
129
- assert.equal(outcome.details.actionFusion.freshness, "unchanged");
130
- assert.equal(mutations, 1);
131
- assert.equal(await readFile(target, "utf8"), "mutation\n");
155
+ for (const state of ["changed", "missing"] as const) {
156
+ const target = join(dir, `${state}.txt`);
157
+ let mutations = 0;
158
+ const controller = new AbortController();
159
+ const fusion = createActionFusionExecutor(async () => {
160
+ if (state === "changed") await writeFile(target, "command changed\n");
161
+ else await rm(target);
162
+ controller.abort();
163
+ throw new Error("timed out");
164
+ });
165
+ const outcome = await fusion({
166
+ budget: DEFAULT_OUTPUT_BUDGETS,
167
+ toolCallId: "cancelled",
168
+ tool: "edit",
169
+ displayPath: `${state}.txt`,
170
+ absolutePath: target,
171
+ thenRun: { command: "check" },
172
+ mutate: async () => {
173
+ mutations++;
174
+ await writeFile(target, "mutation\n");
175
+ return mutation("mutation\n");
176
+ },
177
+ signal: controller.signal,
178
+ ctx: await createToolContext(dir, t),
179
+ });
180
+ const report = reportOf(outcome, "edit");
181
+ assert.equal(report?.publication, "PUBLISHED");
182
+ assert.equal(report?.then_run?.status, "cancelled");
183
+ assert.equal(report?.freshness, state);
184
+ assert.equal(mutations, 1);
185
+ if (state === "changed") assert.equal(await readFile(target, "utf8"), "command changed\n");
186
+ else await assert.rejects(readFile(target), { code: "ENOENT" });
187
+ }
132
188
  }));
133
189
 
134
190
  test("first command fails → releases the queue for the next mutation", async (t) =>
@@ -139,10 +195,11 @@ test("first command fails → releases the queue for the next mutation", async (
139
195
  const fusion = createActionFusionExecutor(async () => {
140
196
  calls++;
141
197
  if (calls === 1) throw new Error("first command failed");
142
- return { status: "succeeded", output: "ok" };
198
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
143
199
  });
144
200
  for (const content of ["first\n", "second\n"]) {
145
201
  const result = await fusion({
202
+ budget: DEFAULT_OUTPUT_BUDGETS,
146
203
  toolCallId: content,
147
204
  tool: "edit",
148
205
  displayPath: "queue.txt",
@@ -155,7 +212,10 @@ test("first command fails → releases the queue for the next mutation", async (
155
212
  signal: undefined,
156
213
  ctx,
157
214
  });
158
- assert.equal(reportOf(result)?.then_run?.status, calls === 1 ? "failed" : "succeeded");
215
+ assert.equal(
216
+ reportOf(result, "edit")?.then_run?.status,
217
+ calls === 1 ? "failed" : "succeeded",
218
+ );
159
219
  }
160
220
  assert.equal(calls, 2);
161
221
  assert.equal(await readFile(target, "utf8"), "second\n");
@@ -166,10 +226,14 @@ test("command succeeds on an unchanged target → retains the result and complet
166
226
  const target = join(dir, "finalize.txt");
167
227
  const progress: ActionFusionProgress[] = [];
168
228
  const fusion = createActionFusionExecutor(
169
- async () => ({ status: "succeeded", output: "command finished" }),
229
+ async () => ({
230
+ status: "succeeded",
231
+ result: { content: [{ type: "text", text: "command finished" }] },
232
+ }),
170
233
  (event) => progress.push(event),
171
234
  );
172
235
  const completed = await fusion({
236
+ budget: DEFAULT_OUTPUT_BUDGETS,
173
237
  toolCallId: "finalize",
174
238
  tool: "edit",
175
239
  displayPath: "finalize.txt",
@@ -183,10 +247,11 @@ test("command succeeds on an unchanged target → retains the result and complet
183
247
  },
184
248
  });
185
249
  assert.equal(completed.content.length, 1);
186
- assert.equal(reportOf(completed)?.then_run?.status, "succeeded");
187
- assert.equal(reportOf(completed)?.then_run?.output, "command finished");
250
+ assert.equal(reportOf(completed, "edit")?.then_run?.status, "succeeded");
251
+ assert.equal(reportOf(completed, "edit")?.then_run?.output, "command finished");
188
252
  assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
189
- assert.equal(progress.at(-1)?.publication, "PUBLISHED");
190
253
  assert.equal(progress.at(-1)?.freshness, "unchanged");
191
- assert.equal(progress.at(-1)?.output, "command finished");
254
+ assert.deepEqual(progress.at(-1)?.result, {
255
+ content: [{ type: "text", text: "command finished" }],
256
+ });
192
257
  }));
@@ -18,7 +18,6 @@ import assert from "node:assert/strict";
18
18
  import { test } from "node:test";
19
19
  import { spawn } from "node:child_process";
20
20
  import {
21
- byteRevision,
22
21
  commitFile,
23
22
  commitReplacement,
24
23
  FileMutationError,
@@ -27,6 +26,7 @@ import {
27
26
  type CommitResult,
28
27
  type FreshnessObservation,
29
28
  } from "./file-commit.ts";
29
+ import { byteRevision } from "./file-revision.ts";
30
30
  import { createActionFusionExecutor } from "./action-fusion.ts";
31
31
  import { makeWriteOverride } from "./write-tool.ts";
32
32
  import { callTool } from "./tool-call.testing.ts";
@@ -39,18 +39,12 @@ function invalidCommitStates() {
39
39
  created: true,
40
40
  publication: "NOT_PUBLISHED",
41
41
  publishedRevision: "r",
42
- };
43
- // @ts-expect-error Replacing an existing target retains its base revision.
44
- const missingBase: CommitResult = {
45
- created: false,
46
- publication: "PUBLISHED",
47
- publishedRevision: "r",
42
+ observedRevision: "r",
48
43
  };
49
44
  // @ts-expect-error A no-op has a confirmed observed revision.
50
45
  const unobservedNoop: CommitResult = {
51
46
  created: false,
52
47
  publication: "NOT_PUBLISHED",
53
- baseRevision: "r",
54
48
  publishedRevision: "r",
55
49
  };
56
50
  // @ts-expect-error A known freshness state cannot carry a read error.
@@ -254,7 +248,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
254
248
  dir,
255
249
  createActionFusionExecutor(async () => {
256
250
  commandRuns++;
257
- return { status: "succeeded", output: "ok" };
251
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
258
252
  }),
259
253
  );
260
254
  try {
@@ -269,7 +263,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
269
263
  { toolCallId: "shared-failure", ctx: { cwd: dir } },
270
264
  );
271
265
  assert.equal(failed.isError, true);
272
- const report = reportOf(failed);
266
+ const report = reportOf(failed, "write");
273
267
  assert.ok(report);
274
268
  assert.ok(report.publication === "NOT_PUBLISHED" || report.publication === "UNKNOWN");
275
269
  assert.equal(report.then_run?.status, "skipped");
@@ -308,7 +302,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
308
302
  { toolCallId: "shared-retry", ctx: { cwd: dir } },
309
303
  );
310
304
  assert.equal(result.isError, undefined);
311
- assert.equal(reportOf(result)?.then_run?.status, "succeeded");
305
+ assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
312
306
  assert.equal(commandRuns, 1);
313
307
  assert.equal(await readFile(target, "utf8"), "replacement\n");
314
308
  }));
@@ -337,7 +331,7 @@ test("cancellation racing publication never reports a settled operation as unpub
337
331
  if (publication === "PUBLISHED") assert.equal(finalContent, newContent);
338
332
  }));
339
333
 
340
- test("commit result binds base, published, and observed revisions", async () =>
334
+ test("bound overwrite → reports published and observed revisions for the published bytes", async () =>
341
335
  withTemp(async (dir) => {
342
336
  const target = join(dir, "versions.txt");
343
337
  await writeFile(target, "before\n");
@@ -346,10 +340,10 @@ test("commit result binds base, published, and observed revisions", async () =>
346
340
  mode: "overwrite",
347
341
  baseRevision,
348
342
  });
349
- assert.equal(result.baseRevision, baseRevision);
350
- assert.equal(result.publishedRevision, byteRevision("after\n"));
343
+ assert.equal(result.publication, "PUBLISHED");
344
+ assert.equal(await readFile(target, "utf8"), "after\n");
345
+ assert.equal(result.publishedRevision, byteRevision(Buffer.from("after\n")));
351
346
  assert.equal(result.observedRevision, result.publishedRevision);
352
- assert.equal("revision" in result, false);
353
347
  }));
354
348
 
355
349
  test("commit rejects lossy UTF-8 output before modifying or creating files", async () =>
@@ -389,7 +383,6 @@ test("identical commits preserve the file and still enforce mode, revision, and
389
383
  });
390
384
  assert.deepEqual(result, {
391
385
  created: false,
392
- baseRevision: revision,
393
386
  publishedRevision: revision,
394
387
  observedRevision: revision,
395
388
  publication: "NOT_PUBLISHED",
@@ -423,7 +416,7 @@ test("identical commits preserve the file and still enforce mode, revision, and
423
416
  assert.equal(created.publication, "PUBLISHED");
424
417
  }));
425
418
 
426
- test("no-op commit with baseRevision validates disk revision against external modifications", async () =>
419
+ test("file changes after the read → bound commits reject changed and unchanged output", async () =>
427
420
  withTemp(async (dir) => {
428
421
  const target = join(dir, "target.txt");
429
422
  const initialContent = "line 1\nline 2\n";
@@ -435,40 +428,32 @@ test("no-op commit with baseRevision validates disk revision against external mo
435
428
  await writeFile(target, "line 1\nmodified line 2\n");
436
429
  const externalRevision = await fileRevision(target);
437
430
 
438
- // A no-op replacement (same text as snapshot) must reject because disk has changed.
439
- await assert.rejects(
440
- commitReplacement(target, snapshot.text, snapshot.baseRevision),
441
- (error: unknown) =>
442
- error instanceof FileMutationError &&
443
- error.stage === "prepare" &&
444
- error.publication === "NOT_PUBLISHED" &&
445
- error.errorCode === "FILE_CHANGED" &&
446
- /after it was read/.test(error.message),
447
- );
448
- // Disk content must remain untouched by the rejected commit.
449
- assert.equal(await readFile(target, "utf8"), "line 1\nmodified line 2\n");
450
- assert.equal(await fileRevision(target), externalRevision);
451
-
452
- // The direct commit path enforces the same snapshot revision.
453
- await assert.rejects(
454
- commitFile(target, snapshot.text, {
455
- mode: "overwrite",
456
- baseRevision: snapshot.baseRevision,
457
- }),
458
- (error: unknown) =>
459
- error instanceof FileMutationError &&
460
- error.stage === "prepare" &&
461
- error.publication === "NOT_PUBLISHED" &&
462
- error.errorCode === "FILE_CHANGED" &&
463
- /after it was read/.test(error.message),
464
- );
431
+ for (const content of [snapshot.text, "replacement\n"]) {
432
+ for (const commit of [
433
+ () => commitReplacement(target, content, snapshot.baseRevision),
434
+ () =>
435
+ commitFile(target, content, { mode: "overwrite", baseRevision: snapshot.baseRevision }),
436
+ ]) {
437
+ await assert.rejects(
438
+ commit,
439
+ (error: unknown) =>
440
+ error instanceof FileMutationError &&
441
+ error.stage === "prepare" &&
442
+ error.publication === "NOT_PUBLISHED" &&
443
+ error.errorCode === "FILE_CHANGED",
444
+ );
445
+ assert.equal(await readFile(target, "utf8"), "line 1\nmodified line 2\n");
446
+ assert.equal(await fileRevision(target), externalRevision);
447
+ }
448
+ }
465
449
 
466
450
  // Without baseRevision, overwrite hashes the current target instead of using the snapshot.
467
451
  const overwriteResult = await commitFile(target, snapshot.text, {
468
452
  mode: "overwrite",
469
453
  });
470
454
  assert.equal(overwriteResult.publication, "PUBLISHED");
471
- assert.equal(overwriteResult.baseRevision, externalRevision);
455
+ assert.equal(overwriteResult.publishedRevision, snapshot.baseRevision);
456
+ assert.equal(overwriteResult.observedRevision, overwriteResult.publishedRevision);
472
457
  assert.equal(await readFile(target, "utf8"), initialContent);
473
458
 
474
459
  // When target does not change externally, no-op commit succeeds and confirms observed revision.
@@ -479,7 +464,6 @@ test("no-op commit with baseRevision validates disk revision against external mo
479
464
  freshSnapshot.baseRevision,
480
465
  );
481
466
  assert.equal(noopResult.publication, "NOT_PUBLISHED");
482
- assert.equal(noopResult.baseRevision, freshSnapshot.baseRevision);
483
467
  assert.equal(noopResult.publishedRevision, freshSnapshot.baseRevision);
484
468
  assert.equal(noopResult.observedRevision, freshSnapshot.baseRevision);
485
469
  }));
@@ -19,7 +19,7 @@ import {
19
19
  } from "node:fs/promises";
20
20
  import type { BigIntStats, Stats } from "node:fs";
21
21
  import { dirname, join } from "node:path";
22
- import { createHash } from "node:crypto";
22
+ import { byteRevision } from "./file-revision.ts";
23
23
  import { decodeEditableText, unwritableTextError } from "../core/text.ts";
24
24
  import {
25
25
  errnoCode,
@@ -42,21 +42,19 @@ export type CommitOptions = { readonly signal?: AbortSignal } & (
42
42
  | { readonly mode: "overwrite"; readonly baseRevision?: string }
43
43
  );
44
44
 
45
- export interface MutationVersions {
46
- baseRevision?: string;
47
- publishedRevision: string;
45
+ /** The published bytes' revision and, when stable, the revision observed right after. */
46
+ interface CommitRevisions {
47
+ readonly publishedRevision: string;
48
48
  /** Absent when a concurrent change prevented a stable observation after publication. */
49
- observedRevision?: string;
49
+ readonly observedRevision?: string;
50
50
  }
51
51
 
52
- export type CommitResult = MutationVersions &
52
+ export type CommitResult = CommitRevisions &
53
53
  (
54
- | { readonly created: true; readonly publication: "PUBLISHED"; readonly baseRevision?: never }
55
- | { readonly created: false; readonly publication: "PUBLISHED"; readonly baseRevision: string }
54
+ | { readonly created: boolean; readonly publication: "PUBLISHED" }
56
55
  | {
57
56
  readonly created: false;
58
57
  readonly publication: "NOT_PUBLISHED";
59
- readonly baseRevision: string;
60
58
  readonly observedRevision: string;
61
59
  }
62
60
  );
@@ -83,10 +81,6 @@ export class FileMutationError<C extends ErrorCode = ErrorCode> extends Hashline
83
81
  }
84
82
  }
85
83
 
86
- export function byteRevision(content: string | Uint8Array): string {
87
- return createHash("sha256").update(content).digest("hex");
88
- }
89
-
90
84
  function requireRegularFile(target: Stats | BigIntStats): void {
91
85
  if (!target.isFile()) throw prepareError("NOT_REGULAR_FILE", "Target is not a regular file.");
92
86
  }
@@ -338,7 +332,6 @@ export async function commitFile(
338
332
  }
339
333
  return {
340
334
  created: false,
341
- baseRevision: target.beforeRevision,
342
335
  publishedRevision,
343
336
  observedRevision: publishedRevision,
344
337
  publication: "NOT_PUBLISHED",
@@ -362,7 +355,6 @@ export async function commitFile(
362
355
  }
363
356
  const tempPath = join(tempDir, "content");
364
357
  let published = false;
365
- let failure: unknown;
366
358
  try {
367
359
  await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
368
360
  if (baseRevision !== undefined) {
@@ -380,9 +372,7 @@ export async function commitFile(
380
372
  published = true;
381
373
  await syncDirectory(publishDirectory);
382
374
  const committed: CommitResult = {
383
- ...(target.existed
384
- ? { created: false, baseRevision: target.beforeRevision }
385
- : { created: true, baseRevision: target.beforeRevision }),
375
+ created: !target.existed,
386
376
  publishedRevision,
387
377
  publication: "PUBLISHED",
388
378
  };
@@ -401,7 +391,6 @@ export async function commitFile(
401
391
  );
402
392
  }
403
393
  } catch (error) {
404
- failure = error;
405
394
  if (error instanceof FileMutationError) throw error;
406
395
  if (published)
407
396
  throw new FileMutationError(
@@ -422,26 +411,8 @@ export async function commitFile(
422
411
  { cause: error },
423
412
  );
424
413
  } finally {
425
- try {
426
- await rm(tempDir, { recursive: true, force: true });
427
- } catch (error) {
428
- if (!published) {
429
- if (failure !== undefined) throw failure;
430
- throw error;
431
- }
432
- throw new FileMutationError(
433
- "POST_PROCESS_FAILED",
434
- "post_process",
435
- "PUBLISHED",
436
- "Temporary cleanup failed.",
437
- {
438
- cause:
439
- failure === undefined
440
- ? error
441
- : new AggregateError([failure, error], "post-publication cleanup also failed"),
442
- },
443
- );
444
- }
414
+ // Best effort: a leftover temporary directory changes neither the publication nor the recovery.
415
+ await rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
445
416
  }
446
417
  }
447
418
 
@@ -455,7 +426,7 @@ export type FreshnessObservation =
455
426
  };
456
427
 
457
428
  /** Freshness known from the commit result alone, before any later observation. */
458
- export function commitFreshness(commit: MutationVersions): FreshnessObservation {
429
+ export function commitFreshness(commit: CommitRevisions): FreshnessObservation {
459
430
  return {
460
431
  freshness: commit.publishedRevision === commit.observedRevision ? "unchanged" : "changed",
461
432
  };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A file revision is the SHA-256 hex digest of its exact bytes, computed whole or streamed;
3
+ * equal bytes always give equal revisions. Commits and streaming scans share this one rule.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+ import { createHash } from "node:crypto";
8
+
9
+ export function createRevisionHasher() {
10
+ const hash = createHash("sha256");
11
+ return {
12
+ update(bytes: Uint8Array): void {
13
+ hash.update(bytes);
14
+ },
15
+ digest(): string {
16
+ return hash.digest("hex");
17
+ },
18
+ };
19
+ }
20
+
21
+ export function byteRevision(bytes: Uint8Array): string {
22
+ const hasher = createRevisionHasher();
23
+ hasher.update(bytes);
24
+ return hasher.digest();
25
+ }