@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
@@ -1,10 +1,17 @@
1
1
  /**
2
- * Bounded diagnostic text shared by ripgrep stderr, batch aggregation, and
2
+ * Bounded diagnostic text shared by ripgrep stderr, report causes, and
3
3
  * model-facing search warnings. Retain the opening context and final cause;
4
4
  * mark omitted text instead of silently dropping diagnostics.
5
5
  */
6
- import { truncateHead, truncateTail } from "@earendil-works/pi-coding-agent";
7
- import { formatKiB } from "./budgets.ts";
6
+ import { formatByteSize } from "./budgets.ts";
7
+
8
+ /** Cut only at UTF-8 boundaries; diagnostics may contain a single oversized line. */
9
+ function byteSlice(text: string, maxBytes: number, tail: boolean): string {
10
+ const bytes = Buffer.from(text);
11
+ let boundary = tail ? Math.max(0, bytes.length - maxBytes) : Math.min(bytes.length, maxBytes);
12
+ while (boundary < bytes.length && (bytes[boundary] & 0xc0) === 0x80) boundary += tail ? 1 : -1;
13
+ return (tail ? bytes.subarray(boundary) : bytes.subarray(0, boundary)).toString("utf8");
14
+ }
8
15
 
9
16
  export class DiagnosticBuffer {
10
17
  private head = "";
@@ -18,7 +25,7 @@ export class DiagnosticBuffer {
18
25
 
19
26
  constructor(maxBytes: number) {
20
27
  this.maxBytes = maxBytes;
21
- this.notice = `\n[Diagnostics truncated (${formatKiB(maxBytes)} limit); middle omitted.]\n`;
28
+ this.notice = `\n[Diagnostics truncated (${formatByteSize(maxBytes)} limit); middle omitted.]\n`;
22
29
  const contentBytes = maxBytes - Buffer.byteLength(this.notice);
23
30
  this.headBytes = Math.floor(contentBytes / 2);
24
31
  this.tailBytes = contentBytes - this.headBytes;
@@ -31,10 +38,7 @@ export class DiagnosticBuffer {
31
38
  this.head = combined;
32
39
  return;
33
40
  }
34
- this.head = truncateHead(combined, {
35
- maxBytes: this.headBytes,
36
- maxLines: Number.MAX_SAFE_INTEGER,
37
- }).content;
41
+ this.head = byteSlice(combined, this.headBytes, false);
38
42
  this.tail = this.truncateTail(combined);
39
43
  this.truncated = true;
40
44
  return;
@@ -47,13 +51,6 @@ export class DiagnosticBuffer {
47
51
  }
48
52
 
49
53
  private truncateTail(text: string): string {
50
- // Pi's truncated previews omit the final newline; streaming must retain it
51
- // so the next chunk cannot merge two diagnostic lines.
52
- const newline = text.endsWith("\n") ? "\n" : "";
53
- const preview = truncateTail(text, {
54
- maxBytes: this.tailBytes - newline.length,
55
- maxLines: Number.MAX_SAFE_INTEGER,
56
- });
57
- return preview.content + (preview.truncated ? newline : "");
54
+ return byteSlice(text, this.tailBytes, true);
58
55
  }
59
56
  }
@@ -37,7 +37,10 @@ test("macOS attempts directory sync, tolerates unsupported operations, and prese
37
37
  (error: unknown) =>
38
38
  error instanceof FileMutationError &&
39
39
  error.publication === "PUBLISHED" &&
40
- /EIO/.test(error.message),
40
+ error.stage === "post_process" &&
41
+ error.cause instanceof Error &&
42
+ "code" in error.cause &&
43
+ error.cause.code === "EIO",
41
44
  );
42
45
  } else {
43
46
  assert.equal((await commit).publication, "PUBLISHED");
@@ -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
+ "Copy, or move (also removes the source), whole lines whose text and indentation stay unchanged; use a body edit when either changes.",
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; ranges must not overlap. Insertions at one position, or at the start of a replaced or deleted range, apply in array order before it. 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 },
@@ -142,50 +165,56 @@ function buildEditSchema(hashLen: number) {
142
165
  }
143
166
  type EditSchema = ReturnType<typeof buildEditSchema>;
144
167
 
145
- function createEditSchema(actionFusion: boolean, hashLen: number) {
146
- return withThenRunSchema(buildEditSchema(hashLen), "edit", actionFusion);
147
- }
148
168
  type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
149
169
 
150
170
  type EditOpInput = Static<EditSchema>["edits"][number];
151
171
 
172
+ /** How to correct edit argument issues; each reason states only what is wrong. */
173
+ const EDIT_ISSUE_FIX = {
174
+ emptyReplace: 'Use {"op":"delete"} to remove lines, or supply the replacement lines.',
175
+ emptyBody: 'Remove this edit or supply at least one line ([""] for a blank line).',
176
+ unsafeLine: 'Copy a complete "LINE#HASH" token from the latest tool result.',
177
+ hashLength: "Read or grep the file for current anchors.",
178
+ } as const;
179
+
152
180
  /** Report semantic argument issues; malformed shapes remain Pi's schema responsibility. */
153
181
  function checkEditArguments(args: unknown, hashLen: number, report: ReportArgumentIssue): void {
154
182
  const raw = (args as { edits?: unknown } | null)?.edits;
155
183
  const edits = argumentItems(raw);
156
- let hashLengthRecoveryHint = " Read or grep the file for current anchors.";
157
184
  edits.forEach((op, index) => {
158
185
  const body = (op as Record<string, unknown> | null)?.body;
159
186
  if (Array.isArray(body)) {
160
187
  if (body.length === 0) {
161
188
  report(
162
189
  `edits[${index}].body`,
190
+ "is empty",
163
191
  (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).',
192
+ ? EDIT_ISSUE_FIX.emptyReplace
193
+ : EDIT_ISSUE_FIX.emptyBody,
166
194
  );
167
195
  }
168
196
  body.forEach((line, lineIndex) => {
169
- const reason = typeof line === "string" ? unwritableTextReason(line) : undefined;
170
- if (reason) report(`edits[${index}].body[${lineIndex}]`, reason);
197
+ const unwritable = typeof line === "string" ? unwritableTextError(line) : undefined;
198
+ if (unwritable) report(`edits[${index}].body[${lineIndex}]`, unwritable.message);
171
199
  });
172
200
  }
173
- for (const field of ["anchor", "end"] as const) {
201
+ for (const field of EDIT_ANCHOR_FIELDS) {
174
202
  const value = (op as Record<string, unknown> | null)?.[field];
175
203
  if (typeof value !== "string") continue;
176
204
  const token = parseAnchorToken(value);
177
205
  if (token && !Number.isSafeInteger(token.line)) {
178
206
  report(
179
207
  `edits[${index}].${field}`,
180
- `line number in ${value} exceeds the safe integer range; copy a complete "LINE#HASH" token from the latest tool result.`,
208
+ "line number exceeds the safe integer range",
209
+ EDIT_ISSUE_FIX.unsafeLine,
181
210
  );
182
211
  }
183
212
  if (token && token.hash.length !== hashLen) {
184
213
  report(
185
214
  `edits[${index}].${field}`,
186
- `Anchor hash length mismatch: ${value} has ${token.hash.length} hash characters, but hashLen is ${hashLen}.${hashLengthRecoveryHint}`,
215
+ `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
216
+ EDIT_ISSUE_FIX.hashLength,
187
217
  );
188
- hashLengthRecoveryHint = "";
189
218
  }
190
219
  }
191
220
  });
@@ -198,12 +227,19 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
198
227
  case "replace":
199
228
  return {
200
229
  op: "replace",
201
- start: parseAnchor(op.anchor),
230
+ anchor: parseAnchor(op.anchor),
202
231
  end: parseAnchor(op.end),
203
232
  body: op.body,
204
233
  };
205
234
  case "delete":
206
- return { op: "delete", start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
235
+ return { op: "delete", anchor: parseAnchor(op.anchor), end: parseAnchor(op.end) };
236
+ case "copy":
237
+ case "move": {
238
+ const source = { op: op.op, anchor: parseAnchor(op.anchor), end: parseAnchor(op.end) };
239
+ return "before" in op
240
+ ? { ...source, before: parseAnchor(op.before) }
241
+ : { ...source, after: parseAnchor(op.after) };
242
+ }
207
243
  case "insert_after":
208
244
  case "insert_before":
209
245
  return { op: op.op, anchor: parseAnchor(op.anchor), body: op.body };
@@ -214,28 +250,6 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
214
250
  });
215
251
  }
216
252
 
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
253
  /** Call header with total/per-kind operation counts and the result's diff counts. */
240
254
  function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
241
255
  let t = theme.fg("toolTitle", theme.bold("edit "));
@@ -246,6 +260,8 @@ function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string
246
260
  const opCounts: Record<EditOpInput["op"] | "unknown", number> = {
247
261
  replace: 0,
248
262
  delete: 0,
263
+ copy: 0,
264
+ move: 0,
249
265
  insert_before: 0,
250
266
  insert_after: 0,
251
267
  append: 0,
@@ -272,27 +288,31 @@ export function makeEditOverride(
272
288
  cwd: string,
273
289
  config: HashlineEditConfig,
274
290
  fusion?: ActionFusionExecutor,
291
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
275
292
  ) {
276
- // Schema, verification, recovery, and returned anchors use the registered configuration.
293
+ // Schema, verification, and recovery use the registered configuration.
277
294
  const { hashLen, shiftRadius } = config;
278
- const parameters = createEditSchema(fusion !== undefined, hashLen);
295
+ const parameters = withThenRunSchema(buildEditSchema(hashLen), "edit", fusion !== undefined);
279
296
 
280
297
  return {
281
298
  name: "edit" as const,
282
299
  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.",
300
+ description: withThenRunDescription(
301
+ "Edit whole lines using LINE#HASH anchors checked against the current file. Use replace instead when the same change repeats in several places, or when only a fragment of a long line changes.",
302
+ fusion !== undefined,
303
+ ),
285
304
  promptSnippet: "Edit file lines using verified anchors",
286
305
  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.",
306
+ "Batch all edits to one file into a single edit call.",
307
+ "After edit or replace, get fresh anchors with read or grep before citing any line it changed. If it added or removed lines, also refresh anchors below the earliest affected line; anchors above it remain valid. If the affected positions are unknown, read or grep the lines you intend to cite.",
291
308
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
292
309
  ],
293
310
  parameters,
294
- prepareArguments: createArgumentPreparer("edit", parameters, (args, report) =>
295
- checkEditArguments(args, hashLen, report),
311
+ prepareArguments: createArgumentPreparer(
312
+ "edit",
313
+ parameters,
314
+ (args, report) => checkEditArguments(args, hashLen, report),
315
+ budgets,
296
316
  ),
297
317
  renderShell: "default" as const,
298
318
 
@@ -301,20 +321,12 @@ export function makeEditOverride(
301
321
  },
302
322
 
303
323
  renderResult(
304
- result: AgentToolResult<EditDetails>,
324
+ result: Parameters<typeof renderMutationResult>[0],
305
325
  options: ToolRenderResultOptions,
306
326
  theme: Theme,
307
327
  context: EditRenderContext,
308
328
  ) {
309
- return renderMutationResult(
310
- result,
311
- options,
312
- theme,
313
- context,
314
- "Editing…",
315
- "Edited",
316
- editHeader,
317
- );
329
+ return renderMutationResult(result, options, theme, context, "Editing…", editHeader, "edit");
318
330
  },
319
331
 
320
332
  async execute(
@@ -324,12 +336,14 @@ export function makeEditOverride(
324
336
  onUpdate: AgentToolUpdateCallback<EditDetails> | undefined,
325
337
  ctx: ExtensionToolContext,
326
338
  ) {
327
- return executeMutation<Omit<EditParams, "then_run">, EditDetails>(
339
+ return executeMutation<EditParams, TextMutationDetails, "edit">(
328
340
  {
341
+ tool: "edit",
329
342
  cwd,
330
343
  fusion,
344
+ budgets,
331
345
  run: (mutationParams, target) =>
332
- runHashline(target, mutationParams.edits, hashLen, shiftRadius),
346
+ runEdit(target, mutationParams.edits, hashLen, shiftRadius),
333
347
  },
334
348
  { toolCallId, params, signal, onUpdate, ctx },
335
349
  );
@@ -337,7 +351,7 @@ export function makeEditOverride(
337
351
  };
338
352
  }
339
353
 
340
- function runHashline(
354
+ function runEdit(
341
355
  target: MutationTarget,
342
356
  editOps: readonly EditOpInput[],
343
357
  hashLen: number,
@@ -345,7 +359,7 @@ function runHashline(
345
359
  ) {
346
360
  const anchorFormatter = createAnchorFormatter(hashLen);
347
361
 
348
- return runTextMutation("edit", target, (currentText) => {
362
+ return runTextMutation<"edit">(target, (currentText) => {
349
363
  const translated = toCoreEdits(editOps);
350
364
 
351
365
  // Recovery reports checksum candidates from nearby lines, then the whole file
@@ -353,27 +367,17 @@ function runHashline(
353
367
  // candidates and resubmit with fresh anchors.
354
368
  const result = applyEdits(currentText, translated, hashLen, shiftRadius);
355
369
  if (!result.ok) {
356
- throw new Error(
357
- formatFailure(
358
- result.failure,
359
- { currentText, anchors: anchorFormatter },
360
- translated.length > 1,
361
- ),
370
+ throw describeEditFailure(
371
+ result.failure,
372
+ { currentText, anchors: anchorFormatter },
373
+ translated.length > 1,
374
+ target.budget,
362
375
  );
363
376
  }
364
377
 
365
378
  return {
366
379
  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"}).`,
380
+ facts: {},
377
381
  };
378
382
  });
379
383
  }
@@ -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
  }