UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,365 lines • 101 kB
import { strict as assert } from "node:assert";
import { createHash, randomUUID } from "node:crypto";
import { chmod, mkdtemp, mkdir, rm, stat, symlink, writeFile, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { isAbsolute, join } from "node:path";
import { fileHistoryBlobExchangeOf, fileHistoryParentIdentTravels, planFileHistoryRestore } from "../file-history-store.js";
import { isGovernanceRetryClass } from "../governance-codes.js";
import { physicalPathOfAsync } from "../physical-path.js";
import { NodeExecutionEnv } from "../../internal/harness.js";
import { beginContract } from "./contract-harness.js";
import { fileHistoryScopeOf } from "../../engine/session/repo-utils.js";
function probeOver(inner) {
    const calls = new Map();
    const paths = new Map();
    const proxied = new Proxy(inner, {
        get(target, prop, receiver) {
            const v = Reflect.get(target, prop, receiver);
            if (typeof v !== "function")
                return v;
            return (...args) => {
                calls.set(String(prop), (calls.get(String(prop)) ?? 0) + 1);
                if (typeof args[0] === "string")
                    paths.set(args[0], (paths.get(args[0]) ?? 0) + 1);
                return v.apply(inner, args);
            };
        },
    });
    return { env: proxied, calls, touched: (p) => paths.get(p) ?? 0 };
}
const wireEnvelope = (raw) => raw;
function envWithFailingRead(inner, fail) {
    return new Proxy(inner, {
        get(target, prop, receiver) {
            const v = Reflect.get(target, prop, receiver);
            if (prop !== "readBinaryFile" || typeof v !== "function")
                return v;
            return async (...args) => fail(String(args[0]));
        },
    });
}
const NAMES_A_FAULT = { track_failed: true, snapshot_failed: true, restore_failed: true, adopt_failed: true, unsupported_format: true, too_large: true, not_found: false, conflict: false, aborted: false };
function assertTooLarge(answer, limit, what) {
    assert.equal(answer.ok, false, `${what}: over the bound is refused`);
    const error = answer.error;
    assert.equal(error?.code, "too_large", `${what}: the refusal's code`);
    assert.equal(error?.permanence, "terminal", `${what}: no retry makes the same bytes fit`);
    assert.deepEqual(error?.limit, { bytes: limit.bytes, source: limit.source }, `${what}: the refusal names the bound and where it comes from`);
    assertPermanenceWord(error, what);
}
function assertPermanenceWord(error, what) {
    const p = error?.permanence;
    assert.ok(p === undefined || isGovernanceRetryClass(p), `${what}: permanence must be absent or a GovernanceRetryClass word, got ${typeof p === "string" ? `"${p}"` : typeof p}`);
    if (p !== undefined)
        assert.ok(error !== undefined && NAMES_A_FAULT[error.code] === true, `${what}: ${error?.code} is not a fault and carries no permanence`);
}
async function existsAt(path) {
    return stat(path).then(() => true, () => false);
}
async function withTree(fn) {
    const dir = await physicalPathOfAsync(await mkdtemp(join(tmpdir(), "fh-kit-")));
    try {
        await fn(dir, new NodeExecutionEnv({ cwd: dir }));
    }
    finally {
        await rm(dir, { recursive: true, force: true });
    }
}
export async function fileHistoryStoreContract(make, runAssertion, onOptionalMember, limits) {
    const { run, settle } = beginContract(runAssertion);
    run("too_large (when the binding declares a bound): one stored copy of exactly the bound is kept, one byte over is refused — counted in bytes, a multi-byte character across the bound included — at trackEdit, snapshot (a later file of the boundary over it), blobExchange.put and importHistory, with the bound and its source and nothing of the call committed; absence is REPORTED", async () => {
        if (limits === undefined) {
            onOptionalMember?.({ member: "sizeLimit", status: "absent" });
            return;
        }
        const n = limits.bytes;
        const limit = { bytes: n, source: limits.source };
        assert.ok(Number.isSafeInteger(n) && n >= 2, "the binding's bound is a whole number of bytes, 2 or more");
        await withTree(async (dir, env) => {
            const store = limits.capped();
            const exact = "a".repeat(n);
            const over = "a".repeat(n + 1);
            const across = `${"a".repeat(n - 1)}é`;
            await writeFile(join(dir, "a-first.txt"), "b");
            await writeFile(join(dir, "exact.txt"), exact);
            await writeFile(join(dir, "over.txt"), over);
            await writeFile(join(dir, "across.txt"), across);
            assert.deepEqual(await store.trackEdit("sc", join(dir, "a-first.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "exact.txt"), env, dir), { ok: true, minted: true }, "a copy of exactly the bound is kept");
            assertTooLarge(await store.trackEdit("sc", join(dir, "over.txt"), env, dir), limit, "trackEdit, one byte over");
            assertTooLarge(await store.trackEdit("sc", join(dir, "across.txt"), env, dir), limit, "trackEdit, a two-byte character across the bound");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "over.txt"), env, dir).then((r) => r.ok), false, "nothing was recorded: the next touch is a first touch again, refused again");
            assert.deepEqual(await store.snapshot("sc", "b0", env, dir), { ok: true }, "a boundary of copies at or under the bound is committed");
            await writeFile(join(dir, "a-first.txt"), "c");
            await writeFile(join(dir, "exact.txt"), over);
            assertTooLarge(await store.snapshot("sc", "b1", env, dir), limit, "snapshot whose later file grew past the bound");
            assert.equal((await store.restore("sc", "b1", env, dir)).error?.code, "not_found", "the refused boundary was never committed");
            const exchange = fileHistoryBlobExchangeOf(store);
            if (exchange !== undefined) {
                const bytes = new TextEncoder().encode(over);
                const hash = createHash("sha256").update(bytes).digest("hex");
                assertTooLarge(await exchange.put(hash, bytes), limit, "blobExchange.put");
                assert.deepEqual([...(await exchange.has([hash]))], [], "a refused put stores nothing");
                const fits = new TextEncoder().encode(`${"c".repeat(n - 1)}d`);
                assert.deepEqual(await exchange.put(createHash("sha256").update(fits).digest("hex"), fits), { ok: true }, "blobExchange.put of exactly the bound is kept");
            }
            if (store.importHistory !== undefined) {
                const envelopeOf = (hash) => wireEnvelope({
                    formatVersion: "file-history/1",
                    tracked: [{ relOrAbsPath: "big.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: hash, backupTime: "t" }] }],
                    boundaries: [{ entryId: "i0", files: [{ relOrAbsPath: "big.txt", version: 1 }] }],
                });
                const bytes = new TextEncoder().encode("h".repeat(n + 1));
                const hash = createHash("sha256").update(bytes).digest("hex");
                assertTooLarge(await store.importHistory("imp", envelopeOf(hash), async () => bytes), { bytes: n, source: limits.source }, "importHistory of a blob over the bound");
                assert.equal((await store.restore("imp", "i0", env, dir)).error?.code, "not_found", "nothing of the refused import was published");
                const fits = new TextEncoder().encode(`${"f".repeat(n - 1)}g`);
                assert.deepEqual(await store.importHistory("imp2", envelopeOf(createHash("sha256").update(fits).digest("hex")), async () => fits), { ok: true }, "importHistory of a blob of exactly the bound is published");
            }
        });
        onOptionalMember?.({ member: "sizeLimit", status: "verified" });
    });
    run("blobExchange (optional member group): read as one group; put checks the address and stores nothing it refuses; has answers from the index; get round-trips; absence is REPORTED", async () => {
        const exchange = fileHistoryBlobExchangeOf(make());
        if (exchange === undefined) {
            onOptionalMember?.({ member: "blobExchange", status: "absent" });
            return;
        }
        const bytes = new TextEncoder().encode("bytes another machine sent ahead of its import");
        const other = new TextEncoder().encode("different bytes");
        const hash = createHash("sha256").update(bytes).digest("hex");
        const otherHash = createHash("sha256").update(other).digest("hex");
        assert.deepEqual([...(await exchange.has([hash]))], [], "nothing is held before the put");
        assert.equal(await exchange.get(hash), undefined, "get answers undefined for bytes the store does not hold");
        const wrong = await exchange.put(otherHash, bytes);
        assert.equal(wrong.ok, false, "bytes that do not hash to the address are refused");
        assert.equal(!wrong.ok && wrong.error.code, "adopt_failed", "the refusal is the adoption family's word");
        assert.equal(!wrong.ok && wrong.error.permanence, "terminal", "no retry makes the bytes hash differently");
        assert.deepEqual([...(await exchange.has([otherHash, hash]))], [], "a refused put stores nothing under either address");
        assert.deepEqual(await exchange.put(hash, bytes), { ok: true });
        assert.deepEqual(await exchange.put(hash, bytes), { ok: true }, "a repeat put is idempotent");
        assert.deepEqual([...(await exchange.has([hash, otherHash]))], [hash], "has names the held ones only");
        assert.deepEqual([...((await exchange.get(hash)) ?? [])], [...bytes], "get round-trips the bytes");
        onOptionalMember?.({ member: "blobExchange", status: "verified" });
    });
    run("readBoundaries (optional seat): a boundary never made and a reaped one read null, a committed one reads its tracked set with each entry's target, and no env is needed; absence is REPORTED", async () => {
        const probe = make();
        if (typeof probe.readBoundaries !== "function") {
            onOptionalMember?.({ member: "readBoundaries", status: "absent" });
            return;
        }
        await withTree(async (dir, env) => {
            const store = make();
            assert.deepEqual(await readOneBoundary(store, "sc", "never-made"), { ok: true, boundary: null }, "a boundary never made reads null");
            await writeFile(join(dir, "f.txt"), "one");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            assert.deepEqual(await store.snapshot("sc", "b2", env, dir), { ok: true });
            const read = await readOneBoundary(store, "sc", "b1");
            assert.ok(read.ok && read.boundary !== null, JSON.stringify(read));
            assert.deepEqual(read.boundary.entries.map((e) => [e.key, e.keyDesc.kind, e.target.kind, "version" in e.target ? e.target.version : null, "hash" in e.target ? e.target.hash : null]), [["f.txt", "root-relative", "bytes", 1, createHash("sha256").update("one").digest("hex")]]);
            assert.deepEqual(await store.reap("sc", ["b2"]), 1);
            assert.deepEqual(await readOneBoundary(store, "sc", "b1"), { ok: true, boundary: null }, "a reaped boundary reads null, as its restore answers not_found");
            assert.equal((await store.restore("sc", "b1", env, dir)).error?.code, "not_found");
        });
        onOptionalMember?.({ member: "readBoundaries", status: "verified" });
    });
    run("readBoundaries answers a batch as its ids asked alone: [b1, b2, never made, reaped, b1] holds four keys — one per distinct id, an id asked twice is one key — each valued as that id's batch of one", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            if (typeof store.readBoundaries !== "function")
                return;
            await writeFile(join(dir, "f.txt"), "f0");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b0", env, dir), { ok: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "f1");
            assert.deepEqual(await store.snapshot("sc", "b2", env, dir), { ok: true });
            assert.deepEqual(await store.reap("sc", ["b1", "b2"]), 1);
            const batch = await store.readBoundaries("sc", ["b1", "b2", "never-made", "b0", "b1"]);
            assert.ok(batch.ok, JSON.stringify(batch));
            assert.deepEqual([...batch.boundaries.keys()].sort(), ["b0", "b1", "b2", "never-made"]);
            for (const id of ["b1", "b2", "never-made", "b0"])
                assert.deepEqual(batch.boundaries.get(id), await readOneBoundary(store, "sc", id), `${id}: the batch answers it as it is answered alone`);
            assert.deepEqual([batch.boundaries.get("b0"), batch.boundaries.get("never-made")], [{ ok: true, boundary: null }, { ok: true, boundary: null }]);
            assert.notDeepEqual(batch.boundaries.get("b1"), batch.boundaries.get("b2"), "two live boundaries read their own versions");
        });
    });
    run("readBoundaries on an empty list answers an empty map (and a scope with no history answers null for every id)", async () => {
        const store = make();
        if (typeof store.readBoundaries !== "function")
            return;
        assert.deepEqual(await store.readBoundaries("sc", []), { ok: true, boundaries: new Map() });
        assert.deepEqual(await store.readBoundaries("no-history", ["a", "b"]), { ok: true, boundaries: new Map([["a", { ok: true, boundary: null }], ["b", { ok: true, boundary: null }]]) });
    });
    run("readBoundaries agrees with restore (implication form): bytes h ⇒ converged to h; absent ⇒ converged to absent; base_unavailable ⇔ refused base_unavailable; frozen ⇔ left frozen_history — on a boundary before and after files were created, tracked late, and tracked with no capturable base", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            if (typeof store.readBoundaries !== "function")
                return;
            await writeFile(join(dir, "f.txt"), "f0");
            await writeFile(join(dir, "h.txt"), "h0");
            await writeFile(join(dir, "u.txt"), "u0");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "f1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "g.txt"), env, dir), { ok: true, minted: true });
            await writeFile(join(dir, "g.txt"), "g1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "h.txt"), env, dir), { ok: true, minted: true });
            await writeFile(join(dir, "h.txt"), "h1");
            const hostile = envWithFailingRead(env, async () => ({ ok: false, error: { code: "unknown", message: "pristine unreadable" } }));
            const marked = await store.trackEdit("sc", join(dir, "u.txt"), hostile, dir);
            await writeFile(join(dir, "u.txt"), "u1");
            assert.deepEqual(await store.snapshot("sc", "b2", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "f-drift");
            await rm(join(dir, "g.txt"));
            const atB2 = await boundaryAgreesWithRestore(store, "sc", "b2", env, dir);
            assert.deepEqual(atB2.violations, [], JSON.stringify(atB2));
            const atB1 = await boundaryAgreesWithRestore(store, "sc", "b1", env, dir);
            assert.deepEqual(atB1.violations, [], JSON.stringify(atB1));
            assert.deepEqual(atB1.kinds, marked.ok ? ["absent", "base_unavailable", "bytes", "bytes"] : ["absent", "bytes", "bytes"]);
            assert.deepEqual(atB2.kinds, marked.ok ? ["bytes", "bytes", "bytes", "bytes"] : ["bytes", "bytes", "bytes"]);
            if (store.importHistory === undefined)
                return;
            await mkdir(join(dir, "real"), { recursive: true, mode: 0o700 });
            await writeFile(join(dir, "real", "z.txt"), "z-0");
            await symlink(join(dir, "real"), join(dir, "inl"));
            const zHash = createHash("sha256").update("z-0").digest("hex");
            const envelope = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: "inl/z.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: zHash, backupTime: "t" }] }],
                boundaries: [{ entryId: "z0", files: [{ relOrAbsPath: "inl/z.txt", version: 1 }] }],
            });
            assert.deepEqual(await store.importHistory("fz", envelope, async () => new TextEncoder().encode("z-0")), { ok: true });
            assert.deepEqual(await store.snapshot("fz", "z1", env, dir), { ok: true }, "the first boundary records the place: the real directory, not the key's");
            const frozen = await boundaryAgreesWithRestore(store, "fz", "z1", env, dir);
            assert.deepEqual([frozen.violations, frozen.kinds], [[], ["frozen"]], JSON.stringify(frozen));
        });
    });
    run("absent everything: canRestore=false, restore=failed/not_found with an empty ledger, reap=0 — and none of it throws", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            assert.equal(await store.canRestore("sc", "e1"), false);
            const r = await store.restore("sc", "e1", env, dir);
            assert.equal(r.outcome, "failed");
            assert.equal(r.error?.code, "not_found");
            assertPermanenceWord(r.error, "a boundary never made (not a fault)");
            assert.deepEqual(r.filesChanged, []);
            assert.deepEqual(r.refused, []);
            assert.equal(await store.reap("sc", []), 0);
            if (store.exportHistory !== undefined)
                assert.deepEqual(await store.exportHistory("sc"), { ok: true, history: null }, "nothing to export is `ok` with `history: null` — the one meaning of null");
            await writeFile(join(dir, "f.txt"), "v1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "v2-edited");
            const never = await store.restore("sc", "never-made", env, dir);
            assert.equal(never.error?.code, "not_found");
            assert.deepEqual([never.filesChanged, never.identicalSkipped, never.refused, never.failed], [[], [], [], []], "a boundary never made has an empty ledger");
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "v2-edited", "a boundary never made touches nothing");
        });
    });
    run("first-touch idempotence: a second trackEdit for the same path is a cheap no-op (ZERO env reads)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "v1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true }, "the FIRST touch reports minted:true — the caller's annul handle");
            const probe = probeOver(env);
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), probe.env, dir), { ok: true, minted: false }, "a repeat must report minted:false — annulling it would discard the FIRST edit's baseline");
            assert.equal(probe.calls.get("readBinaryFile") ?? 0, 0);
        });
    });
    run("boundary commit visibility + idempotence: canRestore flips only on commit; a repeat snapshot over a COMMITTED boundary is ok with zero env reads", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "v1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.equal(await store.canRestore("sc", "b1"), false);
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            assert.equal(await store.canRestore("sc", "b1"), true);
            const probe = probeOver(env);
            assert.deepEqual(await store.snapshot("sc", "b1", probe.env, dir), { ok: true });
            assert.equal(probe.calls.get("readBinaryFile") ?? 0, 0);
        });
    });
    run("fencing: an attempt whose signal fired NEVER publishes (canRestore stays false) — including a signal that fires DURING the capture while the env completes its read anyway", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "v1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            const pre = new AbortController();
            pre.abort();
            const r = await store.snapshot("sc", "bX", env, dir, pre.signal);
            assert.equal(r.ok, false);
            assert.equal(await store.canRestore("sc", "bX"), false);
            const mid = new AbortController();
            const abortDuringRead = new Proxy(env, {
                get(target, prop, receiver) {
                    const v = Reflect.get(target, prop, receiver);
                    if (prop !== "readBinaryFile" || typeof v !== "function")
                        return v;
                    return async (...args) => {
                        mid.abort();
                        return v.apply(target, [args[0], undefined]);
                    };
                },
            });
            const r2 = await store.snapshot("sc", "bY", abortDuringRead, dir, mid.signal);
            assert.equal(r2.ok, false);
            assert.equal(await store.canRestore("sc", "bY"), false);
        });
    });
    run("capture lease: a MID-SET failure (second file's read) spends the lease — no boundary appears (catches per-file publishers), and the retry performs ZERO env calls of ANY kind", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "a.txt"), "a1");
            await writeFile(join(dir, "b.txt"), "b1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "a.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "b.txt"), env, dir), { ok: true, minted: true });
            let reads = 0;
            const brokenSecond = new Proxy(env, {
                get(target, prop, receiver) {
                    const v = Reflect.get(target, prop, receiver);
                    if (prop !== "readBinaryFile" || typeof v !== "function")
                        return v;
                    return async (...args) => {
                        if (reads++ >= 1)
                            return { ok: false, error: { code: "unknown", message: "injected IO fault" } };
                        return v.apply(target, args);
                    };
                },
            });
            assert.equal((await store.snapshot("sc", "bL", brokenSecond, dir)).ok, false);
            assert.equal(await store.canRestore("sc", "bL"), false);
            const probe = probeOver(env);
            const retry = await store.snapshot("sc", "bL", probe.env, dir);
            assert.equal(retry.ok, false);
            const totalCalls = [...probe.calls.values()].reduce((a, b) => a + b, 0);
            assert.equal(totalCalls, 0, `retry must not touch the env AT ALL (saw: ${[...probe.calls.keys()].join(", ")})`);
            assert.equal(await store.canRestore("sc", "bL"), false);
        });
    });
    run("v1 permanence across reap: the pristine fallback outlives every boundary (b0-before-track ⇒ restore b0 walks back to pristine after later boundaries were reaped)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            assert.deepEqual(await store.snapshot("sc", "b0", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            await writeFile(join(dir, "f.txt"), "edited");
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            assert.equal(await store.reap("sc", ["b0"]), 1);
            assert.equal(await store.canRestore("sc", "b1"), false);
            const r = await store.restore("sc", "b0", env, dir);
            assert.equal(r.outcome, "complete");
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "pristine");
        });
    });
    run("deletion-marker round trip: a deleted tracked file revives at an earlier boundary; an agent-created file dies at a pre-creation boundary", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "keep.txt"), "keep-v1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "keep.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "born.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            await writeFile(join(dir, "born.txt"), "created");
            await rm(join(dir, "keep.txt"));
            assert.deepEqual(await store.snapshot("sc", "b2", env, dir), { ok: true });
            let r = await store.restore("sc", "b1", env, dir);
            assert.equal(r.outcome, "complete");
            assert.equal(await readFile(join(dir, "keep.txt"), "utf8"), "keep-v1");
            assert.equal(await readFile(join(dir, "born.txt"), "utf8").then(() => true, () => false), false);
            r = await store.restore("sc", "b2", env, dir);
            assert.equal(r.outcome, "complete");
            assert.equal(await readFile(join(dir, "keep.txt"), "utf8").then(() => true, () => false), false);
            assert.equal(await readFile(join(dir, "born.txt"), "utf8"), "created");
        });
    });
    run("adoptScope: same-scope no-op; adoption copies the graph; EMPTY-TARGET ONLY (typed conflict refusal, target intact)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "v1");
            assert.deepEqual(await store.trackEdit("old", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            await writeFile(join(dir, "f.txt"), "v2");
            assert.deepEqual(await store.snapshot("old", "b", env, dir), { ok: true });
            assert.deepEqual(await store.adoptScope("old", "old"), { ok: true });
            assert.deepEqual(await store.adoptScope("old", "fresh"), { ok: true });
            assert.equal(await store.canRestore("fresh", "b"), true);
            const busy = await store.adoptScope("old", "fresh");
            assert.equal(busy.ok, false);
            if (!busy.ok)
                assert.equal(busy.error.code, "conflict");
            if (!busy.ok)
                assertPermanenceWord(busy.error, "the target law's conflict");
            assert.equal(await store.canRestore("fresh", "b"), true);
        });
    });
    run("adoptScope carries only the entries that travel: after adoption the history holds no absolute-key entry, so a fork's rewind never writes the file its source edited outside its directory", async () => {
        await withTree(async (dir, env) => {
            await withTree(async (outside) => {
                const probe = make();
                await mkdir(join(outside, "w"), { recursive: true, mode: 0o700 });
                await writeFile(join(dir, "w.txt"), "w-a");
                await writeFile(join(outside, "w", "w.txt"), "w-b");
                await probe.trackEdit("w", join(dir, "w.txt"), env, dir);
                await probe.snapshot("w", "wb", env, dir);
                const envW = new NodeExecutionEnv({ cwd: join(outside, "w") });
                await probe.trackEdit("w", join(outside, "w", "w.txt"), envW, join(outside, "w"));
                await writeFile(join(outside, "w", "w.txt"), "w-b-edited");
                const minted = (await probe.restore("w", "wb", envW, join(outside, "w"))).filesChanged.includes(join(outside, "w", "w.txt"));
                const store = make();
                await writeFile(join(dir, "f.txt"), "f-0");
                await writeFile(join(outside, "o.txt"), "o-0");
                assert.deepEqual(await store.trackEdit("src", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await store.trackEdit("src", join(outside, "o.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await store.snapshot("src", "b1", env, dir), { ok: true });
                await writeFile(join(dir, "f.txt"), "f-1");
                await writeFile(join(outside, "o.txt"), "o-source-still-editing");
                assert.deepEqual(await store.adoptScope("src", "fork"), { ok: true });
                const r = await store.restore("fork", "b1", env, dir);
                const combination = minted
                    ? " — and this store mints a second file's absolute key: minting it while carrying every entry writes a fork's rewind into the file its source still edits; the two are followed together or not at all"
                    : "";
                assert.equal(await readFile(join(outside, "o.txt"), "utf8"), "o-source-still-editing", `an absolute-key entry was carried into the fork and restored there${combination}: ${JSON.stringify(r)}`);
                const named = [...r.filesChanged, ...r.identicalSkipped, ...r.refused.map((f) => f.path), ...r.failed.map((f) => f.path)];
                assert.equal(named.includes(join(outside, "o.txt")), false, `the fork's history names no absolute-key entry${combination}: ${JSON.stringify(r)}`);
                assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "f-0", "the root-relative entry is carried and restores");
                const own = await store.restore("src", "b1", env, dir);
                assert.ok(own.filesChanged.includes(join(outside, "o.txt")), `the source's own absolute-key entry still restores: ${JSON.stringify(own)}`);
            });
        });
    });
    run("deleteUnreadableSessionHistory (optional): every scope of the id — its bare id and each occupant's address — is erased, and no other id's (one it is a prefix of, one carrying `~` of its own); a repeat answers 0", async () => {
        if (make().deleteUnreadableSessionHistory === undefined)
            return;
        await withTree(async (dir, env) => {
            const store = make();
            const minted = () => `${randomUUID()}.2`;
            const id = `s1-${randomUUID().slice(0, 8)}`;
            const own = [fileHistoryScopeOf(id, undefined), fileHistoryScopeOf(id, minted()), fileHistoryScopeOf(id, minted())];
            const others = [`${id}x`, `${id}-x`, `${id}~a`].flatMap((other) => [fileHistoryScopeOf(other, undefined), fileHistoryScopeOf(other, minted())]);
            await writeFile(join(dir, "f.txt"), "v1");
            for (const scope of [...own, ...others]) {
                assert.deepEqual(await store.trackEdit(scope, join(dir, "f.txt"), env, dir), { ok: true, minted: true }, `track under ${scope}`);
                assert.deepEqual(await store.snapshot(scope, "b1", env, dir), { ok: true }, `boundary under ${scope}`);
            }
            assert.ok((await store.deleteUnreadableSessionHistory(id)) > 0, "the id's history was erased and counted");
            for (const scope of own)
                assert.equal(await store.canRestore(scope, "b1"), false, `${scope} is one of ${id}'s scopes and is erased`);
            for (const scope of others)
                assert.equal(await store.canRestore(scope, "b1"), true, `${scope} is another id's scope and keeps its history`);
            assert.equal(await store.deleteUnreadableSessionHistory(id), 0, "a repeat finds nothing");
        });
    });
    run("structural out-of-scope (cowork guarantee) + T-1 positive control + G4 zero listDir: restore IO lands ONLY on tracked files, and no verb enumerates directories", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "tracked.txt"), "v1");
            await writeFile(join(dir, "user-parallel.txt"), "user-work");
            const probe = probeOver(env);
            assert.deepEqual(await store.trackEdit("sc", join(dir, "tracked.txt"), probe.env, dir), { ok: true, minted: true });
            await writeFile(join(dir, "tracked.txt"), "v2");
            assert.deepEqual(await store.snapshot("sc", "b", probe.env, dir), { ok: true });
            await writeFile(join(dir, "tracked.txt"), "diverged");
            await writeFile(join(dir, "user-new.txt"), "created-after-boundary");
            const r = await store.restore("sc", "b", probe.env, dir);
            assert.equal(r.outcome, "complete");
            assert.ok(probe.touched(join(dir, "tracked.txt")) > 0, "T-1 positive control: the tracked target must show IO in the SAME probe");
            assert.equal(probe.touched(join(dir, "user-parallel.txt")), 0, "a user's parallel file must be structurally invisible");
            assert.equal(probe.touched(join(dir, "user-new.txt")), 0, "a post-boundary user file must be structurally invisible");
            assert.equal(probe.calls.get("listDir") ?? 0, 0, "G4: zero directory enumeration across every verb");
            assert.equal(await readFile(join(dir, "tracked.txt"), "utf8"), "v2");
            assert.equal(await readFile(join(dir, "user-parallel.txt"), "utf8"), "user-work");
        });
    });
    run("annulTrack: the caller's own mint is retractable with ZERO env IO and the path goes structurally invisible again; an absent record is idempotent-ok", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "anchor.txt"), "anchor-v1");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "anchor.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "never-written.txt"), env, dir), { ok: true, minted: true });
            const probe = probeOver(env);
            assert.deepEqual(await store.annulTrack("sc", join(dir, "never-written.txt"), dir), { ok: true });
            assert.equal([...probe.calls.values()].reduce((a, b) => a + b, 0), 0, "annulTrack without a verify env is a pure record discard — it must perform NO env IO");
            assert.deepEqual(await store.annulTrack("sc", join(dir, "never-written.txt"), dir), { ok: true }, "annulling an absent record is idempotent-ok (the retry arm)");
            await writeFile(join(dir, "never-written.txt"), "USER BYTES");
            await writeFile(join(dir, "anchor.txt"), "anchor-edited");
            const r = await store.restore("sc", "b1", env, dir);
            assert.equal(r.outcome, "complete");
            assert.deepEqual(r.refused, []);
            assert.equal(await readFile(join(dir, "never-written.txt"), "utf8"), "USER BYTES", "the annulled path is structurally out of scope again — restore must not delete it");
            assert.equal(r.filesChanged.some((p) => p.includes("never-written")), false, "an annulled path must not even appear in the ledger");
            assert.equal(await readFile(join(dir, "anchor.txt"), "utf8"), "anchor-v1", "positive control: the genuinely tracked file DID converge in the same restore");
        });
    });
    run("annulTrack EVIDENCE arm: with an env supplied, a path whose bytes moved since the mint keeps its record (deleting a modified file's only baseline is worse than a stale record); an unchanged path still retracts", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "moved.txt"), "pristine");
            await writeFile(join(dir, "still.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "moved.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "still.txt"), env, dir), { ok: true, minted: true });
            await writeFile(join(dir, "moved.txt"), "half-written by the failing write");
            const refused = await store.annulTrack("sc", join(dir, "moved.txt"), dir, { env });
            assert.equal(refused.ok, false, "a changed file keeps its baseline");
            if (!refused.ok)
                assert.equal(refused.error.code, "conflict");
            assert.deepEqual(await store.annulTrack("sc", join(dir, "still.txt"), dir, { env }), { ok: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            await writeFile(join(dir, "moved.txt"), "diverged");
            await writeFile(join(dir, "still.txt"), "USER BYTES");
            const r = await store.restore("sc", "b1", env, dir);
            assert.equal(await readFile(join(dir, "moved.txt"), "utf8"), "half-written by the failing write", "the kept record still protects the modified file");
            assert.equal(await readFile(join(dir, "still.txt"), "utf8"), "USER BYTES", "the retracted one is structurally out of scope again");
            assert.equal(r.outcome, "complete");
        });
    });
    run("annulTrack EVIDENCE arm, base-unavailable case: the DV-14 marker is the refusal state itself, so an ambiguous retraction may not erase it (the PROVEN path still may)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            assert.deepEqual(await store.snapshot("sc", "b0", env, dir), { ok: true });
            await writeFile(join(dir, "opaque.txt"), "true-pristine");
            await writeFile(join(dir, "opaque2.txt"), "true-pristine");
            const hostile = envWithFailingRead(env, async () => ({ ok: false, error: { code: "unknown", message: "pristine unreadable" } }));
            const t = await store.trackEdit("sc", join(dir, "opaque.txt"), hostile, dir);
            if (t.ok === false)
                return;
            const refused = await store.annulTrack("sc", join(dir, "opaque.txt"), dir, { env });
            assert.equal(refused.ok, false, "an ambiguous retraction must not erase a base-unavailable marker");
            if (!refused.ok)
                assert.equal(refused.error.code, "conflict");
            const t2 = await store.trackEdit("sc", join(dir, "opaque2.txt"), hostile, dir);
            if (t2.ok)
                assert.deepEqual(await store.annulTrack("sc", join(dir, "opaque2.txt"), dir), { ok: true });
            await writeFile(join(dir, "opaque.txt"), "agent-edited");
            const r = await store.restore("sc", "b0", env, dir);
            assert.equal(r.refused.some((f) => f.reason.includes("base_unavailable") && f.class === "base_unavailable"), true, `the kept marker must still refuse a below-base restore, classed base_unavailable: ${JSON.stringify(r)}`);
            assert.equal(await readFile(join(dir, "opaque.txt"), "utf8"), "agent-edited", "never overwritten with a fake baseline");
        });
    });
    run("annulTrack's proof read that cannot re-read the path judged nothing: track_failed (aborted when the signal fired), no permanence, the record kept — never the history law's conflict", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "pristine");
            await writeFile(join(dir, "g.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "g.txt"), env, dir), { ok: true, minted: true });
            const unreadable = envWithFailingRead(env, async () => ({ ok: false, error: { code: "unknown", message: "transport gone" } }));
            const unjudged = await store.annulTrack("sc", join(dir, "f.txt"), dir, { env: unreadable });
            assert.equal(unjudged.ok, false, "an unread proof never retracts");
            if (!unjudged.ok) {
                assert.equal(unjudged.error.code, "track_failed", `a proof that could not be read is the verb's failure, not the law: ${JSON.stringify(unjudged)}`);
                assert.equal(unjudged.error.permanence, undefined, "an env read error is not the store's own storage fault — unjudged");
            }
            const aborted = new AbortController();
            aborted.abort();
            const cut = await store.annulTrack("sc", join(dir, "g.txt"), dir, { env, signal: aborted.signal });
            assert.equal(cut.ok, false, "a proof read cut by the signal never retracts");
            if (!cut.ok)
                assert.equal(cut.error.code, "aborted", `the signal fired: ${JSON.stringify(cut)}`);
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "diverged");
            await writeFile(join(dir, "g.txt"), "diverged");
            const r = await store.restore("sc", "b1", env, dir);
            assert.equal(r.outcome, "complete");
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "pristine", "the unjudged retraction left the record intact");
            assert.equal(await readFile(join(dir, "g.txt"), "utf8"), "pristine", "the aborted retraction left the record intact");
        });
    });
    run("annulTrack refuses what is no longer a mint: a boundary-referenced record is history (typed conflict, record intact)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            const busy = await store.annulTrack("sc", join(dir, "f.txt"), dir);
            assert.equal(busy.ok, false, "a record a committed boundary references is not the caller's to withdraw");
            if (!busy.ok)
                assert.equal(busy.error.code, "conflict");
            await writeFile(join(dir, "f.txt"), "diverged");
            const r = await store.restore("sc", "b1", env, dir);
            assert.equal(r.outcome, "complete");
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "pristine", "the refusal left the record fully intact");
        });
    });
    run("never-throw against a hostile env: a rejecting readBinaryFile yields typed results on every verb, never an exception", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "f.txt"), "v1");
            const hostile = envWithFailingRead(env, async () => {
                throw new Error("hostile env rejection");
            });
            const t = await store.trackEdit("sc", join(dir, "f.txt"), hostile, dir);
            assert.equal(typeof t.ok, "boolean");
            if (!t.ok)
                assertPermanenceWord(t.error, "trackEdit over a hostile env");
            const sHealthy = await store.trackEdit("sc2", join(dir, "f.txt"), env, dir);
            assert.deepEqual(sHealthy, { ok: true, minted: true });
            const snap = await store.snapshot("sc2", "b", hostile, dir);
            assert.equal(snap.ok, false);
            if (!snap.ok)
                assertPermanenceWord(snap.error, "snapshot over a hostile env");
            const r = await store.restore("sc2", "nope", hostile, dir);
            assert.equal(r.outcome, "failed");
        });
    });
    run("DV-14 marker honesty: a backend that TOLERATES an uncapturable pristine (trackEdit ok despite a hostile read) must REFUSE a below-base restore for that path — never silently omit it, never overwrite with a fake baseline", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            assert.deepEqual(await store.snapshot("sc", "b0", env, dir), { ok: true });
            await writeFile(join(dir, "f.txt"), "true-pristine");
            const hostile = envWithFailingRead(env, async () => ({ ok: false, error: { code: "unknown", message: "pristine unreadable" } }));
            const t = await store.trackEdit("sc", join(dir, "f.txt"), hostile, dir);
            if (t.ok === false)
                return;
            await writeFile(join(dir, "f.txt"), "agent-edited");
            const r = await store.restore("sc", "b0", env, dir);
            assert.equal(r.outcome, "partial", "a below-base path must surface as a REFUSAL, not fold into complete");
            assert.equal(r.refused.some((f) => f.reason.includes("base_unavailable")), true, "the refusal must name base_unavailable");
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "agent-edited");
        });
    });
    run("track-key COORDINATE (A-082 idx5): an under-root capture is keyed root-relative and an outside-root path verbatim-absolute; a restore handed another root writes neither root's under-root file (the version records the old directory) and restores the outside-root path in place", async () => {
        await withTree(async (dirA, envA) => {
            await withTree(async (dirB) => {
                await withTree(async (outside, _envOut) => {
                    void _envOut;
                    const store = make();
                    const outsideFile = join(outside, "o.txt");
                    await mkdir(join(dirA, "sub"), { recursive: true });
                    await writeFile(join(dirA, "sub", "f.txt"), "P-under-root");
                    await writeFile(outsideFile, "P-outside-root");
                    assert.deepEqual(await store.trackEdit("sc", join(dirA, "sub", "f.txt"), envA, dirA), { ok: true, minted: true });
                    assert.deepEqual(await store.trackEdit("sc", outsideFile, envA, dirA), { ok: true, minted: true });
                    assert.deepEqual(await store.snapshot("sc", "b1", envA, dirA), { ok: true });
                    await writeFile(join(dirA, "sub", "f.txt"), "EDITED");
                    await writeFile(outsideFile, "EDITED");
                    await mkdir(join(dirB, "sub"), { recursive: true });
                    await writeFile(join(dirB, "sub", "f.txt"), "EDITED");
                    const envB = new NodeExecutionEnv({ cwd: dirB });
                    const r = await store.restore("sc", "b1", envB, dirB);
                    assert.equal(r.outcome, "complete", `the under-root version recorded outside this root is left as it is, not refused, got ${JSON.stringify(r)}`);
                    assert.deepEqual(r.refused, []);
                    assert.deepEqual((r.leftAsIs ?? []).map((f) => [f.path, f.class]), [["sub/f.txt", "recorded_outside_root"]], "the under-root key is root-relative and its version records dirA, outside dirB");
                    assert.equal(await readFile(join(dirB, "sub", "f.txt"), "utf8"), "EDITED", "the CURRENT root's same-named file is not written");
                    assert.equal(await readFile(join(dirA, "sub", "f.txt"), "utf8"), "EDITED", "the OLD root is not written either (the key was rel, not absolute)");
                    assert.equal(await readFile(outsideFile, "utf8"), "P-outside-root", "an outside-root key is verbatim-absolute — it restores where it was captured, root move or not");
                });
            });
        });
    });
    run("export/import round trip AFTER a reap: the complete retained state travels (v1 fallbacks, key self-description; never a version's place) and the importing scope serves BOTH a boundary restore and the pristine fallback where the rewind names the directory they were recorded under", async () => {
        await withTree(async (dir, env) => {
            const src = make();
            if (src.exportHistory === undefined || src.importHistory === undefined)
                return;
            const shed = contentShed();
            await shed.write(join(dir, "keep.txt"), "pristine");
            assert.deepEqual(await src.snapshot("sc", "b0", env, dir), { ok: true });
            assert.deepEqual(await src.trackEdit("sc", join(dir, "keep.txt"), env, dir), { ok: true, minted: true });
            await shed.write(join(dir, "keep.txt"), "turn-1");
            assert.deepEqual(await src.snapshot("sc", "b1", env, dir), { ok: true });
            assert.equal(await src.reap("sc", ["b0", "b1"]), 0);
            const exported = await src.exportHistory("sc");
            const envelope = exported.ok ? exported.history : null;
            assert.ok(envelope !== null, "a scope with history must export an envelope");
            assert.equal(envelope.formatVersion, "file-history/1");
            assert.ok(envelope.tracked.every((t) => (t.keyKind === "root-relative" || t.keyKind === "absolute") && (t.keyFamily === "posix" || t.keyFamily === "win")), "every tracked row must carry its key's self-description (kind + family) — a bare key cannot be judged after it crosses machines");
            const dst = make();
            const carried = await dst.importHistory("carried", envelope, shed.fetch);
            assert.deepEqual(carried, { ok: true });
            assert.equal(await dst.canRestore("carried", "b1"), true);
            await writeFile(join(dir, "keep.txt"), "diverged");
            const unnamed = await dst.restore("carried", "b1", env, dir);
            assert.deepEqual(unnamed.refused.map((f) => [f.path, f.class]), [["keep.txt", "place_unrecorded"]], `an imported version records no place: ${JSON.stringify(unnamed)}`);
            const named = { unplacedHistoryRecordedUnder: dir };
            const r1 = await dst.restore("carried", "b1", env, dir, undefined, named);
            assert.equal(r1.outcome, "complete", `imported boundary restore: ${JSON.stringify(r1)}`);
            assert.equal(await readFile(join(dir, "keep.txt"), "utf8"), "turn-1");
            const r0 = await dst.restore("carried", "b0", env, dir, undefined, named);
            assert.equal(r0.outcome, "complete");
            assert.equal(await readFile(join(dir, "keep.txt"), "utf8"), "pristine", "the v1 fallback travelled: a boundary that predates the track still restores pristine");
        });
    });
    run("import door refuses, never coerces: a foreign formatVersion and an unknown key self-description are typed unsupported_format with NOTHING published", async () => {
        await withTree(async (_dir, env) => {
            void _dir;
            const store = make();
            if (store.importHistory === undefined)
                return;
            const foreignEpoch = wireEnvelope({ formatVersion: "file-snapshot/1", tracked: [], boundaries: [] });
            const v = await store.importHistory("sc", foreignEpoch, async () => undefined);
            assert.equal(v.ok, false);
            if (!v.ok)
                assert.equal(v.error.code, "unsupported_format");
            const unknownFamily = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: "a.txt", keyKind: "root-relative", keyFamily: "vms", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] }],
                boundaries: [{ entryId: "b1", files: [{ relOrAbsPath: "a.txt", version: 1 }] }],
            });
            const f = await store.importHistory("sc", unknownFamily, async () => undefined);
            assert.equal(f.ok, false);
            if (!f.ok)
                assert.equal(f.error.code, "unsupported_format");
            assert.equal(await store.canRestore("sc", "b1"), false, "a refused import must publish nothing at all");
            const missingBlob = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: "a.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: "a".repeat(64), backupTime: "t" }] }],
                boundaries: [{ entryId: "b2", files: [{ relOrAbsPath: "a.txt", version: 1 }] }],
            });
            const m = await store.importHistory("sc", missingBlob, async () => undefined);
            assert.equal(m.ok, false);
            if (!m.ok)
                assert.equal(m.error.code, "adopt_failed", "a source that cannot supply a referenced blob");
            if (!m.ok)
                assertPermanenceWord(m.error, "importHistory whose source has no such blob");
            assert.equal(await store.canRestore("sc", "b2"), false);
            const thrown = await store.importHistory("sc", missingBlob, async () => {
                throw Object.assign(new Error("source blob unreadable"), { code: "EACCES" });
            });
            assert.equal(thrown.ok, false);
            if (!thrown.ok)
                assert.equal(thrown.error.code, "adopt_failed", "a source whose read throws cannot supply a referenced blob");
            if (!thrown.ok)
                assertPermanenceWord(thrown.error, "importHistory whose source fetch threw");
            assert.equal(await store.canRestore("sc", "b2"), false);
            const wrongBytes = await store.importHistory("sc", missingBlob, async () => new TextEncoder().encode("bytes that are not the content this address names"));
            assert.equal(wrongBytes.ok, false);
            if (!wrongBytes.ok)
                assert.equal(wrongBytes.error.code, "adopt_failed", "a source whose bytes fail their content address cannot supply a referenced blob");
            if (!wrongBytes.ok)
                assertPermanenceWord(wrongBytes.error, "importHistory whose source served the wrong bytes");
            assert.equal(await store.canRestore("sc", "b2"), false);
            const duplicated = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [
                    { relOrAbsPath: "dup.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] },
                    { relOrAbsPath: "dup.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }, { version: 2, blobHash: null, backupTime: "t" }] },
                ],
                boundaries: [{ entryId: "b3", files: [{ relOrAbsPath: "dup.txt", version: 1 }] }],
            });
            const outOfOrder = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [
                    {
                        relOrAbsPath: "ooo.txt",
                        keyKind: "root-relative",
                        keyFamily: "posix",
                        baseAvailable: true,
                        versions: [
                            { version: 1, blobHash: null, backupTime: "t" },
                            { version: 3, blobHash: null, backupTime: "t" },
                            { version: 2, blobHash: null, backupTime: "t" },
                        ],
                    },
                ],
                boundaries: [{ entryId: "b4", files: [{ relOrAbsPath: "ooo.txt", version: 1 }] }],
            });
            const o = await store.importHistory("sc", outOfOrder, async () => undefined);
            assert.equal(o.ok, false, "an out-of-order version chain must be refused — a later local boundary would reference an ambiguous version");
            if (!o.ok)
                assert.match(o.error.message, /strictly increasing/);
            assert.equal(await store.canRestore("sc", "b4"), false);
            const d = await store.importHistory("sc", duplicated, async () => undefined);
            assert.equal(d.ok, false, "duplicate tracked rows must be refused — the published graph would differ from the validated one");
            if (!d.ok)
                assert.match(d.error.message, /twice/);
            assert.equal(await store.canRestore("sc", "b3"), false);
            void env;
        });
    });
    run("import AUTHORITY BOUND: an envelope may not carry an absolute key or an escaping relative one — a graph that would grant restore authority over a path outside the importing root publishes NOTHING", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            if (store.importHistory === undefined)
                return;
            const outsideVictim = join(dir, "victim-outside.txt");
            await writeFile(outsideVictim, "not the agent's file");
            const absolutePayload = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: outsideVictim, keyKind: "absolute", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] }],
                boundaries: [{ entryId: "bA", files: [{ relOrAbsPath: outsideVictim, version: 1 }] }],
            });
            const a = await store.importHistory("hostile", absolutePayload, async () => undefined);
            assert.equal(a.ok, false, "an absolute imported key must be refused at the door");
            if (!a.ok) {
                assert.equal(a.error.code, "unsupported_format");
                assert.match(a.error.message, /ABSOLUTE key/, `the refusal must name the authority bound: ${a.error.message}`);
            }
            const escaping = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: "../escape.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] }],
                boundaries: [{ entryId: "bB", files: [{ relOrAbsPath: "../escape.txt", version: 1 }] }],
            });
            const b = await store.importHistory("hostile", escaping, async () => undefined);
            assert.equal(b.ok, false, "a '..' relative key must be refused at the door, not per-file at restore");
            assert.equal(await store.canRestore("hostile", "bA"), false);
            assert.equal(await store.canRestore("hostile", "bB"), false);
            const r = await store.restore("hostile", "bA", env, dir);
            assert.equal(r.outcome, "failed");
            assert.equal(await readFile(outsideVictim, "utf8"), "not the agent's file", "the victim path was never in reach");
        });
    });
    run("export carries only the entries that travel, and no version's place: an absolute-key entry is left out and counted (absoluteEntriesOmitted, never its path) and no version carries an absolute parentIdent, so the envelope passes the import door; an envelope carrying a place, or a malformed count, is refused at the door", async () => {
        await withTree(async (dir, env) => {
            await withTree(async (outside) => {
                const src = make();
                if (src.exportHistory === undefined || src.importHistory === undefined)
                    return;
                const shed = contentShed();
                await shed.write(join(dir, "f.txt"), "f-0");
                await shed.write(join(outside, "o.txt"), "o-0");
                assert.deepEqual(await src.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await src.trackEdit("sc", join(outside, "o.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await src.snapshot("sc", "b1", env, dir), { ok: true });
                const exported = await src.exportHistory("sc");
                const envelope = exported.ok ? exported.history : null;
                assert.ok(envelope !== null, JSON.stringify(exported));
                assert.deepEqual(envelope.tracked.map((t) => [t.relOrAbsPath, t.keyKind]), [["f.txt", "root-relative"]], "only the root-relative entry travels");
                assert.deepEqual(envelope.boundaries.map((b) => b.files.map((f) => f.relOrAbsPath)), [["f.txt"]], "and no boundary names the one left out");
                assert.equal(envelope.absoluteEntriesOmitted, 1, "the one left out is counted");
                assert.equal(JSON.stringify(envelope).includes(outside), false, "the left-out path does not travel");
                const placed = envelope.tracked.flatMap((t) => t.versions.filter((v) => v.parentIdent !== undefined && !fileHistoryParentIdentTravels(v.parentIdent)).map((v) => `${t.relOrAbsPath}@v${v.version}`));
                assert.deepEqual(placed, [], "no version's place travels (the importing door refuses an envelope that carries one)");
                const dst = make();
                assert.deepEqual(await dst.importHistory("carried", envelope, shed.fetch), { ok: true });
                const withPlace = wireEnvelope({ ...envelope, tracked: envelope.tracked.map((t) => ({ ...t, versions: t.versions.map((v) => ({ ...v, parentIdent: dir })) })) });
                const placeRefused = await make().importHistory("y", withPlace, shed.fetch);
                assert.equal(placeRefused.ok ? "ok" : placeRefused.error.code, "unsupported_format", "an envelope carrying a version's place is refused at the door");
                for (const bad of [-1, 1.5, "2", null]) {
                    const refused = await make().importHistory("x", wireEnvelope({ ...envelope, absoluteEntriesOmitted: bad }), shed.fetch);
                    assert.equal(refused.ok ? "ok" : refused.error.code, "unsupported_format", `absoluteEntriesOmitted ${JSON.stringify(bad)} is refused at the door`);
                }
            });
        });
    });
    run("annulTrack refuses a mint ANOTHER lane is already relying on: two edits race one path, the first fails its write, and the second's baseline survives", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            await writeFile(join(dir, "contended.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "contended.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "contended.txt"), env, dir), { ok: true, minted: false });
            await writeFile(join(dir, "contended.txt"), "B's edit landed");
            const annul = await store.annulTrack("sc", join(dir, "contended.txt"), dir);
            assert.equal(annul.ok, false, "a record another lane was served is no longer the minter's to retract");
            if (!annul.ok)
                assert.equal(annul.error.code, "conflict");
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "contended.txt"), env, dir), { ok: true, minted: false });
            const r = await store.restore("sc", "b1", env, dir);
            assert.equal(r.outcome, "complete");
            assert.equal(await readFile(join(dir, "contended.txt"), "utf8"), "B's edit landed");
        });
    });
    run("import NON-DESTRUCTIVE target law: the identical envelope re-imports idempotently, while a DIFFERENT graph over locally-grown history is refused typed and the target survives intact", async () => {
        await withTree(async (dir, env) => {
            const src = make();
            if (src.exportHistory === undefined || src.importHistory === undefined)
                return;
            const shed = contentShed();
            await shed.write(join(dir, "f.txt"), "source-pristine");
            assert.deepEqual(await src.trackEdit("sc", join(dir, "f.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await src.snapshot("sc", "b1", env, dir), { ok: true });
            const exported = await src.exportHistory("sc");
            assert.ok(exported.ok && exported.history !== null, "a scope with history must export an envelope");
            const envelope = exported.history;
            const dst = make();
            assert.deepEqual(await dst.importHistory("target", envelope, shed.fetch), { ok: true });
            assert.deepEqual(await dst.importHistory("target", envelope, shed.fetch), { ok: true }, "the same envelope arriving twice is a re-publish, not a conflict");
            await shed.write(join(dir, "local.txt"), "local-work");
            assert.deepEqual(await dst.trackEdit("target", join(dir, "local.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await dst.snapshot("target", "b-local", env, dir), { ok: true });
            const other = await src.exportHistory("sc");
            assert.ok(other.ok && other.history !== null);
            const conflict = await dst.importHistory("target", other.history, shed.fetch);
            assert.equal(conflict.ok, false);
            if (!conflict.ok)
                assert.equal(conflict.error.code, "conflict");
            assert.equal(await dst.canRestore("target", "b-local"), true, "the refusal left the target's own history intact");
            assert.equal(await dst.canRestore("target", "b1"), true);
        });
    });
    run("FOREIGN-FAMILY keys are refused at restore, not re-pointed at this machine's tree (the self-describing key's whole purpose)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            if (store.importHistory === undefined)
                return;
            const foreign = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [
                    { relOrAbsPath: "D:\\other\\machine\\x.txt", keyKind: "absolute", keyFamily: "win", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] },
                    { relOrAbsPath: "sub\\deep.txt", keyKind: "root-relative", keyFamily: "win", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] },
                ],
                boundaries: [
                    {
                        entryId: "bw",
                        files: [
                            { relOrAbsPath: "D:\\other\\machine\\x.txt", version: 1 },
                            { relOrAbsPath: "sub\\deep.txt", version: 1 },
                        ],
                    },
                ],
            });
            const imported = await store.importHistory("foreign", foreign, async () => undefined);
            if (!imported.ok)
                return;
            const r = await store.restore("foreign", "bw", env, dir);
            assert.equal(r.outcome, "partial", `foreign-family rows must surface as refusals: ${JSON.stringify(r)}`);
            assert.equal(r.refused.length, 2, "each foreign-family key is refused by name");
            assert.ok(r.refused.every((f) => /foreign-family/.test(f.reason)), `the refusal must name the provenance mismatch: ${JSON.stringify(r.refused)}`);
            assert.deepEqual(r.filesChanged, [], "nothing under this root may be touched on behalf of a foreign-family record");
        });
    });
    run("mode (DV-8): a recorded POSIX mode is restored with the bytes — including on a file the restore has to RE-CREATE", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            const script = join(dir, "run.sh");
            await writeFile(script, "#!/bin/sh\necho v1\n");
            await chmod(script, 0o755);
            assert.deepEqual(await store.trackEdit("sc", script, env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            const recorded = (await stat(script)).mode & 0o7777;
            if (recorded !== 0o755)
                return;
            await writeFile(script, "#!/bin/sh\necho edited\n");
            await chmod(script, 0o644);
            const back = await store.restore("sc", "b1", env, dir);
            assert.equal(back.outcome, "complete", JSON.stringify(back));
            assert.equal((await stat(script)).mode & 0o7777, 0o755, "the boundary's mode travels with its bytes");
            await rm(script);
            const revived = await store.restore("sc", "b1", env, dir);
            assert.equal(revived.outcome, "complete", JSON.stringify(revived));
            assert.equal((await stat(script)).mode & 0o7777, 0o755, "a re-created file gets the recorded mode, not the umask default");
            assert.equal(revived.modeNotPreserved ?? 0, 0, "an env WITH the mode face reports nothing unpreserved");
        });
    });
    run("mode (DV-8) honest degradation: an env without the optional setFileMode face restores the BYTES and DISCLOSES the unpreserved mode (never silently, never fatally)", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            const script = join(dir, "run.sh");
            await writeFile(script, "v1");
            await chmod(script, 0o755);
            assert.deepEqual(await store.trackEdit("sc", script, env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            if (((await stat(script)).mode & 0o7777) !== 0o755)
                return;
            await rm(script);
            const modeless = new Proxy(env, {
                get(target, prop, receiver) {
                    if (prop === "setFileMode")
                        return undefined;
                    return Reflect.get(target, prop, receiver);
                },
            });
            const r = await store.restore("sc", "b1", modeless, dir);
            assert.equal(r.outcome, "complete", "a mode that cannot be applied is a disclosure, not a failure");
            assert.deepEqual(r.filesChanged, [key(dir, script)], "the BYTES still converge");
            assert.equal(r.modeNotPreserved, 1, "…and the count says so — the honest-absence law, in the ledger");
        });
    });
    run("restore preflight: an in-root ancestor swapped for a link OUT of the root is REFUSED per file, a whole-root move leaves the file as it is (recorded outside the new root; the version restores where it was recorded), a version recorded under a directory inside the root it is handed is refused as recorded elsewhere, and the rest of the set converges either way", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            const outside = await mkdtemp(join(tmpdir(), "fh-kit-outside-"));
            try {
                await mkdir(join(dir, "d"), { recursive: true });
                await writeFile(join(dir, "d", "f.txt"), "pristine");
                await writeFile(join(dir, "sibling.txt"), "sibling-pristine");
                assert.deepEqual(await store.trackEdit("sc", join(dir, "d", "f.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await store.trackEdit("sc", join(dir, "sibling.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
                await writeFile(join(dir, "d", "f.txt"), "agent-edited");
                await writeFile(join(dir, "sibling.txt"), "agent-edited");
                await writeFile(join(outside, "f.txt"), "OUTSIDE-UNTOUCHED");
                await rm(join(dir, "d"), { recursive: true, force: true });
                await symlink(outside, join(dir, "d"), "dir");
                const r = await store.restore("sc", "b1", env, dir);
                assert.equal(r.outcome, "partial", JSON.stringify(r));
                assert.deepEqual(r.refused.map((x) => x.path), [key(dir, join(dir, "d", "f.txt"))], "the swapped path — and ONLY it — is refused");
                assert.equal(await readFile(join(outside, "f.txt"), "utf8"), "OUTSIDE-UNTOUCHED", "E5: zero writes outside the root");
                assert.deepEqual(r.filesChanged, [key(dir, join(dir, "sibling.txt"))], "a security refusal never fails the whole restore");
            }
            finally {
                await rm(outside, { recursive: true, force: true });
            }
        });
        await withTree(async (oldRoot, env) => {
            const store = make();
            await mkdir(join(oldRoot, "d"), { recursive: true });
            await writeFile(join(oldRoot, "d", "f.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(oldRoot, "d", "f.txt"), env, oldRoot), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, oldRoot), { ok: true });
            await writeFile(join(oldRoot, "d", "f.txt"), "old-root-edited");
            await withTree(async (newRoot, newEnv) => {
                await mkdir(join(newRoot, "d"), { recursive: true });
                await writeFile(join(newRoot, "d", "f.txt"), "new-root-own");
                const r = await store.restore("sc", "b1", newEnv, newRoot);
                assert.equal(r.outcome, "complete", `a version recorded under a directory outside this root is left as it is, never re-pointed or refused: ${JSON.stringify(r)}`);
                assert.deepEqual(r.refused, []);
                assert.deepEqual((r.leftAsIs ?? []).map((f) => [f.path, f.class, f.place]), [["d/f.txt", "recorded_outside_root", join(oldRoot, "d")]], "the row names the directory the version was recorded under");
                assert.deepEqual(r.filesChanged, []);
                assert.equal(await readFile(join(newRoot, "d", "f.txt"), "utf8"), "new-root-own", "the new root's file is not written");
                assert.equal(await readFile(join(oldRoot, "d", "f.txt"), "utf8"), "old-root-edited", "nor the old root's");
                const back = await store.restore("sc", "b1", env, oldRoot);
                assert.equal(back.outcome, "complete", JSON.stringify(back));
                assert.equal(await readFile(join(oldRoot, "d", "f.txt"), "utf8"), "pristine");
            });
        });
        await withTree(async (r, env) => {
            const store = make();
            const below = join(r, "x");
            await mkdir(below, { recursive: true, mode: 0o700 });
            await writeFile(join(below, "f.txt"), "pristine");
            assert.deepEqual(await store.trackEdit("sc", join(below, "f.txt"), env, below), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, below), { ok: true });
            await writeFile(join(below, "f.txt"), "edited-below");
            const r2 = await store.restore("sc", "b1", env, r);
            assert.equal(r2.outcome, "partial", JSON.stringify(r2));
            assert.deepEqual([r2.refused.map((f) => [f.path, f.class]), r2.leftAsIs ?? []], [[["f.txt", "recorded_elsewhere"]], []]);
            assert.equal(await readFile(join(below, "f.txt"), "utf8"), "edited-below");
            assert.equal(await existsAt(join(r, "f.txt")), false, "nothing is created at the root's own key path");
        });
    });
    run("K1 one relative name, two files: a boundary taken under another root re-reads each tracked file where it was recorded, never the same-named file it was handed", async () => {
        await withTree(async (r, env) => {
            const store = make();
            const x = join(r, "x");
            await mkdir(join(r, "src"), { recursive: true, mode: 0o700 });
            await mkdir(join(x, "src"), { recursive: true, mode: 0o700 });
            await writeFile(join(r, "src", "i.ts"), "r-0");
            await writeFile(join(x, "src", "i.ts"), "x-0");
            assert.deepEqual(await store.trackEdit("sc", join(r, "src", "i.ts"), env, r), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, r), { ok: true });
            await writeFile(join(r, "src", "i.ts"), "r-1");
            const envX = new NodeExecutionEnv({ cwd: x });
            assert.deepEqual(await store.snapshot("sc", "b2", envX, x), { ok: true });
            await writeFile(join(x, "src", "i.ts"), "x-person");
            const back = await store.restore("sc", "b2", envX, x);
            assert.equal(await readFile(join(x, "src", "i.ts"), "utf8"), "x-person", `a file the history never touched is not written: ${JSON.stringify(back)}`);
            assert.equal(await readFile(join(r, "src", "i.ts"), "utf8"), "r-1");
            assert.deepEqual(back.filesChanged, []);
        });
    });
    run("K2 a boundary reads no file through a link out of the root: an imported key that runs through one, and a tracked file swapped for one, are held, their outside bytes never read", async () => {
        const reading = (env, seen) => new Proxy(env, {
            get(target, prop, receiver) {
                const value = Reflect.get(target, prop, receiver);
                if (typeof value !== "function")
                    return value;
                const fn = value;
                return (...args) => {
                    if ((prop === "readBinaryFile" || prop === "readTextFile" || prop === "readTextLines" || prop === "openBound") && typeof args[0] === "string")
                        seen.push(args[0]);
                    return fn.apply(target, args);
                };
            },
        });
        await withTree(async (outside) => {
            await writeFile(join(outside, "secret"), "OUTSIDE-SECRET");
            await withTree(async (r, plain) => {
                const store = make();
                await symlink(outside, join(r, "link"));
                await mkdir(join(r, "d"), { recursive: true, mode: 0o700 });
                await writeFile(join(r, "d", "f.txt"), "mine");
                assert.deepEqual(await store.trackEdit("sc", join(r, "d", "f.txt"), plain, r), { ok: true, minted: true });
                assert.deepEqual(await store.snapshot("sc", "b1", plain, r), { ok: true });
                await rm(join(r, "d", "f.txt"));
                await symlink(join(outside, "secret"), join(r, "d", "f.txt"));
                const seen = [];
                const env = reading(plain, seen);
                if (store.importHistory !== undefined) {
                    const linked = wireEnvelope({
                        formatVersion: "file-history/1",
                        tracked: [{ relOrAbsPath: "link/secret", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: null, backupTime: "t" }] }],
                        boundaries: [{ entryId: "i1", files: [{ relOrAbsPath: "link/secret", version: 1 }] }],
                    });
                    assert.deepEqual(await store.importHistory("imported", linked, async () => undefined), { ok: true });
                    assert.deepEqual(await store.snapshot("imported", "i2", env, r), { ok: true });
                }
                assert.deepEqual(await store.snapshot("sc", "b2", env, r), { ok: true });
                const leaked = seen.filter((p) => p.startsWith(`${outside}/`) || p.startsWith(`${join(r, "link")}/`) || p === join(r, "d", "f.txt"));
                assert.deepEqual(leaked, [], "no bytes read through a link out of the root");
            });
        });
    });
    run("K3 one key law: a trackEdit of a path through a link keys the file by its real path — out of the root, the outside file's absolute key (it does not travel; a rewind restores it there); inside it, the real relative name — and the retraction with the proof read names the same record", async () => {
        await withTree(async (outside) => {
            await writeFile(join(outside, "o.txt"), "o-0");
            await withTree(async (r, plain) => {
                const store = make();
                await mkdir(join(r, "real"), { recursive: true, mode: 0o700 });
                await writeFile(join(r, "real", "g.txt"), "g-0");
                await symlink(outside, join(r, "lnk"));
                await symlink(join(r, "real"), join(r, "inl"));
                assert.deepEqual(await store.trackEdit("sc", join(r, "lnk", "o.txt"), plain, r), { ok: true, minted: true });
                assert.deepEqual(await store.trackEdit("sc", join(outside, "o.txt"), plain, r), { ok: true, minted: false }, "the outside file by its real path is the same entry");
                assert.deepEqual(await store.trackEdit("sc", join(r, "inl", "g.txt"), plain, r), { ok: true, minted: true });
                assert.deepEqual(await store.trackEdit("sc", join(r, "real", "g.txt"), plain, r), { ok: true, minted: false }, "the inside file by its real path is the same entry");
                assert.deepEqual(await store.trackEdit("sc", join(r, "lnk", "new.txt"), plain, r), { ok: true, minted: true });
                assert.deepEqual(await store.annulTrack("sc", join(r, "lnk", "new.txt"), r, { env: plain }), { ok: true });
                assert.deepEqual(await store.trackEdit("sc", join(outside, "new.txt"), plain, r), { ok: true, minted: true }, "the retraction removed the record the touch through the link made");
                assert.deepEqual(await store.annulTrack("sc", join(outside, "new.txt"), r), { ok: true });
                assert.deepEqual(await store.snapshot("sc", "b1", plain, r), { ok: true });
                if (store.exportHistory !== undefined) {
                    const e = await store.exportHistory("sc");
                    assert.ok(e.ok && e.history !== null, JSON.stringify(e));
                    assert.deepEqual([e.history.tracked.map((t) => t.relOrAbsPath), e.history.absoluteEntriesOmitted, e.history.frozenEntryKeys], [["real/g.txt"], 1, undefined]);
                }
                await writeFile(join(outside, "o.txt"), "o-1");
                await rm(join(r, "lnk"));
                const res = await store.restore("sc", "b1", plain, r);
                assert.deepEqual([res.outcome, res.leftAsIs], ["complete", undefined], JSON.stringify(res));
                assert.equal(await readFile(join(outside, "o.txt"), "utf8"), "o-0", "restored where the file is");
            });
        });
    });
    run("K4 an entry recorded through a link on its key's path is frozen: a key imported through a link inside the root, once a boundary has recorded its place, is never read by a boundary again, a restore leaves it as it is and lists it in `leftAsIs` with the class `frozen_history` (outcome unaffected, nothing written), and an export leaves it out and names its key", async () => {
        await withTree(async (r, plain) => {
            const store = make();
            if (store.importHistory === undefined)
                return;
            await mkdir(join(r, "real"), { recursive: true, mode: 0o700 });
            await writeFile(join(r, "real", "g.txt"), "g-0");
            await symlink(join(r, "real"), join(r, "inl"));
            const hash = createHash("sha256").update("g-0").digest("hex");
            const envelope = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: "inl/g.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: hash, backupTime: "t" }] }],
                boundaries: [{ entryId: "b0", files: [{ relOrAbsPath: "inl/g.txt", version: 1 }] }],
            });
            assert.deepEqual(await store.importHistory("sc", envelope, async () => new TextEncoder().encode("g-0")), { ok: true });
            assert.deepEqual(await store.snapshot("sc", "b1", plain, r), { ok: true }, "the first boundary records the place: the real directory, not the key's");
            await writeFile(join(r, "real", "g.txt"), "g-1");
            const seen = [];
            const env = new Proxy(plain, {
                get(target, prop, receiver) {
                    const value = Reflect.get(target, prop, receiver);
                    if (typeof value !== "function")
                        return value;
                    const fn = value;
                    return (...args) => {
                        if ((prop === "readBinaryFile" || prop === "readTextFile" || prop === "readTextLines" || prop === "openBound" || prop === "writeFile" || prop === "writeFileGuarded" || prop === "remove") && typeof args[0] === "string")
                            seen.push(`${String(prop)} ${args[0]}`);
                        return fn.apply(target, args);
                    };
                },
            });
            assert.deepEqual(await store.snapshot("sc", "b2", env, r), { ok: true });
            const res = await store.restore("sc", "b1", env, r);
            assert.deepEqual([res.outcome, res.filesChanged, res.refused, res.leftAsIs?.map((f) => [f.path, f.class, f.place])], ["complete", [], [], [["inl/g.txt", "frozen_history", join(r, "real")]]], JSON.stringify(res));
            assert.deepEqual(seen, [], "neither the boundary nor the restore reads or writes the frozen file");
            assert.equal(await readFile(join(r, "real", "g.txt"), "utf8"), "g-1");
            if (store.exportHistory !== undefined) {
                const e = await store.exportHistory("sc");
                assert.ok(e.ok && e.history !== null, JSON.stringify(e));
                assert.deepEqual([e.history.tracked.map((t) => t.relOrAbsPath), e.history.frozenEntryKeys], [[], ["inl/g.txt"]]);
            }
        });
    });
    run("W1 a second file whose root-relative name another directory's file already keys is tracked under its own absolute key, and a rewind restores it where it was recorded", async () => {
        await withTree(async (a, envA) => {
            await withTree(async (b, envB) => {
                const store = make();
                await writeFile(join(a, "f.txt"), "a-0");
                await writeFile(join(b, "f.txt"), "b-0");
                assert.deepEqual(await store.trackEdit("sc", join(a, "f.txt"), envA, a), { ok: true, minted: true });
                assert.deepEqual(await store.snapshot("sc", "b1", envA, a), { ok: true });
                await writeFile(join(a, "f.txt"), "a-1");
                assert.deepEqual(await store.snapshot("sc", "b2", envB, b), { ok: true });
                assert.deepEqual(await store.trackEdit("sc", join(b, "f.txt"), envB, b), { ok: true, minted: true }, "the second file is a first touch of its own");
                assert.deepEqual(await store.trackEdit("sc", join(b, "g.txt"), envB, b), { ok: true, minted: true });
                await writeFile(join(b, "f.txt"), "b-1");
                await writeFile(join(b, "g.txt"), "b-g");
                const r = await store.restore("sc", "b2", envB, b);
                assert.equal(r.outcome, "complete", JSON.stringify(r));
                assert.equal(await readFile(join(b, "f.txt"), "utf8"), "b-0", "B's own edit is restored at B");
                assert.equal(await existsAt(join(b, "g.txt")), false, "B's created file is removed");
                assert.equal(await readFile(join(a, "f.txt"), "utf8"), "a-1", "A's file is not written by a rewind of B's turn");
                assert.ok(r.filesChanged.includes(join(b, "f.txt")) && r.filesChanged.includes("g.txt"), `the second file answers under its absolute key: ${JSON.stringify(r.filesChanged)}`);
            });
        });
    });
    run("FC the key choice after a carry: a fork whose carried history keys A's f.txt, handed B, edits B's own f.txt — a first touch of its own under its absolute key, restored at B (W1 holds the same choice within one session; this cell holds it across adoptScope, which must carry each version's place)", async () => {
        await withTree(async (a, envA) => {
            await withTree(async (b, envB) => {
                const store = make();
                await writeFile(join(a, "f.txt"), "a-0");
                await writeFile(join(b, "f.txt"), "b-0");
                assert.deepEqual(await store.trackEdit("src", join(a, "f.txt"), envA, a), { ok: true, minted: true });
                assert.deepEqual(await store.snapshot("src", "b1", envA, a), { ok: true });
                await writeFile(join(a, "f.txt"), "a-1");
                assert.deepEqual(await store.adoptScope("src", "fork"), { ok: true });
                assert.deepEqual(await store.snapshot("fork", "b2", envB, b), { ok: true });
                assert.deepEqual(await store.trackEdit("fork", join(b, "f.txt"), envB, b), { ok: true, minted: true }, "after a carry, the second file is still a first touch of its own (the carried entry's place is another directory)");
                assert.deepEqual(await store.trackEdit("fork", join(b, "g.txt"), envB, b), { ok: true, minted: true });
                await writeFile(join(b, "f.txt"), "b-1");
                await writeFile(join(b, "g.txt"), "b-g");
                const r = await store.restore("fork", "b2", envB, b);
                assert.equal(r.outcome, "complete", JSON.stringify(r));
                assert.equal(await readFile(join(b, "f.txt"), "utf8"), "b-0", "B's own edit is restored at B");
                assert.equal(await existsAt(join(b, "g.txt")), false, "B's created file is removed");
                assert.equal(await readFile(join(a, "f.txt"), "utf8"), "a-1", "A's file is not written by the fork's rewind");
            });
        });
    });
    run("a version that records no directory (an older engine's row) is refused place_unrecorded, unless the rewind names the directory such versions were recorded under — then the one place comparison judges it", async () => {
        await withTree(async (dir, env) => {
            const src = make();
            if (src.exportHistory === undefined || src.importHistory === undefined)
                return;
            const shed = contentShed();
            await shed.write(join(dir, "f.txt"), "pristine");
            const pristine = createHash("sha256").update("pristine").digest("hex");
            const unplaced = wireEnvelope({
                formatVersion: "file-history/1",
                tracked: [{ relOrAbsPath: "f.txt", keyKind: "root-relative", keyFamily: "posix", baseAvailable: true, versions: [{ version: 1, blobHash: pristine, parentIdent: ".", backupTime: new Date(0).toISOString() }] }],
                boundaries: [{ entryId: "b1", files: [{ relOrAbsPath: "f.txt", version: 1 }] }],
            });
            assert.deepEqual(await src.importHistory("old", unplaced, shed.fetch), { ok: true });
            await writeFile(join(dir, "f.txt"), "edited");
            const refused = await src.restore("old", "b1", env, dir);
            assert.deepEqual(refused.refused.map((f) => [f.path, f.class]), [["f.txt", "place_unrecorded"]], JSON.stringify(refused));
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "edited");
            await withTree(async (elsewhere) => {
                const named = await src.restore("old", "b1", env, dir, undefined, { unplacedHistoryRecordedUnder: elsewhere });
                assert.deepEqual([named.refused, (named.leftAsIs ?? []).map((f) => [f.path, f.class])], [[], [["f.txt", "recorded_outside_root"]]], `a named directory that is not this one is the same comparison (outside this root: left as it is): ${JSON.stringify(named)}`);
                assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "edited");
            });
            const here = await src.restore("old", "b1", env, dir, undefined, { unplacedHistoryRecordedUnder: dir });
            assert.equal(here.outcome, "complete", JSON.stringify(here));
            assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "pristine");
        });
    });
    run("restore preflight (kind arm, G11): a target replaced by a LEAF SYMLINK or a DIRECTORY is refused by name and the link's own target is untouched", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            const outside = await mkdtemp(join(tmpdir(), "fh-kit-kind-"));
            try {
                await writeFile(join(dir, "leaf.txt"), "pristine-leaf");
                await writeFile(join(dir, "dir.txt"), "pristine-dir");
                assert.deepEqual(await store.trackEdit("sc", join(dir, "leaf.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await store.trackEdit("sc", join(dir, "dir.txt"), env, dir), { ok: true, minted: true });
                assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
                await writeFile(join(outside, "victim.txt"), "OUTSIDE-UNTOUCHED");
                await rm(join(dir, "leaf.txt"));
                await symlink(join(outside, "victim.txt"), join(dir, "leaf.txt"), "file");
                await rm(join(dir, "dir.txt"));
                await mkdir(join(dir, "dir.txt"));
                const r = await store.restore("sc", "b1", env, dir);
                assert.equal(r.outcome, "partial", JSON.stringify(r));
                assert.equal(r.refused.length, 2, "both kind mismatches are refused, each by name");
                assert.deepEqual(r.refused.map((f) => f.class), ["link_safety", "link_safety"], `a kind mismatch is a link-safety refusal: ${JSON.stringify(r.refused)}`);
                assert.equal(await readFile(join(outside, "victim.txt"), "utf8"), "OUTSIDE-UNTOUCHED", "a leaf link is never written THROUGH");
                assert.deepEqual(r.filesChanged, []);
            }
            finally {
                await rm(outside, { recursive: true, force: true });
            }
        });
    });
    run("the planned restore (a rewind's preview: this store's `restore` on a view that writes nothing) lists exactly the files a restore WOULD change with their line arithmetic; an already-converged tracked set plans nothing; no boundary at all is the restore's own not_found — never an empty plan", async () => {
        await withTree(async (dir, env) => {
            const store = make();
            const plan = (entryId) => planFileHistoryRestore(store, { scope: "sc", entryId, env, root: dir });
            await writeFile(join(dir, "edited.txt"), "one\ntwo\nthree\n");
            await writeFile(join(dir, "untouched.txt"), "same\n");
            assert.deepEqual(await store.trackEdit("sc", join(dir, "edited.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.trackEdit("sc", join(dir, "untouched.txt"), env, dir), { ok: true, minted: true });
            assert.deepEqual(await store.snapshot("sc", "b1", env, dir), { ok: true });
            const none = await plan("no-such-boundary");
            assert.deepEqual([none.restore.outcome, none.restore.error?.code, none.restore.files], ["failed", "not_found", []]);
            const quiet = (await plan("b1")).diffStats;
            assert.deepEqual({ filesChanged: quiet.filesChanged, insertions: quiet.insertions, deletions: quiet.deletions }, { filesChanged: [], insertions: 0, deletions: 0 });
            await writeFile(join(dir, "edited.txt"), "one\nTWO\nthree\nfour\n");
            const preview = (await plan("b1")).diffStats;
            assert.deepEqual(preview.filesChanged, [key(dir, join(dir, "edited.txt"))], "an unchanged tracked file is not a change");
            assert.deepEqual({ insertions: preview.insertions, deletions: preview.deletions }, { insertions: 1, deletions: 2 });
            const restored = await store.restore("sc", "b1", env, dir);
            assert.deepEqual(restored.filesChanged, preview.filesChanged);
            await chmod(join(dir, "edited.txt"), 0o600);
            if (((await stat(join(dir, "edited.txt"))).mode & 0o7777) !== 0o600)
                return;
            const modePreview = (await plan("b1")).diffStats;
            assert.deepEqual(modePreview.filesChanged, [key(dir, join(dir, "edited.txt"))], "a mode-only restoration is a change the plan must list");
            assert.deepEqual({ insertions: modePreview.insertions, deletions: modePreview.deletions }, { insertions: 0, deletions: 0 }, "…and it moves no lines");
            const modeRestored = await store.restore("sc", "b1", env, dir);
            assert.deepEqual(modeRestored.filesChanged, modePreview.filesChanged, "plan and operation agree on the mode-only arm too");
        });
    });
    await settle();
}
async function readOneBoundary(store, scope, entryId) {
    const batch = await store.readBoundaries(scope, [entryId]);
    assert.ok(batch.ok, `readBoundaries(${scope}, [${entryId}]) could not answer: ${JSON.stringify(batch)}`);
    assert.deepEqual([...batch.boundaries.keys()], [entryId], "a batch of one holds that id and nothing else");
    return batch.boundaries.get(entryId);
}
async function boundaryAgreesWithRestore(store, scope, entryId, env, dir) {
    const read = await readOneBoundary(store, scope, entryId);
    if (!read.ok || read.boundary === null)
        return { violations: [`readBoundaries(${entryId}) answered ${JSON.stringify(read)}`], kinds: [] };
    const entries = read.boundary.entries;
    const targetOf = new Map(entries.map((e) => [e.key, e.target]));
    const plan = (await planFileHistoryRestore(store, { scope, entryId, env, root: dir })).restore;
    const restored = await store.restore(scope, entryId, env, dir);
    const converged = new Set([...restored.filesChanged, ...restored.identicalSkipped]);
    const refusedBase = new Set(plan.refused.filter((r) => r.class === "base_unavailable").map((r) => r.path));
    const leftFrozen = new Set((plan.leftAsIs ?? []).filter((r) => r.class === "frozen_history").map((r) => r.path));
    const failed = new Set(plan.failed.map((r) => r.path));
    const violations = [];
    const at = (k) => (isAbsolute(k) ? k : join(dir, k));
    for (const { key: k, target } of entries) {
        switch (target.kind) {
            case "bytes": {
                const bytes = converged.has(k) ? await readFile(at(k)).catch(() => undefined) : undefined;
                if (bytes === undefined || createHash("sha256").update(bytes).digest("hex") !== target.hash)
                    violations.push(`${k}: bytes ${target.hash.slice(0, 8)} but the restore did not converge it there`);
                break;
            }
            case "absent":
                if (!converged.has(k) || (await existsAt(at(k))))
                    violations.push(`${k}: absent but the restore did not converge it to absent`);
                break;
            case "base_unavailable":
                if (!refusedBase.has(k))
                    violations.push(`${k}: base_unavailable but the restore did not refuse it base_unavailable`);
                break;
            case "frozen":
                if (!leftFrozen.has(k))
                    violations.push(`${k}: frozen but the restore did not leave it frozen_history`);
                break;
            case "record_missing":
                if (!failed.has(k))
                    violations.push(`${k}: record_missing but the restore did not fail it`);
                break;
        }
    }
    for (const k of refusedBase)
        if (targetOf.get(k)?.kind !== "base_unavailable")
            violations.push(`${k}: refused base_unavailable but read ${targetOf.get(k)?.kind ?? "no entry"}`);
    for (const k of leftFrozen)
        if (targetOf.get(k)?.kind !== "frozen")
            violations.push(`${k}: left frozen_history but read ${targetOf.get(k)?.kind ?? "no entry"}`);
    const named = [...plan.filesChanged, ...plan.identicalSkipped, ...plan.refused.map((r) => r.path), ...plan.failed.map((r) => r.path), ...(plan.leftAsIs ?? []).map((r) => r.path)];
    for (const k of named)
        if (!targetOf.has(k))
            violations.push(`${k}: the restore names it, the seat did not read it`);
    return { violations, kinds: entries.map((e) => e.target.kind).sort() };
}
function key(root, absPath) {
    return absPath.slice(root.length + 1).replace(/\\/g, "/");
}
function contentShed() {
    const bytesOf = new Map();
    return {
        async write(path, text) {
            const bytes = Buffer.from(text, "utf8");
            bytesOf.set(createHash("sha256").update(bytes).digest("hex"), bytes);
            await writeFile(path, bytes);
        },
        async fetch(hash) {
            return bytesOf.get(hash);
        },
    };
}