@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
@@ -71,7 +71,7 @@ test("all-file candidates exceed the scan budget → stop listing and retain sca
71
71
  let stopped = false;
72
72
  const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
73
73
  runRgLines: async () => assert.fail("multiline candidates must use file listing"),
74
- runRgPaths: async (_rgPath, _args, _signal, onFile) => {
74
+ runRgPaths: async (_args, _signal, onFile) => {
75
75
  for (const path of paths) {
76
76
  offered.push(path);
77
77
  if (!(await onFile(path))) {
@@ -92,7 +92,7 @@ test("all-file candidates exceed the scan budget → stop listing and retain sca
92
92
  assert.deepEqual(offered, [fixture, ...padding, blocked]);
93
93
  const report = reportOf(result, "grep");
94
94
  assert.ok(report);
95
- assert.equal(report.candidates, "all");
95
+ assert.equal(report.scanned, "all");
96
96
  assert.equal(report.scanLimit, formatByteSize(MAX_UNNARROWED_SCAN_BYTES));
97
97
  if (scenario.stderr) {
98
98
  assert.equal(result.isError, true);
@@ -3,11 +3,10 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
5
  import { test } from "node:test";
6
- import { rgPath } from "@vscode/ripgrep";
7
6
  import { searchText, type GrepQuery } from "../core/search.ts";
8
7
  import { searchFiles, type GrepFileMatch } from "../pi/grep-search.ts";
9
8
  import { runRgLines, runRgPaths } from "../pi/rg-process.ts";
10
- import { runCandidatePaths } from "../pi/grep-candidates.ts";
9
+ import { candidateArgs } from "../pi/grep-candidates.ts";
11
10
  import { lineCandidatePatterns } from "../pi/rg-regex.ts";
12
11
  import { extractPrefilter } from "../core/search-analysis.ts";
13
12
  import { REGEX_TRANSLATION_CORPUS } from "../testing/regex-translation-corpus.ts";
@@ -71,28 +70,23 @@ test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates,
71
70
  inputs.push({ bytes, filePath });
72
71
  }
73
72
  const candidates = new Map<string, readonly number[] | undefined>();
74
- const warnings: string[] = [];
75
73
  const result = await searchFiles({
76
74
  backend: {
77
75
  runRgPaths: async () => assert.fail("unexpected file fallback"),
78
- runRgLines: (rg, args, signal, maxLines, onFile) =>
79
- runRgLines(rg, args, signal, maxLines, (path, lines) => {
76
+ runRgLines: (args, signal, maxLines, onFile) =>
77
+ runRgLines(args, signal, maxLines, (path, lines) => {
80
78
  candidates.set(resolve(path), lines);
81
79
  return onFile(path, lines);
82
80
  }),
83
81
  },
84
- rgPath,
85
82
  scope: {
86
83
  globs: [],
87
- noIgnore: false,
88
- follow: false,
89
84
  searchPaths: inputs.map((input) => input.filePath),
90
85
  },
91
86
  query,
92
87
  limit: 1000,
93
88
  timeoutMs,
94
89
  signal: AbortSignal.timeout(timeoutMs),
95
- warnings,
96
90
  });
97
91
  const expected = inputs.map(({ bytes, filePath }) => {
98
92
  const native = searchText({ source: bytes.toString("utf8"), query, limit: 1000 });
@@ -112,14 +106,14 @@ test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates,
112
106
  }
113
107
  return { filePath, rows: native.lines };
114
108
  });
115
- assert.deepEqual(warnings, []);
109
+ assert.deepEqual(result.warnings, []);
116
110
  assert.deepEqual(sorted(result.files), sorted(expected));
117
111
  },
118
112
  );
119
113
  }
120
114
  });
121
115
 
122
- test("real rg AND/OR file prefilter → excludes incomplete branches before JS verification", async (t) => {
116
+ test("real rg AND/OR file prefilter → broad candidates retain exact JS results", async (t) => {
123
117
  const directory = await mkdtemp(join(tmpdir(), "hl-regex-conjunction-"));
124
118
  t.after(() => rm(directory, { recursive: true, force: true }));
125
119
  const fixtures = ["foo\nbar", "baz\nqux", "foo\nqux", "baz\nbar", "foo", "bar", "unrelated"];
@@ -136,11 +130,8 @@ test("real rg AND/OR file prefilter → excludes incomplete branches before JS v
136
130
  multiline: true,
137
131
  };
138
132
  const candidates: string[] = [];
139
- const listing = await runCandidatePaths(
140
- runRgPaths,
141
- rgPath,
142
- extractPrefilter(query),
143
- ["--", directory],
133
+ const listing = await runRgPaths(
134
+ [...candidateArgs(extractPrefilter(query)), "--null", "--", directory],
144
135
  AbortSignal.timeout(timeoutMs),
145
136
  (path) => {
146
137
  candidates.push(resolve(path));
@@ -149,18 +140,15 @@ test("real rg AND/OR file prefilter → excludes incomplete branches before JS v
149
140
  );
150
141
  assert.equal(listing.code, 0);
151
142
  assert.equal(listing.stderr, "");
152
- assert.deepEqual(candidates.sort(), paths.slice(0, 2).sort());
153
- const warnings: string[] = [];
143
+ assert.deepEqual(candidates.sort(), [paths[0], paths[1], paths[2], paths[3], paths[4]].sort());
154
144
  const result = await searchFiles({
155
145
  backend: { runRgPaths, runRgLines },
156
- rgPath,
157
- scope: { globs: [], noIgnore: false, follow: false, searchPaths: [directory] },
146
+ scope: { globs: [], searchPaths: [directory] },
158
147
  query,
159
148
  limit: 100,
160
149
  timeoutMs,
161
- warnings,
162
150
  });
163
- assert.deepEqual(warnings, []);
151
+ assert.deepEqual(result.warnings, []);
164
152
  assert.deepEqual(
165
153
  sorted(result.files),
166
154
  sorted(
@@ -181,7 +169,6 @@ test("oversized line translation → file prefilter fallback preserves JS result
181
169
  const path = join(directory, "long.txt");
182
170
  await writeFile(path, pattern);
183
171
  let filePasses = 0;
184
- const warnings: string[] = [];
185
172
  const result = await searchFiles({
186
173
  backend: {
187
174
  runRgPaths: (...args) => {
@@ -190,15 +177,13 @@ test("oversized line translation → file prefilter fallback preserves JS result
190
177
  },
191
178
  runRgLines: async () => assert.fail("translation budget must select file prefilter"),
192
179
  },
193
- rgPath,
194
- scope: { globs: [], noIgnore: false, follow: false, searchPaths: [path] },
180
+ scope: { globs: [], searchPaths: [path] },
195
181
  query,
196
182
  limit: 10,
197
183
  timeoutMs,
198
- warnings,
199
184
  });
200
185
  assert.ok(filePasses > 0);
201
- assert.deepEqual(warnings, []);
186
+ assert.deepEqual(result.warnings, []);
202
187
  assert.deepEqual(
203
188
  sorted(result.files),
204
189
  sorted([{ filePath: path, rows: searchText({ source: pattern, query, limit: 10 }).lines }]),
@@ -1,11 +1,9 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { makeReadOverride } from "../pi/read-tool.ts";
7
- import { makeEditOverride } from "../pi/edit-tool.ts";
8
- import { reportOf } from "../pi/report.ts";
9
7
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
10
8
  import { computeLineHash } from "../core/hash.ts";
11
9
  import { callTool } from "../pi/tool-call.testing.ts";
@@ -70,47 +68,3 @@ test("CRLF snapshots normalize terminators split across read chunks and preserve
70
68
  await rm(directory, { recursive: true, force: true });
71
69
  }
72
70
  });
73
-
74
- test("copy/move a 150,000-line block → publish every captured line", async (t) => {
75
- const directory = await mkdtemp(join(tmpdir(), "hashline-large-transfer-"));
76
- t.after(() => rm(directory, { recursive: true, force: true }));
77
- const path = join(directory, "transfer.txt");
78
- const lineCount = 150_000;
79
- const block = " value🙂\r\n".repeat(lineCount);
80
- const source = `\uFEFFSTART\n${block}END`;
81
- const read = makeReadOverride(directory, DEFAULT_CONFIG);
82
- const edit = makeEditOverride(directory, DEFAULT_CONFIG);
83
- const observedAnchor = async (line: number) => {
84
- const result: Awaited<ReturnType<typeof read.execute>> = await callTool(read, {
85
- path,
86
- offset: line,
87
- limit: 1,
88
- });
89
- const rows = result.content
90
- .filter((part) => part.type === "text")
91
- .map((part) => part.text)
92
- .join("\n");
93
- const match = new RegExp(`^(${line}#[0-9A-Z]+)│`, "m").exec(rows);
94
- assert(match);
95
- return match[1];
96
- };
97
- for (const op of ["copy", "move"] as const) {
98
- await writeFile(path, source);
99
- const [anchor, end, after] = await Promise.all([
100
- observedAnchor(2),
101
- observedAnchor(lineCount + 1),
102
- observedAnchor(lineCount + 2),
103
- ]);
104
- const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(edit, {
105
- path,
106
- edits: [{ action: op, anchor, end, after }],
107
- });
108
- const expected = Buffer.from(
109
- (op === "copy" ? source : "\uFEFFSTART\nEND") + "\r\n" + block.slice(0, -2),
110
- "utf8",
111
- );
112
- assert.deepEqual(await readFile(path), expected);
113
- assert.equal(result.isError, undefined);
114
- assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
115
- }
116
- });
@@ -5,7 +5,8 @@ import { join } from "node:path";
5
5
  import hashlineEdit from "../index.ts";
6
6
  import { callTool } from "../pi/tool-call.testing.ts";
7
7
  import { outputBudgetsFor } from "../pi/budgets.ts";
8
- import { decodeReport, reportOf, type Report } from "../pi/report.ts";
8
+ import { decodeReport, reportOf } from "../pi/report.ts";
9
+ import type { Report } from "../pi/report-schema.ts";
9
10
  import { openTestSession } from "../testing/session.testing.ts";
10
11
 
11
12
  // Budget invalidation relies on Pi publishing the new model before tool preparation.
@@ -8,14 +8,11 @@ import { join } from "node:path";
8
8
  import { test, type TestContext } from "node:test";
9
9
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
10
10
  import { createActionFusionExecutor } from "../pi/action-fusion.ts";
11
- import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
12
11
  import { DEFAULT_CONFIG } from "../pi/config.ts";
13
12
  import { makeEditOverride } from "../pi/edit-tool.ts";
14
- import { commitFile, FileMutationError } from "../pi/file-commit.ts";
15
- import { byteRevision } from "../pi/file-revision.ts";
16
- import { describeFailure, reportOf } from "../pi/report.ts";
13
+ import { reportOf } from "../pi/report.ts";
17
14
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
18
- import { REREAD } from "../pi/report-schema.ts";
15
+ import { PUBLICATION_NEXT, REREAD } from "../pi/report-schema.ts";
19
16
  import { makeReplaceTool } from "../pi/replace-tool.ts";
20
17
  import { callTool, createToolContext } from "../pi/tool-call.testing.ts";
21
18
  import { makeWriteOverride } from "../pi/write-tool.ts";
@@ -111,6 +108,19 @@ const mutationCases = [
111
108
  },
112
109
  ] as const;
113
110
 
111
+ const prePublicationCases = [
112
+ { phase: "inspect target", mutation: mutationCases[2], observation: 1 },
113
+ { phase: "revision recheck", mutation: mutationCases[0], observation: 2 },
114
+ {
115
+ phase: "no-op check",
116
+ mutation: {
117
+ ...mutationCases[1],
118
+ args: { replacements: [{ literal: true, find: BEFORE, replace: BEFORE }] },
119
+ },
120
+ observation: 2,
121
+ },
122
+ ] as const;
123
+
114
124
  for (const fused of [false, true]) {
115
125
  test(`concurrent change during post-publication read without then_run (${fused ? "Fusion enabled" : "plain"}) → succeeds and withholds stale anchors`, async (t) => {
116
126
  for (const mutation of mutationCases) {
@@ -122,7 +132,11 @@ for (const fused of [false, true]) {
122
132
  t,
123
133
  mutation.name === "write create" ? undefined : BEFORE,
124
134
  );
125
- const fusion = fused ? createActionFusionExecutor() : undefined;
135
+ const fusion = fused
136
+ ? createActionFusionExecutor(async () =>
137
+ assert.fail("command must not run without then_run"),
138
+ )
139
+ : undefined;
126
140
  const result = await withDisturbedRead(
127
141
  t,
128
142
  path,
@@ -251,61 +265,125 @@ test("disturbance during post-command freshness read → retains publication and
251
265
  });
252
266
 
253
267
  test("other I/O failure during post-publication read → retains the published post-process error", async (t) => {
254
- const { path } = await targetFile(t, BEFORE);
255
- await withDisturbedRead(
256
- t,
257
- path,
258
- PUBLISHED,
259
- "I/O failure",
260
- (bytes) => bytes.equals(Buffer.from(PUBLISHED)),
261
- async () => {
262
- await assert.rejects(commitFile(path, PUBLISHED, { mode: "overwrite" }), (error: unknown) => {
263
- assert.ok(error instanceof FileMutationError);
264
- assert.equal(error.stage, "post_process");
265
- assert.equal(error.publication, "PUBLISHED");
266
- assert.equal(error.cause, READ_FAILURE);
267
- return true;
268
- });
269
- },
270
- );
271
- await assertTarget(path, PUBLISHED, "I/O failure");
268
+ for (const fused of [false, true]) {
269
+ await t.test(fused ? "Fusion enabled" : "plain", async (t) => {
270
+ const { directory, path } = await targetFile(t, BEFORE);
271
+ let commands = 0;
272
+ const fusion = fused
273
+ ? createActionFusionExecutor(async () => {
274
+ commands++;
275
+ return {
276
+ status: "succeeded",
277
+ result: { content: [{ type: "text", text: "checked" }] },
278
+ };
279
+ })
280
+ : undefined;
281
+ const ctx = await createToolContext(directory, t);
282
+ await withDisturbedRead(
283
+ t,
284
+ path,
285
+ PUBLISHED,
286
+ "I/O failure",
287
+ (bytes) => bytes.equals(Buffer.from(PUBLISHED)),
288
+ () =>
289
+ expectToolFailure(
290
+ callTool(
291
+ makeWriteOverride(directory, fusion),
292
+ {
293
+ path,
294
+ content: PUBLISHED,
295
+ mode: "overwrite",
296
+ ...(fused ? { then_run: { command: "check" } } : {}),
297
+ },
298
+ { ctx },
299
+ ),
300
+ "POST_PROCESS_FAILED",
301
+ (report) => {
302
+ assert.equal(report.publication, "PUBLISHED");
303
+ assert.equal(report.cause?.message, READ_FAILURE.message);
304
+ assert.equal(report.cause?.code, "EIO");
305
+ assert.equal(report.then_run?.status, fused ? "skipped" : undefined);
306
+ assert.equal(report.next, PUBLICATION_NEXT.PUBLISHED);
307
+ },
308
+ ),
309
+ );
310
+ assert.equal(commands, 0);
311
+ await assertTarget(path, PUBLISHED, "I/O failure");
312
+ });
313
+ }
272
314
  });
273
315
 
274
316
  test("concurrent change during pre-publication revision read → rejects without publishing and keeps retry advice", async (t) => {
275
- for (const phase of ["inspect target", "revision recheck", "no-op check"] as const) {
317
+ for (const { phase, mutation, observation } of prePublicationCases) {
276
318
  await t.test(`${phase} → NOT_PUBLISHED`, async (t) => {
277
- const { path } = await targetFile(t, BEFORE);
278
- const revision = byteRevision(Buffer.from(BEFORE));
319
+ const { directory, path } = await targetFile(t, BEFORE);
320
+ let targetReads = 0;
279
321
  await withDisturbedRead(
280
322
  t,
281
323
  path,
282
324
  BEFORE,
283
325
  "append",
284
- () => true,
285
- async () => {
286
- await assert.rejects(
287
- commitFile(path, phase === "no-op check" ? BEFORE : PUBLISHED, {
288
- mode: "overwrite",
289
- ...(phase !== "inspect target" ? { baseRevision: revision } : {}),
290
- }),
291
- (error: unknown) => {
292
- assert.ok(error instanceof FileMutationError);
293
- assert.equal(error.publication, "NOT_PUBLISHED");
294
- assert.equal(error.errorCode, "FILE_CHANGED");
295
- assert.equal(
296
- describeFailure("write", error, { budget: DEFAULT_OUTPUT_BUDGETS }).next,
297
- "Retry the call.",
298
- );
299
- return true;
326
+ () => ++targetReads === observation,
327
+ () =>
328
+ expectToolFailure(
329
+ callTool(mutation.make(directory), { path, ...mutation.args }),
330
+ "FILE_CHANGED",
331
+ (report) => {
332
+ assert.equal(report.publication, "NOT_PUBLISHED");
333
+ assert.equal(report.next, "Retry the call.");
300
334
  },
301
- );
302
- },
335
+ ),
303
336
  );
337
+ assert.equal(targetReads, observation);
304
338
  await assertTarget(path, BEFORE, "append");
305
339
  });
306
340
  }
307
341
  });
308
342
 
343
+ test("target disappears or becomes a directory before publication → keeps the path error without publishing", async (t) => {
344
+ for (const { phase, mutation, observation } of prePublicationCases) {
345
+ for (const disturbance of ["missing", "directory"] as const) {
346
+ await t.test(`${phase}: ${disturbance}`, async (t) => {
347
+ const { directory, path } = await targetFile(t, BEFORE);
348
+ const originalPath = join(directory, "original.txt");
349
+ const nativeOpen = fs.promises.open;
350
+ let targetReads = 0;
351
+ t.mock.method(fs.promises, "open", async (...args: Parameters<typeof nativeOpen>) => {
352
+ if (args[0] === path && ++targetReads === observation) {
353
+ // Keep the displaced inode to prove the commit never changed its bytes.
354
+ fs.renameSync(path, originalPath);
355
+ if (disturbance === "directory") fs.mkdirSync(path);
356
+ }
357
+ return nativeOpen(...args);
358
+ });
359
+ syncBuiltinESMExports();
360
+ try {
361
+ await expectToolFailure(
362
+ callTool(mutation.make(directory), { path, ...mutation.args }),
363
+ disturbance === "missing" ? "PATH_NOT_FOUND" : "NOT_REGULAR_FILE",
364
+ (report) => {
365
+ assert.equal(
366
+ report.message,
367
+ disturbance === "missing" ? "Path not found." : "Path is not a regular file.",
368
+ );
369
+ assert.deepEqual(report.missing, disturbance === "missing" ? [path] : undefined);
370
+ assert.equal(report.publication, "NOT_PUBLISHED");
371
+ assert.equal(report.cause, undefined);
372
+ },
373
+ );
374
+ assert.equal(targetReads, observation, "the intended target read must be disturbed");
375
+ assert.deepEqual(await readFile(originalPath), Buffer.from(BEFORE));
376
+ if (disturbance === "directory") assert.deepEqual(fs.readdirSync(path), []);
377
+ else await assertTarget(path, BEFORE, "delete");
378
+ } finally {
379
+ t.mock.restoreAll();
380
+ syncBuiltinESMExports();
381
+ }
382
+ });
383
+ }
384
+ }
385
+ });
386
+
309
387
  test("file changes after the editable snapshot → rejects publication against the read bytes", async (t) => {
310
388
  for (const mutation of mutationCases.filter(
311
389
  ({ name }) => name === "edit" || name === "replace",
@@ -4,7 +4,7 @@ import { test } from "node:test";
4
4
  import { HashlineError } from "../core/errors.ts";
5
5
  import { runRegexReplacements } from "../pi/replace-regex.ts";
6
6
  import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
7
- import { causeOf } from "../pi/report.ts";
7
+ import { causeOf } from "../pi/report-cause.ts";
8
8
  import type { Cause } from "../pi/report-schema.ts";
9
9
 
10
10
  const timeoutMs = 10_000;
@@ -16,11 +16,17 @@ test("worker boundary: malformed external reply → rejects its result and facts
16
16
  { result: { text: "changed", count: 0 } },
17
17
  {
18
18
  result: { text: "changed", count: 1 },
19
- error: { code: "NO_MATCH", message: "failure", facts: { rule: 0 } },
19
+ error: { code: "NO_MATCH", message: "failure", facts: { unmatched: ["replacements[0]"] } },
20
20
  },
21
21
  { error: { code: "NO_MATCH", message: "failure" } },
22
22
  { error: { code: "foreign", message: "failure" } },
23
- { error: { code: "NO_MATCH", message: "failure", facts: { rule: 0, foreign: true } } },
23
+ {
24
+ error: {
25
+ code: "NO_MATCH",
26
+ message: "failure",
27
+ facts: { unmatched: ["replacements[0]"], foreign: true },
28
+ },
29
+ },
24
30
  ]) {
25
31
  await t.test(JSON.stringify(reply), { timeout: timeoutMs }, async (t) => {
26
32
  const emit = Worker.prototype.emit;
@@ -42,7 +48,7 @@ test("worker boundary: malformed external reply → rejects its result and facts
42
48
  }
43
49
  });
44
50
 
45
- test("worker boundary: deep structured cause reply → preserves the terminal cause and every branch", {
51
+ test("worker boundary: deep structured cause reply → preserves the complete cause chain", {
46
52
  timeout: timeoutMs,
47
53
  }, async (t) => {
48
54
  let nested: Cause = { code: "EACCES", message: "permission denied" };
@@ -51,10 +57,6 @@ test("worker boundary: deep structured cause reply → preserves the terminal ca
51
57
  const cause: Cause = {
52
58
  message: "worker failure",
53
59
  cause: nested,
54
- errors: Array.from({ length: 24 }, (_, index) => ({
55
- code: "EIO",
56
- message: `branch ${index}`,
57
- })),
58
60
  };
59
61
  const emit = Worker.prototype.emit;
60
62
  t.mock.method(
@@ -88,7 +90,14 @@ test("worker boundary: cyclic structured cause → rejects a reply accepted with
88
90
  await t.test(`cyclic=${cyclic}`, async (t) => {
89
91
  const cause: Cause = { code: "EIO", message: "worker failure" };
90
92
  if (cyclic) cause.cause = cause;
91
- const reply = { error: { code: "NO_MATCH", message: "no match", facts: { rule: 0 }, cause } };
93
+ const reply = {
94
+ error: {
95
+ code: "NO_MATCH",
96
+ message: "no match",
97
+ facts: { unmatched: ["replacements[0]"] },
98
+ cause,
99
+ },
100
+ };
92
101
  const emit = Worker.prototype.emit;
93
102
  t.mock.method(
94
103
  Worker.prototype,
@@ -103,10 +112,11 @@ test("worker boundary: cyclic structured cause → rejects a reply accepted with
103
112
  assert.ok(error instanceof HashlineError);
104
113
  if (cyclic) {
105
114
  assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
106
- assert.match(error.message, /invalid result/i);
115
+ assert.ok(error.cause instanceof RangeError);
107
116
  } else {
108
117
  assert.equal(error.errorCode, "NO_MATCH");
109
- assert.deepEqual(error.facts, { rule: 0 });
118
+ assert.equal(error.message, reply.error.message);
119
+ assert.deepEqual(error.facts, reply.error.facts);
110
120
  assert.deepEqual(causeOf(error.cause, DEFAULT_OUTPUT_BUDGETS.fieldBytes), cause);
111
121
  }
112
122
  return true;
@@ -64,27 +64,25 @@ test("live preparation failure → replays diagnostic after fresh registration",
64
64
  const tool = second.session.getToolDefinition("edit");
65
65
  assert.ok(tool?.renderResult);
66
66
  for (const expanded of [false, true]) {
67
- for (let rendering = 0; rendering < 2; rendering++) {
68
- const decoded = JSON.parse(serialized);
69
- const component = tool.renderResult(decoded, { expanded, isPartial: false }, theme, {
70
- args,
71
- toolCallId: "invalid-edit",
72
- cwd: second.cwd,
73
- state: {},
74
- invalidate() {},
75
- lastComponent: undefined,
76
- executionStarted: true,
77
- argsComplete: true,
78
- expanded,
79
- isPartial: false,
80
- showImages: false,
81
- isError: true,
82
- });
83
- const shown = stripVTControlCharacters(component.render(240).join("\n"));
84
- assert.match(shown, /edits\[0\]\.body: is empty/);
85
- assert.equal(shown.split("edits[0].body: is empty").length - 1, 1);
86
- assert.doesNotMatch(shown, /"issues":/);
87
- assert.equal(JSON.stringify(decoded), serialized);
88
- }
67
+ const decoded = JSON.parse(serialized);
68
+ const component = tool.renderResult(decoded, { expanded, isPartial: false }, theme, {
69
+ args,
70
+ toolCallId: "invalid-edit",
71
+ cwd: second.cwd,
72
+ state: {},
73
+ invalidate() {},
74
+ lastComponent: undefined,
75
+ executionStarted: true,
76
+ argsComplete: true,
77
+ expanded,
78
+ isPartial: false,
79
+ showImages: false,
80
+ isError: true,
81
+ });
82
+ const shown = stripVTControlCharacters(component.render(240).join("\n"));
83
+ assert.match(shown, /edits\[0\]\.body: is empty/);
84
+ assert.equal(shown.split("edits[0].body: is empty").length - 1, 1);
85
+ assert.doesNotMatch(shown, /"issues":/);
86
+ assert.equal(JSON.stringify(decoded), serialized);
89
87
  }
90
88
  });