@criogaid/pi-hashline-edit 0.6.1 → 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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,16 +1,16 @@
1
- import { mkdtemp, 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
- import {
7
- createActionFusionExecutor,
8
- ActionFusionError,
9
- THEN_RUN_STALE,
10
- THEN_RUN_SUCCEEDED,
11
- } from "./action-fusion.ts";
7
+ import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
12
8
  import { FileMutationError } from "./file-commit.ts";
13
- import { staleTargetNotice } from "./mutation-result.ts";
9
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
10
+ import { REREAD } from "./report-schema.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";
14
14
  import { publishedMutation } from "./mutation-outcome.testing.ts";
15
15
 
16
16
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
@@ -21,175 +21,237 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
21
21
  await rm(dir, { recursive: true, force: true });
22
22
  }
23
23
  }
24
+ const mutation = (content: string) => publishedMutation(content, { content: [], details: {} });
24
25
 
25
- const context = (cwd: string) => ({ cwd }) as any;
26
- const result = (content: string) =>
27
- publishedMutation(content, {
28
- content: [{ type: "text", text: "mutation" }],
29
- details: undefined,
30
- });
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
+ }));
31
64
 
32
- test("published post-processing failure skips command and preserves publication state", async () =>
65
+ test("published post-processing failure → skips command and preserves publication state", async (t) =>
33
66
  withTemp(async (dir) => {
34
67
  const target = join(dir, "published.txt");
35
68
  await writeFile(target, "content\n");
36
69
  let commanded = false;
37
- const updates: any[] = [];
38
- const fusion = createActionFusionExecutor(async () => {
39
- commanded = true;
40
- return { status: "succeeded", output: "never" };
41
- });
70
+ const progress: ActionFusionProgress[] = [];
71
+ const mutationError = new FileMutationError(
72
+ "POST_PROCESS_FAILED",
73
+ "post_process",
74
+ "PUBLISHED",
75
+ "result generation failed",
76
+ );
77
+ const fusion = createActionFusionExecutor(
78
+ async () => {
79
+ commanded = true;
80
+ return { status: "succeeded", result: { content: [{ type: "text", text: "never" }] } };
81
+ },
82
+ (update) => progress.push(update),
83
+ );
42
84
  await assert.rejects(
43
85
  fusion({
86
+ budget: DEFAULT_OUTPUT_BUDGETS,
44
87
  toolCallId: "published",
88
+ tool: "edit",
89
+ displayPath: "published.txt",
45
90
  absolutePath: target,
46
91
  thenRun: { command: "check" },
47
92
  mutate: async () => {
48
- throw new FileMutationError(
49
- "post_process",
50
- "PUBLISHED",
51
- "file was published but result generation failed",
52
- );
93
+ throw mutationError;
53
94
  },
54
95
  signal: undefined,
55
- ctx: context(dir),
56
- onUpdate: (update) => updates.push(update),
96
+ ctx: await createToolContext(dir, t),
57
97
  }),
58
- (error: unknown) =>
59
- error instanceof ActionFusionError &&
60
- error.publication === "PUBLISHED" &&
61
- error.command === "skipped" &&
62
- !commanded &&
63
- /Re-read before retrying/.test(error.message),
98
+ (error: unknown) => {
99
+ assert.ok(error instanceof CommandNotRun);
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 });
104
+ assert.equal(report.publication, "PUBLISHED");
105
+ assert.equal(report.stage, "post_process");
106
+ assert.equal(report.then_run?.status, "skipped");
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);
111
+ return true;
112
+ },
64
113
  );
65
- assert.ok(updates.every((update) => update.details.actionFusion.mutationCompleted === false));
66
- assert.equal(updates.at(-1).details.actionFusion.publication, "PUBLISHED");
114
+ assert.equal(commanded, false);
115
+ assert.ok(progress.every((update) => update.mutationCompleted === false));
116
+ assert.equal(await readFile(target, "utf8"), "content\n");
67
117
  }));
68
118
 
69
- test("command failure still reports final changed freshness", async () =>
119
+ test("command fails and modifies the target → reports changed freshness and command failure", async (t) =>
70
120
  withTemp(async (dir) => {
71
121
  const target = join(dir, "failed.txt");
72
- await writeFile(target, "before\n");
73
122
  const fusion = createActionFusionExecutor(async () => {
74
123
  await writeFile(target, "command changed\n");
75
124
  throw new Error("command failed");
76
125
  });
77
- const outcome: any = await fusion({
126
+ const outcome = await fusion({
127
+ budget: DEFAULT_OUTPUT_BUDGETS,
78
128
  toolCallId: "failed",
129
+ tool: "edit",
130
+ displayPath: "failed.txt",
79
131
  absolutePath: target,
80
132
  thenRun: { command: "check" },
81
133
  mutate: async () => {
82
134
  await writeFile(target, "mutation\n");
83
- return result("mutation\n");
135
+ return mutation("mutation\n");
84
136
  },
85
137
  signal: undefined,
86
- ctx: context(dir),
87
- });
88
- assert.deepEqual(outcome.details.actionFusion, {
89
- publication: "PUBLISHED",
90
- command: "failed",
91
- freshness: "changed",
138
+ ctx: await createToolContext(dir, t),
92
139
  });
93
- assert.deepEqual(outcome.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
94
- assert.equal(outcome.content.length, 3);
95
- assert.match(outcome.content[2].text, /command failed/);
140
+ const report = reportOf(outcome, "edit");
141
+ assert.equal(report?.publication, "PUBLISHED");
142
+ assert.equal(report?.then_run?.status, "failed");
143
+ assert.equal(report?.freshness, "changed");
144
+ assert.equal(report?.next, REREAD);
145
+ assert.equal(report?.then_run?.output, "command failed");
146
+ assert.doesNotMatch(
147
+ outcome.content.map((block) => (block.type === "text" ? block.text : "")).join("\n"),
148
+ /Updated anchors|1#AB/,
149
+ );
150
+ assert.equal(await readFile(target, "utf8"), "command changed\n");
96
151
  }));
97
152
 
98
- test("timeout and cancellation do not rerun mutation and still inspect freshness", async () =>
153
+ test("cancellation after publication → does not rerun mutation and still inspects freshness", async (t) =>
99
154
  withTemp(async (dir) => {
100
- const target = join(dir, "cancelled.txt");
101
- await writeFile(target, "before\n");
102
- let mutations = 0;
103
- const controller = new AbortController();
104
- const fusion = createActionFusionExecutor(async () => {
105
- controller.abort();
106
- throw new Error("timed out");
107
- });
108
- const outcome: any = await fusion({
109
- toolCallId: "cancelled",
110
- absolutePath: target,
111
- thenRun: { command: "check" },
112
- mutate: async () => {
113
- mutations++;
114
- await writeFile(target, "mutation\n");
115
- return result("mutation\n");
116
- },
117
- signal: controller.signal,
118
- ctx: context(dir),
119
- });
120
- assert.equal(outcome.details.actionFusion.command, "cancelled");
121
- assert.equal(outcome.details.actionFusion.freshness, "unchanged");
122
- assert.equal(mutations, 1);
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
+ }
123
188
  }));
124
189
 
125
- test("queue is released after a failed command", async () =>
190
+ test("first command fails → releases the queue for the next mutation", async (t) =>
126
191
  withTemp(async (dir) => {
127
192
  const target = join(dir, "queue.txt");
128
- await writeFile(target, "before\n");
193
+ const ctx = await createToolContext(dir, t);
129
194
  let calls = 0;
130
195
  const fusion = createActionFusionExecutor(async () => {
131
196
  calls++;
132
197
  if (calls === 1) throw new Error("first command failed");
133
- return { status: "succeeded", output: "ok" };
134
- });
135
- const first = fusion({
136
- toolCallId: "first",
137
- absolutePath: target,
138
- thenRun: { command: "fail" },
139
- mutate: async () => {
140
- await writeFile(target, "first\n");
141
- return result("first\n");
142
- },
143
- signal: undefined,
144
- ctx: context(dir),
145
- });
146
- const failed: any = await first;
147
- assert.equal(failed.details.actionFusion.command, "failed");
148
- const second = await fusion({
149
- toolCallId: "second",
150
- absolutePath: target,
151
- thenRun: { command: "ok" },
152
- mutate: async () => {
153
- await writeFile(target, "second\n");
154
- return result("second\n");
155
- },
156
- signal: undefined,
157
- ctx: context(dir),
198
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
158
199
  });
200
+ for (const content of ["first\n", "second\n"]) {
201
+ const result = await fusion({
202
+ budget: DEFAULT_OUTPUT_BUDGETS,
203
+ toolCallId: content,
204
+ tool: "edit",
205
+ displayPath: "queue.txt",
206
+ absolutePath: target,
207
+ thenRun: { command: "check" },
208
+ mutate: async () => {
209
+ await writeFile(target, content);
210
+ return mutation(content);
211
+ },
212
+ signal: undefined,
213
+ ctx,
214
+ });
215
+ assert.equal(
216
+ reportOf(result, "edit")?.then_run?.status,
217
+ calls === 1 ? "failed" : "succeeded",
218
+ );
219
+ }
159
220
  assert.equal(calls, 2);
160
- assert.match(
161
- second.content[1].type === "text" ? second.content[1].text : "",
162
- /then_run:succeeded/,
163
- );
221
+ assert.equal(await readFile(target, "utf8"), "second\n");
164
222
  }));
165
223
 
166
- test("successful command finalizes anchors and retains completed progress", async () =>
224
+ test("command succeeds on an unchanged target → retains the result and completed progress", async (t) =>
167
225
  withTemp(async (dir) => {
168
226
  const target = join(dir, "finalize.txt");
169
- const progress: any[] = [];
227
+ const progress: ActionFusionProgress[] = [];
170
228
  const fusion = createActionFusionExecutor(
171
- async () => ({ status: "succeeded", output: "command finished" }),
229
+ async () => ({
230
+ status: "succeeded",
231
+ result: { content: [{ type: "text", text: "command finished" }] },
232
+ }),
172
233
  (event) => progress.push(event),
173
234
  );
174
235
  const completed = await fusion({
236
+ budget: DEFAULT_OUTPUT_BUDGETS,
175
237
  toolCallId: "finalize",
238
+ tool: "edit",
239
+ displayPath: "finalize.txt",
176
240
  absolutePath: target,
177
241
  thenRun: { command: "check" },
178
242
  signal: undefined,
179
- ctx: context(dir),
243
+ ctx: await createToolContext(dir, t),
180
244
  mutate: async () => {
181
245
  await writeFile(target, "saved\n");
182
- return { ...result("saved\n"), anchors: " ANCHOR" };
246
+ return mutation("saved\n");
183
247
  },
184
248
  });
185
- assert.deepEqual(completed.content, [
186
- { type: "text", text: "mutation ANCHOR" },
187
- { type: "text", text: `${THEN_RUN_SUCCEEDED}\ncommand finished` },
188
- ]);
249
+ assert.equal(completed.content.length, 1);
250
+ assert.equal(reportOf(completed, "edit")?.then_run?.status, "succeeded");
251
+ assert.equal(reportOf(completed, "edit")?.then_run?.output, "command finished");
189
252
  assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
190
- assert.equal(progress.at(-1).publication, "PUBLISHED");
191
- assert.equal(progress.at(-1).freshness, "unchanged");
192
- assert.equal(progress.at(-1).command, "succeeded");
193
- assert.equal(progress.at(-1).output, "command finished");
194
- assert.equal(progress.at(-1).reason, undefined);
253
+ assert.equal(progress.at(-1)?.freshness, "unchanged");
254
+ assert.deepEqual(progress.at(-1)?.result, {
255
+ content: [{ type: "text", text: "command finished" }],
256
+ });
195
257
  }));
@@ -18,16 +18,43 @@ 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,
25
24
  fileRevision,
26
25
  readEditableSnapshot,
26
+ type CommitResult,
27
+ type FreshnessObservation,
27
28
  } from "./file-commit.ts";
29
+ import { byteRevision } from "./file-revision.ts";
28
30
  import { createActionFusionExecutor } from "./action-fusion.ts";
29
31
  import { makeWriteOverride } from "./write-tool.ts";
30
32
  import { callTool } from "./tool-call.testing.ts";
33
+ import { reportOf } from "./report.ts";
34
+
35
+ // Checked by tsc; these states cannot be returned by the commit layer.
36
+ function invalidCommitStates() {
37
+ // @ts-expect-error A newly created target is always published.
38
+ const unpublishedCreate: CommitResult = {
39
+ created: true,
40
+ publication: "NOT_PUBLISHED",
41
+ publishedRevision: "r",
42
+ observedRevision: "r",
43
+ };
44
+ // @ts-expect-error A no-op has a confirmed observed revision.
45
+ const unobservedNoop: CommitResult = {
46
+ created: false,
47
+ publication: "NOT_PUBLISHED",
48
+ publishedRevision: "r",
49
+ };
50
+ // @ts-expect-error A known freshness state cannot carry a read error.
51
+ const knownError: FreshnessObservation = {
52
+ freshness: "changed",
53
+ error: new Error("read failed"),
54
+ };
55
+ // @ts-expect-error Unknown freshness records the error that prevented observation.
56
+ const unexplainedUnknown: FreshnessObservation = { freshness: "unknown" };
57
+ }
31
58
 
32
59
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
33
60
  const dir = await mkdtemp(join(tmpdir(), "hashline-commit-"));
@@ -98,7 +125,7 @@ test("independent create commits race at the no-replace publication primitive",
98
125
  assert.match(await readFile(target, "utf8"), /^winner-[ab]\n$/);
99
126
  }));
100
127
 
101
- test("create never overwrites an existing target and expectedRevision remains strict", async () =>
128
+ test("create never overwrites an existing target", async () =>
102
129
  withTemp(async (dir) => {
103
130
  const target = join(dir, "existing.txt");
104
131
  await writeFile(target, "original\n");
@@ -108,10 +135,6 @@ test("create never overwrites an existing target and expectedRevision remains st
108
135
  (error: unknown) =>
109
136
  error instanceof FileMutationError && error.publication === "NOT_PUBLISHED",
110
137
  );
111
- await assert.rejects(
112
- commitFile(target, "replacement\n", { mode: "overwrite", expectedRevision: "stale" }),
113
- /expectedRevision/,
114
- );
115
138
  assert.equal(await fileRevision(target), revision);
116
139
  assert.equal(await readFile(target, "utf8"), "original\n");
117
140
  }));
@@ -225,26 +248,25 @@ test("Windows shared access failure preserves the target, skips then_run, and re
225
248
  dir,
226
249
  createActionFusionExecutor(async () => {
227
250
  commandRuns++;
228
- return { status: "succeeded", output: "ok" };
251
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
229
252
  }),
230
253
  );
231
254
  try {
232
- await assert.rejects(
233
- callTool(
234
- tool,
235
- {
236
- path: target,
237
- content: "replacement\n",
238
- mode: "overwrite",
239
- then_run: { command: "deterministic-command" },
240
- },
241
- { toolCallId: "shared-failure", ctx: { cwd: dir } },
242
- ),
243
- (error: unknown) =>
244
- error instanceof Error &&
245
- /File state is uncertain|No file changes were published/.test(error.message) &&
246
- /Command skipped/.test(error.message),
255
+ const failed = await callTool(
256
+ tool,
257
+ {
258
+ path: target,
259
+ content: "replacement\n",
260
+ mode: "overwrite",
261
+ then_run: { command: "deterministic-command" },
262
+ },
263
+ { toolCallId: "shared-failure", ctx: { cwd: dir } },
247
264
  );
265
+ assert.equal(failed.isError, true);
266
+ const report = reportOf(failed, "write");
267
+ assert.ok(report);
268
+ assert.ok(report.publication === "NOT_PUBLISHED" || report.publication === "UNKNOWN");
269
+ assert.equal(report.then_run?.status, "skipped");
248
270
  assert.equal(commandRuns, 0);
249
271
  } finally {
250
272
  holder.release();
@@ -279,10 +301,8 @@ test("Windows shared access failure preserves the target, skips then_run, and re
279
301
  },
280
302
  { toolCallId: "shared-retry", ctx: { cwd: dir } },
281
303
  );
282
- assert.match(
283
- result.content.map((item: any) => (item.type === "text" ? item.text : "")).join("\n"),
284
- /then_run:succeeded/,
285
- );
304
+ assert.equal(result.isError, undefined);
305
+ assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
286
306
  assert.equal(commandRuns, 1);
287
307
  assert.equal(await readFile(target, "utf8"), "replacement\n");
288
308
  }));
@@ -311,19 +331,19 @@ test("cancellation racing publication never reports a settled operation as unpub
311
331
  if (publication === "PUBLISHED") assert.equal(finalContent, newContent);
312
332
  }));
313
333
 
314
- test("commit result binds base, published, and observed revisions", async () =>
334
+ test("bound overwrite → reports published and observed revisions for the published bytes", async () =>
315
335
  withTemp(async (dir) => {
316
336
  const target = join(dir, "versions.txt");
317
337
  await writeFile(target, "before\n");
318
338
  const baseRevision = await fileRevision(target);
319
339
  const result = await commitFile(target, "after\n", {
320
340
  mode: "overwrite",
321
- expectedRevision: baseRevision,
341
+ baseRevision,
322
342
  });
323
- assert.equal(result.baseRevision, baseRevision);
324
- 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")));
325
346
  assert.equal(result.observedRevision, result.publishedRevision);
326
- assert.equal("revision" in result, false);
327
347
  }));
328
348
 
329
349
  test("commit rejects lossy UTF-8 output before modifying or creating files", async () =>
@@ -335,8 +355,10 @@ test("commit rejects lossy UTF-8 output before modifying or creating files", asy
335
355
  for (const path of [existing, missing]) {
336
356
  await assert.rejects(
337
357
  commitFile(path, content, { mode: path === existing ? "overwrite" : "create" }),
338
- (error: any) =>
339
- error.publication === "NOT_PUBLISHED" && /INVALID_UNICODE/.test(error.message),
358
+ (error: unknown) =>
359
+ error instanceof FileMutationError &&
360
+ error.publication === "NOT_PUBLISHED" &&
361
+ error.errorCode === "INVALID_UNICODE",
340
362
  );
341
363
  }
342
364
  }
@@ -357,11 +379,10 @@ test("identical commits preserve the file and still enforce mode, revision, and
357
379
  const revision = await fileRevision(target);
358
380
  const result = await commitFile(target, content, {
359
381
  mode: "overwrite",
360
- expectedRevision: revision,
382
+ baseRevision: revision,
361
383
  });
362
384
  assert.deepEqual(result, {
363
385
  created: false,
364
- baseRevision: revision,
365
386
  publishedRevision: revision,
366
387
  observedRevision: revision,
367
388
  publication: "NOT_PUBLISHED",
@@ -373,8 +394,13 @@ test("identical commits preserve the file and still enforce mode, revision, and
373
394
  );
374
395
  await assert.rejects(commitFile(target, content, { mode: "create" }), /already exists/);
375
396
  await assert.rejects(
376
- commitFile(target, content, { mode: "overwrite", expectedRevision: "stale" }),
377
- /expectedRevision/,
397
+ commitFile(target, content, { mode: "overwrite", baseRevision: "stale" }),
398
+ (error: unknown) =>
399
+ error instanceof FileMutationError &&
400
+ error.errorCode === "FILE_CHANGED" &&
401
+ error.stage === "prepare" &&
402
+ error.publication === "NOT_PUBLISHED" &&
403
+ /before publication/.test(error.message),
378
404
  );
379
405
  await assert.rejects(
380
406
  commitFile(target, content, { mode: "overwrite", signal: AbortSignal.abort() }),
@@ -390,77 +416,68 @@ test("identical commits preserve the file and still enforce mode, revision, and
390
416
  assert.equal(created.publication, "PUBLISHED");
391
417
  }));
392
418
 
393
- test("no-op commit with knownBeforeRevision validates disk revision against external modifications", async () =>
419
+ test("file changes after the read → bound commits reject changed and unchanged output", async () =>
394
420
  withTemp(async (dir) => {
395
421
  const target = join(dir, "target.txt");
396
422
  const initialContent = "line 1\nline 2\n";
397
423
  await writeFile(target, initialContent);
398
- const snapshot = await readEditableSnapshot(target, "target.txt");
424
+ const snapshot = await readEditableSnapshot(target);
399
425
  assert.equal(snapshot.text, initialContent);
400
426
 
401
427
  // External process modifies target after snapshot is read.
402
428
  await writeFile(target, "line 1\nmodified line 2\n");
403
429
  const externalRevision = await fileRevision(target);
404
430
 
405
- // A no-op replacement (same text as snapshot) must reject because disk has changed.
406
- await assert.rejects(
407
- commitReplacement(target, "target.txt", snapshot.text, snapshot.baseRevision),
408
- (error: unknown) =>
409
- error instanceof FileMutationError &&
410
- error.stage === "prepare" &&
411
- error.publication === "NOT_PUBLISHED" &&
412
- /expectedRevision/.test(error.message),
413
- );
414
- // Disk content must remain untouched by the rejected commit.
415
- assert.equal(await readFile(target, "utf8"), "line 1\nmodified line 2\n");
416
- assert.equal(await fileRevision(target), externalRevision);
417
-
418
- // Direct commitFile with knownBeforeRevision and matching expectedRevision also rejects.
419
- await assert.rejects(
420
- commitFile(target, snapshot.text, {
421
- mode: "overwrite",
422
- expectedRevision: snapshot.baseRevision,
423
- knownBeforeRevision: snapshot.baseRevision,
424
- }),
425
- (error: unknown) =>
426
- error instanceof FileMutationError &&
427
- error.stage === "prepare" &&
428
- error.publication === "NOT_PUBLISHED" &&
429
- /expectedRevision/.test(error.message),
430
- );
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
+ }
431
449
 
432
- // Without expectedRevision, commitFile recognizes disk has changed and publishes the content.
450
+ // Without baseRevision, overwrite hashes the current target instead of using the snapshot.
433
451
  const overwriteResult = await commitFile(target, snapshot.text, {
434
452
  mode: "overwrite",
435
- knownBeforeRevision: snapshot.baseRevision,
436
453
  });
437
454
  assert.equal(overwriteResult.publication, "PUBLISHED");
455
+ assert.equal(overwriteResult.publishedRevision, snapshot.baseRevision);
456
+ assert.equal(overwriteResult.observedRevision, overwriteResult.publishedRevision);
438
457
  assert.equal(await readFile(target, "utf8"), initialContent);
439
458
 
440
459
  // When target does not change externally, no-op commit succeeds and confirms observed revision.
441
- const freshSnapshot = await readEditableSnapshot(target, "target.txt");
460
+ const freshSnapshot = await readEditableSnapshot(target);
442
461
  const noopResult = await commitReplacement(
443
462
  target,
444
- "target.txt",
445
463
  freshSnapshot.text,
446
464
  freshSnapshot.baseRevision,
447
465
  );
448
466
  assert.equal(noopResult.publication, "NOT_PUBLISHED");
449
- assert.equal(noopResult.baseRevision, freshSnapshot.baseRevision);
450
467
  assert.equal(noopResult.publishedRevision, freshSnapshot.baseRevision);
451
468
  assert.equal(noopResult.observedRevision, freshSnapshot.baseRevision);
452
469
  }));
453
470
 
454
- test("no-op commit with knownBeforeRevision rejects if target was deleted externally", async () =>
471
+ test("no-op commit with baseRevision rejects if target was deleted externally", async () =>
455
472
  withTemp(async (dir) => {
456
473
  const target = join(dir, "deleted.txt");
457
474
  await writeFile(target, "content\n");
458
- const snapshot = await readEditableSnapshot(target, "deleted.txt");
475
+ const snapshot = await readEditableSnapshot(target);
459
476
 
460
477
  await rm(target);
461
478
 
462
479
  await assert.rejects(
463
- commitReplacement(target, "deleted.txt", snapshot.text, snapshot.baseRevision),
480
+ commitReplacement(target, snapshot.text, snapshot.baseRevision),
464
481
  (error: unknown) =>
465
482
  error instanceof FileMutationError &&
466
483
  error.stage === "prepare" &&