@criogaid/pi-hashline-edit 0.8.0 → 0.9.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.
@@ -14,6 +14,7 @@ import { callTool } from "./tool-call.testing.ts";
14
14
  import { argumentError, rejectsArgument } from "./argument-error.testing.ts";
15
15
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
16
  import { reportOf } from "./report.ts";
17
+ import { createAnchorFormatter } from "./anchor-format.ts";
17
18
 
18
19
  const invalidCommand = { command: "", timeout: 0 };
19
20
  const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
@@ -38,10 +39,10 @@ const cases = [
38
39
  makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
39
40
  args: {
40
41
  edits: [
41
- { op: "replace", anchor: `1#${anchorHash}`, body: [] },
42
- { op: "append", body: ["bad\0", "bad\ud800"] },
43
- { op: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, end: "1#A" },
44
- { op: "append", body: [] },
42
+ { action: "replace", anchor: `1#${anchorHash}`, body: [] },
43
+ { action: "append", body: ["bad\0", "bad\ud800"] },
44
+ { action: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, end: "1#A" },
45
+ { action: "append", body: [] },
45
46
  ],
46
47
  then_run: invalidCommand,
47
48
  },
@@ -99,6 +100,7 @@ for (const scenario of cases) {
99
100
  });
100
101
  const tool = scenario.make(cwd, fusion);
101
102
  const args: unknown = JSON.parse(JSON.stringify({ path, ...scenario.args, unexpected: true }));
103
+ const snapshot = structuredClone(args);
102
104
  await assert.rejects(callTool(tool, args), (error: unknown) => {
103
105
  const result = argumentError(error);
104
106
  assert.deepEqual(
@@ -107,6 +109,7 @@ for (const scenario of cases) {
107
109
  );
108
110
  return true;
109
111
  });
112
+ assert.deepEqual(args, snapshot);
110
113
  assert.equal(await readFile(path, "utf8"), original);
111
114
  assert.equal(commandRuns, 0);
112
115
  });
@@ -156,112 +159,253 @@ test("grep and replace flags → accept V8 modes and reject invalid flags before
156
159
  }
157
160
  });
158
161
 
159
- test("known edit operations with empty bodies → report the actionable issue once", async () => {
160
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
161
- for (const op of ["replace", "insert_after", "insert_before", "append", "prepend"]) {
162
- const operation = {
163
- op,
164
- ...(op === "append" || op === "prepend" ? {} : { anchor: `22#${anchorHash}` }),
165
- body: [],
162
+ const editFields = ["anchor", "end", "body", "before", "after"] as const;
163
+ type EditField = (typeof editFields)[number];
164
+ const fieldValues = {
165
+ anchor: `1#${anchorHash}`,
166
+ end: `2#${anchorHash}`,
167
+ body: ["text"],
168
+ before: `3#${anchorHash}`,
169
+ after: `3#${anchorHash}`,
170
+ };
171
+ const actionCases: readonly {
172
+ action: string;
173
+ required: readonly EditField[];
174
+ optional: readonly EditField[];
175
+ transfer?: boolean;
176
+ expected: string;
177
+ }[] = [
178
+ {
179
+ action: "replace",
180
+ required: ["anchor", "body"],
181
+ optional: ["end"],
182
+ expected: "text\nbeta\ngamma\n",
183
+ },
184
+ { action: "delete", required: ["anchor"], optional: ["end"], expected: "beta\ngamma\n" },
185
+ {
186
+ action: "insert_after",
187
+ required: ["anchor", "body"],
188
+ optional: [],
189
+ expected: "alpha\ntext\nbeta\ngamma\n",
190
+ },
191
+ {
192
+ action: "insert_before",
193
+ required: ["anchor", "body"],
194
+ optional: [],
195
+ expected: "text\nalpha\nbeta\ngamma\n",
196
+ },
197
+ {
198
+ action: "copy",
199
+ required: ["anchor"],
200
+ optional: ["end", "before", "after"],
201
+ transfer: true,
202
+ expected: "alpha\nbeta\nalpha\ngamma\n",
203
+ },
204
+ {
205
+ action: "move",
206
+ required: ["anchor"],
207
+ optional: ["end", "before", "after"],
208
+ transfer: true,
209
+ expected: "beta\nalpha\ngamma\n",
210
+ },
211
+ { action: "append", required: ["body"], optional: [], expected: "alpha\nbeta\ngamma\ntext\n" },
212
+ { action: "prepend", required: ["body"], optional: [], expected: "text\nalpha\nbeta\ngamma\n" },
213
+ ];
214
+
215
+ for (const scenario of actionCases) {
216
+ test(`${scenario.action} field matrix → requires its fields and rejects fields it does not take`, async (t) => {
217
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
218
+ const fields = schemaProperties(tool).edits?.items?.properties;
219
+ const choice = fields?.action?.anyOf?.find((option) => option.const === scenario.action);
220
+ assert.ok(choice?.description);
221
+ const description = choice.description;
222
+ const valid = {
223
+ action: scenario.action,
224
+ ...Object.fromEntries(scenario.required.map((field) => [field, fieldValues[field]])),
225
+ ...(scenario.transfer ? { before: fieldValues.before } : {}),
166
226
  };
167
- await assert.rejects(
168
- callTool(tool, { path: "unused.txt", edits: [operation] }),
169
- (error: unknown) => {
170
- const result = argumentError(error);
171
- assert.equal(result.issues.length, 1);
172
- assert.equal(result.issues[0].field, "edits[0].body");
173
- assert.match(result.issues[0].reason, /empty/);
174
- assert.match(
175
- result.issues[0].fix ?? "",
176
- op === "replace" ? /delete/ : /supply at least one line/,
227
+ for (const field of scenario.required) {
228
+ for (const value of [undefined, null]) {
229
+ await t.test(
230
+ `${field} is ${value === null ? "null" : "missing"} → reports the required field`,
231
+ async () => {
232
+ const edit: Record<string, unknown> = Object.fromEntries(
233
+ Object.entries(valid).filter(([key]) => key !== field),
234
+ );
235
+ if (value === null) edit[field] = null;
236
+ const args = { path: "unused.txt", edits: [edit] };
237
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
238
+ assert.deepEqual(argumentError(error).issues, [
239
+ {
240
+ field: `edits[0].${field}`,
241
+ reason: `is required for "${scenario.action}"`,
242
+ fix: fields?.[field]?.description,
243
+ },
244
+ ]);
245
+ return true;
246
+ });
247
+ },
177
248
  );
178
- assert.equal(result.schemaLimited, undefined);
179
- return true;
180
- },
181
- );
182
- }
183
- });
184
-
185
- test("known edit branch has independent errors → report them without unrelated branches", async () => {
186
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG, createActionFusionExecutor());
187
- await assert.rejects(
188
- callTool(tool, {
189
- path: "unused.txt",
190
- edits: [
191
- { op: "insert_after", body: [], extra: true },
192
- { op: "delete", anchor: `2#${anchorHash}`, body: ["wrong"] },
193
- { op: "replace", anchor: "bad", body: ["valid"] },
194
- ],
195
- then_run: invalidCommand,
196
- unexpected: true,
197
- }),
198
- (error: unknown) => {
199
- const result = argumentError(error);
200
- assert.deepEqual(
201
- new Set(result.issues.map((issue) => issue.field)),
202
- new Set([
203
- "edits[0].body",
204
- "edits[0].anchor",
205
- "edits[0].extra",
206
- "edits[1].body",
207
- "edits[2].anchor",
208
- "then_run.command",
209
- "then_run.timeout",
210
- "unexpected",
211
- ]),
212
- );
213
- return true;
214
- },
215
- );
216
- });
249
+ }
250
+ }
251
+ for (const field of editFields.filter(
252
+ (field) => !scenario.required.includes(field) && !scenario.optional.includes(field),
253
+ )) {
254
+ await t.test(`${field} is supplied → reports only that forbidden field`, async () => {
255
+ await assert.rejects(
256
+ callTool(tool, {
257
+ path: "unused.txt",
258
+ edits: [{ ...valid, [field]: fieldValues[field] }],
259
+ }),
260
+ (error: unknown) => {
261
+ assert.deepEqual(argumentError(error).issues, [
262
+ {
263
+ field: `edits[0].${field}`,
264
+ reason: "is not allowed",
265
+ fix: `"${scenario.action}": ${description}`,
266
+ },
267
+ ]);
268
+ assert.match(description, /Takes /);
269
+ return true;
270
+ },
271
+ );
272
+ });
273
+ }
274
+ });
275
+ }
217
276
 
218
- test("edit operation tag is missing or invalid → report its field once without guessing a branch", async () => {
277
+ test("edit action is missing or invalid → reports choices without guessing field permissions", async () => {
219
278
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
220
- for (const tag of [undefined, "unknown", null, 42, {}]) {
279
+ const choices = schemaProperties(tool).edits?.items?.properties?.action?.anyOf ?? [];
280
+ assert.equal(choices.length, actionCases.length);
281
+ for (const action of [undefined, "unknown", null, 42, {}]) {
221
282
  await assert.rejects(
222
283
  callTool(tool, {
223
284
  path: "unused.txt",
224
285
  edits: [
225
- { ...(tag === undefined ? {} : { op: tag }), anchor: `1#${anchorHash}`, body: ["valid"] },
286
+ {
287
+ ...(action === undefined ? {} : { action }),
288
+ anchor: `1#${anchorHash}`,
289
+ body: ["valid"],
290
+ },
226
291
  ],
227
292
  }),
228
293
  (error: unknown) => {
229
- const result = argumentError(error);
230
- assert.equal(result.issues.length, 1);
231
- assert.equal(result.issues[0].field, "edits[0].op");
232
- if (tag === undefined) assert.match(result.issues[0].reason, /required/);
233
- else
234
- for (const op of [
235
- "replace",
236
- "delete",
237
- "insert_before",
238
- "insert_after",
239
- "append",
240
- "prepend",
241
- ])
242
- assert.ok(result.issues[0].reason.includes(op));
294
+ const { issues } = argumentError(error);
295
+ assert.equal(issues.length, 1);
296
+ const issue = issues[0];
297
+ assert.equal(issue.field, "edits[0].action");
298
+ if (action === undefined) {
299
+ assert.equal(issue.reason, "is required");
300
+ for (const choice of choices) {
301
+ assert.ok(choice.description);
302
+ inOrder(issue.fix ?? "", [JSON.stringify(choice.const), choice.description]);
303
+ }
304
+ } else {
305
+ assert.equal(
306
+ issue.reason,
307
+ `expected one of: ${choices.map((choice) => JSON.stringify(choice.const)).join(", ")}`,
308
+ );
309
+ assert.equal(issue.fix, undefined);
310
+ }
243
311
  return true;
244
312
  },
245
313
  );
246
314
  }
247
315
  });
248
316
 
249
- test("edit range end is null → preserve the original rejection and its field diagnostic", async () => {
250
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
251
- for (const operation of [
252
- { op: "delete", anchor: `1#${anchorHash}`, end: null },
253
- { op: "replace", anchor: `1#${anchorHash}`, end: null, body: ["ok"] },
254
- { op: "replace", anchor: `1#${anchorHash}`, end: null, body: [] },
255
- ]) {
256
- await assert.rejects(
257
- callTool(tool, { path: "unused.txt", edits: [operation] }),
258
- (error: unknown) => {
259
- const result = argumentError(error);
260
- assert.deepEqual(
261
- result.issues.map((issue) => issue.field),
262
- operation.body?.length === 0 ? ["edits[0].body", "edits[0].end"] : ["edits[0].end"],
263
- );
264
- return true;
317
+ test("optional edit fields and then_run are null with Fusion → publishes bytes without rewriting caller arguments", async (t) => {
318
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-null-"));
319
+ t.after(() => rm(cwd, { recursive: true, force: true }));
320
+ const path = join(cwd, "target.txt");
321
+ let commandRuns = 0;
322
+ const fusion = createActionFusionExecutor(async () => {
323
+ commandRuns++;
324
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
325
+ });
326
+ const tool = makeEditOverride(cwd, DEFAULT_CONFIG, fusion);
327
+ const anchors = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
328
+ for (const scenario of actionCases) {
329
+ for (const side of scenario.transfer ? ["before", "after"] : [undefined]) {
330
+ await t.test(
331
+ `${scenario.action}${side ? `/${side}` : ""} → accepts null optional fields`,
332
+ async () => {
333
+ await writeFile(path, "alpha\nbeta\ngamma\n");
334
+ const edit = {
335
+ action: scenario.action,
336
+ ...Object.fromEntries(editFields.map((field) => [field, null])),
337
+ ...Object.fromEntries(
338
+ scenario.required.map((field) => [
339
+ field,
340
+ field === "body" ? ["text"] : anchors.token(1, "alpha"),
341
+ ]),
342
+ ),
343
+ ...(side
344
+ ? {
345
+ [side]: anchors.token(
346
+ side === "before" ? 3 : 2,
347
+ side === "before" ? "gamma" : "beta",
348
+ ),
349
+ }
350
+ : {}),
351
+ };
352
+ const args = { path, edits: [edit], then_run: null };
353
+ const snapshot = structuredClone(args);
354
+ const result = await callTool(tool, args);
355
+ assert.equal(result.isError, undefined);
356
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
357
+ assert.equal(reportOf(result, "edit")?.then_run, undefined);
358
+ assert.deepEqual(await readFile(path), Buffer.from(scenario.expected));
359
+ assert.deepEqual(args, snapshot);
360
+ },
361
+ );
362
+ }
363
+ }
364
+ assert.equal(commandRuns, 0);
365
+ });
366
+
367
+ test("edit batch has 64 or 65 operations → publishes the maximum or rejects the oversized batch unchanged", async (t) => {
368
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-edit-limit-"));
369
+ t.after(() => rm(cwd, { recursive: true, force: true }));
370
+ const path = join(cwd, "target.txt");
371
+ const tool = makeEditOverride(cwd, DEFAULT_CONFIG);
372
+ const maxEdits: unknown = Reflect.get(tool.parameters.properties.edits, "maxItems");
373
+ assert.ok(typeof maxEdits === "number");
374
+ assert.equal(maxEdits, 64);
375
+ const lines = Array.from({ length: maxEdits + 2 }, (_, i) => `line ${i + 1}`);
376
+ const original = Buffer.from(`${lines.join("\n")}\n`);
377
+ const anchors = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
378
+ for (const count of [maxEdits, maxEdits + 1]) {
379
+ await t.test(
380
+ `${count} edits → ${count === maxEdits ? "publishes distinct deletions" : `rejects edits above max${maxEdits}`}`,
381
+ async () => {
382
+ await writeFile(path, original);
383
+ const args = {
384
+ path,
385
+ edits: lines
386
+ .slice(0, count)
387
+ .map((line, i) => ({ action: "delete", anchor: anchors.token(i + 1, line) })),
388
+ };
389
+ const snapshot = structuredClone(args);
390
+ if (count === maxEdits) {
391
+ const result = await callTool(tool, args);
392
+ assert.equal(result.isError, undefined);
393
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
394
+ assert.deepEqual(await readFile(path), Buffer.from(`${lines.slice(count).join("\n")}\n`));
395
+ } else {
396
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
397
+ const report = argumentError(error);
398
+ assert.equal(report.issues.length, 1);
399
+ assert.equal(report.issues[0].field, "edits");
400
+ assert.match(
401
+ report.issues[0].reason,
402
+ new RegExp(`must not have more than ${maxEdits} items`),
403
+ );
404
+ return true;
405
+ });
406
+ assert.deepEqual(await readFile(path), original);
407
+ }
408
+ assert.deepEqual(args, snapshot);
265
409
  },
266
410
  );
267
411
  }
@@ -309,68 +453,6 @@ test("literal enum is invalid → report the permitted values once", async () =>
309
453
  );
310
454
  });
311
455
 
312
- test("specific child errors exist → omit parent summaries and retain independent fields", async () => {
313
- await assert.rejects(
314
- callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG, createActionFusionExecutor()), {
315
- path: "unused.txt",
316
- edits: [{ op: "insert_after", body: ["ok"], extra: true }, { op: "unknown" }],
317
- then_run: { command: "echo ok", extra: true },
318
- unexpected: true,
319
- }),
320
- (error: unknown) => {
321
- const result = argumentError(error);
322
- assert.deepEqual(
323
- new Set(result.issues.map((issue) => issue.field)),
324
- new Set([
325
- "edits[0].anchor",
326
- "edits[0].extra",
327
- "edits[1].op",
328
- "then_run.extra",
329
- "unexpected",
330
- ]),
331
- );
332
- return true;
333
- },
334
- );
335
- });
336
-
337
- test("operation shape does not permit a field → omit inapplicable semantic advice", async () => {
338
- for (const edits of [
339
- [{ op: "unknown", anchor: "1#A", body: [] }],
340
- [{ op: "delete", anchor: `1#${anchorHash}`, body: [] }],
341
- "bad",
342
- ]) {
343
- await assert.rejects(
344
- callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), { path: "unused.txt", edits }),
345
- (error: unknown) => {
346
- const result = argumentError(error);
347
- assert.equal(result.issues.length, 1);
348
- assert.doesNotMatch(result.issues[0].reason, /empty|hash length mismatch/);
349
- return true;
350
- },
351
- );
352
- }
353
- });
354
-
355
- test("multiple required fields are missing → report every missing field", async () => {
356
- await assert.rejects(
357
- callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
358
- path: "unused.txt",
359
- edits: [{ op: "replace" }],
360
- }),
361
- (error: unknown) => {
362
- const result = argumentError(error);
363
- assert.deepEqual(
364
- new Set(result.issues.map((issue) => issue.field)),
365
- new Set(["edits[0].anchor", "edits[0].body"]),
366
- );
367
- assert.ok(result.issues.every((issue) => /required/.test(issue.reason)));
368
- assert.equal(result.schemaLimited, undefined);
369
- return true;
370
- },
371
- );
372
- });
373
-
374
456
  test("unknown field names contain punctuation, numeric keys or newlines → quote property keys without treating them as array indices", async () => {
375
457
  for (const key of ["odd.\nfield/~", "0", "01", "a/b", "a~b", 'quote"field']) {
376
458
  await assert.rejects(
@@ -392,12 +474,12 @@ test("one field exhausts native diagnostics → label the limit and retain anoth
392
474
  await assert.rejects(
393
475
  callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
394
476
  path: "",
395
- edits: Array.from({ length: 30 }, () => ({ op: "unknown" })),
477
+ edits: Array.from({ length: 30 }, () => ({ action: "unknown" })),
396
478
  }),
397
479
  (error: unknown) => {
398
480
  const result = argumentError(error);
399
481
  assert.ok(result.issues.some((issue) => issue.field === "path"));
400
- assert.ok(result.issues.some((issue) => issue.field === "edits[0].op"));
482
+ assert.ok(result.issues.some((issue) => issue.field === "edits[0].action"));
401
483
  assert.equal(result.schemaLimited, true);
402
484
  return true;
403
485
  },
@@ -408,7 +490,7 @@ test("one field violates independent constraints → combine its reasons without
408
490
  await assert.rejects(
409
491
  callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
410
492
  path: "unused.txt",
411
- edits: [{ op: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#A` }],
493
+ edits: [{ action: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#A` }],
412
494
  }),
413
495
  (error: unknown) => {
414
496
  const result = argumentError(error);
@@ -431,179 +513,153 @@ test("one field violates independent constraints → combine its reasons without
431
513
  );
432
514
  });
433
515
 
434
- test("copy/move destination tokens → reject unsafe positions and wrong hash lengths before reading", async () => {
516
+ test("edit fields contain semantic errors → checks only fields accepted by their action", async (t) => {
435
517
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
436
- for (const op of ["copy", "move"]) {
437
- for (const side of ["before", "after"]) {
438
- for (const [token, reason] of [
439
- [`${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, /safe integer/],
440
- ["1#A", /has 1 hash characters/],
441
- ] as const) {
442
- await assert.rejects(
443
- callTool(tool, {
444
- path: "missing-copy-move.txt",
445
- edits: [{ op, anchor: `1#${anchorHash}`, [side]: token }],
446
- }),
447
- rejectsArgument(`edits[0].${side}`, reason),
518
+ for (const scenario of actionCases) {
519
+ const valid = {
520
+ action: scenario.action,
521
+ ...Object.fromEntries(scenario.required.map((field) => [field, fieldValues[field]])),
522
+ ...(scenario.transfer ? { before: fieldValues.before } : {}),
523
+ };
524
+ for (const field of editFields) {
525
+ const accepted = scenario.required.includes(field) || scenario.optional.includes(field);
526
+ const values: readonly (readonly [unknown, RegExp])[] =
527
+ field === "body"
528
+ ? [
529
+ [[], /empty/],
530
+ [["bad\0"], /NUL/],
531
+ [["bad\ud800"], /surrogate|UTF-8/],
532
+ ]
533
+ : [
534
+ [`${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, /safe integer/],
535
+ ["1#A", /hash characters/],
536
+ ];
537
+ for (const [value, reason] of values) {
538
+ await t.test(
539
+ `${scenario.action}/${field}/${reason.source} → ${accepted ? "reports value error" : "reports only forbidden field"}`,
540
+ async () => {
541
+ const edit = {
542
+ ...Object.fromEntries(
543
+ Object.entries(valid).filter(
544
+ ([key]) => !(scenario.transfer && field === "after" && key === "before"),
545
+ ),
546
+ ),
547
+ [field]: value,
548
+ };
549
+ await assert.rejects(
550
+ callTool(tool, { path: "unused.txt", edits: [edit] }),
551
+ (error: unknown) => {
552
+ const report = argumentError(error);
553
+ assert.equal(report.issues.length, 1, JSON.stringify(report));
554
+ const issue = report.issues[0];
555
+ assert.equal(
556
+ issue.field,
557
+ `edits[0].${field}${accepted && field === "body" && Array.isArray(value) && value.length ? "[0]" : ""}`,
558
+ );
559
+ if (accepted) {
560
+ assert.match(issue.reason, reason);
561
+ if (field === "body" && Array.isArray(value) && value.length === 0) {
562
+ assert.match(
563
+ issue.fix ?? "",
564
+ scenario.action === "replace"
565
+ ? /"action":"delete"/
566
+ : /supply at least one line/,
567
+ );
568
+ }
569
+ } else {
570
+ assert.equal(issue.reason, "is not allowed");
571
+ assert.match(issue.fix ?? "", new RegExp(`^"${scenario.action}":.*Takes `));
572
+ }
573
+ return true;
574
+ },
575
+ );
576
+ },
448
577
  );
449
578
  }
450
579
  }
451
580
  }
452
581
  });
453
582
 
454
- test("copy/move illegal argument shapes → reject before any file access", async () => {
455
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
456
- const anchor = `1#${anchorHash}`;
457
- for (const op of ["copy", "move"]) {
458
- for (const fields of [
459
- {},
460
- { before: anchor, after: anchor },
461
- { before: anchor, body: ["unused"] },
462
- { after: anchor, end: null },
463
- { before: 1 },
464
- { before: anchor, end: "1#IXXX" },
465
- ]) {
583
+ test("copy/move destination count and field errors coexist → retains object and field diagnostics", async (t) => {
584
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-object-diagnostics-"));
585
+ t.after(() => rm(cwd, { recursive: true, force: true }));
586
+ const tool = makeEditOverride(cwd, DEFAULT_CONFIG);
587
+ for (const scenario of [
588
+ {
589
+ edit: { action: "copy", anchor: "abc" },
590
+ field: "anchor",
591
+ reason: /must match pattern/,
592
+ fix: /LINE#HASH/,
593
+ },
594
+ {
595
+ edit: { action: "copy", anchor: `1#${anchorHash}`, extra: 1 },
596
+ field: "extra",
597
+ reason: /^is not allowed$/,
598
+ fix: /^Accepted fields:/,
599
+ },
600
+ {
601
+ edit: {
602
+ action: "move",
603
+ anchor: `1#${anchorHash}`,
604
+ end: "x",
605
+ before: `3#${anchorHash}`,
606
+ after: `4#${anchorHash}`,
607
+ },
608
+ field: "end",
609
+ reason: /must match pattern/,
610
+ fix: /LINE#HASH/,
611
+ },
612
+ ]) {
613
+ await t.test(`${scenario.edit.action}/${scenario.field} → retains both issues`, async () => {
466
614
  await assert.rejects(
467
- callTool(tool, { path: "missing-copy-move.txt", edits: [{ op, anchor, ...fields }] }),
615
+ callTool(tool, { path: "missing.txt", edits: [scenario.edit] }),
468
616
  (error: unknown) => {
469
- const result = argumentError(error);
470
- assert(result.issues.length > 0);
471
- if ("body" in fields)
472
- assert(result.issues.some((issue) => issue.field === "edits[0].body"));
473
- if ("end" in fields)
474
- assert(result.issues.some((issue) => issue.field === "edits[0].end"));
475
- if (fields.before === 1)
476
- assert(result.issues.some((issue) => issue.field === "edits[0].before"));
617
+ const { issues } = argumentError(error);
618
+ assert.deepEqual(
619
+ issues.map((issue) => issue.field).sort(),
620
+ ["edits[0]", `edits[0].${scenario.field}`].sort(),
621
+ );
622
+ const item = issues.find((issue) => issue.field === "edits[0]");
623
+ assert.equal(item?.reason, "expected exactly one of: before, after");
624
+ assert.equal(item?.fix, undefined);
625
+ const field = issues.find((issue) => issue.field === `edits[0].${scenario.field}`);
626
+ assert.ok(field);
627
+ assert.match(field.reason, scenario.reason);
628
+ assert.match(field.fix ?? "", scenario.fix);
477
629
  return true;
478
630
  },
479
631
  );
480
- }
632
+ });
481
633
  }
482
634
  });
483
635
 
484
- const exactlyOneDestination = /expected exactly one of: before, after/;
485
-
486
- for (const op of ["copy", "move"] as const) {
487
- test(`${op} without a destination → one exactly-one issue without a description fix`, async () => {
488
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
489
- await assert.rejects(
490
- callTool(tool, {
491
- path: "unused.txt",
492
- edits: [{ op, anchor: `1#${anchorHash}` }],
493
- }),
494
- (error: unknown) => {
495
- const result = argumentError(error);
496
- assert.equal(result.issues.length, 1);
497
- assert.equal(result.issues[0].field, "edits[0]");
498
- assert.match(result.issues[0].reason, exactlyOneDestination);
499
- assert.equal(result.issues[0].fix, undefined);
500
- assert.equal(result.schemaLimited, undefined);
501
- return true;
502
- },
503
- );
504
- });
505
-
506
- test(`${op} with both destinations → the same single exactly-one issue, no not-allowed pair`, async () => {
507
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
508
- await assert.rejects(
509
- callTool(tool, {
510
- path: "unused.txt",
511
- edits: [
512
- { op, anchor: `1#${anchorHash}`, before: `2#${anchorHash}`, after: `3#${anchorHash}` },
513
- ],
514
- }),
515
- (error: unknown) => {
516
- const result = argumentError(error);
517
- assert.equal(result.issues.length, 1);
518
- assert.equal(result.issues[0].field, "edits[0]");
519
- assert.match(result.issues[0].reason, exactlyOneDestination);
520
- assert.equal(result.schemaLimited, undefined);
521
- return true;
522
- },
523
- );
524
- });
525
- }
526
-
527
- test("mixed copy and move batch → every operation keeps its exactly-one and unknown-field issues", async () => {
636
+ test("copy/move has zero or two destinations → reports one exactly-one issue without a fix", async (t) => {
528
637
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
529
- await assert.rejects(
530
- callTool(tool, {
531
- path: "unused.txt",
532
- edits: [
533
- { op: "copy", anchor: `1#${anchorHash}`, start: { x: 1 }, to: `2#${anchorHash}` },
534
- { op: "move", anchor: `3#${anchorHash}` },
535
- ],
536
- }),
537
- (error: unknown) => {
538
- const result = argumentError(error);
539
- assert.deepEqual(
540
- new Set(result.issues.map((issue) => issue.field)),
541
- new Set(["edits[0]", "edits[0].start", "edits[0].to", "edits[1]"]),
542
- );
543
- for (const field of ["edits[0]", "edits[1]"])
544
- assert.match(
545
- result.issues.find((issue) => issue.field === field)?.reason ?? "",
546
- exactlyOneDestination,
547
- );
548
- for (const field of ["edits[0].start", "edits[0].to"])
549
- assert.match(
550
- result.issues.find((issue) => issue.field === field)?.reason ?? "",
551
- /not allowed/,
552
- );
553
- assert.equal(result.schemaLimited, undefined);
554
- return true;
555
- },
556
- );
557
- });
558
-
559
- for (const op of ["copy", "move"] as const) {
560
- test(`${op} with both destinations and a wrong before hash → keeps the hash-length issue beside exactly-one`, async () => {
561
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
562
- const shortHash = `2#${"A".repeat(DEFAULT_CONFIG.hashLen - 1)}`;
563
- await assert.rejects(
564
- callTool(tool, {
565
- path: "unused.txt",
566
- edits: [{ op, anchor: `1#${anchorHash}`, before: shortHash, after: `3#${anchorHash}` }],
567
- }),
568
- (error: unknown) => {
569
- const result = argumentError(error);
570
- const exactly = result.issues.filter((issue) => issue.field === "edits[0]");
571
- assert.equal(exactly.length, 1);
572
- assert.match(exactly[0].reason, exactlyOneDestination);
573
- const hashIssue = result.issues.find((issue) => issue.field === "edits[0].before");
574
- assert.ok(hashIssue, JSON.stringify(result.issues));
575
- assert.match(hashIssue.reason, /hash characters/);
576
- assert.match(hashIssue.fix ?? "", /Read or grep/);
577
- assert.ok(!result.issues.some((issue) => issue.field === "edits[0].after"));
578
- return true;
579
- },
580
- );
581
- });
582
- }
583
-
584
- for (const op of ["copy", "move"] as const) {
585
- for (const side of ["before", "after"] as const) {
586
- test(`${op} with one ${side} destination and an unknown field → only the unknown field is reported`, async () => {
587
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
588
- await assert.rejects(
589
- callTool(tool, {
590
- path: "unused.txt",
591
- edits: [
592
- { op, anchor: `1#${anchorHash}`, [side]: `2#${anchorHash}`, to: `3#${anchorHash}` },
593
- ],
594
- }),
595
- (error: unknown) => {
596
- const result = argumentError(error);
597
- assert.equal(result.issues.length, 1);
598
- assert.equal(result.issues[0].field, "edits[0].to");
599
- assert.match(result.issues[0].reason, /not allowed/);
600
- assert.equal(result.schemaLimited, undefined);
601
- return true;
638
+ for (const action of ["copy", "move"]) {
639
+ for (const destinations of [{}, { before: fieldValues.before, after: fieldValues.after }]) {
640
+ await t.test(
641
+ `${action}/${Object.keys(destinations).length} destinations → reports the item`,
642
+ async () => {
643
+ await assert.rejects(
644
+ callTool(tool, {
645
+ path: "unused.txt",
646
+ edits: [{ action, anchor: fieldValues.anchor, ...destinations }],
647
+ }),
648
+ (error: unknown) => {
649
+ assert.deepEqual(argumentError(error).issues, [
650
+ {
651
+ field: "edits[0]",
652
+ reason: "expected exactly one of: before, after",
653
+ },
654
+ ]);
655
+ return true;
656
+ },
657
+ );
602
658
  },
603
659
  );
604
- });
660
+ }
605
661
  }
606
- }
662
+ });
607
663
 
608
664
  /** Tool schema properties, so expected fix text comes from the schema instead of the test. */
609
665
  interface SchemaNode {
@@ -659,27 +715,6 @@ test("missing required parameter → fix states the parameter's role from its sc
659
715
  inOrder(fix, ['"create"', create.description, '"overwrite"', overwrite.description]);
660
716
  },
661
717
  },
662
- {
663
- name: "edit op",
664
- tool: edit,
665
- args: { path: "unused.txt", edits: [{ anchor: `1#${anchorHash}`, body: ["text"] }] },
666
- field: "edits[0].op",
667
- verify: (fix: string) => {
668
- for (const op of [
669
- "replace",
670
- "delete",
671
- "insert_before",
672
- "insert_after",
673
- "copy",
674
- "move",
675
- "append",
676
- "prepend",
677
- ])
678
- assert.ok(fix.includes(`\"${op}\"`), `${op} missing from ${fix}`);
679
- assert.equal(fix.split('"copy"').length - 1, 1);
680
- assert.equal(fix.split('"move"').length - 1, 1);
681
- },
682
- },
683
718
  ] as const;
684
719
  for (const scenario of cases) {
685
720
  await assert.rejects(callTool(scenario.tool, scenario.args), (error: unknown) => {
@@ -698,7 +733,7 @@ test("missing required parameter → fix states the parameter's role from its sc
698
733
  test("two operations miss the same required field → the shared fix appears once", async () => {
699
734
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
700
735
  await assert.rejects(
701
- callTool(tool, { path: "unused.txt", edits: [{ op: "replace" }, { op: "replace" }] }),
736
+ callTool(tool, { path: "unused.txt", edits: [{ action: "replace" }, { action: "replace" }] }),
702
737
  (error: unknown) => {
703
738
  const result = argumentError(error);
704
739
  const anchors = result.issues.filter((issue) => issue.field.endsWith(".anchor"));
@@ -706,13 +741,7 @@ test("two operations miss the same required field → the shared fix appears onc
706
741
  assert.equal(anchors.filter((issue) => issue.fix).length, 1);
707
742
  const fixes = result.issues.flatMap((issue) => (issue.fix ? [issue.fix] : []));
708
743
  assert.equal(new Set(fixes).size, fixes.length, JSON.stringify(fixes));
709
- const anchorDescriptions = new Set(
710
- (schemaProperties(tool).edits?.items?.anyOf ?? []).flatMap((branch) =>
711
- branch.properties?.anchor ? [branch.properties.anchor.description] : [],
712
- ),
713
- );
714
- assert.equal(anchorDescriptions.size, 1);
715
- const description = [...anchorDescriptions][0];
744
+ const description = schemaProperties(tool).edits?.items?.properties?.anchor?.description;
716
745
  assert.ok(description);
717
746
  assert.ok(fixes.includes(description));
718
747
  return true;
@@ -739,66 +768,30 @@ test("invalid enum value → the reason carries no description fix", async () =>
739
768
  );
740
769
  });
741
770
 
742
- const branchWithOp = (tool: { readonly parameters: unknown }, op: string): SchemaNode => {
743
- const branch = (schemaProperties(tool).edits?.items?.anyOf ?? []).find((candidate) => {
744
- const opSchema = candidate.properties?.op;
745
- return [opSchema?.const, ...(opSchema?.anyOf ?? []).map((option) => option.const)].includes(op);
746
- });
747
- assert.ok(branch, `no edit branch for op ${op}`);
748
- return branch;
749
- };
750
-
751
- const acceptedFields = (branch: SchemaNode): string =>
752
- `Accepted fields: ${Object.keys(branch.properties ?? {}).join(", ")}.`;
753
-
754
- const opExplanation = (branch: SchemaNode): string => {
755
- const options = branch.properties?.op?.anyOf ?? [{ const: branch.properties?.op?.const }];
756
- return `${options.map((option) => JSON.stringify(option.const)).join(" or ")}: ${branch.properties?.op?.description}`;
757
- };
771
+ const acceptedFields = (shape: SchemaNode): string =>
772
+ `Accepted fields: ${Object.keys(shape.properties ?? {}).join(", ")}.`;
758
773
 
759
- test("extra field is not allowed → fix describes the selected shape from its schema", async () => {
774
+ test("unknown field is supplied → fix lists only the flat object's accepted fields", async () => {
760
775
  const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
761
776
  const grep = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
762
- const append = branchWithOp(edit, "append");
763
- const move = branchWithOp(edit, "move");
764
- const cases = [
777
+ for (const scenario of [
765
778
  {
766
- name: "tagged branch rejects another branch's field",
767
779
  tool: edit,
768
- args: {
769
- path: "unused.txt",
770
- edits: [{ op: "append", anchor: `1#${anchorHash}`, body: ["text"] }],
771
- },
772
- field: "edits[0].anchor",
773
- fix: `${opExplanation(append)} ${acceptedFields(append)}`,
780
+ args: { path: "unused.txt", edits: [{ action: "append", body: ["text"], op: "append" }] },
781
+ field: "edits[0].op",
782
+ fix: "Accepted fields: action, anchor, end, body, before, after.",
774
783
  },
775
784
  {
776
- name: "unknown top-level field",
777
785
  tool: grep,
778
- args: { path: "unused.txt", pattern: "text", literal: true, bogus: 1 },
786
+ args: { pattern: "text", literal: true, bogus: 1 },
779
787
  field: "bogus",
780
788
  fix: acceptedFields({ properties: schemaProperties(grep) }),
781
789
  },
782
- {
783
- name: "transfer branch selected by before",
784
- tool: edit,
785
- args: {
786
- path: "unused.txt",
787
- edits: [
788
- { op: "move", anchor: `1#${anchorHash}`, before: `2#${anchorHash}`, body: ["text"] },
789
- ],
790
- },
791
- field: "edits[0].body",
792
- fix: `${opExplanation(move)} ${acceptedFields(move)}`,
793
- },
794
- ] as const;
795
- for (const scenario of cases) {
790
+ ]) {
796
791
  await assert.rejects(callTool(scenario.tool, scenario.args), (error: unknown) => {
797
- const result = argumentError(error);
798
- const issue = result.issues.find((candidate) => candidate.field === scenario.field);
799
- assert.ok(issue, JSON.stringify(result.issues));
800
- assert.match(issue.reason, /is not allowed/);
801
- assert.equal(issue.fix, scenario.fix, JSON.stringify(result.issues));
792
+ assert.deepEqual(argumentError(error).issues, [
793
+ { field: scenario.field, reason: "is not allowed", fix: scenario.fix },
794
+ ]);
802
795
  return true;
803
796
  });
804
797
  }
@@ -806,20 +799,19 @@ test("extra field is not allowed → fix describes the selected shape from its s
806
799
 
807
800
  test("value mismatches the field pattern → fix states the field description from the schema", async () => {
808
801
  const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
809
- const append = branchWithOp(edit, "append");
810
- const replace = branchWithOp(edit, "replace");
802
+ const fields = schemaProperties(edit).edits?.items?.properties;
811
803
  const cases = [
812
804
  {
813
805
  name: "body element with a newline",
814
- args: { path: "unused.txt", edits: [{ op: "append", body: ["a\nb"] }] },
806
+ args: { path: "unused.txt", edits: [{ action: "append", body: ["a\nb"] }] },
815
807
  field: "edits[0].body[0]",
816
- fix: append.properties?.body?.description,
808
+ fix: fields?.body?.description,
817
809
  },
818
810
  {
819
811
  name: "anchor without the line-hash shape",
820
- args: { path: "unused.txt", edits: [{ op: "replace", anchor: "abc", body: ["text"] }] },
812
+ args: { path: "unused.txt", edits: [{ action: "replace", anchor: "abc", body: ["text"] }] },
821
813
  field: "edits[0].anchor",
822
- fix: replace.properties?.anchor?.description,
814
+ fix: fields?.anchor?.description,
823
815
  },
824
816
  ] as const;
825
817
  for (const scenario of cases) {
@@ -839,7 +831,7 @@ test("two unknown fields in one object → the shared fix appears once", async (
839
831
  await assert.rejects(
840
832
  callTool(edit, {
841
833
  path: "unused.txt",
842
- edits: [{ op: "append", body: ["text"], zzz: 1, yyy: 2 }],
834
+ edits: [{ action: "append", body: ["text"], zzz: 1, yyy: 2 }],
843
835
  }),
844
836
  (error: unknown) => {
845
837
  const result = argumentError(error);