@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -9
  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.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import fs, { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { syncBuiltinESMExports } from "node:module";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { test } from "node:test";
@@ -15,6 +16,8 @@ import { argumentError, rejectsArgument } from "./argument-error.testing.ts";
15
16
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
17
  import { reportOf } from "./report.ts";
17
18
  import { createAnchorFormatter } from "./anchor-format.ts";
19
+ import { computeLineHash } from "../core/hash.ts";
20
+ import { grepCounts } from "./grep-output.testing.ts";
18
21
 
19
22
  const invalidCommand = { command: "", timeout: 0 };
20
23
  const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
@@ -43,6 +46,8 @@ const cases = [
43
46
  { action: "append", body: ["bad\0", "bad\ud800"] },
44
47
  { action: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, end: "1#A" },
45
48
  { action: "append", body: [] },
49
+ { action: "replace", anchor: `3#${anchorHash}`, end: `1#${anchorHash}`, body: ["text"] },
50
+ { action: "delete", anchor: `4#${anchorHash}`, end: `2#${anchorHash}` },
46
51
  ],
47
52
  then_run: invalidCommand,
48
53
  },
@@ -53,9 +58,15 @@ const cases = [
53
58
  "edits[2].anchor",
54
59
  "edits[2].end",
55
60
  "edits[3].body",
61
+ "edits[4].end",
62
+ "edits[5].end",
56
63
  "then_run.command",
57
64
  "then_run.timeout",
58
65
  ],
66
+ reasons: [
67
+ { field: "edits[4].end", reason: /line 1 is before anchor line 3/ },
68
+ { field: "edits[5].end", reason: /line 2 is before anchor line 4/ },
69
+ ],
59
70
  },
60
71
  {
61
72
  name: "replace",
@@ -101,14 +112,29 @@ for (const scenario of cases) {
101
112
  const tool = scenario.make(cwd, fusion);
102
113
  const args: unknown = JSON.parse(JSON.stringify({ path, ...scenario.args, unexpected: true }));
103
114
  const snapshot = structuredClone(args);
104
- await assert.rejects(callTool(tool, args), (error: unknown) => {
105
- const result = argumentError(error);
106
- assert.deepEqual(
107
- new Set(result.issues.map((issue) => issue.field)),
108
- new Set([...scenario.fields, "unexpected"]),
109
- );
110
- return true;
111
- });
115
+ const open = t.mock.method(fs, "open");
116
+ syncBuiltinESMExports();
117
+ try {
118
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
119
+ const result = argumentError(error);
120
+ assert.deepEqual(
121
+ new Set(result.issues.map((issue) => issue.field)),
122
+ new Set([...scenario.fields, "unexpected"]),
123
+ );
124
+ if ("reasons" in scenario) {
125
+ for (const expected of scenario.reasons) {
126
+ const issue = result.issues.find((issue) => issue.field === expected.field);
127
+ assert.ok(issue);
128
+ assert.match(issue.reason, expected.reason);
129
+ }
130
+ }
131
+ return true;
132
+ });
133
+ assert.equal(open.mock.callCount(), 0);
134
+ } finally {
135
+ t.mock.restoreAll();
136
+ syncBuiltinESMExports();
137
+ }
112
138
  assert.deepEqual(args, snapshot);
113
139
  assert.equal(await readFile(path, "utf8"), original);
114
140
  assert.equal(commandRuns, 0);
@@ -159,20 +185,17 @@ test("grep and replace flags → accept V8 modes and reject invalid flags before
159
185
  }
160
186
  });
161
187
 
162
- const editFields = ["anchor", "end", "body", "before", "after"] as const;
188
+ const editFields = ["anchor", "end", "body"] as const;
163
189
  type EditField = (typeof editFields)[number];
164
190
  const fieldValues = {
165
191
  anchor: `1#${anchorHash}`,
166
192
  end: `2#${anchorHash}`,
167
193
  body: ["text"],
168
- before: `3#${anchorHash}`,
169
- after: `3#${anchorHash}`,
170
194
  };
171
195
  const actionCases: readonly {
172
196
  action: string;
173
197
  required: readonly EditField[];
174
198
  optional: readonly EditField[];
175
- transfer?: boolean;
176
199
  expected: string;
177
200
  }[] = [
178
201
  {
@@ -194,20 +217,6 @@ const actionCases: readonly {
194
217
  optional: [],
195
218
  expected: "text\nalpha\nbeta\ngamma\n",
196
219
  },
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
220
  { action: "append", required: ["body"], optional: [], expected: "alpha\nbeta\ngamma\ntext\n" },
212
221
  { action: "prepend", required: ["body"], optional: [], expected: "text\nalpha\nbeta\ngamma\n" },
213
222
  ];
@@ -222,7 +231,6 @@ for (const scenario of actionCases) {
222
231
  const valid = {
223
232
  action: scenario.action,
224
233
  ...Object.fromEntries(scenario.required.map((field) => [field, fieldValues[field]])),
225
- ...(scenario.transfer ? { before: fieldValues.before } : {}),
226
234
  };
227
235
  for (const field of scenario.required) {
228
236
  for (const value of [undefined, null]) {
@@ -277,7 +285,10 @@ for (const scenario of actionCases) {
277
285
  test("edit action is missing or invalid → reports choices without guessing field permissions", async () => {
278
286
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
279
287
  const choices = schemaProperties(tool).edits?.items?.properties?.action?.anyOf ?? [];
280
- assert.equal(choices.length, actionCases.length);
288
+ assert.deepEqual(
289
+ choices.map((choice) => choice.const),
290
+ actionCases.map(({ action }) => action),
291
+ );
281
292
  for (const action of [undefined, "unknown", null, 42, {}]) {
282
293
  await assert.rejects(
283
294
  callTool(tool, {
@@ -324,46 +335,70 @@ test("optional edit fields and then_run are null with Fusion → publishes bytes
324
335
  return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
325
336
  });
326
337
  const tool = makeEditOverride(cwd, DEFAULT_CONFIG, fusion);
327
- const anchors = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
328
338
  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
- }
339
+ await t.test(`${scenario.action} → accepts null optional fields`, async () => {
340
+ await writeFile(path, "alpha\nbeta\ngamma\n");
341
+ const edit = {
342
+ action: scenario.action,
343
+ ...Object.fromEntries(editFields.map((field) => [field, null])),
344
+ ...Object.fromEntries(
345
+ scenario.required.map((field) => [
346
+ field,
347
+ field === "body" ? ["text"] : token(1, "alpha"),
348
+ ]),
349
+ ),
350
+ };
351
+ const args = { path, edits: [edit], then_run: null };
352
+ const snapshot = structuredClone(args);
353
+ const result = await callTool(tool, args);
354
+ assert.equal(result.isError, undefined);
355
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
356
+ assert.equal(reportOf(result, "edit")?.then_run, undefined);
357
+ assert.deepEqual(await readFile(path), Buffer.from(scenario.expected));
358
+ assert.deepEqual(args, snapshot);
359
+ });
363
360
  }
364
361
  assert.equal(commandRuns, 0);
365
362
  });
366
363
 
364
+ test("null optional fields → grep applies defaults without filename filters", async (t) => {
365
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-grep-null-"));
366
+ t.after(() => rm(cwd, { recursive: true, force: true }));
367
+ const path = join(cwd, "target.txt");
368
+ const config = DEFAULT_CONFIG;
369
+ await writeFile(path, "x\n".repeat(config.grep.defaultLimit + 1));
370
+ const rgCalls: (readonly string[])[] = [];
371
+ const discover = async (
372
+ args: readonly string[],
373
+ onPath: (path: string) => boolean | Promise<boolean>,
374
+ ) => {
375
+ rgCalls.push(args);
376
+ await onPath(path);
377
+ return { code: 0, stderr: "", stopped: false };
378
+ };
379
+ const tool = makeGrepOverrideWithBackend(cwd, config, {
380
+ runRgPaths: (args, _signal, onPath) => discover(args, onPath),
381
+ runRgLines: (args, _signal, _maxLines, onFile) =>
382
+ discover(args, (file) => onFile(file, undefined)),
383
+ });
384
+ const result = await callTool(tool, {
385
+ pattern: "x",
386
+ literal: true,
387
+ glob: null,
388
+ limit: null,
389
+ context: null,
390
+ });
391
+ assert.equal(result.isError, undefined);
392
+ assert.equal(grepCounts(result).matches, config.grep.defaultLimit);
393
+ assert.equal(reportOf(result, "grep")?.matchLimit, config.grep.defaultLimit);
394
+ assert.ok(rgCalls.length > 0);
395
+ for (const args of rgCalls) {
396
+ const globs = args.flatMap((arg, index) => (arg === "--glob" ? [args[index + 1]] : []));
397
+ // The built-in .git exclusion remains; null adds no filename filter.
398
+ assert.deepEqual(globs, ["!.git"]);
399
+ }
400
+ });
401
+
367
402
  test("edit batch has 64 or 65 operations → publishes the maximum or rejects the oversized batch unchanged", async (t) => {
368
403
  const cwd = await mkdtemp(join(tmpdir(), "hashline-edit-limit-"));
369
404
  t.after(() => rm(cwd, { recursive: true, force: true }));
@@ -374,7 +409,6 @@ test("edit batch has 64 or 65 operations → publishes the maximum or rejects th
374
409
  assert.equal(maxEdits, 64);
375
410
  const lines = Array.from({ length: maxEdits + 2 }, (_, i) => `line ${i + 1}`);
376
411
  const original = Buffer.from(`${lines.join("\n")}\n`);
377
- const anchors = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
378
412
  for (const count of [maxEdits, maxEdits + 1]) {
379
413
  await t.test(
380
414
  `${count} edits → ${count === maxEdits ? "publishes distinct deletions" : `rejects edits above max${maxEdits}`}`,
@@ -384,7 +418,7 @@ test("edit batch has 64 or 65 operations → publishes the maximum or rejects th
384
418
  path,
385
419
  edits: lines
386
420
  .slice(0, count)
387
- .map((line, i) => ({ action: "delete", anchor: anchors.token(i + 1, line) })),
421
+ .map((line, i) => ({ action: "delete", anchor: token(i + 1, line) })),
388
422
  };
389
423
  const snapshot = structuredClone(args);
390
424
  if (count === maxEdits) {
@@ -519,7 +553,6 @@ test("edit fields contain semantic errors → checks only fields accepted by the
519
553
  const valid = {
520
554
  action: scenario.action,
521
555
  ...Object.fromEntries(scenario.required.map((field) => [field, fieldValues[field]])),
522
- ...(scenario.transfer ? { before: fieldValues.before } : {}),
523
556
  };
524
557
  for (const field of editFields) {
525
558
  const accepted = scenario.required.includes(field) || scenario.optional.includes(field);
@@ -538,14 +571,7 @@ test("edit fields contain semantic errors → checks only fields accepted by the
538
571
  await t.test(
539
572
  `${scenario.action}/${field}/${reason.source} → ${accepted ? "reports value error" : "reports only forbidden field"}`,
540
573
  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
- };
574
+ const edit = { ...valid, [field]: value };
549
575
  await assert.rejects(
550
576
  callTool(tool, { path: "unused.txt", edits: [edit] }),
551
577
  (error: unknown) => {
@@ -580,87 +606,6 @@ test("edit fields contain semantic errors → checks only fields accepted by the
580
606
  }
581
607
  });
582
608
 
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 () => {
614
- await assert.rejects(
615
- callTool(tool, { path: "missing.txt", edits: [scenario.edit] }),
616
- (error: unknown) => {
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);
629
- return true;
630
- },
631
- );
632
- });
633
- }
634
- });
635
-
636
- test("copy/move has zero or two destinations → reports one exactly-one issue without a fix", async (t) => {
637
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
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
- );
658
- },
659
- );
660
- }
661
- }
662
- });
663
-
664
609
  /** Tool schema properties, so expected fix text comes from the schema instead of the test. */
665
610
  interface SchemaNode {
666
611
  readonly description?: string;
@@ -779,7 +724,7 @@ test("unknown field is supplied → fix lists only the flat object's accepted fi
779
724
  tool: edit,
780
725
  args: { path: "unused.txt", edits: [{ action: "append", body: ["text"], op: "append" }] },
781
726
  field: "edits[0].op",
782
- fix: "Accepted fields: action, anchor, end, body, before, after.",
727
+ fix: "Accepted fields: action, anchor, end, body.",
783
728
  },
784
729
  {
785
730
  tool: grep,
@@ -857,3 +802,30 @@ test("value has the wrong type → the reason carries no fix", async () => {
857
802
  },
858
803
  );
859
804
  });
805
+
806
+ function token(line: number, content: string): string {
807
+ const hashLen = DEFAULT_CONFIG.hashLen;
808
+ return createAnchorFormatter(hashLen).reference(line, computeLineHash(line, content, hashLen));
809
+ }
810
+
811
+ test("20 unknown keys including a slash → bounded issues retain one accepted-fields fix", async () => {
812
+ const tool = makeReadOverride(process.cwd(), DEFAULT_CONFIG);
813
+ const keys = Array.from({ length: 20 }, (_, index) =>
814
+ index === 0 ? "unknown/key" : `unknown${index}`,
815
+ );
816
+ await assert.rejects(
817
+ callTool(tool, { path: "unused.txt", ...Object.fromEntries(keys.map((key) => [key, true])) }),
818
+ (error: unknown) => {
819
+ const result = argumentError(error);
820
+ assert.equal(result.schemaLimited, true);
821
+ assert.ok(result.issues.length >= 8);
822
+ assert.ok(result.issues.some((issue) => issue.field.includes("unknown/key")));
823
+ for (const issue of result.issues) {
824
+ assert.equal(issue.reason, "is not allowed");
825
+ }
826
+ assert.equal(result.issues[0].fix, acceptedFields({ properties: schemaProperties(tool) }));
827
+ assert.ok(result.issues.slice(1).every((issue) => issue.fix === undefined));
828
+ return true;
829
+ },
830
+ );
831
+ });
@@ -15,7 +15,7 @@ import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
15
15
 
16
16
  /** Report one semantic issue: what is wrong (a fact), and how to correct it when the fact alone does not say. */
17
17
  export type ReportArgumentIssue = (field: string, reason: string, fix?: string) => void;
18
- type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
18
+ export type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
19
19
 
20
20
  /** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
21
21
  export function argumentItems(value: unknown): readonly unknown[] {
@@ -82,18 +82,15 @@ export function createArgumentPreparer<T extends TObject>(
82
82
  check?.(checked, (field, reason, fix) =>
83
83
  issues.push(fix === undefined ? { field, reason } : { field, reason, fix }),
84
84
  );
85
+ // Keep Pi's preparation contract: the framework performs its own coercion next.
85
86
  if (schemaFailure === undefined && issues.length === 0) return args as Static<T>;
86
87
  const result = diagnoseArguments(parameters, checked, issues, schemaFailure !== undefined);
87
88
  const reported =
88
89
  result.issues.length > 0
89
90
  ? result.issues
90
91
  : [{ field: "$", reason: errorMessage(schemaFailure) }];
91
- if (schemaFailure !== undefined || result.issues.length > 0) {
92
- throw new Error(formatArgumentError(reported, result.limited, budgets()), {
93
- cause: schemaFailure,
94
- });
95
- }
96
- // Keep Pi's preparation contract: the framework performs its own coercion next.
97
- return args as Static<T>;
92
+ throw new Error(formatArgumentError(reported, result.limited, budgets()), {
93
+ cause: schemaFailure,
94
+ });
98
95
  };
99
96
  }
package/src/pi/budgets.ts CHANGED
@@ -3,7 +3,6 @@
3
3
  * The context window is a capacity hint, not a tokenizer or remaining-context counter.
4
4
  */
5
5
 
6
- const BYTES_PER_CONTEXT_TOKEN = 1;
7
6
  const BLOCK_SHARE = 4;
8
7
  const FIELD_SHARE = 4;
9
8
  const UTF16_PREVIEW_BYTES = 4;
@@ -16,6 +15,7 @@ const MIN_FIELD_BYTES = 128;
16
15
  export const MAX_CONTENT_KIB = 4096;
17
16
  const MAX_CONTENT_BYTES = MAX_CONTENT_KIB * 1024;
18
17
 
18
+ // Declared apart so Object.freeze keeps these as numbers rather than literal types.
19
19
  const fallbackBudgets = {
20
20
  readBytes: 256 * 1024,
21
21
  grepBytes: 50 * 1024,
@@ -32,7 +32,8 @@ export function outputBudgetsFor(contextWindow: number | undefined): OutputBudge
32
32
  if (contextWindow === undefined || !Number.isSafeInteger(contextWindow) || contextWindow <= 0) {
33
33
  return DEFAULT_OUTPUT_BUDGETS;
34
34
  }
35
- const contentBytes = Math.min(contextWindow * BYTES_PER_CONTEXT_TOKEN, MAX_CONTENT_BYTES);
35
+ // One byte per declared context token.
36
+ const contentBytes = Math.min(contextWindow, MAX_CONTENT_BYTES);
36
37
  const blockBytes = Math.max(MIN_BLOCK_BYTES, Math.floor(contentBytes / BLOCK_SHARE));
37
38
  const fieldBytes = Math.max(MIN_FIELD_BYTES, Math.floor(blockBytes / FIELD_SHARE));
38
39
  return Object.freeze({
@@ -49,7 +50,7 @@ export const defaultOutputBudgets: OutputBudgetProvider = () => DEFAULT_OUTPUT_B
49
50
 
50
51
  const MIB = 1024 * 1024;
51
52
 
52
- /** Size wording for every model-facing limit: whole MiB as `256 MiB`, otherwise `16 KiB`. */
53
+ /** Size wording for every model-facing limit: whole MiB as `256 MiB`, otherwise `195.3 KiB`. */
53
54
  export function formatByteSize(bytes: number): string {
54
- return bytes % MIB === 0 ? `${bytes / MIB} MiB` : `${bytes / 1024} KiB`;
55
+ return bytes % MIB === 0 ? `${bytes / MIB} MiB` : `${Number((bytes / 1024).toFixed(1))} KiB`;
55
56
  }
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_MAX_LINES } from "@earendil-works/pi-coding-agent";
1
2
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
@@ -34,7 +35,7 @@ test("defaults come from the settings schema", () => {
34
35
  actionFusion: true,
35
36
  hashLen: 4,
36
37
  shiftRadius: 15,
37
- read: { defaultLimit: 500, maxKiB: undefined },
38
+ read: { defaultLimit: DEFAULT_MAX_LINES, maxKiB: undefined },
38
39
  grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 100, defaultContext: 0 },
39
40
  replace: { regexTimeoutMs: 5_000 },
40
41
  });
@@ -114,7 +115,9 @@ test("project settings replace global groups while absent project settings use g
114
115
  join(agentDir, "settings.json"),
115
116
  JSON.stringify({ hashlineEdit: globalConfig }),
116
117
  );
117
- assert.deepEqual(loadConfig(), globalConfig);
118
+ const withoutSettings = join(root, "without-settings");
119
+ await mkdir(withoutSettings);
120
+ assert.deepEqual(loadConfig(withoutSettings), globalConfig);
118
121
  assert.deepEqual(loadConfig(root), globalConfig);
119
122
  for (const settings of [{}, null, [], 42, "settings"]) {
120
123
  await write(settings);
package/src/pi/config.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * @module pi-hashline-edit/pi
7
7
  */
8
8
 
9
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
9
+ import { DEFAULT_MAX_LINES, getAgentDir } from "@earendil-works/pi-coding-agent";
10
10
  import * as fs from "node:fs";
11
11
  import * as path from "node:path";
12
12
  import { Type, type Static, type TSchema } from "typebox";
@@ -24,7 +24,6 @@ function integerSetting(
24
24
  }
25
25
 
26
26
  // The floor exceeds measured worker startup+handshake on slower Windows hosts.
27
- // README's regex timeout settings link to this shared definition.
28
27
  const regexTimeoutSetting = integerSetting(
29
28
  integerRange(3_000, 300_000),
30
29
  5_000,
@@ -55,7 +54,7 @@ const configSchema = Type.Object({
55
54
  read: Type.Object({
56
55
  defaultLimit: integerSetting(
57
56
  POSITIVE_SAFE_INTEGER,
58
- 500,
57
+ DEFAULT_MAX_LINES,
59
58
  "Lines returned when limit is omitted.",
60
59
  ),
61
60
  maxKiB: Type.Optional(
@@ -113,7 +112,6 @@ export const DEFAULT_CONFIG: HashlineEditConfig = resolveSetting(configSchema, {
113
112
  /** Parse JSON directly without stripping comments (standard JSON forbids comments; on error fall back to default). */
114
113
  function readSettings(filePath: string): Record<string, unknown> {
115
114
  try {
116
- if (!fs.existsSync(filePath)) return {};
117
115
  return asRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
118
116
  } catch {
119
117
  return {};
@@ -124,9 +122,9 @@ function readSettings(filePath: string): Record<string, unknown> {
124
122
  * Load config. The `hashlineEdit` in project `cwd/.pi/settings.json` replaces
125
123
  * the global one wholesale; missing or invalid settings use their defaults.
126
124
  */
127
- export function loadConfig(cwd?: string): HashlineEditConfig {
125
+ export function loadConfig(cwd: string): HashlineEditConfig {
128
126
  const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
129
- const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
127
+ const projectSettings = readSettings(path.join(cwd, ".pi", "settings.json"));
130
128
  // Any project value replaces the global one, even null or an invalid value, which yields defaults.
131
129
  const settings = Object.hasOwn(projectSettings, "hashlineEdit")
132
130
  ? projectSettings
@@ -1,5 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
+ import childProcess from "node:child_process";
4
+ import { syncBuiltinESMExports } from "node:module";
3
5
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
4
6
  import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
5
7
  import { assembleGrepOutput } from "./grep-output.ts";
@@ -53,6 +55,7 @@ test("search warning aggregation retains the final cause and labels truncation",
53
55
  files: 1,
54
56
  },
55
57
  warnings: [diagnostic(DEFAULT_OUTPUT_BUDGETS.fieldBytes)],
58
+ searchFacts: {},
56
59
  outputMode: "content",
57
60
  matchLimitReached: false,
58
61
  effectiveLimit: 100,
@@ -64,13 +67,21 @@ test("search warning aggregation retains the final cause and labels truncation",
64
67
  });
65
68
 
66
69
  test("stderr overflow → UTF-8 opening and final cause survive", async (t) => {
70
+ const spawn = childProcess.spawn;
71
+ t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) =>
72
+ spawn(process.execPath, args[1] ?? [], args[2]),
73
+ );
74
+ syncBuiltinESMExports();
75
+ t.after(() => {
76
+ t.mock.restoreAll();
77
+ syncBuiltinESMExports();
78
+ });
67
79
  const directory = await mkdtemp(join(tmpdir(), "hl-rg-stderr-"));
68
80
  t.after(() => rm(directory, { recursive: true, force: true }));
69
81
  const path = join(directory, "stderr.txt");
70
82
  for (const source of ["权限不足🙂\n", diagnostic(MAX_RG_STDERR_BYTES)]) {
71
83
  await writeFile(path, source);
72
84
  const result = await runRgPaths(
73
- process.execPath,
74
85
  [
75
86
  "--input-type=module",
76
87
  "--eval",
@@ -17,12 +17,11 @@ export class DiagnosticBuffer {
17
17
  private head = "";
18
18
  private tail = "";
19
19
  private truncated = false;
20
+ private readonly maxBytes: number;
20
21
  private readonly notice: string;
21
22
  private readonly headBytes: number;
22
23
  private readonly tailBytes: number;
23
24
 
24
- private readonly maxBytes: number;
25
-
26
25
  constructor(maxBytes: number) {
27
26
  this.maxBytes = maxBytes;
28
27
  this.notice = `\n[Diagnostics truncated (${formatByteSize(maxBytes)} limit); middle omitted.]\n`;
@@ -37,7 +37,6 @@ test("macOS attempts directory sync, tolerates unsupported operations, and prese
37
37
  (error: unknown) =>
38
38
  error instanceof FileMutationError &&
39
39
  error.publication === "PUBLISHED" &&
40
- error.stage === "post_process" &&
41
40
  error.cause instanceof Error &&
42
41
  "code" in error.cause &&
43
42
  error.cause.code === "EIO",