@criogaid/pi-hashline-edit 0.4.0 → 0.5.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 (60) hide show
  1. package/README.md +116 -20
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.ts +1 -3
  10. package/src/core/types.ts +4 -7
  11. package/src/index.ts +9 -11
  12. package/src/integration/config-registration.test.ts +206 -0
  13. package/src/integration/grep-rg.test.ts +73 -60
  14. package/src/integration/large-text.test.ts +9 -8
  15. package/src/integration/replace-package.test.ts +11 -7
  16. package/src/pi/action-fusion.test.ts +110 -34
  17. package/src/pi/action-fusion.ts +77 -114
  18. package/src/pi/anchor-format.test.ts +43 -22
  19. package/src/pi/anchor-format.ts +23 -8
  20. package/src/pi/budgets.ts +7 -2
  21. package/src/pi/config.test.ts +153 -40
  22. package/src/pi/config.ts +87 -41
  23. package/src/pi/e2e-scenarios.test.ts +12 -11
  24. package/src/pi/edit-tool.ts +20 -156
  25. package/src/pi/error-text.ts +10 -5
  26. package/src/pi/execute.test.ts +299 -175
  27. package/src/pi/failure-context.test.ts +7 -2
  28. package/src/pi/failure-context.ts +155 -8
  29. package/src/pi/failure-path.test.ts +33 -26
  30. package/src/pi/file-commit.ts +2 -1
  31. package/src/pi/fusion-card.ts +83 -2
  32. package/src/pi/grep-output.ts +26 -9
  33. package/src/pi/grep-render.ts +6 -5
  34. package/src/pi/grep-scope.ts +2 -15
  35. package/src/pi/grep-search.ts +29 -15
  36. package/src/pi/grep-tool.ts +94 -78
  37. package/src/pi/grep.test.ts +357 -320
  38. package/src/pi/mutation-outcome.testing.ts +22 -0
  39. package/src/pi/mutation-result.test.ts +51 -2
  40. package/src/pi/mutation-result.ts +62 -55
  41. package/src/pi/mutation-runner.ts +16 -33
  42. package/src/pi/pi.test.ts +10 -5
  43. package/src/pi/read-tool.ts +61 -33
  44. package/src/pi/registration.test.ts +1 -5
  45. package/src/pi/render.test.ts +16 -8
  46. package/src/pi/render.ts +4 -91
  47. package/src/pi/replace-regex.ts +54 -0
  48. package/src/pi/replace-tool.ts +24 -58
  49. package/src/pi/replace-worker.ts +2 -2
  50. package/src/pi/replace.test.ts +62 -58
  51. package/src/pi/result-safety.test.ts +124 -84
  52. package/src/pi/rg-line-ranges.ts +3 -2
  53. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  54. package/src/pi/{rg-line-filter.ts → rg-process.ts} +35 -4
  55. package/src/pi/rg-text-view.ts +17 -33
  56. package/src/pi/schema.ts +2 -10
  57. package/src/pi/write-tool.ts +1 -2
  58. package/src/pi/write.test.ts +10 -9
  59. package/src/core/index.ts +0 -14
  60. package/src/pi/state.ts +0 -26
@@ -1,4 +1,4 @@
1
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
@@ -16,9 +16,13 @@ import {
16
16
  createActionFusionExecutor,
17
17
  THEN_RUN_FAILED,
18
18
  THEN_RUN_SKIPPED,
19
+ THEN_RUN_STALE,
19
20
  THEN_RUN_SUCCEEDED,
20
21
  } from "./action-fusion.ts";
21
22
  import { byteRevision, FileMutationError } from "./file-commit.ts";
23
+ import { DEFAULT_CONFIG } from "./config.ts";
24
+ import { staleTargetNotice } from "./mutation-result.ts";
25
+ import { publishedMutation } from "./mutation-outcome.testing.ts";
22
26
 
23
27
  async function tempDir(): Promise<string> {
24
28
  return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
@@ -26,9 +30,16 @@ async function tempDir(): Promise<string> {
26
30
 
27
31
  const ctx = (cwd: string) => ({ cwd }) as ExtensionContext;
28
32
 
33
+ type Fusion = Parameters<typeof makeWriteOverride>[1];
34
+ const mutationFactories = [
35
+ (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
36
+ (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
37
+ makeWriteOverride,
38
+ ];
39
+
29
40
  test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
30
41
  const fusion = createActionFusionExecutor();
31
- for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
42
+ for (const makeTool of mutationFactories) {
32
43
  const disabled = makeTool("/tmp");
33
44
  const enabled = makeTool("/tmp", fusion);
34
45
  assert.equal(Object.hasOwn(disabled.parameters.properties, "then_run"), false);
@@ -50,7 +61,7 @@ test("mutation tools expose Fusion schemas and guidance when supplied an executo
50
61
  test("then_run schemas reject invalid commands, unknown keys, and excessive timeouts", async () => {
51
62
  const dir = await tempDir();
52
63
  try {
53
- for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
64
+ for (const makeTool of mutationFactories) {
54
65
  const tool = makeTool(dir, createActionFusionExecutor());
55
66
  const path = `${tool.name}.txt`;
56
67
  await writeFile(join(dir, path), "old\n");
@@ -86,8 +97,8 @@ test("edit and replace share one embedded executor and preserve mutation results
86
97
  calls.push(input.command);
87
98
  return "checked";
88
99
  });
89
- const edit = makeEditOverride(dir, fusion);
90
- const replace = makeReplaceTool(dir, fusion);
100
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
101
+ const replace = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
91
102
  await writeFile(join(dir, "edit.txt"), "before\n");
92
103
  await writeFile(join(dir, "replace.txt"), "before\n");
93
104
  const editResult = await edit.execute(
@@ -161,10 +172,11 @@ test("mutation failure skips the command and command failure does not roll back"
161
172
  toolCallId: "y",
162
173
  absolutePath: target,
163
174
  thenRun: { command: "check" },
164
- mutate: async () => ({
165
- content: [{ type: "text", text: "mutation" }],
166
- details: { ok: true, publishedRevision: byteRevision("changed\n") },
167
- }),
175
+ mutate: async () =>
176
+ publishedMutation("changed\n", {
177
+ content: [{ type: "text", text: "mutation" }],
178
+ details: { ok: true },
179
+ }),
168
180
  signal: undefined,
169
181
  ctx: ctx(dir),
170
182
  });
@@ -196,7 +208,7 @@ test("cancelled calls do not mutate or run the command", async () => {
196
208
  thenRun: { command: "check" },
197
209
  mutate: async () => {
198
210
  mutated = true;
199
- return { content: [], details: undefined };
211
+ throw new Error("Cancelled mutation must not run");
200
212
  },
201
213
  signal: controller.signal,
202
214
  ctx: ctx(dir),
@@ -221,10 +233,10 @@ test("default runner executes a real local command", async () => {
221
233
  thenRun: { command: "node -e \"process.stdout.write('real runner')\"" },
222
234
  mutate: async () => {
223
235
  await writeFile(target, "after\n");
224
- return {
236
+ return publishedMutation("after\n", {
225
237
  content: [{ type: "text", text: "mutated" }],
226
- details: { ok: true, publishedRevision: byteRevision("after\n") },
227
- };
238
+ details: { ok: true },
239
+ });
228
240
  },
229
241
  signal: undefined,
230
242
  ctx: {
@@ -257,10 +269,14 @@ test("marks anchors stale when then_run changes the target", async () => {
257
269
  thenRun: { command: "mutate target" },
258
270
  mutate: async () => {
259
271
  await writeFile(target, "after mutation\n");
260
- return {
261
- content: [{ type: "text", text: "mutated" }],
262
- details: { publishedRevision: byteRevision("after mutation\n") },
263
- };
272
+ return publishedMutation(
273
+ "after mutation\n",
274
+ {
275
+ content: [{ type: "text", text: "mutated" }],
276
+ details: undefined,
277
+ },
278
+ " ANCHOR",
279
+ );
264
280
  },
265
281
  signal: undefined,
266
282
  ctx: ctx(dir),
@@ -269,7 +285,8 @@ test("marks anchors stale when then_run changes the target", async () => {
269
285
  .filter((block) => block.type === "text")
270
286
  .map((block) => (block.type === "text" ? block.text : ""))
271
287
  .join("\n");
272
- assert.match(output, /\[then_run:stale\]/);
288
+ assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
289
+ assert.doesNotMatch(output, /ANCHOR/);
273
290
  assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
274
291
  } finally {
275
292
  await rm(dir, { recursive: true, force: true });
@@ -279,7 +296,7 @@ test("marks anchors stale when then_run changes the target", async () => {
279
296
  test("Action Fusion omits structured anchors when target freshness is unknown", async () => {
280
297
  const dir = await tempDir();
281
298
  try {
282
- const missing = join(dir, "never-created.txt");
299
+ const missing = join(dir, "unreadable.txt");
283
300
  let commands = 0;
284
301
  const fusion = createActionFusionExecutor(async () => {
285
302
  commands++;
@@ -289,11 +306,19 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
289
306
  toolCallId: "unknown",
290
307
  absolutePath: missing,
291
308
  thenRun: { command: "check" },
292
- mutate: async () => ({ content: [{ type: "text", text: "mutated" }], details: {} }),
293
- finalizeMutation: (mutation, publishAnchors) => ({
294
- ...mutation,
295
- content: [{ type: "text", text: `mutated${publishAnchors ? " ANCHOR" : ""}` }],
296
- }),
309
+ mutate: async () => {
310
+ await writeFile(missing, "mutation\n");
311
+ await rm(missing);
312
+ await mkdir(missing);
313
+ return publishedMutation(
314
+ "mutation\n",
315
+ {
316
+ content: [{ type: "text", text: "mutated" }],
317
+ details: undefined,
318
+ },
319
+ " ANCHOR",
320
+ );
321
+ },
297
322
  signal: undefined,
298
323
  ctx: ctx(dir),
299
324
  });
@@ -303,7 +328,7 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
303
328
  assert.equal(commands, 0);
304
329
  assert.equal((result.details as any).actionFusion.freshness, "unknown");
305
330
  assert.doesNotMatch(output, /ANCHOR/);
306
- assert.match(output, /Pre-command anchors are omitted/);
331
+ assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
307
332
  } finally {
308
333
  await rm(dir, { recursive: true, force: true });
309
334
  }
@@ -318,11 +343,11 @@ test("edit omits Updated anchors when then_run changes the target", async () =>
318
343
  await writeFile(target, "command changed\n");
319
344
  return "changed";
320
345
  });
321
- const result = await makeEditOverride(dir, fusion).execute(
346
+ const result = await makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
322
347
  "edit-stale",
323
348
  {
324
349
  path: "edit-stale.txt",
325
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before")}`, body: ["after"] }],
350
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before", 4)}`, body: ["after"] }],
326
351
  then_run: { command: "change target" },
327
352
  },
328
353
  undefined,
@@ -332,7 +357,7 @@ test("edit omits Updated anchors when then_run changes the target", async () =>
332
357
  const output = result.content.map((block: any) => block.text ?? "").join("\n");
333
358
  assert.ok(result.details.actionFusion);
334
359
  assert.equal(result.details.actionFusion.freshness, "changed");
335
- assert.match(output, /Pre-command anchors are omitted/);
360
+ assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
336
361
  assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
337
362
  assert.equal(await readFile(target, "utf8"), "command changed\n");
338
363
  } finally {
@@ -357,7 +382,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
357
382
  );
358
383
  const cases = [
359
384
  () =>
360
- makeEditOverride(dir, fusion).execute(
385
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
361
386
  "edit",
362
387
  {
363
388
  path: "progress.txt",
@@ -369,7 +394,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
369
394
  { ...ctx(dir), mode: "rpc" },
370
395
  ),
371
396
  () =>
372
- makeReplaceTool(dir, fusion).execute(
397
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
373
398
  "replace",
374
399
  {
375
400
  path: "progress.txt",
@@ -424,7 +449,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
424
449
  (event) => events.push(event),
425
450
  );
426
451
  await assert.rejects(
427
- makeEditOverride(dir, fusion).execute(
452
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
428
453
  "skip",
429
454
  {
430
455
  path: "missing.txt",
@@ -446,7 +471,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
446
471
  events.length = 0;
447
472
  await writeFile(join(dir, "replace.txt"), "original\n");
448
473
  await assert.rejects(
449
- makeReplaceTool(dir, fusion).execute(
474
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
450
475
  "replace-skip",
451
476
  {
452
477
  path: "replace.txt",
@@ -505,7 +530,7 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
505
530
  order.push("start-1");
506
531
  await firstRunning;
507
532
  order.push("end-1");
508
- return { content: [], details: { publication: "PUBLISHED" as const } };
533
+ return publishedMutation("first\n", { content: [], details: undefined });
509
534
  },
510
535
  signal: undefined,
511
536
  ctx: ctx(dir),
@@ -518,7 +543,7 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
518
543
  mutate: async () => {
519
544
  order.push("start-2");
520
545
  order.push("end-2");
521
- return { content: [], details: { publication: "PUBLISHED" as const } };
546
+ return publishedMutation("second\n", { content: [], details: undefined });
522
547
  },
523
548
  signal: undefined,
524
549
  ctx: ctx(dir),
@@ -575,3 +600,54 @@ test("ActionFusionError re-wrapping appends recovery guidance without duplicatin
575
600
  await rm(dir, { recursive: true, force: true });
576
601
  }
577
602
  });
603
+
604
+ test("Fusion uses commit facts when details omit or contradict publication and revision", async () => {
605
+ const dir = await tempDir();
606
+ try {
607
+ const target = join(dir, "unchanged.txt");
608
+ await writeFile(target, "same\n");
609
+ const commit = {
610
+ publication: "NOT_PUBLISHED" as const,
611
+ publishedRevision: byteRevision("same\n"),
612
+ observedRevision: byteRevision("same\n"),
613
+ created: false,
614
+ };
615
+ for (const details of [
616
+ undefined,
617
+ { publication: "UNKNOWN", publishedRevision: "wrong", observedRevision: "wrong" },
618
+ ]) {
619
+ for (const thenRun of [undefined, { command: "check" }]) {
620
+ let commands = 0;
621
+ const fusion = createActionFusionExecutor(async () => {
622
+ commands++;
623
+ return "checked";
624
+ });
625
+ const result = await fusion({
626
+ toolCallId: "commit-facts",
627
+ absolutePath: target,
628
+ thenRun,
629
+ signal: undefined,
630
+ ctx: ctx(dir),
631
+ mutate: async () => ({
632
+ result: { content: [{ type: "text", text: "mutation" }], details },
633
+ commit,
634
+ anchors: " ANCHOR",
635
+ }),
636
+ });
637
+ assert.deepEqual(result.content[0], { type: "text", text: "mutation ANCHOR" });
638
+ assert.deepEqual(result.details, {
639
+ ...details,
640
+ actionFusion: {
641
+ publication: "NOT_PUBLISHED",
642
+ command: thenRun ? "succeeded" : "not_requested",
643
+ freshness: "unchanged",
644
+ },
645
+ });
646
+ assert.equal(commands, thenRun ? 1 : 0);
647
+ assert.equal(await readFile(target, "utf8"), "same\n");
648
+ }
649
+ }
650
+ } finally {
651
+ await rm(dir, { recursive: true, force: true });
652
+ }
653
+ });
@@ -1,11 +1,33 @@
1
+ /**
2
+ * Action Fusion: run an optional `then_run` command after a successful mutation.
3
+ *
4
+ * Two per-file queues nest here, with different jobs:
5
+ * - Pi's `withFileMutationQueue` (entered by the mutation runner) serializes
6
+ * the read-modify-write itself and is shared with every tool that uses it.
7
+ * It is released as soon as the file is published.
8
+ * - The executor's own queue wraps mutation, freshness check, and command, so
9
+ * a later fused call on the same file waits until this command finishes and
10
+ * cannot change the revision the command started from. Its key resolves the nearest
11
+ * existing ancestor and folds case on Windows, so it is never looser than
12
+ * Pi's key. It is always taken first and Pi's queue never waits on it, so
13
+ * the nesting cannot deadlock.
14
+ *
15
+ * Writers outside these queues are not blocked; the freshness check against
16
+ * `publishedRevision` detects them and the command is skipped or reported stale.
17
+ * A failed command never rolls back the published file.
18
+ *
19
+ * @module pi-hashline-edit/pi
20
+ */
21
+
1
22
  import { realpath } from "node:fs/promises";
2
23
  import { basename, dirname, resolve } from "node:path";
3
24
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
4
25
  import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
26
  import { Type, type Static, type TObject, type TProperties } from "typebox";
6
27
  import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
7
- import { finalizeMutationResult, observedFreshness } from "./mutation-result.ts";
8
- import { errorMessage, OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
28
+ import { commitFreshness, finalizeMutation, type MutationOutcome } from "./mutation-result.ts";
29
+ import { errorMessage } from "../core/errors.ts";
30
+ import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
9
31
 
10
32
  export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
11
33
  export const THEN_RUN_FAILED = "[then_run:failed]";
@@ -93,13 +115,20 @@ type CommandRunner = (
93
115
  ) => Promise<string>;
94
116
 
95
117
  type MutationResult<TDetails> = AgentToolResult<TDetails>;
96
- type MutationFinalizer<TDetails> = (
118
+ /** Attach the fused outcome to a finalized mutation result, plus optional command text. */
119
+ function withFusionDetails<TDetails>(
97
120
  result: MutationResult<TDetails>,
98
- publishAnchors: boolean,
99
- ) => MutationResult<TDetails>;
100
-
101
- function staleAnchorNotice(): string {
102
- return `${THEN_RUN_STALE} Pre-command anchors are omitted: target freshness is unconfirmed. Re-read before further edits.`;
121
+ actionFusion: ActionFusionDetails,
122
+ commandText?: string,
123
+ ): MutationResult<TDetails> {
124
+ return {
125
+ ...result,
126
+ details: { ...((result.details as object) ?? {}), actionFusion },
127
+ content:
128
+ commandText === undefined
129
+ ? result.content
130
+ : [...result.content, { type: "text", text: commandText }],
131
+ } as MutationResult<TDetails>;
103
132
  }
104
133
 
105
134
  async function readFreshness(path: string, baseline: string): Promise<Freshness> {
@@ -171,17 +200,6 @@ export class ActionFusionError extends Error {
171
200
  }
172
201
  }
173
202
 
174
- function mutationPublication<TDetails>(result: MutationResult<TDetails>): PublicationStatus {
175
- const details = result.details as { publication?: PublicationStatus } | undefined;
176
- return details?.publication ?? "PUBLISHED";
177
- }
178
-
179
- function mutationPublishedRevision<TDetails>(result: MutationResult<TDetails>): string | undefined {
180
- const revision = (result.details as { publishedRevision?: unknown } | undefined)
181
- ?.publishedRevision;
182
- return typeof revision === "string" && revision.length > 0 ? revision : undefined;
183
- }
184
-
185
203
  function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
186
204
  if (signal?.aborted) return "cancelled";
187
205
  return /timeout|timed out/i.test(errorMessage(error)) ? "timeout" : "failed";
@@ -261,20 +279,17 @@ export function createActionFusionExecutor(
261
279
  signal,
262
280
  ctx,
263
281
  onUpdate,
264
- finalizeMutation,
265
282
  }: {
266
283
  toolCallId: string;
267
284
  absolutePath: string;
268
285
  thenRun: ThenRunInput | undefined;
269
- mutate: () => Promise<MutationResult<TDetails>>;
286
+ mutate: () => Promise<MutationOutcome<TDetails>>;
270
287
  signal: AbortSignal | undefined;
271
288
  ctx: ExtensionContext;
272
289
  onUpdate?: AgentToolUpdateCallback<TDetails>;
273
- finalizeMutation?: MutationFinalizer<TDetails>;
274
290
  }): Promise<MutationResult<TDetails>> {
275
- let completedMutation: MutationResult<TDetails> | undefined;
291
+ let completedMutation: MutationOutcome<TDetails> | undefined;
276
292
  let progressFailure: string | undefined;
277
- let commandSucceeded = false;
278
293
  const report = (
279
294
  command: ActionFusionProgress["command"],
280
295
  publication: PublicationStatus,
@@ -282,7 +297,6 @@ export function createActionFusionExecutor(
282
297
  output = "",
283
298
  reason?: string,
284
299
  ) => {
285
- if (command === "succeeded") commandSucceeded = true;
286
300
  if (!thenRun) return;
287
301
  const progress: ActionFusionProgress = {
288
302
  toolCallId,
@@ -301,13 +315,16 @@ export function createActionFusionExecutor(
301
315
  () =>
302
316
  onUpdate?.({
303
317
  content: [
304
- ...(completedMutation?.content ?? []),
318
+ ...(completedMutation?.result.content ?? []),
305
319
  {
306
320
  type: "text",
307
321
  text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}`,
308
322
  },
309
323
  ],
310
- details: { ...((completedMutation?.details as object) ?? {}), actionFusion: progress },
324
+ details: {
325
+ ...((completedMutation?.result.details as object) ?? {}),
326
+ actionFusion: progress,
327
+ },
311
328
  } as MutationResult<TDetails>),
312
329
  ]) {
313
330
  try {
@@ -334,10 +351,10 @@ export function createActionFusionExecutor(
334
351
  );
335
352
  throw error;
336
353
  }
337
- let mutationResult: MutationResult<TDetails>;
354
+ let outcome: MutationOutcome<TDetails>;
338
355
  try {
339
- mutationResult = await mutate();
340
- completedMutation = mutationResult;
356
+ outcome = await mutate();
357
+ completedMutation = outcome;
341
358
  } catch (error) {
342
359
  const publication =
343
360
  error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
@@ -355,32 +372,15 @@ export function createActionFusionExecutor(
355
372
  throw error;
356
373
  }
357
374
 
358
- const publication = mutationPublication(mutationResult);
375
+ const { publication, publishedRevision: baseline } = outcome.commit;
359
376
  report("waiting", publication, "unknown");
360
377
  if (thenRun === undefined) {
361
- const finalized = finalizeMutation
362
- ? finalizeMutationResult(mutationResult, finalizeMutation)
363
- : mutationResult;
364
- return {
365
- ...finalized,
366
- details: {
367
- ...((finalized.details as object) ?? {}),
368
- actionFusion: {
369
- publication,
370
- command: "not_requested",
371
- freshness: observedFreshness(mutationResult),
372
- } satisfies ActionFusionDetails,
373
- },
374
- } as MutationResult<TDetails>;
375
- }
376
-
377
- const baseline = mutationPublishedRevision(mutationResult);
378
- if (baseline === undefined) {
379
- throw new ActionFusionError(
380
- "Missing published revision; cannot validate fused command freshness.",
381
- { publication, command: "skipped", freshness: "unknown" },
382
- { commandReason: "Not run because the mutation revision is unavailable." },
383
- );
378
+ const freshness = commitFreshness(outcome.commit);
379
+ return withFusionDetails(finalizeMutation(outcome, freshness === "unchanged"), {
380
+ publication,
381
+ command: "not_requested",
382
+ freshness,
383
+ });
384
384
  }
385
385
  try {
386
386
  throwIfCancelled(signal);
@@ -424,71 +424,34 @@ export function createActionFusionExecutor(
424
424
  );
425
425
  }
426
426
 
427
- const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
428
427
  report("succeeded", publication, freshness, output);
429
- const finalized = finalizeMutation
430
- ? finalizeMutationResult(
431
- mutationResult,
432
- finalizeMutation,
433
- freshness === "unchanged",
434
- staleAnchorNotice(),
435
- )
436
- : mutationResult;
437
- 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}` : ""}`;
438
- return {
439
- ...finalized,
440
- details: { ...((finalized.details as object) ?? {}), actionFusion },
441
- content: [...finalized.content, { type: "text", text: commandText }],
442
- } as MutationResult<TDetails>;
428
+ return withFusionDetails(
429
+ finalizeMutation(outcome, freshness === "unchanged", THEN_RUN_STALE),
430
+ { publication, command: "succeeded", freshness },
431
+ `${THEN_RUN_SUCCEEDED}${output ? `\n${output}` : ""}`,
432
+ );
443
433
  })
444
434
  .catch((error: unknown) => {
445
- // Result-generation errors after a successful command must not relabel it skipped.
446
- if (!commandSucceeded) {
447
- report(
448
- error instanceof ActionFusionError
449
- ? (error.command as ActionFusionProgress["command"])
450
- : "skipped",
451
- error instanceof ActionFusionError || error instanceof FileMutationError
452
- ? error.publication
453
- : completedMutation
454
- ? mutationPublication(completedMutation)
455
- : "NOT_PUBLISHED",
456
- error instanceof ActionFusionError ? error.freshness : "unknown",
457
- error instanceof ActionFusionError ? error.commandOutput : "",
458
- error instanceof ActionFusionError
459
- ? error.commandReason
460
- : "Not run because the mutation did not complete.",
461
- );
462
- }
435
+ report(
436
+ error instanceof ActionFusionError
437
+ ? (error.command as ActionFusionProgress["command"])
438
+ : "skipped",
439
+ error instanceof ActionFusionError || error instanceof FileMutationError
440
+ ? error.publication
441
+ : (completedMutation?.commit.publication ?? "NOT_PUBLISHED"),
442
+ error instanceof ActionFusionError ? error.freshness : "unknown",
443
+ error instanceof ActionFusionError ? error.commandOutput : "",
444
+ error instanceof ActionFusionError
445
+ ? error.commandReason
446
+ : "Not run because the mutation did not complete.",
447
+ );
463
448
  // A completed mutation remains successful; command failure belongs to its own card.
464
449
  if (completedMutation && error instanceof ActionFusionError) {
465
- const finalized = finalizeMutation
466
- ? finalizeMutationResult(
467
- completedMutation,
468
- finalizeMutation,
469
- error.freshness === "unchanged",
470
- staleAnchorNotice(),
471
- )
472
- : completedMutation;
473
- const anchorNotice =
474
- !finalizeMutation && error.freshness !== "unchanged"
475
- ? `\n${THEN_RUN_STALE} Re-read before further edits; previous anchors may no longer match.`
476
- : "";
477
- return {
478
- ...finalized,
479
- details: {
480
- ...((finalized.details as object) ?? {}),
481
- actionFusion: {
482
- publication: error.publication,
483
- command: error.command,
484
- freshness: error.freshness,
485
- } satisfies ActionFusionDetails,
486
- },
487
- content: [
488
- ...finalized.content,
489
- { type: "text", text: `${error.message}${anchorNotice}` },
490
- ],
491
- } as MutationResult<TDetails>;
450
+ return withFusionDetails(
451
+ finalizeMutation(completedMutation, error.freshness === "unchanged", THEN_RUN_STALE),
452
+ { publication: error.publication, command: error.command, freshness: error.freshness },
453
+ error.message,
454
+ );
492
455
  }
493
456
  {
494
457
  const parts: string[] = [errorMessage(error)];
@@ -1,30 +1,29 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
- import { anchorPattern, createAnchorFormatter, parseAnchorToken } from "./anchor-format.ts";
5
- import { getState } from "./state.ts";
4
+ import {
5
+ anchorPattern,
6
+ createAnchorFormatter,
7
+ parseAnchorToken,
8
+ parseHashline,
9
+ } from "./anchor-format.ts";
6
10
 
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 };
11
+ test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
12
+ const formatter = createAnchorFormatter(6);
13
+ const shortFormatter = createAnchorFormatter(4);
14
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(anchorPattern(6)));
19
- assert.doesNotMatch(formatter.token(3, "full content"), new RegExp(anchorPattern(4)));
20
- assert.equal(
21
- formatter.row(3, "full content", "full…"),
22
- `3#${computeLineHash(3, "full content", 6)}│full…`,
23
- );
24
- assert.equal(createAnchorFormatter().hashLen, 4);
25
- } finally {
26
- state.config = previous;
27
- }
15
+ assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
16
+ assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
17
+ assert.match(formatter.token(3, "full content"), new RegExp(anchorPattern(6)));
18
+ assert.doesNotMatch(formatter.token(3, "full content"), new RegExp(anchorPattern(4)));
19
+ assert.equal(
20
+ formatter.row(3, "full content", "full…"),
21
+ `3#${computeLineHash(3, "full content", 6)}│full…`,
22
+ );
23
+ assert.equal(
24
+ shortFormatter.token(3, "full content"),
25
+ `3#${computeLineHash(3, "full content", 4)}`,
26
+ );
28
27
  });
29
28
 
30
29
  test("anchor tokens parse at any hash length so wrong lengths can be explained", () => {
@@ -39,3 +38,25 @@ test("anchor rows expose carriage returns while checksums retain source content"
39
38
  assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
40
39
  assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
41
40
  });
41
+
42
+ test("anchor syntax rejects characters absent from the checksum alphabet", () => {
43
+ const pattern = new RegExp(anchorPattern(4));
44
+ for (const hash of ["IIII", "LLLL", "OOOO", "UUUU", "abcd"]) {
45
+ assert.doesNotMatch(`1#${hash}`, pattern);
46
+ assert.equal(parseAnchorToken(`1#${hash}`), undefined);
47
+ assert.equal(parseHashline(`1#${hash}│content`), null);
48
+ }
49
+ });
50
+
51
+ test("display rows accept supported hash lengths and preserve nested anchor-like content", () => {
52
+ for (const hashLen of [2, 4, 6, 8]) {
53
+ const formatter = createAnchorFormatter(hashLen);
54
+ assert.deepEqual(parseHashline(formatter.row(12, "12#abc│content")), {
55
+ lineNo: "12",
56
+ content: "12#abc│content",
57
+ });
58
+ }
59
+ for (const row of ["0#ABCD│text", "01#ABCD│text", "12#A│text", "12#AAAAAAAAA│text"]) {
60
+ assert.equal(parseHashline(row), null);
61
+ }
62
+ });