@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.
@@ -1,6 +1,10 @@
1
1
  import { rejectsArgument } from "./argument-error.testing.ts";
2
2
  import { createEditTool } from "@earendil-works/pi-coding-agent";
3
3
  import { validateToolArguments } from "@earendil-works/pi-ai";
4
+ import {
5
+ makeStrictJsonSchema,
6
+ resolveJsonSchemaStrictSampling,
7
+ } from "@earendil-works/pi-ai/api/constrained-sampling";
4
8
  import { makeEditOverride } from "./edit-tool.ts";
5
9
  import { makeReadOverride } from "./read-tool.ts";
6
10
  import { loadConfig } from "./config.ts";
@@ -19,11 +23,43 @@ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/m
19
23
  import { computeLineHash } from "../core/hash.ts";
20
24
  import { callTool } from "./tool-call.testing.ts";
21
25
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
22
- import type { ActionFusionProgress } from "./action-fusion.ts";
26
+ import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
23
27
  import { reportOf } from "./report.ts";
24
28
  import { formatByteSize } from "./budgets.ts";
25
29
  import { expectToolFailure } from "./report-failure.testing.ts";
26
30
 
31
+ test("edit with or without Fusion → expose parameters usable by Pi strict sampling", () => {
32
+ for (const fusion of [undefined, createActionFusionExecutor()]) {
33
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG, fusion);
34
+ assert.deepEqual(tool.constrainedSampling, { type: "json_schema", strict: "prefer" });
35
+ assert.equal(resolveJsonSchemaStrictSampling(tool, true), true);
36
+ const strict = makeStrictJsonSchema(tool.parameters);
37
+ assert.partialDeepStrictEqual(strict, {
38
+ type: "object",
39
+ additionalProperties: false,
40
+ required: fusion ? ["path", "edits", "then_run"] : ["path", "edits"],
41
+ properties: {
42
+ edits: {
43
+ type: "array",
44
+ items: {
45
+ type: "object",
46
+ additionalProperties: false,
47
+ required: ["action", "anchor", "end", "body", "before", "after"],
48
+ properties: {
49
+ anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
50
+ end: { anyOf: [{ type: "string" }, { type: "null" }] },
51
+ body: { anyOf: [{ type: "array" }, { type: "null" }] },
52
+ before: { anyOf: [{ type: "string" }, { type: "null" }] },
53
+ after: { anyOf: [{ type: "string" }, { type: "null" }] },
54
+ },
55
+ },
56
+ },
57
+ ...(fusion ? { then_run: { anyOf: [{ type: "object" }, { type: "null" }] } } : {}),
58
+ },
59
+ });
60
+ }
61
+ });
62
+
27
63
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
28
64
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
29
65
  const previousCwd = process.cwd();
@@ -107,7 +143,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
107
143
  );
108
144
  const cases = [
109
145
  { name: "write", args: { content: "published\n", mode: "create" } },
110
- { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
146
+ { name: "edit", args: { edits: [{ action: "append", body: ["appended"] }] } },
111
147
  {
112
148
  name: "replace",
113
149
  args: { replacements: [{ literal: true, find: "published", replace: "published" }] },
@@ -199,14 +235,12 @@ test("mutation cards use Fusion by default and explicit false removes command su
199
235
  tui,
200
236
  dir,
201
237
  );
202
- const failed = await tool.execute(
203
- `${name}-bad`,
204
- invalid,
205
- undefined,
206
- (update: AgentToolResult<unknown>) =>
238
+ const failed = await callTool(tool, invalid, {
239
+ toolCallId: `${name}-bad`,
240
+ onUpdate: (update: AgentToolResult<unknown>) =>
207
241
  failedCard.updateResult({ ...update, isError: false }, true),
208
- { cwd: dir },
209
- );
242
+ ctx: { cwd: dir },
243
+ });
210
244
  assert.equal(failed.isError, true);
211
245
  const report = reportOf(failed, name);
212
246
  assert.equal(report?.error, "PATH_NOT_FOUND");
@@ -250,18 +284,18 @@ test("mutation cards use Fusion by default and explicit false removes command su
250
284
  const edit = tools.find((tool) => tool.name === "edit");
251
285
  const stale = {
252
286
  path: "stale.txt",
253
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] }],
287
+ edits: [
288
+ { action: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] },
289
+ ],
254
290
  then_run: { command: "exit 99" },
255
291
  };
256
292
  const staleCard = new ToolExecutionComponent("edit", "stale", stale, {}, edit, tui, dir);
257
- const failed = await edit.execute(
258
- "stale",
259
- stale,
260
- undefined,
261
- (update: AgentToolResult<unknown>) =>
293
+ const failed = await callTool(edit, stale, {
294
+ toolCallId: "stale",
295
+ onUpdate: (update: AgentToolResult<unknown>) =>
262
296
  staleCard.updateResult({ ...update, isError: false }, true),
263
- { cwd: dir },
264
- );
297
+ ctx: { cwd: dir },
298
+ });
265
299
  assert.equal(failed.isError, true);
266
300
  assert.equal(reportOf(failed, "edit")?.failures?.[0].result, "shifted");
267
301
  staleCard.updateResult(failed);
@@ -385,7 +419,7 @@ test("loaded configuration controls hash length and recovery radius", async () =
385
419
  await expectToolFailure(
386
420
  call(makeEditOverride(dir, config), {
387
421
  path: "configured.txt",
388
- edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
422
+ edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
389
423
  }),
390
424
  "ANCHOR_MISMATCH",
391
425
  (report) => {
@@ -77,7 +77,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
77
77
  ]) {
78
78
  const args = {
79
79
  path: "a.txt",
80
- edits: [{ op: "append" as const, body: ["new"] }],
80
+ edits: [{ action: "append" as const, body: ["new"] }],
81
81
  replacements: [{ literal: true, find: "old", replace: "new" }],
82
82
  };
83
83
  const context: any = {
@@ -108,19 +108,19 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
108
108
  }
109
109
  });
110
110
 
111
- test("edit call titles count each operation type and refresh with partial input", () => {
111
+ test("partial edit actions → refresh per-action counts", () => {
112
112
  initTheme("dark");
113
113
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
114
114
  const edits = [
115
- { op: "replace", anchor: "1#AB", body: ["new"] },
116
- { op: "append", body: ["more"] },
117
- { op: "replace", anchor: "3#CD", body: ["changed"] },
118
- { op: "delete", anchor: "5#EF" },
119
- { op: "insert_before", anchor: "7#GH", body: ["before"] },
120
- { op: "insert_after", anchor: "9#JK", body: ["after"] },
121
- { op: "prepend", body: ["first"] },
122
- { op: "copy", anchor: "1#AB", before: "3#CD" },
123
- { op: "move", anchor: "3#CD", after: "5#EF" },
115
+ { action: "replace", anchor: "1#AB", body: ["new"] },
116
+ { action: "append", body: ["more"] },
117
+ { action: "replace", anchor: "3#CD", body: ["changed"] },
118
+ { action: "delete", anchor: "5#EF" },
119
+ { action: "insert_before", anchor: "7#GH", body: ["before"] },
120
+ { action: "insert_after", anchor: "9#JK", body: ["after"] },
121
+ { action: "prepend", body: ["first"] },
122
+ { action: "copy", anchor: "1#AB", before: "3#CD" },
123
+ { action: "move", anchor: "3#CD", after: "5#EF" },
124
124
  ];
125
125
  let header: ReturnType<typeof tool.renderCall> | undefined;
126
126
  const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
@@ -153,7 +153,7 @@ test("edit call titles count each operation type and refresh with partial input"
153
153
  assert.match(single, /1 op: replace ×1/);
154
154
  assert.doesNotMatch(single, /append|copy|delete|insert_before|insert_after|move|prepend/);
155
155
  assert.match(
156
- render([null, { op: "rep" }, { op: "__proto__" }, { op: { toString: null } }]),
156
+ render([null, { action: "rep" }, { action: "__proto__" }, { action: { toString: null } }]),
157
157
  /4 ops: unknown ×4/,
158
158
  );
159
159
  for (const invalid of [[], undefined, JSON.stringify(edits), "[{bad"]) {
@@ -161,10 +161,37 @@ test("edit call titles count each operation type and refresh with partial input"
161
161
  }
162
162
  });
163
163
 
164
+ test("missing or empty mutation path → show a themed placeholder until the path arrives", () => {
165
+ initTheme("dark");
166
+ for (const tool of [
167
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG),
168
+ makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
169
+ ]) {
170
+ const context = { state: {} } as Parameters<
171
+ ReturnType<typeof makeEditOverride>["renderCall"]
172
+ >[2] &
173
+ Parameters<ReturnType<typeof makeReplaceTool>["renderCall"]>[2];
174
+ let header: ReturnType<typeof tool.renderCall> | undefined;
175
+ for (const path of [undefined, "", "f.txt"]) {
176
+ // Streaming arguments may contain operations before the path arrives.
177
+ const args = { path, edits: [], replacements: [] } as Parameters<
178
+ ReturnType<typeof makeEditOverride>["renderCall"]
179
+ >[0] &
180
+ Parameters<ReturnType<typeof makeReplaceTool>["renderCall"]>[0];
181
+ const previous = header;
182
+ header = tool.renderCall(args, theme, { ...context, lastComponent: header });
183
+ if (previous) assert.equal(header, previous);
184
+ const output = header.render(100).join("\n");
185
+ assert.ok(output.includes(theme.fg(path ? "accent" : "toolOutput", path || "...")));
186
+ assert.ok(stripVTControlCharacters(output).startsWith(`${tool.name} ${path || "..."}`));
187
+ }
188
+ }
189
+ });
190
+
164
191
  test("mutation card owns stale-anchor notices without internal status", () => {
165
192
  initTheme("dark");
166
193
  const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
167
- const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
194
+ const args = { path: "a.txt", edits: [{ action: "append" as const, body: ["new"] }] };
168
195
  const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
169
196
  const card = tool.renderCall!(args, theme, context);
170
197
  tool.renderResult!(
@@ -194,7 +221,7 @@ test("mutation card owns stale-anchor notices without internal status", () => {
194
221
  test("mutation card omits status when then_run was not requested", () => {
195
222
  initTheme("dark");
196
223
  const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
197
- const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
224
+ const args = { path: "a.txt", edits: [{ action: "append" as const, body: ["new"] }] };
198
225
  const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
199
226
  const card = tool.renderCall!(args, theme, context);
200
227
  tool.renderResult!(
@@ -282,7 +309,7 @@ test("diff previews retain standalone CR and literal control-picture characters"
282
309
  { expanded: true, isPartial: false },
283
310
  theme,
284
311
  {
285
- args: { path: "a.txt", edits: [{ op: "append", body: ["new"] }] },
312
+ args: { path: "a.txt", edits: [{ action: "append", body: ["new"] }] },
286
313
  state: {},
287
314
  isError: false,
288
315
  } as Parameters<typeof tool.renderResult>[3],
@@ -369,7 +396,7 @@ test("all tools render argument issues as field diagnostics while preserving mod
369
396
  path: "unused.txt",
370
397
  content: "unused",
371
398
  mode: "create" as const,
372
- edits: [{ op: "append" as const, body: ["unused"] }],
399
+ edits: [{ action: "append" as const, body: ["unused"] }],
373
400
  replacements: [{ literal: true, find: "unused", replace: "unused" }],
374
401
  pattern: "unused",
375
402
  literal: true,
package/src/pi/render.ts CHANGED
@@ -67,6 +67,16 @@ function countDiffLines(diff: string): DiffCounts {
67
67
  return { added, removed };
68
68
  }
69
69
 
70
+ /**
71
+ * The call header's path. Arguments stream in the provider's key order, so the
72
+ * path may arrive after the operations; until then it shows Pi's `...` placeholder.
73
+ */
74
+ export function formatHeaderPath(path: unknown, theme: Theme): string {
75
+ return typeof path === "string" && path
76
+ ? theme.fg("accent", path)
77
+ : theme.fg("toolOutput", "...");
78
+ }
79
+
70
80
  /** Format `+N -N` with the theme's diff colors for the tool call header. */
71
81
  export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
72
82
  return ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`;
@@ -46,6 +46,7 @@ import {
46
46
  import type { HashlineEditConfig } from "./config.ts";
47
47
  import {
48
48
  formatDiffCounts,
49
+ formatHeaderPath,
49
50
  renderMutationCall,
50
51
  renderMutationResult,
51
52
  type DiffCounts,
@@ -85,7 +86,7 @@ type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
85
86
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
86
87
  function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
87
88
  let t = theme.fg("toolTitle", theme.bold("replace "));
88
- t += theme.fg("accent", args.path);
89
+ t += formatHeaderPath(args.path, theme);
89
90
  const count = args.replacements?.length ?? 0;
90
91
  t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
91
92
  if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
@@ -121,7 +121,7 @@ export type ActionFusionProgress = Static<typeof ACTION_FUSION_PROGRESS_SCHEMA>;
121
121
  const ANCHOR_FAILURE_SCHEMA = Type.Object(
122
122
  {
123
123
  field: Type.String(),
124
- op: Type.String(),
124
+ action: Type.String(),
125
125
  cited: Type.String(),
126
126
  result: Type.Union([
127
127
  Type.Literal("shifted"),
@@ -301,7 +301,10 @@ export const ERROR_DEFINITIONS = {
301
301
  },
302
302
  OVERLAPPING_EDITS: {
303
303
  facts: facts([], MATCHED),
304
- next: { default: "Merge overlapping edits into one edit per range." },
304
+ next: {
305
+ default:
306
+ "Merge overlapping edits into one edit per range, and insertions at one position into one insertion.",
307
+ },
305
308
  },
306
309
  NO_MATCH: {
307
310
  facts: facts(["rule"]),
@@ -7,7 +7,7 @@ import { writeFileSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { test } from "node:test";
10
- import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
10
+ import { DEFAULT_OUTPUT_BUDGETS, outputBudgetsFor } from "./budgets.ts";
11
11
  import { createActionFusionExecutor } from "./action-fusion.ts";
12
12
  import { makeReplaceTool } from "./replace-tool.ts";
13
13
  import { makeWriteOverride } from "./write-tool.ts";
@@ -32,15 +32,20 @@ const invoke = (
32
32
  context?: unknown,
33
33
  ) => callTool(tool, args, { toolCallId, signal, onUpdate, ctx: context });
34
34
 
35
+ const anchorBudget = outputBudgetsFor(4096);
36
+ const anchorBatchSize: unknown = Reflect.get(
37
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.edits,
38
+ "maxItems",
39
+ );
40
+ assert.ok(typeof anchorBatchSize === "number");
41
+
35
42
  function assertFailureByteBudgets(message: string): void {
36
43
  const report = decodeReport(message, "edit");
37
44
  assert.ok(report);
38
45
  assert.equal(report.error, "ANCHOR_MISMATCH");
39
46
  assert.ok(report.failures && report.failures.length > 0);
40
- assert.ok(
41
- Buffer.byteLength(JSON.stringify(report.failures)) <= DEFAULT_OUTPUT_BUDGETS.blockBytes,
42
- );
43
- assert.equal(report.failures.length + (report.omittedFailures ?? 0), 1000);
47
+ assert.ok(Buffer.byteLength(JSON.stringify(report.failures)) <= anchorBudget.blockBytes);
48
+ assert.equal(report.failures.length + (report.omittedFailures ?? 0), anchorBatchSize);
44
49
  assert.ok(report.omittedFailures);
45
50
  assert.equal(report.matched, undefined);
46
51
  assert.equal(report.omittedMatched, undefined);
@@ -48,7 +53,7 @@ function assertFailureByteBudgets(message: string): void {
48
53
  if (report.candidateNeighborhoods) {
49
54
  const rows = report.candidateNeighborhoods.flatMap((group) => group.rows);
50
55
  assert.ok(rows.length > 0);
51
- assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= DEFAULT_OUTPUT_BUDGETS.blockBytes);
56
+ assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= anchorBudget.blockBytes);
52
57
  }
53
58
  }
54
59
 
@@ -83,7 +88,7 @@ test("edit and replace commands change or remove the file → withhold anchors a
83
88
  ? {
84
89
  edits: [
85
90
  {
86
- op: "replace",
91
+ action: "replace",
87
92
  anchor: `1#${computeLineHash(1, "before", DEFAULT_CONFIG.hashLen)}`,
88
93
  body: ["after"],
89
94
  },
@@ -269,9 +274,15 @@ test("aggregate anchor diagnostics → respect their byte budgets", async (t) =>
269
274
  const path = join(dir, "long.txt");
270
275
  await writeFile(path, "current\n");
271
276
  const failure = await invoke(
272
- makeEditOverride(dir, DEFAULT_CONFIG),
277
+ makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
273
278
  "errors",
274
- { path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })) },
279
+ {
280
+ path,
281
+ edits: Array.from({ length: anchorBatchSize }, () => ({
282
+ action: "delete",
283
+ anchor: "1#XXXX",
284
+ })),
285
+ },
275
286
  undefined,
276
287
  undefined,
277
288
  await ctx(dir, t),
@@ -300,7 +311,11 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
300
311
  const cases = [
301
312
  {
302
313
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
303
- args: { path, edits: [{ op: "append", body: ["\ud800"] }], then_run: { command: "check" } },
314
+ args: {
315
+ path,
316
+ edits: [{ action: "append", body: ["\ud800"] }],
317
+ then_run: { command: "check" },
318
+ },
304
319
  field: "edits[0].body[0]",
305
320
  },
306
321
  {
@@ -343,12 +358,12 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
343
358
  lines[49] = "different";
344
359
  await writeFile(path, lines.join("\n"));
345
360
  const failure = await invoke(
346
- makeEditOverride(dir, DEFAULT_CONFIG),
361
+ makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
347
362
  "ambiguous",
348
363
  {
349
364
  path,
350
- edits: Array.from({ length: 1000 }, () => ({
351
- op: "delete",
365
+ edits: Array.from({ length: anchorBatchSize }, () => ({
366
+ action: "delete",
352
367
  anchor: `50#${computeLineHash(50, "same", 4)}`,
353
368
  })),
354
369
  },
@@ -385,7 +400,7 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
385
400
  const cases = [
386
401
  {
387
402
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
388
- args: { path, edits: [{ op: "append", body: ["\0"] }], then_run: { command: "check" } },
403
+ args: { path, edits: [{ action: "append", body: ["\0"] }], then_run: { command: "check" } },
389
404
  field: "edits[0].body[0]",
390
405
  },
391
406
  {
@@ -480,7 +495,7 @@ const noOpCases = [
480
495
  params: {
481
496
  edits: [
482
497
  {
483
- op: "replace",
498
+ action: "replace",
484
499
  anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
485
500
  body: ["same"],
486
501
  },