@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
@@ -32,16 +32,9 @@ import {
32
32
  type MutationTarget,
33
33
  type MutationToolEnvironment,
34
34
  } from "./mutation-runner.ts";
35
- import { argumentItems, type ReportArgumentIssue } from "./argument-validation.ts";
35
+ import type { ReportArgumentIssue } from "./argument-validation.ts";
36
36
  import { filePathField, literalUnion } from "./schema.ts";
37
37
 
38
- /** Split a validated anchor token; prepareArguments and the schema already checked it. */
39
- function parseAnchor(value: string): Anchor;
40
- function parseAnchor(value: string | undefined): Anchor | undefined;
41
- function parseAnchor(value: string | undefined) {
42
- return value === undefined ? undefined : parseAnchorToken(value)!;
43
- }
44
-
45
38
  /** Operation item fields besides `action`. */
46
39
  type EditItemField = (typeof EDIT_ANCHOR_FIELDS)[number] | "lines";
47
40
 
@@ -70,7 +63,7 @@ const EDIT_OPS = {
70
63
  },
71
64
  append: { meaning: "Add lines at the end of the file.", required: ["lines"] },
72
65
  prepend: { meaning: "Add lines at the start of the file.", required: ["lines"] },
73
- } as const satisfies Record<string, EditOpSpec>;
66
+ } as const satisfies Record<Edit["op"], EditOpSpec>;
74
67
  type EditOpName = keyof typeof EDIT_OPS;
75
68
  const EDIT_OP_NAMES = Object.keys(EDIT_OPS) as EditOpName[];
76
69
 
@@ -127,9 +120,33 @@ type EditSchema = ReturnType<typeof buildEditSchema>;
127
120
 
128
121
  type EditParams = Static<EditSchema>;
129
122
 
130
- type EditOpInput = EditParams["steps"][number];
131
123
  type EditOpSchema = EditSchema["properties"]["steps"]["items"];
132
124
 
125
+ function editArgumentRules(item: EditOpSchema) {
126
+ const { action: _action, ...fields } = item.properties;
127
+ // Object keys preserve the step schema's diagnostic order.
128
+ const fieldNames = Object.keys(fields) as EditItemField[];
129
+ return new Map(
130
+ EDIT_OP_NAMES.map((action) => {
131
+ const spec: EditOpSpec = EDIT_OPS[action];
132
+ const fix = `"${action}": ${describeEditOp(spec)}`;
133
+ const rules = fieldNames.map((field) => {
134
+ if (spec.required.includes(field))
135
+ return {
136
+ field,
137
+ missing: {
138
+ reason: `is required for "${action}"`,
139
+ fix: Reflect.get(fields[field], "description"),
140
+ },
141
+ };
142
+ if (spec.optional?.includes(field)) return { field };
143
+ return { field, present: { reason: "is not allowed", fix } };
144
+ });
145
+ return [action as unknown, { action, rules }] as const;
146
+ }),
147
+ );
148
+ }
149
+
133
150
  /** How to correct edit argument issues; each reason states only what is wrong. */
134
151
  const EDIT_ISSUE_FIX = {
135
152
  emptyReplace: 'Use {"action":"delete"} to remove lines, or supply the replacement lines.',
@@ -138,115 +155,121 @@ const EDIT_ISSUE_FIX = {
138
155
  hashLength: "Read or grep the file for current anchors.",
139
156
  } as const;
140
157
 
141
- /**
142
- * Report semantic argument issues: the fields each op takes, and field values
143
- * the schema cannot judge. Malformed shapes remain Pi's schema responsibility;
144
- * Pi has already removed null optional fields.
145
- */
146
- function checkEditArguments(
147
- args: unknown,
158
+ /** Decode a cited token and leave shape errors to the schema. */
159
+ function parseCitedAnchor(
160
+ value: unknown,
161
+ field: string,
148
162
  hashLen: number,
149
- item: EditOpSchema,
150
163
  report: ReportArgumentIssue,
151
- ): void {
152
- argumentItems((args as { steps?: unknown } | null)?.steps).forEach((value, index) => {
153
- if (value === null || typeof value !== "object") return;
154
- const edit = value as Record<string, unknown>;
155
- // The schema reports an unknown action; which fields it takes is then unknown.
156
- if (typeof edit.action !== "string" || !Object.hasOwn(EDIT_OPS, edit.action)) return;
157
- const name = edit.action as EditOpName;
158
- const spec: EditOpSpec = EDIT_OPS[name];
159
- const path = `steps[${index}]`;
160
- const accepted = new Set([...spec.required, ...(spec.optional ?? [])]);
161
- for (const [field, declaration] of Object.entries(item.properties)) {
162
- if (field === "action") continue;
163
- const given = edit[field] !== undefined;
164
- if (given && !accepted.has(field as EditItemField))
165
- report(`${path}.${field}`, "is not allowed", `"${name}": ${describeEditOp(spec)}`);
166
- else if (!given && spec.required.includes(field as EditItemField))
167
- report(
168
- `${path}.${field}`,
169
- `is required for "${name}"`,
170
- Reflect.get(declaration, "description"),
171
- );
172
- }
164
+ ): Anchor | undefined {
165
+ if (typeof value !== "string") return undefined;
166
+ const token = parseAnchorToken(value);
167
+ if (!token) return undefined;
168
+ const safeLine = Number.isSafeInteger(token.line);
169
+ if (!safeLine)
170
+ report(field, "line number exceeds the safe integer range", EDIT_ISSUE_FIX.unsafeLine);
171
+ if (token.hash.length !== hashLen)
172
+ report(
173
+ field,
174
+ `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
175
+ EDIT_ISSUE_FIX.hashLength,
176
+ );
177
+ // A hash-length error still allows a range comparison, but an unsafe line does not.
178
+ return safeLine ? token : undefined;
179
+ }
173
180
 
174
- const lines = edit.lines;
175
- if (accepted.has("lines") && Array.isArray(lines)) {
176
- if (lines.length === 0) {
177
- report(
178
- `${path}.lines`,
179
- "is empty",
180
- name === "replace" ? EDIT_ISSUE_FIX.emptyReplace : EDIT_ISSUE_FIX.emptyLines,
181
- );
182
- }
183
- lines.forEach((line, lineIndex) => {
184
- const unwritable = typeof line === "string" ? unwritableTextError(line) : undefined;
185
- if (unwritable) report(`${path}.lines[${lineIndex}]`, unwritable.message);
186
- });
187
- }
188
- const cited: { anchor?: number; end?: number } = {};
189
- for (const field of EDIT_ANCHOR_FIELDS) {
190
- const anchor = edit[field];
191
- if (!accepted.has(field) || typeof anchor !== "string") continue;
192
- const token = parseAnchorToken(anchor);
193
- if (!token) continue;
194
- if (Number.isSafeInteger(token.line)) {
195
- cited[field] = token.line;
196
- } else {
197
- report(
198
- `${path}.${field}`,
199
- "line number exceeds the safe integer range",
200
- EDIT_ISSUE_FIX.unsafeLine,
201
- );
202
- }
203
- if (token.hash.length !== hashLen) {
204
- report(
205
- `${path}.${field}`,
206
- `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
207
- EDIT_ISSUE_FIX.hashLength,
208
- );
209
- }
210
- }
181
+ function checkEditBody(
182
+ lines: unknown,
183
+ path: string,
184
+ emptyFix: string,
185
+ report: ReportArgumentIssue,
186
+ ): string[] | undefined {
187
+ if (!Array.isArray(lines)) return undefined;
188
+ if (lines.length === 0) report(path, "is empty", emptyFix);
189
+ for (const [index, line] of lines.entries()) {
190
+ if (typeof line !== "string") continue;
191
+ const unwritable = unwritableTextError(line);
192
+ if (unwritable) report(`${path}[${index}]`, unwritable.message);
193
+ }
194
+ // The boundary releases the body only after the schema checks its item types.
195
+ return lines as string[];
196
+ }
211
197
 
212
- // The cited line numbers alone decide this, whatever the file holds. An
213
- // unsafe line number was reported above, and comparing it would add a false issue.
214
- if (cited.anchor !== undefined && cited.end !== undefined && cited.end < cited.anchor) {
215
- report(`${path}.end`, `line ${cited.end} is before anchor line ${cited.anchor}`);
216
- }
217
- });
198
+ function checkEditStep(
199
+ value: unknown,
200
+ path: string,
201
+ hashLen: number,
202
+ rules: ReturnType<typeof editArgumentRules>,
203
+ report: ReportArgumentIssue,
204
+ ) {
205
+ if (!(value instanceof Object)) return undefined;
206
+ // The schema reports an unknown action; which fields it takes is then unknown.
207
+ const rule = rules.get(Reflect.get(value, "action"));
208
+ if (!rule) return undefined;
209
+ const { action } = rule;
210
+ const admitted: Partial<Record<EditItemField, unknown>> = {};
211
+ for (const { field, missing, present } of rule.rules) {
212
+ const input: unknown = Reflect.get(value, field);
213
+ const issue = input === undefined ? missing : present;
214
+ if (issue) report(`${path}.${field}`, issue.reason, issue.fix);
215
+ else admitted[field] = input;
216
+ }
217
+ const body = checkEditBody(
218
+ admitted.lines,
219
+ `${path}.lines`,
220
+ action === "replace" ? EDIT_ISSUE_FIX.emptyReplace : EDIT_ISSUE_FIX.emptyLines,
221
+ report,
222
+ );
223
+ const anchor = parseCitedAnchor(admitted.anchor, `${path}.anchor`, hashLen, report);
224
+ const end = parseCitedAnchor(admitted.end, `${path}.end`, hashLen, report);
225
+ if (anchor && end && end.line < anchor.line)
226
+ report(`${path}.end`, `line ${end.line} is before anchor line ${anchor.line}`);
227
+ return { action, anchor, end, body };
218
228
  }
219
229
 
220
- /**
221
- * Translate validated public operations into core steps, parsing numeric anchor
222
- * positions. Argument checks guarantee each op carries exactly the fields it takes.
223
- */
224
- function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
225
- return ops.map((op) => {
226
- switch (op.action) {
227
- case "replace":
228
- return {
229
- op: "replace",
230
- anchor: parseAnchor(op.anchor!),
231
- end: parseAnchor(op.end),
232
- body: op.lines!,
233
- };
234
- case "delete":
235
- return { op: "delete", anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
236
- case "insert_after":
237
- case "insert_before":
238
- return { op: op.action, anchor: parseAnchor(op.anchor!), body: op.lines! };
239
- case "append":
240
- case "prepend":
241
- return { op: op.action, body: op.lines! };
242
- }
243
- });
230
+ type CheckedEditStep = {
231
+ [Op in Edit as Op["op"]]: Omit<Op, "op"> & { action: Op["op"] };
232
+ }[EditOpName];
233
+
234
+ function buildEdit(step: CheckedEditStep): Edit {
235
+ switch (step.action) {
236
+ case "append":
237
+ case "prepend":
238
+ return { op: step.action, body: step.body };
239
+ case "delete":
240
+ return { op: step.action, anchor: step.anchor, end: step.end };
241
+ case "replace":
242
+ return { op: step.action, anchor: step.anchor, body: step.body, end: step.end };
243
+ case "insert_after":
244
+ case "insert_before":
245
+ return { op: step.action, anchor: step.anchor, body: step.body };
246
+ default:
247
+ step satisfies never;
248
+ throw new Error("Accepted edit step has an unknown action.");
249
+ }
250
+ }
251
+
252
+ function parseEditArguments(
253
+ args: unknown,
254
+ hashLen: number,
255
+ rules: ReturnType<typeof editArgumentRules>,
256
+ report: ReportArgumentIssue,
257
+ ): () => Edit[] {
258
+ const steps = (args as { steps?: unknown } | null)?.steps;
259
+ const drafts = Array.isArray(steps)
260
+ ? steps.map((value: unknown, index) =>
261
+ checkEditStep(value, `steps[${index}]`, hashLen, rules, report),
262
+ )
263
+ : [];
264
+ // Schema validation admits only known actions and typed fields. The semantic check
265
+ // enforces their presence and parses every admitted anchor. The verdict precedes this map.
266
+ return () => (drafts as readonly CheckedEditStep[]).map(buildEdit);
244
267
  }
245
268
 
246
269
  /** Call header with total/per-kind operation counts and the result's diff counts. */
247
- function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
270
+ function editHeader(args: EditParams, theme: Theme, cwd: string, counts?: DiffCounts): string {
248
271
  let t = theme.fg("toolTitle", theme.bold("edit "));
249
- t += formatHeaderPath(args.path, theme);
272
+ t += formatHeaderPath(args.path, theme, cwd);
250
273
  const steps = Array.isArray(args.steps) ? args.steps : [];
251
274
  const n = steps.length;
252
275
  if (n) {
@@ -273,6 +296,7 @@ export function makeEditOverride(env: MutationToolEnvironment) {
273
296
  // Schema, verification, and recovery use the registered configuration.
274
297
  const { hashLen, shiftRadius } = env.config;
275
298
  const schema = buildEditSchema(hashLen);
299
+ const rules = editArgumentRules(schema.properties.steps.items);
276
300
 
277
301
  return {
278
302
  ...mutationToolBase({
@@ -286,9 +310,8 @@ export function makeEditOverride(env: MutationToolEnvironment) {
286
310
  "Batch all steps for one file into a single edit call, and send changes to different files in the same response; they do not interfere.",
287
311
  "Before citing a line after write, edit, or replace, get its anchor from a new read or grep. Only after edit, lines above the earliest changed line keep their anchors.",
288
312
  ],
289
- check: (args, report) =>
290
- checkEditArguments(args, hashLen, schema.properties.steps.items, report),
291
- run: (params, target) => runEdit(target, params.steps, hashLen, shiftRadius),
313
+ check: (args, report) => parseEditArguments(args, hashLen, rules, report),
314
+ run: (_params, target, edits) => runEdit(target, edits, hashLen, shiftRadius),
292
315
  }),
293
316
  ...diffCardRenderers("edit", "Editing…", editHeader),
294
317
  };
@@ -296,7 +319,7 @@ export function makeEditOverride(env: MutationToolEnvironment) {
296
319
 
297
320
  function runEdit(
298
321
  target: MutationTarget,
299
- editOps: readonly EditOpInput[],
322
+ edits: readonly Edit[],
300
323
  hashLen: number,
301
324
  shiftRadius: number,
302
325
  ) {
@@ -306,10 +329,10 @@ function runEdit(
306
329
  // Recovery reports checksum candidates from nearby lines, then the whole file
307
330
  // if needed. Every failed anchor still rejects the batch; callers inspect
308
331
  // candidates and resubmit with fresh anchors.
309
- const result = applyEdits(currentText, toCoreEdits(editOps), hashLen, shiftRadius);
332
+ const result = applyEdits(currentText, edits, hashLen, shiftRadius);
310
333
  if (!result.ok) {
311
334
  throw describeEditFailure(currentText, result.failures, anchorFormatter, target.budget);
312
335
  }
313
- return { text: result.text, facts: {} };
336
+ return { text: result.text, copied: result.copied, facts: { tool: "edit" } };
314
337
  });
315
338
  }
@@ -14,8 +14,16 @@ export function cancellationError(): HashlineError<"OPERATION_ABORTED"> {
14
14
  return new HashlineError("OPERATION_ABORTED", "Operation aborted.");
15
15
  }
16
16
 
17
- export function throwIfCancelled(signal: AbortSignal | undefined): void {
18
- if (signal?.aborted) throw cancellationError();
17
+ export function throwIfCancelled(signal: AbortSignal): void {
18
+ if (signal.aborted) throw cancellationError();
19
+ }
20
+
21
+ /**
22
+ * Pi omits the signal when nothing can cancel a call. A signal that never aborts stands in for it
23
+ * at the tool entry, so every layer below takes one.
24
+ */
25
+ export function callSignal(signal: AbortSignal | undefined): AbortSignal {
26
+ return signal ?? new AbortController().signal;
19
27
  }
20
28
 
21
29
  /**
@@ -108,8 +108,6 @@ function ambiguousCandidateNeighborhoods(
108
108
  };
109
109
  }
110
110
 
111
- const RESULT = { found: "shifted", ambiguous: "ambiguous", none: "unresolved" } as const;
112
-
113
111
  /** One failure entry: what was cited, then what the search found or what the cited line holds. */
114
112
  function failureEntry(
115
113
  f: AnchorFailure,
@@ -118,50 +116,50 @@ function failureEntry(
118
116
  budget: OutputBudgets,
119
117
  ): AnchorFailureFact {
120
118
  const rowTooLarge = `row exceeds ${formatByteSize(budget.fieldBytes)}`;
121
- const entry: { -readonly [K in keyof AnchorFailureFact]: AnchorFailureFact[K] } = {
119
+ const cited = {
122
120
  field: `steps[${f.opIndex}].${f.which}`,
123
121
  action: f.op,
124
122
  cited: anchors.reference(f.cited.line, f.cited.hash),
125
- result: RESULT[f.recovery.kind],
126
123
  };
127
124
  switch (f.recovery.kind) {
128
125
  case "found": {
129
126
  const { newLine, newHash } = f.recovery;
130
- entry.candidate = anchors.reference(newLine, newHash);
127
+ const shifted = {
128
+ ...cited,
129
+ result: "shifted" as const,
130
+ candidate: anchors.reference(newLine, newHash),
131
+ };
131
132
  const content = currentLines[newLine - 1];
132
133
  // The row budget matches the neighborhoods'; the anchor itself is already `candidate`.
133
- if (Buffer.byteLength(anchors.row(newLine, content), "utf8") <= budget.fieldBytes) {
134
- entry.content = displayCarriageReturns(content);
135
- } else {
136
- entry.notShown = rowTooLarge;
137
- }
138
- break;
134
+ return Buffer.byteLength(anchors.row(newLine, content), "utf8") <= budget.fieldBytes
135
+ ? { ...shifted, content: displayCarriageReturns(content) }
136
+ : { ...shifted, notShown: rowTooLarge };
139
137
  }
140
138
  case "ambiguous": {
141
139
  const candidates = selectAmbiguousCandidates(f.recovery.candidates);
142
- entry.candidates = candidates.map((candidate) =>
143
- anchors.reference(candidate.line, candidate.hash),
144
- );
145
140
  const omitted = f.recovery.candidates.length - candidates.length;
146
- if (omitted) entry.omittedCandidates = omitted;
147
- break;
141
+ return {
142
+ ...cited,
143
+ result: "ambiguous",
144
+ candidates: candidates.map((candidate) =>
145
+ anchors.reference(candidate.line, candidate.hash),
146
+ ),
147
+ ...(omitted ? { omittedCandidates: omitted } : {}),
148
+ };
148
149
  }
149
150
  case "none": {
151
+ const unresolved = { ...cited, result: "unresolved" as const };
150
152
  const content = currentLines[f.cited.line - 1];
151
- if (content === undefined) {
152
- entry.notShown = "cited line is out of range";
153
- break;
154
- }
153
+ if (content === undefined) return { ...unresolved, notShown: "cited line is out of range" };
155
154
  const row = anchors.row(f.cited.line, content);
156
- if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) entry.observed = row;
157
- else entry.notShown = rowTooLarge;
158
- break;
155
+ return Buffer.byteLength(row, "utf8") <= budget.fieldBytes
156
+ ? { ...unresolved, observed: row }
157
+ : { ...unresolved, notShown: rowTooLarge };
159
158
  }
160
159
  }
161
- return entry;
162
160
  }
163
161
 
164
- /** Classify a batch's anchor failures with their bounded facts. */
162
+ /** Classify a batch's anchor failures; each entry's rows fit the field budget, and the report layer bounds the list. */
165
163
  export function describeEditFailure(
166
164
  currentText: string,
167
165
  failures: readonly AnchorFailure[],
@@ -169,20 +167,9 @@ export function describeEditFailure(
169
167
  budget: OutputBudgets,
170
168
  ): HashlineError<"ANCHOR_MISMATCH"> {
171
169
  const currentLines = splitLines(currentText);
172
- // Leading entries whose compact JSON fits the block; whole entries are omitted, never cut.
173
- const kept: AnchorFailureFact[] = [];
174
- let bytes = 1; // Brackets less the comma charged to the first entry.
175
- for (const failure of failures) {
176
- const entry = failureEntry(failure, anchors, currentLines, budget);
177
- bytes += Buffer.byteLength(JSON.stringify(entry)) + 1;
178
- if (bytes > budget.blockBytes) break;
179
- kept.push(entry);
180
- }
181
- const omitted = failures.length - kept.length;
182
170
  return new HashlineError("ANCHOR_MISMATCH", "Anchors did not match the current file.", {
183
171
  facts: {
184
- failures: kept,
185
- ...(omitted ? { omittedFailures: omitted } : {}),
172
+ failures: failures.map((failure) => failureEntry(failure, anchors, currentLines, budget)),
186
173
  ...ambiguousCandidateNeighborhoods(currentLines, failures, anchors, budget),
187
174
  },
188
175
  });