@criogaid/pi-hashline-edit 0.1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +279 -0
  3. package/package.json +50 -0
  4. package/src/core/apply.test.ts +327 -0
  5. package/src/core/apply.ts +264 -0
  6. package/src/core/hash.test.ts +54 -0
  7. package/src/core/hash.ts +68 -0
  8. package/src/core/index.ts +13 -0
  9. package/src/core/lines.test.ts +33 -0
  10. package/src/core/lines.ts +52 -0
  11. package/src/core/types.ts +87 -0
  12. package/src/index.ts +44 -0
  13. package/src/integration/grep-rg.test.ts +390 -0
  14. package/src/pi/action-fusion.test.ts +244 -0
  15. package/src/pi/action-fusion.ts +284 -0
  16. package/src/pi/config.test.ts +22 -0
  17. package/src/pi/config.ts +56 -0
  18. package/src/pi/edit-tool.ts +367 -0
  19. package/src/pi/execute.test.ts +521 -0
  20. package/src/pi/failure-context.test.ts +88 -0
  21. package/src/pi/failure-context.ts +98 -0
  22. package/src/pi/failure-path.test.ts +60 -0
  23. package/src/pi/file-commit.test.ts +200 -0
  24. package/src/pi/file-commit.ts +185 -0
  25. package/src/pi/fusion-card.test.ts +69 -0
  26. package/src/pi/fusion-card.ts +78 -0
  27. package/src/pi/grep-tool.ts +795 -0
  28. package/src/pi/grep.test.ts +515 -0
  29. package/src/pi/pi.test.ts +19 -0
  30. package/src/pi/read-tool.ts +178 -0
  31. package/src/pi/registration.test.ts +41 -0
  32. package/src/pi/render.ts +103 -0
  33. package/src/pi/replace-tool.ts +303 -0
  34. package/src/pi/replace.test.ts +287 -0
  35. package/src/pi/rg-line-filter.test.ts +79 -0
  36. package/src/pi/rg-line-filter.ts +358 -0
  37. package/src/pi/rg-line-ranges.test.ts +30 -0
  38. package/src/pi/rg-line-ranges.ts +106 -0
  39. package/src/pi/state.ts +27 -0
  40. package/src/pi/write-tool.ts +83 -0
  41. package/src/pi/write.test.ts +126 -0
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Override edit: hashline ops via structured `edits` (LINE#HASH anchors).
3
+ *
4
+ * Each op in `edits` references line anchors copied from read / grep / replace output
5
+ * (or from a prior edit's "Updated anchors"). The core verifies each anchor live against
6
+ * the current file content — no snapshot, no global stale check: a cited line
7
+ * that changed (or was misremembered) fails its own anchor; unchanged lines
8
+ * elsewhere never block the edit. Legacy oldText/newText is not accepted — the
9
+ * schema requires an `op` discriminator, so legacy payloads are rejected at the
10
+ * schema layer (a visible failure, never a silent degradation).
11
+ *
12
+ * On success the result carries fresh `LINE#HASH` anchors for the lines this
13
+ * edit produced (and the line that shifted into a deletion gap), so the model
14
+ * can chain edits without a re-read.
15
+ *
16
+ * Concurrency safety: read-modify-write is wrapped in withFileMutationQueue.
17
+ * AbortSignal is honored — checked after read / before write.
18
+ *
19
+ * @module pi-hashline-edit/pi
20
+ */
21
+
22
+ import { generateDiffString, generateUnifiedPatch, withFileMutationQueue, type EditToolDetails } from "@earendil-works/pi-coding-agent";
23
+ import { Type, type Static } from "typebox";
24
+ import { Text } from "@earendil-works/pi-tui";
25
+ import { readFile } from "node:fs/promises";
26
+ import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
27
+ import { commitFile, FileMutationError, type PublicationStatus } from "./file-commit.ts";
28
+ import { applyEdits, hashFileLines } from "../core/index.ts";
29
+ import { splitLines } from "../core/lines.ts";
30
+ import type { ApplyFailure, Edit } from "../core/types.ts";
31
+ import { canonicalPath } from "./read-tool.ts";
32
+ import { getState } from "./state.ts";
33
+ import { formatDiffCounts, publishDiffCounts, renderDiffPreview, type DiffCounts } from "./render.ts";
34
+ import { formatFailureContext } from "./failure-context.ts";
35
+
36
+ /** Cap on the number of updated anchors returned inline (bounds token cost for large inserts). */
37
+ const MAX_ANCHOR_LINES = 40;
38
+
39
+ const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
40
+
41
+ function anchorRef(description: string) {
42
+ return Type.Optional(Type.String({ pattern: ANCHOR_PATTERN, description }));
43
+ }
44
+
45
+ /** Parse copied tokens at the boundary; core edits retain numeric anchors. */
46
+ function parseAnchor(value: string | undefined) {
47
+ if (value === undefined) return undefined;
48
+ const match = typeof value === "string" ? new RegExp(ANCHOR_PATTERN).exec(value) : null;
49
+ if (!match || !Number.isSafeInteger(Number(match[1]))) {
50
+ throw new Error('Invalid anchor; copy a complete "LINE#HASH" token from the latest tool result.');
51
+ }
52
+ return { line: Number(match[1]), hash: match[2] };
53
+ }
54
+
55
+ const editOpSchema = Type.Object({
56
+ op: Type.Union(
57
+ [
58
+ Type.Literal("replace", { description: "Replace the cited line(s) with `body`." }),
59
+ Type.Literal("delete", { description: "Delete the cited line(s)." }),
60
+ Type.Literal("insert_after", {
61
+ description: "Insert `body` immediately after the anchor line — the anchor line is kept as-is; do NOT copy it into `body`.",
62
+ }),
63
+ Type.Literal("insert_before", {
64
+ description: "Insert `body` immediately before the anchor line — the anchor line is kept as-is; do NOT copy it into `body`.",
65
+ }),
66
+ Type.Literal("append", { description: "Append `body` at the end of the file." }),
67
+ Type.Literal("prepend", { description: "Prepend `body` at the start of the file." }),
68
+ ],
69
+ { description: "Operation kind" },
70
+ ),
71
+ anchor: anchorRef(
72
+ 'Copy "LINE#HASH" from the latest read, grep, or mutation result. Required for replace/delete/insert; omit for append/prepend.',
73
+ ),
74
+ end: anchorRef(
75
+ 'Inclusive last "LINE#HASH" for replace/delete ranges. Required to change multiple existing lines; omitted means only the anchor line. Omit for insert/append/prepend.',
76
+ ),
77
+ body: Type.Optional(Type.Array(Type.String(), { description: "New content lines (required for replace/insert/append/prepend; omit for delete)" })),
78
+ });
79
+
80
+ function createEditSchema(actionFusion: boolean) {
81
+ return Type.Object({
82
+ path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
83
+ edits: Type.Array(editOpSchema, { description: "Hashline ops, each referencing LINE#HASH anchors from your latest read or edit result" }),
84
+ ...(actionFusion ? { then_run: createThenRunSchema("Command to run after the edit succeeds; failure does not roll back the edit.") } : {}),
85
+ });
86
+ }
87
+
88
+ const editSchema = createEditSchema(false);
89
+ type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: ThenRunInput };
90
+
91
+ type EditOpInput = Static<typeof editOpSchema>;
92
+
93
+ /** Format a failed batch with retryable shifted anchors and bounded live context. */
94
+ function formatFailure(
95
+ failure: ApplyFailure,
96
+ snapshot: Readonly<{ currentText: string; hashLen: number }>,
97
+ ): string {
98
+ if (failure.kind === "range") return failure.message;
99
+ if (failure.kind === "noop") return failure.message;
100
+
101
+ const lines: string[] = [];
102
+ let found = 0;
103
+ let ambiguous = 0;
104
+ let none = 0;
105
+ for (const f of failure.failures) {
106
+ const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
107
+ switch (f.recovery.kind) {
108
+ case "found":
109
+ found++;
110
+ lines.push(`• ${where}: content shifted. Resend with ${f.which} "${f.recovery.newLine}#${f.recovery.newHash}".`);
111
+ break;
112
+ case "ambiguous": {
113
+ ambiguous++;
114
+ const nums = f.recovery.candidates.map((candidate) => candidate.line).join(", ");
115
+ const list = f.recovery.candidates.map((candidate) => `"${candidate.line}#${candidate.hash}"`).join(" / ");
116
+ lines.push(`• ${where}: ambiguous — same content at lines ${nums}. Pick the right one and resend ${f.which} ${list}.`);
117
+ break;
118
+ }
119
+ case "none":
120
+ none++;
121
+ lines.push(
122
+ `• ${where}: original content not found within the configured shift-recovery window.` +
123
+ (f.current === null ? " Cited line is out of range." : ""),
124
+ );
125
+ break;
126
+ }
127
+ }
128
+ const parts: string[] = [];
129
+ if (found) parts.push(`${found} shifted`);
130
+ if (ambiguous) parts.push(`${ambiguous} ambiguous`);
131
+ if (none) parts.push(`${none} unresolved`);
132
+ return [
133
+ `Anchor mismatch: ${parts.join(", ")}.`,
134
+ "No changes written by this edit batch.",
135
+ ...lines,
136
+ ].join("\n") + formatFailureContext(snapshot.currentText, failure.failures, snapshot.hashLen);
137
+ }
138
+
139
+ /** Translate JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
140
+ function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } | { ok: false; error: string } {
141
+ const edits: Edit[] = [];
142
+ for (const o of ops) {
143
+ const anchor = parseAnchor(o.anchor);
144
+ const end = parseAnchor(o.end);
145
+ if (o.op !== "replace" && o.op !== "delete" && end) return { ok: false, error: `${o.op} does not accept \`end\`` };
146
+ if ((o.op === "append" || o.op === "prepend") && anchor) return { ok: false, error: `${o.op} does not accept \`anchor\`` };
147
+ if (o.op === "delete" && o.body !== undefined) return { ok: false, error: "delete does not accept `body`" };
148
+ switch (o.op) {
149
+ case "replace":
150
+ if (!anchor) return { ok: false, error: 'replace needs `anchor` "LINE#HASH"' };
151
+ if (!o.body) return { ok: false, error: "replace needs `body`" };
152
+ edits.push({ op: "replace", start: anchor, end, body: o.body });
153
+ break;
154
+ case "delete":
155
+ if (!anchor) return { ok: false, error: 'delete needs `anchor` "LINE#HASH"' };
156
+ edits.push({ op: "delete", start: anchor, end });
157
+ break;
158
+ case "insert_after":
159
+ case "insert_before":
160
+ if (!anchor) return { ok: false, error: `${o.op} needs \`anchor\` "LINE#HASH"` };
161
+ if (!o.body) return { ok: false, error: `${o.op} needs \`body\`` };
162
+ edits.push({ op: o.op, anchor, body: o.body });
163
+ break;
164
+ case "append":
165
+ case "prepend":
166
+ if (!o.body) return { ok: false, error: `${o.op} needs \`body\`` };
167
+ edits.push({ op: o.op, body: o.body });
168
+ break;
169
+ }
170
+ }
171
+ return { ok: true, edits };
172
+ }
173
+
174
+ /**
175
+ * Fail the edit by throwing. pi's contract: a tool failure is signaled by throwing,
176
+ * not by returning `{ isError: true }` — the framework derives `context.isError` from
177
+ * whether execute threw, and overwrites `result.isError` with it
178
+ * (`updateResult({ ...result, isError: event.isError })`). Returning an isError object
179
+ * left the TUI rendering failures as success (green). The thrown message reaches the
180
+ * LLM verbatim; renderResult shows its first line in red.
181
+ */
182
+ function errResult(text: string): never {
183
+ throw new Error(text);
184
+ }
185
+
186
+ /**
187
+ * Format the updated anchors (fresh LINE#HASH│content) for the touched new-file
188
+ * lines, so the model can chain edits without a re-read. Capped to bound tokens.
189
+ */
190
+ function formatUpdatedAnchors(newText: string, touched: readonly number[], hashLen: number): string {
191
+ const newLines = splitLines(newText);
192
+ const newHashes = hashFileLines(newLines, hashLen);
193
+ const idxs = [...new Set(touched)].sort((a, b) => a - b);
194
+ if (idxs.length === 0) return "";
195
+ const rows = idxs.map((i) => `${i + 1}#${newHashes[i]}│${newLines[i]}`);
196
+ const shown = rows.length > MAX_ANCHOR_LINES ? rows.slice(0, MAX_ANCHOR_LINES) : rows;
197
+ const more = rows.length > MAX_ANCHOR_LINES ? `\n… (${rows.length - MAX_ANCHOR_LINES} more; re-read for full anchors)` : "";
198
+ return `\nUpdated anchors (use these for the next edit):\n${shown.join("\n")}${more}`;
199
+ }
200
+
201
+ /** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
202
+ function editHeader(args: any, theme: any, counts?: DiffCounts): string {
203
+ let t = theme.fg("toolTitle", theme.bold("edit "));
204
+ t += theme.fg("accent", args.path);
205
+ const n = args.edits?.length ?? 0;
206
+ if (n) t += theme.fg("dim", ` — ${n} op${n > 1 ? "s" : ""}: ${args.edits[0].op}`);
207
+ if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
208
+ return t;
209
+ }
210
+
211
+ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
212
+ const parameters = createEditSchema(fusion !== undefined);
213
+
214
+ return {
215
+ name: "edit" as const,
216
+ label: "edit",
217
+ description:
218
+ "Edit file lines using content-verified anchors. Returns fresh anchors for subsequent edits. Unrecoverable anchor errors may include bounded current-file anchors; retries are always verified again and never run automatically.",
219
+ promptSnippet: "Edit file lines using verified anchors",
220
+ promptGuidelines: [
221
+ "Batch changes to the same file in one edit call.",
222
+ "Use the latest returned anchors for subsequent edits; read again only for lines not covered by those results.",
223
+ ...(fusion ? ACTION_FUSION_GUIDELINES : []),
224
+ ],
225
+ parameters,
226
+ renderShell: "default" as const,
227
+
228
+ renderCall(args: EditParams, theme: any, context: any) {
229
+ const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
230
+ // Stash the header for renderResult: the diff counts land after
231
+ // execution and are refreshed in place (renderResult's lastComponent
232
+ // is the result component, not this header)
233
+ if (context?.state) context.state.callText = text;
234
+ text.setText(editHeader(args, theme, context?.state?.diffCounts));
235
+ return text;
236
+ },
237
+
238
+ renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
239
+ if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", "Editing…"), 0, 0);
240
+ const content = result.content?.[0];
241
+ if (context.isError) {
242
+ const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
243
+ return new Text(theme.fg("error", t), 0, 0);
244
+ }
245
+ const diff: string | undefined = result.details?.diff;
246
+ // refresh the call header's +N -N in place — never invalidate from
247
+ // inside a renderer (re-enters updateDisplay, diff renders twice)
248
+ publishDiffCounts(diff, context, (counts) => {
249
+ context.state?.callText?.setText(editHeader(context.args, theme, counts));
250
+ });
251
+ if (!diff) {
252
+ // No net diff (e.g. a successful but non-mutating edit): show only the summary
253
+ // line — content.text also carries `Updated anchors` (hashline) for the model.
254
+ const summary = content?.type === "text" ? content.text.split("\n")[0] : "Edited";
255
+ return new Text(theme.fg("success", summary), 0, 0);
256
+ }
257
+ // details.diff is pi-format (+N/-N/<space>N content); renderDiff handles
258
+ // semantic colors plus intra-line change highlighting
259
+ const rendered = renderDiffPreview(diff, expanded, theme);
260
+ return new Text(rendered, 0, 0);
261
+ },
262
+
263
+ async execute(toolCallId: string, params: EditParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
264
+ const { then_run, ...mutationParams } = params;
265
+ if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
266
+ const absolutePath = canonicalPath(cwd, mutationParams.path);
267
+ let mutationAnchors = "";
268
+ const mutate = () => {
269
+ const path = mutationParams.path;
270
+ if (!mutationParams.edits?.length) return errResult(`Edit ${path}: \`edits\` is empty or missing.`);
271
+ return withFileMutationQueue(absolutePath, () => runHashline(
272
+ absolutePath,
273
+ path,
274
+ mutationParams.edits,
275
+ signal,
276
+ (anchors) => { mutationAnchors = anchors; },
277
+ ));
278
+ };
279
+ const finalizeMutation = (result: any, publishAnchors: boolean) => ({
280
+ ...result,
281
+ content: result.content.map((block: any, index: number) =>
282
+ index === 0 && block.type === "text"
283
+ ? { ...block, text: `${block.text}${publishAnchors ? mutationAnchors : ""}` }
284
+ : block,
285
+ ),
286
+ });
287
+ if (!fusion) return finalizeMutation(await mutate(), true);
288
+ return fusion({
289
+ toolCallId,
290
+ absolutePath,
291
+ thenRun: then_run,
292
+ mutate,
293
+ finalizeMutation,
294
+ signal,
295
+ ctx,
296
+ onUpdate,
297
+ });
298
+ },
299
+ };
300
+ }
301
+
302
+ async function runHashline(
303
+ absPath: string,
304
+ displayPath: string,
305
+ editOps: readonly EditOpInput[],
306
+ signal: AbortSignal | undefined,
307
+ onAnchors: (anchors: string) => void,
308
+ ) {
309
+ const { hashLen, shiftRadius } = getState().config;
310
+
311
+ let currentText: string;
312
+ try {
313
+ currentText = (await readFile(absPath)).toString("utf-8");
314
+ } catch (e) {
315
+ const msg = e instanceof Error ? e.message : String(e);
316
+ return errResult(`Error reading ${displayPath}: ${msg}`);
317
+ }
318
+ // Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
319
+ if (signal?.aborted) return errResult(`Edit ${displayPath} aborted before apply.`);
320
+
321
+ const translated = toCoreEdits(editOps);
322
+ if (!translated.ok) return errResult(translated.error);
323
+
324
+ // Anchors are verified against the current content. A line that changed (or a
325
+ // hash the model didn't actually read) fails its own anchor — but first we try
326
+ // shifted recovery: if the content merely moved within ±shiftRadius, a fresh
327
+ // anchor is returned so the model can retry without a re-read. All failures in
328
+ // the batch are collected (nothing written on any failure).
329
+ const result = applyEdits(currentText, translated.edits, hashLen, shiftRadius);
330
+ if (!result.ok) {
331
+ return errResult(formatFailure(result.failure, { currentText, hashLen }));
332
+ }
333
+
334
+ // Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
335
+ if (signal?.aborted) return errResult(`Edit ${displayPath} aborted before write.`);
336
+
337
+ let publication: PublicationStatus = "NOT_PUBLISHED";
338
+ try {
339
+ publication = (await commitFile(absPath, result.text, { mode: "overwrite", signal })).publication;
340
+ } catch (e) {
341
+ if (e instanceof FileMutationError) throw e;
342
+ throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
343
+ }
344
+
345
+ let details: EditToolDetails & { publication: PublicationStatus };
346
+ let anchors: string;
347
+ try {
348
+ // diff 和 anchors 的计算属于发布后的后处理;失败时仍保留 publication。
349
+ const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
350
+ const newLf = result.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
351
+ const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
352
+ details = {
353
+ diff,
354
+ patch: generateUnifiedPatch(displayPath, oldLf, newLf),
355
+ firstChangedLine,
356
+ publication,
357
+ };
358
+ anchors = formatUpdatedAnchors(result.text, result.touchedLines, hashLen);
359
+ onAnchors(anchors);
360
+ } catch (error) {
361
+ throw new FileMutationError("post_process", publication, `file was published but edit result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
362
+ }
363
+ return {
364
+ content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)).` }],
365
+ details,
366
+ };
367
+ }