@criogaid/pi-hashline-edit 0.5.0 β†’ 0.6.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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -0,0 +1,58 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
4
+ import { MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
5
+ import { formatSearchWarnings } from "./grep-output.ts";
6
+ import { MAX_RG_STDERR_BYTES, runText } from "./rg-process.ts";
7
+
8
+ const diagnostic = (size: number) =>
9
+ `regex parse error:\n${"intermediate context δΈ­πŸ™‚\n".repeat(size)}error: unclosed group\n`;
10
+
11
+ test("bounded diagnostics retain opening context and the final cause across streamed chunks", () => {
12
+ const source = diagnostic(MAX_SEARCH_DIAGNOSTIC_BYTES);
13
+ const buffer = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
14
+ const chunkChars = 113;
15
+ for (let offset = 0; offset < source.length; offset += chunkChars) {
16
+ buffer.append(source.slice(offset, offset + chunkChars));
17
+ }
18
+ const result = buffer.toString();
19
+ assert.match(result, /^regex parse error:/);
20
+ assert.match(result, /error: unclosed group\n$/);
21
+ assert.match(result, /omitted/i);
22
+ assert.ok(Buffer.byteLength(result) <= MAX_SEARCH_DIAGNOSTIC_BYTES);
23
+ });
24
+
25
+ test("diagnostics within the budget are unchanged", () => {
26
+ const buffer = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
27
+ const source = "path: ζƒι™δΈθΆ³πŸ™‚\nretry with another path\n";
28
+ for (const point of source) buffer.append(point);
29
+ assert.equal(buffer.toString(), source);
30
+ });
31
+
32
+ test("search warning aggregation retains the final cause and labels truncation", () => {
33
+ const result = formatSearchWarnings([diagnostic(MAX_SEARCH_DIAGNOSTIC_BYTES)]);
34
+ assert.match(result, /Search incomplete/);
35
+ assert.match(result, /regex parse error:/);
36
+ assert.match(result, /error: unclosed group/);
37
+ assert.match(result, /omitted/i);
38
+ });
39
+
40
+ test("stderr collection preserves UTF-8 and reports overflow without losing the final cause", async () => {
41
+ for (const source of ["ζƒι™δΈθΆ³πŸ™‚\n", diagnostic(MAX_RG_STDERR_BYTES)]) {
42
+ const result = await runText(
43
+ process.execPath,
44
+ ["--input-type=module", "--eval", "process.stdin.pipe(process.stderr)"],
45
+ Buffer.from(source),
46
+ AbortSignal.timeout(10000),
47
+ );
48
+ if (Buffer.byteLength(source) <= MAX_RG_STDERR_BYTES) {
49
+ assert.equal(result.stderr, source);
50
+ } else {
51
+ assert.match(result.stderr, /^regex parse error:/);
52
+ assert.match(result.stderr, /error: unclosed group\n$/);
53
+ assert.match(result.stderr, /omitted/i);
54
+ assert.doesNotMatch(result.stderr, /οΏ½/);
55
+ assert.ok(Buffer.byteLength(result.stderr) <= MAX_RG_STDERR_BYTES);
56
+ }
57
+ }
58
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Bounded diagnostic text shared by ripgrep stderr, batch aggregation, and
3
+ * model-facing search warnings. Retain the opening context and final cause;
4
+ * mark omitted text instead of silently dropping diagnostics.
5
+ */
6
+ import { truncateHead, truncateTail } from "@earendil-works/pi-coding-agent";
7
+ import { formatKiB } from "./budgets.ts";
8
+
9
+ export class DiagnosticBuffer {
10
+ private head = "";
11
+ private tail = "";
12
+ private truncated = false;
13
+ private readonly notice: string;
14
+ private readonly headBytes: number;
15
+ private readonly tailBytes: number;
16
+
17
+ private readonly maxBytes: number;
18
+
19
+ constructor(maxBytes: number) {
20
+ this.maxBytes = maxBytes;
21
+ this.notice = `\n[Diagnostics truncated (${formatKiB(maxBytes)} limit); middle omitted.]\n`;
22
+ const contentBytes = maxBytes - Buffer.byteLength(this.notice);
23
+ this.headBytes = Math.floor(contentBytes / 2);
24
+ this.tailBytes = contentBytes - this.headBytes;
25
+ }
26
+
27
+ append(text: string): void {
28
+ if (!this.truncated) {
29
+ const combined = this.head + text;
30
+ if (Buffer.byteLength(combined) <= this.maxBytes) {
31
+ this.head = combined;
32
+ return;
33
+ }
34
+ this.head = truncateHead(combined, {
35
+ maxBytes: this.headBytes,
36
+ maxLines: Number.MAX_SAFE_INTEGER,
37
+ }).content;
38
+ this.tail = this.truncateTail(combined);
39
+ this.truncated = true;
40
+ return;
41
+ }
42
+ this.tail = this.truncateTail(this.tail + text);
43
+ }
44
+
45
+ toString(): string {
46
+ return this.truncated ? this.head + this.notice + this.tail : this.head;
47
+ }
48
+
49
+ private truncateTail(text: string): string {
50
+ // Pi's truncated previews omit the final newline; streaming must retain it
51
+ // so the next chunk cannot merge two diagnostic lines.
52
+ const newline = text.endsWith("\n") ? "\n" : "";
53
+ const preview = truncateTail(text, {
54
+ maxBytes: this.tailBytes - newline.length,
55
+ maxLines: Number.MAX_SAFE_INTEGER,
56
+ });
57
+ return preview.content + (preview.truncated ? newline : "");
58
+ }
59
+ }
@@ -30,7 +30,7 @@ test("macOS attempts directory sync, tolerates unsupported operations, and prese
30
30
  syncBuiltinESMExports();
31
31
  for (failure of [undefined, "EINVAL", "ENOTSUP", "EIO"]) {
32
32
  const path = join(directory, failure ?? "success");
33
- const commit = commitFile(path, "published\n");
33
+ const commit = commitFile(path, "published\n", { mode: "create" });
34
34
  if (failure === "EIO") {
35
35
  await assert.rejects(
36
36
  commit,
@@ -20,7 +20,7 @@
20
20
  */
21
21
 
22
22
  import {
23
- type ExtensionContext,
23
+ type ExtensionToolContext,
24
24
  type Theme,
25
25
  type ToolDefinition,
26
26
  type ToolRenderResultOptions,
@@ -31,7 +31,6 @@ import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "
31
31
  import { applyEdits } from "../core/apply.ts";
32
32
  import { splitLines } from "../core/lines.ts";
33
33
  import { unwritableTextReason } from "../core/text.ts";
34
- import { invalidArgument } from "./error-text.ts";
35
34
  import type { Anchor, Edit } from "../core/types.ts";
36
35
  import type { HashlineEditConfig } from "./config.ts";
37
36
  import {
@@ -55,6 +54,12 @@ import {
55
54
  type MutationTarget,
56
55
  type TextMutationDetails,
57
56
  } from "./mutation-runner.ts";
57
+ import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
58
+ import {
59
+ argumentItems,
60
+ createArgumentPreparer,
61
+ type ReportArgumentIssue,
62
+ } from "./argument-validation.ts";
58
63
  type EditDetails = TextMutationDetails;
59
64
  type EditRenderContext = Parameters<NonNullable<ToolDefinition<EditSchema>["renderCall"]>>[2];
60
65
 
@@ -79,7 +84,8 @@ function buildEditSchema(hashLen: number) {
79
84
  }),
80
85
  );
81
86
  const bodyLines = Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
82
- description: "New lines, one per element, without CR/LF.",
87
+ minItems: 1,
88
+ description: 'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
83
89
  });
84
90
  const editOpSchema = Type.Union([
85
91
  Type.Object(
@@ -137,33 +143,31 @@ function buildEditSchema(hashLen: number) {
137
143
  type EditSchema = ReturnType<typeof buildEditSchema>;
138
144
 
139
145
  function createEditSchema(actionFusion: boolean, hashLen: number) {
140
- return withThenRunSchema(
141
- buildEditSchema(hashLen),
142
- "Command to run after the edit succeeds; failure does not roll back the edit.",
143
- actionFusion,
144
- );
146
+ return withThenRunSchema(buildEditSchema(hashLen), "edit", actionFusion);
145
147
  }
146
148
  type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
147
149
 
148
150
  type EditOpInput = Static<EditSchema>["edits"][number];
149
151
 
150
- /**
151
- * Checks the schema cannot express, run before Pi's schema validation. Rejects body
152
- * lines that cannot be written as UTF-8, anchor line numbers beyond the safe-integer
153
- * range, and names anchors whose hash length differs from `hashLen` (the schema would
154
- * report only a bare pattern mismatch). Malformed shapes are left to the schema.
155
- * Arguments are never changed.
156
- */
157
- function checkEditArguments(args: unknown, hashLen: number): void {
158
- const edits = (args as { edits?: unknown } | null)?.edits;
159
- if (!Array.isArray(edits)) return;
160
- const mismatches: string[] = [];
152
+ /** Report semantic argument issues; malformed shapes remain Pi's schema responsibility. */
153
+ function checkEditArguments(args: unknown, hashLen: number, report: ReportArgumentIssue): void {
154
+ const raw = (args as { edits?: unknown } | null)?.edits;
155
+ const edits = argumentItems(raw);
156
+ let hashLengthRecoveryHint = " Read or grep the file for current anchors.";
161
157
  edits.forEach((op, index) => {
162
158
  const body = (op as Record<string, unknown> | null)?.body;
163
159
  if (Array.isArray(body)) {
160
+ if (body.length === 0) {
161
+ report(
162
+ `edits[${index}].body`,
163
+ (op as Record<string, unknown>).op === "replace"
164
+ ? 'is empty; use {"op":"delete"} to remove lines, or supply the replacement lines.'
165
+ : 'is empty; remove this edit or supply at least one line ([""] for a blank line).',
166
+ );
167
+ }
164
168
  body.forEach((line, lineIndex) => {
165
169
  const reason = typeof line === "string" ? unwritableTextReason(line) : undefined;
166
- if (reason) throw invalidArgument(`edits[${index}].body[${lineIndex}]`, reason);
170
+ if (reason) report(`edits[${index}].body[${lineIndex}]`, reason);
167
171
  });
168
172
  }
169
173
  for (const field of ["anchor", "end"] as const) {
@@ -171,23 +175,20 @@ function checkEditArguments(args: unknown, hashLen: number): void {
171
175
  if (typeof value !== "string") continue;
172
176
  const token = parseAnchorToken(value);
173
177
  if (token && !Number.isSafeInteger(token.line)) {
174
- throw invalidArgument(
178
+ report(
175
179
  `edits[${index}].${field}`,
176
180
  `line number in ${value} exceeds the safe integer range; copy a complete "LINE#HASH" token from the latest tool result.`,
177
181
  );
178
182
  }
179
183
  if (token && token.hash.length !== hashLen) {
180
- mismatches.push(
181
- `edits[${index}].${field} ${value} has ${token.hash.length} hash characters`,
184
+ report(
185
+ `edits[${index}].${field}`,
186
+ `Anchor hash length mismatch: ${value} has ${token.hash.length} hash characters, but hashLen is ${hashLen}.${hashLengthRecoveryHint}`,
182
187
  );
188
+ hashLengthRecoveryHint = "";
183
189
  }
184
190
  }
185
191
  });
186
- if (mismatches.length) {
187
- throw new Error(
188
- `Anchor hash length mismatch: ${mismatches.join("; ")}, but hashLen is ${hashLen}. Anchors from a different hashLen setting cannot be verified; read or grep the file for current anchors.`,
189
- );
190
- }
191
192
  }
192
193
 
193
194
  /** Translate validated public operations into core edits, parsing numeric anchor positions. */
@@ -235,15 +236,33 @@ function formatUpdatedAnchors(
235
236
  );
236
237
  }
237
238
 
238
- /** Call-header line: `edit path β€” N ops: op`, plus `+N -N` once the result's diff counts are known. */
239
+ /** Call header with total/per-kind operation counts and the result's diff counts. */
239
240
  function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
240
241
  let t = theme.fg("toolTitle", theme.bold("edit "));
241
242
  t += theme.fg("accent", args.path);
242
243
  const edits = Array.isArray(args.edits) ? args.edits : [];
243
244
  const n = edits.length;
244
245
  if (n) {
245
- const kind = typeof edits[0]?.op === "string" ? edits[0].op : "unknown";
246
- t += theme.fg("dim", ` β€” ${n} op${n > 1 ? "s" : ""}: ${kind}`);
246
+ const opCounts: Record<EditOpInput["op"] | "unknown", number> = {
247
+ replace: 0,
248
+ delete: 0,
249
+ insert_before: 0,
250
+ insert_after: 0,
251
+ append: 0,
252
+ prepend: 0,
253
+ unknown: 0,
254
+ };
255
+ // Renderers receive partial arguments; fixed buckets keep one-pass counting O(1) in space.
256
+ for (const edit of edits) {
257
+ const kind = edit?.op;
258
+ if (typeof kind === "string" && Object.hasOwn(opCounts, kind)) opCounts[kind]++;
259
+ else opCounts.unknown++;
260
+ }
261
+ const summary = Object.entries(opCounts)
262
+ .filter(([, count]) => count > 0)
263
+ .map(([kind, count]) => `${kind} Γ—${count}`)
264
+ .join(", ");
265
+ t += theme.fg("dim", ` β€” ${n} op${n > 1 ? "s" : ""}: ${summary}`);
247
266
  }
248
267
  if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
249
268
  return t;
@@ -265,16 +284,16 @@ export function makeEditOverride(
265
284
  "Edit file lines by LINE#HASH anchors checked against the current file. Returns fresh anchors for changed lines. On anchor failure, shows current context and recovery candidates; nothing is retried automatically.",
266
285
  promptSnippet: "Edit file lines using verified anchors",
267
286
  promptGuidelines: [
268
- "Batch related edits to one file in a single edit call; all its anchors are checked against one snapshot.",
287
+ MUTATION_TOOL_GUIDELINE,
288
+ "Batch all edits to one file in a single edit call; all its anchors are checked against one snapshot.",
269
289
  "Reuse anchors while their line number and content are unchanged; inserts and deletes shift later lines, so use the edit's Updated anchors or re-read shifted lines.",
270
290
  "On edit anchor failure, inspect the recovery candidates before retrying or re-reading.",
271
291
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
272
292
  ],
273
293
  parameters,
274
- prepareArguments(args: unknown): EditParams {
275
- checkEditArguments(args, hashLen);
276
- return args as EditParams;
277
- },
294
+ prepareArguments: createArgumentPreparer("edit", parameters, (args, report) =>
295
+ checkEditArguments(args, hashLen, report),
296
+ ),
278
297
  renderShell: "default" as const,
279
298
 
280
299
  renderCall(args: EditParams, theme: Theme, context: EditRenderContext) {
@@ -303,7 +322,7 @@ export function makeEditOverride(
303
322
  params: EditParams,
304
323
  signal: AbortSignal | undefined,
305
324
  onUpdate: AgentToolUpdateCallback<EditDetails> | undefined,
306
- ctx: ExtensionContext,
325
+ ctx: ExtensionToolContext,
307
326
  ) {
308
327
  return executeMutation<Omit<EditParams, "then_run">, EditDetails>(
309
328
  {