@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,18 +1,14 @@
1
1
  /**
2
2
  * Override edit: hashline ops via structured `edits` (LINE#HASH anchors).
3
3
  *
4
- * Each op in `edits` references line anchors copied from read / grep / replace output
5
- * (or from a prior edit's "Updated anchors"). The core verifies each anchor live against
6
- * the current file content — no snapshot, no global stale check: a cited line
4
+ * Each op in `edits` references line anchors from read, grep, or edit failure diagnostics.
5
+ * The core verifies each anchor live against
6
+ * the current file content — no prior-read revision guard: a cited line
7
7
  * that changed (or was misremembered) fails its own anchor; unchanged lines
8
8
  * elsewhere never block the edit. The extension requires structured `edits` arrays
9
9
  * at execution; Pi may coerce a single object before validation. Legacy
10
10
  * oldText/newText inputs fail schema validation before mutation.
11
11
  *
12
- * On success the result carries fresh `LINE#HASH` anchors for the lines this
13
- * edit produced (and the line that shifted into a deletion gap), so the model
14
- * can chain edits without a re-read.
15
- *
16
12
  * Concurrency safety: read-modify-write is wrapped in withFileMutationQueue.
17
13
  * AbortSignal is honored — checked after read / before write.
18
14
  *
@@ -25,28 +21,27 @@ import {
25
21
  type ToolDefinition,
26
22
  type ToolRenderResultOptions,
27
23
  } from "@earendil-works/pi-coding-agent";
28
- import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
24
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
29
25
  import { Type, type Static } from "typebox";
30
- import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
26
+ import {
27
+ ACTION_FUSION_GUIDELINES,
28
+ withThenRunDescription,
29
+ withThenRunSchema,
30
+ type ThenRunInput,
31
+ } from "./action-fusion.ts";
31
32
  import { applyEdits } from "../core/apply.ts";
32
- import { splitLines } from "../core/lines.ts";
33
- import { unwritableTextReason } from "../core/text.ts";
34
- import type { Anchor, Edit } from "../core/types.ts";
33
+ import { unwritableTextError } from "../core/text.ts";
34
+ import { EDIT_ANCHOR_FIELDS, type Anchor, type Edit } from "../core/types.ts";
35
35
  import type { HashlineEditConfig } from "./config.ts";
36
- import {
37
- anchorPattern,
38
- createAnchorFormatter,
39
- parseAnchorToken,
40
- type AnchorFormatter,
41
- } from "./anchor-format.ts";
36
+ import { anchorPattern, createAnchorFormatter, parseAnchorToken } from "./anchor-format.ts";
42
37
  import {
43
38
  formatDiffCounts,
44
39
  renderMutationCall,
45
40
  renderMutationResult,
46
41
  type DiffCounts,
47
42
  } from "./render.ts";
48
- import { formatFailure } from "./failure-context.ts";
49
- import { formatMutationAnchors } from "./mutation-result.ts";
43
+ import { describeEditFailure } from "./failure-context.ts";
44
+ import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
50
45
  import {
51
46
  executeMutation,
52
47
  runTextMutation,
@@ -54,13 +49,13 @@ import {
54
49
  type MutationTarget,
55
50
  type TextMutationDetails,
56
51
  } from "./mutation-runner.ts";
57
- import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
52
+ import type { MutationResultDetails } from "./mutation-result.ts";
58
53
  import {
59
54
  argumentItems,
60
55
  createArgumentPreparer,
61
56
  type ReportArgumentIssue,
62
57
  } from "./argument-validation.ts";
63
- type EditDetails = TextMutationDetails;
58
+ type EditDetails = MutationResultDetails<TextMutationDetails>;
64
59
  type EditRenderContext = Parameters<NonNullable<ToolDefinition<EditSchema>["renderCall"]>>[2];
65
60
 
66
61
  /** Split a validated anchor token; prepareArguments and the schema already checked it. */
@@ -87,6 +82,14 @@ function buildEditSchema(hashLen: number) {
87
82
  minItems: 1,
88
83
  description: 'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
89
84
  });
85
+ const transferFields = {
86
+ op: Type.Union([Type.Literal("copy"), Type.Literal("move")], {
87
+ description:
88
+ "Use copy or move to transfer whole lines whose text and indentation stay unchanged; move also removes the source. Use a body edit when text or indentation must change. Give exactly one destination: before or after.",
89
+ }),
90
+ anchor: requiredAnchor,
91
+ end: optionalEnd,
92
+ };
90
93
  const editOpSchema = Type.Union([
91
94
  Type.Object(
92
95
  {
@@ -116,6 +119,26 @@ function buildEditSchema(hashLen: number) {
116
119
  },
117
120
  { additionalProperties: false },
118
121
  ),
122
+ Type.Object(
123
+ {
124
+ ...transferFields,
125
+ before: Type.String({
126
+ pattern,
127
+ description: "Insert captured lines before this original line.",
128
+ }),
129
+ },
130
+ { additionalProperties: false },
131
+ ),
132
+ Type.Object(
133
+ {
134
+ ...transferFields,
135
+ after: Type.String({
136
+ pattern,
137
+ description: "Insert captured lines after this original line.",
138
+ }),
139
+ },
140
+ { additionalProperties: false },
141
+ ),
119
142
  Type.Object(
120
143
  {
121
144
  op: Type.Union([Type.Literal("append"), Type.Literal("prepend")], {
@@ -134,7 +157,7 @@ function buildEditSchema(hashLen: number) {
134
157
  }),
135
158
  edits: Type.Array(editOpSchema, {
136
159
  minItems: 1,
137
- description: `Operations on one snapshot. Anchors are LINE#HASH with exactly ${hashLen} hash characters, copied from the latest read, grep, edit, or replace result.`,
160
+ description: `Operations on one snapshot. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
138
161
  }),
139
162
  },
140
163
  { additionalProperties: false },
@@ -149,43 +172,52 @@ type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
149
172
 
150
173
  type EditOpInput = Static<EditSchema>["edits"][number];
151
174
 
175
+ /** How to correct edit argument issues; each reason states only what is wrong. */
176
+ const EDIT_ISSUE_FIX = {
177
+ emptyReplace: 'Use {"op":"delete"} to remove lines, or supply the replacement lines.',
178
+ emptyBody: 'Remove this edit or supply at least one line ([""] for a blank line).',
179
+ unsafeLine: 'Copy a complete "LINE#HASH" token from the latest tool result.',
180
+ hashLength: "Read or grep the file for current anchors.",
181
+ } as const;
182
+
152
183
  /** Report semantic argument issues; malformed shapes remain Pi's schema responsibility. */
153
184
  function checkEditArguments(args: unknown, hashLen: number, report: ReportArgumentIssue): void {
154
185
  const raw = (args as { edits?: unknown } | null)?.edits;
155
186
  const edits = argumentItems(raw);
156
- let hashLengthRecoveryHint = " Read or grep the file for current anchors.";
157
187
  edits.forEach((op, index) => {
158
188
  const body = (op as Record<string, unknown> | null)?.body;
159
189
  if (Array.isArray(body)) {
160
190
  if (body.length === 0) {
161
191
  report(
162
192
  `edits[${index}].body`,
193
+ "is empty",
163
194
  (op as Record<string, unknown>).op === "replace"
164
- ? 'is empty; use {"op":"delete"} to remove lines, or supply the replacement lines.'
165
- : 'is empty; remove this edit or supply at least one line ([""] for a blank line).',
195
+ ? EDIT_ISSUE_FIX.emptyReplace
196
+ : EDIT_ISSUE_FIX.emptyBody,
166
197
  );
167
198
  }
168
199
  body.forEach((line, lineIndex) => {
169
- const reason = typeof line === "string" ? unwritableTextReason(line) : undefined;
170
- if (reason) report(`edits[${index}].body[${lineIndex}]`, reason);
200
+ const unwritable = typeof line === "string" ? unwritableTextError(line) : undefined;
201
+ if (unwritable) report(`edits[${index}].body[${lineIndex}]`, unwritable.message);
171
202
  });
172
203
  }
173
- for (const field of ["anchor", "end"] as const) {
204
+ for (const field of EDIT_ANCHOR_FIELDS) {
174
205
  const value = (op as Record<string, unknown> | null)?.[field];
175
206
  if (typeof value !== "string") continue;
176
207
  const token = parseAnchorToken(value);
177
208
  if (token && !Number.isSafeInteger(token.line)) {
178
209
  report(
179
210
  `edits[${index}].${field}`,
180
- `line number in ${value} exceeds the safe integer range; copy a complete "LINE#HASH" token from the latest tool result.`,
211
+ "line number exceeds the safe integer range",
212
+ EDIT_ISSUE_FIX.unsafeLine,
181
213
  );
182
214
  }
183
215
  if (token && token.hash.length !== hashLen) {
184
216
  report(
185
217
  `edits[${index}].${field}`,
186
- `Anchor hash length mismatch: ${value} has ${token.hash.length} hash characters, but hashLen is ${hashLen}.${hashLengthRecoveryHint}`,
218
+ `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
219
+ EDIT_ISSUE_FIX.hashLength,
187
220
  );
188
- hashLengthRecoveryHint = "";
189
221
  }
190
222
  }
191
223
  });
@@ -204,6 +236,13 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
204
236
  };
205
237
  case "delete":
206
238
  return { op: "delete", start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
239
+ case "copy":
240
+ case "move": {
241
+ const source = { op: op.op, start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
242
+ return "before" in op
243
+ ? { ...source, before: parseAnchor(op.before) }
244
+ : { ...source, after: parseAnchor(op.after) };
245
+ }
207
246
  case "insert_after":
208
247
  case "insert_before":
209
248
  return { op: op.op, anchor: parseAnchor(op.anchor), body: op.body };
@@ -214,28 +253,6 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
214
253
  });
215
254
  }
216
255
 
217
- /**
218
- * Return compact tokens for changed caller-supplied rows, retaining content for deletion successors.
219
- * Uses the applicator's final indices so mixed batches do not need a second position calculation.
220
- */
221
- function formatUpdatedAnchors(
222
- before: string,
223
- newText: string,
224
- touched: readonly number[],
225
- contextLines: readonly number[],
226
- anchors: AnchorFormatter,
227
- ): string {
228
- const idxs = [...new Set(touched)].sort((a, b) => a - b);
229
- return formatMutationAnchors(
230
- splitLines(before),
231
- splitLines(newText),
232
- idxs,
233
- anchors,
234
- "Updated anchors:",
235
- new Set(contextLines),
236
- );
237
- }
238
-
239
256
  /** Call header with total/per-kind operation counts and the result's diff counts. */
240
257
  function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
241
258
  let t = theme.fg("toolTitle", theme.bold("edit "));
@@ -246,6 +263,8 @@ function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string
246
263
  const opCounts: Record<EditOpInput["op"] | "unknown", number> = {
247
264
  replace: 0,
248
265
  delete: 0,
266
+ copy: 0,
267
+ move: 0,
249
268
  insert_before: 0,
250
269
  insert_after: 0,
251
270
  append: 0,
@@ -272,27 +291,31 @@ export function makeEditOverride(
272
291
  cwd: string,
273
292
  config: HashlineEditConfig,
274
293
  fusion?: ActionFusionExecutor,
294
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
275
295
  ) {
276
- // Schema, verification, recovery, and returned anchors use the registered configuration.
296
+ // Schema, verification, and recovery use the registered configuration.
277
297
  const { hashLen, shiftRadius } = config;
278
298
  const parameters = createEditSchema(fusion !== undefined, hashLen);
279
299
 
280
300
  return {
281
301
  name: "edit" as const,
282
302
  label: "edit",
283
- description:
284
- "Edit file lines by LINE#HASH anchors checked against the current file. Returns fresh anchors for changed lines. On anchor failure, shows current context and recovery candidates; nothing is retried automatically.",
303
+ description: withThenRunDescription(
304
+ "Edit file lines by LINE#HASH anchors checked against the current file. Each operation replaces whole lines. Use replace instead when the same change repeats in several places, or when only a fragment of a long line changes. On anchor failure, shows current context and recovery candidates; nothing is retried automatically.",
305
+ fusion !== undefined,
306
+ ),
285
307
  promptSnippet: "Edit file lines using verified anchors",
286
308
  promptGuidelines: [
287
- MUTATION_TOOL_GUIDELINE,
288
- "Batch all edits to one file in a single edit call; all its anchors are checked against one snapshot.",
289
- "Reuse anchors while their line number and content are unchanged; inserts and deletes shift later lines, so use the edit's Updated anchors or re-read shifted lines.",
290
- "On edit anchor failure, inspect the recovery candidates before retrying or re-reading.",
309
+ "Batch all edits to one file into a single edit call.",
310
+ "Do not re-read a file just to refresh anchors: anchors stay valid while their line number and content are unchanged. Re-read or grep only the lines an edit changed or shifted.",
291
311
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
292
312
  ],
293
313
  parameters,
294
- prepareArguments: createArgumentPreparer("edit", parameters, (args, report) =>
295
- checkEditArguments(args, hashLen, report),
314
+ prepareArguments: createArgumentPreparer(
315
+ "edit",
316
+ parameters,
317
+ (args, report) => checkEditArguments(args, hashLen, report),
318
+ budgets,
296
319
  ),
297
320
  renderShell: "default" as const,
298
321
 
@@ -301,20 +324,12 @@ export function makeEditOverride(
301
324
  },
302
325
 
303
326
  renderResult(
304
- result: AgentToolResult<EditDetails>,
327
+ result: Parameters<typeof renderMutationResult>[0],
305
328
  options: ToolRenderResultOptions,
306
329
  theme: Theme,
307
330
  context: EditRenderContext,
308
331
  ) {
309
- return renderMutationResult(
310
- result,
311
- options,
312
- theme,
313
- context,
314
- "Editing…",
315
- "Edited",
316
- editHeader,
317
- );
332
+ return renderMutationResult(result, options, theme, context, "Editing…", editHeader);
318
333
  },
319
334
 
320
335
  async execute(
@@ -324,12 +339,14 @@ export function makeEditOverride(
324
339
  onUpdate: AgentToolUpdateCallback<EditDetails> | undefined,
325
340
  ctx: ExtensionToolContext,
326
341
  ) {
327
- return executeMutation<Omit<EditParams, "then_run">, EditDetails>(
342
+ return executeMutation<EditParams, TextMutationDetails, "edit">(
328
343
  {
344
+ tool: "edit",
329
345
  cwd,
330
346
  fusion,
347
+ budgets,
331
348
  run: (mutationParams, target) =>
332
- runHashline(target, mutationParams.edits, hashLen, shiftRadius),
349
+ runEdit(target, mutationParams.edits, hashLen, shiftRadius),
333
350
  },
334
351
  { toolCallId, params, signal, onUpdate, ctx },
335
352
  );
@@ -337,7 +354,7 @@ export function makeEditOverride(
337
354
  };
338
355
  }
339
356
 
340
- function runHashline(
357
+ function runEdit(
341
358
  target: MutationTarget,
342
359
  editOps: readonly EditOpInput[],
343
360
  hashLen: number,
@@ -345,7 +362,7 @@ function runHashline(
345
362
  ) {
346
363
  const anchorFormatter = createAnchorFormatter(hashLen);
347
364
 
348
- return runTextMutation("edit", target, (currentText) => {
365
+ return runTextMutation<"edit">(target, (currentText) => {
349
366
  const translated = toCoreEdits(editOps);
350
367
 
351
368
  // Recovery reports checksum candidates from nearby lines, then the whole file
@@ -353,27 +370,17 @@ function runHashline(
353
370
  // candidates and resubmit with fresh anchors.
354
371
  const result = applyEdits(currentText, translated, hashLen, shiftRadius);
355
372
  if (!result.ok) {
356
- throw new Error(
357
- formatFailure(
358
- result.failure,
359
- { currentText, anchors: anchorFormatter },
360
- translated.length > 1,
361
- ),
373
+ throw describeEditFailure(
374
+ result.failure,
375
+ { currentText, anchors: anchorFormatter },
376
+ translated.length > 1,
377
+ target.budget,
362
378
  );
363
379
  }
364
380
 
365
381
  return {
366
382
  text: result.text,
367
- anchors: () =>
368
- formatUpdatedAnchors(
369
- currentText,
370
- result.text,
371
- result.touchedLines,
372
- result.contextLines,
373
- anchorFormatter,
374
- ),
375
- summary: () =>
376
- `Edited ${target.displayPath} (${translated.length} op(s)${result.changed ? "" : ", no net change"}).`,
383
+ facts: {},
377
384
  };
378
385
  });
379
386
  }
@@ -1,26 +1,49 @@
1
- /** Every cancellation starts with this text, matching Pi's built-in tools. */
2
- export const OPERATION_ABORTED = "Operation aborted";
1
+ import { errnoCode, HashlineError } from "../core/errors.ts";
3
2
 
4
- /** Cancellation error; `detail` says where it stopped and what state remains. */
5
- export function cancellationError(detail?: string): Error {
6
- return new Error(detail ? `${OPERATION_ABORTED} ${detail}` : OPERATION_ABORTED);
3
+ /**
4
+ * Cancellation, worded like Pi's built-in tools. A mutation report's
5
+ * `publication` and `stage` say where it stopped, so the message does not.
6
+ * Whatever a cancelled operation threw is its effect, not a cause.
7
+ */
8
+ export function cancellationError(): HashlineError<"OPERATION_ABORTED"> {
9
+ return new HashlineError("OPERATION_ABORTED", "Operation aborted.");
10
+ }
11
+
12
+ export function throwIfCancelled(signal: AbortSignal | undefined): void {
13
+ if (signal?.aborted) throw cancellationError();
7
14
  }
8
15
 
9
- export function throwIfCancelled(signal: AbortSignal | undefined, detail?: string): void {
10
- if (signal?.aborted) throw cancellationError(detail);
16
+ /**
17
+ * A read observed a concurrent file change; partial bytes must not be classified as source text,
18
+ * so whatever the read raised meanwhile is not reported as a cause.
19
+ * Its retry advice holds only before publication; a published mutation's report replaces it.
20
+ */
21
+ export class FileChangedDuringReadError extends HashlineError<"FILE_CHANGED"> {
22
+ constructor() {
23
+ super("FILE_CHANGED", "File changed during read.");
24
+ }
11
25
  }
12
26
 
13
27
  /**
14
- * A searched file no longer matches what ripgrep reported. grep binds matches to
15
- * one snapshot per file: rg-line-ranges checks line counts, the CRLF text view
16
- * checks the snapshot copy, and grep-output checks matched text and the
17
- * revision recorded by grep-search. All of them report this one error.
28
+ * A searched file no longer matches what grep matched. grep binds matches to the
29
+ * revision grep-search hashed while matching, and grep-output re-reads the file
30
+ * against it.
18
31
  */
19
- export function searchChangedError(): Error {
20
- return new Error("File changed during search; rerun the query.");
32
+ export function searchChangedError(): HashlineError<"FILE_CHANGED"> {
33
+ return new HashlineError("FILE_CHANGED", "File changed during search.");
21
34
  }
22
35
 
23
- /** Rejection from a tool's prepareArguments for a check the schema cannot express. */
24
- export function invalidArgument(path: string, reason: string): Error {
25
- return new Error(`Invalid argument ${path}: ${reason}`);
36
+ /**
37
+ * A per-file failure that leaves the rest of the search valid: a filesystem error, or the
38
+ * file changing while it was searched or displayed. Undefined for any other failure.
39
+ */
40
+ export function fileReadWarning(
41
+ filePath: string,
42
+ error: unknown,
43
+ signal?: AbortSignal,
44
+ ): string | undefined {
45
+ if (signal?.aborted || !(error instanceof Error)) return undefined;
46
+ const changed = error instanceof HashlineError && error.errorCode === "FILE_CHANGED";
47
+ if (!changed && errnoCode(error) === undefined) return undefined;
48
+ return `Could not read ${filePath}: ${error.message}`;
26
49
  }