@criogaid/pi-hashline-edit 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +77 -23
  2. package/package.json +1 -1
  3. package/src/core/apply.test.ts +87 -10
  4. package/src/core/apply.ts +106 -84
  5. package/src/core/lines.test.ts +12 -1
  6. package/src/core/lines.ts +43 -1
  7. package/src/core/ranges.test.ts +28 -0
  8. package/src/core/ranges.ts +25 -0
  9. package/src/core/text.ts +5 -0
  10. package/src/core/types.ts +37 -20
  11. package/src/integration/grep-rg.test.ts +188 -1
  12. package/src/pi/action-fusion.test.ts +3 -1
  13. package/src/pi/action-fusion.ts +38 -35
  14. package/src/pi/anchor-format.test.ts +30 -0
  15. package/src/pi/anchor-format.ts +28 -0
  16. package/src/pi/config.ts +1 -1
  17. package/src/pi/edit-tool.ts +91 -100
  18. package/src/pi/execute.test.ts +239 -14
  19. package/src/pi/failure-context.test.ts +99 -62
  20. package/src/pi/failure-context.ts +67 -64
  21. package/src/pi/failure-path.test.ts +20 -2
  22. package/src/pi/file-commit.test.ts +21 -0
  23. package/src/pi/file-commit.ts +35 -3
  24. package/src/pi/fusion-card.test.ts +38 -1
  25. package/src/pi/fusion-card.ts +41 -17
  26. package/src/pi/grep-tool.ts +84 -55
  27. package/src/pi/grep.test.ts +77 -6
  28. package/src/pi/mutation-result.ts +48 -9
  29. package/src/pi/path.ts +22 -0
  30. package/src/pi/pi.test.ts +64 -2
  31. package/src/pi/read-tool.ts +9 -30
  32. package/src/pi/registration.test.ts +28 -1
  33. package/src/pi/render.test.ts +111 -0
  34. package/src/pi/render.ts +30 -6
  35. package/src/pi/replace-tool.ts +144 -140
  36. package/src/pi/replace.test.ts +193 -1
  37. package/src/pi/result-safety.test.ts +241 -8
  38. package/src/pi/rg-line-filter.test.ts +7 -1
  39. package/src/pi/rg-line-filter.ts +10 -12
  40. package/src/pi/rg-line-ranges.test.ts +10 -0
  41. package/src/pi/rg-line-ranges.ts +21 -15
  42. package/src/pi/rg-text-view.ts +88 -0
  43. package/src/pi/write-tool.ts +13 -47
  44. package/src/pi/write.test.ts +25 -36
@@ -10,7 +10,11 @@ import { join } from "node:path";
10
10
  import { rgPath } from "@vscode/ripgrep";
11
11
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
12
12
  import { makeEditOverride } from "../pi/edit-tool.ts";
13
+ import { makeReadOverride } from "../pi/read-tool.ts";
14
+ import { makeWriteOverride } from "../pi/write-tool.ts";
15
+ import { makeReplaceTool } from "../pi/replace-tool.ts";
13
16
  import { COMMON_RG_ARGS, createLinePredicate, resolveIgnoreCase, runRg } from "../pi/rg-line-filter.ts";
17
+ import { computeLineHash } from "../core/hash.ts";
14
18
 
15
19
  const REGEX_MODE = { engine: "default", multiline: false, literal: false } as const;
16
20
 
@@ -151,7 +155,7 @@ test("real rg validates its own regex syntax and limits automatic literal fallba
151
155
  for (const pattern of ["queueTool(", "foo(?=bar)"]) {
152
156
  const result: any = await tool.execute("0", { pattern }, undefined, undefined);
153
157
  assert.ok(result.content[0].text.includes(`│${pattern}`));
154
- assert.match(result.content[0].text, /Invalid regex; searched all patterns as literal text/);
158
+ assert.match(result.content[0].text, /Invalid regex; searched the pattern as literal text/);
155
159
  await assert.rejects(
156
160
  tool.execute("0", { pattern, literal: false }, undefined, undefined),
157
161
  /regex parse error/,
@@ -162,6 +166,12 @@ test("real rg validates its own regex syntax and limits automatic literal fallba
162
166
  const explicit: any = await tool.execute("0", { pattern: "queueTool(", literal: true }, undefined, undefined);
163
167
  assert.match(explicit.content[0].text, /│queueTool\(/);
164
168
  assert.doesNotMatch(explicit.content[0].text, /Invalid regex/);
169
+ for (const params of [
170
+ { pattern: ["queueTool(", "\\bfoo\\b"] },
171
+ { pattern: "queueTool(", excludePattern: "^\\s*//" },
172
+ ]) {
173
+ await assert.rejects(tool.execute("0", params, undefined, undefined), /Invalid regex in compound query/);
174
+ }
165
175
  } finally {
166
176
  await rm(directory, { recursive: true, force: true });
167
177
  }
@@ -435,3 +445,180 @@ test("real rg accepts wildcard-only regexes and preserves limits and literal mod
435
445
  await rm(directory, { recursive: true, force: true });
436
446
  }
437
447
  });
448
+
449
+ test("tools share physical lines and anchors across text representations", async () => {
450
+ const directory = await mkdtemp(join(tmpdir(), "hl-text-integration-"));
451
+ const call = (tool: any, params: any) => tool.execute("0", params, undefined, undefined);
452
+ const rows = (result: any): string[] => result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line));
453
+ try {
454
+ const file = join(directory, "fixture.txt");
455
+ for (const before of [
456
+ "a\nold\n",
457
+ "a\r\nold\r\n",
458
+ "\uFEFFa\r\nold\nkeep\r\n",
459
+ "a\rb\nold\n",
460
+ "a\rb\nold",
461
+ ]) {
462
+ await call(makeWriteOverride(directory), { path: file, content: before });
463
+ assert.equal(await readFile(file, "utf8"), before);
464
+ const read = await call(makeReadOverride(directory), { path: file });
465
+ const grep = await call(makeGrepOverrideWithBackend(directory, {}), { path: file, pattern: "old", context: 2 });
466
+ assert.deepEqual(rows(grep), rows(read));
467
+ if (before.includes("a\rb")) assert.match(rows(read)[0], /│a␍b$/);
468
+ const anchor = rows(grep)[1].split("│")[0];
469
+ const edit = await call(makeEditOverride(directory), { path: file, edits: [{ op: "replace", anchor, body: ["new"] }] });
470
+ assert.equal(await readFile(file, "utf8"), before.replace("old", "new"));
471
+ assert.equal(edit.details.firstChangedLine, 2);
472
+ assert.match(edit.details.diff, /^-2 old/m);
473
+ assert.match(edit.details.diff, /^\+2 new/m);
474
+ assert.ok(!edit.details.diff.includes("\r"));
475
+ if (before.includes("a\rb")) assert.ok(edit.details.patch.includes(" a\rb\n"));
476
+ const editedRead = await call(makeReadOverride(directory), { path: file });
477
+ assert.equal(rows(edit)[0], rows(editedRead)[1].split("│")[0]);
478
+ const replaced = await call(makeReplaceTool(directory), { path: file, find: "new", replace: "next" });
479
+ assert.equal(await readFile(file, "utf8"), before.replace("old", "next"));
480
+ assert.equal(replaced.details.firstChangedLine, 2);
481
+ const replacedRead = await call(makeReadOverride(directory), { path: file });
482
+ assert.equal(rows(replaced)[0], rows(replacedRead)[1].split("│")[0]);
483
+ }
484
+ } finally {
485
+ await rm(directory, { recursive: true, force: true });
486
+ }
487
+ });
488
+
489
+ test("long-line previews expose real rg hits across engines and preserve full-line anchors", async () => {
490
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-preview-"));
491
+ try {
492
+ const long = "😀界".repeat(220) + "NEEDLE" + "tail".repeat(200);
493
+ const context = "x" + "😀".repeat(400);
494
+ await writeFile(join(directory, "long.txt"), `${long}\r\nfollow\r\n${context}\r\n`);
495
+ const tool = makeGrepOverrideWithBackend(directory, {});
496
+ for (const params of [
497
+ { pattern: "NEEDLE" },
498
+ { pattern: ["NEEDLE", "tail"], matchMode: "all", excludePattern: "absent" },
499
+ { pattern: "NEEDLE(?=tail)", pcre2: true },
500
+ { pattern: "NEEDLE(?:tail)+\\r?\\nfollow", multiline: true },
501
+ ]) {
502
+ const result: any = await tool.execute("preview", { ...params, context: 2 }, undefined, undefined);
503
+ const output = result.content[0].text;
504
+ const row = output.split("\n").find((line: string) => line.startsWith("1#"));
505
+ assert.ok(row.startsWith(`1#${computeLineHash(1, long)}│[partial, columns `));
506
+ assert.ok(row.includes("NEEDLE"));
507
+ assert.equal(Buffer.from(row).toString("utf8"), row);
508
+ assert.ok(output.includes(`3#${computeLineHash(3, context)}│[partial, columns 1-499]`));
509
+ assert.match(output, /anchors hash full lines/);
510
+ }
511
+ } finally { await rm(directory, { recursive: true, force: true }); }
512
+ });
513
+
514
+ test("all text tools share logical CRLF matching, anchors, and mutation separators", async () => {
515
+ const directory = await mkdtemp(join(tmpdir(), "hl-shared-text-"));
516
+ try {
517
+ const path = join(directory, "mixed.txt");
518
+ const before = "\uFEFFhead\r\nalpha\r\nbeta\nstand\rCR\r\r\nlast";
519
+ const write = makeWriteOverride(directory);
520
+ const read = makeReadOverride(directory);
521
+ const grep = makeGrepOverrideWithBackend(directory, {});
522
+ await write.execute("write", { path, content: before }, undefined, undefined);
523
+ assert.equal(await readFile(path, "utf8"), before);
524
+ const observed = await read.execute("read", { path }, undefined, undefined);
525
+ assert.ok(observed.content[0].type === "text");
526
+ const rows = observed.content[0].text.split("\n").filter((line: string) => /^\d+#[0-9A-Z]+│/.test(line));
527
+ for (const query of [
528
+ { pattern: "alpha\r\nbeta", literal: true },
529
+ { pattern: "alpha\\nbeta", literal: false },
530
+ { pattern: "alpha\\nbeta", literal: false, pcre2: true },
531
+ { pattern: ["alpha\\nbeta", "alpha|beta"], matchMode: "all", literal: false },
532
+ ]) {
533
+ const found = await grep.execute("grep", { path, multiline: true, ignoreCase: false, ...query }, undefined, undefined);
534
+ assert.ok(found.content[0].text.includes(rows[1]), JSON.stringify(query));
535
+ assert.ok(found.content[0].text.includes(rows[2]), JSON.stringify(query));
536
+ }
537
+ const excluded = await grep.execute("grep", { path, pattern: "alpha\\nbeta", excludePattern: "alpha", multiline: true, literal: false }, undefined, undefined);
538
+ assert.ok(!excluded.content[0].text.includes(rows[1]));
539
+ assert.ok(excluded.content[0].text.includes(rows[2]));
540
+ const carriage = await grep.execute("grep", { path, pattern: "\\r", literal: false }, undefined, undefined);
541
+ assert.ok(carriage.content[0].text.includes(rows[3]));
542
+ assert.ok(!carriage.content[0].text.includes(rows[1]));
543
+ const standaloneEnd = await grep.execute("grep", { path, pattern: "CR\\r$", literal: false }, undefined, undefined);
544
+ assert.ok(standaloneEnd.content[0].text.includes(rows[3]));
545
+
546
+ const expected = "\uFEFFhead\r\nA\r\nB\r\nC\nstand\rCR\r\r\nlast";
547
+ for (const mode of ["edit", "literal", "regex"]) {
548
+ await write.execute("reset", { path, content: before }, undefined, undefined);
549
+ if (mode === "edit") {
550
+ await makeEditOverride(directory).execute("edit", { path, edits: [{ op: "replace", anchor: rows[1].split("│")[0], end: rows[2].split("│")[0], body: ["A", "B", "C"] }] }, undefined, undefined);
551
+ } else {
552
+ await makeReplaceTool(directory).execute("replace", { path, find: mode === "regex" ? "alpha\\nbeta" : "alpha\r\nbeta", replace: "A\nB\nC", regex: mode === "regex" }, undefined, undefined);
553
+ }
554
+ assert.equal(await readFile(path, "utf8"), expected, mode);
555
+ }
556
+ // Whole-file write remains the explicit representation boundary, including EOL conversion.
557
+ await write.execute("convert", { path, content: "alpha\nbeta\n" }, undefined, undefined);
558
+ assert.equal(await readFile(path, "utf8"), "alpha\nbeta\n");
559
+ } finally {
560
+ await rm(directory, { recursive: true, force: true });
561
+ }
562
+ });
563
+
564
+ test("visible source escapes remain readable and searchable while real CRLF stays preserved", async () => {
565
+ const directory = await mkdtemp(join(tmpdir(), "hl-source-escapes-"));
566
+ try {
567
+ const path = join(directory, "escapes.ts");
568
+ const code = 'const eol = "\\r\\n";\r\n';
569
+ await makeWriteOverride(directory).execute("write", { path, content: code }, undefined, undefined);
570
+ const read = await makeReadOverride(directory).execute("read", { path }, undefined, undefined);
571
+ assert.ok(read.content[0].type === "text");
572
+ assert.ok(read.content[0].text.includes(String.raw`const eol = "\r\n";`));
573
+ const grep = makeGrepOverrideWithBackend(directory, {});
574
+ for (const query of [
575
+ { pattern: String.raw`\r\n`, literal: true },
576
+ { pattern: String.raw`\\r\\n`, literal: false },
577
+ { pattern: String.raw`\\r\\n`, literal: false, pcre2: true },
578
+ ]) {
579
+ const result = await grep.execute("grep", { path, ...query, ignoreCase: false }, undefined, undefined);
580
+ assert.ok(result.content[0].text.includes(String.raw`const eol = "\r\n";`));
581
+ }
582
+ const replace = makeReplaceTool(directory);
583
+ await replace.execute("literal", { path, find: String.raw`\r\n`, replace: String.raw`\n` }, undefined, undefined);
584
+ assert.equal(await readFile(path, "utf8"), 'const eol = "\\n";\r\n');
585
+ await replace.execute("regex", { path, find: String.raw`\\n`, replace: String.raw`\r\n`, regex: true }, undefined, undefined);
586
+ assert.equal(await readFile(path, "utf8"), code);
587
+ } finally {
588
+ await rm(directory, { recursive: true, force: true });
589
+ }
590
+ });
591
+
592
+ test("normalized grep batches retain original paths, literal option markers, and decode diagnostics", async () => {
593
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-snapshots-"));
594
+ try {
595
+ await Promise.all(Array.from({ length: 70 }, (_, i) => writeFile(join(directory, `file ${i}.txt`), "--\r\n")));
596
+ await writeFile(join(directory, "invalid.txt"), Buffer.from([0xc3, 0x28]));
597
+ const grep = makeGrepOverrideWithBackend(directory, {});
598
+ const result = await grep.execute("grep", { path: directory, pattern: "--", literal: true, outputMode: "count", limit: 100 }, undefined, undefined);
599
+ assert.equal((result.content[0].text.match(/file \d+\.txt: 1/g) ?? []).length, 70);
600
+ assert.match(result.content[0].text, /Search incomplete/);
601
+ assert.match(result.content[0].text, /invalid\.txt/);
602
+ assert.match(result.content[0].text, /UNSUPPORTED_ENCODING/);
603
+ assert.doesNotMatch(result.content[0].text, /hashline-grep-/);
604
+ } finally {
605
+ await rm(directory, { recursive: true, force: true });
606
+ }
607
+ });
608
+
609
+ test("NUL files are rejected on a confirmed hit, not reported as no match", async () => {
610
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-nul-"));
611
+ try {
612
+ const binary = join(directory, "binary.txt");
613
+ await writeFile(binary, Buffer.from("needle\r\nother\0needle\n"));
614
+ const grep = makeGrepOverrideWithBackend(directory, {});
615
+ await assert.rejects(grep.execute("grep", { path: binary, pattern: "needle", literal: true }, undefined, undefined), /UNSUPPORTED_TEXT/);
616
+ const absent = await grep.execute("grep", { path: binary, pattern: "absent", literal: true }, undefined, undefined);
617
+ assert.equal(absent.content[0].type, "text");
618
+ if (absent.content[0].type === "text") assert.equal(absent.content[0].text, "No matches found");
619
+ await writeFile(join(directory, "valid.txt"), "needle\n");
620
+ await assert.rejects(grep.execute("grep", { path: directory, pattern: "needle", literal: true }, undefined, undefined), /UNSUPPORTED_TEXT/);
621
+ } finally {
622
+ await rm(directory, { recursive: true, force: true });
623
+ }
624
+ });
@@ -228,6 +228,8 @@ test("progress reports skipped mutations and failed commands without rolling bac
228
228
  await assert.rejects(makeEditOverride(dir, fusion).execute("skip", { path: "missing.txt", edits: [{ op: "append", body: ["after"] }], then_run: { command: "check" } }, undefined, undefined, ctx(dir)));
229
229
  assert.equal(commands, 0);
230
230
  assert.deepEqual(events.map((event) => event.command), ["waiting", "skipped"]);
231
+ assert.equal(events.at(-1)!.output, "");
232
+ assert.equal(events.at(-1)!.reason, "Not run because the mutation did not complete.");
231
233
  events.length = 0;
232
234
  await writeFile(join(dir, "replace.txt"), "original\n");
233
235
  await assert.rejects(makeReplaceTool(dir, fusion).execute("replace-skip", { path: "replace.txt", find: "missing", replace: "changed", then_run: { command: "check" } }, undefined, undefined, ctx(dir)), /no matches/);
@@ -238,7 +240,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
238
240
  const failed = await makeWriteOverride(dir, fusion).execute("fail", { path: "failed.txt", content: "published\n", then_run: { command: "check" } }, undefined, undefined, ctx(dir));
239
241
  assert.equal(failed.details.actionFusion.command, "failed");
240
242
  assert.deepEqual(events.map((event) => event.command), ["waiting", "waiting", "running", "failed"]);
241
- assert.match(events.at(-1)!.output, /diagnostic[\s\S]*code 7/);
243
+ assert.equal(events.at(-1)!.output, "diagnostic\nCommand exited with code 7");
242
244
  assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
243
245
  } finally {
244
246
  await rm(dir, { recursive: true, force: true });
@@ -35,7 +35,10 @@ export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command
35
35
  path: string;
36
36
  commandText: string;
37
37
  command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
38
+ /** Command output or command execution errors only. */
38
39
  output: string;
40
+ /** A short explanation when the command was not started; never mutation diagnostics. */
41
+ reason?: string;
39
42
  /** True only after mutation execution and result generation both succeed. */
40
43
  mutationCompleted: boolean;
41
44
  }
@@ -54,13 +57,8 @@ type CommandRunner = (toolCallId: string, input: ThenRunInput, signal: AbortSign
54
57
  type MutationResult<TDetails> = AgentToolResult<TDetails>;
55
58
  type MutationFinalizer<TDetails> = (result: MutationResult<TDetails>, publishAnchors: boolean) => MutationResult<TDetails>;
56
59
 
57
- function staleAnchorNotice<TDetails>(result: MutationResult<TDetails>): string {
58
- const publishedRevision = (result.details as { publishedRevision?: unknown } | undefined)?.publishedRevision;
59
- return [
60
- `${THEN_RUN_STALE} Target freshness was not confirmed unchanged after then_run.`,
61
- "Pre-command anchors are omitted. Re-read before further edits.",
62
- ...(typeof publishedRevision === "string" ? ["The published revision may not describe the final file."] : []),
63
- ].join("\n");
60
+ function staleAnchorNotice(): string {
61
+ return `${THEN_RUN_STALE} Pre-command anchors are omitted: target freshness is unconfirmed. Re-read before further edits.`;
64
62
  }
65
63
 
66
64
  function errorText(error: unknown): string {
@@ -93,15 +91,18 @@ export class ActionFusionError extends Error {
93
91
  readonly publication: PublicationStatus;
94
92
  readonly command: CommandStatus;
95
93
  readonly freshness: Freshness;
94
+ readonly commandOutput: string;
95
+ readonly commandReason: string | undefined;
96
96
 
97
- constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown }) {
97
+ constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown; mutationFailure?: boolean; commandOutput?: string; commandReason?: string }) {
98
98
  const fileState = state.publication === "PUBLISHED" ? "File changes are saved."
99
- : state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain; read before retrying.";
100
- const nextStep = state.publication === "PUBLISHED" && state.freshness !== "unchanged"
101
- ? " Re-read the file before further edits." : "";
102
- super(`${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.${nextStep}`, options);
103
- // Pi exposes error.message to the model, but does not serialize Error.cause.
104
- if (options?.cause !== undefined) this.message += `\n${errorText(options.cause)}`;
99
+ : state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
100
+ const outcome = `${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.`;
101
+ const diagnostic = options?.cause === undefined ? "" : errorText(options.cause);
102
+ // Pi serializes only the message. Put the mutation's own error first for its card.
103
+ super((options?.mutationFailure ? [diagnostic, outcome] : [outcome, diagnostic]).filter(Boolean).join("\n"), options);
104
+ this.commandOutput = options?.commandOutput ?? "";
105
+ this.commandReason = options?.commandReason;
105
106
  this.name = "ActionFusionError";
106
107
  this.publication = state.publication;
107
108
  this.command = state.command;
@@ -194,14 +195,16 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
194
195
  if (thenRun !== undefined) validateThenRun(thenRun);
195
196
  let completedMutation: MutationResult<TDetails> | undefined;
196
197
  let progressFailure: string | undefined;
197
- const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "") => {
198
+ let commandSucceeded = false;
199
+ const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "", reason?: string) => {
200
+ if (command === "succeeded") commandSucceeded = true;
198
201
  if (!thenRun) return;
199
- const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output, mutationCompleted: completedMutation !== undefined };
202
+ const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output, ...(reason ? { reason } : {}), mutationCompleted: completedMutation !== undefined };
200
203
  // Display callbacks are observers: their failures must not change publication or command execution.
201
204
  for (const notify of [
202
205
  () => onProgress?.(progress, ctx),
203
206
  () => onUpdate?.({
204
- content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${output}` }],
207
+ content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}` }],
205
208
  details: { ...(completedMutation?.details as object ?? {}), actionFusion: progress },
206
209
  } as MutationResult<TDetails>),
207
210
  ]) {
@@ -211,7 +214,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
211
214
  report("waiting", "NOT_PUBLISHED", "unknown");
212
215
  return withQueue(absolutePath, async () => {
213
216
  try { signal?.throwIfAborted(); } catch (error) {
214
- if (thenRun !== undefined) throw new ActionFusionError("mutation was cancelled before it started; the command was not run", { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" }, { cause: error });
217
+ if (thenRun !== undefined) throw new ActionFusionError("mutation was cancelled before it started; the command was not run", { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" }, { cause: error, mutationFailure: true, commandReason: "Not run because the mutation was cancelled." });
215
218
  throw error;
216
219
  }
217
220
  let mutationResult: MutationResult<TDetails>;
@@ -221,7 +224,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
221
224
  } catch (error) {
222
225
  const publication = error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
223
226
  if (thenRun !== undefined) {
224
- throw new ActionFusionError(`mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`, { publication, command: "skipped", freshness: "unknown" }, { cause: error });
227
+ throw new ActionFusionError(`mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`, { publication, command: "skipped", freshness: "unknown" }, { cause: error, mutationFailure: true, commandReason: "Not run because the mutation did not complete." });
225
228
  }
226
229
  throw error;
227
230
  }
@@ -238,7 +241,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
238
241
 
239
242
  const baseline = mutationPublishedRevision(mutationResult);
240
243
  if (baseline === undefined) {
241
- throw new ActionFusionError("Missing published revision; cannot validate fused command freshness.", { publication, command: "skipped", freshness: "unknown" });
244
+ throw new ActionFusionError("Missing published revision; cannot validate fused command freshness.", { publication, command: "skipped", freshness: "unknown" }, { commandReason: "Not run because the mutation revision is unavailable." });
242
245
  }
243
246
  try {
244
247
  signal?.throwIfAborted();
@@ -246,7 +249,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
246
249
  signal?.throwIfAborted();
247
250
  } catch (error) {
248
251
  const freshness = await readFreshness(absolutePath, baseline);
249
- throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error });
252
+ throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error, commandReason: signal?.aborted ? "Not run because the operation was cancelled." : "Not run because the target revision could not be confirmed." });
250
253
  }
251
254
 
252
255
  report("running", publication, "unchanged");
@@ -263,38 +266,38 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
263
266
  }
264
267
  const freshness = await readFreshness(absolutePath, baseline);
265
268
  if (commandError !== undefined) {
266
- throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError });
269
+ throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError, commandOutput: errorText(commandError) });
267
270
  }
268
271
 
269
272
  const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
270
273
  report("succeeded", publication, freshness, output);
271
- const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation, freshness === "unchanged") : mutationResult;
272
- const commandText = freshness === "unchanged"
273
- ? (output ? `${THEN_RUN_SUCCEEDED}\n${output}` : THEN_RUN_SUCCEEDED)
274
- : `${THEN_RUN_SUCCEEDED}\n${
275
- finalizeMutation
276
- ? staleAnchorNotice(finalized)
277
- : `${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.`
278
- }${output ? `\n${output}` : ""}`;
274
+ const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation, freshness === "unchanged", staleAnchorNotice()) : mutationResult;
275
+ const commandText = `${THEN_RUN_SUCCEEDED}${!finalizeMutation && freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.` : ""}${output ? `\n${output}` : ""}`;
279
276
  return {
280
277
  ...finalized,
281
278
  details: { ...(finalized.details as object ?? {}), actionFusion },
282
279
  content: [...finalized.content, { type: "text", text: commandText }],
283
280
  } as MutationResult<TDetails>;
284
281
  }).catch((error: unknown) => {
285
- report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
286
- error instanceof ActionFusionError || error instanceof FileMutationError ? error.publication : completedMutation ? mutationPublication(completedMutation) : "NOT_PUBLISHED",
287
- error instanceof ActionFusionError ? error.freshness : "unknown", errorText(error));
282
+ // Result-generation errors after a successful command must not relabel it skipped.
283
+ if (!commandSucceeded) {
284
+ report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
285
+ error instanceof ActionFusionError || error instanceof FileMutationError ? error.publication : completedMutation ? mutationPublication(completedMutation) : "NOT_PUBLISHED",
286
+ error instanceof ActionFusionError ? error.freshness : "unknown",
287
+ error instanceof ActionFusionError ? error.commandOutput : "",
288
+ error instanceof ActionFusionError ? error.commandReason : "Not run because the mutation did not complete.");
289
+ }
288
290
  // A completed mutation remains successful; command failure belongs to its own card.
289
291
  if (completedMutation && error instanceof ActionFusionError) {
290
- const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged") : completedMutation;
291
- const anchorNotice = finalizeMutation && error.freshness !== "unchanged" ? `\n${staleAnchorNotice(finalized)}` : "";
292
+ const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged", staleAnchorNotice()) : completedMutation;
293
+ const anchorNotice = !finalizeMutation && error.freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read before further edits; previous anchors may no longer match.` : "";
292
294
  return {
293
295
  ...finalized,
294
296
  details: { ...(finalized.details as object ?? {}), actionFusion: { publication: error.publication, command: error.command, freshness: error.freshness } satisfies ActionFusionDetails },
295
297
  content: [...finalized.content, { type: "text", text: `${error.message}${anchorNotice}` }],
296
298
  } as MutationResult<TDetails>;
297
299
  }
300
+ if (error instanceof ActionFusionError && error.publication !== "NOT_PUBLISHED") error.message += "\nRe-read before retrying.";
298
301
  if (progressFailure && error instanceof Error) error.message += `\nProgress reporting failed: ${progressFailure}`;
299
302
  throw error;
300
303
  }).then((result) => progressFailure ? {
@@ -0,0 +1,30 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { computeLineHash } from "../core/hash.ts";
4
+ import { ANCHOR_PATTERN, createAnchorFormatter } from "./anchor-format.ts";
5
+ import { getState } from "./state.ts";
6
+
7
+ test("anchor formatter snapshots configured hash length and hashes undisplayed content", () => {
8
+ const state = getState();
9
+ const previous = state.config;
10
+ try {
11
+ state.config = { ...previous, hashLen: 6 };
12
+ const formatter = createAnchorFormatter();
13
+ state.config = { ...previous, hashLen: 4 };
14
+
15
+ assert.equal(formatter.hashLen, 6);
16
+ assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
17
+ assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
18
+ assert.match(formatter.token(3, "full content"), new RegExp(ANCHOR_PATTERN));
19
+ assert.equal(formatter.row(3, "full content", "full…"), `3#${computeLineHash(3, "full content", 6)}│full…`);
20
+ assert.equal(createAnchorFormatter().hashLen, 4);
21
+ } finally {
22
+ state.config = previous;
23
+ }
24
+ });
25
+
26
+ test("anchor rows expose carriage returns while checksums retain source content", () => {
27
+ const formatter = createAnchorFormatter(4);
28
+ assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
29
+ assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
30
+ });
@@ -0,0 +1,28 @@
1
+ import { computeLineHash } from "../core/hash.ts";
2
+ import { getState } from "./state.ts";
3
+
4
+ export const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
5
+
6
+ /** Anchor serialization bound to one hash-length snapshot. */
7
+ export interface AnchorFormatter {
8
+ readonly hashLen: number;
9
+ reference(line: number, hash: string): string;
10
+ token(line: number, content: string): string;
11
+ row(line: number, content: string, displayContent?: string): string;
12
+ }
13
+
14
+ /** Make CR visible without changing the source text used for checksums or patches. */
15
+ export function displayCarriageReturns(text: string): string {
16
+ return text.replace(/\r/g, "␍");
17
+ }
18
+
19
+ export function createAnchorFormatter(hashLen = getState().config.hashLen): AnchorFormatter {
20
+ const reference = (line: number, hash: string) => `${line}#${hash}`;
21
+ const token = (line: number, content: string) => reference(line, computeLineHash(line, content, hashLen));
22
+ return {
23
+ hashLen,
24
+ token,
25
+ reference,
26
+ row: (line, content, displayContent = content) => `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
27
+ };
28
+ }
package/src/pi/config.ts CHANGED
@@ -17,7 +17,7 @@ export interface HashlineEditConfig {
17
17
  actionFusion: boolean;
18
18
  /** Line hash length (default 4). */
19
19
  hashLen: number;
20
- /** ±line radius for shifted-anchor recovery (default 15; 0 disables rescue). */
20
+ /** First-pass ±line radius before full-file recovery (default 15; 0 disables recovery). */
21
21
  shiftRadius: number;
22
22
  }
23
23