@criogaid/pi-hashline-edit 0.1.1 → 0.1.2

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.
@@ -19,22 +19,23 @@
19
19
  * @module pi-hashline-edit/pi
20
20
  */
21
21
 
22
- import { generateDiffString, generateUnifiedPatch, withFileMutationQueue, type EditToolDetails } from "@earendil-works/pi-coding-agent";
22
+ import { generateDiffString, generateUnifiedPatch, truncateHead, withFileMutationQueue, type EditToolDetails } from "@earendil-works/pi-coding-agent";
23
23
  import { Type, type Static } from "typebox";
24
24
  import { Text } from "@earendil-works/pi-tui";
25
25
  import { readFile } from "node:fs/promises";
26
26
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
27
- import { commitFile, FileMutationError, type PublicationStatus } from "./file-commit.ts";
28
- import { applyEdits, hashFileLines } from "../core/index.ts";
27
+ import { byteRevision, commitFile, FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
28
+ import { applyEdits, decodeEditableText } from "../core/index.ts";
29
29
  import { splitLines } from "../core/lines.ts";
30
30
  import type { ApplyFailure, Edit } from "../core/types.ts";
31
31
  import { canonicalPath } from "./read-tool.ts";
32
32
  import { getState } from "./state.ts";
33
- import { formatDiffCounts, publishDiffCounts, renderDiffPreview, type DiffCounts } from "./render.ts";
33
+ import { formatDiffCounts, renderMutationResult, type DiffCounts } from "./render.ts";
34
34
  import { formatFailureContext } from "./failure-context.ts";
35
+ import { finalizeMutationResult, formatMutationAnchors } from "./mutation-result.ts";
35
36
 
36
- /** Cap on the number of updated anchors returned inline (bounds token cost for large inserts). */
37
- const MAX_ANCHOR_LINES = 40;
37
+ /** Bound detailed failures before constructing diagnostics; the final message also has a byte cap. */
38
+ const MAX_FAILURE_DETAILS = 40;
38
39
 
39
40
  const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
40
41
 
@@ -74,7 +75,7 @@ const editOpSchema = Type.Object({
74
75
  end: anchorRef(
75
76
  'Inclusive last "LINE#HASH" for replace/delete ranges. Required to change multiple existing lines; omitted means only the anchor line. Omit for insert/append/prepend.',
76
77
  ),
77
- body: Type.Optional(Type.Array(Type.String(), { description: "New content lines (required for replace/insert/append/prepend; omit for delete)" })),
78
+ body: Type.Optional(Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), { description: "New content lines (required for replace/insert/append/prepend; each element must be one logical line without CR/LF; omit for delete)" })),
78
79
  });
79
80
 
80
81
  function createEditSchema(actionFusion: boolean) {
@@ -95,29 +96,29 @@ function formatFailure(
95
96
  failure: ApplyFailure,
96
97
  snapshot: Readonly<{ currentText: string; hashLen: number }>,
97
98
  ): string {
98
- if (failure.kind === "range") return failure.message;
99
- if (failure.kind === "noop") return failure.message;
99
+ if (failure.kind !== "anchor") return failure.message;
100
100
 
101
101
  const lines: string[] = [];
102
102
  let found = 0;
103
103
  let ambiguous = 0;
104
104
  let none = 0;
105
105
  for (const f of failure.failures) {
106
+ if (f.recovery.kind === "found") found++;
107
+ else if (f.recovery.kind === "ambiguous") ambiguous++;
108
+ else none++;
109
+ if (lines.length >= MAX_FAILURE_DETAILS) continue;
106
110
  const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
107
111
  switch (f.recovery.kind) {
108
112
  case "found":
109
- found++;
110
- lines.push(`• ${where}: content shifted. Resend with ${f.which} "${f.recovery.newLine}#${f.recovery.newHash}".`);
113
+ lines.push(`• ${where}: checksum-matching candidate. Resend with ${f.which} "${f.recovery.newLine}#${f.recovery.newHash}" after checking the target.`);
111
114
  break;
112
115
  case "ambiguous": {
113
- ambiguous++;
114
- const nums = f.recovery.candidates.map((candidate) => candidate.line).join(", ");
115
- const list = f.recovery.candidates.map((candidate) => `"${candidate.line}#${candidate.hash}"`).join(" / ");
116
- lines.push(`• ${where}: ambiguous — same content at lines ${nums}. Pick the right one and resend ${f.which} ${list}.`);
116
+ const list = f.recovery.candidates.slice(0, 8).map((candidate) => `"${candidate.line}#${candidate.hash}"`).join(" / ");
117
+ const more = f.recovery.candidates.length > 8 ? ` (${f.recovery.candidates.length - 8} more candidates omitted; use read)` : "";
118
+ lines.push(`• ${where}: ambiguous checksum matches. Inspect the target and resend ${f.which} ${list}${more}.`);
117
119
  break;
118
120
  }
119
121
  case "none":
120
- none++;
121
122
  lines.push(
122
123
  `• ${where}: original content not found within the configured shift-recovery window.` +
123
124
  (f.current === null ? " Cited line is out of range." : ""),
@@ -129,11 +130,15 @@ function formatFailure(
129
130
  if (found) parts.push(`${found} shifted`);
130
131
  if (ambiguous) parts.push(`${ambiguous} ambiguous`);
131
132
  if (none) parts.push(`${none} unresolved`);
132
- return [
133
+ const message = [
133
134
  `Anchor mismatch: ${parts.join(", ")}.`,
134
135
  "No changes written by this edit batch.",
135
136
  ...lines,
137
+ ...(failure.failures.length > lines.length ? [`${failure.failures.length - lines.length} failure details omitted; use read to inspect remaining targets.`] : []),
136
138
  ].join("\n") + formatFailureContext(snapshot.currentText, failure.failures, snapshot.hashLen);
139
+ const notice = "\nDiagnostic output truncated at 16 KiB. Use read to inspect omitted targets.";
140
+ const bounded = truncateHead(message, { maxBytes: 16 * 1024 - Buffer.byteLength(notice) });
141
+ return bounded.content + (bounded.truncated ? notice : "");
137
142
  }
138
143
 
139
144
  /** Translate JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
@@ -171,31 +176,13 @@ function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } |
171
176
  return { ok: true, edits };
172
177
  }
173
178
 
174
- /**
175
- * Fail the edit by throwing. pi's contract: a tool failure is signaled by throwing,
176
- * not by returning `{ isError: true }` — the framework derives `context.isError` from
177
- * whether execute threw, and overwrites `result.isError` with it
178
- * (`updateResult({ ...result, isError: event.isError })`). Returning an isError object
179
- * left the TUI rendering failures as success (green). The thrown message reaches the
180
- * LLM verbatim; renderResult shows its first line in red.
181
- */
182
- function errResult(text: string): never {
183
- throw new Error(text);
184
- }
185
-
186
179
  /**
187
180
  * Format the updated anchors (fresh LINE#HASH│content) for the touched new-file
188
181
  * lines, so the model can chain edits without a re-read. Capped to bound tokens.
189
182
  */
190
183
  function formatUpdatedAnchors(newText: string, touched: readonly number[], hashLen: number): string {
191
- const newLines = splitLines(newText);
192
- const newHashes = hashFileLines(newLines, hashLen);
193
184
  const idxs = [...new Set(touched)].sort((a, b) => a - b);
194
- if (idxs.length === 0) return "";
195
- const rows = idxs.map((i) => `${i + 1}#${newHashes[i]}│${newLines[i]}`);
196
- const shown = rows.length > MAX_ANCHOR_LINES ? rows.slice(0, MAX_ANCHOR_LINES) : rows;
197
- const more = rows.length > MAX_ANCHOR_LINES ? `\n… (${rows.length - MAX_ANCHOR_LINES} more; re-read for full anchors)` : "";
198
- return `\nUpdated anchors (use these for the next edit):\n${shown.join("\n")}${more}`;
185
+ return formatMutationAnchors(splitLines(newText), idxs, hashLen, "Updated anchors (use these for the next edit):");
199
186
  }
200
187
 
201
188
  /** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
@@ -235,29 +222,8 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
235
222
  return text;
236
223
  },
237
224
 
238
- renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
239
- if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", "Editing…"), 0, 0);
240
- const content = result.content?.[0];
241
- if (context.isError) {
242
- const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
243
- return new Text(theme.fg("error", t), 0, 0);
244
- }
245
- const diff: string | undefined = result.details?.diff;
246
- // refresh the call header's +N -N in place — never invalidate from
247
- // inside a renderer (re-enters updateDisplay, diff renders twice)
248
- publishDiffCounts(diff, context, (counts) => {
249
- context.state?.callText?.setText(editHeader(context.args, theme, counts));
250
- });
251
- if (!diff) {
252
- // No net diff (e.g. a successful but non-mutating edit): show only the summary
253
- // line — content.text also carries `Updated anchors` (hashline) for the model.
254
- const summary = content?.type === "text" ? content.text.split("\n")[0] : "Edited";
255
- return new Text(theme.fg("success", summary), 0, 0);
256
- }
257
- // details.diff is pi-format (+N/-N/<space>N content); renderDiff handles
258
- // semantic colors plus intra-line change highlighting
259
- const rendered = renderDiffPreview(diff, expanded, theme);
260
- return new Text(rendered, 0, 0);
225
+ renderResult(result: any, options: any, theme: any, context: any) {
226
+ return renderMutationResult(result, options, theme, context, "Editing…", "Edited", editHeader);
261
227
  },
262
228
 
263
229
  async execute(toolCallId: string, params: EditParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
@@ -267,7 +233,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
267
233
  let mutationAnchors = "";
268
234
  const mutate = () => {
269
235
  const path = mutationParams.path;
270
- if (!mutationParams.edits?.length) return errResult(`Edit ${path}: \`edits\` is empty or missing.`);
236
+ if (!mutationParams.edits?.length) throw new Error(`Edit ${path}: \`edits\` is empty or missing.`);
271
237
  return withFileMutationQueue(absolutePath, () => runHashline(
272
238
  absolutePath,
273
239
  path,
@@ -284,7 +250,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
284
250
  : block,
285
251
  ),
286
252
  });
287
- if (!fusion) return finalizeMutation(await mutate(), true);
253
+ if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
288
254
  return fusion({
289
255
  toolCallId,
290
256
  absolutePath,
@@ -309,17 +275,20 @@ async function runHashline(
309
275
  const { hashLen, shiftRadius } = getState().config;
310
276
 
311
277
  let currentText: string;
278
+ let baseRevision: string;
312
279
  try {
313
- currentText = (await readFile(absPath)).toString("utf-8");
280
+ const currentBytes = await readFile(absPath);
281
+ baseRevision = byteRevision(currentBytes);
282
+ currentText = decodeEditableText(currentBytes);
314
283
  } catch (e) {
315
284
  const msg = e instanceof Error ? e.message : String(e);
316
- return errResult(`Error reading ${displayPath}: ${msg}`);
285
+ throw new Error(`Error reading ${displayPath}: ${msg}`);
317
286
  }
318
287
  // Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
319
- if (signal?.aborted) return errResult(`Edit ${displayPath} aborted before apply.`);
288
+ if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before apply.`);
320
289
 
321
290
  const translated = toCoreEdits(editOps);
322
- if (!translated.ok) return errResult(translated.error);
291
+ if (!translated.ok) throw new Error(translated.error);
323
292
 
324
293
  // Anchors are verified against the current content. A line that changed (or a
325
294
  // hash the model didn't actually read) fails its own anchor — but first we try
@@ -328,24 +297,27 @@ async function runHashline(
328
297
  // the batch are collected (nothing written on any failure).
329
298
  const result = applyEdits(currentText, translated.edits, hashLen, shiftRadius);
330
299
  if (!result.ok) {
331
- return errResult(formatFailure(result.failure, { currentText, hashLen }));
300
+ throw new Error(formatFailure(result.failure, { currentText, hashLen }));
332
301
  }
333
302
 
334
303
  // Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
335
- if (signal?.aborted) return errResult(`Edit ${displayPath} aborted before write.`);
304
+ if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before write.`);
336
305
 
337
306
  let publication: PublicationStatus = "NOT_PUBLISHED";
307
+ let versions: MutationVersions;
338
308
  try {
339
- publication = (await commitFile(absPath, result.text, { mode: "overwrite", signal })).publication;
309
+ const commit = await commitFile(absPath, result.text, { mode: "overwrite", expectedRevision: baseRevision, signal });
310
+ publication = commit.publication;
311
+ versions = commit;
340
312
  } catch (e) {
341
313
  if (e instanceof FileMutationError) throw e;
342
314
  throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
343
315
  }
344
316
 
345
- let details: EditToolDetails & { publication: PublicationStatus };
317
+ let details: EditToolDetails & MutationVersions & { publication: PublicationStatus; revision: string };
346
318
  let anchors: string;
347
319
  try {
348
- // diff 和 anchors 的计算属于发布后的后处理;失败时仍保留 publication。
320
+ // Diff and anchor generation happens after publication; preserve that state on failure.
349
321
  const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
350
322
  const newLf = result.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
351
323
  const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
@@ -354,6 +326,8 @@ async function runHashline(
354
326
  patch: generateUnifiedPatch(displayPath, oldLf, newLf),
355
327
  firstChangedLine,
356
328
  publication,
329
+ ...versions,
330
+ revision: versions.publishedRevision,
357
331
  };
358
332
  anchors = formatUpdatedAnchors(result.text, result.touchedLines, hashLen);
359
333
  onAnchors(anchors);
@@ -19,6 +19,7 @@ import { createActionFusionExecutor } from "./action-fusion.ts";
19
19
  import { getState } from "./state.ts";
20
20
  import { computeLineHash } from "../core/hash.ts";
21
21
  import { splitLines } from "../core/lines.ts";
22
+ import { byteRevision } from "./file-commit.ts";
22
23
 
23
24
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
24
25
  const dir = await mkdtemp(join(tmpdir(), "hl-"));
@@ -517,5 +518,53 @@ test("failed commands preserve mutation results and stay out of all main card re
517
518
  assert.doesNotMatch(rendered.render(120).join("\n"), /command-only diagnostic|then_run:failed/);
518
519
  assert.equal(await readFile(join(dir, args.path), "utf8"), expected);
519
520
  }
520
- assert.deepEqual(commands, ["waiting", "running", "failed", "waiting", "running", "failed", "waiting", "running", "failed"]);
521
+ assert.deepEqual(commands, cases.flatMap(() => ["waiting", "waiting", "running", "failed"]));
522
+ }));
523
+
524
+ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source bytes", async () => withDir(async (dir) => {
525
+ const target = join(dir, "invalid-utf8.txt");
526
+ const original = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
527
+ await writeFile(target, original);
528
+ await assert.rejects(call(makeReadOverride(dir), { path: "invalid-utf8.txt" }), /UNSUPPORTED_ENCODING/);
529
+ await assert.rejects(call(makeEditOverride(dir), { path: "invalid-utf8.txt", edits: [{ op: "append", body: ["x"] }] }), /UNSUPPORTED_ENCODING/);
530
+ await assert.rejects(call(makeReplaceTool(dir), { path: "invalid-utf8.txt", find: "a", replace: "b" }), /UNSUPPORTED_ENCODING/);
531
+ assert.deepEqual(await readFile(target), original);
532
+
533
+ const nulTarget = join(dir, "nul.txt");
534
+ const nulOriginal = Buffer.from([0x61, 0x00, 0x62]);
535
+ await writeFile(nulTarget, nulOriginal);
536
+ await assert.rejects(call(makeEditOverride(dir), { path: "nul.txt", edits: [{ op: "append", body: ["x"] }] }), /UNSUPPORTED_TEXT/);
537
+ await assert.rejects(call(makeReplaceTool(dir), { path: "nul.txt", find: "a", replace: "b" }), /UNSUPPORTED_TEXT/);
538
+ assert.deepEqual(await readFile(nulTarget), nulOriginal);
539
+ }));
540
+
541
+ test("edit rejects embedded line terminators even when schema validation is bypassed", async () => withDir(async (dir) => {
542
+ const target = join(dir, "body.txt");
543
+ await writeFile(target, "a\n");
544
+ await assert.rejects(call(makeEditOverride(dir), { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] }), /INVALID_BODY/);
545
+ assert.equal(await readFile(target, "utf8"), "a\n");
546
+ assert.throws(() => validateToolArguments(makeEditOverride(dir) as any, { type: "toolCall", id: "body", name: "edit", arguments: { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] } }));
547
+ }));
548
+
549
+ test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () => withDir(async (dir) => {
550
+ const target = join(dir, "bom.txt");
551
+ const original = Buffer.from("\ufeffguard\nold\n", "utf8");
552
+ await writeFile(target, original);
553
+ const result: any = await call(makeEditOverride(dir), { path: "bom.txt", edits: [{ op: "replace", anchor: h("\ufeffguard\nold\n", 2), body: ["new"] }] });
554
+ const expected = Buffer.from("\ufeffguard\nnew\n", "utf8");
555
+ assert.deepEqual(await readFile(target), expected);
556
+ assert.equal(result.details.baseRevision, byteRevision(original));
557
+ assert.equal(result.details.publishedRevision, byteRevision(expected));
558
+ assert.equal(result.details.observedRevision, result.details.publishedRevision);
559
+ assert.equal(result.details.revision, result.details.publishedRevision);
560
+ }));
561
+
562
+ test("edit and replace reject NUL output without rewriting source bytes", async () => withDir(async (dir) => {
563
+ const target = join(dir, "output.txt");
564
+ const original = Buffer.from("\ufeffbefore\r\n", "utf8");
565
+ await writeFile(target, original);
566
+ await assert.rejects(call(makeEditOverride(dir), { path: "output.txt", edits: [{ op: "append", body: ["bad\0text"] }] }), /UNSUPPORTED_TEXT/);
567
+ assert.deepEqual(await readFile(target), original);
568
+ await assert.rejects(call(makeReplaceTool(dir), { path: "output.txt", find: "before", replace: "bad\0text" }), /UNSUPPORTED_TEXT/);
569
+ assert.deepEqual(await readFile(target), original);
521
570
  }));
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
6
  import { createActionFusionExecutor, ActionFusionError } from "./action-fusion.ts";
7
- import { FileMutationError } from "./file-commit.ts";
7
+ import { byteRevision, FileMutationError } from "./file-commit.ts";
8
8
 
9
9
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
10
10
  const dir = await mkdtemp(join(tmpdir(), "hashline-failure-"));
@@ -12,24 +12,27 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
12
12
  }
13
13
 
14
14
  const context = (cwd: string) => ({ cwd }) as any;
15
- const result = () => ({ content: [{ type: "text" as const, text: "mutation" }], details: { publication: "PUBLISHED" } });
15
+ const result = (content: string) => ({ content: [{ type: "text" as const, text: "mutation" }], details: { publication: "PUBLISHED", publishedRevision: byteRevision(content) } });
16
16
 
17
17
  test("published post-processing failure skips command and preserves publication state", async () => withTemp(async (dir) => {
18
18
  const target = join(dir, "published.txt");
19
19
  await writeFile(target, "content\n");
20
20
  let commanded = false;
21
+ const updates: any[] = [];
21
22
  const fusion = createActionFusionExecutor(async () => { commanded = true; return "never"; });
22
23
  await assert.rejects(
23
- fusion({ toolCallId: "published", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { throw new FileMutationError("post_process", "PUBLISHED", "file was published but result generation failed"); }, signal: undefined, ctx: context(dir) }),
24
+ fusion({ toolCallId: "published", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { throw new FileMutationError("post_process", "PUBLISHED", "file was published but result generation failed"); }, signal: undefined, ctx: context(dir), onUpdate: (update) => updates.push(update) }),
24
25
  (error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded,
25
26
  );
27
+ assert.ok(updates.every((update) => update.details.actionFusion.mutationCompleted === false));
28
+ assert.equal(updates.at(-1).details.actionFusion.publication, "PUBLISHED");
26
29
  }));
27
30
 
28
31
  test("command failure still reports final changed freshness", async () => withTemp(async (dir) => {
29
32
  const target = join(dir, "failed.txt");
30
33
  await writeFile(target, "before\n");
31
34
  const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); throw new Error("command failed"); });
32
- const outcome: any = await fusion({ toolCallId: "failed", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { await writeFile(target, "mutation\n"); return result(); }, signal: undefined, ctx: context(dir) });
35
+ const outcome: any = await fusion({ toolCallId: "failed", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { await writeFile(target, "mutation\n"); return result("mutation\n"); }, signal: undefined, ctx: context(dir) });
33
36
  assert.deepEqual(outcome.details.actionFusion, { publication: "PUBLISHED", command: "failed", freshness: "changed" });
34
37
  assert.match(outcome.content[1].text, /Re-read the file/);
35
38
  }));
@@ -40,7 +43,7 @@ test("timeout and cancellation do not rerun mutation and still inspect freshness
40
43
  let mutations = 0;
41
44
  const controller = new AbortController();
42
45
  const fusion = createActionFusionExecutor(async () => { controller.abort(); throw new Error("timed out"); });
43
- const outcome: any = await fusion({ toolCallId: "cancelled", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { mutations++; await writeFile(target, "mutation\n"); return result(); }, signal: controller.signal, ctx: context(dir) });
46
+ const outcome: any = await fusion({ toolCallId: "cancelled", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { mutations++; await writeFile(target, "mutation\n"); return result("mutation\n"); }, signal: controller.signal, ctx: context(dir) });
44
47
  assert.equal(outcome.details.actionFusion.command, "cancelled");
45
48
  assert.equal(outcome.details.actionFusion.freshness, "unchanged");
46
49
  assert.equal(mutations, 1);
@@ -51,10 +54,10 @@ test("queue is released after a failed command", async () => withTemp(async (dir
51
54
  await writeFile(target, "before\n");
52
55
  let calls = 0;
53
56
  const fusion = createActionFusionExecutor(async () => { calls++; if (calls === 1) throw new Error("first command failed"); return "ok"; });
54
- const first = fusion({ toolCallId: "first", absolutePath: target, thenRun: { command: "fail" }, mutate: async () => { await writeFile(target, "first\n"); return result(); }, signal: undefined, ctx: context(dir) });
57
+ const first = fusion({ toolCallId: "first", absolutePath: target, thenRun: { command: "fail" }, mutate: async () => { await writeFile(target, "first\n"); return result("first\n"); }, signal: undefined, ctx: context(dir) });
55
58
  const failed: any = await first;
56
59
  assert.equal(failed.details.actionFusion.command, "failed");
57
- const second = await fusion({ toolCallId: "second", absolutePath: target, thenRun: { command: "ok" }, mutate: async () => { await writeFile(target, "second\n"); return result(); }, signal: undefined, ctx: context(dir) });
60
+ const second = await fusion({ toolCallId: "second", absolutePath: target, thenRun: { command: "ok" }, mutate: async () => { await writeFile(target, "second\n"); return result("second\n"); }, signal: undefined, ctx: context(dir) });
58
61
  assert.equal(calls, 2);
59
62
  assert.match(second.content[1].type === "text" ? second.content[1].text : "", /then_run:succeeded/);
60
63
  }));
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
6
  import { spawn } from "node:child_process";
7
- import { commitFile, FileMutationError, fileRevision } from "./file-commit.ts";
7
+ import { byteRevision, commitFile, FileMutationError, fileRevision } from "./file-commit.ts";
8
8
  import { createActionFusionExecutor } from "./action-fusion.ts";
9
9
  import { makeWriteOverride } from "./write-tool.ts";
10
10
 
@@ -198,3 +198,31 @@ test("cancellation racing publication never reports a settled operation as unpub
198
198
  const finalContent = await readFile(target, "utf8");
199
199
  assert.ok(finalContent === oldContent || finalContent === newContent);
200
200
  }));
201
+
202
+ test("commit result binds base, published, and observed revisions", async () => withTemp(async (dir) => {
203
+ const target = join(dir, "versions.txt");
204
+ await writeFile(target, "before\n");
205
+ const baseRevision = await fileRevision(target);
206
+ const result = await commitFile(target, "after\n", { mode: "overwrite", expectedRevision: baseRevision });
207
+ assert.equal(result.baseRevision, baseRevision);
208
+ assert.equal(result.publishedRevision, byteRevision("after\n"));
209
+ assert.equal(result.observedRevision, result.publishedRevision);
210
+ assert.equal(result.revision, result.publishedRevision);
211
+ }));
212
+
213
+ test("commit rejects lossy UTF-8 output before modifying or creating files", async () => withTemp(async (dir) => {
214
+ const existing = join(dir, "existing.txt");
215
+ const missing = join(dir, "missing.txt");
216
+ await writeFile(existing, "original\n");
217
+ for (const content of ["\ud800", "\udfff", "before\ud800after"]) {
218
+ for (const path of [existing, missing]) {
219
+ await assert.rejects(commitFile(path, content), (error: any) => error.publication === "NOT_PUBLISHED" && /INVALID_UNICODE/.test(error.message));
220
+ }
221
+ }
222
+ assert.equal(await readFile(existing, "utf8"), "original\n");
223
+ await assert.rejects(readFile(missing), { code: "ENOENT" });
224
+ const content = "\uFEFFvalid 😀\r\n";
225
+ const result = await commitFile(existing, content);
226
+ assert.deepEqual(await readFile(existing), Buffer.from(content));
227
+ assert.equal(result.publishedRevision, byteRevision(Buffer.from(content)));
228
+ }));
@@ -11,8 +11,15 @@ export interface CommitOptions {
11
11
  signal?: AbortSignal;
12
12
  }
13
13
 
14
- export interface CommitResult {
14
+ export interface MutationVersions {
15
+ baseRevision?: string;
16
+ publishedRevision: string;
17
+ observedRevision: string;
18
+ }
19
+
20
+ export interface CommitResult extends MutationVersions {
15
21
  created: boolean;
22
+ /** Backward-compatible alias for publishedRevision. */
16
23
  revision: string;
17
24
  publication: "PUBLISHED";
18
25
  }
@@ -29,8 +36,12 @@ export class FileMutationError extends Error {
29
36
  }
30
37
  }
31
38
 
39
+ export function byteRevision(content: string | Uint8Array): string {
40
+ return createHash("sha256").update(content).digest("hex");
41
+ }
42
+
32
43
  export async function fileRevision(path: string): Promise<string> {
33
- return createHash("sha256").update(await readFile(path)).digest("hex");
44
+ return byteRevision(await readFile(path));
34
45
  }
35
46
 
36
47
  function prepareError(message: string, cause?: unknown): FileMutationError {
@@ -89,11 +100,11 @@ async function inspectTarget(path: string): Promise<TargetInfo> {
89
100
  };
90
101
  }
91
102
 
92
- async function writeAndSyncTemp(tempPath: string, content: string, modeBits: number | undefined, signal: AbortSignal | undefined): Promise<void> {
103
+ async function writeAndSyncTemp(tempPath: string, content: Buffer, modeBits: number | undefined, signal: AbortSignal | undefined): Promise<void> {
93
104
  signal?.throwIfAborted();
94
105
  const handle = await open(tempPath, "w", modeBits === undefined ? 0o600 : modeBits & 0o7777);
95
106
  try {
96
- await handle.writeFile(content, "utf8");
107
+ await handle.writeFile(content);
97
108
  await handle.sync();
98
109
  } finally {
99
110
  await handle.close();
@@ -134,8 +145,11 @@ async function syncDirectory(path: string): Promise<void> {
134
145
  }
135
146
  }
136
147
 
137
- /** 统一 mutation 提交:先准备并同步临时文件,再按创建/替换语义发布;调用方负责外层文件队列。 */
148
+ /** Prepare and sync exact UTF-8 bytes before publication; callers own the outer file queue. */
138
149
  export async function commitFile(path: string, content: string, options: CommitOptions = {}): Promise<CommitResult> {
150
+ if (content.includes("\0")) throw prepareError("UNSUPPORTED_TEXT: NUL bytes are not editable.");
151
+ const bytes = Buffer.from(content, "utf8");
152
+ if (bytes.toString("utf8") !== content) throw prepareError("INVALID_UNICODE: content cannot be encoded losslessly as UTF-8.");
139
153
  const target = await inspectTarget(path);
140
154
  const mode = options.mode ?? (target.existed ? "overwrite" : "create");
141
155
  if (mode === "create" && target.existed) throw prepareError("target already exists; use mode=overwrite");
@@ -159,13 +173,31 @@ export async function commitFile(path: string, content: string, options: CommitO
159
173
  let published = false;
160
174
  let failure: unknown;
161
175
  try {
162
- await writeAndSyncTemp(tempPath, content, target.modeBits, options.signal);
176
+ await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
177
+ if (mode === "overwrite" && options.expectedRevision !== undefined) {
178
+ let currentRevision: string;
179
+ try {
180
+ currentRevision = await fileRevision(publishPath);
181
+ } catch (error) {
182
+ throw prepareError(`unable to recheck target revision: ${error instanceof Error ? error.message : String(error)}`, error);
183
+ }
184
+ if (currentRevision !== options.expectedRevision) throw prepareError("expectedRevision changed before publication");
185
+ }
163
186
  if (mode === "create") await publishCreate(tempPath, publishPath, options.signal);
164
187
  else await publishReplace(tempPath, publishPath, options.signal);
165
188
  published = true;
166
189
  await syncDirectory(publishDirectory);
167
190
  try {
168
- return { created: mode === "create", revision: await fileRevision(publishPath), publication: "PUBLISHED" };
191
+ const publishedRevision = byteRevision(bytes);
192
+ const observedRevision = await fileRevision(publishPath);
193
+ return {
194
+ created: mode === "create",
195
+ baseRevision: target.beforeRevision,
196
+ publishedRevision,
197
+ observedRevision,
198
+ revision: publishedRevision,
199
+ publication: "PUBLISHED",
200
+ };
169
201
  } catch (error) {
170
202
  throw new FileMutationError("post_process", "PUBLISHED", `target was published but final revision could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
171
203
  }
@@ -32,7 +32,7 @@ function harness(entries: any[] = []) {
32
32
 
33
33
  const waiting: ActionFusionProgress = {
34
34
  toolCallId: "call-1", path: "file.ts", commandText: "npm test", command: "waiting",
35
- publication: "NOT_PUBLISHED", freshness: "unknown", output: "",
35
+ publication: "NOT_PUBLISHED", freshness: "unknown", output: "", mutationCompleted: false,
36
36
  };
37
37
 
38
38
  test("one independent card updates live and only persists its endpoints", () => {
@@ -35,8 +35,9 @@ import { Type } from "typebox";
35
35
  import { Text } from "@earendil-works/pi-tui";
36
36
  import { readFile, realpath, stat } from "node:fs/promises";
37
37
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
38
- import { hashFileLines } from "../core/hash.ts";
38
+ import { computeLineHash } from "../core/hash.ts";
39
39
  import { splitLines } from "../core/lines.ts";
40
+ import { decodeEditableText } from "../core/text.ts";
40
41
  import { getState } from "./state.ts";
41
42
  import { canonicalPath } from "./read-tool.ts";
42
43
  import { parseHashline } from "./render.ts";
@@ -59,7 +60,6 @@ const DEFAULT_LIMIT = 100;
59
60
  /** Max chars per result line for display (mirrors pi's truncate.ts; not exported there). */
60
61
  const GREP_MAX_LINE_LENGTH = 500;
61
62
  const GREP_CONTEXT_MAX = 20;
62
- const WILDCARD_ONLY_REGEX = /^(?:\^?\.(?:[*+?][+?]?)?\$?|[*+?])$/;
63
63
  const MAX_ALL_PATTERNS = 16;
64
64
  // ponytail: finite batches bound candidate buffers but still spawn per batch; revisit streaming for sustained large scans.
65
65
  const FILTER_BATCH_SIZE = 4096;
@@ -120,7 +120,7 @@ function clampContext(context: number | undefined): number {
120
120
  const grepOverrideSchema = Type.Object({
121
121
  pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
122
122
  description:
123
- "Non-empty pattern(s). Arrays use matchMode. Wildcard-only searches require literal:true.",
123
+ "Non-empty pattern(s). Arrays use matchMode.",
124
124
  }),
125
125
  matchMode: Type.Optional(
126
126
  Type.Union([Type.Literal("any"), Type.Literal("all")], {
@@ -331,7 +331,7 @@ async function scanPatternRanges(
331
331
  if (!files.includes(filePath)) throw new Error("ripgrep returned an unexpected search path");
332
332
  let lineCount = lineCounts.get(filePath);
333
333
  if (lineCount === undefined) {
334
- lineCount = splitLines((await readFile(filePath)).toString("utf8")).length;
334
+ lineCount = splitLines(decodeEditableText(await readFile(filePath))).length;
335
335
  lineCounts.set(filePath, lineCount);
336
336
  }
337
337
  const bytes = rgBytes(data.lines);
@@ -587,14 +587,6 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
587
587
  if (patterns.some((pattern) => pattern.trim() === "")) {
588
588
  throw new Error("pattern must not be empty");
589
589
  }
590
- if (params.literal !== true) {
591
- const wildcard = patterns.find((pattern) => WILDCARD_ONLY_REGEX.test(pattern.trim()));
592
- if (wildcard !== undefined) {
593
- throw new Error(
594
- `Pattern ${JSON.stringify(wildcard)} is wildcard-only; use read for a known file or provide a concrete substring or identifier`,
595
- );
596
- }
597
- }
598
590
 
599
591
  const rgPath = bundledRgPath;
600
592
  const excludes = toArray(params.excludePattern);
@@ -753,29 +745,23 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
753
745
  }
754
746
  for (const lines of byFile.values()) lines.sort((a, b) => a - b);
755
747
 
756
- // Read each file once and hash all its lines; hash is computed from the FULL line.
757
- const fileCache = new Map<string, { lines: string[]; hashes: string[] }>();
748
+ // Read each file once; only hash the selected match/context rows below.
758
749
  const getFile = async (filePath: string) => {
759
- let entry = fileCache.get(filePath);
760
- if (!entry) {
761
- let content: string;
762
- try {
763
- content = (await readFile(filePath)).toString("utf-8");
764
- } catch (error) {
765
- if (strictIdentities) throw error;
766
- content = "";
767
- }
768
- if (strictIdentities) {
769
- const baseline = strictIdentities.get(filePath);
770
- if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
771
- throw new Error("File changed during search; rerun the query.");
772
- }
750
+ let bytes: Buffer;
751
+ try {
752
+ bytes = await readFile(filePath);
753
+ } catch (error) {
754
+ if (strictIdentities) throw error;
755
+ bytes = Buffer.alloc(0);
756
+ }
757
+ const content = decodeEditableText(bytes);
758
+ if (strictIdentities) {
759
+ const baseline = strictIdentities.get(filePath);
760
+ if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
761
+ throw new Error("File changed during search; rerun the query.");
773
762
  }
774
- const lines = splitLines(content);
775
- entry = { lines, hashes: hashFileLines(lines, hashLen) };
776
- fileCache.set(filePath, entry);
777
763
  }
778
- return entry;
764
+ return splitLines(content);
779
765
  };
780
766
 
781
767
  const formatPath = (filePath: string): string => {
@@ -789,7 +775,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
789
775
  const blocks: string[] = [];
790
776
  if (outputMode === "content") {
791
777
  for (const [filePath, matchLines] of byFile) {
792
- const { lines, hashes } = await getFile(filePath);
778
+ const lines = await getFile(filePath);
793
779
  // Context windows are rebuilt from surviving matches so context
794
780
  // lines of a filtered-out match never leak.
795
781
  const windowSet = new Set<number>();
@@ -804,7 +790,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
804
790
  const rows: string[] = [];
805
791
  for (const n of [...windowSet].sort((a, b) => a - b)) {
806
792
  const content = lines[n - 1] ?? "";
807
- const hash = hashes[n - 1] ?? "";
793
+ const hash = n <= lines.length ? computeLineHash(n, content, hashLen) : "";
808
794
  const { text: display, wasTruncated } = truncateLine(content.replace(/\r/g, ""));
809
795
  if (wasTruncated) linesTruncated = true;
810
796
  rows.push(`${n}#${hash}│${display}`);