@criogaid/pi-hashline-edit 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +4 -3
  2. package/README.zh-CN.md +4 -3
  3. package/package.json +1 -1
  4. package/src/core/apply.test.ts +2 -2
  5. package/src/core/apply.ts +2 -2
  6. package/src/core/character-set.test.ts +2 -3
  7. package/src/core/character-set.ts +1 -1
  8. package/src/core/ranges.test.ts +2 -1
  9. package/src/core/ranges.ts +1 -1
  10. package/src/core/types.ts +1 -1
  11. package/src/index.ts +8 -8
  12. package/src/integration/config-registration.test.ts +8 -10
  13. package/src/integration/fusion-dispatch.test.ts +2 -2
  14. package/src/integration/grep-errors.test.ts +3 -3
  15. package/src/integration/grep-flags.test.ts +5 -5
  16. package/src/integration/grep-js-completeness.test.ts +12 -11
  17. package/src/integration/grep-line-candidates.test.ts +3 -2
  18. package/src/integration/grep-matrix.test.ts +5 -4
  19. package/src/integration/grep-order.test.ts +4 -4
  20. package/src/integration/grep-path-matrix.test.ts +5 -4
  21. package/src/integration/grep-prefilter-coverage.test.ts +4 -3
  22. package/src/integration/grep-process-limits.test.ts +2 -4
  23. package/src/integration/grep-regex.test.ts +10 -10
  24. package/src/integration/grep-rg.test.ts +50 -48
  25. package/src/integration/grep-scan-budget.test.ts +8 -8
  26. package/src/integration/grep-translation.test.ts +8 -7
  27. package/src/integration/large-text.test.ts +5 -5
  28. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  29. package/src/integration/mutation-file-types.testing.ts +4 -4
  30. package/src/integration/npm-package.testing.ts +3 -3
  31. package/src/integration/publication-read-changes.test.ts +54 -54
  32. package/src/integration/read-changes.test.ts +4 -4
  33. package/src/integration/replace-worker-boundary.test.ts +1 -1
  34. package/src/integration/report-replay.test.ts +5 -6
  35. package/src/integration/utf8-errors.test.ts +4 -4
  36. package/src/pi/AGENTS.md +6 -5
  37. package/src/pi/action-fusion.test.ts +125 -105
  38. package/src/pi/action-fusion.testing.ts +38 -0
  39. package/src/pi/action-fusion.ts +9 -21
  40. package/src/pi/argument-diagnostics.ts +4 -3
  41. package/src/pi/argument-format.test.ts +19 -18
  42. package/src/pi/argument-validation.test.ts +218 -139
  43. package/src/pi/budgets.ts +1 -4
  44. package/src/pi/codemode.test.ts +7 -2
  45. package/src/pi/config.test.ts +2 -1
  46. package/src/pi/config.ts +8 -3
  47. package/src/pi/diagnostic-buffer.test.ts +23 -13
  48. package/src/pi/edit-tool.ts +47 -62
  49. package/src/pi/error-text.ts +7 -2
  50. package/src/pi/execute.test.ts +174 -157
  51. package/src/pi/failure-context.test.ts +4 -3
  52. package/src/pi/failure-context.ts +1 -1
  53. package/src/pi/failure-path.test.ts +37 -37
  54. package/src/pi/file-commit.test.ts +47 -19
  55. package/src/pi/file-commit.ts +36 -9
  56. package/src/pi/fusion-card.test.ts +22 -21
  57. package/src/pi/grep-candidates.test.ts +18 -20
  58. package/src/pi/grep-candidates.ts +8 -13
  59. package/src/pi/grep-matrix.test.ts +3 -3
  60. package/src/pi/grep-order.test.ts +12 -11
  61. package/src/pi/grep-output.ts +36 -15
  62. package/src/pi/grep-reread.ts +7 -2
  63. package/src/pi/grep-rg.testing.ts +70 -0
  64. package/src/pi/grep-scope.ts +4 -4
  65. package/src/pi/grep-search.ts +8 -11
  66. package/src/pi/grep-tool.ts +23 -39
  67. package/src/pi/grep.test.ts +102 -116
  68. package/src/pi/model-budgets.test.ts +2 -1
  69. package/src/pi/mutation-outcome.testing.ts +0 -1
  70. package/src/pi/mutation-result.test.ts +8 -8
  71. package/src/pi/mutation-result.ts +1 -1
  72. package/src/pi/mutation-runner.ts +9 -5
  73. package/src/pi/output-budgets.test.ts +53 -31
  74. package/src/pi/pi.test.ts +18 -13
  75. package/src/pi/read-tool.ts +13 -18
  76. package/src/pi/read.test.ts +22 -41
  77. package/src/pi/registration.test.ts +25 -19
  78. package/src/pi/render.test.ts +51 -32
  79. package/src/pi/render.ts +7 -4
  80. package/src/pi/replace-regex.ts +1 -1
  81. package/src/pi/replace-tool.ts +6 -16
  82. package/src/pi/replace.test.ts +45 -34
  83. package/src/pi/report-failure.testing.ts +9 -1
  84. package/src/pi/report-schema.ts +205 -83
  85. package/src/pi/report.test.ts +66 -64
  86. package/src/pi/report.ts +23 -17
  87. package/src/pi/result-safety.test.ts +121 -100
  88. package/src/pi/rg-process.test.ts +2 -2
  89. package/src/pi/rg-process.ts +9 -15
  90. package/src/pi/schema.ts +23 -0
  91. package/src/pi/tool-factories.testing.ts +59 -0
  92. package/src/pi/write-tool.ts +9 -15
  93. package/src/pi/write.test.ts +30 -31
  94. package/src/testing/run-tests.ts +1 -1
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
1
2
  import { test } from "node:test";
2
3
  import assert from "node:assert/strict";
3
4
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
@@ -7,8 +8,8 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
9
  import { join } from "node:path";
9
10
  import { createActionFusionExecutor } from "./action-fusion.ts";
10
- import { makeWriteOverride } from "./write-tool.ts";
11
- import { makeReplaceTool } from "./replace-tool.ts";
11
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
12
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
12
13
  import type { SuccessReport } from "./report-schema.ts";
13
14
  import { callTool, createToolContext } from "./tool-call.testing.ts";
14
15
  import { reportOf } from "./report.ts";
@@ -30,20 +31,19 @@ test("command content includes images → report text joins only text blocks", a
30
31
  const dir = await mkdtemp(join(tmpdir(), "hashline-command-content-"));
31
32
  try {
32
33
  const path = join(dir, "file.txt");
33
- const fusion = createActionFusionExecutor(async () => ({
34
- status: "succeeded",
35
- result: {
34
+ const executeTool: SessionCommand = async () =>
35
+ commandCompletion({
36
36
  content: [
37
37
  { type: "text", text: "first" },
38
38
  { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
39
39
  { type: "text", text: "second" },
40
40
  ],
41
- },
42
- }));
41
+ });
42
+ const fusion = createActionFusionExecutor(() => {});
43
43
  const result = await callTool(
44
44
  makeWriteOverride(dir, fusion),
45
45
  { path, content: "saved\n", mode: "create", then_run: { command: "check" } },
46
- { ctx: await createToolContext(dir, t) },
46
+ { ctx: { ...(await createToolContext(dir, t)), executeTool } },
47
47
  );
48
48
  assert.equal(reportOf(result, "write")?.then_run?.output, "first\nsecond");
49
49
  assert.equal(await readFile(path, "utf8"), "saved\n");
@@ -48,7 +48,7 @@ export function generateMutationDetails(before: string, after: string) {
48
48
  /** The facts a mutation tool states about its own outcome. */
49
49
  export type MutationFacts<TTool extends MutationToolName = MutationToolName> = {
50
50
  [T in TTool]: SuccessFacts<T> & {
51
- [K in Exclude<"matches" | "created", keyof SuccessFacts<T>>]?: never;
51
+ [K in Exclude<"matches", keyof SuccessFacts<T>>]?: never;
52
52
  };
53
53
  }[TTool];
54
54
 
@@ -54,11 +54,17 @@ import {
54
54
  import { canonicalPath } from "./path.ts";
55
55
  import { throwIfCancelled } from "./error-text.ts";
56
56
  import { runTool } from "./report.ts";
57
- import type { OutputBudgetProvider, OutputBudgets } from "./budgets.ts";
57
+ import type { OutputBudgets } from "./budgets.ts";
58
+ import type { ToolEnvironment } from "./config.ts";
58
59
  import { STRICT_SAMPLING } from "./schema.ts";
59
60
 
60
61
  export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
61
62
 
63
+ /** A mutation tool's registration environment; fusion is undefined when Action Fusion is off. */
64
+ export interface MutationToolEnvironment extends ToolEnvironment {
65
+ readonly fusion: ActionFusionExecutor | undefined;
66
+ }
67
+
62
68
  /** Result details shared by the read-modify-write tools. */
63
69
  type TextMutationDetails = ReturnType<typeof generateMutationDetails>;
64
70
 
@@ -73,11 +79,9 @@ export interface MutationTarget {
73
79
  type MutationParams<P extends TProperties> = Static<TObject<P>> & { readonly path: string };
74
80
 
75
81
  /** What a mutation tool supplies to the shared definition; renderers stay with the tool. */
76
- interface MutationToolSpec<P extends TProperties, TDetails, TTool extends MutationToolName> {
82
+ interface MutationToolSpec<P extends TProperties, TDetails, TTool extends MutationToolName>
83
+ extends MutationToolEnvironment {
77
84
  readonly tool: TTool;
78
- readonly cwd: string;
79
- readonly fusion: ActionFusionExecutor | undefined;
80
- readonly budgets: OutputBudgetProvider;
81
85
  /** Parameters without then_run, which Action Fusion adds. */
82
86
  readonly schema: TObject<P>;
83
87
  readonly description: string;
@@ -1,3 +1,5 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { runRegexReplacements } from "./replace-regex.ts";
1
3
  import assert from "node:assert/strict";
2
4
  import { test } from "node:test";
3
5
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
@@ -11,15 +13,13 @@ import { openTestSession } from "../testing/session.testing.ts";
11
13
  import { createAnchorFormatter } from "./anchor-format.ts";
12
14
  import { formatArgumentError } from "./argument-error.ts";
13
15
  import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
14
- import { DEFAULT_CONFIG } from "./config.ts";
15
- import { makeEditOverride } from "./edit-tool.ts";
16
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
17
+ import { makeEditOverride } from "./tool-factories.testing.ts";
16
18
  import { describeEditFailure } from "./failure-context.ts";
17
- import { assembleGrepOutput } from "./grep-output.ts";
19
+ import { grepOutput } from "./grep-output.ts";
18
20
  import { registerModelBudgets } from "./model-budgets.ts";
19
21
  import { describeMutationFailure } from "./mutation-result.ts";
20
- import { decodeReport, reportOf } from "./report.ts";
21
- import { decodeWorkerReply } from "./replace-regex.ts";
22
- import { restoreWorkerError } from "./regex-worker-contract.ts";
22
+ import { reportOf } from "./report.ts";
23
23
  import { workerFailure } from "./report-cause.ts";
24
24
  import { callTool } from "./tool-call.testing.ts";
25
25
 
@@ -52,14 +52,14 @@ test("byte budget sizes include fractional KiB → round to one decimal and pres
52
52
 
53
53
  test("model budget grows → argument issues remain complete JSON with counted omissions", () => {
54
54
  const issues = Array.from({ length: 100 }, (_, index) => ({
55
- field: `edits[${index}].body`,
55
+ field: `steps[${index}].lines`,
56
56
  reason: "中文🙂".repeat(100),
57
57
  fix: "Supply a line.",
58
58
  }));
59
59
  const reports = [outputBudgetsFor(1), small, large].map((budget) => {
60
60
  const text = formatArgumentError(issues, false, budget);
61
61
  assert.ok(Buffer.byteLength(text) <= budget.blockBytes);
62
- const report = decodeReport(text, "edit");
62
+ const report = reportOf({ content: [{ type: "text", text }] }, "edit");
63
63
  assert.ok(report);
64
64
  assert.equal((report.issues?.length ?? 0) + (report.omittedIssues ?? 0), issues.length);
65
65
  return report;
@@ -99,23 +99,32 @@ test("model row allowance grows → anchor failures return complete observations
99
99
  }
100
100
  });
101
101
 
102
- test("model budget grows → grep payload and diagnostics use that call's allowances", () => {
103
- const payload = Array.from({ length: 3_000 }, () => "中文🙂".repeat(3)).join("\n");
102
+ test("model budget grows → grep payload and diagnostics use that call's allowances", async () => {
103
+ const paths = Array.from({ length: 3_000 }, () => "中文🙂".repeat(3));
104
+ const payload = paths.join("\n");
104
105
  const warning = "opening\n" + "中文🙂".repeat(800) + "\nfinal cause";
105
- const outputs = [small, large].map((budget) =>
106
- assembleGrepOutput({
107
- formatted: {
108
- blocks: [{ lines: payload.split("\n") }],
109
- matches: 3_000,
110
- files: 1,
111
- },
112
- warnings: [warning],
113
- searchFacts: {},
114
- outputMode: "content",
115
- matchLimitReached: false,
116
- effectiveLimit: 3_000,
117
- budget,
118
- }),
106
+ const outputs = await Promise.all(
107
+ [small, large].map((budget) =>
108
+ grepOutput({
109
+ cwd: process.cwd(),
110
+ anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen),
111
+ context: 0,
112
+ outputMode: "files",
113
+ search: {
114
+ files: paths.map((path) => ({
115
+ filePath: join(process.cwd(), path),
116
+ rows: [],
117
+ snapshot: { revision: "", validUtf8: true },
118
+ })),
119
+ scanLimitReached: false,
120
+ matchLimitReached: false,
121
+ },
122
+ warnings: [{ reason: warning }],
123
+ effectiveLimit: 3_000,
124
+ literalPipe: false,
125
+ budget,
126
+ }),
127
+ ),
119
128
  );
120
129
  assert.equal(outputs[0].facts.outputLimit, formatByteSize(small.grepBytes));
121
130
  assert.equal(outputs[1].payload, payload);
@@ -129,13 +138,26 @@ test("model budget grows → grep payload and diagnostics use that call's allowa
129
138
  }
130
139
  });
131
140
 
132
- test("worker error reaches the tool → text is bounded once using the selected model", () => {
141
+ test("worker error reaches the tool → text is bounded once using the selected model", async (t) => {
133
142
  const text = "中文🙂".repeat(800);
134
- const reply = decodeWorkerReply(
135
- workerFailure(new HashlineError("REGEX_WORKER_FAILED", text, { cause: new Error(text) })),
143
+ const reply = workerFailure(
144
+ new HashlineError("REGEX_WORKER_FAILED", text, { cause: new Error(text) }),
136
145
  );
137
- assert.ok(reply && "error" in reply);
138
- const error = restoreWorkerError(reply.error);
146
+ t.mock.method(Worker.prototype, "postMessage", function (this: Worker) {
147
+ queueMicrotask(() => this.emit("message", reply));
148
+ });
149
+ let error: unknown;
150
+ try {
151
+ await runRegexReplacements(
152
+ "source",
153
+ [{ find: "source", replace: "target", literal: false }],
154
+ 5_000,
155
+ undefined,
156
+ );
157
+ assert.fail("Worker failure must reject");
158
+ } catch (failure) {
159
+ error = failure;
160
+ }
139
161
  const reports = [small, large].map((budget) =>
140
162
  describeMutationFailure("replace", error, { budget }),
141
163
  );
@@ -171,7 +193,7 @@ test("model switches while a mutation waits → failure uses its starting budget
171
193
  try {
172
194
  const running = callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
173
195
  path,
174
- edits: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
196
+ steps: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
175
197
  });
176
198
  await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
177
199
  assert.equal(budgets().readBytes, large.readBytes);
@@ -182,7 +204,7 @@ test("model switches while a mutation waits → failure uses its starting budget
182
204
  const next = reportOf(
183
205
  await callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
184
206
  path,
185
- edits: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
207
+ steps: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
186
208
  }),
187
209
  "edit",
188
210
  );
package/src/pi/pi.test.ts CHANGED
@@ -4,16 +4,17 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
4
4
  import { tmpdir, homedir } from "node:os";
5
5
  import { computeLineHash } from "../core/hash.ts";
6
6
  import { createActionFusionExecutor } from "./action-fusion.ts";
7
- import { makeEditOverride } from "./edit-tool.ts";
8
- import { makeGrepOverride } from "./grep-tool.ts";
9
- import { makeReadOverride } from "./read-tool.ts";
10
- import { makeReplaceTool } from "./replace-tool.ts";
11
- import { makeWriteOverride } from "./write-tool.ts";
7
+ import { commandCompletion } from "./action-fusion.testing.ts";
8
+ import { makeEditOverride } from "./tool-factories.testing.ts";
9
+ import { makeGrepOverride } from "./tool-factories.testing.ts";
10
+ import { makeReadOverride } from "./tool-factories.testing.ts";
11
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
12
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
12
13
  import { canonicalPath } from "./path.ts";
13
14
  import { join, resolve } from "node:path";
14
15
  import { pathToFileURL } from "node:url";
15
16
  import { callTool } from "./tool-call.testing.ts";
16
- import { DEFAULT_CONFIG } from "./config.ts";
17
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
17
18
 
18
19
  test("canonicalPath resolves relative and absolute", () => {
19
20
  const cwd = resolve("/cwd");
@@ -95,8 +96,8 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
95
96
  makeEditOverride(dir, DEFAULT_CONFIG),
96
97
  {
97
98
  path: `@${url}`,
98
- edits: [
99
- { action: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, body: ["edited"] },
99
+ steps: [
100
+ { action: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, lines: ["edited"] },
100
101
  ],
101
102
  },
102
103
  { toolCallId: "edit", ctx },
@@ -110,10 +111,14 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
110
111
  assert.match(matches.content[0].text, /edited/);
111
112
  assert.equal(await readFile(file, "utf8"), "edited\n");
112
113
  let commands = 0;
113
- const fusion = createActionFusionExecutor(async () => {
114
- commands++;
115
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
116
- });
114
+ const fusion = createActionFusionExecutor(() => {});
115
+ const fusionContext = {
116
+ cwd: dir,
117
+ executeTool: async () => {
118
+ commands++;
119
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
120
+ },
121
+ };
117
122
  await callTool(
118
123
  makeWriteOverride(dir, fusion),
119
124
  {
@@ -122,7 +127,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
122
127
  mode: "overwrite",
123
128
  then_run: { command: "check" },
124
129
  },
125
- { toolCallId: "fused", ctx },
130
+ { toolCallId: "fused", ctx: fusionContext },
126
131
  );
127
132
  assert.equal(commands, 1);
128
133
  } finally {
@@ -31,8 +31,8 @@ import { POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
31
31
  import { errnoCode } from "../core/errors.ts";
32
32
  import { throwIfCancelled } from "./error-text.ts";
33
33
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
34
- import { defaultOutputBudgets, formatByteSize, type OutputBudgetProvider } from "./budgets.ts";
35
- import type { HashlineEditConfig } from "./config.ts";
34
+ import { formatByteSize } from "./budgets.ts";
35
+ import type { ToolEnvironment } from "./config.ts";
36
36
  import { createArgumentPreparer } from "./argument-validation.ts";
37
37
 
38
38
  const DEFAULT_OFFSET = 1;
@@ -44,7 +44,7 @@ type ReadDetails = (ReadToolDetails & { nativeRead?: true }) & Partial<ReportDet
44
44
  * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
45
45
  * ` · no trailing newline`. A missing final newline is a byte-level fact the
46
46
  * numbered rows cannot show, so the header, which the model never copies into an
47
- * edit `body`, states it. READ_HEADER is the TUI's parser for this exact line.
47
+ * edit `lines`, states it. READ_HEADER is the TUI's parser for this exact line.
48
48
  */
49
49
  function formatReadHeader(
50
50
  path: string,
@@ -106,11 +106,11 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
106
106
  }
107
107
 
108
108
  /** Build the read override (a ToolDefinition fragment for registerTool). */
109
- export function makeReadOverride(
110
- cwd: string,
111
- config: HashlineEditConfig,
112
- budgets: OutputBudgetProvider = defaultOutputBudgets,
113
- ): ToolDefinition<
109
+ export function makeReadOverride({
110
+ cwd,
111
+ config,
112
+ budgets,
113
+ }: ToolEnvironment): ToolDefinition<
114
114
  ReturnType<typeof createReadToolDefinition>["parameters"],
115
115
  ReadDetails | undefined
116
116
  > {
@@ -155,7 +155,7 @@ export function makeReadOverride(
155
155
  const { isPartial, expanded } = options;
156
156
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
157
157
  if (context.isError) return renderToolError(result, "read", theme, expanded);
158
- const { content, report } = splitReport(result);
158
+ const { content, report } = splitReport(result, "read");
159
159
  if (result.details?.nativeRead)
160
160
  return builtin.renderResult!({ ...result, content }, options, theme, context);
161
161
  // Collapsed (not expanded): show nothing — the call line carries the
@@ -243,16 +243,11 @@ export function makeReadOverride(
243
243
  // Rows were returned and more remain. A caller's own limit is a chosen window: its header
244
244
  // and rows already show where it ends, so only a window the extension cut (default limit
245
245
  // or byte budget) gets a report.
246
- const pagination =
246
+ const nextOffset =
247
247
  (params.limit === undefined || truncated) &&
248
248
  rows.length > 0 &&
249
249
  start + rows.length <= stats.totalLines
250
- ? {
251
- start,
252
- end: start + (rows.length - 1),
253
- totalLines: stats.totalLines,
254
- nextOffset: start + rows.length,
255
- }
250
+ ? start + rows.length
256
251
  : undefined;
257
252
  const header = `${formatReadHeader(serializePath(cwd, absPath), stats.totalLines, start, stats.finalNewline)}\n`;
258
253
  const limitText = formatByteSize(maxBytes);
@@ -260,9 +255,9 @@ export function makeReadOverride(
260
255
  return reportResult(
261
256
  {
262
257
  ...report,
263
- pagination,
258
+ nextOffset,
264
259
  outputLimit: truncated && !firstLineExceedsLimit ? limitText : undefined,
265
- lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
260
+ lineTooLong: firstLineExceedsLimit ? limitText : undefined,
266
261
  },
267
262
  [{ type: "text" as const, text: header + rows.join("\n") }],
268
263
  );
@@ -7,11 +7,12 @@ import { join } from "node:path";
7
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
8
8
  import type { Theme } from "@earendil-works/pi-coding-agent";
9
9
  import { validateToolArguments } from "@earendil-works/pi-ai";
10
- import { makeReadOverride } from "./read-tool.ts";
10
+ import { makeReadOverride } from "./tool-factories.testing.ts";
11
11
  import { computeLineHash } from "../core/hash.ts";
12
12
  import { callTool } from "./tool-call.testing.ts";
13
- import { DEFAULT_CONFIG } from "./config.ts";
14
- import { DEFAULT_OUTPUT_BUDGETS, formatByteSize } from "./budgets.ts";
13
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
14
+ import { formatByteSize } from "./budgets.ts";
15
+ import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
15
16
  import { reportOf } from "./report.ts";
16
17
  import { createAnchorFormatter } from "./anchor-format.ts";
17
18
 
@@ -146,10 +147,7 @@ test("read reports an oversized first row without suggesting an ineffective retr
146
147
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "long.txt" });
147
148
  assert.doesNotMatch(result.content[0].text, /^\d+#/m);
148
149
  assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
149
- assert.deepEqual(reportOf(result, "read")?.lineTooLong, {
150
- line: 1,
151
- limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
152
- });
150
+ assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
153
151
  assert.match(reportOf(result, "read")?.next ?? "", /chunks.*bash.*replace/);
154
152
  }));
155
153
 
@@ -158,14 +156,14 @@ test("read preserves empty files and explicit limits above the native default",
158
156
  await writeFile(join(dir, "empty.txt"), "");
159
157
  const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
160
158
  assert.match(empty.content[0].text, /0 lines/);
161
- assert.equal(reportOf(empty, "read")?.pagination, undefined);
159
+ assert.equal(reportOf(empty, "read")?.nextOffset, undefined);
162
160
  await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
163
161
  const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
164
162
  path: "many.txt",
165
163
  limit: 2001,
166
164
  });
167
165
  assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
168
- assert.equal(reportOf(many, "read")?.pagination, undefined);
166
+ assert.equal(reportOf(many, "read")?.nextOffset, undefined);
169
167
  }));
170
168
 
171
169
  test("read window end chosen by caller or default → only the default offers optional continuation", async () =>
@@ -185,14 +183,14 @@ test("read window end chosen by caller or default → only the default offers op
185
183
  assert.match(result.content[0].text, new RegExp(`large\\.txt · ${totalLines} lines`));
186
184
  assert.match(result.content[0].text, new RegExp(`\\n${end}#[0-9A-Z]+│line${end}`));
187
185
  assert.doesNotMatch(result.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│`));
188
- const pagination = { start: 1, end, totalLines, nextOffset: end + 1 };
186
+ const nextOffset = end + 1;
189
187
  const report = reportOf(result, "read");
190
188
  assert.ok(report);
191
189
  if (limit === undefined) {
192
- assert.deepEqual(report.pagination, pagination);
193
- assert.match(report.next ?? "", /if you need more lines.*offset.*pagination\.nextOffset/i);
190
+ assert.equal(report.nextOffset, nextOffset);
191
+ assert.match(report.next ?? "", /if you need more lines.*offset.*nextOffset/i);
194
192
  } else {
195
- assert.equal(Object.hasOwn(report, "pagination"), false);
193
+ assert.equal(Object.hasOwn(report, "nextOffset"), false);
196
194
  assert.equal(Object.hasOwn(report, "next"), false);
197
195
  }
198
196
  }
@@ -209,26 +207,20 @@ test("read pagination supports offset windows and stops suggesting continuation
209
207
  );
210
208
  const read = makeReadOverride(dir, DEFAULT_CONFIG);
211
209
  const page = await call(read, { path: "pages.txt", offset: start });
212
- assert.match(reportOf(page, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
213
- assert.deepEqual(reportOf(page, "read")?.pagination, {
214
- start,
215
- end,
216
- totalLines,
217
- nextOffset: end + 1,
218
- });
219
- const pagination = reportOf(page, "read")?.pagination;
220
- assert.ok(pagination);
210
+ assert.match(reportOf(page, "read")?.next ?? "", /offset.*nextOffset/);
211
+ const nextOffset = reportOf(page, "read")?.nextOffset;
212
+ assert.ok(nextOffset);
221
213
  const next = await call(read, {
222
214
  path: "pages.txt",
223
- offset: pagination.nextOffset,
215
+ offset: nextOffset,
224
216
  });
225
217
  assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
226
218
  assert.match(next.content[0].text, new RegExp(`\\n${totalLines}#[0-9A-Z]+│line${totalLines}`));
227
- assert.equal(reportOf(next, "read")?.pagination, undefined);
219
+ assert.equal(reportOf(next, "read")?.nextOffset, undefined);
228
220
  assert.equal(reportOf(next, "read")?.next, undefined);
229
221
  for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
230
222
  const result = await call(read, { path: "pages.txt", offset });
231
- assert.equal(reportOf(result, "read")?.pagination, undefined);
223
+ assert.equal(reportOf(result, "read")?.nextOffset, undefined);
232
224
  assert.equal(reportOf(result, "read")?.next, undefined);
233
225
  }
234
226
  }));
@@ -288,14 +280,9 @@ test("read byte truncation retains its budget and a continuation after complete
288
280
  path: "large.txt",
289
281
  limit: 2,
290
282
  });
291
- assert.deepEqual(reportOf(result, "read")?.pagination, {
292
- start: 1,
293
- end: 1,
294
- totalLines: 3,
295
- nextOffset: 2,
296
- });
283
+ assert.equal(reportOf(result, "read")?.nextOffset, 2);
297
284
  assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
298
- assert.match(reportOf(result, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
285
+ assert.match(reportOf(result, "read")?.next ?? "", /offset.*nextOffset/);
299
286
  assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
300
287
  }));
301
288
 
@@ -310,10 +297,7 @@ test("read bounds oversized selected lines while reporting limits and preserving
310
297
  assert.equal(reportOf(result, "read")?.lineTooLong, undefined);
311
298
  assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
312
299
  const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
313
- assert.deepEqual(reportOf(oversized, "read")?.lineTooLong, {
314
- line: 2,
315
- limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
316
- });
300
+ assert.equal(reportOf(oversized, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
317
301
  assert.doesNotMatch(oversized.content[0].text, /^\d+#/m);
318
302
  const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
319
303
  assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
@@ -325,10 +309,7 @@ test("read budgets visible standalone CR characters using rendered UTF-8 bytes",
325
309
  const content = "\r".repeat(90_000);
326
310
  await writeFile(join(dir, "cr.txt"), content);
327
311
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "cr.txt", limit: 1 });
328
- assert.deepEqual(reportOf(result, "read")?.lineTooLong, {
329
- line: 1,
330
- limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
331
- });
312
+ assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
332
313
  assert.doesNotMatch(result.content[0].text, /^\d+#/m);
333
314
  }));
334
315
 
@@ -363,7 +344,7 @@ test("read accepts safe offsets and limits whose sum exceeds the safe integer ra
363
344
  offset,
364
345
  limit: Number.MAX_SAFE_INTEGER,
365
346
  });
366
- assert.equal(reportOf(result, "read")?.pagination, undefined);
347
+ assert.equal(reportOf(result, "read")?.nextOffset, undefined);
367
348
  assert.doesNotMatch(result.content[0].text, /to continue|│first/);
368
349
  if (offset <= 3) assert.match(result.content[0].text, /│third/);
369
350
  else assert.doesNotMatch(result.content[0].text, /│/);
@@ -2,10 +2,10 @@ import { rejectsArgument } from "./argument-error.testing.ts";
2
2
  import { createEditTool } from "@earendil-works/pi-coding-agent";
3
3
  import { validateToolArguments, type Tool } from "@earendil-works/pi-ai";
4
4
  import { makeStrictJsonSchema } from "@earendil-works/pi-ai/api/constrained-sampling";
5
- import { makeEditOverride } from "./edit-tool.ts";
6
- import { makeReadOverride } from "./read-tool.ts";
5
+ import { makeEditOverride } from "./tool-factories.testing.ts";
6
+ import { makeReadOverride } from "./tool-factories.testing.ts";
7
7
  import { loadConfig } from "./config.ts";
8
- import { DEFAULT_CONFIG } from "./config.ts";
8
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
9
9
  import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
10
10
  import { tmpdir } from "node:os";
11
11
  import { join } from "node:path";
@@ -58,18 +58,18 @@ test("registered tools with or without Fusion → request strict sampling with c
58
58
  assert.partialDeepStrictEqual(strict, {
59
59
  type: "object",
60
60
  additionalProperties: false,
61
- required: actionFusion ? ["path", "edits", "then_run"] : ["path", "edits"],
61
+ required: actionFusion ? ["path", "steps", "then_run"] : ["path", "steps"],
62
62
  properties: {
63
- edits: {
63
+ steps: {
64
64
  type: "array",
65
65
  items: {
66
66
  type: "object",
67
67
  additionalProperties: false,
68
- required: ["action", "anchor", "end", "body"],
68
+ required: ["action", "anchor", "end", "lines"],
69
69
  properties: {
70
70
  anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
71
71
  end: { anyOf: [{ type: "string" }, { type: "null" }] },
72
- body: { anyOf: [{ type: "array" }, { type: "null" }] },
72
+ lines: { anyOf: [{ type: "array" }, { type: "null" }] },
73
73
  },
74
74
  },
75
75
  },
@@ -78,6 +78,17 @@ test("registered tools with or without Fusion → request strict sampling with c
78
78
  : {}),
79
79
  },
80
80
  });
81
+ const properties = strict.properties as Record<
82
+ string,
83
+ { items?: { properties?: Record<string, unknown> } }
84
+ >;
85
+ assert.deepEqual(
86
+ Object.keys(properties),
87
+ actionFusion ? ["path", "steps", "then_run"] : ["path", "steps"],
88
+ );
89
+ const stepProperties = properties.steps.items?.properties;
90
+ assert.ok(stepProperties);
91
+ assert.deepEqual(Object.keys(stepProperties), ["action", "anchor", "end", "lines"]);
81
92
  }
82
93
  });
83
94
  }
@@ -171,7 +182,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
171
182
  );
172
183
  const cases = [
173
184
  { name: "write", args: { content: "published\n", mode: "create" } },
174
- { name: "edit", args: { edits: [{ action: "append", body: ["appended"] }] } },
185
+ { name: "edit", args: { steps: [{ action: "append", lines: ["appended"] }] } },
175
186
  {
176
187
  name: "replace",
177
188
  args: { replacements: [{ literal: true, find: "published", replace: "published" }] },
@@ -312,8 +323,8 @@ test("mutation cards use Fusion by default and explicit false removes command su
312
323
  const edit = tools.find((tool) => tool.name === "edit");
313
324
  const stale = {
314
325
  path: "stale.txt",
315
- edits: [
316
- { action: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] },
326
+ steps: [
327
+ { action: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, lines: ["changed"] },
317
328
  ],
318
329
  then_run: { command: "exit 99" },
319
330
  };
@@ -447,7 +458,7 @@ test("loaded configuration controls hash length and recovery radius", async () =
447
458
  await expectToolFailure(
448
459
  call(makeEditOverride(dir, config), {
449
460
  path: "configured.txt",
450
- edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
461
+ steps: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
451
462
  }),
452
463
  "ANCHOR_MISMATCH",
453
464
  (report) => {
@@ -470,19 +481,14 @@ test("configured read defaults bound omitted limits and returned bytes", async (
470
481
  assert.match(description, /default 2\)/);
471
482
  await writeFile(join(dir, "short.txt"), "a\nb\nc\n");
472
483
  const paged = await call(read, { path: "short.txt" });
473
- assert.deepEqual(reportOf(paged, "read")?.pagination, {
474
- start: 1,
475
- end: 2,
476
- totalLines: 3,
477
- nextOffset: 3,
478
- });
479
- assert.match(reportOf(paged, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
484
+ assert.equal(reportOf(paged, "read")?.nextOffset, 3);
485
+ assert.match(reportOf(paged, "read")?.next ?? "", /offset.*nextOffset/);
480
486
  assert.match(paged.content[0].text, /^2#[0-9A-Z]+│b$/m);
481
487
  assert.doesNotMatch(paged.content[0].text, /^3#/m);
482
488
  const explicit = await call(read, { path: "short.txt", limit: 3 });
483
489
  assert.match(explicit.content[0].text, /^3#[0-9A-Z]+│c$/m);
484
490
  await writeFile(join(dir, "wide.txt"), `${"x".repeat(2048)}\n`);
485
491
  const wide = await call(read, { path: "wide.txt" });
486
- assert.deepEqual(reportOf(wide, "read")?.lineTooLong, { line: 1, limit: formatByteSize(1024) });
492
+ assert.equal(reportOf(wide, "read")?.lineTooLong, formatByteSize(1024));
487
493
  assert.doesNotMatch(wide.content[0].text, /^\d+#/m);
488
494
  }));