@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.
- package/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +50 -0
- package/src/core/apply.test.ts +327 -0
- package/src/core/apply.ts +264 -0
- package/src/core/hash.test.ts +54 -0
- package/src/core/hash.ts +68 -0
- package/src/core/index.ts +13 -0
- package/src/core/lines.test.ts +33 -0
- package/src/core/lines.ts +52 -0
- package/src/core/types.ts +87 -0
- package/src/index.ts +44 -0
- package/src/integration/grep-rg.test.ts +390 -0
- package/src/pi/action-fusion.test.ts +244 -0
- package/src/pi/action-fusion.ts +284 -0
- package/src/pi/config.test.ts +22 -0
- package/src/pi/config.ts +56 -0
- package/src/pi/edit-tool.ts +367 -0
- package/src/pi/execute.test.ts +521 -0
- package/src/pi/failure-context.test.ts +88 -0
- package/src/pi/failure-context.ts +98 -0
- package/src/pi/failure-path.test.ts +60 -0
- package/src/pi/file-commit.test.ts +200 -0
- package/src/pi/file-commit.ts +185 -0
- package/src/pi/fusion-card.test.ts +69 -0
- package/src/pi/fusion-card.ts +78 -0
- package/src/pi/grep-tool.ts +795 -0
- package/src/pi/grep.test.ts +515 -0
- package/src/pi/pi.test.ts +19 -0
- package/src/pi/read-tool.ts +178 -0
- package/src/pi/registration.test.ts +41 -0
- package/src/pi/render.ts +103 -0
- package/src/pi/replace-tool.ts +303 -0
- package/src/pi/replace.test.ts +287 -0
- package/src/pi/rg-line-filter.test.ts +79 -0
- package/src/pi/rg-line-filter.ts +358 -0
- package/src/pi/rg-line-ranges.test.ts +30 -0
- package/src/pi/rg-line-ranges.ts +106 -0
- package/src/pi/state.ts +27 -0
- package/src/pi/write-tool.ts +83 -0
- package/src/pi/write.test.ts +126 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
2
|
+
import { splitLines } from "../core/lines.ts";
|
|
3
|
+
import type { AnchorFailure } from "../core/types.ts";
|
|
4
|
+
|
|
5
|
+
const CONTEXT_RADIUS = 3;
|
|
6
|
+
const MAX_CONTEXT_ROWS = 40;
|
|
7
|
+
const MAX_CONTEXT_BYTES = 16 * 1024;
|
|
8
|
+
|
|
9
|
+
type Interval = { lo: number; hi: number };
|
|
10
|
+
type ContextRow = { line: number; text: string };
|
|
11
|
+
|
|
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
|
+
|
|
23
|
+
function shownIntervals(rows: readonly ContextRow[]): Interval[] {
|
|
24
|
+
const intervals: Interval[] = [];
|
|
25
|
+
for (const row of rows) {
|
|
26
|
+
const previous = intervals.at(-1);
|
|
27
|
+
if (previous && row.line === previous.hi + 1) previous.hi = row.line;
|
|
28
|
+
else intervals.push({ lo: row.line, hi: row.line });
|
|
29
|
+
}
|
|
30
|
+
return intervals;
|
|
31
|
+
}
|
|
32
|
+
|
|
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) };
|
|
58
|
+
}));
|
|
59
|
+
const total = windows.reduce((sum, window) => sum + window.hi - window.lo + 1, 0);
|
|
60
|
+
const rows: ContextRow[] = [];
|
|
61
|
+
let bytes = 0;
|
|
62
|
+
let truncatedBy: "row limit" | "byte limit" | undefined;
|
|
63
|
+
|
|
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
|
+
}
|
|
70
|
+
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;
|
|
76
|
+
}
|
|
77
|
+
rows.push({ line, text });
|
|
78
|
+
bytes += rowBytes;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const body: string[] = [...heading];
|
|
83
|
+
if (rows.length === 0) {
|
|
84
|
+
body.push("No context row fits the byte budget. Use read or grep for additional context.");
|
|
85
|
+
} 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
|
+
}
|
|
91
|
+
}
|
|
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")}`;
|
|
98
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import { createActionFusionExecutor, ActionFusionError } from "./action-fusion.ts";
|
|
7
|
+
import { FileMutationError } from "./file-commit.ts";
|
|
8
|
+
|
|
9
|
+
async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
10
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-failure-"));
|
|
11
|
+
try { return await run(dir); } finally { await rm(dir, { recursive: true, force: true }); }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const context = (cwd: string) => ({ cwd }) as any;
|
|
15
|
+
const result = () => ({ content: [{ type: "text" as const, text: "mutation" }], details: { publication: "PUBLISHED" } });
|
|
16
|
+
|
|
17
|
+
test("published post-processing failure skips command and preserves publication state", async () => withTemp(async (dir) => {
|
|
18
|
+
const target = join(dir, "published.txt");
|
|
19
|
+
await writeFile(target, "content\n");
|
|
20
|
+
let commanded = false;
|
|
21
|
+
const fusion = createActionFusionExecutor(async () => { commanded = true; return "never"; });
|
|
22
|
+
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
|
+
(error: unknown) => error instanceof ActionFusionError && error.publication === "PUBLISHED" && error.command === "skipped" && !commanded,
|
|
25
|
+
);
|
|
26
|
+
}));
|
|
27
|
+
|
|
28
|
+
test("command failure still reports final changed freshness", async () => withTemp(async (dir) => {
|
|
29
|
+
const target = join(dir, "failed.txt");
|
|
30
|
+
await writeFile(target, "before\n");
|
|
31
|
+
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) });
|
|
33
|
+
assert.deepEqual(outcome.details.actionFusion, { publication: "PUBLISHED", command: "failed", freshness: "changed" });
|
|
34
|
+
assert.match(outcome.content[1].text, /Re-read the file/);
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
test("timeout and cancellation do not rerun mutation and still inspect freshness", async () => withTemp(async (dir) => {
|
|
38
|
+
const target = join(dir, "cancelled.txt");
|
|
39
|
+
await writeFile(target, "before\n");
|
|
40
|
+
let mutations = 0;
|
|
41
|
+
const controller = new AbortController();
|
|
42
|
+
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) });
|
|
44
|
+
assert.equal(outcome.details.actionFusion.command, "cancelled");
|
|
45
|
+
assert.equal(outcome.details.actionFusion.freshness, "unchanged");
|
|
46
|
+
assert.equal(mutations, 1);
|
|
47
|
+
}));
|
|
48
|
+
|
|
49
|
+
test("queue is released after a failed command", async () => withTemp(async (dir) => {
|
|
50
|
+
const target = join(dir, "queue.txt");
|
|
51
|
+
await writeFile(target, "before\n");
|
|
52
|
+
let calls = 0;
|
|
53
|
+
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) });
|
|
55
|
+
const failed: any = await first;
|
|
56
|
+
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) });
|
|
58
|
+
assert.equal(calls, 2);
|
|
59
|
+
assert.match(second.content[1].type === "text" ? second.content[1].text : "", /then_run:succeeded/);
|
|
60
|
+
}));
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { chmod, lstat, mkdir, mkdtemp, open, readFile, readlink, stat, symlink, link as createHardLink, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { commitFile, FileMutationError, fileRevision } from "./file-commit.ts";
|
|
8
|
+
import { createActionFusionExecutor } from "./action-fusion.ts";
|
|
9
|
+
import { makeWriteOverride } from "./write-tool.ts";
|
|
10
|
+
|
|
11
|
+
async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
12
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-commit-"));
|
|
13
|
+
try { return await run(dir); } finally { await rm(dir, { recursive: true, force: true }); }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function isPermissionError(error: unknown): boolean {
|
|
17
|
+
return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "EPERM";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function holdWindowsExclusive(path: string): Promise<{ release: () => void; done: Promise<void> }> {
|
|
21
|
+
const escaped = path.replaceAll("'", "''");
|
|
22
|
+
const child = spawn("powershell.exe", ["-NoProfile", "-Command", `$stream = [IO.File]::Open('${escaped}', [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None); Write-Output READY; [Console]::ReadLine(); $stream.Dispose()`], { stdio: ["pipe", "pipe", "pipe"] });
|
|
23
|
+
let output = "";
|
|
24
|
+
const ready = new Promise<void>((resolve, reject) => {
|
|
25
|
+
child.stdout.on("data", (chunk) => { output += String(chunk); if (output.includes("READY")) resolve(); });
|
|
26
|
+
child.once("error", reject);
|
|
27
|
+
});
|
|
28
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
29
|
+
child.once("error", reject);
|
|
30
|
+
child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`exclusive holder exited with ${code}`)));
|
|
31
|
+
});
|
|
32
|
+
await ready;
|
|
33
|
+
return { release: () => { child.stdin.write("release\n"); child.stdin.end(); }, done };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
test("independent create commits race at the no-replace publication primitive", async () => withTemp(async (dir) => {
|
|
37
|
+
const target = join(dir, "race.txt");
|
|
38
|
+
const results = await Promise.allSettled([
|
|
39
|
+
commitFile(target, "winner-a\n", { mode: "create" }),
|
|
40
|
+
commitFile(target, "winner-b\n", { mode: "create" }),
|
|
41
|
+
]);
|
|
42
|
+
assert.equal(results.filter((result) => result.status === "fulfilled").length, 1);
|
|
43
|
+
assert.equal(results.filter((result) => result.status === "rejected").length, 1);
|
|
44
|
+
const rejected = results.find((result) => result.status === "rejected") as PromiseRejectedResult;
|
|
45
|
+
assert.ok(rejected.reason instanceof FileMutationError);
|
|
46
|
+
assert.equal(rejected.reason.publication, "NOT_PUBLISHED");
|
|
47
|
+
assert.match(await readFile(target, "utf8"), /^winner-[ab]\n$/);
|
|
48
|
+
}));
|
|
49
|
+
|
|
50
|
+
test("create never overwrites an existing target and expectedRevision remains strict", async () => withTemp(async (dir) => {
|
|
51
|
+
const target = join(dir, "existing.txt");
|
|
52
|
+
await writeFile(target, "original\n");
|
|
53
|
+
const revision = await fileRevision(target);
|
|
54
|
+
await assert.rejects(commitFile(target, "replacement\n", { mode: "create" }), (error: unknown) => error instanceof FileMutationError && error.publication === "NOT_PUBLISHED");
|
|
55
|
+
await assert.rejects(commitFile(target, "replacement\n", { mode: "overwrite", expectedRevision: "stale" }), /expectedRevision/);
|
|
56
|
+
assert.equal(await fileRevision(target), revision);
|
|
57
|
+
assert.equal(await readFile(target, "utf8"), "original\n");
|
|
58
|
+
}));
|
|
59
|
+
|
|
60
|
+
test("replacement exposes complete old or new content during concurrent reads", async (t) => withTemp(async (dir) => {
|
|
61
|
+
if (process.platform === "win32") return t.skip("Windows rename can reject a concurrently open reader; see platform matrix");
|
|
62
|
+
const target = join(dir, "atomic.txt");
|
|
63
|
+
const oldContent = "old-".repeat(200_000);
|
|
64
|
+
const newContent = "new-".repeat(200_000);
|
|
65
|
+
await writeFile(target, oldContent);
|
|
66
|
+
let done = false;
|
|
67
|
+
const commit = commitFile(target, newContent, { mode: "overwrite" }).finally(() => { done = true; });
|
|
68
|
+
const observed = new Set<string>();
|
|
69
|
+
while (!done) {
|
|
70
|
+
const current = await readFile(target, "utf8");
|
|
71
|
+
assert.ok(current === oldContent || current === newContent, "reader observed partial replacement content");
|
|
72
|
+
observed.add(current === oldContent ? "old" : "new");
|
|
73
|
+
}
|
|
74
|
+
await commit;
|
|
75
|
+
assert.ok(observed.size === 0 || [...observed].every((value) => value === "old" || value === "new"));
|
|
76
|
+
assert.equal(await readFile(target, "utf8"), newContent);
|
|
77
|
+
}));
|
|
78
|
+
|
|
79
|
+
test("overwriting a symlink updates its resolved regular-file target and preserves the link", async (t) => withTemp(async (dir) => {
|
|
80
|
+
const target = join(dir, "real.txt");
|
|
81
|
+
const alias = join(dir, "alias.txt");
|
|
82
|
+
await writeFile(target, "old\n");
|
|
83
|
+
try { await symlink("real.txt", alias); } catch (error) { if (isPermissionError(error)) return t.skip("symlink creation unavailable"); throw error; }
|
|
84
|
+
await commitFile(alias, "new\n", { mode: "overwrite" });
|
|
85
|
+
assert.equal(await readFile(target, "utf8"), "new\n");
|
|
86
|
+
assert.equal((await lstat(alias)).isSymbolicLink(), true);
|
|
87
|
+
assert.equal(await readlink(alias), "real.txt");
|
|
88
|
+
}));
|
|
89
|
+
|
|
90
|
+
test("create rejects both valid and dangling symlinks without replacing the link", async (t) => withTemp(async (dir) => {
|
|
91
|
+
const real = join(dir, "real.txt");
|
|
92
|
+
const valid = join(dir, "valid.txt");
|
|
93
|
+
const dangling = join(dir, "dangling.txt");
|
|
94
|
+
await writeFile(real, "original\n");
|
|
95
|
+
try {
|
|
96
|
+
await symlink("real.txt", valid);
|
|
97
|
+
await symlink("missing.txt", dangling);
|
|
98
|
+
} catch (error) { if (isPermissionError(error)) return t.skip("symlink creation unavailable"); throw error; }
|
|
99
|
+
await assert.rejects(commitFile(valid, "bad\n", { mode: "create" }), /already exists|symlink/);
|
|
100
|
+
await assert.rejects(commitFile(dangling, "bad\n", { mode: "create" }), /symlink/);
|
|
101
|
+
assert.equal((await lstat(valid)).isSymbolicLink(), true);
|
|
102
|
+
assert.equal((await lstat(dangling)).isSymbolicLink(), true);
|
|
103
|
+
assert.equal(await readFile(real, "utf8"), "original\n");
|
|
104
|
+
}));
|
|
105
|
+
|
|
106
|
+
test("replacement rejects a multi-hardlink target without changing either link", async (t) => withTemp(async (dir) => {
|
|
107
|
+
const target = join(dir, "target.txt");
|
|
108
|
+
const sibling = join(dir, "sibling.txt");
|
|
109
|
+
await writeFile(target, "original\n");
|
|
110
|
+
try { await createHardLink(target, sibling); } catch (error) { if (isPermissionError(error)) return t.skip("hardlink creation unavailable"); throw error; }
|
|
111
|
+
await assert.rejects(commitFile(target, "bad\n", { mode: "overwrite" }), /multiple hard links/);
|
|
112
|
+
assert.equal(await readFile(target, "utf8"), "original\n");
|
|
113
|
+
assert.equal(await readFile(sibling, "utf8"), "original\n");
|
|
114
|
+
assert.equal((await stat(target)).nlink, 2);
|
|
115
|
+
}));
|
|
116
|
+
|
|
117
|
+
test("existing private and executable permissions survive replacement; new files use private mode", async (t) => withTemp(async (dir) => {
|
|
118
|
+
if (process.platform === "win32") return t.skip("Windows mode bits are not an ACL preservation test");
|
|
119
|
+
const existing = join(dir, "existing.sh");
|
|
120
|
+
await writeFile(existing, "old\n");
|
|
121
|
+
await chmod(existing, 0o750);
|
|
122
|
+
await commitFile(existing, "new\n", { mode: "overwrite" });
|
|
123
|
+
assert.equal((await stat(existing)).mode & 0o777, 0o750);
|
|
124
|
+
const created = join(dir, "created.txt");
|
|
125
|
+
await commitFile(created, "new\n", { mode: "create" });
|
|
126
|
+
assert.equal((await stat(created)).mode & 0o777, 0o600);
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
test("directories are rejected instead of entering regular-file publication", async () => withTemp(async (dir) => {
|
|
130
|
+
const target = join(dir, "directory");
|
|
131
|
+
await mkdir(target);
|
|
132
|
+
await assert.rejects(commitFile(target, "bad\n", { mode: "overwrite" }), /not a regular file/);
|
|
133
|
+
}));
|
|
134
|
+
|
|
135
|
+
test("Windows replacement failure never falls back to delete-then-write", async (t) => withTemp(async (dir) => {
|
|
136
|
+
if (process.platform !== "win32") return t.skip("Windows-specific behavior");
|
|
137
|
+
const target = join(dir, "readonly.txt");
|
|
138
|
+
await writeFile(target, "original\n");
|
|
139
|
+
await chmod(target, 0o444);
|
|
140
|
+
try {
|
|
141
|
+
await commitFile(target, "replacement\n", { mode: "overwrite" });
|
|
142
|
+
} catch (error) {
|
|
143
|
+
assert.ok(error instanceof FileMutationError);
|
|
144
|
+
assert.ok(error.publication === "NOT_PUBLISHED" || error.publication === "UNKNOWN");
|
|
145
|
+
assert.equal(await readFile(target, "utf8"), "original\n");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
assert.equal(await readFile(target, "utf8"), "replacement\n");
|
|
149
|
+
}));
|
|
150
|
+
|
|
151
|
+
test("Windows shared access failure preserves the target, skips then_run, and releases the queue", async (t) => withTemp(async (dir) => {
|
|
152
|
+
if (process.platform !== "win32") return t.skip("Windows shared-access behavior");
|
|
153
|
+
const target = join(dir, "shared.txt");
|
|
154
|
+
await writeFile(target, "original\n");
|
|
155
|
+
const holder = await holdWindowsExclusive(target);
|
|
156
|
+
let commandRuns = 0;
|
|
157
|
+
const tool = makeWriteOverride(dir, createActionFusionExecutor(async () => { commandRuns++; return "ok"; }));
|
|
158
|
+
try {
|
|
159
|
+
await assert.rejects(
|
|
160
|
+
tool.execute("shared-failure", { path: target, content: "replacement\n", then_run: { command: "deterministic-command" } }, undefined, undefined, { cwd: dir }),
|
|
161
|
+
(error: unknown) => error instanceof Error && /File state is uncertain|No file changes were published/.test(error.message) && /Command skipped/.test(error.message),
|
|
162
|
+
);
|
|
163
|
+
assert.equal(commandRuns, 0);
|
|
164
|
+
} finally {
|
|
165
|
+
holder.release();
|
|
166
|
+
await holder.done;
|
|
167
|
+
}
|
|
168
|
+
let unlocked = false;
|
|
169
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
170
|
+
try { const probe = await open(target, "r"); await probe.close(); unlocked = true; break; } catch (error) {
|
|
171
|
+
if (!(error instanceof Error) || !("code" in error) || (error as NodeJS.ErrnoException).code !== "EBUSY") throw error;
|
|
172
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
assert.equal(unlocked, true, "Windows did not release the shared-access holder");
|
|
176
|
+
assert.equal(await readFile(target, "utf8"), "original\n");
|
|
177
|
+
const result = await tool.execute("shared-retry", { path: target, content: "replacement\n", then_run: { command: "deterministic-command" } }, undefined, undefined, { cwd: dir });
|
|
178
|
+
assert.match(result.content.map((item: any) => item.type === "text" ? item.text : "").join("\n"), /then_run:succeeded/);
|
|
179
|
+
assert.equal(commandRuns, 1);
|
|
180
|
+
assert.equal(await readFile(target, "utf8"), "replacement\n");
|
|
181
|
+
}));
|
|
182
|
+
|
|
183
|
+
test("cancellation racing publication never reports a settled operation as unpublished after success", async () => withTemp(async (dir) => {
|
|
184
|
+
const target = join(dir, "cancel.txt");
|
|
185
|
+
const oldContent = "old\n";
|
|
186
|
+
const newContent = "new-".repeat(100_000);
|
|
187
|
+
await writeFile(target, oldContent);
|
|
188
|
+
const controller = new AbortController();
|
|
189
|
+
const commit = commitFile(target, newContent, { mode: "overwrite", signal: controller.signal });
|
|
190
|
+
setImmediate(() => controller.abort());
|
|
191
|
+
try {
|
|
192
|
+
const result = await commit;
|
|
193
|
+
assert.equal(result.publication, "PUBLISHED");
|
|
194
|
+
} catch (error) {
|
|
195
|
+
assert.ok(error instanceof FileMutationError);
|
|
196
|
+
assert.notEqual(error.publication, "PUBLISHED");
|
|
197
|
+
}
|
|
198
|
+
const finalContent = await readFile(target, "utf8");
|
|
199
|
+
assert.ok(finalContent === oldContent || finalContent === newContent);
|
|
200
|
+
}));
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { chmod, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, link } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
|
|
6
|
+
export type CommitMode = "create" | "overwrite";
|
|
7
|
+
|
|
8
|
+
export interface CommitOptions {
|
|
9
|
+
mode?: CommitMode;
|
|
10
|
+
expectedRevision?: string;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface CommitResult {
|
|
15
|
+
created: boolean;
|
|
16
|
+
revision: string;
|
|
17
|
+
publication: "PUBLISHED";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class FileMutationError extends Error {
|
|
21
|
+
readonly stage: "prepare" | "commit" | "post_process";
|
|
22
|
+
readonly publication: PublicationStatus;
|
|
23
|
+
|
|
24
|
+
constructor(stage: "prepare" | "commit" | "post_process", publication: PublicationStatus, message: string, options?: { cause?: unknown }) {
|
|
25
|
+
super(message, options);
|
|
26
|
+
this.name = "FileMutationError";
|
|
27
|
+
this.stage = stage;
|
|
28
|
+
this.publication = publication;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function fileRevision(path: string): Promise<string> {
|
|
33
|
+
return createHash("sha256").update(await readFile(path)).digest("hex");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function prepareError(message: string, cause?: unknown): FileMutationError {
|
|
37
|
+
return new FileMutationError("prepare", "NOT_PUBLISHED", message, { cause });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function errorCode(error: unknown): string | undefined {
|
|
41
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface TargetInfo {
|
|
45
|
+
existed: boolean;
|
|
46
|
+
publishPath: string;
|
|
47
|
+
beforeRevision?: string;
|
|
48
|
+
modeBits?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function inspectTarget(path: string): Promise<TargetInfo> {
|
|
52
|
+
let entry;
|
|
53
|
+
try {
|
|
54
|
+
entry = await lstat(path);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (errorCode(error) === "ENOENT") return { existed: false, publishPath: path };
|
|
57
|
+
throw prepareError(`unable to inspect target: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let publishPath = path;
|
|
61
|
+
if (entry.isSymbolicLink()) {
|
|
62
|
+
try {
|
|
63
|
+
publishPath = await realpath(path);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
throw prepareError(`target symlink cannot be resolved: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let target;
|
|
70
|
+
try {
|
|
71
|
+
target = await stat(publishPath);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
throw prepareError(`unable to inspect target: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
74
|
+
}
|
|
75
|
+
if (!target.isFile()) throw prepareError("target is not a regular file");
|
|
76
|
+
if (target.nlink > 1) throw prepareError("target has multiple hard links; refusing to split the link set");
|
|
77
|
+
|
|
78
|
+
let beforeRevision: string;
|
|
79
|
+
try {
|
|
80
|
+
beforeRevision = await fileRevision(publishPath);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw prepareError(`unable to read target revision: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
existed: true,
|
|
86
|
+
publishPath,
|
|
87
|
+
beforeRevision,
|
|
88
|
+
modeBits: target.mode,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function writeAndSyncTemp(tempPath: string, content: string, modeBits: number | undefined, signal: AbortSignal | undefined): Promise<void> {
|
|
93
|
+
signal?.throwIfAborted();
|
|
94
|
+
const handle = await open(tempPath, "w", modeBits === undefined ? 0o600 : modeBits & 0o7777);
|
|
95
|
+
try {
|
|
96
|
+
await handle.writeFile(content, "utf8");
|
|
97
|
+
await handle.sync();
|
|
98
|
+
} finally {
|
|
99
|
+
await handle.close();
|
|
100
|
+
}
|
|
101
|
+
if (modeBits !== undefined) await chmod(tempPath, modeBits & 0o7777);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function publishCreate(tempPath: string, targetPath: string, signal: AbortSignal | undefined): Promise<void> {
|
|
105
|
+
// link() 在同一文件系统内创建不可覆盖的目录项,避免检查与发布之间的覆盖竞争。
|
|
106
|
+
signal?.throwIfAborted();
|
|
107
|
+
try {
|
|
108
|
+
await link(tempPath, targetPath);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (errorCode(error) === "EEXIST" || errorCode(error) === "ENOTEMPTY") {
|
|
111
|
+
throw new FileMutationError("commit", "NOT_PUBLISHED", "target appeared during create; refusing to overwrite it", { cause: error });
|
|
112
|
+
}
|
|
113
|
+
throw new FileMutationError("commit", "UNKNOWN", `unable to publish new target: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function publishReplace(tempPath: string, targetPath: string, signal: AbortSignal | undefined): Promise<void> {
|
|
118
|
+
// rename() 替换目录项,但不会先删除旧文件;读者看到旧文件或完整新文件。
|
|
119
|
+
signal?.throwIfAborted();
|
|
120
|
+
try {
|
|
121
|
+
await rename(tempPath, targetPath);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw new FileMutationError("commit", "UNKNOWN", `unable to publish replacement: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function syncDirectory(path: string): Promise<void> {
|
|
128
|
+
if (process.platform === "win32") return;
|
|
129
|
+
const handle = await open(path, "r");
|
|
130
|
+
try {
|
|
131
|
+
await handle.sync();
|
|
132
|
+
} finally {
|
|
133
|
+
await handle.close();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 统一 mutation 提交:先准备并同步临时文件,再按创建/替换语义发布;调用方负责外层文件队列。 */
|
|
138
|
+
export async function commitFile(path: string, content: string, options: CommitOptions = {}): Promise<CommitResult> {
|
|
139
|
+
const target = await inspectTarget(path);
|
|
140
|
+
const mode = options.mode ?? (target.existed ? "overwrite" : "create");
|
|
141
|
+
if (mode === "create" && target.existed) throw prepareError("target already exists; use mode=overwrite");
|
|
142
|
+
if (mode === "overwrite" && !target.existed) throw prepareError("target does not exist; use mode=create or omit mode");
|
|
143
|
+
if (mode === "create" && options.expectedRevision !== undefined) throw prepareError("expectedRevision cannot be combined with mode=create");
|
|
144
|
+
if (options.expectedRevision !== undefined && (!target.beforeRevision || target.beforeRevision !== options.expectedRevision)) {
|
|
145
|
+
throw prepareError("expectedRevision does not match the current file");
|
|
146
|
+
}
|
|
147
|
+
try { options.signal?.throwIfAborted(); } catch (error) { throw prepareError("mutation was cancelled before publication", error); }
|
|
148
|
+
|
|
149
|
+
const publishPath = target.publishPath;
|
|
150
|
+
const publishDirectory = dirname(publishPath);
|
|
151
|
+
let tempDir: string;
|
|
152
|
+
try {
|
|
153
|
+
await mkdir(publishDirectory, { recursive: true });
|
|
154
|
+
tempDir = await mkdtemp(join(publishDirectory, ".hashline-commit-"));
|
|
155
|
+
} catch (error) {
|
|
156
|
+
throw new FileMutationError("commit", "NOT_PUBLISHED", `unable to prepare temporary publication area: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
157
|
+
}
|
|
158
|
+
const tempPath = join(tempDir, "content");
|
|
159
|
+
let published = false;
|
|
160
|
+
let failure: unknown;
|
|
161
|
+
try {
|
|
162
|
+
await writeAndSyncTemp(tempPath, content, target.modeBits, options.signal);
|
|
163
|
+
if (mode === "create") await publishCreate(tempPath, publishPath, options.signal);
|
|
164
|
+
else await publishReplace(tempPath, publishPath, options.signal);
|
|
165
|
+
published = true;
|
|
166
|
+
await syncDirectory(publishDirectory);
|
|
167
|
+
try {
|
|
168
|
+
return { created: mode === "create", revision: await fileRevision(publishPath), publication: "PUBLISHED" };
|
|
169
|
+
} catch (error) {
|
|
170
|
+
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
|
+
}
|
|
172
|
+
} catch (error) {
|
|
173
|
+
failure = error;
|
|
174
|
+
if (error instanceof FileMutationError) throw error;
|
|
175
|
+
if (published) throw new FileMutationError("post_process", "PUBLISHED", `target was published but post-publication processing failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
176
|
+
throw new FileMutationError("commit", "NOT_PUBLISHED", `unable to prepare or publish target: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
177
|
+
} finally {
|
|
178
|
+
try {
|
|
179
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (!published) { if (failure !== undefined) throw failure; throw error; }
|
|
182
|
+
throw new FileMutationError("post_process", "PUBLISHED", `target was published but temporary cleanup failed: ${error instanceof Error ? error.message : String(error)}`, { cause: failure === undefined ? error : new AggregateError([failure, error], "post-publication cleanup also failed") });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { after, before, test } from "node:test";
|
|
3
|
+
import { initTheme } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { registerFusionCards } from "./fusion-card.ts";
|
|
5
|
+
import type { ActionFusionProgress } from "./action-fusion.ts";
|
|
6
|
+
|
|
7
|
+
const theme = { fg: (_color: string, text: string) => text, bg: (_color: string, text: string) => text, bold: (text: string) => text };
|
|
8
|
+
const themeKeys = [Symbol.for("@earendil-works/pi-coding-agent:theme"), Symbol.for("@mariozechner/pi-coding-agent:theme")];
|
|
9
|
+
const originalThemes = themeKeys.map((key) => Object.getOwnPropertyDescriptor(globalThis, key));
|
|
10
|
+
before(() => initTheme("dark"));
|
|
11
|
+
after(() => themeKeys.forEach((key, index) => {
|
|
12
|
+
const original = originalThemes[index];
|
|
13
|
+
if (original) Object.defineProperty(globalThis, key, original);
|
|
14
|
+
else Reflect.deleteProperty(globalThis, key);
|
|
15
|
+
}));
|
|
16
|
+
|
|
17
|
+
function harness(entries: any[] = []) {
|
|
18
|
+
const renderers = new Map<string, any>();
|
|
19
|
+
const handlers = new Map<string, any>();
|
|
20
|
+
const backgrounds: string[] = [];
|
|
21
|
+
const report = registerFusionCards({
|
|
22
|
+
on(event: string, handler: any) { handlers.set(event, handler); },
|
|
23
|
+
registerEntryRenderer(type: string, renderer: any) { renderers.set(type, renderer); },
|
|
24
|
+
appendEntry(customType: string, data: unknown) { entries.push({ type: "custom", customType, data: structuredClone(data) }); },
|
|
25
|
+
} as any);
|
|
26
|
+
const restore = (event = "session_start", branch = entries) => handlers.get(event)({}, { sessionManager: { getBranch: () => branch } });
|
|
27
|
+
const card = (entry: any, expanded = false) => renderers.get(entry.customType)(entry, { expanded }, {
|
|
28
|
+
...theme, bg: (color: string, text: string) => { backgrounds.push(color); return text; },
|
|
29
|
+
});
|
|
30
|
+
return { entries, report, restore, card, backgrounds };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const waiting: ActionFusionProgress = {
|
|
34
|
+
toolCallId: "call-1", path: "file.ts", commandText: "npm test", command: "waiting",
|
|
35
|
+
publication: "NOT_PUBLISHED", freshness: "unknown", output: "",
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
test("one independent card updates live and only persists its endpoints", () => {
|
|
39
|
+
const h = harness();
|
|
40
|
+
h.report(waiting);
|
|
41
|
+
const card = h.card(h.entries[0]);
|
|
42
|
+
assert.match(card.render(100).join("\n"), /waiting/);
|
|
43
|
+
assert.equal(h.backgrounds.at(-1), "toolPendingBg");
|
|
44
|
+
h.report({ ...waiting, command: "running", publication: "PUBLISHED", output: "first test passed" });
|
|
45
|
+
assert.match(card.render(100).join("\n"), /running[\s\S]*first test passed/);
|
|
46
|
+
assert.equal(h.entries.length, 1);
|
|
47
|
+
const output = Array.from({ length: 20 }, (_, i) => `output line ${i}`).join("\n");
|
|
48
|
+
h.report({ ...waiting, command: "succeeded", publication: "PUBLISHED", freshness: "changed", output });
|
|
49
|
+
assert.equal(h.entries.length, 2);
|
|
50
|
+
assert.equal(h.entries[0].data.command, "waiting");
|
|
51
|
+
const collapsed = card.render(100).join("\n");
|
|
52
|
+
assert.match(collapsed, /succeeded[\s\S]*Anchors are stale/);
|
|
53
|
+
assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
|
|
54
|
+
assert.match(collapsed, /output line 19/);
|
|
55
|
+
assert.doesNotMatch(collapsed, /output line 0\b/);
|
|
56
|
+
assert.match(h.card(h.entries[0], true).render(100).join("\n"), /output line 0\b/);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("session restore uses final snapshots and marks unfinished calls unknown", () => {
|
|
60
|
+
const h = harness();
|
|
61
|
+
h.report(waiting);
|
|
62
|
+
h.report({ ...waiting, command: "failed", publication: "PUBLISHED", output: "Command exited with code 7" });
|
|
63
|
+
const resumed = harness(h.entries);
|
|
64
|
+
resumed.restore();
|
|
65
|
+
assert.match(resumed.card(h.entries[0]).render(100).join("\n"), /failed[\s\S]*Command exited with code 7/);
|
|
66
|
+
assert.equal(resumed.backgrounds.at(-1), "toolErrorBg");
|
|
67
|
+
resumed.restore("session_tree", [h.entries[0]]);
|
|
68
|
+
assert.match(resumed.card(h.entries[0]).render(100).join("\n"), /interrupted \(final status unknown\)/);
|
|
69
|
+
});
|