@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.
@@ -1,24 +1,16 @@
1
- import { computeLineHash } from "../core/hash.ts";
1
+ import type { AnchorFormatter } from "./anchor-format.ts";
2
2
  import { splitLines } from "../core/lines.ts";
3
3
  import type { AnchorFailure } from "../core/types.ts";
4
+ import { mergeRanges } from "../core/ranges.ts";
4
5
 
5
6
  const CONTEXT_RADIUS = 3;
6
- const MAX_CONTEXT_ROWS = 40;
7
7
  const MAX_CONTEXT_BYTES = 16 * 1024;
8
+ export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
9
+ export const MAX_AMBIGUOUS_CANDIDATES = 8;
8
10
 
9
11
  type Interval = { lo: number; hi: number };
10
12
  type ContextRow = { line: number; text: string };
11
13
 
12
- function mergeIntervals(intervals: Interval[]): Interval[] {
13
- const sorted = intervals.sort((a, b) => a.lo - b.lo || a.hi - b.hi);
14
- const merged: Interval[] = [];
15
- for (const interval of sorted) {
16
- const previous = merged.at(-1);
17
- if (previous && interval.lo <= previous.hi + 1) previous.hi = Math.max(previous.hi, interval.hi);
18
- else merged.push({ ...interval });
19
- }
20
- return merged;
21
- }
22
14
 
23
15
  function shownIntervals(rows: readonly ContextRow[]): Interval[] {
24
16
  const intervals: Interval[] = [];
@@ -30,69 +22,80 @@ function shownIntervals(rows: readonly ContextRow[]): Interval[] {
30
22
  return intervals;
31
23
  }
32
24
 
33
- /**
34
- * Format bounded current-file anchors for unrecoverable anchor failures.
35
- * @internal Used by the edit tool and focused tests; performs no I/O.
36
- */
37
- export function formatFailureContext(
38
- currentText: string,
39
- failures: readonly AnchorFailure[],
40
- hashLen: number,
41
- ): string {
42
- const unresolved = failures.filter((failure) => failure.recovery.kind === "none");
43
- if (unresolved.length === 0) return "";
44
-
45
- const lines = splitLines(currentText);
46
- const heading = [
47
- "Current-file context from the snapshot used for this check:",
48
- "Window: +/-3 lines around each clamped unresolved anchor.",
49
- "Limits: 40 rows; 16384 UTF-8 bytes of anchored row text.",
50
- ];
51
- if (lines.length === 0) {
52
- return `\n${heading.join("\n")}\nThe file is empty in the validation snapshot; no context anchors are available.`;
53
- }
54
-
55
- const windows = mergeIntervals(unresolved.map((failure) => {
56
- const center = Math.min(lines.length, Math.max(1, failure.cited.line));
57
- return { lo: Math.max(1, center - CONTEXT_RADIUS), hi: Math.min(lines.length, center + CONTEXT_RADIUS) };
25
+ function collectContextRows(
26
+ lines: readonly string[],
27
+ centers: readonly number[],
28
+ anchors: AnchorFormatter,
29
+ candidateLines: ReadonlySet<number>,
30
+ ) {
31
+ const windows = mergeRanges(centers.map((center) => {
32
+ const line = Math.min(lines.length, Math.max(1, center));
33
+ return [Math.max(1, line - CONTEXT_RADIUS), Math.min(lines.length, line + CONTEXT_RADIUS) + 1];
58
34
  }));
59
- const total = windows.reduce((sum, window) => sum + window.hi - window.lo + 1, 0);
35
+ const total = windows.reduce((sum, [start, end]) => sum + end - start, 0);
60
36
  const rows: ContextRow[] = [];
61
37
  let bytes = 0;
62
- let truncatedBy: "row limit" | "byte limit" | undefined;
38
+ const omissions = new Set<"byte limit" | "candidate row limit">();
63
39
 
64
- outer: for (const window of windows) {
65
- for (let line = window.lo; line <= window.hi; line++) {
66
- if (rows.length >= MAX_CONTEXT_ROWS) {
67
- truncatedBy = "row limit";
68
- break outer;
69
- }
40
+ for (const [start, end] of windows) {
41
+ for (let line = start; line < end; line++) {
70
42
  const content = lines[line - 1];
71
- const text = `${line}#${computeLineHash(line, content, hashLen)}│${content}`;
72
- const rowBytes = Buffer.byteLength(`${text}\n`, "utf8");
73
- if (bytes + rowBytes > MAX_CONTEXT_BYTES) {
74
- truncatedBy = "byte limit";
75
- break outer;
43
+ const text = anchors.row(line, content);
44
+ const rowBytes = Buffer.byteLength(text, "utf8");
45
+ // Neighborhoods must not bypass the standalone candidate's complete-row limit.
46
+ if (candidateLines.has(line) && rowBytes > MAX_RECOVERY_CANDIDATE_BYTES) {
47
+ omissions.add("candidate row limit");
48
+ continue;
49
+ }
50
+ if (bytes + rowBytes + 1 > MAX_CONTEXT_BYTES) {
51
+ omissions.add("byte limit");
52
+ continue;
76
53
  }
77
54
  rows.push({ line, text });
78
- bytes += rowBytes;
55
+ bytes += rowBytes + 1;
79
56
  }
80
57
  }
58
+ return { rows, total, truncatedBy: [...omissions].join(" and ") || undefined };
59
+ }
81
60
 
82
- const body: string[] = [...heading];
61
+ function formatContextRows(rows: readonly ContextRow[]): string[] {
62
+ const body: string[] = [];
63
+ let index = 0;
64
+ for (const interval of shownIntervals(rows)) {
65
+ body.push(`@@ candidate-neighborhood lines ${interval.lo}-${interval.hi} @@`);
66
+ while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
67
+ }
68
+ return body;
69
+ }
70
+
71
+ /**
72
+ * Format observation rows around listed ambiguous candidates and report rows actually shown.
73
+ * @internal Performs no I/O; the edit diagnostic uses shownLines to avoid repeating content.
74
+ */
75
+ export function formatAmbiguousCandidateNeighborhoods(
76
+ currentText: string,
77
+ failures: readonly AnchorFailure[],
78
+ anchors: AnchorFormatter,
79
+ ): { text: string; shownLines: ReadonlySet<number> } {
80
+ const centers = failures.flatMap((failure) => failure.recovery.kind === "ambiguous"
81
+ ? failure.recovery.candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES).map(candidate => candidate.line) : []);
82
+ if (centers.length === 0) return { text: "", shownLines: new Set() };
83
+
84
+ const lines = splitLines(currentText);
85
+ const candidateLines = new Set(centers);
86
+ for (const failure of failures) {
87
+ if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
88
+ }
89
+ const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
90
+ const body = ["Ambiguous-candidate neighborhoods (+/-3; observation only):"];
83
91
  if (rows.length === 0) {
84
- body.push("No context row fits the byte budget. Use read or grep for additional context.");
92
+ body.push("No complete neighborhood row fits the limits.");
85
93
  } else {
86
- let index = 0;
87
- for (const interval of shownIntervals(rows)) {
88
- body.push(`@@ lines ${interval.lo}-${interval.hi} @@`);
89
- while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
90
- }
94
+ body.push(...formatContextRows(rows));
95
+ }
96
+ if (truncatedBy) {
97
+ body.push(`Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`);
98
+ body.push(`Candidate neighborhoods truncated: ${truncatedBy} (16384 bytes; candidate row 4096 bytes; lowest lines first).`);
91
99
  }
92
- const omitted = total - rows.length;
93
- body.push(`Context rows: ${rows.length}/${total}; ${omitted} omitted.`);
94
- if (truncatedBy) body.push(`Context truncated: ${truncatedBy}. Lowest-line rows were kept first.`);
95
- body.push("Re-evaluate the edit against these lines; do not blindly replace the old anchor.");
96
- body.push("Use read or grep if the relevant lines are omitted or more context is needed.");
97
- return `\n${body.join("\n")}`;
100
+ return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
98
101
  }
@@ -22,7 +22,7 @@ test("published post-processing failure skips command and preserves publication
22
22
  const fusion = createActionFusionExecutor(async () => { commanded = true; return "never"; });
23
23
  await assert.rejects(
24
24
  fusion({ toolCallId: "published", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { throw new FileMutationError("post_process", "PUBLISHED", "file was published but result generation failed"); }, signal: undefined, ctx: context(dir), onUpdate: (update) => updates.push(update) }),
25
- (error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded,
25
+ (error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded && /Re-read before retrying/.test(error.message),
26
26
  );
27
27
  assert.ok(updates.every((update) => update.details.actionFusion.mutationCompleted === false));
28
28
  assert.equal(updates.at(-1).details.actionFusion.publication, "PUBLISHED");
@@ -34,7 +34,8 @@ test("command failure still reports final changed freshness", async () => withTe
34
34
  const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); throw new Error("command failed"); });
35
35
  const outcome: any = await fusion({ toolCallId: "failed", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { await writeFile(target, "mutation\n"); return result("mutation\n"); }, signal: undefined, ctx: context(dir) });
36
36
  assert.deepEqual(outcome.details.actionFusion, { publication: "PUBLISHED", command: "failed", freshness: "changed" });
37
- assert.match(outcome.content[1].text, /Re-read the file/);
37
+ assert.equal((outcome.content[1].text.match(/Re-read/g) ?? []).length, 1);
38
+ assert.match(outcome.content[1].text, /then_run:stale/);
38
39
  }));
39
40
 
40
41
  test("timeout and cancellation do not rerun mutation and still inspect freshness", async () => withTemp(async (dir) => {
@@ -226,3 +226,24 @@ test("commit rejects lossy UTF-8 output before modifying or creating files", asy
226
226
  assert.deepEqual(await readFile(existing), Buffer.from(content));
227
227
  assert.equal(result.publishedRevision, byteRevision(Buffer.from(content)));
228
228
  }));
229
+
230
+ test("identical commits preserve the file and still enforce mode, revision, and cancellation", async () => withTemp(async (dir) => {
231
+ const target = join(dir, "same.txt");
232
+ const content = "\uFEFFsame\r\nbytes\n";
233
+ await writeFile(target, content);
234
+ const before = await stat(target);
235
+ const revision = await fileRevision(target);
236
+ for (const mode of [undefined, "overwrite"] as const) {
237
+ const result = await commitFile(target, content, { mode, expectedRevision: revision });
238
+ assert.deepEqual(result, { created: false, baseRevision: revision, publishedRevision: revision, observedRevision: revision, revision, publication: "NOT_PUBLISHED" });
239
+ }
240
+ const after = await stat(target);
241
+ assert.deepEqual([after.ino, after.mtimeMs, after.ctimeMs], [before.ino, before.mtimeMs, before.ctimeMs]);
242
+ await assert.rejects(commitFile(target, content, { mode: "create" }), /already exists/);
243
+ await assert.rejects(commitFile(target, content, { expectedRevision: "stale" }), /expectedRevision/);
244
+ await assert.rejects(commitFile(target, content, { signal: AbortSignal.abort() }), (error: unknown) => error instanceof FileMutationError && error.publication === "NOT_PUBLISHED");
245
+ await assert.rejects(commitFile(join(dir, "missing"), "", { mode: "overwrite" }), /does not exist/);
246
+ const created = await commitFile(join(dir, "empty"), "");
247
+ assert.equal(created.created, true);
248
+ assert.equal(created.publication, "PUBLISHED");
249
+ }));
@@ -1,6 +1,7 @@
1
1
  import { chmod, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, link } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
+ import { decodeEditableText } from "../core/text.ts";
4
5
 
5
6
  export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
6
7
  export type CommitMode = "create" | "overwrite";
@@ -21,7 +22,7 @@ export interface CommitResult extends MutationVersions {
21
22
  created: boolean;
22
23
  /** Backward-compatible alias for publishedRevision. */
23
24
  revision: string;
24
- publication: "PUBLISHED";
25
+ publication: "NOT_PUBLISHED" | "PUBLISHED";
25
26
  }
26
27
 
27
28
  export class FileMutationError extends Error {
@@ -44,6 +45,26 @@ export async function fileRevision(path: string): Promise<string> {
44
45
  return byteRevision(await readFile(path));
45
46
  }
46
47
 
48
+ /** Decode and bind a mutation snapshot to the exact bytes read. */
49
+ export async function readEditableSnapshot(path: string, displayPath: string) {
50
+ try {
51
+ const bytes = await readFile(path);
52
+ return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
53
+ } catch (error) {
54
+ throw new Error(`Error reading ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
55
+ }
56
+ }
57
+
58
+ /** Publish a read-modify-write result against its source revision. Callers own the queue. */
59
+ export async function commitReplacement(path: string, displayPath: string, text: string, baseRevision: string, signal?: AbortSignal) {
60
+ try {
61
+ return await commitFile(path, text, { mode: "overwrite", expectedRevision: baseRevision, signal });
62
+ } catch (error) {
63
+ if (error instanceof FileMutationError) throw error;
64
+ throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
65
+ }
66
+ }
67
+
47
68
  function prepareError(message: string, cause?: unknown): FileMutationError {
48
69
  return new FileMutationError("prepare", "NOT_PUBLISHED", message, { cause });
49
70
  }
@@ -145,7 +166,7 @@ async function syncDirectory(path: string): Promise<void> {
145
166
  }
146
167
  }
147
168
 
148
- /** Prepare and sync exact UTF-8 bytes before publication; callers own the outer file queue. */
169
+ /** Validate the target, skip identical content, otherwise sync and publish. Callers own the file queue. */
149
170
  export async function commitFile(path: string, content: string, options: CommitOptions = {}): Promise<CommitResult> {
150
171
  if (content.includes("\0")) throw prepareError("UNSUPPORTED_TEXT: NUL bytes are not editable.");
151
172
  const bytes = Buffer.from(content, "utf8");
@@ -159,6 +180,18 @@ export async function commitFile(path: string, content: string, options: CommitO
159
180
  throw prepareError("expectedRevision does not match the current file");
160
181
  }
161
182
  try { options.signal?.throwIfAborted(); } catch (error) { throw prepareError("mutation was cancelled before publication", error); }
183
+ const publishedRevision = byteRevision(bytes);
184
+ // Mode, revision, target safety, and cancellation checks still apply to no-ops.
185
+ if (target.beforeRevision === publishedRevision) {
186
+ return {
187
+ created: false,
188
+ baseRevision: target.beforeRevision,
189
+ publishedRevision,
190
+ observedRevision: target.beforeRevision,
191
+ revision: publishedRevision,
192
+ publication: "NOT_PUBLISHED",
193
+ };
194
+ }
162
195
 
163
196
  const publishPath = target.publishPath;
164
197
  const publishDirectory = dirname(publishPath);
@@ -188,7 +221,6 @@ export async function commitFile(path: string, content: string, options: CommitO
188
221
  published = true;
189
222
  await syncDirectory(publishDirectory);
190
223
  try {
191
- const publishedRevision = byteRevision(bytes);
192
224
  const observedRevision = await fileRevision(publishPath);
193
225
  return {
194
226
  created: mode === "create",