@criogaid/pi-hashline-edit 0.1.0 → 0.1.2
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.
- package/README.md +168 -197
- package/package.json +1 -1
- package/src/core/apply.test.ts +40 -1
- package/src/core/apply.ts +13 -3
- package/src/core/hash.test.ts +7 -3
- package/src/core/hash.ts +6 -10
- package/src/core/index.ts +1 -0
- package/src/core/text.test.ts +15 -0
- package/src/core/text.ts +18 -0
- package/src/core/types.ts +1 -2
- package/src/index.ts +4 -3
- package/src/integration/grep-rg.test.ts +47 -0
- package/src/pi/action-fusion.test.ts +7 -5
- package/src/pi/action-fusion.ts +39 -18
- package/src/pi/config.test.ts +23 -0
- package/src/pi/config.ts +6 -4
- package/src/pi/edit-tool.ts +44 -70
- package/src/pi/execute.test.ts +50 -1
- package/src/pi/failure-path.test.ts +10 -7
- package/src/pi/file-commit.test.ts +29 -1
- package/src/pi/file-commit.ts +39 -7
- package/src/pi/fusion-card.test.ts +1 -1
- package/src/pi/grep-tool.ts +82 -40
- package/src/pi/grep.test.ts +54 -9
- package/src/pi/mutation-result.ts +46 -0
- package/src/pi/read-tool.ts +4 -4
- package/src/pi/registration.test.ts +55 -8
- package/src/pi/render.ts +51 -1
- package/src/pi/replace-tool.ts +34 -44
- package/src/pi/result-safety.test.ts +169 -0
- package/src/pi/write-tool.ts +12 -2
- package/src/pi/write.test.ts +7 -1
package/src/pi/edit-tool.ts
CHANGED
|
@@ -19,22 +19,23 @@
|
|
|
19
19
|
* @module pi-hashline-edit/pi
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import { generateDiffString, generateUnifiedPatch, withFileMutationQueue, type EditToolDetails } from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { generateDiffString, generateUnifiedPatch, truncateHead, withFileMutationQueue, type EditToolDetails } from "@earendil-works/pi-coding-agent";
|
|
23
23
|
import { Type, type Static } from "typebox";
|
|
24
24
|
import { Text } from "@earendil-works/pi-tui";
|
|
25
25
|
import { readFile } from "node:fs/promises";
|
|
26
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,
|
|
27
|
+
import { byteRevision, commitFile, FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
|
|
28
|
+
import { applyEdits, decodeEditableText } from "../core/index.ts";
|
|
29
29
|
import { splitLines } from "../core/lines.ts";
|
|
30
30
|
import type { ApplyFailure, Edit } from "../core/types.ts";
|
|
31
31
|
import { canonicalPath } from "./read-tool.ts";
|
|
32
32
|
import { getState } from "./state.ts";
|
|
33
|
-
import { formatDiffCounts,
|
|
33
|
+
import { formatDiffCounts, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
34
34
|
import { formatFailureContext } from "./failure-context.ts";
|
|
35
|
+
import { finalizeMutationResult, formatMutationAnchors } from "./mutation-result.ts";
|
|
35
36
|
|
|
36
|
-
/**
|
|
37
|
-
const
|
|
37
|
+
/** Bound detailed failures before constructing diagnostics; the final message also has a byte cap. */
|
|
38
|
+
const MAX_FAILURE_DETAILS = 40;
|
|
38
39
|
|
|
39
40
|
const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
|
|
40
41
|
|
|
@@ -74,7 +75,7 @@ const editOpSchema = Type.Object({
|
|
|
74
75
|
end: anchorRef(
|
|
75
76
|
'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
|
),
|
|
77
|
-
body: Type.Optional(Type.Array(Type.String(), { description: "New content lines (required for replace/insert/append/prepend; omit for delete)" })),
|
|
78
|
+
body: Type.Optional(Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), { description: "New content lines (required for replace/insert/append/prepend; each element must be one logical line without CR/LF; omit for delete)" })),
|
|
78
79
|
});
|
|
79
80
|
|
|
80
81
|
function createEditSchema(actionFusion: boolean) {
|
|
@@ -95,29 +96,29 @@ function formatFailure(
|
|
|
95
96
|
failure: ApplyFailure,
|
|
96
97
|
snapshot: Readonly<{ currentText: string; hashLen: number }>,
|
|
97
98
|
): string {
|
|
98
|
-
if (failure.kind
|
|
99
|
-
if (failure.kind === "noop") return failure.message;
|
|
99
|
+
if (failure.kind !== "anchor") return failure.message;
|
|
100
100
|
|
|
101
101
|
const lines: string[] = [];
|
|
102
102
|
let found = 0;
|
|
103
103
|
let ambiguous = 0;
|
|
104
104
|
let none = 0;
|
|
105
105
|
for (const f of failure.failures) {
|
|
106
|
+
if (f.recovery.kind === "found") found++;
|
|
107
|
+
else if (f.recovery.kind === "ambiguous") ambiguous++;
|
|
108
|
+
else none++;
|
|
109
|
+
if (lines.length >= MAX_FAILURE_DETAILS) continue;
|
|
106
110
|
const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
|
|
107
111
|
switch (f.recovery.kind) {
|
|
108
112
|
case "found":
|
|
109
|
-
|
|
110
|
-
lines.push(`• ${where}: content shifted. Resend with ${f.which} "${f.recovery.newLine}#${f.recovery.newHash}".`);
|
|
113
|
+
lines.push(`• ${where}: checksum-matching candidate. Resend with ${f.which} "${f.recovery.newLine}#${f.recovery.newHash}" after checking the target.`);
|
|
111
114
|
break;
|
|
112
115
|
case "ambiguous": {
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
lines.push(`• ${where}: ambiguous — same content at lines ${nums}. Pick the right one and resend ${f.which} ${list}.`);
|
|
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}.`);
|
|
117
119
|
break;
|
|
118
120
|
}
|
|
119
121
|
case "none":
|
|
120
|
-
none++;
|
|
121
122
|
lines.push(
|
|
122
123
|
`• ${where}: original content not found within the configured shift-recovery window.` +
|
|
123
124
|
(f.current === null ? " Cited line is out of range." : ""),
|
|
@@ -129,11 +130,15 @@ function formatFailure(
|
|
|
129
130
|
if (found) parts.push(`${found} shifted`);
|
|
130
131
|
if (ambiguous) parts.push(`${ambiguous} ambiguous`);
|
|
131
132
|
if (none) parts.push(`${none} unresolved`);
|
|
132
|
-
|
|
133
|
+
const message = [
|
|
133
134
|
`Anchor mismatch: ${parts.join(", ")}.`,
|
|
134
135
|
"No changes written by this edit batch.",
|
|
135
136
|
...lines,
|
|
137
|
+
...(failure.failures.length > lines.length ? [`${failure.failures.length - lines.length} failure details omitted; use read to inspect remaining targets.`] : []),
|
|
136
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 : "");
|
|
137
142
|
}
|
|
138
143
|
|
|
139
144
|
/** Translate JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
|
|
@@ -171,31 +176,13 @@ function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } |
|
|
|
171
176
|
return { ok: true, edits };
|
|
172
177
|
}
|
|
173
178
|
|
|
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
179
|
/**
|
|
187
180
|
* Format the updated anchors (fresh LINE#HASH│content) for the touched new-file
|
|
188
181
|
* lines, so the model can chain edits without a re-read. Capped to bound tokens.
|
|
189
182
|
*/
|
|
190
183
|
function formatUpdatedAnchors(newText: string, touched: readonly number[], hashLen: number): string {
|
|
191
|
-
const newLines = splitLines(newText);
|
|
192
|
-
const newHashes = hashFileLines(newLines, hashLen);
|
|
193
184
|
const idxs = [...new Set(touched)].sort((a, b) => a - b);
|
|
194
|
-
|
|
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}`;
|
|
185
|
+
return formatMutationAnchors(splitLines(newText), idxs, hashLen, "Updated anchors (use these for the next edit):");
|
|
199
186
|
}
|
|
200
187
|
|
|
201
188
|
/** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
|
|
@@ -235,29 +222,8 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
235
222
|
return text;
|
|
236
223
|
},
|
|
237
224
|
|
|
238
|
-
renderResult(result: any,
|
|
239
|
-
|
|
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);
|
|
225
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
226
|
+
return renderMutationResult(result, options, theme, context, "Editing…", "Edited", editHeader);
|
|
261
227
|
},
|
|
262
228
|
|
|
263
229
|
async execute(toolCallId: string, params: EditParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
|
|
@@ -267,7 +233,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
267
233
|
let mutationAnchors = "";
|
|
268
234
|
const mutate = () => {
|
|
269
235
|
const path = mutationParams.path;
|
|
270
|
-
if (!mutationParams.edits?.length)
|
|
236
|
+
if (!mutationParams.edits?.length) throw new Error(`Edit ${path}: \`edits\` is empty or missing.`);
|
|
271
237
|
return withFileMutationQueue(absolutePath, () => runHashline(
|
|
272
238
|
absolutePath,
|
|
273
239
|
path,
|
|
@@ -284,7 +250,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
284
250
|
: block,
|
|
285
251
|
),
|
|
286
252
|
});
|
|
287
|
-
if (!fusion) return
|
|
253
|
+
if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
|
|
288
254
|
return fusion({
|
|
289
255
|
toolCallId,
|
|
290
256
|
absolutePath,
|
|
@@ -309,17 +275,20 @@ async function runHashline(
|
|
|
309
275
|
const { hashLen, shiftRadius } = getState().config;
|
|
310
276
|
|
|
311
277
|
let currentText: string;
|
|
278
|
+
let baseRevision: string;
|
|
312
279
|
try {
|
|
313
|
-
|
|
280
|
+
const currentBytes = await readFile(absPath);
|
|
281
|
+
baseRevision = byteRevision(currentBytes);
|
|
282
|
+
currentText = decodeEditableText(currentBytes);
|
|
314
283
|
} catch (e) {
|
|
315
284
|
const msg = e instanceof Error ? e.message : String(e);
|
|
316
|
-
|
|
285
|
+
throw new Error(`Error reading ${displayPath}: ${msg}`);
|
|
317
286
|
}
|
|
318
287
|
// Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
|
|
319
|
-
if (signal?.aborted)
|
|
288
|
+
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before apply.`);
|
|
320
289
|
|
|
321
290
|
const translated = toCoreEdits(editOps);
|
|
322
|
-
if (!translated.ok)
|
|
291
|
+
if (!translated.ok) throw new Error(translated.error);
|
|
323
292
|
|
|
324
293
|
// Anchors are verified against the current content. A line that changed (or a
|
|
325
294
|
// hash the model didn't actually read) fails its own anchor — but first we try
|
|
@@ -328,24 +297,27 @@ async function runHashline(
|
|
|
328
297
|
// the batch are collected (nothing written on any failure).
|
|
329
298
|
const result = applyEdits(currentText, translated.edits, hashLen, shiftRadius);
|
|
330
299
|
if (!result.ok) {
|
|
331
|
-
|
|
300
|
+
throw new Error(formatFailure(result.failure, { currentText, hashLen }));
|
|
332
301
|
}
|
|
333
302
|
|
|
334
303
|
// Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
|
|
335
|
-
if (signal?.aborted)
|
|
304
|
+
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before write.`);
|
|
336
305
|
|
|
337
306
|
let publication: PublicationStatus = "NOT_PUBLISHED";
|
|
307
|
+
let versions: MutationVersions;
|
|
338
308
|
try {
|
|
339
|
-
|
|
309
|
+
const commit = await commitFile(absPath, result.text, { mode: "overwrite", expectedRevision: baseRevision, signal });
|
|
310
|
+
publication = commit.publication;
|
|
311
|
+
versions = commit;
|
|
340
312
|
} catch (e) {
|
|
341
313
|
if (e instanceof FileMutationError) throw e;
|
|
342
314
|
throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
343
315
|
}
|
|
344
316
|
|
|
345
|
-
let details: EditToolDetails & { publication: PublicationStatus };
|
|
317
|
+
let details: EditToolDetails & MutationVersions & { publication: PublicationStatus; revision: string };
|
|
346
318
|
let anchors: string;
|
|
347
319
|
try {
|
|
348
|
-
//
|
|
320
|
+
// Diff and anchor generation happens after publication; preserve that state on failure.
|
|
349
321
|
const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
350
322
|
const newLf = result.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
351
323
|
const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
|
|
@@ -354,6 +326,8 @@ async function runHashline(
|
|
|
354
326
|
patch: generateUnifiedPatch(displayPath, oldLf, newLf),
|
|
355
327
|
firstChangedLine,
|
|
356
328
|
publication,
|
|
329
|
+
...versions,
|
|
330
|
+
revision: versions.publishedRevision,
|
|
357
331
|
};
|
|
358
332
|
anchors = formatUpdatedAnchors(result.text, result.touchedLines, hashLen);
|
|
359
333
|
onAnchors(anchors);
|
package/src/pi/execute.test.ts
CHANGED
|
@@ -19,6 +19,7 @@ import { createActionFusionExecutor } from "./action-fusion.ts";
|
|
|
19
19
|
import { getState } from "./state.ts";
|
|
20
20
|
import { computeLineHash } from "../core/hash.ts";
|
|
21
21
|
import { splitLines } from "../core/lines.ts";
|
|
22
|
+
import { byteRevision } from "./file-commit.ts";
|
|
22
23
|
|
|
23
24
|
async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
|
24
25
|
const dir = await mkdtemp(join(tmpdir(), "hl-"));
|
|
@@ -517,5 +518,53 @@ test("failed commands preserve mutation results and stay out of all main card re
|
|
|
517
518
|
assert.doesNotMatch(rendered.render(120).join("\n"), /command-only diagnostic|then_run:failed/);
|
|
518
519
|
assert.equal(await readFile(join(dir, args.path), "utf8"), expected);
|
|
519
520
|
}
|
|
520
|
-
assert.deepEqual(commands,
|
|
521
|
+
assert.deepEqual(commands, cases.flatMap(() => ["waiting", "waiting", "running", "failed"]));
|
|
522
|
+
}));
|
|
523
|
+
|
|
524
|
+
test("text tools reject malformed UTF-8 and NUL bytes without rewriting source bytes", async () => withDir(async (dir) => {
|
|
525
|
+
const target = join(dir, "invalid-utf8.txt");
|
|
526
|
+
const original = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
|
|
527
|
+
await writeFile(target, original);
|
|
528
|
+
await assert.rejects(call(makeReadOverride(dir), { path: "invalid-utf8.txt" }), /UNSUPPORTED_ENCODING/);
|
|
529
|
+
await assert.rejects(call(makeEditOverride(dir), { path: "invalid-utf8.txt", edits: [{ op: "append", body: ["x"] }] }), /UNSUPPORTED_ENCODING/);
|
|
530
|
+
await assert.rejects(call(makeReplaceTool(dir), { path: "invalid-utf8.txt", find: "a", replace: "b" }), /UNSUPPORTED_ENCODING/);
|
|
531
|
+
assert.deepEqual(await readFile(target), original);
|
|
532
|
+
|
|
533
|
+
const nulTarget = join(dir, "nul.txt");
|
|
534
|
+
const nulOriginal = Buffer.from([0x61, 0x00, 0x62]);
|
|
535
|
+
await writeFile(nulTarget, nulOriginal);
|
|
536
|
+
await assert.rejects(call(makeEditOverride(dir), { path: "nul.txt", edits: [{ op: "append", body: ["x"] }] }), /UNSUPPORTED_TEXT/);
|
|
537
|
+
await assert.rejects(call(makeReplaceTool(dir), { path: "nul.txt", find: "a", replace: "b" }), /UNSUPPORTED_TEXT/);
|
|
538
|
+
assert.deepEqual(await readFile(nulTarget), nulOriginal);
|
|
539
|
+
}));
|
|
540
|
+
|
|
541
|
+
test("edit rejects embedded line terminators even when schema validation is bypassed", async () => withDir(async (dir) => {
|
|
542
|
+
const target = join(dir, "body.txt");
|
|
543
|
+
await writeFile(target, "a\n");
|
|
544
|
+
await assert.rejects(call(makeEditOverride(dir), { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] }), /INVALID_BODY/);
|
|
545
|
+
assert.equal(await readFile(target, "utf8"), "a\n");
|
|
546
|
+
assert.throws(() => validateToolArguments(makeEditOverride(dir) as any, { type: "toolCall", id: "body", name: "edit", arguments: { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] } }));
|
|
547
|
+
}));
|
|
548
|
+
|
|
549
|
+
test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () => withDir(async (dir) => {
|
|
550
|
+
const target = join(dir, "bom.txt");
|
|
551
|
+
const original = Buffer.from("\ufeffguard\nold\n", "utf8");
|
|
552
|
+
await writeFile(target, original);
|
|
553
|
+
const result: any = await call(makeEditOverride(dir), { path: "bom.txt", edits: [{ op: "replace", anchor: h("\ufeffguard\nold\n", 2), body: ["new"] }] });
|
|
554
|
+
const expected = Buffer.from("\ufeffguard\nnew\n", "utf8");
|
|
555
|
+
assert.deepEqual(await readFile(target), expected);
|
|
556
|
+
assert.equal(result.details.baseRevision, byteRevision(original));
|
|
557
|
+
assert.equal(result.details.publishedRevision, byteRevision(expected));
|
|
558
|
+
assert.equal(result.details.observedRevision, result.details.publishedRevision);
|
|
559
|
+
assert.equal(result.details.revision, result.details.publishedRevision);
|
|
560
|
+
}));
|
|
561
|
+
|
|
562
|
+
test("edit and replace reject NUL output without rewriting source bytes", async () => withDir(async (dir) => {
|
|
563
|
+
const target = join(dir, "output.txt");
|
|
564
|
+
const original = Buffer.from("\ufeffbefore\r\n", "utf8");
|
|
565
|
+
await writeFile(target, original);
|
|
566
|
+
await assert.rejects(call(makeEditOverride(dir), { path: "output.txt", edits: [{ op: "append", body: ["bad\0text"] }] }), /UNSUPPORTED_TEXT/);
|
|
567
|
+
assert.deepEqual(await readFile(target), original);
|
|
568
|
+
await assert.rejects(call(makeReplaceTool(dir), { path: "output.txt", find: "before", replace: "bad\0text" }), /UNSUPPORTED_TEXT/);
|
|
569
|
+
assert.deepEqual(await readFile(target), original);
|
|
521
570
|
}));
|
|
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { test } from "node:test";
|
|
6
6
|
import { createActionFusionExecutor, ActionFusionError } from "./action-fusion.ts";
|
|
7
|
-
import { FileMutationError } from "./file-commit.ts";
|
|
7
|
+
import { byteRevision, FileMutationError } from "./file-commit.ts";
|
|
8
8
|
|
|
9
9
|
async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
10
10
|
const dir = await mkdtemp(join(tmpdir(), "hashline-failure-"));
|
|
@@ -12,24 +12,27 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
const context = (cwd: string) => ({ cwd }) as any;
|
|
15
|
-
const result = () => ({ content: [{ type: "text" as const, text: "mutation" }], details: { publication: "PUBLISHED" } });
|
|
15
|
+
const result = (content: string) => ({ content: [{ type: "text" as const, text: "mutation" }], details: { publication: "PUBLISHED", publishedRevision: byteRevision(content) } });
|
|
16
16
|
|
|
17
17
|
test("published post-processing failure skips command and preserves publication state", async () => withTemp(async (dir) => {
|
|
18
18
|
const target = join(dir, "published.txt");
|
|
19
19
|
await writeFile(target, "content\n");
|
|
20
20
|
let commanded = false;
|
|
21
|
+
const updates: any[] = [];
|
|
21
22
|
const fusion = createActionFusionExecutor(async () => { commanded = true; return "never"; });
|
|
22
23
|
await assert.rejects(
|
|
23
|
-
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) }),
|
|
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) }),
|
|
24
25
|
(error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded,
|
|
25
26
|
);
|
|
27
|
+
assert.ok(updates.every((update) => update.details.actionFusion.mutationCompleted === false));
|
|
28
|
+
assert.equal(updates.at(-1).details.actionFusion.publication, "PUBLISHED");
|
|
26
29
|
}));
|
|
27
30
|
|
|
28
31
|
test("command failure still reports final changed freshness", async () => withTemp(async (dir) => {
|
|
29
32
|
const target = join(dir, "failed.txt");
|
|
30
33
|
await writeFile(target, "before\n");
|
|
31
34
|
const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); throw new Error("command failed"); });
|
|
32
|
-
const outcome: any = await fusion({ toolCallId: "failed", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { await writeFile(target, "mutation\n"); return result(); }, signal: undefined, ctx: context(dir) });
|
|
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) });
|
|
33
36
|
assert.deepEqual(outcome.details.actionFusion, { publication: "PUBLISHED", command: "failed", freshness: "changed" });
|
|
34
37
|
assert.match(outcome.content[1].text, /Re-read the file/);
|
|
35
38
|
}));
|
|
@@ -40,7 +43,7 @@ test("timeout and cancellation do not rerun mutation and still inspect freshness
|
|
|
40
43
|
let mutations = 0;
|
|
41
44
|
const controller = new AbortController();
|
|
42
45
|
const fusion = createActionFusionExecutor(async () => { controller.abort(); throw new Error("timed out"); });
|
|
43
|
-
const outcome: any = await fusion({ toolCallId: "cancelled", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { mutations++; await writeFile(target, "mutation\n"); return result(); }, signal: controller.signal, ctx: context(dir) });
|
|
46
|
+
const outcome: any = await fusion({ toolCallId: "cancelled", absolutePath: target, thenRun: { command: "check" }, mutate: async () => { mutations++; await writeFile(target, "mutation\n"); return result("mutation\n"); }, signal: controller.signal, ctx: context(dir) });
|
|
44
47
|
assert.equal(outcome.details.actionFusion.command, "cancelled");
|
|
45
48
|
assert.equal(outcome.details.actionFusion.freshness, "unchanged");
|
|
46
49
|
assert.equal(mutations, 1);
|
|
@@ -51,10 +54,10 @@ test("queue is released after a failed command", async () => withTemp(async (dir
|
|
|
51
54
|
await writeFile(target, "before\n");
|
|
52
55
|
let calls = 0;
|
|
53
56
|
const fusion = createActionFusionExecutor(async () => { calls++; if (calls === 1) throw new Error("first command failed"); return "ok"; });
|
|
54
|
-
const first = fusion({ toolCallId: "first", absolutePath: target, thenRun: { command: "fail" }, mutate: async () => { await writeFile(target, "first\n"); return result(); }, signal: undefined, ctx: context(dir) });
|
|
57
|
+
const first = fusion({ toolCallId: "first", absolutePath: target, thenRun: { command: "fail" }, mutate: async () => { await writeFile(target, "first\n"); return result("first\n"); }, signal: undefined, ctx: context(dir) });
|
|
55
58
|
const failed: any = await first;
|
|
56
59
|
assert.equal(failed.details.actionFusion.command, "failed");
|
|
57
|
-
const second = await fusion({ toolCallId: "second", absolutePath: target, thenRun: { command: "ok" }, mutate: async () => { await writeFile(target, "second\n"); return result(); }, signal: undefined, ctx: context(dir) });
|
|
60
|
+
const second = await fusion({ toolCallId: "second", absolutePath: target, thenRun: { command: "ok" }, mutate: async () => { await writeFile(target, "second\n"); return result("second\n"); }, signal: undefined, ctx: context(dir) });
|
|
58
61
|
assert.equal(calls, 2);
|
|
59
62
|
assert.match(second.content[1].type === "text" ? second.content[1].text : "", /then_run:succeeded/);
|
|
60
63
|
}));
|
|
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { test } from "node:test";
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
|
-
import { commitFile, FileMutationError, fileRevision } from "./file-commit.ts";
|
|
7
|
+
import { byteRevision, commitFile, FileMutationError, fileRevision } from "./file-commit.ts";
|
|
8
8
|
import { createActionFusionExecutor } from "./action-fusion.ts";
|
|
9
9
|
import { makeWriteOverride } from "./write-tool.ts";
|
|
10
10
|
|
|
@@ -198,3 +198,31 @@ test("cancellation racing publication never reports a settled operation as unpub
|
|
|
198
198
|
const finalContent = await readFile(target, "utf8");
|
|
199
199
|
assert.ok(finalContent === oldContent || finalContent === newContent);
|
|
200
200
|
}));
|
|
201
|
+
|
|
202
|
+
test("commit result binds base, published, and observed revisions", async () => withTemp(async (dir) => {
|
|
203
|
+
const target = join(dir, "versions.txt");
|
|
204
|
+
await writeFile(target, "before\n");
|
|
205
|
+
const baseRevision = await fileRevision(target);
|
|
206
|
+
const result = await commitFile(target, "after\n", { mode: "overwrite", expectedRevision: baseRevision });
|
|
207
|
+
assert.equal(result.baseRevision, baseRevision);
|
|
208
|
+
assert.equal(result.publishedRevision, byteRevision("after\n"));
|
|
209
|
+
assert.equal(result.observedRevision, result.publishedRevision);
|
|
210
|
+
assert.equal(result.revision, result.publishedRevision);
|
|
211
|
+
}));
|
|
212
|
+
|
|
213
|
+
test("commit rejects lossy UTF-8 output before modifying or creating files", async () => withTemp(async (dir) => {
|
|
214
|
+
const existing = join(dir, "existing.txt");
|
|
215
|
+
const missing = join(dir, "missing.txt");
|
|
216
|
+
await writeFile(existing, "original\n");
|
|
217
|
+
for (const content of ["\ud800", "\udfff", "before\ud800after"]) {
|
|
218
|
+
for (const path of [existing, missing]) {
|
|
219
|
+
await assert.rejects(commitFile(path, content), (error: any) => error.publication === "NOT_PUBLISHED" && /INVALID_UNICODE/.test(error.message));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
assert.equal(await readFile(existing, "utf8"), "original\n");
|
|
223
|
+
await assert.rejects(readFile(missing), { code: "ENOENT" });
|
|
224
|
+
const content = "\uFEFFvalid 😀\r\n";
|
|
225
|
+
const result = await commitFile(existing, content);
|
|
226
|
+
assert.deepEqual(await readFile(existing), Buffer.from(content));
|
|
227
|
+
assert.equal(result.publishedRevision, byteRevision(Buffer.from(content)));
|
|
228
|
+
}));
|
package/src/pi/file-commit.ts
CHANGED
|
@@ -11,8 +11,15 @@ export interface CommitOptions {
|
|
|
11
11
|
signal?: AbortSignal;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
export interface
|
|
14
|
+
export interface MutationVersions {
|
|
15
|
+
baseRevision?: string;
|
|
16
|
+
publishedRevision: string;
|
|
17
|
+
observedRevision: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CommitResult extends MutationVersions {
|
|
15
21
|
created: boolean;
|
|
22
|
+
/** Backward-compatible alias for publishedRevision. */
|
|
16
23
|
revision: string;
|
|
17
24
|
publication: "PUBLISHED";
|
|
18
25
|
}
|
|
@@ -29,8 +36,12 @@ export class FileMutationError extends Error {
|
|
|
29
36
|
}
|
|
30
37
|
}
|
|
31
38
|
|
|
39
|
+
export function byteRevision(content: string | Uint8Array): string {
|
|
40
|
+
return createHash("sha256").update(content).digest("hex");
|
|
41
|
+
}
|
|
42
|
+
|
|
32
43
|
export async function fileRevision(path: string): Promise<string> {
|
|
33
|
-
return
|
|
44
|
+
return byteRevision(await readFile(path));
|
|
34
45
|
}
|
|
35
46
|
|
|
36
47
|
function prepareError(message: string, cause?: unknown): FileMutationError {
|
|
@@ -89,11 +100,11 @@ async function inspectTarget(path: string): Promise<TargetInfo> {
|
|
|
89
100
|
};
|
|
90
101
|
}
|
|
91
102
|
|
|
92
|
-
async function writeAndSyncTemp(tempPath: string, content:
|
|
103
|
+
async function writeAndSyncTemp(tempPath: string, content: Buffer, modeBits: number | undefined, signal: AbortSignal | undefined): Promise<void> {
|
|
93
104
|
signal?.throwIfAborted();
|
|
94
105
|
const handle = await open(tempPath, "w", modeBits === undefined ? 0o600 : modeBits & 0o7777);
|
|
95
106
|
try {
|
|
96
|
-
await handle.writeFile(content
|
|
107
|
+
await handle.writeFile(content);
|
|
97
108
|
await handle.sync();
|
|
98
109
|
} finally {
|
|
99
110
|
await handle.close();
|
|
@@ -134,8 +145,11 @@ async function syncDirectory(path: string): Promise<void> {
|
|
|
134
145
|
}
|
|
135
146
|
}
|
|
136
147
|
|
|
137
|
-
/**
|
|
148
|
+
/** Prepare and sync exact UTF-8 bytes before publication; callers own the outer file queue. */
|
|
138
149
|
export async function commitFile(path: string, content: string, options: CommitOptions = {}): Promise<CommitResult> {
|
|
150
|
+
if (content.includes("\0")) throw prepareError("UNSUPPORTED_TEXT: NUL bytes are not editable.");
|
|
151
|
+
const bytes = Buffer.from(content, "utf8");
|
|
152
|
+
if (bytes.toString("utf8") !== content) throw prepareError("INVALID_UNICODE: content cannot be encoded losslessly as UTF-8.");
|
|
139
153
|
const target = await inspectTarget(path);
|
|
140
154
|
const mode = options.mode ?? (target.existed ? "overwrite" : "create");
|
|
141
155
|
if (mode === "create" && target.existed) throw prepareError("target already exists; use mode=overwrite");
|
|
@@ -159,13 +173,31 @@ export async function commitFile(path: string, content: string, options: CommitO
|
|
|
159
173
|
let published = false;
|
|
160
174
|
let failure: unknown;
|
|
161
175
|
try {
|
|
162
|
-
await writeAndSyncTemp(tempPath,
|
|
176
|
+
await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
|
|
177
|
+
if (mode === "overwrite" && options.expectedRevision !== undefined) {
|
|
178
|
+
let currentRevision: string;
|
|
179
|
+
try {
|
|
180
|
+
currentRevision = await fileRevision(publishPath);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
throw prepareError(`unable to recheck target revision: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
183
|
+
}
|
|
184
|
+
if (currentRevision !== options.expectedRevision) throw prepareError("expectedRevision changed before publication");
|
|
185
|
+
}
|
|
163
186
|
if (mode === "create") await publishCreate(tempPath, publishPath, options.signal);
|
|
164
187
|
else await publishReplace(tempPath, publishPath, options.signal);
|
|
165
188
|
published = true;
|
|
166
189
|
await syncDirectory(publishDirectory);
|
|
167
190
|
try {
|
|
168
|
-
|
|
191
|
+
const publishedRevision = byteRevision(bytes);
|
|
192
|
+
const observedRevision = await fileRevision(publishPath);
|
|
193
|
+
return {
|
|
194
|
+
created: mode === "create",
|
|
195
|
+
baseRevision: target.beforeRevision,
|
|
196
|
+
publishedRevision,
|
|
197
|
+
observedRevision,
|
|
198
|
+
revision: publishedRevision,
|
|
199
|
+
publication: "PUBLISHED",
|
|
200
|
+
};
|
|
169
201
|
} catch (error) {
|
|
170
202
|
throw new FileMutationError("post_process", "PUBLISHED", `target was published but final revision could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
171
203
|
}
|
|
@@ -32,7 +32,7 @@ function harness(entries: any[] = []) {
|
|
|
32
32
|
|
|
33
33
|
const waiting: ActionFusionProgress = {
|
|
34
34
|
toolCallId: "call-1", path: "file.ts", commandText: "npm test", command: "waiting",
|
|
35
|
-
publication: "NOT_PUBLISHED", freshness: "unknown", output: "",
|
|
35
|
+
publication: "NOT_PUBLISHED", freshness: "unknown", output: "", mutationCompleted: false,
|
|
36
36
|
};
|
|
37
37
|
|
|
38
38
|
test("one independent card updates live and only persists its endpoints", () => {
|