@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,43 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
4
+ import { createOutputBudgetProvider } from "./model-budgets.ts";
5
+
6
+ test("unchanged model → budget calculation is lazy and reuses the immutable snapshot", () => {
7
+ let reads = 0;
8
+ let model = { provider: "local", id: "small", contextWindow: 65_536 };
9
+ const get = createOutputBudgetProvider(() => {
10
+ reads++;
11
+ return model;
12
+ });
13
+ assert.equal(reads, 0);
14
+ const first = get();
15
+ assert.ok(Object.isFrozen(first));
16
+ assert.equal(get(), first);
17
+ model = { ...model };
18
+ assert.equal(get(), first);
19
+ model = { ...model, id: "large", contextWindow: 1_048_576 };
20
+ const large = get();
21
+ assert.notEqual(large, first);
22
+ assert.ok(large.readBytes > first.readBytes);
23
+ assert.ok(large.blockBytes > first.blockBytes);
24
+ assert.ok(large.fieldBytes > first.fieldBytes);
25
+ assert.ok(large.grepPreviewUnits > first.grepPreviewUnits);
26
+ assert.equal(get(), large);
27
+ assert.ok(first.readBytes < large.readBytes);
28
+ model = { ...model, contextWindow: 65_536 };
29
+ assert.equal(get().readBytes, first.readBytes);
30
+ });
31
+
32
+ test("unknown or invalid model capacity → bounded defaults are used", () => {
33
+ for (const capacity of [undefined, 0, -1, NaN, Infinity, 2.5]) {
34
+ assert.equal(outputBudgetsFor(capacity), DEFAULT_OUTPUT_BUDGETS);
35
+ }
36
+ });
37
+
38
+ test("declared capacity beyond the explicit ceiling → content budgets cap at read.maxKiB's maximum", () => {
39
+ const capped = outputBudgetsFor(MAX_CONTENT_KIB * 1024 + 1);
40
+ assert.equal(capped.readBytes, MAX_CONTENT_KIB * 1024);
41
+ assert.equal(capped.grepBytes, MAX_CONTENT_KIB * 1024);
42
+ assert.equal(capped.blockBytes, (MAX_CONTENT_KIB * 1024) / 4);
43
+ });
@@ -0,0 +1,44 @@
1
+ /** Per-extension lazy budgets. Tool preparation and execution share the same provider. */
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { outputBudgetsFor, type OutputBudgetProvider, type OutputBudgets } from "./budgets.ts";
4
+
5
+ type BudgetModel = Pick<
6
+ NonNullable<ExtensionContext["model"]>,
7
+ "provider" | "id" | "contextWindow"
8
+ >;
9
+
10
+ /** Reuse the snapshot until selection or its declared capacity changes. No provider request is made. */
11
+ export function createOutputBudgetProvider(
12
+ readModel: () => BudgetModel | undefined,
13
+ ): OutputBudgetProvider {
14
+ let provider: string | undefined;
15
+ let id: string | undefined;
16
+ let contextWindow: number | undefined;
17
+ let cached: OutputBudgets | undefined;
18
+ return () => {
19
+ const model = readModel();
20
+ if (
21
+ cached === undefined ||
22
+ provider !== model?.provider ||
23
+ id !== model?.id ||
24
+ !Object.is(contextWindow, model?.contextWindow)
25
+ ) {
26
+ provider = model?.provider;
27
+ id = model?.id;
28
+ contextWindow = model?.contextWindow;
29
+ cached = outputBudgetsFor(contextWindow);
30
+ }
31
+ return cached;
32
+ };
33
+ }
34
+
35
+ /** Retain Pi's live context getter, including after session restore, without calculating on events. */
36
+ export function registerModelBudgets(pi: ExtensionAPI): OutputBudgetProvider {
37
+ let context: ExtensionContext | undefined;
38
+ const bind = (_event: unknown, ctx: ExtensionContext) => {
39
+ context = ctx;
40
+ };
41
+ pi.on("session_start", bind);
42
+ pi.on("model_select", bind);
43
+ return createOutputBudgetProvider(() => context?.model);
44
+ }
@@ -1,22 +1,21 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
- import { byteRevision } from "./file-commit.ts";
2
+ import { byteRevision } from "./file-revision.ts";
3
3
  import type { MutationOutcome } from "./mutation-result.ts";
4
4
 
5
5
  /** Build a completed overwrite fixture with matching published and observed bytes. */
6
- export function publishedMutation<T>(
6
+ export function publishedMutation<T extends object | undefined>(
7
7
  content: string,
8
8
  result: AgentToolResult<T>,
9
- anchors?: string,
10
- ): MutationOutcome<T> {
11
- const revision = byteRevision(content);
9
+ ): MutationOutcome<T extends object ? T : object> {
10
+ const revision = byteRevision(Buffer.from(content));
12
11
  return {
13
- result,
12
+ details: (result.details ?? {}) as T extends object ? T : object,
13
+ facts: {},
14
14
  commit: {
15
15
  publication: "PUBLISHED",
16
16
  publishedRevision: revision,
17
17
  observedRevision: revision,
18
18
  created: false,
19
19
  },
20
- anchors,
21
20
  };
22
21
  }
@@ -1,10 +1,47 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
- import { formatMutationAnchors, generateMutationDetails } from "./mutation-result.ts";
5
- import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
6
- import { byteRevision } from "./file-commit.ts";
7
- import { MAX_BLOCK_BYTES } from "./budgets.ts";
3
+ import { generateDiffString } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ commandText,
6
+ finalizeMutation,
7
+ generateMutationDetails,
8
+ type MutationFacts,
9
+ type MutationFinalDetails,
10
+ type MutationOutcome,
11
+ } from "./mutation-result.ts";
12
+ import { displayCarriageReturns } from "./anchor-format.ts";
13
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
14
+
15
+ // Checked by tsc; these callers must never run.
16
+ function invalidMutationConstruction(
17
+ replacement: MutationOutcome<object, "replace">,
18
+ result: MutationFinalDetails<{ diff: string }>,
19
+ ) {
20
+ // @ts-expect-error edit has no replacement-count fact.
21
+ const editFacts: MutationFacts<"edit"> = { matches: 1 };
22
+ finalizeMutation(
23
+ "edit",
24
+ "file.txt",
25
+ // @ts-expect-error Replacement facts cannot be finalized as edit facts.
26
+ replacement,
27
+ { freshness: "unchanged" },
28
+ undefined,
29
+ DEFAULT_OUTPUT_BUDGETS,
30
+ );
31
+ // @ts-expect-error A failed mutation has no diff details.
32
+ const diff: string = result.diff;
33
+ }
34
+
35
+ test("command content includes images → report text joins only text blocks", () => {
36
+ assert.equal(
37
+ commandText([
38
+ { type: "text", text: "first" },
39
+ { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
40
+ { type: "text", text: "second" },
41
+ ]),
42
+ "first\nsecond",
43
+ );
44
+ });
8
45
 
9
46
  for (const [name, before, after] of [
10
47
  ["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
@@ -16,94 +53,11 @@ for (const [name, before, after] of [
16
53
  ["BOM and literal escapes", "\uFEFFguard\nold\\n\\0", "\uFEFFguard\nnew\\n\\0"],
17
54
  ["no-op", "unchanged\n", "unchanged\n"],
18
55
  ] as const) {
19
- test(`mutation evidence preserves raw patch and logical preview for ${name}`, () => {
20
- const versions = {
21
- baseRevision: byteRevision(before),
22
- publishedRevision: byteRevision(after),
23
- observedRevision: byteRevision(after),
24
- };
25
- const publication = before === after ? "NOT_PUBLISHED" : "PUBLISHED";
26
- const details = generateMutationDetails("file.txt", before, after, versions, publication);
27
- const raw = generateDiffString(before, after);
56
+ test(`${name} mutation → details contain only the logical-view diff`, () => {
57
+ const details = generateMutationDetails(before, after);
28
58
  const logical = generateDiffString(before.replace(/\r\n/g, "\n"), after.replace(/\r\n/g, "\n"));
29
59
  assert.deepEqual(details, {
30
- diff: displayCarriageReturns(raw.diff),
31
- displayDiff: displayCarriageReturns(logical.diff),
32
- firstChangedLine: raw.firstChangedLine,
33
- patch: generateUnifiedPatch("file.txt", before, after),
34
- publication,
35
- ...versions,
60
+ diff: displayCarriageReturns(logical.diff),
36
61
  });
37
62
  });
38
63
  }
39
-
40
- test("mutation anchors use the full byte budget when no omission notice is needed", () => {
41
- const anchors = createAnchorFormatter(4);
42
- const heading = "Updated anchors:";
43
- const prefix = `\n${heading}\n`;
44
- const available = MAX_BLOCK_BYTES - Buffer.byteLength(prefix + anchors.row(1, ""));
45
- const content = "界".repeat(Math.floor(available / 3)) + "x".repeat(available % 3);
46
- const expected = prefix + anchors.row(1, content);
47
- assert.equal(Buffer.byteLength(expected), MAX_BLOCK_BYTES);
48
- const report = formatMutationAnchors([], [content], [0], anchors, heading, new Set([0]));
49
- assert.equal(report, expected);
50
- });
51
-
52
- test("mutation anchors count separators exactly at the byte boundary", () => {
53
- const anchors = createAnchorFormatter(4);
54
- const heading = "Updated anchors:";
55
- const prefix = `\n${heading}\n`;
56
- const tail = "tail";
57
- const overhead = Buffer.byteLength(`${prefix}${anchors.row(1, "")}\n${anchors.row(2, tail)}`);
58
- const lines = ["x".repeat(MAX_BLOCK_BYTES - overhead), tail];
59
- const expected = prefix + lines.map((line, index) => anchors.row(index + 1, line)).join("\n");
60
- assert.equal(Buffer.byteLength(expected), MAX_BLOCK_BYTES);
61
- assert.equal(
62
- formatMutationAnchors([], lines, [0, 1], anchors, heading, new Set([0, 1])),
63
- expected,
64
- );
65
- });
66
-
67
- test("mutation anchors reserve the notice after overflow and retain later fitting rows", () => {
68
- const anchors = createAnchorFormatter(4);
69
- const heading = "Updated anchors:";
70
- const overhead = Buffer.byteLength(`\n${heading}\n${anchors.row(1, "")}`);
71
- for (const extra of [0, 1, MAX_BLOCK_BYTES]) {
72
- const lines = ["x".repeat(MAX_BLOCK_BYTES - overhead + extra), "short", "last"];
73
- const report = formatMutationAnchors(
74
- [],
75
- lines,
76
- [0, 1, 2].values(),
77
- anchors,
78
- heading,
79
- new Set([0, 1, 2]),
80
- );
81
- assert.ok(Buffer.byteLength(report) <= MAX_BLOCK_BYTES);
82
- assert.match(report, /additional anchors omitted/);
83
- assert.ok(!report.includes(anchors.row(1, lines[0])));
84
- assert.ok(report.includes(`${anchors.row(2, lines[1])}\n${anchors.row(3, lines[2])}`));
85
- }
86
- });
87
-
88
- test("compact mutation anchors have no row cap and stop at the byte budget", () => {
89
- const anchors = createAnchorFormatter(4);
90
- for (const count of [80, 3000]) {
91
- const lines = Array.from({ length: count }, (_, index) => `changed ${index}`);
92
- const report = formatMutationAnchors([], lines, lines.keys(), anchors, "Updated anchors:");
93
- const rows = report.match(/^\d+#[0-9A-Z]+$/gm) ?? [];
94
- assert.ok(rows.length > 40);
95
- assert.doesNotMatch(report, /│/);
96
- assert.ok(Buffer.byteLength(report) <= MAX_BLOCK_BYTES);
97
- if (count === 80) {
98
- assert.equal(rows.length, count);
99
- assert.doesNotMatch(report, /omitted/);
100
- } else {
101
- assert.ok(rows.length < count);
102
- assert.match(report, /additional anchors omitted/);
103
- }
104
- assert.deepEqual(
105
- rows,
106
- lines.slice(0, rows.length).map((line, index) => anchors.token(index + 1, line)),
107
- );
108
- }
109
- });
@@ -1,140 +1,112 @@
1
+ /**
2
+ * Mutation report building: details, diffs, and post-process outcome
3
+ * classification.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
1
8
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
- import {
3
- FileMutationError,
4
- type CommitResult,
5
- type MutationVersions,
6
- type PublicationStatus,
7
- } from "./file-commit.ts";
8
- import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
9
- import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
9
+ import { FileMutationError, type CommitResult, type FreshnessObservation } from "./file-commit.ts";
10
+ import { generateDiffString } from "@earendil-works/pi-coding-agent";
11
+ import { displayCarriageReturns } from "./anchor-format.ts";
10
12
  import { normalizeLineEndings } from "../core/lines.ts";
11
- import { errorMessage } from "../core/errors.ts";
12
- import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
13
+ import type {
14
+ CommandResult,
15
+ CommandStatus,
16
+ FailureReport,
17
+ MutationToolName,
18
+ PublicationStatus,
19
+ SuccessFacts,
20
+ SuccessReport,
21
+ } from "./report-schema.ts";
22
+ import { causeOf, reportResult, type ReportDetails } from "./report.ts";
23
+ import type { OutputBudgets } from "./budgets.ts";
24
+ import type { ActionFusionProgress } from "./action-fusion.ts";
13
25
 
14
- /** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
15
- export function generateMutationDetails(
16
- path: string,
17
- before: string,
18
- after: string,
19
- versions: MutationVersions,
20
- publication: PublicationStatus,
21
- ) {
22
- const { diff, firstChangedLine } = generateDiffString(before, after);
23
- const logicalBefore = normalizeLineEndings(before);
24
- const logicalAfter = normalizeLineEndings(after);
25
- const displayDiff =
26
- logicalBefore === before && logicalAfter === after
27
- ? diff
28
- : generateDiffString(logicalBefore, logicalAfter).diff;
29
- return {
30
- diff: displayCarriageReturns(diff),
31
- displayDiff: displayCarriageReturns(displayDiff),
32
- firstChangedLine,
33
- patch: generateUnifiedPatch(path, before, after),
34
- publication,
35
- ...versions,
36
- };
26
+ /** Final success carries tool details; final failure carries only its report; neither carries progress. */
27
+ export type MutationFinalDetails<TDetails> =
28
+ | (TDetails & ReportDetails<SuccessReport> & { actionFusion?: never })
29
+ | (ReportDetails<FailureReport> & { actionFusion?: never });
30
+
31
+ /** Progress can precede the mutation and carries no final report yet. */
32
+ export type MutationResultDetails<TDetails> =
33
+ | MutationFinalDetails<TDetails>
34
+ | (Partial<TDetails> & { actionFusion: ActionFusionProgress });
35
+
36
+ /** The diff of the shared logical text, which the card and Pi's session export both show. */
37
+ export function generateMutationDetails(before: string, after: string) {
38
+ const { diff } = generateDiffString(normalizeLineEndings(before), normalizeLineEndings(after));
39
+ return { diff: displayCarriageReturns(diff) };
37
40
  }
38
41
 
39
42
  /** Keep result-building failures distinct from file publication failures. */
40
- export function postProcessMutation<T>(
41
- tool: string,
42
- publication: PublicationStatus,
43
- build: () => T,
44
- ): T {
43
+ export function postProcessMutation<T>(publication: PublicationStatus, build: () => T): T {
45
44
  try {
46
45
  return build();
47
46
  } catch (error) {
48
47
  throw new FileMutationError(
48
+ "POST_PROCESS_FAILED",
49
49
  "post_process",
50
50
  publication,
51
- `${tool} result generation failed; publication=${publication}: ${errorMessage(error)}`,
51
+ "Result generation failed.",
52
52
  { cause: error },
53
53
  );
54
54
  }
55
55
  }
56
56
 
57
- /** A published (or no-op) mutation with its commit facts, before anchors are released. */
58
- export interface MutationOutcome<TDetails> {
59
- readonly result: AgentToolResult<TDetails>;
57
+ /** The facts a mutation tool states about its own outcome. */
58
+ export type MutationFacts<TTool extends MutationToolName = MutationToolName> = {
59
+ [T in TTool]: SuccessFacts<T> & {
60
+ [K in Exclude<"matches" | "created", keyof SuccessFacts<T>>]?: never;
61
+ };
62
+ }[TTool];
63
+
64
+ /** A published (or no-op) mutation with its commit facts, before freshness is known. */
65
+ export interface MutationOutcome<TDetails, TTool extends MutationToolName = MutationToolName> {
60
66
  /** Publication and revisions from the commit layer; later steps never read them back from details. */
61
67
  readonly commit: CommitResult;
62
- /** Fresh anchor report for the committed text; absent for tools that never report anchors. */
63
- readonly anchors?: string;
68
+ readonly details: TDetails;
69
+ readonly facts: MutationFacts<TTool>;
64
70
  }
65
71
 
66
- /** Freshness known from the commit layer alone, before any later observation. */
67
- export function commitFreshness(commit: MutationVersions): "unchanged" | "changed" {
68
- return commit.publishedRevision === commit.observedRevision ? "unchanged" : "changed";
72
+ /** The text blocks of a command result, joined as then_run reports its output. */
73
+ export function commandText(content: CommandResult["content"]): string {
74
+ return content
75
+ .filter((block) => block.type === "text")
76
+ .map((block) => block.text)
77
+ .join("\n");
69
78
  }
70
79
 
71
- /** The single notice for a target whose published revision was not confirmed unchanged. */
72
- export function staleTargetNotice(marker = ""): string {
73
- return `${marker ? `${marker} ` : ""}Target not confirmed unchanged since publication; anchors are withheld and earlier anchors may no longer match. Re-read before further edits.`;
80
+ /** What Action Fusion states about the command; it never restates file state. */
81
+ export interface CommandFacts {
82
+ readonly status: CommandStatus;
83
+ /** Absent when the command never produced a result. */
84
+ readonly result?: CommandResult;
85
+ /** A progress observer failed; command and file outcomes are unaffected. */
86
+ readonly progressError?: unknown;
74
87
  }
75
88
 
76
- /**
77
- * Release the result: append anchors to the summary when the target is fresh,
78
- * otherwise add the stale notice (prefixed by `staleMarker`, e.g. then_run's).
79
- */
80
- export function finalizeMutation<T>(
81
- { result, anchors }: MutationOutcome<T>,
82
- fresh: boolean,
83
- staleMarker = "",
84
- ): AgentToolResult<T> {
85
- if (!fresh) {
86
- return {
87
- ...result,
88
- content: [...result.content, { type: "text", text: staleTargetNotice(staleMarker) }],
89
- };
90
- }
91
- if (!anchors) return result;
92
- return {
93
- ...result,
94
- content: result.content.map((block, index) =>
95
- index === 0 && block.type === "text" ? { ...block, text: block.text + anchors } : block,
96
- ),
97
- };
98
- }
99
-
100
- /** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
101
- export function formatMutationAnchors(
102
- beforeLines: readonly string[],
103
- lines: readonly string[],
104
- indices: Iterable<number>,
105
- anchors: AnchorFormatter,
106
- heading: string,
107
- contentIndices?: ReadonlySet<number>,
108
- ): string {
109
- const notice = `\n… (additional anchors omitted: ${formatKiB(MAX_BLOCK_BYTES)} limit; use read for omitted positions)`;
110
- const prefix = `\n${heading}\n`;
111
- let rows: string[] = [];
112
- let bytes = Buffer.byteLength(prefix);
113
- let omitted = false;
114
- const append = (row: string): boolean => {
115
- const rowBytes = Buffer.byteLength(row) + (rows.length ? 1 : 0);
116
- if (bytes + rowBytes > MAX_BLOCK_BYTES) return false;
117
- rows.push(row);
118
- bytes += rowBytes;
119
- return true;
120
- };
121
- for (const index of indices) {
122
- const content = lines[index];
123
- // Compare source content, not short hashes: a collision must not suppress a changed row.
124
- // Deletion successors (contentIndices) shifted into this position and must not be skipped.
125
- if (beforeLines[index] === content && !contentIndices?.has(index)) continue;
126
- const row = contentIndices?.has(index)
127
- ? anchors.row(index + 1, content)
128
- : anchors.token(index + 1, content);
129
- if (append(row) || omitted) continue;
130
- // Only reserve a notice after overflow. Reconsider earlier rows in order so
131
- // a newly oversized row does not prevent later, shorter rows from fitting.
132
- omitted = true;
133
- const previousRows = rows;
134
- rows = [];
135
- bytes = Buffer.byteLength(prefix) + Buffer.byteLength(notice);
136
- for (const previous of previousRows) append(previous);
137
- append(row);
138
- }
139
- return rows.length || omitted ? `${prefix}${rows.join("\n")}${omitted ? notice : ""}` : "";
89
+ /** Build the mutation report from commit, freshness, and command facts; the TUI uses its diff details. */
90
+ export function finalizeMutation<TDetails extends object, TTool extends MutationToolName>(
91
+ tool: TTool,
92
+ path: string,
93
+ { commit, details, facts }: MutationOutcome<TDetails, NoInfer<TTool>>,
94
+ observation: FreshnessObservation,
95
+ command: CommandFacts | undefined,
96
+ budget: OutputBudgets,
97
+ ): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
98
+ const fresh = observation.freshness === "unchanged";
99
+ const output = command?.result ? commandText(command.result.content) : "";
100
+ // Tool-indexed facts preserve the correlation that object spread loses.
101
+ const report = {
102
+ tool,
103
+ path,
104
+ publication: commit.publication,
105
+ ...facts,
106
+ freshness: fresh ? undefined : observation.freshness,
107
+ freshnessError: causeOf(observation.error, budget.fieldBytes),
108
+ then_run: command ? { status: command.status, ...(output ? { output } : {}) } : undefined,
109
+ progressError: causeOf(command?.progressError, budget.fieldBytes),
110
+ } as SuccessReport;
111
+ return reportResult(report, [], details);
140
112
  }