@criogaid/pi-hashline-edit 0.1.3 → 0.2.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.
@@ -0,0 +1,30 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { computeLineHash } from "../core/hash.ts";
4
+ import { ANCHOR_PATTERN, createAnchorFormatter } from "./anchor-format.ts";
5
+ import { getState } from "./state.ts";
6
+
7
+ test("anchor formatter snapshots configured hash length and hashes undisplayed content", () => {
8
+ const state = getState();
9
+ const previous = state.config;
10
+ try {
11
+ state.config = { ...previous, hashLen: 6 };
12
+ const formatter = createAnchorFormatter();
13
+ state.config = { ...previous, hashLen: 4 };
14
+
15
+ assert.equal(formatter.hashLen, 6);
16
+ assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
17
+ assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
18
+ assert.match(formatter.token(3, "full content"), new RegExp(ANCHOR_PATTERN));
19
+ assert.equal(formatter.row(3, "full content", "full…"), `3#${computeLineHash(3, "full content", 6)}│full…`);
20
+ assert.equal(createAnchorFormatter().hashLen, 4);
21
+ } finally {
22
+ state.config = previous;
23
+ }
24
+ });
25
+
26
+ test("anchor rows expose carriage returns while checksums retain source content", () => {
27
+ const formatter = createAnchorFormatter(4);
28
+ assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
29
+ assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
30
+ });
@@ -0,0 +1,28 @@
1
+ import { computeLineHash } from "../core/hash.ts";
2
+ import { getState } from "./state.ts";
3
+
4
+ export const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
5
+
6
+ /** Anchor serialization bound to one hash-length snapshot. */
7
+ export interface AnchorFormatter {
8
+ readonly hashLen: number;
9
+ reference(line: number, hash: string): string;
10
+ token(line: number, content: string): string;
11
+ row(line: number, content: string, displayContent?: string): string;
12
+ }
13
+
14
+ /** Make CR visible without changing the source text used for checksums or patches. */
15
+ export function displayCarriageReturns(text: string): string {
16
+ return text.replace(/\r/g, "␍");
17
+ }
18
+
19
+ export function createAnchorFormatter(hashLen = getState().config.hashLen): AnchorFormatter {
20
+ const reference = (line: number, hash: string) => `${line}#${hash}`;
21
+ const token = (line: number, content: string) => reference(line, computeLineHash(line, content, hashLen));
22
+ return {
23
+ hashLen,
24
+ token,
25
+ reference,
26
+ row: (line, content, displayContent = content) => `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
27
+ };
28
+ }
package/src/pi/config.ts CHANGED
@@ -17,7 +17,7 @@ export interface HashlineEditConfig {
17
17
  actionFusion: boolean;
18
18
  /** Line hash length (default 4). */
19
19
  hashLen: number;
20
- /** ±line radius for shifted-anchor recovery (default 15; 0 disables rescue). */
20
+ /** First-pass ±line radius before full-file recovery (default 15; 0 disables recovery). */
21
21
  shiftRadius: number;
22
22
  }
23
23
 
@@ -19,25 +19,26 @@
19
19
  * @module pi-hashline-edit/pi
20
20
  */
21
21
 
22
- import { generateDiffString, generateUnifiedPatch, truncateHead, withFileMutationQueue, type EditToolDetails } from "@earendil-works/pi-coding-agent";
22
+ import { truncateHead, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
23
23
  import { Type, type Static } from "typebox";
24
- import { Text } from "@earendil-works/pi-tui";
25
- import { readFile } from "node:fs/promises";
26
24
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
27
- import { byteRevision, commitFile, FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
28
- import { applyEdits, decodeEditableText } from "../core/index.ts";
25
+ import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
26
+ import { applyEdits } from "../core/index.ts";
29
27
  import { splitLines } from "../core/lines.ts";
30
28
  import type { ApplyFailure, Edit } from "../core/types.ts";
31
29
  import { canonicalPath } from "./read-tool.ts";
32
30
  import { getState } from "./state.ts";
33
- import { formatDiffCounts, renderMutationResult, type DiffCounts } from "./render.ts";
34
- import { formatFailureContext } from "./failure-context.ts";
35
- import { finalizeMutationResult, formatMutationAnchors } from "./mutation-result.ts";
31
+ import { ANCHOR_PATTERN, createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
32
+ import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
33
+ import { formatAmbiguousCandidateNeighborhoods, MAX_AMBIGUOUS_CANDIDATES, MAX_RECOVERY_CANDIDATE_BYTES } from "./failure-context.ts";
34
+ import { appendMutationAnchors, finalizeMutationResult, formatMutationAnchors, generateMutationDetails, postProcessMutation } from "./mutation-result.ts";
36
35
 
37
- /** Bound detailed failures before constructing diagnostics; the final message also has a byte cap. */
38
- const MAX_FAILURE_DETAILS = 40;
36
+ /** Keep independent byte budgets for failure details and input-anchor checks. */
37
+ function boundDiagnostic(message: string, notice: string): string {
38
+ const bounded = truncateHead(message, { maxBytes: 16 * 1024 - Buffer.byteLength(notice) });
39
+ return bounded.content + (bounded.truncated ? notice : "");
40
+ }
39
41
 
40
- const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
41
42
 
42
43
  function anchorRef(description: string) {
43
44
  return Type.Optional(Type.String({ pattern: ANCHOR_PATTERN, description }));
@@ -91,14 +92,17 @@ type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: The
91
92
 
92
93
  type EditOpInput = Static<typeof editOpSchema>;
93
94
 
94
- /** Format a failed batch with retryable shifted anchors and bounded live context. */
95
- function formatFailure(
95
+ /** Format failure mappings and complete unique-candidate rows within the detail budget. */
96
+ function formatFailureDetails(
96
97
  failure: ApplyFailure,
97
- snapshot: Readonly<{ currentText: string; hashLen: number }>,
98
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
99
+ candidateLines: ReadonlySet<number>,
98
100
  ): string {
99
101
  if (failure.kind !== "anchor") return failure.message;
100
102
 
101
103
  const lines: string[] = [];
104
+ const currentLines = splitLines(snapshot.currentText);
105
+ const shownCandidates = new Set(candidateLines);
102
106
  let found = 0;
103
107
  let ambiguous = 0;
104
108
  let none = 0;
@@ -106,21 +110,35 @@ function formatFailure(
106
110
  if (f.recovery.kind === "found") found++;
107
111
  else if (f.recovery.kind === "ambiguous") ambiguous++;
108
112
  else none++;
109
- if (lines.length >= MAX_FAILURE_DETAILS) continue;
110
113
  const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
114
+ const search = f.recovery.kind === "none" ? "" : f.recovery.scope === "local"
115
+ ? "Search: local; matches outside the window were not checked." : "Search: full file.";
111
116
  switch (f.recovery.kind) {
112
- case "found":
113
- lines.push(`• ${where}: checksum-matching candidate. Resend with ${f.which} "${f.recovery.newLine}#${f.recovery.newHash}" after checking the target.`);
117
+ case "found": {
118
+ const content = currentLines[f.recovery.newLine - 1];
119
+ const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
120
+ const row = content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
121
+ let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
122
+ if (!shownCandidates.has(f.recovery.newLine)) {
123
+ if (content !== undefined && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
124
+ detail += `\n${row}`;
125
+ shownCandidates.add(f.recovery.newLine);
126
+ } else {
127
+ detail += ` Candidate content exceeds ${MAX_RECOVERY_CANDIDATE_BYTES} bytes.`;
128
+ }
129
+ }
130
+ lines.push(detail);
114
131
  break;
132
+ }
115
133
  case "ambiguous": {
116
- const list = f.recovery.candidates.slice(0, 8).map((candidate) => `"${candidate.line}#${candidate.hash}"`).join(" / ");
117
- const more = f.recovery.candidates.length > 8 ? ` (${f.recovery.candidates.length - 8} more candidates omitted; use read)` : "";
118
- lines.push(`• ${where}: ambiguous checksum matches. Inspect the target and resend ${f.which} ${list}${more}.`);
134
+ const list = f.recovery.candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES).map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`).join(" / ");
135
+ const more = f.recovery.candidates.length > MAX_AMBIGUOUS_CANDIDATES ? ` (${f.recovery.candidates.length - MAX_AMBIGUOUS_CANDIDATES} more candidates omitted)` : "";
136
+ lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
119
137
  break;
120
138
  }
121
139
  case "none":
122
140
  lines.push(
123
- `• ${where}: original content not found within the configured shift-recovery window.` +
141
+ `• ${where}: no checksum-matching candidate found. Use read to inspect the current file before retrying.` +
124
142
  (f.current === null ? " Cited line is out of range." : ""),
125
143
  );
126
144
  break;
@@ -134,11 +152,33 @@ function formatFailure(
134
152
  `Anchor mismatch: ${parts.join(", ")}.`,
135
153
  "No changes written by this edit batch.",
136
154
  ...lines,
137
- ...(failure.failures.length > lines.length ? [`${failure.failures.length - lines.length} failure details omitted; use read to inspect remaining targets.`] : []),
138
- ].join("\n") + formatFailureContext(snapshot.currentText, failure.failures, snapshot.hashLen);
139
- const notice = "\nDiagnostic output truncated at 16 KiB. Use read to inspect omitted targets.";
140
- const bounded = truncateHead(message, { maxBytes: 16 * 1024 - Buffer.byteLength(notice) });
141
- return bounded.content + (bounded.truncated ? notice : "");
155
+ ].join("\n");
156
+ return boundDiagnostic(message, "\nDiagnostic output truncated at 16 KiB.");
157
+ }
158
+
159
+ function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
160
+ const rows = failure.checks.map((check) =>
161
+ `op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
162
+ );
163
+ const message = [
164
+ "Input-anchor checks (this snapshot):",
165
+ ...rows,
166
+ "Anchor checks only; retries revalidate.",
167
+ ].join("\n");
168
+ return boundDiagnostic(message, "\nAnchor-check output truncated at 16 KiB; omitted entries are not implied matched.");
169
+ }
170
+
171
+ /** Keep validation status and observation context visible even when failure details are truncated. */
172
+ function formatFailure(
173
+ failure: ApplyFailure,
174
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
175
+ ): string {
176
+ const candidateNeighborhoods = failure.kind === "anchor"
177
+ ? formatAmbiguousCandidateNeighborhoods(snapshot.currentText, failure.failures, snapshot.anchors)
178
+ : { text: "", shownLines: new Set<number>() };
179
+ const guidance = failure.kind === "anchor"
180
+ ? "\nCheck the intended target before retrying; use read or grep for omitted or additional context." : "";
181
+ return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}\n${formatAnchorChecks(failure, snapshot.anchors)}${candidateNeighborhoods.text}${guidance}`;
142
182
  }
143
183
 
144
184
  /** Translate JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
@@ -177,12 +217,12 @@ function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } |
177
217
  }
178
218
 
179
219
  /**
180
- * Format the updated anchors (fresh LINE#HASH│content) for the touched new-file
181
- * lines, so the model can chain edits without a re-read. Capped to bound tokens.
220
+ * Return compact tokens for changed caller-supplied rows, retaining content for deletion successors.
221
+ * Uses the applicator's final indices so mixed batches do not need a second position calculation.
182
222
  */
183
- function formatUpdatedAnchors(newText: string, touched: readonly number[], hashLen: number): string {
223
+ function formatUpdatedAnchors(before: string, newText: string, touched: readonly number[], contextLines: readonly number[], anchors: AnchorFormatter): string {
184
224
  const idxs = [...new Set(touched)].sort((a, b) => a - b);
185
- return formatMutationAnchors(splitLines(newText), idxs, hashLen, "Updated anchors (use these for the next edit):");
225
+ return formatMutationAnchors(splitLines(before), splitLines(newText), idxs, anchors, "Updated anchors:", new Set(contextLines));
186
226
  }
187
227
 
188
228
  /** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
@@ -202,24 +242,18 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
202
242
  name: "edit" as const,
203
243
  label: "edit",
204
244
  description:
205
- "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.",
245
+ "Edit file lines using content-verified anchors. Returns fresh anchors for subsequent edits. Anchor failures report input-anchor status and bounded current-file context. Inspect recovery candidates before retrying; retries always revalidate anchors and never run automatically.",
206
246
  promptSnippet: "Edit file lines using verified anchors",
207
247
  promptGuidelines: [
208
248
  "Batch changes to the same file in one edit call.",
209
- "Use the latest returned anchors for subsequent edits; read again only for lines not covered by those results.",
249
+ "Reuse prior anchors when their line number and content are unchanged. Re-read changed or shifted lines when no fresh anchor is available.",
210
250
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
211
251
  ],
212
252
  parameters,
213
253
  renderShell: "default" as const,
214
254
 
215
255
  renderCall(args: EditParams, theme: any, context: any) {
216
- const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
217
- // Stash the header for renderResult: the diff counts land after
218
- // execution and are refreshed in place (renderResult's lastComponent
219
- // is the result component, not this header)
220
- if (context?.state) context.state.callText = text;
221
- text.setText(editHeader(args, theme, context?.state?.diffCounts));
222
- return text;
256
+ return renderMutationCall(args, theme, context, editHeader);
223
257
  },
224
258
 
225
259
  renderResult(result: any, options: any, theme: any, context: any) {
@@ -242,14 +276,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
242
276
  (anchors) => { mutationAnchors = anchors; },
243
277
  ));
244
278
  };
245
- const finalizeMutation = (result: any, publishAnchors: boolean) => ({
246
- ...result,
247
- content: result.content.map((block: any, index: number) =>
248
- index === 0 && block.type === "text"
249
- ? { ...block, text: `${block.text}${publishAnchors ? mutationAnchors : ""}` }
250
- : block,
251
- ),
252
- });
279
+ const finalizeMutation = (result: any, publishAnchors: boolean) => appendMutationAnchors(result, mutationAnchors, publishAnchors);
253
280
  if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
254
281
  return fusion({
255
282
  toolCallId,
@@ -272,70 +299,34 @@ async function runHashline(
272
299
  signal: AbortSignal | undefined,
273
300
  onAnchors: (anchors: string) => void,
274
301
  ) {
275
- const { hashLen, shiftRadius } = getState().config;
302
+ const anchorFormatter = createAnchorFormatter();
303
+ const { shiftRadius } = getState().config;
276
304
 
277
- let currentText: string;
278
- let baseRevision: string;
279
- try {
280
- const currentBytes = await readFile(absPath);
281
- baseRevision = byteRevision(currentBytes);
282
- currentText = decodeEditableText(currentBytes);
283
- } catch (e) {
284
- const msg = e instanceof Error ? e.message : String(e);
285
- throw new Error(`Error reading ${displayPath}: ${msg}`);
286
- }
305
+ const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
287
306
  // Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
288
307
  if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before apply.`);
289
308
 
290
309
  const translated = toCoreEdits(editOps);
291
310
  if (!translated.ok) throw new Error(translated.error);
292
311
 
293
- // Anchors are verified against the current content. A line that changed (or a
294
- // hash the model didn't actually read) fails its own anchor — but first we try
295
- // shifted recovery: if the content merely moved within ±shiftRadius, a fresh
296
- // anchor is returned so the model can retry without a re-read. All failures in
297
- // the batch are collected (nothing written on any failure).
298
- const result = applyEdits(currentText, translated.edits, hashLen, shiftRadius);
312
+ // Recovery reports checksum candidates from nearby lines, then the whole file
313
+ // if needed. Every failed anchor still rejects the batch; callers inspect
314
+ // candidates and resubmit with fresh anchors.
315
+ const result = applyEdits(currentText, translated.edits, anchorFormatter.hashLen, shiftRadius);
299
316
  if (!result.ok) {
300
- throw new Error(formatFailure(result.failure, { currentText, hashLen }));
317
+ throw new Error(formatFailure(result.failure, { currentText, anchors: anchorFormatter }));
301
318
  }
302
319
 
303
320
  // Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
304
321
  if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before write.`);
305
322
 
306
- let publication: PublicationStatus = "NOT_PUBLISHED";
307
- let versions: MutationVersions;
308
- try {
309
- const commit = await commitFile(absPath, result.text, { mode: "overwrite", expectedRevision: baseRevision, signal });
310
- publication = commit.publication;
311
- versions = commit;
312
- } catch (e) {
313
- if (e instanceof FileMutationError) throw e;
314
- throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
315
- }
316
-
317
- let details: EditToolDetails & MutationVersions & { publication: PublicationStatus; revision: string };
318
- let anchors: string;
319
- try {
320
- // Diff and anchor generation happens after publication; preserve that state on failure.
321
- const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
322
- const newLf = result.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
323
- const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
324
- details = {
325
- diff,
326
- patch: generateUnifiedPatch(displayPath, oldLf, newLf),
327
- firstChangedLine,
328
- publication,
329
- ...versions,
330
- revision: versions.publishedRevision,
323
+ const versions = await commitReplacement(absPath, displayPath, result.text, baseRevision, signal);
324
+ return postProcessMutation("edit", versions.publication, () => {
325
+ const details = generateMutationDetails(displayPath, currentText, result.text, versions, versions.publication);
326
+ onAnchors(formatUpdatedAnchors(currentText, result.text, result.touchedLines, result.contextLines, anchorFormatter));
327
+ return {
328
+ content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)${result.changed ? "" : ", no net change"}).` }],
329
+ details,
331
330
  };
332
- anchors = formatUpdatedAnchors(result.text, result.touchedLines, hashLen);
333
- onAnchors(anchors);
334
- } catch (error) {
335
- throw new FileMutationError("post_process", publication, `file was published but edit result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
336
- }
337
- return {
338
- content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)).` }],
339
- details,
340
- };
331
+ });
341
332
  }