@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -0,0 +1,238 @@
1
+ import { diffArrays } from "diff";
2
+ import type { CopiedSpan } from "../core/copy-span.ts";
3
+ import { indexSourceLines } from "../core/lines.ts";
4
+
5
+ const CONTEXT_LINES = 4;
6
+ // Bound the search by changed lines so large ranges with a few edits can still align.
7
+ const MAX_ALIGNMENT_EDITS = 128;
8
+
9
+ type LineIndex = ReturnType<typeof indexSourceLines>;
10
+
11
+ function boundaryAtOrAfter(lines: LineIndex, offset: number): number {
12
+ let low = 0;
13
+ let high = lines.length + 1;
14
+ while (low < high) {
15
+ const middle = low + Math.floor((high - low) / 2);
16
+ if (lines.start(middle) < offset) low = middle + 1;
17
+ else high = middle;
18
+ }
19
+ return low;
20
+ }
21
+
22
+ function sameLogicalText(
23
+ source: LineIndex,
24
+ target: LineIndex,
25
+ copied: readonly CopiedSpan[],
26
+ ): boolean {
27
+ if (source.length !== target.length) return false;
28
+ if (source.length === 0) return true;
29
+
30
+ const last = source.length - 1;
31
+ // All earlier rows are terminated. At EOF, the terminator is part of logical equality.
32
+ const sourceTerminated = source.end(last) < source.start(last + 1);
33
+ const targetTerminated = target.end(last) < target.start(last + 1);
34
+ if (sourceTerminated !== targetTerminated) return false;
35
+
36
+ let row = 0;
37
+ for (const { sourceStart, targetStart, length } of copied) {
38
+ while (row < last && source.start(row) < sourceStart) {
39
+ if (source.content(row) !== target.content(row)) return false;
40
+ row++;
41
+ }
42
+ if (row === last) break;
43
+
44
+ const offset = source.start(row) - sourceStart;
45
+ if (offset >= length || offset !== target.start(row) - targetStart) continue;
46
+ // Same-numbered starts in one span prove equality through its last copied LF.
47
+ // Compare the last row directly: copying to one EOF can leave a suffix at the other.
48
+ row = Math.min(last, boundaryAtOrAfter(source, sourceStart + length + 1) - 1);
49
+ }
50
+ for (; row < source.length; row++) {
51
+ if (source.content(row) !== target.content(row)) return false;
52
+ }
53
+ return true;
54
+ }
55
+
56
+ // Match a copied EOF body to its original row when adding or removing its neighbor
57
+ // also adds or removes the separator. A terminator-only change still shows as an edit.
58
+ function copiedEofBody(
59
+ eof: LineIndex,
60
+ other: LineIndex,
61
+ eofStart: number,
62
+ otherStart: number,
63
+ length: number,
64
+ otherFirst: number,
65
+ ): number | undefined {
66
+ const eofRow = eof.length - 1;
67
+ const bodyEnd = eof.start(eof.length);
68
+ if (eofStart + length !== bodyEnd || eof.end(eofRow) !== bodyEnd) return;
69
+ const skip = eof.start(eofRow) - eofStart;
70
+ if (skip < 0) return;
71
+ const start = otherStart + skip;
72
+ const row = boundaryAtOrAfter(other, start);
73
+ if (
74
+ row >= otherFirst &&
75
+ row < other.length - 1 &&
76
+ other.start(row) === start &&
77
+ other.end(row) === otherStart + length
78
+ )
79
+ return row;
80
+ }
81
+
82
+ type RowToken = string | symbol;
83
+
84
+ function rowTokens(index: LineIndex, start: number, end: number): RowToken[] {
85
+ const tokens: RowToken[] = [];
86
+ for (let row = start; row < end; row++) {
87
+ const content = index.content(row);
88
+ tokens.push(index.end(row) < index.start(row + 1) ? `${content}\n` : content);
89
+ }
90
+ return tokens;
91
+ }
92
+
93
+ /** Render copied full rows at their proven positions and diff the gaps in the logical LF view. */
94
+ export function generateRangeDiff(
95
+ before: string,
96
+ after: string,
97
+ copied: readonly CopiedSpan[],
98
+ ): string {
99
+ // A header BOM stays at byte zero even when the body of the first row moves.
100
+ const sharedBom = before.startsWith("\uFEFF") && after.startsWith("\uFEFF");
101
+ const source = lineIndex(before);
102
+ const target = lineIndex(after);
103
+
104
+ function lineIndex(text: string): LineIndex {
105
+ const lines = indexSourceLines(text);
106
+ return sharedBom ? { ...lines, start: (row) => (row === 0 ? 1 : lines.start(row)) } : lines;
107
+ }
108
+ // The card shows net logical changes even when edit operations rearrange identical rows.
109
+ if (sameLogicalText(source, target, copied)) return "";
110
+ // Pi's number column includes the empty slot after a final LF (or in an empty file).
111
+ const width = String(
112
+ Math.max(
113
+ source.length + Number(!before || before.endsWith("\n")),
114
+ target.length + Number(!after || after.endsWith("\n")),
115
+ ),
116
+ ).length;
117
+ const output: string[] = [];
118
+ let oldRow = 0;
119
+ let newRow = 0;
120
+ let equalRows = 0;
121
+
122
+ function row(kind: " " | "-" | "+", index: LineIndex, line: number): void {
123
+ output.push(`${kind}${String(line + 1).padStart(width)} ${index.content(line)}`);
124
+ }
125
+
126
+ function flushEqual(tailContext: number): void {
127
+ const head = output.length ? Math.min(equalRows, CONTEXT_LINES) : 0;
128
+ const tail = Math.max(head, equalRows - tailContext);
129
+ for (let i = 0; i < head; i++) row(" ", source, oldRow + i);
130
+ if (tail > head) output.push(`${" ".repeat(width + 2)}...`);
131
+ for (let i = tail; i < equalRows; i++) row(" ", source, oldRow + i);
132
+ oldRow += equalRows;
133
+ newRow += equalRows;
134
+ equalRows = 0;
135
+ }
136
+
137
+ function emitChange(kind: "-" | "+", count: number): void {
138
+ if (!count) return;
139
+ flushEqual(CONTEXT_LINES);
140
+ if (kind === "-") {
141
+ for (let i = 0; i < count; i++) row("-", source, oldRow++);
142
+ } else {
143
+ for (let i = 0; i < count; i++) row("+", target, newRow++);
144
+ }
145
+ }
146
+
147
+ function provenEofPair(
148
+ { sourceStart, targetStart, length }: CopiedSpan,
149
+ oldStart: number,
150
+ newStart: number,
151
+ ) {
152
+ const newMatch = copiedEofBody(source, target, sourceStart, targetStart, length, newStart);
153
+ if (newMatch !== undefined) return { old: source.length - 1, new: newMatch };
154
+ const oldMatch = copiedEofBody(target, source, targetStart, sourceStart, length, oldStart);
155
+ if (oldMatch !== undefined) return { old: oldMatch, new: target.length - 1 };
156
+ }
157
+
158
+ function diffGap(oldEnd: number, newEnd: number, eofSpan?: CopiedSpan): void {
159
+ const oldStart = oldRow + equalRows;
160
+ const newStart = newRow + equalRows;
161
+ const oldCount = oldEnd - oldStart;
162
+ const newCount = newEnd - newStart;
163
+ if (!oldCount || !newCount) {
164
+ emitChange("-", oldCount);
165
+ emitChange("+", newCount);
166
+ return;
167
+ }
168
+
169
+ const oldRows = rowTokens(source, oldStart, oldEnd);
170
+ const newRows = rowTokens(target, newStart, newEnd);
171
+ const proven = eofSpan && provenEofPair(eofSpan, oldStart, newStart);
172
+ // A proven row must not compare equal to an unrelated occurrence of the same text.
173
+ const identity = Symbol();
174
+ if (proven) oldRows[proven.old - oldStart] = newRows[proven.new - newStart] = identity;
175
+ const parts = diffArrays(oldRows, newRows, { maxEditLength: MAX_ALIGNMENT_EDITS });
176
+ // Keep proven identity even if the search is exhausted or its shortest path skips the pair.
177
+ if (
178
+ !parts ||
179
+ (proven &&
180
+ !parts.some((part) => !part.added && !part.removed && part.value.includes(identity)))
181
+ ) {
182
+ if (proven) {
183
+ emitBlock(proven.old - oldStart, proven.new - newStart);
184
+ equalRows++;
185
+ }
186
+ emitBlock(oldCount, newCount);
187
+ return;
188
+ }
189
+ for (const part of parts) {
190
+ if (part.removed) emitChange("-", part.count);
191
+ else if (part.added) emitChange("+", part.count);
192
+ else equalRows += part.count;
193
+ }
194
+
195
+ function emitBlock(toOld: number, toNew: number) {
196
+ // Pending equal rows are aligned but have not advanced the output cursors.
197
+ const fromOld = oldRow + equalRows - oldStart;
198
+ const fromNew = newRow + equalRows - newStart;
199
+ const commonLimit = Math.min(toOld - fromOld, toNew - fromNew);
200
+ let prefix = 0;
201
+ while (prefix < commonLimit && oldRows[fromOld + prefix] === newRows[fromNew + prefix])
202
+ prefix++;
203
+ let suffix = 0;
204
+ while (
205
+ suffix < commonLimit - prefix &&
206
+ oldRows[toOld - suffix - 1] === newRows[toNew - suffix - 1]
207
+ )
208
+ suffix++;
209
+ equalRows += prefix;
210
+ emitChange("-", toOld - fromOld - prefix - suffix);
211
+ emitChange("+", toNew - fromNew - prefix - suffix);
212
+ equalRows += suffix;
213
+ }
214
+ }
215
+
216
+ for (const { sourceStart, targetStart, length } of copied) {
217
+ // If either start is partial, the first copied LF is the first possible joint boundary.
218
+ const firstSource = boundaryAtOrAfter(source, sourceStart);
219
+ const firstTarget = boundaryAtOrAfter(target, targetStart);
220
+ const skip = Math.max(
221
+ source.start(firstSource) - sourceStart,
222
+ target.start(firstTarget) - targetStart,
223
+ );
224
+ if (skip >= length) continue;
225
+ const oldAnchor = boundaryAtOrAfter(source, sourceStart + skip);
226
+ const newAnchor = boundaryAtOrAfter(target, targetStart + skip);
227
+ const oldEnd = boundaryAtOrAfter(source, sourceStart + length + 1) - 1;
228
+ const newEnd = boundaryAtOrAfter(target, targetStart + length + 1) - 1;
229
+ // An unterminated last row is complete only at EOF on both sides.
230
+ const count = Math.min(oldEnd - oldAnchor, newEnd - newAnchor);
231
+ if (count <= 0) continue;
232
+ diffGap(oldAnchor, newAnchor);
233
+ equalRows += count;
234
+ }
235
+ diffGap(source.length, target.length, copied.at(-1));
236
+ if (output.length) flushEqual(0);
237
+ return output.join("\n");
238
+ }
@@ -5,18 +5,23 @@
5
5
  */
6
6
 
7
7
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
8
- import { FileMutationError, type CommitResult, type FreshnessObservation } from "./file-commit.ts";
9
- import { generateDiffString } from "@earendil-works/pi-coding-agent";
8
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
9
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
10
+ import type { ThenRunRequest } from "./fusion-arguments.ts";
11
+ import type { CommitResult, FreshnessObservation } from "./file-commit.ts";
12
+ import { generateRangeDiff } from "./mutation-diff.ts";
10
13
  import { displayCarriageReturns } from "./anchor-format.ts";
11
- import { errorMessage } from "../core/errors.ts";
12
- import { normalizeLineEndings } from "../core/lines.ts";
14
+ import { HashlineError } from "../core/errors.ts";
15
+ import type { CopiedSpan } from "../core/copy-span.ts";
13
16
  import type {
14
17
  ActionFusionProgress,
15
18
  CommandResult,
16
19
  CommandStatus,
17
20
  FailureReport,
18
21
  MutationToolName,
22
+ PublicationStatus,
19
23
  ReportTool,
24
+ MutationFacts,
20
25
  SuccessFacts,
21
26
  SuccessReport,
22
27
  } from "./report-schema.ts";
@@ -26,7 +31,7 @@ import {
26
31
  type FailureContext,
27
32
  type ReportDetails,
28
33
  } from "./report.ts";
29
- import { boundedText, causeOf } from "./report-cause.ts";
34
+ import { describeThrown } from "./report-cause.ts";
30
35
  import type { OutputBudgets } from "./budgets.ts";
31
36
 
32
37
  /** Final success carries tool details; final failure carries only its report; neither carries progress. */
@@ -40,18 +45,14 @@ export type MutationResultDetails<TDetails> =
40
45
  | (Partial<TDetails> & { actionFusion: ActionFusionProgress });
41
46
 
42
47
  /** The diff of the shared logical text, which the card and Pi's session export both show. */
43
- export function generateMutationDetails(before: string, after: string) {
44
- const { diff } = generateDiffString(normalizeLineEndings(before), normalizeLineEndings(after));
45
- return { diff: displayCarriageReturns(diff) };
48
+ export function generateMutationDetails(
49
+ before: string,
50
+ after: string,
51
+ copied: readonly CopiedSpan[],
52
+ ) {
53
+ return { diff: displayCarriageReturns(generateRangeDiff(before, after, copied)) };
46
54
  }
47
55
 
48
- /** The facts a mutation tool states about its own outcome. */
49
- export type MutationFacts<TTool extends MutationToolName = MutationToolName> = {
50
- [T in TTool]: SuccessFacts<T> & {
51
- [K in Exclude<"matches", keyof SuccessFacts<T>>]?: never;
52
- };
53
- }[TTool];
54
-
55
56
  /** A published (or no-op) mutation with its commit facts, before freshness is known. */
56
57
  export interface MutationOutcome<TDetails, TTool extends MutationToolName = MutationToolName> {
57
58
  /** Publication and revisions from the commit layer; later steps never read them back from details. */
@@ -60,89 +61,111 @@ export interface MutationOutcome<TDetails, TTool extends MutationToolName = Muta
60
61
  readonly facts: MutationFacts<TTool>;
61
62
  }
62
63
 
63
- /** The text blocks of a command result, joined as then_run reports its output. */
64
- export function commandText(content: CommandResult["content"]): string {
65
- return content
66
- .filter((block) => block.type === "text")
67
- .map((block) => block.text)
68
- .join("\n");
64
+ /** The first failure of a progress observer; any thrown value, `undefined` included. */
65
+ interface ObserverFailure {
66
+ readonly error: unknown;
69
67
  }
70
68
 
71
- /** What Action Fusion states about the command; it never restates file state. */
69
+ /** Bash's model-facing blocks and the script outcome for this follow-up. */
72
70
  export interface CommandFacts {
73
- readonly status: CommandStatus;
74
- /** Absent when the command never produced a result. */
75
- readonly result?: CommandResult;
76
- /** A progress observer failed; command and file outcomes are unaffected. */
77
- readonly progressError?: unknown;
71
+ readonly content: CommandResult["content"];
72
+ readonly script: NonNullable<SuccessFacts<MutationToolName>["then_run"]>;
78
73
  }
79
74
 
80
75
  /**
81
- * A mutation that did not complete, so its then_run command never ran. Action
82
- * Fusion owns the command status; the mutation's own failure stays unchanged.
76
+ * A completed mutation. A call without then_run settles alone, and its commit result states its
77
+ * freshness; a fused call adds the command and the freshness last observed: after the session's
78
+ * Bash call returns, or before it when the command was cancelled or skipped first.
83
79
  */
84
- export class CommandNotRun extends Error {
85
- readonly status: Extract<CommandStatus, "skipped" | "cancelled">;
86
- /** A progress observer failed; the mutation's failure is unaffected. */
87
- readonly progressError: unknown;
80
+ export type SettledMutation<TDetails, TTool extends MutationToolName> =
81
+ | { readonly kind: "alone"; readonly outcome: MutationOutcome<TDetails, TTool> }
82
+ | {
83
+ readonly kind: "fused";
84
+ readonly outcome: MutationOutcome<TDetails, TTool>;
85
+ readonly observation: FreshnessObservation;
86
+ readonly command: CommandFacts;
87
+ };
88
88
 
89
- constructor(
90
- error: unknown,
91
- status: Extract<CommandStatus, "skipped" | "cancelled">,
92
- progressError?: unknown,
93
- ) {
94
- super(errorMessage(error), { cause: error });
95
- this.name = "CommandNotRun";
96
- this.status = status;
97
- this.progressError = progressError;
98
- }
89
+ /** Command facts available even if reading the result or settling the mutation fails. */
90
+ export interface MutationCommandFacts {
91
+ readonly status?: CommandStatus;
92
+ /** The session Bash result's request to stop after this tool batch, as Pi gave it. */
93
+ readonly terminate?: boolean;
94
+ readonly progressFailure?: ObserverFailure;
99
95
  }
100
96
 
101
- /**
102
- * Classify a mutation tool's failure with what only a mutation states: what it published and,
103
- * when the call was fused, why its command never ran.
104
- */
97
+ /** One validated mutation call, as the scheduler receives it. */
98
+ export interface MutationCall<TDetails, TTool extends MutationToolName> {
99
+ readonly toolCallId: string;
100
+ readonly absolutePath: string;
101
+ /** The model's optional follow-up command; only Action Fusion's schema admits it. */
102
+ readonly thenRun: ThenRunRequest | undefined;
103
+ readonly mutate: () => Promise<MutationOutcome<TDetails, TTool>>;
104
+ readonly signal: AbortSignal;
105
+ readonly ctx: ExtensionToolContext;
106
+ readonly onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
107
+ readonly recordCommand: (facts: MutationCommandFacts) => void;
108
+ }
109
+
110
+ /** Runs mutation calls; chosen once at registration from the actionFusion setting. */
111
+ export type MutationScheduler = <TDetails extends object, TTool extends MutationToolName>(
112
+ call: MutationCall<TDetails, TTool>,
113
+ ) => Promise<SettledMutation<TDetails, TTool>>;
114
+
115
+ function observerFailure(failure: ObserverFailure | undefined, budget: OutputBudgets) {
116
+ return failure && describeThrown(failure.error, budget.fieldBytes);
117
+ }
118
+
119
+ /** Classify the failure using publication and command facts already recorded by their owners. */
105
120
  export function describeMutationFailure(
106
121
  tool: ReportTool,
107
122
  caught: unknown,
108
- context: FailureContext,
123
+ context: FailureContext & {
124
+ readonly commit?: CommitResult;
125
+ readonly failedPublication?: PublicationStatus;
126
+ readonly command: MutationCommandFacts;
127
+ },
109
128
  ): FailureReport {
110
- const command = caught instanceof CommandNotRun ? caught : undefined;
111
- // The mutation's own failure, unchanged.
112
- const error = command ? command.cause : caught;
129
+ const { commit, failedPublication = "NOT_PUBLISHED", command } = context;
130
+ const error = commit
131
+ ? new HashlineError("POST_PROCESS_FAILED", "Result generation failed.", { cause: caught })
132
+ : caught;
113
133
  return describeFailure(tool, error, context, {
114
- publication: error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED",
115
- then_run: command ? { status: command.status } : undefined,
116
- progressError: causeOf(command?.progressError, context.budget.fieldBytes),
134
+ publication: commit?.publication ?? failedPublication,
135
+ then_run: command.status && { status: command.status },
136
+ progressError: observerFailure(command.progressFailure, context.budget),
117
137
  });
118
138
  }
119
139
 
120
- /** Build the mutation report from commit, freshness, and command facts; the TUI uses its diff details. */
121
- export function finalizeMutation<TDetails extends object, TTool extends MutationToolName>(
122
- tool: TTool,
140
+ /**
141
+ * Build the mutation result from commit, freshness, and command facts; the TUI uses its diff
142
+ * details. The model receives Bash content before the status report. Scripts receive the
143
+ * follow-up status and Bash's structured fields in `then_run`.
144
+ */
145
+ export function finalizeMutation<TDetails extends object>(
123
146
  path: string,
124
- { commit, details, facts }: MutationOutcome<TDetails, NoInfer<TTool>>,
125
- observation: FreshnessObservation,
126
- command: CommandFacts | undefined,
147
+ settled: SettledMutation<TDetails, MutationToolName>,
148
+ progressFailure: ObserverFailure | undefined,
127
149
  budget: OutputBudgets,
128
150
  ): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
129
- const fresh = observation.freshness === "unchanged";
130
- const output = command?.result ? commandText(command.result.content) : "";
131
- // Tool-indexed facts preserve the correlation that object spread loses.
132
- const report = {
133
- tool,
134
- path,
135
- publication: commit.publication,
136
- ...facts,
137
- freshness: fresh ? undefined : observation.freshness,
138
- freshnessError: causeOf(observation.error, budget.fieldBytes),
139
- then_run: command
140
- ? {
141
- status: command.status,
142
- ...(output ? { output: boundedText(output, budget.fieldBytes) } : {}),
143
- }
144
- : undefined,
145
- progressError: causeOf(command?.progressError, budget.fieldBytes),
146
- } as SuccessReport;
147
- return reportResult(report, [], details);
151
+ const { commit, details, facts } = settled.outcome;
152
+ const observation: FreshnessObservation = settled.kind === "alone" ? commit : settled.observation;
153
+ const command = settled.kind === "fused" ? settled.command : undefined;
154
+ return reportResult(
155
+ {
156
+ ...facts,
157
+ path,
158
+ publication: commit.publication,
159
+ freshness: observation.freshness === "unchanged" ? undefined : observation.freshness,
160
+ freshnessError:
161
+ observation.freshness === "unknown"
162
+ ? describeThrown(observation.error, budget.fieldBytes)
163
+ : undefined,
164
+ then_run: command?.script,
165
+ progressError: observerFailure(progressFailure, budget),
166
+ },
167
+ command?.content ?? [],
168
+ budget,
169
+ { details },
170
+ );
148
171
  }