@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,13 +1,11 @@
1
1
  /**
2
- * Override edit: hashline ops via structured `edits` (LINE#HASH anchors).
2
+ * Override edit: hashline ops via structured `steps` (LINE#HASH anchors).
3
3
  *
4
- * Each op in `edits` references line anchors from read, grep, or edit failure diagnostics.
4
+ * Each op in `steps` references line anchors from read, grep, or edit failure diagnostics.
5
5
  * The core verifies each anchor live against
6
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
- * elsewhere never block the edit. The extension requires structured `edits` arrays
9
- * at execution; Pi may coerce a single object before validation. Legacy
10
- * oldText/newText inputs fail schema validation before mutation.
8
+ * elsewhere never block the edit.
11
9
  *
12
10
  * Concurrency safety: read-modify-write is wrapped in withFileMutationQueue.
13
11
  * AbortSignal is honored — checked after read / before write.
@@ -15,49 +13,27 @@
15
13
  * @module pi-hashline-edit/pi
16
14
  */
17
15
 
18
- import {
19
- type ExtensionToolContext,
20
- type Theme,
21
- type ToolDefinition,
22
- type ToolRenderResultOptions,
23
- } from "@earendil-works/pi-coding-agent";
24
- import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
25
- import { Type, type Static, type TLiteral } from "typebox";
26
- import {
27
- ACTION_FUSION_GUIDELINES,
28
- withThenRunDescription,
29
- withThenRunSchema,
30
- type ThenRunInput,
31
- } from "./action-fusion.ts";
16
+ import type { Theme } from "@earendil-works/pi-coding-agent";
17
+ import { Type, type Static } from "typebox";
32
18
  import { applyEdits } from "../core/apply.ts";
33
19
  import { unwritableTextError } from "../core/text.ts";
34
20
  import { EDIT_ANCHOR_FIELDS, type Anchor, type Edit } from "../core/types.ts";
35
- import type { HashlineEditConfig } from "./config.ts";
36
21
  import { anchorPattern, createAnchorFormatter, parseAnchorToken } from "./anchor-format.ts";
37
22
  import {
23
+ diffCardRenderers,
38
24
  formatDiffCounts,
39
25
  formatHeaderPath,
40
- renderMutationCall,
41
- renderMutationResult,
42
26
  type DiffCounts,
43
27
  } from "./render.ts";
44
28
  import { describeEditFailure } from "./failure-context.ts";
45
- import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
46
29
  import {
47
- executeMutation,
30
+ mutationToolBase,
48
31
  runTextMutation,
49
- type ActionFusionExecutor,
50
32
  type MutationTarget,
51
- type TextMutationDetails,
33
+ type MutationToolEnvironment,
52
34
  } from "./mutation-runner.ts";
53
- import type { MutationResultDetails } from "./mutation-result.ts";
54
- import {
55
- argumentItems,
56
- createArgumentPreparer,
57
- type ReportArgumentIssue,
58
- } from "./argument-validation.ts";
59
- type EditDetails = MutationResultDetails<TextMutationDetails>;
60
- type EditRenderContext = Parameters<NonNullable<ToolDefinition<EditSchema>["renderCall"]>>[2];
35
+ import { argumentItems, type ReportArgumentIssue } from "./argument-validation.ts";
36
+ import { filePathField, literalUnion } from "./schema.ts";
61
37
 
62
38
  /** Split a validated anchor token; prepareArguments and the schema already checked it. */
63
39
  function parseAnchor(value: string): Anchor;
@@ -67,51 +43,33 @@ function parseAnchor(value: string | undefined) {
67
43
  }
68
44
 
69
45
  /** Operation item fields besides `action`. */
70
- type EditItemField = (typeof EDIT_ANCHOR_FIELDS)[number] | "body";
46
+ type EditItemField = (typeof EDIT_ANCHOR_FIELDS)[number] | "lines";
71
47
 
72
48
  /** What one op does and which item fields it takes; it takes no others. */
73
49
  interface EditOpSpec {
74
50
  readonly meaning: string;
75
51
  readonly required: readonly EditItemField[];
76
52
  readonly optional?: readonly EditItemField[];
77
- /** Destinations, of which exactly one is required. */
78
- readonly destination?: readonly EditItemField[];
79
53
  }
80
54
 
81
- const TRANSFER_DESTINATION = ["before", "after"] as const;
82
-
83
55
  /** Every op and its fields; the schema states them, and argument checks enforce them. */
84
56
  const EDIT_OPS = {
85
57
  replace: {
86
- meaning: "Replace the cited line(s) with body.",
87
- required: ["anchor", "body"],
58
+ meaning: "Replace the cited line(s) with lines.",
59
+ required: ["anchor", "lines"],
88
60
  optional: ["end"],
89
61
  },
90
62
  delete: { meaning: "Delete the cited line(s).", required: ["anchor"], optional: ["end"] },
91
63
  insert_after: {
92
- meaning: "Insert body after the anchor line, which is kept; do not repeat it in body.",
93
- required: ["anchor", "body"],
64
+ meaning: "Insert lines after the anchor line, which is kept; do not repeat it in lines.",
65
+ required: ["anchor", "lines"],
94
66
  },
95
67
  insert_before: {
96
- meaning: "Insert body before the anchor line, which is kept; do not repeat it in body.",
97
- required: ["anchor", "body"],
98
- },
99
- copy: {
100
- meaning:
101
- "Copy the cited line(s), text and indentation unchanged, before or after another original line; use a body edit when either changes.",
102
- required: ["anchor"],
103
- optional: ["end"],
104
- destination: TRANSFER_DESTINATION,
68
+ meaning: "Insert lines before the anchor line, which is kept; do not repeat it in lines.",
69
+ required: ["anchor", "lines"],
105
70
  },
106
- move: {
107
- meaning:
108
- "Move the cited line(s), text and indentation unchanged, before or after another original line, removing the source; use a body edit when either changes.",
109
- required: ["anchor"],
110
- optional: ["end"],
111
- destination: TRANSFER_DESTINATION,
112
- },
113
- append: { meaning: "Add body at the end of the file.", required: ["body"] },
114
- prepend: { meaning: "Add body at the start of the file.", required: ["body"] },
71
+ append: { meaning: "Add lines at the end of the file.", required: ["lines"] },
72
+ prepend: { meaning: "Add lines at the start of the file.", required: ["lines"] },
115
73
  } as const satisfies Record<string, EditOpSpec>;
116
74
  type EditOpName = keyof typeof EDIT_OPS;
117
75
  const EDIT_OP_NAMES = Object.keys(EDIT_OPS) as EditOpName[];
@@ -120,12 +78,8 @@ const EDIT_OP_NAMES = Object.keys(EDIT_OPS) as EditOpName[];
120
78
  const MAX_EDIT_OPS = 64;
121
79
 
122
80
  /** An op's meaning followed by the fields it takes. */
123
- function describeEditOp({ meaning, required, optional = [], destination }: EditOpSpec): string {
124
- const takes = [
125
- ...required,
126
- ...(destination ? [`exactly one of ${destination.join(" or ")}`] : []),
127
- ].join(" and ");
128
- return `${meaning} Takes ${takes}${optional.length ? `; ${optional.join(", ")} is optional` : ""}.`;
81
+ function describeEditOp({ meaning, required, optional = [] }: EditOpSpec): string {
82
+ return `${meaning} Takes ${required.join(" and ")}${optional.length ? `; ${optional.join(", ")} is optional` : ""}.`;
129
83
  }
130
84
 
131
85
  /**
@@ -138,25 +92,19 @@ function buildEditSchema(hashLen: number) {
138
92
  const anchorField = (description: string) => Type.Optional(Type.String({ pattern, description }));
139
93
  const editOpSchema = Type.Object(
140
94
  {
141
- // Constrained sampling and some gateways emit keys alphabetically; `action`
142
- // sorts first, so the operation is chosen before the fields it governs.
143
- // TypeBox infers a union's static type only from a tuple.
144
- action: Type.Union(
145
- EDIT_OP_NAMES.map((op) =>
146
- Type.Literal(op, { description: describeEditOp(EDIT_OPS[op]) }),
147
- ) as [TLiteral<EditOpName>, ...TLiteral<EditOpName>[]],
148
- ),
95
+ // Session evidence is mixed: OpenAI calls usually follow declaration order, while
96
+ // GLM and local calls often use lexical key order. Keep `action`, `anchor`,
97
+ // `end`, `lines` so both orders choose the operation and range before its payload.
98
+ action: literalUnion(EDIT_OP_NAMES, (op) => describeEditOp(EDIT_OPS[op])),
149
99
  anchor: anchorField("LINE#HASH of the target line."),
150
100
  end: anchorField("Inclusive last LINE#HASH of the range; omit for one line."),
151
- body: Type.Optional(
101
+ lines: Type.Optional(
152
102
  Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
153
103
  minItems: 1,
154
104
  description:
155
105
  'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
156
106
  }),
157
107
  ),
158
- before: anchorField("Insert captured lines before this original line."),
159
- after: anchorField("Insert captured lines after this original line."),
160
108
  },
161
109
  {
162
110
  additionalProperties: false,
@@ -165,14 +113,11 @@ function buildEditSchema(hashLen: number) {
165
113
  );
166
114
  return Type.Object(
167
115
  {
168
- path: Type.String({
169
- minLength: 1,
170
- description: "Path to the file (relative or absolute)",
171
- }),
172
- edits: Type.Array(editOpSchema, {
116
+ path: filePathField(),
117
+ steps: Type.Array(editOpSchema, {
173
118
  minItems: 1,
174
119
  maxItems: MAX_EDIT_OPS,
175
- description: `Operations on one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion, copy/move destinations included; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one body. An insertion at the start of a replaced or deleted range goes 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.`,
120
+ description: `Operations on one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one operation. An insertion at the start of a replaced or deleted range goes 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.`,
176
121
  }),
177
122
  },
178
123
  { additionalProperties: false },
@@ -180,15 +125,15 @@ function buildEditSchema(hashLen: number) {
180
125
  }
181
126
  type EditSchema = ReturnType<typeof buildEditSchema>;
182
127
 
183
- type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
128
+ type EditParams = Static<EditSchema>;
184
129
 
185
- type EditOpInput = Static<EditSchema>["edits"][number];
186
- type EditOpSchema = EditSchema["properties"]["edits"]["items"];
130
+ type EditOpInput = EditParams["steps"][number];
131
+ type EditOpSchema = EditSchema["properties"]["steps"]["items"];
187
132
 
188
133
  /** How to correct edit argument issues; each reason states only what is wrong. */
189
134
  const EDIT_ISSUE_FIX = {
190
135
  emptyReplace: 'Use {"action":"delete"} to remove lines, or supply the replacement lines.',
191
- emptyBody: 'Remove this edit or supply at least one line ([""] for a blank line).',
136
+ emptyLines: 'Remove this step or supply at least one line ([""] for a blank line).',
192
137
  unsafeLine: 'Copy a complete "LINE#HASH" token from the latest tool result.',
193
138
  hashLength: "Read or grep the file for current anchors.",
194
139
  } as const;
@@ -204,19 +149,15 @@ function checkEditArguments(
204
149
  item: EditOpSchema,
205
150
  report: ReportArgumentIssue,
206
151
  ): void {
207
- argumentItems((args as { edits?: unknown } | null)?.edits).forEach((value, index) => {
152
+ argumentItems((args as { steps?: unknown } | null)?.steps).forEach((value, index) => {
208
153
  if (value === null || typeof value !== "object") return;
209
154
  const edit = value as Record<string, unknown>;
210
155
  // The schema reports an unknown action; which fields it takes is then unknown.
211
156
  if (typeof edit.action !== "string" || !Object.hasOwn(EDIT_OPS, edit.action)) return;
212
157
  const name = edit.action as EditOpName;
213
158
  const spec: EditOpSpec = EDIT_OPS[name];
214
- const path = `edits[${index}]`;
215
- const accepted = new Set([
216
- ...spec.required,
217
- ...(spec.optional ?? []),
218
- ...(spec.destination ?? []),
219
- ]);
159
+ const path = `steps[${index}]`;
160
+ const accepted = new Set([...spec.required, ...(spec.optional ?? [])]);
220
161
  for (const [field, declaration] of Object.entries(item.properties)) {
221
162
  if (field === "action") continue;
222
163
  const given = edit[field] !== undefined;
@@ -229,38 +170,37 @@ function checkEditArguments(
229
170
  Reflect.get(declaration, "description"),
230
171
  );
231
172
  }
232
- if (
233
- spec.destination &&
234
- spec.destination.filter((field) => edit[field] !== undefined).length !== 1
235
- )
236
- report(path, `expected exactly one of: ${spec.destination.join(", ")}`);
237
173
 
238
- const body = edit.body;
239
- if (accepted.has("body") && Array.isArray(body)) {
240
- if (body.length === 0) {
174
+ const lines = edit.lines;
175
+ if (accepted.has("lines") && Array.isArray(lines)) {
176
+ if (lines.length === 0) {
241
177
  report(
242
- `${path}.body`,
178
+ `${path}.lines`,
243
179
  "is empty",
244
- name === "replace" ? EDIT_ISSUE_FIX.emptyReplace : EDIT_ISSUE_FIX.emptyBody,
180
+ name === "replace" ? EDIT_ISSUE_FIX.emptyReplace : EDIT_ISSUE_FIX.emptyLines,
245
181
  );
246
182
  }
247
- body.forEach((line, lineIndex) => {
183
+ lines.forEach((line, lineIndex) => {
248
184
  const unwritable = typeof line === "string" ? unwritableTextError(line) : undefined;
249
- if (unwritable) report(`${path}.body[${lineIndex}]`, unwritable.message);
185
+ if (unwritable) report(`${path}.lines[${lineIndex}]`, unwritable.message);
250
186
  });
251
187
  }
188
+ const cited: { anchor?: number; end?: number } = {};
252
189
  for (const field of EDIT_ANCHOR_FIELDS) {
253
190
  const anchor = edit[field];
254
191
  if (!accepted.has(field) || typeof anchor !== "string") continue;
255
192
  const token = parseAnchorToken(anchor);
256
- if (token && !Number.isSafeInteger(token.line)) {
193
+ if (!token) continue;
194
+ if (Number.isSafeInteger(token.line)) {
195
+ cited[field] = token.line;
196
+ } else {
257
197
  report(
258
198
  `${path}.${field}`,
259
199
  "line number exceeds the safe integer range",
260
200
  EDIT_ISSUE_FIX.unsafeLine,
261
201
  );
262
202
  }
263
- if (token && token.hash.length !== hashLen) {
203
+ if (token.hash.length !== hashLen) {
264
204
  report(
265
205
  `${path}.${field}`,
266
206
  `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
@@ -268,11 +208,17 @@ function checkEditArguments(
268
208
  );
269
209
  }
270
210
  }
211
+
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
+ }
271
217
  });
272
218
  }
273
219
 
274
220
  /**
275
- * Translate validated public operations into core edits, parsing numeric anchor
221
+ * Translate validated public operations into core steps, parsing numeric anchor
276
222
  * positions. Argument checks guarantee each op carries exactly the fields it takes.
277
223
  */
278
224
  function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
@@ -283,23 +229,16 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
283
229
  op: "replace",
284
230
  anchor: parseAnchor(op.anchor!),
285
231
  end: parseAnchor(op.end),
286
- body: op.body!,
232
+ body: op.lines!,
287
233
  };
288
234
  case "delete":
289
235
  return { op: "delete", anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
290
- case "copy":
291
- case "move": {
292
- const source = { op: op.action, anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
293
- return op.before !== undefined
294
- ? { ...source, before: parseAnchor(op.before) }
295
- : { ...source, after: parseAnchor(op.after!) };
296
- }
297
236
  case "insert_after":
298
237
  case "insert_before":
299
- return { op: op.action, anchor: parseAnchor(op.anchor!), body: op.body! };
238
+ return { op: op.action, anchor: parseAnchor(op.anchor!), body: op.lines! };
300
239
  case "append":
301
240
  case "prepend":
302
- return { op: op.action, body: op.body! };
241
+ return { op: op.action, body: op.lines! };
303
242
  }
304
243
  });
305
244
  }
@@ -308,22 +247,14 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
308
247
  function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
309
248
  let t = theme.fg("toolTitle", theme.bold("edit "));
310
249
  t += formatHeaderPath(args.path, theme);
311
- const edits = Array.isArray(args.edits) ? args.edits : [];
312
- const n = edits.length;
250
+ const steps = Array.isArray(args.steps) ? args.steps : [];
251
+ const n = steps.length;
313
252
  if (n) {
314
- const opCounts: Record<EditOpName | "unknown", number> = {
315
- replace: 0,
316
- delete: 0,
317
- copy: 0,
318
- move: 0,
319
- insert_before: 0,
320
- insert_after: 0,
321
- append: 0,
322
- prepend: 0,
323
- unknown: 0,
324
- };
253
+ const opCounts: Record<string, number> = Object.fromEntries(
254
+ [...EDIT_OP_NAMES, "unknown"].map((kind) => [kind, 0]),
255
+ );
325
256
  // Renderers receive partial arguments; fixed buckets keep one-pass counting O(1) in space.
326
- for (const edit of edits) {
257
+ for (const edit of steps) {
327
258
  const kind = edit?.action;
328
259
  if (typeof kind === "string" && Object.hasOwn(opCounts, kind)) opCounts[kind]++;
329
260
  else opCounts.unknown++;
@@ -338,73 +269,28 @@ function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string
338
269
  return t;
339
270
  }
340
271
 
341
- export function makeEditOverride(
342
- cwd: string,
343
- config: HashlineEditConfig,
344
- fusion?: ActionFusionExecutor,
345
- budgets: OutputBudgetProvider = defaultOutputBudgets,
346
- ) {
272
+ export function makeEditOverride(env: MutationToolEnvironment) {
347
273
  // Schema, verification, and recovery use the registered configuration.
348
- const { hashLen, shiftRadius } = config;
274
+ const { hashLen, shiftRadius } = env.config;
349
275
  const schema = buildEditSchema(hashLen);
350
- const parameters = withThenRunSchema(schema, "edit", fusion !== undefined);
351
276
 
352
277
  return {
353
- name: "edit" as const,
354
- label: "edit",
355
- description: withThenRunDescription(
356
- "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.",
357
- fusion !== undefined,
358
- ),
359
- promptSnippet: "Edit file lines using verified anchors",
360
- promptGuidelines: [
361
- "Batch all edits to one file into a single edit call.",
362
- "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.",
363
- ...(fusion ? ACTION_FUSION_GUIDELINES : []),
364
- ],
365
- parameters,
366
- // Providers that support it bound the batch by the schema while sampling.
367
- constrainedSampling: { type: "json_schema", strict: "prefer" } as const,
368
- prepareArguments: createArgumentPreparer(
369
- "edit",
370
- parameters,
371
- (args, report) => checkEditArguments(args, hashLen, schema.properties.edits.items, report),
372
- budgets,
373
- ),
374
- renderShell: "default" as const,
375
-
376
- renderCall(args: EditParams, theme: Theme, context: EditRenderContext) {
377
- return renderMutationCall(args, theme, context, editHeader);
378
- },
379
-
380
- renderResult(
381
- result: Parameters<typeof renderMutationResult>[0],
382
- options: ToolRenderResultOptions,
383
- theme: Theme,
384
- context: EditRenderContext,
385
- ) {
386
- return renderMutationResult(result, options, theme, context, "Editing…", editHeader, "edit");
387
- },
388
-
389
- async execute(
390
- toolCallId: string,
391
- params: EditParams,
392
- signal: AbortSignal | undefined,
393
- onUpdate: AgentToolUpdateCallback<EditDetails> | undefined,
394
- ctx: ExtensionToolContext,
395
- ) {
396
- return executeMutation<EditParams, TextMutationDetails, "edit">(
397
- {
398
- tool: "edit",
399
- cwd,
400
- fusion,
401
- budgets,
402
- run: (mutationParams, target) =>
403
- runEdit(target, mutationParams.edits, hashLen, shiftRadius),
404
- },
405
- { toolCallId, params, signal, onUpdate, ctx },
406
- );
407
- },
278
+ ...mutationToolBase({
279
+ ...env,
280
+ tool: "edit",
281
+ schema,
282
+ description:
283
+ "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.",
284
+ promptSnippet: "Edit file lines using verified anchors",
285
+ promptGuidelines: [
286
+ "Batch all steps for one file into a single edit call.",
287
+ "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
+ ],
289
+ check: (args, report) =>
290
+ checkEditArguments(args, hashLen, schema.properties.steps.items, report),
291
+ run: (params, target) => runEdit(target, params.steps, hashLen, shiftRadius),
292
+ }),
293
+ ...diffCardRenderers("edit", "Editing…", editHeader),
408
294
  };
409
295
  }
410
296
 
@@ -417,24 +303,13 @@ function runEdit(
417
303
  const anchorFormatter = createAnchorFormatter(hashLen);
418
304
 
419
305
  return runTextMutation<"edit">(target, (currentText) => {
420
- const translated = toCoreEdits(editOps);
421
-
422
306
  // Recovery reports checksum candidates from nearby lines, then the whole file
423
307
  // if needed. Every failed anchor still rejects the batch; callers inspect
424
308
  // candidates and resubmit with fresh anchors.
425
- const result = applyEdits(currentText, translated, hashLen, shiftRadius);
309
+ const result = applyEdits(currentText, toCoreEdits(editOps), hashLen, shiftRadius);
426
310
  if (!result.ok) {
427
- throw describeEditFailure(
428
- result.failure,
429
- { currentText, anchors: anchorFormatter },
430
- translated.length > 1,
431
- target.budget,
432
- );
311
+ throw describeEditFailure(currentText, result.failures, anchorFormatter, target.budget);
433
312
  }
434
-
435
- return {
436
- text: result.text,
437
- facts: {},
438
- };
313
+ return { text: result.text, facts: {} };
439
314
  });
440
315
  }
@@ -1,8 +1,13 @@
1
1
  import { errnoCode, HashlineError } from "../core/errors.ts";
2
2
 
3
+ export interface SearchWarning {
4
+ readonly path?: string;
5
+ readonly reason: string;
6
+ }
7
+
3
8
  /**
4
9
  * 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.
10
+ * `publication` says where it stopped, so the message does not.
6
11
  * Whatever a cancelled operation threw is its effect, not a cause.
7
12
  */
8
13
  export function cancellationError(): HashlineError<"OPERATION_ABORTED"> {
@@ -26,7 +31,7 @@ export class FileChangedDuringReadError extends HashlineError<"FILE_CHANGED"> {
26
31
 
27
32
  /**
28
33
  * 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
34
+ * revision grep-search hashed while matching, and grep-reread reads the file again
30
35
  * against it.
31
36
  */
32
37
  export function searchChangedError(): HashlineError<"FILE_CHANGED"> {
@@ -37,13 +42,9 @@ export function searchChangedError(): HashlineError<"FILE_CHANGED"> {
37
42
  * A per-file failure that leaves the rest of the search valid: a filesystem error, or the
38
43
  * file changing while it was searched or displayed. Undefined for any other failure.
39
44
  */
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;
45
+ export function fileReadWarning(filePath: string, error: unknown): SearchWarning | undefined {
46
+ if (!(error instanceof Error)) return undefined;
46
47
  const changed = error instanceof HashlineError && error.errorCode === "FILE_CHANGED";
47
48
  if (!changed && errnoCode(error) === undefined) return undefined;
48
- return `Could not read ${filePath}: ${error.message}`;
49
+ return { path: filePath, reason: error.message };
49
50
  }