@criogaid/pi-hashline-edit 0.6.0 → 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 +56 -59
  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 +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  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
@@ -11,7 +11,7 @@ import { makeReadOverride } from "./read-tool.ts";
11
11
  import { makeReplaceTool } from "./replace-tool.ts";
12
12
  import { makeWriteOverride } from "./write-tool.ts";
13
13
  import { callTool } from "./tool-call.testing.ts";
14
- import { MAX_BLOCK_BYTES } from "./budgets.ts";
14
+ import { argumentError, rejectsArgument } from "./argument-error.testing.ts";
15
15
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
16
 
17
17
  const invalidCommand = { command: "", timeout: 0 };
@@ -22,17 +22,14 @@ const cases = [
22
22
  make: (cwd: string, _fusion: ReturnType<typeof createActionFusionExecutor>) =>
23
23
  makeReadOverride(cwd, DEFAULT_CONFIG),
24
24
  args: { offset: -1, limit: 0 },
25
- diagnostics: [
26
- new RegExp(`\\n - offset:.*>= ${POSITIVE_SAFE_INTEGER.minimum}`),
27
- new RegExp(`\\n - limit:.*>= ${POSITIVE_SAFE_INTEGER.minimum}`),
28
- ],
25
+ fields: ["offset", "limit"],
29
26
  },
30
27
  {
31
28
  name: "grep",
32
29
  make: (cwd: string, _fusion: ReturnType<typeof createActionFusionExecutor>) =>
33
30
  makeGrepOverride(cwd, DEFAULT_CONFIG),
34
31
  args: { pattern: [], literal: true, limit: 0, context: -1 },
35
- diagnostics: [/\n - pattern:/, /\n - limit:/, /\n - context:/],
32
+ fields: ["pattern", "limit", "context"],
36
33
  },
37
34
  {
38
35
  name: "edit",
@@ -47,15 +44,15 @@ const cases = [
47
44
  ],
48
45
  then_run: invalidCommand,
49
46
  },
50
- diagnostics: [
51
- /Invalid argument edits\[0\]\.body:.*delete/,
52
- /Invalid argument edits\[1\]\.body\[0\]: UNSUPPORTED_TEXT:/,
53
- /Invalid argument edits\[1\]\.body\[1\]: INVALID_UNICODE:/,
54
- /Invalid argument edits\[2\]\.anchor:.*safe integer/,
55
- /Invalid argument edits\[2\]\.end:.*hash/,
56
- /Invalid argument edits\[3\]\.body:.*empty/,
57
- /\n - then_run.command:/,
58
- /\n - then_run.timeout:/,
47
+ fields: [
48
+ "edits[0].body",
49
+ "edits[1].body[0]",
50
+ "edits[1].body[1]",
51
+ "edits[2].anchor",
52
+ "edits[2].end",
53
+ "edits[3].body",
54
+ "then_run.command",
55
+ "then_run.timeout",
59
56
  ],
60
57
  },
61
58
  {
@@ -69,13 +66,13 @@ const cases = [
69
66
  ],
70
67
  then_run: invalidCommand,
71
68
  },
72
- diagnostics: [
73
- /Invalid argument replacements\[0\]\.replace: UNSUPPORTED_TEXT:/,
74
- /Invalid argument replacements\[0\]\.find: invalid regex/,
75
- /Invalid argument replacements\[1\]\.replace: INVALID_UNICODE:/,
76
- /Invalid argument replacements\[1\]\.find: invalid regex/,
77
- /\n - then_run.command:/,
78
- /\n - then_run.timeout:/,
69
+ fields: [
70
+ "replacements[0].replace",
71
+ "replacements[0].find",
72
+ "replacements[1].replace",
73
+ "replacements[1].find",
74
+ "then_run.command",
75
+ "then_run.timeout",
79
76
  ],
80
77
  },
81
78
  {
@@ -83,12 +80,7 @@ const cases = [
83
80
  make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
84
81
  makeWriteOverride(cwd, fusion),
85
82
  args: { content: "bad\0", mode: "invalid", then_run: invalidCommand },
86
- diagnostics: [
87
- /Invalid argument content: UNSUPPORTED_TEXT:/,
88
- /\n - mode:/,
89
- /\n - then_run.command:/,
90
- /\n - then_run.timeout:/,
91
- ],
83
+ fields: ["content", "mode", "then_run.command", "then_run.timeout"],
92
84
  },
93
85
  ] as const;
94
86
 
@@ -105,18 +97,13 @@ for (const scenario of cases) {
105
97
  return { status: "succeeded", output: "ran" };
106
98
  });
107
99
  const tool = scenario.make(cwd, fusion);
108
- // These values round-trip through JSON exactly as model tool arguments do.
109
100
  const args: unknown = JSON.parse(JSON.stringify({ path, ...scenario.args, unexpected: true }));
110
- await assert.rejects(callTool(tool, args), (error: Error) => {
111
- for (const diagnostic of [...scenario.diagnostics, /\n - unexpected:/]) {
112
- assert.match(error.message, diagnostic);
113
- }
114
- assert.doesNotMatch(error.message, /\n - path:/);
115
- assert.doesNotMatch(error.message, /Received arguments:\n/);
116
- const echoedArgs = [...error.message.matchAll(/^Received arguments: (.+)$/gm)].map((match) =>
117
- JSON.parse(match[1]),
101
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
102
+ const result = argumentError(error);
103
+ assert.deepEqual(
104
+ new Set(result.issues.map((issue) => issue.field)),
105
+ new Set([...scenario.fields, "unexpected"]),
118
106
  );
119
- assert.deepEqual(echoedArgs.at(-1), { unexpected: true });
120
107
  return true;
121
108
  });
122
109
  assert.equal(await readFile(path, "utf8"), original);
@@ -124,13 +111,723 @@ for (const scenario of cases) {
124
111
  });
125
112
  }
126
113
 
127
- test("argument diagnostics exceed the shared budget → rejection labels omitted text", async () => {
114
+ test("known edit operations with empty bodies → report the actionable issue once", async () => {
115
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
116
+ for (const op of ["replace", "insert_after", "insert_before", "append", "prepend"]) {
117
+ const operation = {
118
+ op,
119
+ ...(op === "append" || op === "prepend" ? {} : { anchor: `22#${anchorHash}` }),
120
+ body: [],
121
+ };
122
+ await assert.rejects(
123
+ callTool(tool, { path: "unused.txt", edits: [operation] }),
124
+ (error: unknown) => {
125
+ const result = argumentError(error);
126
+ assert.equal(result.issues.length, 1);
127
+ assert.equal(result.issues[0].field, "edits[0].body");
128
+ assert.match(result.issues[0].reason, /empty/);
129
+ assert.match(
130
+ result.issues[0].fix ?? "",
131
+ op === "replace" ? /delete/ : /supply at least one line/,
132
+ );
133
+ assert.equal(result.schemaLimited, undefined);
134
+ return true;
135
+ },
136
+ );
137
+ }
138
+ });
139
+
140
+ test("known edit branch has independent errors → report them without unrelated branches", async () => {
141
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG, createActionFusionExecutor());
142
+ await assert.rejects(
143
+ callTool(tool, {
144
+ path: "unused.txt",
145
+ edits: [
146
+ { op: "insert_after", body: [], extra: true },
147
+ { op: "delete", anchor: `2#${anchorHash}`, body: ["wrong"] },
148
+ { op: "replace", anchor: "bad", body: ["valid"] },
149
+ ],
150
+ then_run: invalidCommand,
151
+ unexpected: true,
152
+ }),
153
+ (error: unknown) => {
154
+ const result = argumentError(error);
155
+ assert.deepEqual(
156
+ new Set(result.issues.map((issue) => issue.field)),
157
+ new Set([
158
+ "edits[0].body",
159
+ "edits[0].anchor",
160
+ "edits[0].extra",
161
+ "edits[1].body",
162
+ "edits[2].anchor",
163
+ "then_run.command",
164
+ "then_run.timeout",
165
+ "unexpected",
166
+ ]),
167
+ );
168
+ return true;
169
+ },
170
+ );
171
+ });
172
+
173
+ test("edit operation tag is missing or invalid → report its field once without guessing a branch", async () => {
174
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
175
+ for (const tag of [undefined, "unknown", null, 42, {}]) {
176
+ await assert.rejects(
177
+ callTool(tool, {
178
+ path: "unused.txt",
179
+ edits: [
180
+ { ...(tag === undefined ? {} : { op: tag }), anchor: `1#${anchorHash}`, body: ["valid"] },
181
+ ],
182
+ }),
183
+ (error: unknown) => {
184
+ const result = argumentError(error);
185
+ assert.equal(result.issues.length, 1);
186
+ assert.equal(result.issues[0].field, "edits[0].op");
187
+ if (tag === undefined) assert.match(result.issues[0].reason, /required/);
188
+ else
189
+ for (const op of [
190
+ "replace",
191
+ "delete",
192
+ "insert_before",
193
+ "insert_after",
194
+ "append",
195
+ "prepend",
196
+ ])
197
+ assert.ok(result.issues[0].reason.includes(op));
198
+ return true;
199
+ },
200
+ );
201
+ }
202
+ });
203
+
204
+ test("edit range end is null → preserve the original rejection and its field diagnostic", async () => {
205
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
206
+ for (const operation of [
207
+ { op: "delete", anchor: `1#${anchorHash}`, end: null },
208
+ { op: "replace", anchor: `1#${anchorHash}`, end: null, body: ["ok"] },
209
+ { op: "replace", anchor: `1#${anchorHash}`, end: null, body: [] },
210
+ ]) {
211
+ await assert.rejects(
212
+ callTool(tool, { path: "unused.txt", edits: [operation] }),
213
+ (error: unknown) => {
214
+ const result = argumentError(error);
215
+ assert.deepEqual(
216
+ result.issues.map((issue) => issue.field),
217
+ operation.body?.length === 0 ? ["edits[0].body", "edits[0].end"] : ["edits[0].end"],
218
+ );
219
+ return true;
220
+ },
221
+ );
222
+ }
223
+ });
224
+
225
+ test("edit item is not an object → report the item type once", async () => {
226
+ for (const item of [null, 42, "bad", [], true]) {
227
+ await assert.rejects(
228
+ callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
229
+ path: "unused.txt",
230
+ edits: [item],
231
+ }),
232
+ (error: unknown) => {
233
+ const result = argumentError(error);
234
+ assert.equal(result.issues.length, 1);
235
+ return rejectsArgument("edits[0]", /object/)(error);
236
+ },
237
+ );
238
+ }
239
+ });
240
+
241
+ test("grep union value has one applicable type → report only its constraint", async () => {
242
+ for (const pattern of ["", [], [""]]) {
243
+ await assert.rejects(
244
+ callTool(makeGrepOverride(process.cwd(), DEFAULT_CONFIG), { pattern, literal: true }),
245
+ (error: unknown) => {
246
+ const result = argumentError(error);
247
+ assert.equal(result.issues.length, 1);
248
+ assert.match(result.issues[0].field, /^pattern(?:\[0\])?$/);
249
+ assert.doesNotMatch(result.issues[0].reason, /anyOf/);
250
+ return true;
251
+ },
252
+ );
253
+ }
254
+ });
255
+
256
+ test("literal enum is invalid → report the permitted values once", async () => {
257
+ await assert.rejects(
258
+ callTool(makeWriteOverride(process.cwd()), { path: "unused.txt", content: "ok", mode: "bad" }),
259
+ (error: unknown) => {
260
+ const result = argumentError(error);
261
+ assert.equal(result.issues.length, 1);
262
+ return rejectsArgument("mode", /create.*overwrite/)(error);
263
+ },
264
+ );
265
+ });
266
+
267
+ test("specific child errors exist → omit parent summaries and retain independent fields", async () => {
268
+ await assert.rejects(
269
+ callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG, createActionFusionExecutor()), {
270
+ path: "unused.txt",
271
+ edits: [{ op: "insert_after", body: ["ok"], extra: true }, { op: "unknown" }],
272
+ then_run: { command: "echo ok", extra: true },
273
+ unexpected: true,
274
+ }),
275
+ (error: unknown) => {
276
+ const result = argumentError(error);
277
+ assert.deepEqual(
278
+ new Set(result.issues.map((issue) => issue.field)),
279
+ new Set([
280
+ "edits[0].anchor",
281
+ "edits[0].extra",
282
+ "edits[1].op",
283
+ "then_run.extra",
284
+ "unexpected",
285
+ ]),
286
+ );
287
+ return true;
288
+ },
289
+ );
290
+ });
291
+
292
+ test("operation shape does not permit a field → omit inapplicable semantic advice", async () => {
293
+ for (const edits of [
294
+ [{ op: "unknown", anchor: "1#A", body: [] }],
295
+ [{ op: "delete", anchor: `1#${anchorHash}`, body: [] }],
296
+ "bad",
297
+ ]) {
298
+ await assert.rejects(
299
+ callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), { path: "unused.txt", edits }),
300
+ (error: unknown) => {
301
+ const result = argumentError(error);
302
+ assert.equal(result.issues.length, 1);
303
+ assert.doesNotMatch(result.issues[0].reason, /empty|hash length mismatch/);
304
+ return true;
305
+ },
306
+ );
307
+ }
308
+ });
309
+
310
+ test("Pi coerces valid fields while another field fails → do not diagnose the original value", async () => {
311
+ await assert.rejects(
312
+ callTool(makeReadOverride(process.cwd(), DEFAULT_CONFIG), {
313
+ path: "unused.txt",
314
+ offset: "1",
315
+ limit: 0,
316
+ }),
317
+ (error: unknown) => {
318
+ const result = argumentError(error);
319
+ assert.deepEqual(
320
+ result.issues.map((issue) => issue.field),
321
+ ["limit"],
322
+ );
323
+ assert.equal(result.schemaLimited, undefined);
324
+ return true;
325
+ },
326
+ );
327
+ });
328
+
329
+ test("multiple required fields are missing → report every missing field", async () => {
330
+ await assert.rejects(
331
+ callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
332
+ path: "unused.txt",
333
+ edits: [{ op: "replace" }],
334
+ }),
335
+ (error: unknown) => {
336
+ const result = argumentError(error);
337
+ assert.deepEqual(
338
+ new Set(result.issues.map((issue) => issue.field)),
339
+ new Set(["edits[0].anchor", "edits[0].body"]),
340
+ );
341
+ assert.ok(result.issues.every((issue) => /required/.test(issue.reason)));
342
+ assert.equal(result.schemaLimited, undefined);
343
+ return true;
344
+ },
345
+ );
346
+ });
347
+
348
+ test("unknown field names contain punctuation, numeric keys or newlines → quote property keys without treating them as array indices", async () => {
349
+ for (const key of ["odd.\nfield/~", "0", "01", "a/b", "a~b", 'quote"field']) {
350
+ await assert.rejects(
351
+ callTool(makeReadOverride(process.cwd(), DEFAULT_CONFIG), {
352
+ path: "unused.txt",
353
+ [key]: true,
354
+ }),
355
+ (error: unknown) => {
356
+ const result = argumentError(error);
357
+ assert.equal(result.issues.length, 1);
358
+ assert.equal(result.issues[0].field, `[${JSON.stringify(key)}]`);
359
+ return true;
360
+ },
361
+ );
362
+ }
363
+ });
364
+
365
+ test("one field exhausts native diagnostics → label the limit and retain another field", async () => {
366
+ await assert.rejects(
367
+ callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
368
+ path: "",
369
+ edits: Array.from({ length: 30 }, () => ({ op: "unknown" })),
370
+ }),
371
+ (error: unknown) => {
372
+ const result = argumentError(error);
373
+ assert.ok(result.issues.some((issue) => issue.field === "path"));
374
+ assert.ok(result.issues.some((issue) => issue.field === "edits[0].op"));
375
+ assert.equal(result.schemaLimited, true);
376
+ return true;
377
+ },
378
+ );
379
+ });
380
+
381
+ test("one field violates independent constraints → combine its reasons without losing either", async () => {
382
+ await assert.rejects(
383
+ callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
384
+ path: "unused.txt",
385
+ edits: [{ op: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#A` }],
386
+ }),
387
+ (error: unknown) => {
388
+ const result = argumentError(error);
389
+ assert.equal(result.issues.length, 1);
390
+ return rejectsArgument("edits[0].anchor", /safe integer[\s\S]*hash characters/)(error);
391
+ },
392
+ );
393
+ await assert.rejects(
394
+ callTool(makeReadOverride(process.cwd(), DEFAULT_CONFIG), { path: "unused.txt", offset: 0.5 }),
395
+ (error: unknown) => {
396
+ const result = argumentError(error);
397
+ assert.equal(result.issues.length, 1);
398
+ assert.match(
399
+ result.issues[0].reason,
400
+ new RegExp(`multiple of ${POSITIVE_SAFE_INTEGER.multipleOf}`),
401
+ );
402
+ assert.match(result.issues[0].reason, new RegExp(`>= ${POSITIVE_SAFE_INTEGER.minimum}`));
403
+ return true;
404
+ },
405
+ );
406
+ });
407
+
408
+ test("copy/move destination tokens → reject unsafe positions and wrong hash lengths before reading", async () => {
128
409
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
129
- const edits = Array.from({ length: MAX_BLOCK_BYTES }, () => ({ op: "append", body: [] }));
130
- await assert.rejects(callTool(tool, { path: "", edits }), (error: Error) => {
131
- assert.ok(Buffer.byteLength(error.message) <= MAX_BLOCK_BYTES);
132
- assert.match(error.message, /Invalid argument edits\[0\]\.body:/);
133
- assert.match(error.message, /Diagnostics truncated/);
134
- return true;
410
+ for (const op of ["copy", "move"]) {
411
+ for (const side of ["before", "after"]) {
412
+ for (const [token, reason] of [
413
+ [`${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, /safe integer/],
414
+ ["1#A", /has 1 hash characters/],
415
+ ] as const) {
416
+ await assert.rejects(
417
+ callTool(tool, {
418
+ path: "missing-copy-move.txt",
419
+ edits: [{ op, anchor: `1#${anchorHash}`, [side]: token }],
420
+ }),
421
+ rejectsArgument(`edits[0].${side}`, reason),
422
+ );
423
+ }
424
+ }
425
+ }
426
+ });
427
+
428
+ test("copy/move illegal argument shapes → reject before any file access", async () => {
429
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
430
+ const anchor = `1#${anchorHash}`;
431
+ for (const op of ["copy", "move"]) {
432
+ for (const fields of [
433
+ {},
434
+ { before: anchor, after: anchor },
435
+ { before: anchor, body: ["unused"] },
436
+ { after: anchor, end: null },
437
+ { before: 1 },
438
+ { before: anchor, end: "1#IXXX" },
439
+ ]) {
440
+ await assert.rejects(
441
+ callTool(tool, { path: "missing-copy-move.txt", edits: [{ op, anchor, ...fields }] }),
442
+ (error: unknown) => {
443
+ const result = argumentError(error);
444
+ assert.equal(result.tool, "edit");
445
+ assert(result.issues.length > 0);
446
+ if ("body" in fields)
447
+ assert(result.issues.some((issue) => issue.field === "edits[0].body"));
448
+ if ("end" in fields)
449
+ assert(result.issues.some((issue) => issue.field === "edits[0].end"));
450
+ if (fields.before === 1)
451
+ assert(result.issues.some((issue) => issue.field === "edits[0].before"));
452
+ return true;
453
+ },
454
+ );
455
+ }
456
+ }
457
+ });
458
+
459
+ const exactlyOneDestination = /expected exactly one of: before, after/;
460
+
461
+ for (const op of ["copy", "move"] as const) {
462
+ test(`${op} without a destination → one exactly-one issue without a description fix`, async () => {
463
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
464
+ await assert.rejects(
465
+ callTool(tool, {
466
+ path: "unused.txt",
467
+ edits: [{ op, anchor: `1#${anchorHash}` }],
468
+ }),
469
+ (error: unknown) => {
470
+ const result = argumentError(error);
471
+ assert.equal(result.issues.length, 1);
472
+ assert.equal(result.issues[0].field, "edits[0]");
473
+ assert.match(result.issues[0].reason, exactlyOneDestination);
474
+ assert.equal(result.issues[0].fix, undefined);
475
+ assert.equal(result.schemaLimited, undefined);
476
+ return true;
477
+ },
478
+ );
135
479
  });
480
+
481
+ test(`${op} with both destinations → the same single exactly-one issue, no not-allowed pair`, async () => {
482
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
483
+ await assert.rejects(
484
+ callTool(tool, {
485
+ path: "unused.txt",
486
+ edits: [
487
+ { op, anchor: `1#${anchorHash}`, before: `2#${anchorHash}`, after: `3#${anchorHash}` },
488
+ ],
489
+ }),
490
+ (error: unknown) => {
491
+ const result = argumentError(error);
492
+ assert.equal(result.issues.length, 1);
493
+ assert.equal(result.issues[0].field, "edits[0]");
494
+ assert.match(result.issues[0].reason, exactlyOneDestination);
495
+ assert.equal(result.schemaLimited, undefined);
496
+ return true;
497
+ },
498
+ );
499
+ });
500
+ }
501
+
502
+ test("mixed copy and move batch → every operation keeps its exactly-one and unknown-field issues", async () => {
503
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
504
+ await assert.rejects(
505
+ callTool(tool, {
506
+ path: "unused.txt",
507
+ edits: [
508
+ { op: "copy", anchor: `1#${anchorHash}`, start: { x: 1 }, to: `2#${anchorHash}` },
509
+ { op: "move", anchor: `3#${anchorHash}` },
510
+ ],
511
+ }),
512
+ (error: unknown) => {
513
+ const result = argumentError(error);
514
+ assert.deepEqual(
515
+ new Set(result.issues.map((issue) => issue.field)),
516
+ new Set(["edits[0]", "edits[0].start", "edits[0].to", "edits[1]"]),
517
+ );
518
+ for (const field of ["edits[0]", "edits[1]"])
519
+ assert.match(
520
+ result.issues.find((issue) => issue.field === field)?.reason ?? "",
521
+ exactlyOneDestination,
522
+ );
523
+ for (const field of ["edits[0].start", "edits[0].to"])
524
+ assert.match(
525
+ result.issues.find((issue) => issue.field === field)?.reason ?? "",
526
+ /not allowed/,
527
+ );
528
+ assert.equal(result.schemaLimited, undefined);
529
+ return true;
530
+ },
531
+ );
532
+ });
533
+
534
+ for (const op of ["copy", "move"] as const) {
535
+ test(`${op} with both destinations and a wrong before hash → keeps the hash-length issue beside exactly-one`, async () => {
536
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
537
+ const shortHash = `2#${"A".repeat(DEFAULT_CONFIG.hashLen - 1)}`;
538
+ await assert.rejects(
539
+ callTool(tool, {
540
+ path: "unused.txt",
541
+ edits: [{ op, anchor: `1#${anchorHash}`, before: shortHash, after: `3#${anchorHash}` }],
542
+ }),
543
+ (error: unknown) => {
544
+ const result = argumentError(error);
545
+ const exactly = result.issues.filter((issue) => issue.field === "edits[0]");
546
+ assert.equal(exactly.length, 1);
547
+ assert.match(exactly[0].reason, exactlyOneDestination);
548
+ const hashIssue = result.issues.find((issue) => issue.field === "edits[0].before");
549
+ assert.ok(hashIssue, JSON.stringify(result.issues));
550
+ assert.match(hashIssue.reason, /hash characters/);
551
+ assert.match(hashIssue.fix ?? "", /Read or grep/);
552
+ assert.ok(!result.issues.some((issue) => issue.field === "edits[0].after"));
553
+ return true;
554
+ },
555
+ );
556
+ });
557
+ }
558
+
559
+ for (const op of ["copy", "move"] as const) {
560
+ for (const side of ["before", "after"] as const) {
561
+ test(`${op} with one ${side} destination and an unknown field → only the unknown field is reported`, async () => {
562
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
563
+ await assert.rejects(
564
+ callTool(tool, {
565
+ path: "unused.txt",
566
+ edits: [
567
+ { op, anchor: `1#${anchorHash}`, [side]: `2#${anchorHash}`, to: `3#${anchorHash}` },
568
+ ],
569
+ }),
570
+ (error: unknown) => {
571
+ const result = argumentError(error);
572
+ assert.equal(result.issues.length, 1);
573
+ assert.equal(result.issues[0].field, "edits[0].to");
574
+ assert.match(result.issues[0].reason, /not allowed/);
575
+ assert.equal(result.schemaLimited, undefined);
576
+ return true;
577
+ },
578
+ );
579
+ });
580
+ }
581
+ }
582
+
583
+ /** Tool schema properties, so expected fix text comes from the schema instead of the test. */
584
+ interface SchemaNode {
585
+ readonly description?: string;
586
+ readonly const?: unknown;
587
+ readonly anyOf?: readonly SchemaNode[];
588
+ readonly properties?: Readonly<Record<string, SchemaNode>>;
589
+ readonly items?: SchemaNode;
590
+ }
591
+
592
+ const schemaProperties = (tool: {
593
+ readonly parameters: unknown;
594
+ }): Readonly<Record<string, SchemaNode>> =>
595
+ (tool.parameters as { properties: Readonly<Record<string, SchemaNode>> }).properties;
596
+
597
+ const inOrder = (fix: string, pieces: readonly string[]): void => {
598
+ let cursor = -1;
599
+ for (const piece of pieces) {
600
+ const at = fix.indexOf(piece);
601
+ assert.ok(at > cursor, `missing or out of order: ${piece} in ${fix}`);
602
+ cursor = at;
603
+ }
604
+ };
605
+
606
+ test("missing required parameter → fix states the parameter's role from its schema description", async () => {
607
+ const grep = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
608
+ const write = makeWriteOverride(process.cwd());
609
+ const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
610
+ const cases = [
611
+ {
612
+ name: "grep literal",
613
+ tool: grep,
614
+ args: { pattern: "text" },
615
+ field: "literal",
616
+ verify: (fix: string) => assert.equal(fix, schemaProperties(grep).literal?.description),
617
+ },
618
+ {
619
+ name: "write mode",
620
+ tool: write,
621
+ args: { path: "unused.txt", content: "text" },
622
+ field: "mode",
623
+ verify: (fix: string) => {
624
+ const [create, overwrite] = schemaProperties(write).mode?.anyOf ?? [];
625
+ assert.ok(create?.description && overwrite?.description);
626
+ inOrder(fix, ['"create"', create.description, '"overwrite"', overwrite.description]);
627
+ },
628
+ },
629
+ {
630
+ name: "edit op",
631
+ tool: edit,
632
+ args: { path: "unused.txt", edits: [{ anchor: `1#${anchorHash}`, body: ["text"] }] },
633
+ field: "edits[0].op",
634
+ verify: (fix: string) => {
635
+ for (const op of [
636
+ "replace",
637
+ "delete",
638
+ "insert_before",
639
+ "insert_after",
640
+ "copy",
641
+ "move",
642
+ "append",
643
+ "prepend",
644
+ ])
645
+ assert.ok(fix.includes(`\"${op}\"`), `${op} missing from ${fix}`);
646
+ assert.equal(fix.split('"copy"').length - 1, 1);
647
+ assert.equal(fix.split('"move"').length - 1, 1);
648
+ },
649
+ },
650
+ ] as const;
651
+ for (const scenario of cases) {
652
+ await assert.rejects(callTool(scenario.tool, scenario.args), (error: unknown) => {
653
+ const result = argumentError(error);
654
+ const issue = result.issues.find((candidate) => candidate.field === scenario.field);
655
+ assert.ok(issue, JSON.stringify(result.issues));
656
+ assert.match(issue.reason, /is required/);
657
+ assert.ok(issue.fix, JSON.stringify(result.issues));
658
+ scenario.verify(issue.fix);
659
+ return true;
660
+ });
661
+ }
662
+ });
663
+
664
+ test("two operations miss the same required field → the shared fix appears once", async () => {
665
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
666
+ await assert.rejects(
667
+ callTool(tool, { path: "unused.txt", edits: [{ op: "replace" }, { op: "replace" }] }),
668
+ (error: unknown) => {
669
+ const result = argumentError(error);
670
+ const anchors = result.issues.filter((issue) => issue.field.endsWith(".anchor"));
671
+ assert.equal(anchors.length, 2);
672
+ assert.equal(anchors.filter((issue) => issue.fix).length, 1);
673
+ const fixes = result.issues.flatMap((issue) => (issue.fix ? [issue.fix] : []));
674
+ assert.equal(new Set(fixes).size, fixes.length, JSON.stringify(fixes));
675
+ const anchorDescriptions = new Set(
676
+ (schemaProperties(tool).edits?.items?.anyOf ?? []).flatMap((branch) =>
677
+ branch.properties?.anchor ? [branch.properties.anchor.description] : [],
678
+ ),
679
+ );
680
+ assert.equal(anchorDescriptions.size, 1);
681
+ const description = [...anchorDescriptions][0];
682
+ assert.ok(description);
683
+ assert.ok(fixes.includes(description));
684
+ return true;
685
+ },
686
+ );
687
+ });
688
+
689
+ test("invalid enum value → the reason carries no description fix", async () => {
690
+ await assert.rejects(
691
+ callTool(makeGrepOverride(process.cwd(), DEFAULT_CONFIG), {
692
+ path: "unused.txt",
693
+ pattern: "text",
694
+ literal: true,
695
+ outputMode: "unknown",
696
+ }),
697
+ (error: unknown) => {
698
+ const result = argumentError(error);
699
+ assert.equal(result.issues.length, 1);
700
+ assert.equal(result.issues[0].field, "outputMode");
701
+ assert.match(result.issues[0].reason, /expected one of/);
702
+ assert.equal(result.issues[0].fix, undefined);
703
+ return true;
704
+ },
705
+ );
706
+ });
707
+
708
+ const branchWithOp = (tool: { readonly parameters: unknown }, op: string): SchemaNode => {
709
+ const branch = (schemaProperties(tool).edits?.items?.anyOf ?? []).find((candidate) => {
710
+ const opSchema = candidate.properties?.op;
711
+ return [opSchema?.const, ...(opSchema?.anyOf ?? []).map((option) => option.const)].includes(op);
712
+ });
713
+ assert.ok(branch, `no edit branch for op ${op}`);
714
+ return branch;
715
+ };
716
+
717
+ const acceptedFields = (branch: SchemaNode): string =>
718
+ `Accepted fields: ${Object.keys(branch.properties ?? {}).join(", ")}.`;
719
+
720
+ const opExplanation = (branch: SchemaNode): string => {
721
+ const options = branch.properties?.op?.anyOf ?? [{ const: branch.properties?.op?.const }];
722
+ return `${options.map((option) => JSON.stringify(option.const)).join(" or ")}: ${branch.properties?.op?.description}`;
723
+ };
724
+
725
+ test("extra field is not allowed → fix describes the selected shape from its schema", async () => {
726
+ const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
727
+ const grep = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
728
+ const append = branchWithOp(edit, "append");
729
+ const move = branchWithOp(edit, "move");
730
+ const cases = [
731
+ {
732
+ name: "tagged branch rejects another branch's field",
733
+ tool: edit,
734
+ args: {
735
+ path: "unused.txt",
736
+ edits: [{ op: "append", anchor: `1#${anchorHash}`, body: ["text"] }],
737
+ },
738
+ field: "edits[0].anchor",
739
+ fix: `${opExplanation(append)} ${acceptedFields(append)}`,
740
+ },
741
+ {
742
+ name: "unknown top-level field",
743
+ tool: grep,
744
+ args: { path: "unused.txt", pattern: "text", literal: true, bogus: 1 },
745
+ field: "bogus",
746
+ fix: acceptedFields({ properties: schemaProperties(grep) }),
747
+ },
748
+ {
749
+ name: "transfer branch selected by before",
750
+ tool: edit,
751
+ args: {
752
+ path: "unused.txt",
753
+ edits: [
754
+ { op: "move", anchor: `1#${anchorHash}`, before: `2#${anchorHash}`, body: ["text"] },
755
+ ],
756
+ },
757
+ field: "edits[0].body",
758
+ fix: `${opExplanation(move)} ${acceptedFields(move)}`,
759
+ },
760
+ ] as const;
761
+ for (const scenario of cases) {
762
+ await assert.rejects(callTool(scenario.tool, scenario.args), (error: unknown) => {
763
+ const result = argumentError(error);
764
+ const issue = result.issues.find((candidate) => candidate.field === scenario.field);
765
+ assert.ok(issue, JSON.stringify(result.issues));
766
+ assert.match(issue.reason, /is not allowed/);
767
+ assert.equal(issue.fix, scenario.fix, JSON.stringify(result.issues));
768
+ return true;
769
+ });
770
+ }
771
+ });
772
+
773
+ test("value mismatches the field pattern → fix states the field description from the schema", async () => {
774
+ const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
775
+ const append = branchWithOp(edit, "append");
776
+ const replace = branchWithOp(edit, "replace");
777
+ const cases = [
778
+ {
779
+ name: "body element with a newline",
780
+ args: { path: "unused.txt", edits: [{ op: "append", body: ["a\nb"] }] },
781
+ field: "edits[0].body[0]",
782
+ fix: append.properties?.body?.description,
783
+ },
784
+ {
785
+ name: "anchor without the line-hash shape",
786
+ args: { path: "unused.txt", edits: [{ op: "replace", anchor: "abc", body: ["text"] }] },
787
+ field: "edits[0].anchor",
788
+ fix: replace.properties?.anchor?.description,
789
+ },
790
+ ] as const;
791
+ for (const scenario of cases) {
792
+ await assert.rejects(callTool(edit, scenario.args), (error: unknown) => {
793
+ const result = argumentError(error);
794
+ const issue = result.issues.find((candidate) => candidate.field === scenario.field);
795
+ assert.ok(issue, JSON.stringify(result.issues));
796
+ assert.match(issue.reason, /^must match pattern/);
797
+ assert.equal(issue.fix, scenario.fix, JSON.stringify(result.issues));
798
+ return true;
799
+ });
800
+ }
801
+ });
802
+
803
+ test("two unknown fields in one object → the shared fix appears once", async () => {
804
+ const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
805
+ await assert.rejects(
806
+ callTool(edit, {
807
+ path: "unused.txt",
808
+ edits: [{ op: "append", body: ["text"], zzz: 1, yyy: 2 }],
809
+ }),
810
+ (error: unknown) => {
811
+ const result = argumentError(error);
812
+ assert.equal(result.issues.length, 2, JSON.stringify(result.issues));
813
+ assert.ok(result.issues.every((issue) => issue.reason === "is not allowed"));
814
+ assert.ok(result.issues[0].fix, JSON.stringify(result.issues));
815
+ assert.equal(result.issues[1].fix, undefined);
816
+ return true;
817
+ },
818
+ );
819
+ });
820
+
821
+ test("value has the wrong type → the reason carries no fix", async () => {
822
+ await assert.rejects(
823
+ callTool(makeReadOverride(process.cwd(), DEFAULT_CONFIG), { path: "unused.txt", limit: "abc" }),
824
+ (error: unknown) => {
825
+ const result = argumentError(error);
826
+ assert.equal(result.issues.length, 1);
827
+ assert.equal(result.issues[0].field, "limit");
828
+ assert.match(result.issues[0].reason, /must be number/);
829
+ assert.equal(result.issues[0].fix, undefined);
830
+ return true;
831
+ },
832
+ );
136
833
  });