UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,421 lines • 106 kB
import assert from "node:assert";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { computeEntryRev } from "./frontmatter.js";
import { MEMORY_CONTROL_OBJECT_KINDS, MEMORY_GOVERNANCE_DOC_NAMES } from "./types.js";
import { ControlPlaneCorruptError, STRICT_CONTROL_PLANE_LEDGERS } from "./layout.js";
import { fileGovernanceStore } from "./consolidation.js";
import { adoptReplicaControlPlane, readControlPlaneAdoptionReceipt, replicaControlPlaneStrays } from "./control-plane-adoption.js";
function entry(id, scope, slug, body, fm = {}) {
    const e = { id, scope, slug, frontmatter: { ...fm }, body, rev: "" };
    e.rev = computeEntryRev(e);
    return e;
}
export async function memoryBackendContract(hooks) {
    const cases = [];
    const defer = (name, fn) => cases.push([name, fn]);
    defer("add → listHeaders/getByIds visible; header carries name/description/type + positive size", async () => {
        const b = await hooks.make();
        const e = entry("id-alpha-001", "s1", "alpha", "the alpha body", { name: "Alpha", description: "first", type: "project" });
        const rep = await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
        assert.deepStrictEqual(rep.conflicts, []);
        assert.deepStrictEqual(rep.applied, [{ op: "add", id: "id-alpha-001", slug: "alpha" }]);
        const headers = await b.listHeaders(["s1"]);
        assert.strictEqual(headers.length, 1);
        assert.strictEqual(headers[0].id, "id-alpha-001");
        assert.strictEqual(headers[0].name, "Alpha");
        assert.strictEqual(headers[0].description, "first");
        assert.strictEqual(headers[0].type, "project");
        assert.ok(headers[0].sizeBytes > 0, "sizeBytes must be positive");
        assert.strictEqual(headers[0].rev, e.rev);
        const got = await b.getByIds(["id-alpha-001"]);
        assert.strictEqual(got.length, 1);
        assert.strictEqual(got[0].body.replace(/\s+$/, ""), "the alpha body");
    });
    defer("listHeaders excludes other scopes; empty scopes → empty", async () => {
        const b = await hooks.make();
        await b.applyPatches([
            { op: "add", id: "id-scope1-01", entry: entry("id-scope1-01", "s1", "one", "b1") },
            { op: "add", id: "id-scope2-01", entry: entry("id-scope2-01", "s2", "two", "b2") },
        ]);
        assert.deepStrictEqual((await b.listHeaders(["s1"])).map((h) => h.id), ["id-scope1-01"]);
        assert.strictEqual((await b.listHeaders([])).length, 0);
        assert.strictEqual((await b.listHeaders(["nope"])).length, 0);
    });
    defer("search answers only the scopes asked — a query naming s1 never returns an s2 entry", async () => {
        const b = await hooks.make();
        await b.applyPatches([
            { op: "add", id: "id-sfence1-01", entry: entry("id-sfence1-01", "s1", "lantern-one", "lantern harbor signal") },
            { op: "add", id: "id-sfence2-01", entry: entry("id-sfence2-01", "s2", "lantern-two", "lantern harbor signal") },
        ]);
        assert.deepStrictEqual((await b.search("lantern harbor", ["s1"])).map((h) => h.id), ["id-sfence1-01"], "only the s1 entry answers a query naming s1");
        assert.deepStrictEqual((await b.search("lantern harbor", ["s2"])).map((h) => h.id), ["id-sfence2-01"], "control: the s2 entry is findable, and answers only a query naming s2");
    });
    defer("getByIds silently skips unknown ids", async () => {
        const b = await hooks.make();
        await b.applyPatches([{ op: "add", id: "id-known-01", entry: entry("id-known-01", "s1", "known", "kb") }]);
        const got = await b.getByIds(["id-known-01", "id-ghost-404"]);
        assert.deepStrictEqual(got.map((e2) => e2.id), ["id-known-01"]);
    });
    defer("update with the CURRENT baseRev wins and advances rev", async () => {
        const b = await hooks.make();
        const v1 = entry("id-update-01", "s1", "note", "v1");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-update-01", "s1", "note", "v2");
        const rep = await b.applyPatches([{ op: "update", id: "id-update-01", entry: v2, baseRev: v1.rev }]);
        assert.deepStrictEqual(rep.conflicts, []);
        assert.deepStrictEqual(rep.applied, [{ op: "update", id: "id-update-01", slug: "note" }]);
        const got = await b.getByIds(["id-update-01"]);
        assert.strictEqual(got[0].body.replace(/\s+$/, ""), "v2");
        assert.strictEqual(got[0].rev, v2.rev);
        assert.notStrictEqual(got[0].rev, v1.rev);
    });
    defer("update with a STALE baseRev is a reported conflict (never thrown, never blind-written)", async () => {
        const b = await hooks.make();
        const v1 = entry("id-cas-0001", "s1", "note", "v1");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-cas-0001", "s1", "note", "v2");
        await b.applyPatches([{ op: "update", id: "id-cas-0001", entry: v2, baseRev: v1.rev }]);
        const v3 = entry("id-cas-0001", "s1", "note", "v3-from-a-stale-reader");
        const rep = await b.applyPatches([{ op: "update", id: "id-cas-0001", entry: v3, baseRev: v1.rev }]);
        assert.strictEqual(rep.applied.length, 0);
        assert.strictEqual(rep.conflicts.length, 1);
        assert.strictEqual(rep.conflicts[0].id, "id-cas-0001");
        assert.strictEqual(rep.conflicts[0].baseRev, v1.rev);
        assert.strictEqual(rep.conflicts[0].currentRev, v2.rev);
        const got = await b.getByIds(["id-cas-0001"]);
        assert.strictEqual(got[0].body.replace(/\s+$/, ""), "v2", "the CAS winner's content must survive");
    });
    defer("update with a STALE baseRev conflicts even when its new bytes equal the committed bytes", async () => {
        const b = await hooks.make();
        const v1 = entry("id-casbyte-01", "s1", "note", "v1");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-casbyte-01", "s1", "note", "v2");
        await b.applyPatches([{ op: "update", id: "id-casbyte-01", entry: v2, baseRev: v1.rev }]);
        const same = entry("id-casbyte-01", "s1", "note", "v2");
        assert.strictEqual(same.rev, v2.rev, "the fixture: the stale writer's rev equals the committed rev");
        const rep = await b.applyPatches([{ op: "update", id: "id-casbyte-01", entry: same, baseRev: v1.rev }]);
        assert.strictEqual(rep.applied.length, 0, "a stale baseRev applies nothing, whatever its bytes are");
        assert.strictEqual(rep.conflicts.length, 1);
        assert.strictEqual(rep.conflicts[0].id, "id-casbyte-01");
        assert.strictEqual(rep.conflicts[0].baseRev, v1.rev);
        assert.strictEqual(rep.conflicts[0].currentRev, v2.rev, "the conflict names the committed rev");
        const got = await b.getByIds(["id-casbyte-01"]);
        assert.strictEqual(got.length, 1);
        assert.strictEqual(got[0].rev, v2.rev, "the committed state does not move");
        assert.strictEqual(got[0].body.replace(/\s+$/, ""), "v2");
    });
    defer("delete removes the entry; unknown-id update/delete are conflicts", async () => {
        const b = await hooks.make();
        const e = entry("id-del-0001", "s1", "gone", "bye");
        await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
        const rep = await b.applyPatches([{ op: "delete", id: "id-del-0001", baseRev: e.rev }]);
        assert.deepStrictEqual(rep.applied, [{ op: "delete", id: "id-del-0001", slug: "gone" }]);
        assert.strictEqual((await b.getByIds(["id-del-0001"])).length, 0);
        const rep2 = await b.applyPatches([
            { op: "update", id: "id-del-0001", entry: entry("id-del-0001", "s1", "gone", "zombie") },
            { op: "delete", id: "id-never-404" },
        ]);
        assert.strictEqual(rep2.applied.length, 0);
        assert.strictEqual(rep2.conflicts.length, 2);
    });
    defer("a delete leaves the entry in no read face — listHeaders, getByIds and search are all empty of it", async () => {
        const b = await hooks.make();
        const gone = entry("id-faces-gone1", "s1", "faces-gone", "quartz zebra marker");
        const kept = entry("id-faces-kept1", "s1", "faces-kept", "quartz zebra marker too");
        await b.applyPatches([
            { op: "add", id: gone.id, entry: gone },
            { op: "add", id: kept.id, entry: kept },
        ]);
        const ids = async () => ({
            headers: (await b.listHeaders(["s1"])).map((h) => h.id).sort(),
            got: (await b.getByIds([gone.id, kept.id])).map((x) => x.id).sort(),
            hits: (await b.search("quartz zebra", ["s1"])).map((h) => h.id).sort(),
        });
        const both = [gone.id, kept.id].sort();
        assert.deepStrictEqual(await ids(), { headers: both, got: both, hits: both }, "control: before the delete every face serves both entries");
        const rep = await b.applyPatches([{ op: "delete", id: gone.id, baseRev: gone.rev }]);
        assert.deepStrictEqual(rep.conflicts, []);
        assert.deepStrictEqual(await ids(), { headers: [kept.id], got: [kept.id], hits: [kept.id] }, "after the delete no face serves the deleted entry");
    });
    defer("an evidenced erase leaves the entry in no read face — listHeaders, getByIds and search (optional seat)", async () => {
        const b = await hooks.make();
        const seat = b.eraseWithEvidence;
        if (typeof seat !== "function")
            return;
        const erase = seat;
        const gone = entry("id-efaces-gone1", "s1", "efaces-gone", "quartz zebra marker");
        const kept = entry("id-efaces-kept1", "s1", "efaces-kept", "quartz zebra marker too");
        await b.applyPatches([
            { op: "add", id: gone.id, entry: gone },
            { op: "add", id: kept.id, entry: kept },
        ]);
        assert.deepStrictEqual((await b.search("quartz zebra", ["s1"])).map((h) => h.id).sort(), [gone.id, kept.id].sort(), "control: the search face serves both entries before the erase");
        const att = await erase.call(b, { requestId: "req-faces-1", select: { ids: [gone.id] } });
        assert.deepStrictEqual(att.erased.map((r) => r.id), [gone.id]);
        assert.deepStrictEqual((await b.listHeaders(["s1"])).map((h) => h.id), [kept.id], "listHeaders no longer lists the erased entry");
        assert.deepStrictEqual((await b.getByIds([gone.id, kept.id])).map((x) => x.id), [kept.id], "getByIds no longer returns the erased entry");
        assert.deepStrictEqual((await b.search("quartz zebra", ["s1"])).map((h) => h.id), [kept.id], "search no longer returns the erased entry");
    });
    defer("at most ONE non-delete op per id per batch — the later one conflicts", async () => {
        const b = await hooks.make();
        const a1 = entry("id-dup-0001", "s1", "one", "first");
        const a2 = entry("id-dup-0001", "s1", "two", "second");
        const rep = await b.applyPatches([
            { op: "add", id: "id-dup-0001", entry: a1 },
            { op: "add", id: "id-dup-0001", entry: a2 },
        ]);
        assert.strictEqual(rep.applied.length, 1);
        assert.strictEqual(rep.conflicts.length, 1);
        assert.match(rep.conflicts[0].reason, /duplicate id in batch/);
    });
    defer("add slug collision with a DIFFERENT id gets a deterministic -n suffix", async () => {
        const b = await hooks.make();
        await b.applyPatches([{ op: "add", id: "id-slugA-01", entry: entry("id-slugA-01", "s1", "taken", "a") }]);
        const rep = await b.applyPatches([{ op: "add", id: "id-slugB-01", entry: entry("id-slugB-01", "s1", "taken", "b") }]);
        assert.deepStrictEqual(rep.applied, [{ op: "add", id: "id-slugB-01", slug: "taken-2" }]);
    });
    defer("search: lexical floor — distance ∈ [0,2] ascending, zero-overlap excluded, limit honored", async () => {
        const b = await hooks.make();
        await b.applyPatches([
            { op: "add", id: "id-hit-0001", entry: entry("id-hit-0001", "s1", "hit", "alpha beta gamma", { name: "alpha beta" }) },
            { op: "add", id: "id-hit-0002", entry: entry("id-hit-0002", "s1", "half", "alpha zzz qqq") },
            { op: "add", id: "id-miss-001", entry: entry("id-miss-001", "s1", "miss", "totally unrelated words") },
        ]);
        const hits = await b.search("alpha beta", ["s1"]);
        assert.ok(hits.length >= 2, "both overlapping entries hit");
        assert.strictEqual(hits[0].id, "id-hit-0001", "closest first");
        assert.ok(!hits.some((h) => h.id === "id-miss-001"), "zero-overlap excluded");
        for (const h of hits)
            assert.ok(h.score >= 0 && h.score <= 2, `score in [0,2], got ${h.score}`);
        for (let i = 1; i < hits.length; i++)
            assert.ok(hits[i - 1].score <= hits[i].score, "ascending");
        assert.strictEqual((await b.search("alpha beta", ["s1"], { limit: 1 })).length, 1);
        assert.strictEqual((await b.search("", ["s1"])).length, 0, "empty query → empty");
    });
    defer("update MAY move an entry across scopes (old scope loses it, new scope gains it)", async () => {
        const b = await hooks.make();
        const v1 = entry("id-move-001", "s1", "mover", "in s1");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-move-001", "s2", "mover", "now in s2");
        const rep = await b.applyPatches([{ op: "update", id: "id-move-001", entry: v2, baseRev: v1.rev }]);
        assert.strictEqual(rep.conflicts.length, 0);
        assert.strictEqual((await b.listHeaders(["s1"])).length, 0, "old scope must lose the entry");
        assert.deepStrictEqual((await b.listHeaders(["s2"])).map((h) => h.id), ["id-move-001"]);
    });
    defer("same-scope re-add of an existing id is the idempotent overwrite (zero-copy re-write parity)", async () => {
        const b = await hooks.make();
        const v1 = entry("id-readd-01", "s1", "note", "first");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-readd-01", "s1", "note", "second");
        const rep = await b.applyPatches([{ op: "add", id: v2.id, entry: v2 }]);
        assert.deepStrictEqual(rep.applied, [{ op: "add", id: "id-readd-01", slug: "note" }]);
        assert.strictEqual((await b.listHeaders(["s1"])).length, 1, "still ONE entry — overwrite, not duplicate");
        assert.strictEqual((await b.getByIds(["id-readd-01"]))[0].body.replace(/\s+$/, ""), "second");
    });
    defer("cross-scope re-add of an existing id is REFUSED (an add never relocates; MOVE = update)", async () => {
        const b = await hooks.make();
        const v1 = entry("id-xadd-001", "s1", "home", "original");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-xadd-001", "s2", "away", "smuggled copy");
        const rep = await b.applyPatches([{ op: "add", id: v2.id, entry: v2 }]);
        assert.strictEqual(rep.applied.length, 0, "a cross-scope add applies nothing");
        assert.strictEqual(rep.conflicts.length, 1);
        assert.strictEqual(rep.conflicts[0].id, "id-xadd-001");
        assert.match(rep.conflicts[0].reason, /cross-scope add refused/);
        assert.deepStrictEqual((await b.listHeaders(["s1"])).map((h) => h.id), ["id-xadd-001"], "the entry stays home");
        assert.strictEqual((await b.listHeaders(["s2"])).length, 0, "no second projection in the target scope");
        assert.strictEqual((await b.getByIds(["id-xadd-001"])).length, 1, "one id ⇒ one row, everywhere");
    });
    defer("add guard:'absent' — idempotent onto same rev, REPORTED conflict onto a different rev (never blind-overwrites)", async () => {
        const b = await hooks.make();
        const v1 = entry("id-guard-01", "s1", "note", "first");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const same = entry("id-guard-01", "s1", "note", "first");
        const repSame = await b.applyPatches([{ op: "add", id: same.id, entry: same, guard: "absent" }]);
        assert.deepStrictEqual(repSame.conflicts, [], "guarded re-add at the SAME rev is idempotent, not a conflict");
        assert.deepStrictEqual(repSame.applied, [{ op: "add", id: "id-guard-01", slug: "note" }]);
        const diff = entry("id-guard-01", "s1", "note", "an intruding different body");
        const repDiff = await b.applyPatches([{ op: "add", id: diff.id, entry: diff, guard: "absent" }]);
        assert.strictEqual(repDiff.applied.length, 0, "guarded add onto a different rev applies nothing");
        assert.strictEqual(repDiff.conflicts.length, 1);
        assert.strictEqual(repDiff.conflicts[0].id, "id-guard-01");
        assert.match(repDiff.conflicts[0].reason, /add_guard_absent_conflict/);
        assert.strictEqual(repDiff.conflicts[0].currentRev, v1.rev, "the conflict reports the current rev (the caller uses it to reconcile the versions)");
        assert.strictEqual((await b.getByIds(["id-guard-01"]))[0].body.replace(/\s+$/, ""), "first", "the existing content must NOT be overwritten");
        const fresh = entry("id-guard-02", "s1", "fresh", "brand new");
        const repFresh = await b.applyPatches([{ op: "add", id: fresh.id, entry: fresh, guard: "absent" }]);
        assert.deepStrictEqual(repFresh.conflicts, []);
        assert.deepStrictEqual(repFresh.applied, [{ op: "add", id: "id-guard-02", slug: "fresh" }]);
    });
    defer("getByIds with duplicate ids returns each entry once; search limit:0 and fractional limit<1 → empty", async () => {
        const b = await hooks.make();
        await b.applyPatches([{ op: "add", id: "id-once-001", entry: entry("id-once-001", "s1", "once", "alpha body") }]);
        assert.deepStrictEqual((await b.getByIds(["id-once-001", "id-once-001"])).map((e2) => e2.id), ["id-once-001"]);
        assert.deepStrictEqual(await b.search("alpha", ["s1"], { limit: 0 }), []);
        assert.deepStrictEqual(await b.search("alpha", ["s1"], { limit: 0.5 }), []);
    });
    defer("a patch whose entry.id differs from patch.id is refused as malformed (both ops)", async () => {
        const b = await hooks.make();
        const good = entry("id-good-001", "s1", "good", "gb");
        await b.applyPatches([{ op: "add", id: good.id, entry: good }]);
        const impostor = entry("id-impostor1", "s1", "good", "impostor");
        const rep = await b.applyPatches([
            { op: "add", id: "id-other-001", entry: impostor },
            { op: "update", id: "id-good-001", entry: entry("id-impostor2", "s1", "good", "x"), baseRev: good.rev },
        ]);
        assert.strictEqual(rep.applied.length, 0);
        assert.strictEqual(rep.conflicts.length, 2);
        for (const c of rep.conflicts)
            assert.match(c.reason, /malformed patch refused/);
        assert.strictEqual((await b.getByIds(["id-good-001"]))[0].body.replace(/\s+$/, ""), "gb", "nothing was written");
    });
    defer("I-2: update stripping provenance/trust from a repo_file entry is refused as malformed; carrying them forward applies", async () => {
        const b = await hooks.make();
        const prov = { kind: "repo_file", path: "AGENTS.md", contentHash: "sha256:aaaa1111", ingestedAt: 1700000000000 };
        const base = {
            id: "id-prov-0001",
            scope: "s1",
            slug: "instructions-agents-md",
            frontmatter: { name: "project-instructions", description: "repo-provided, untrusted", provenance: prov, trust: "untrusted" },
            body: "instruction text v1",
            rev: "",
        };
        base.rev = computeEntryRev(base);
        const repAdd = await b.applyPatches([{ op: "add", id: base.id, entry: base }]);
        assert.deepStrictEqual(repAdd.conflicts, []);
        const strippedBoth = { ...base, frontmatter: { name: "project-instructions", description: "repo-provided, untrusted" }, rev: "" };
        strippedBoth.rev = computeEntryRev(strippedBoth);
        const rep1 = await b.applyPatches([{ op: "update", id: base.id, entry: strippedBoth, baseRev: base.rev }]);
        assert.strictEqual(rep1.applied.length, 0, "a provenance-stripping update must not apply");
        assert.strictEqual(rep1.conflicts.length, 1);
        assert.match(rep1.conflicts[0].reason, /malformed patch refused/);
        const strippedTrust = { ...base, frontmatter: { name: "project-instructions", provenance: prov }, rev: "" };
        strippedTrust.rev = computeEntryRev(strippedTrust);
        const rep2 = await b.applyPatches([{ op: "update", id: base.id, entry: strippedTrust, baseRev: base.rev }]);
        assert.strictEqual(rep2.applied.length, 0, "a trust-stripping update must not apply");
        assert.strictEqual(rep2.conflicts.length, 1);
        assert.match(rep2.conflicts[0].reason, /malformed patch refused/);
        const kept = await b.getByIds([base.id]);
        assert.strictEqual(kept.length, 1);
        assert.deepStrictEqual(kept[0].frontmatter.provenance, prov, "provenance must survive the refused patches (and round-trip storage)");
        assert.strictEqual(kept[0].frontmatter.trust, "untrusted");
        const next = {
            ...base,
            frontmatter: { ...base.frontmatter, provenance: { ...prov, contentHash: "sha256:bbbb2222", ingestedAt: 1700000000001 } },
            body: "instruction text v2",
            rev: "",
        };
        next.rev = computeEntryRev(next);
        const rep3 = await b.applyPatches([{ op: "update", id: base.id, entry: next, baseRev: base.rev }]);
        assert.deepStrictEqual(rep3.conflicts, []);
        assert.deepStrictEqual(rep3.applied, [{ op: "update", id: base.id, slug: base.slug }]);
        const after = (await b.getByIds([base.id]))[0];
        assert.strictEqual(after.frontmatter.provenance?.contentHash, "sha256:bbbb2222");
        assert.strictEqual(after.frontmatter.trust, "untrusted");
        assert.strictEqual(after.rev, next.rev, "provenance participates in the rev (computeEntryRev closure)");
    });
    defer("origin marker round-trips; strip/rewrite refused across update, re-add, guard add and same-batch delete+re-add; committed tombstone is the legal exit", async () => {
        const b = await hooks.make();
        const origin = { taint: "external", cause: "observed", at: 1700000000500 };
        const base = {
            id: "id-origin-001",
            scope: "s1",
            slug: "marked-note",
            frontmatter: { name: "marked-note", description: "written by an exposed session", origin },
            body: "marked body v1",
            rev: "",
        };
        base.rev = computeEntryRev(base);
        const repAdd = await b.applyPatches([{ op: "add", id: base.id, entry: base }]);
        assert.deepStrictEqual(repAdd.conflicts, []);
        const stored = (await b.getByIds([base.id]))[0];
        assert.deepStrictEqual(stored.frontmatter.origin, origin, "origin must survive storage (round-trip)");
        assert.strictEqual(stored.rev, base.rev, "origin participates in the rev (computeEntryRev closure)");
        const mkStripped = () => {
            const e = { ...base, frontmatter: { name: "marked-note", description: "written by an exposed session" }, rev: "" };
            e.rev = computeEntryRev(e);
            return e;
        };
        const rep1 = await b.applyPatches([{ op: "update", id: base.id, entry: mkStripped(), baseRev: base.rev }]);
        assert.strictEqual(rep1.applied.length, 0, "an origin-stripping update must not apply");
        assert.match(rep1.conflicts[0]?.reason ?? "", /malformed patch refused/);
        const rewritten = { ...base, frontmatter: { ...base.frontmatter, origin: { taint: "external", cause: "static", at: 1 } }, rev: "" };
        rewritten.rev = computeEntryRev(rewritten);
        const rep2 = await b.applyPatches([{ op: "update", id: base.id, entry: rewritten, baseRev: base.rev }]);
        assert.strictEqual(rep2.applied.length, 0, "an origin-rewriting update must not apply");
        assert.match(rep2.conflicts[0]?.reason ?? "", /malformed patch refused/);
        const rep3 = await b.applyPatches([{ op: "add", id: base.id, entry: mkStripped() }]);
        assert.strictEqual(rep3.applied.length, 0, "an origin-stripping re-add must not apply");
        assert.match(rep3.conflicts[0]?.reason ?? "", /malformed patch refused/);
        const rep4 = await b.applyPatches([{ op: "add", id: base.id, entry: mkStripped(), guard: "absent" }]);
        assert.strictEqual(rep4.applied.length, 0, "an origin-stripping guard add must not apply");
        assert.match(rep4.conflicts[0]?.reason ?? "", /malformed patch refused/);
        const rep5 = await b.applyPatches([
            { op: "delete", id: base.id, baseRev: base.rev },
            { op: "add", id: base.id, entry: mkStripped() },
        ]);
        const readd = rep5.conflicts.find((c) => c.op === "add");
        assert.ok(readd !== undefined, "the same-batch unmarked re-add must be refused");
        assert.match(readd.reason, /malformed patch refused/);
        const survivors = await b.getByIds([base.id]);
        if (survivors.length > 0) {
            assert.deepStrictEqual(survivors[0].frontmatter.origin, origin, "a surviving entry keeps its marker verbatim");
        }
        if (survivors.length > 0) {
            const repDel = await b.applyPatches([{ op: "delete", id: base.id }]);
            assert.deepStrictEqual(repDel.conflicts.filter((c) => c.op === "delete"), [], "the tombstone itself applies");
        }
        const fresh = mkStripped();
        const rep6 = await b.applyPatches([{ op: "add", id: base.id, entry: fresh }]);
        assert.deepStrictEqual(rep6.conflicts, [], "after a committed tombstone, the id starts an unmarked life");
        assert.strictEqual((await b.getByIds([base.id]))[0]?.frontmatter.origin, undefined);
        const b2 = await hooks.make();
        const m0 = { ...base, id: "id-origin-002", rev: "" };
        m0.rev = computeEntryRev(m0);
        await b2.applyPatches([{ op: "add", id: m0.id, entry: m0 }]);
        const m1 = { ...m0, body: "marked body v2", rev: "" };
        m1.rev = computeEntryRev(m1);
        const rep7 = await b2.applyPatches([{ op: "update", id: m0.id, entry: m1, baseRev: m0.rev }]);
        assert.deepStrictEqual(rep7.conflicts, []);
        assert.deepStrictEqual((await b2.getByIds([m0.id]))[0]?.frontmatter.origin, origin, "the conforming update carries the marker forward verbatim");
    });
    defer("an AMBIGUOUS origin representation (disagreeing carriers) is refused on add and update; agreeing multi-carrier shapes stay legal", async () => {
        const b = await hooks.make();
        const typed = { taint: "external", cause: "observed", at: 1700000000500 };
        const mk = (id, extra) => {
            const e = {
                id,
                scope: "s1",
                slug: `amb-${id.slice(-4)}`,
                frontmatter: { name: "amb", description: "d", origin: typed, ...(extra !== undefined ? { extra: [...extra] } : {}) },
                body: "b",
                rev: "",
            };
            e.rev = computeEntryRev(e);
            return e;
        };
        const bad = mk("id-ambig-0001", ["origin:", "  taint: external", "  at: 999"]);
        const rep1 = await b.applyPatches([{ op: "add", id: bad.id, entry: bad }]);
        assert.strictEqual(rep1.applied.length, 0, "an ambiguous-representation add must not apply");
        assert.match(rep1.conflicts[0]?.reason ?? "", /representation conflict|malformed patch refused/);
        assert.deepStrictEqual(await b.getByIds([bad.id]), [], "the refused entry must not be readable");
        const clean = mk("id-ambig-0002", undefined);
        const repAdd = await b.applyPatches([{ op: "add", id: clean.id, entry: clean }]);
        assert.deepStrictEqual(repAdd.conflicts, []);
        const badUpd = mk("id-ambig-0002", ["origin:", "  taint: external", "  at: 999"]);
        const rep2 = await b.applyPatches([{ op: "update", id: badUpd.id, entry: badUpd, baseRev: clean.rev }]);
        assert.strictEqual(rep2.applied.length, 0, "an ambiguous-representation update must not apply");
        assert.match(rep2.conflicts[0]?.reason ?? "", /representation conflict|malformed patch refused/);
        assert.deepStrictEqual((await b.getByIds([clean.id]))[0]?.frontmatter.origin, typed, "the committed clean state survives the refused update");
        const agreeing = mk("id-ambig-0003", ["origin:", "  taint: external", "  cause: observed", "  at: 1700000000500"]);
        const rep3 = await b.applyPatches([{ op: "add", id: agreeing.id, entry: agreeing }]);
        assert.deepStrictEqual(rep3.conflicts, [], "agreeing multi-carrier representations are the legal legacy carriage");
        assert.strictEqual(rep3.applied.length, 1);
    });
    defer("projection authority: getByIds carries the OWNING scope; other scopes never list the entry", async () => {
        const b = await hooks.make();
        const e = entry("id-auth-0001", "s1", "authored", "authored body", { name: "Authored" });
        await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
        const got = await b.getByIds([e.id]);
        assert.strictEqual(got.length, 1);
        assert.strictEqual(got[0]?.scope, "s1", "getByIds must carry the owning scope");
        assert.deepStrictEqual((await b.listHeaders(["s2"])).map((h) => h.id), [], "a foreign scope never lists it");
    });
    defer("move immediacy: a cross-scope update moves the WHOLE projection in one transaction (no account lag)", async () => {
        const b = await hooks.make();
        const v1 = entry("id-mvnow-001", "s1", "prompt", "in s1");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const v2 = entry("id-mvnow-001", "s2", "prompt", "in s1");
        const rep = await b.applyPatches([{ op: "update", id: v1.id, entry: v2, baseRev: v1.rev }]);
        assert.strictEqual(rep.conflicts.length, 0);
        assert.strictEqual((await b.listHeaders(["s1"])).length, 0, "the old scope loses it in the same transaction");
        assert.deepStrictEqual((await b.listHeaders(["s2"])).map((h) => h.id), [v1.id]);
        const got = await b.getByIds([v1.id]);
        assert.strictEqual(got.length, 1, "one id ⇒ one entry, mid-move states never observable");
        assert.strictEqual(got[0]?.scope, "s2");
    });
    defer("landing honesty: a suffixed slug collision reports the slug that ACTUALLY landed, and reads agree with it", async () => {
        const b = await hooks.make();
        await b.applyPatches([{ op: "add", id: "id-land-0001", entry: entry("id-land-0001", "s1", "spot", "first") }]);
        const rep = await b.applyPatches([{ op: "add", id: "id-land-0002", entry: entry("id-land-0002", "s1", "spot", "second") }]);
        const applied = rep.applied.find((a) => a.id === "id-land-0002");
        assert.ok(applied !== undefined, "the collided add applies (suffixed)");
        const header = (await b.listHeaders(["s1"])).find((h) => h.id === "id-land-0002");
        assert.ok(header !== undefined);
        assert.strictEqual(applied.slug, header.slug, "applied[].slug must be the landing slug the reads serve — never the requested one");
        assert.notStrictEqual(header.slug, "spot", "the collision really landed on a suffix");
    });
    defer("search: tied scores order deterministically by id (no arrival-order accident)", async () => {
        const b = await hooks.make();
        await b.applyPatches([
            { op: "add", id: "id-tie-b-01", entry: entry("id-tie-b-01", "s1", "tie-b", "same words here") },
            { op: "add", id: "id-tie-a-01", entry: entry("id-tie-a-01", "s1", "tie-a", "same words here") },
        ]);
        const hits = await b.search("same words", ["s1"]);
        assert.deepStrictEqual(hits.map((h) => h.id), ["id-tie-a-01", "id-tie-b-01"]);
    });
    defer("headers carry the exposure fact on BOTH faces (listHeaders + search), typed and extra-form marker alike; unmarked entries carry none", async () => {
        const b = await hooks.make();
        const marked = entry("id-exp-typed-01", "s1", "marked-typed", "same words here");
        marked.frontmatter.origin = { taint: "external", cause: "observed", at: 1700000000600 };
        marked.rev = computeEntryRev(marked);
        const extraForm = entry("id-exp-extra-01", "s1", "marked-extra", "same words here");
        extraForm.frontmatter.extra = ["origin:", "  taint: external", "  at: 5"];
        extraForm.rev = computeEntryRev(extraForm);
        const clean = entry("id-exp-clean-01", "s1", "unmarked", "same words here");
        const rep = await b.applyPatches([
            { op: "add", id: marked.id, entry: marked },
            { op: "add", id: extraForm.id, entry: extraForm },
            { op: "add", id: clean.id, entry: clean },
        ]);
        assert.deepStrictEqual(rep.conflicts, []);
        const headers = await b.listHeaders(["s1"]);
        assert.strictEqual(headers.find((h) => h.id === marked.id)?.exposure, "external", "typed marker ⇒ header exposure");
        assert.strictEqual(headers.find((h) => h.id === extraForm.id)?.exposure, "external", "extra-form marker ⇒ header exposure (one normalization)");
        assert.strictEqual(headers.find((h) => h.id === clean.id)?.exposure, undefined, "unmarked ⇒ no exposure member");
        const hits = await b.search("same words", ["s1"]);
        assert.strictEqual(hits.find((h) => h.id === marked.id)?.exposure, "external", "search hits carry the same fact");
        assert.strictEqual(hits.find((h) => h.id === clean.id)?.exposure, undefined);
    });
    defer("search exposureBands orders unmarked-first BEFORE truncation (the limit-boundary clean entry is served, never starved); absent flag keeps the single-band contract order", async () => {
        const b = await hooks.make();
        const mk = (id, slug, marked) => {
            const e = entry(id, "s1", slug, "same words here");
            if (marked) {
                e.frontmatter.origin = { taint: "external", cause: "observed", at: 1700000000700 };
                e.rev = computeEntryRev(e);
            }
            return e;
        };
        const m1 = mk("id-band-a-01", "band-a", true);
        const m2 = mk("id-band-b-01", "band-b", true);
        const m3 = mk("id-band-c-01", "band-c", true);
        const clean = mk("id-band-z-01", "band-z", false);
        assert.deepStrictEqual((await b.applyPatches([m1, m2, m3, clean].map((e) => ({ op: "add", id: e.id, entry: e })))).conflicts, []);
        const banded = await b.search("same words", ["s1"], { limit: 3, exposureBands: true });
        assert.deepStrictEqual(banded.map((h) => h.id), ["id-band-z-01", "id-band-a-01", "id-band-b-01"], "two-band order must apply before the limit truncation (clean first, contract order within the band)");
        const flat = await b.search("same words", ["s1"], { limit: 3 });
        assert.deepStrictEqual(flat.map((h) => h.id), ["id-band-a-01", "id-band-b-01", "id-band-c-01"]);
    });
    defer("hold protocol (update form): mid-hold writes apply plainly (backend is hold-unaware); the release replay at the capture anchor is a reported conflict carrying currentRev; a clean release applies and the snapshot face answers its committed triple", async () => {
        const b = await hooks.make();
        const e1v0 = entry("id-hold-upd1", "s1", "held-clean", "committed v0");
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: e1v0.id, entry: e1v0 }])).conflicts, []);
        const e1rel = entry("id-hold-upd1", "s1", "held-clean", "the released capture");
        const rep1 = await b.applyPatches([{ op: "update", id: e1v0.id, entry: e1rel, baseRev: e1v0.rev }]);
        assert.deepStrictEqual(rep1.conflicts, [], "a release onto an untouched anchor applies");
        const snapFace = b.committedSnapshotOf;
        if (typeof snapFace === "function") {
            const snap = await snapFace.call(b, e1v0.id);
            assert.strictEqual(snap.state, "row");
            if (snap.state === "row") {
                assert.strictEqual(snap.rev, e1rel.rev, "the snapshot tracks the UPDATE — not the add-time state");
                assert.strictEqual(snap.binding.state, "bound");
                if (snap.binding.state === "bound") {
                    assert.strictEqual(snap.binding.scope, "s1");
                    assert.strictEqual(snap.binding.slug, "held-clean");
                }
            }
        }
        const rep1b = await b.applyPatches([{ op: "update", id: e1v0.id, entry: e1rel, baseRev: e1v0.rev }]);
        assert.strictEqual(rep1b.applied.length, 0);
        assert.strictEqual(rep1b.conflicts.length, 1);
        assert.strictEqual(rep1b.conflicts[0]?.currentRev, e1rel.rev, "currentRev is the retry's idempotency evidence");
        const e2v0 = entry("id-hold-upd2", "s1", "held-raced", "committed v0");
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: e2v0.id, entry: e2v0 }])).conflicts, []);
        const mid = entry("id-hold-upd2", "s1", "held-raced", "mid-hold edit by another writer");
        const repMid = await b.applyPatches([{ op: "update", id: e2v0.id, entry: mid, baseRev: e2v0.rev }]);
        assert.deepStrictEqual(repMid.conflicts, [], "a mid-hold write applies plainly — the backend is hold-unaware");
        assert.strictEqual((await b.getByIds([e2v0.id])).length, 1, "the held id keeps serving reads during the pendency window");
        const e2rel = entry("id-hold-upd2", "s1", "held-raced", "the captured bytes");
        const rep2 = await b.applyPatches([{ op: "update", id: e2v0.id, entry: e2rel, baseRev: e2v0.rev }]);
        assert.strictEqual(rep2.applied.length, 0, "the release never blind-writes over a mid-hold winner");
        assert.strictEqual(rep2.conflicts.length, 1);
        assert.strictEqual(rep2.conflicts[0]?.baseRev, e2v0.rev);
        assert.strictEqual(rep2.conflicts[0]?.currentRev, mid.rev, "the conflict names the winner — the dispose('conflict') evidence");
        assert.strictEqual((await b.getByIds([e2v0.id]))[0]?.body.replace(/\s+$/, ""), "mid-hold edit by another writer", "the winner's content survives");
    });
    defer("hold protocol (add form): a guard-absent release applies onto a free id; the crash retry re-applies idempotently (one row, original slug); a concurrent claim answers the guarded conflict with currentRev and survives", async () => {
        const b = await hooks.make();
        const rel = entry("id-hold-add1", "s1", "held-note", "instruction body");
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: rel.id, entry: rel, guard: "absent" }])).conflicts, []);
        const rep2 = await b.applyPatches([{ op: "add", id: rel.id, entry: rel, guard: "absent" }]);
        assert.deepStrictEqual(rep2.conflicts, [], "the crash retry of a committed release re-applies idempotently");
        assert.deepStrictEqual(rep2.applied, [{ op: "add", id: rel.id, slug: "held-note" }]);
        assert.deepStrictEqual((await b.listHeaders(["s1"])).filter((h) => h.id === rel.id).map((h) => h.slug), ["held-note"], "ONE row at the ORIGINAL slug — never a suffixed duplicate");
        const claimed = entry("id-hold-add2", "s1", "claimed-note", "the claimant's content");
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: claimed.id, entry: claimed }])).conflicts, []);
        const rel2 = entry("id-hold-add2", "s1", "claimed-note", "the captured bytes");
        const rep3 = await b.applyPatches([{ op: "add", id: rel2.id, entry: rel2, guard: "absent" }]);
        assert.strictEqual(rep3.applied.length, 0);
        assert.strictEqual(rep3.conflicts.length, 1);
        assert.match(rep3.conflicts[0]?.reason ?? "", /add_guard_absent_conflict/);
        assert.strictEqual(rep3.conflicts[0]?.currentRev, claimed.rev, "currentRev distinguishes 'claimed by another writer' from the idempotent retry");
        assert.strictEqual((await b.getByIds([claimed.id]))[0]?.body.replace(/\s+$/, ""), "the claimant's content", "the claimant survives");
    });
    defer("the whitewash judgment precedes CAS — an origin/trust strip with a STALE baseRev still answers the malformed refusal, never the rev-mismatch conflict", async () => {
        const b = await hooks.make();
        const origin = { taint: "external", cause: "observed", at: 1700000000900 };
        const m0 = { id: "id-prec-0001", scope: "s1", slug: "prec-marked", frontmatter: { name: "prec", origin }, body: "b0", rev: "" };
        m0.rev = computeEntryRev(m0);
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: m0.id, entry: m0 }])).conflicts, []);
        const m1 = { ...m0, body: "b1", rev: "" };
        m1.rev = computeEntryRev(m1);
        assert.deepStrictEqual((await b.applyPatches([{ op: "update", id: m0.id, entry: m1, baseRev: m0.rev }])).conflicts, []);
        const stripped = { id: m0.id, scope: "s1", slug: "prec-marked", frontmatter: { name: "prec" }, body: "b2", rev: "" };
        stripped.rev = computeEntryRev(stripped);
        const rep = await b.applyPatches([{ op: "update", id: m0.id, entry: stripped, baseRev: m0.rev }]);
        assert.strictEqual(rep.applied.length, 0);
        assert.strictEqual(rep.conflicts.length, 1);
        assert.match(rep.conflicts[0]?.reason ?? "", /malformed patch refused/, "the stronger refusal answers — a CAS conflict here would hide the whitewash");
        const prov = { kind: "repo_file", path: "AGENTS.md", contentHash: "sha256:cccc3333", ingestedAt: 1700000001000 };
        const p0 = { id: "id-prec-0002", scope: "s1", slug: "prec-repo", frontmatter: { name: "prec-repo", provenance: prov, trust: "untrusted" }, body: "p0", rev: "" };
        p0.rev = computeEntryRev(p0);
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: p0.id, entry: p0 }])).conflicts, []);
        const p1 = { ...p0, body: "p1", rev: "" };
        p1.rev = computeEntryRev(p1);
        assert.deepStrictEqual((await b.applyPatches([{ op: "update", id: p0.id, entry: p1, baseRev: p0.rev }])).conflicts, []);
        const strippedTrust = { id: p0.id, scope: "s1", slug: "prec-repo", frontmatter: { name: "prec-repo", provenance: prov }, body: "p2", rev: "" };
        strippedTrust.rev = computeEntryRev(strippedTrust);
        const rep2 = await b.applyPatches([{ op: "update", id: p0.id, entry: strippedTrust, baseRev: p0.rev }]);
        assert.strictEqual(rep2.applied.length, 0);
        assert.strictEqual(rep2.conflicts.length, 1);
        assert.match(rep2.conflicts[0]?.reason ?? "", /malformed patch refused/);
        assert.deepStrictEqual((await b.getByIds([m0.id]))[0]?.frontmatter.origin, origin);
        assert.strictEqual((await b.getByIds([p0.id]))[0]?.frontmatter.trust, "untrusted");
    });
    const distilledEntry = (id, scope, slug, body, inputs) => {
        const e = { id, scope, slug, frontmatter: { name: slug, distilled: { planId: "plan-c35-0001", at: 1_700_000_000_000, carrierRev: "", inputs } }, body, rev: "" };
        e.rev = computeEntryRev(e);
        e.frontmatter.distilled.carrierRev = e.rev;
        return e;
    };
    defer("distilled round-trips deep-equal (typed block, superseded rows); rev is conditional — no-block entries keep their historical rev, carrierRev never participates", async () => {
        const b = await hooks.make();
        const inputs = [
            { id: "id-input-0001", rev: "aaaaaaaaaaaaaaaa", superseded: true },
            { id: "id-input-0002", rev: "bbbbbbbbbbbbbbbb" },
        ];
        const p = distilledEntry("id-prod-00001", "s1", "product", "the distilled abstraction", inputs);
        const rep = await b.applyPatches([{ op: "add", id: p.id, entry: p, guard: "absent" }]);
        assert.deepStrictEqual(rep.conflicts, []);
        const [got] = await b.getByIds([p.id]);
        assert.deepStrictEqual(got?.frontmatter.distilled, p.frontmatter.distilled, "the distilled block must round-trip deep-equal through storage");
        const bare = { id: p.id, scope: p.scope, slug: p.slug, frontmatter: { name: p.frontmatter.name }, body: p.body, rev: "" };
        bare.rev = computeEntryRev(bare);
        assert.notStrictEqual(bare.rev, p.rev, "the distilled block participates in the rev");
        const otherAnchor = { ...p, frontmatter: { ...p.frontmatter, distilled: { ...p.frontmatter.distilled, carrierRev: "different-anchor" } } };
        assert.strictEqual(computeEntryRev(otherAnchor), p.rev, "carrierRev is outside the rev tuple");
        const plainRow = entry("id-plain-0001", "s1", "plain", "plain body", { name: "Plain" });
        await b.applyPatches([{ op: "add", id: plainRow.id, entry: plainRow }]);
        assert.strictEqual((await b.getByIds([plainRow.id]))[0]?.rev, plainRow.rev);
    });
    defer("distilled immutability across update strip/member rewrite, plain re-add, guard add and same-batch delete+re-add ⇒ /malformed patch refused/; committed tombstone is the legal exit", async () => {
        const b = await hooks.make();
        const p = distilledEntry("id-prod-00002", "s1", "prod-immutable", "product body", [{ id: "id-input-0003", rev: "cccccccccccccccc", superseded: true }]);
        await b.applyPatches([{ op: "add", id: p.id, entry: p, guard: "absent" }]);
        const expectMalformed = async (patch) => {
            const rep = await b.applyPatches([patch]);
            assert.strictEqual(rep.applied.filter((a) => a.id === p.id && a.op !== "delete").length, 0, "the touching op must not apply");
            const bad = rep.conflicts.find((c) => c.id === p.id);
            assert.match(bad?.reason ?? "", /malformed patch refused/);
            const [committed] = await b.getByIds([p.id]);
            assert.deepStrictEqual(committed?.frontmatter.distilled, p.frontmatter.distilled, "the committed block survives the refused op");
        };
        const stripped = { ...p, frontmatter: { name: p.frontmatter.name }, body: "edited" };
        stripped.rev = computeEntryRev(stripped);
        await expectMalformed({ op: "update", id: p.id, entry: stripped, baseRev: p.rev });
        const flipped = { ...p, frontmatter: { ...p.frontmatter, distilled: { ...p.frontmatter.distilled, inputs: [{ id: "id-input-0003", rev: "cccccccccccccccc" }] } } };
        flipped.rev = computeEntryRev(flipped);
        await expectMalformed({ op: "update", id: p.id, entry: flipped, baseRev: p.rev });
        const reanchored = { ...p, frontmatter: { ...p.frontmatter, distilled: { ...p.frontmatter.distilled, carrierRev: "forged-anchor-0001" } } };
        reanchored.rev = computeEntryRev(reanchored);
        assert.strictEqual(reanchored.rev, p.rev, "precondition: the carrierRev rewrite moves no rev");
        await expectMalformed({ op: "update", id: p.id, entry: reanchored, baseRev: p.rev });
        const bareAdd = { id: p.id, scope: p.scope, slug: p.slug, frontmatter: { name: p.frontmatter.name }, body: p.body, rev: "" };
        bareAdd.rev = computeEntryRev(bareAdd);
        await expectMalformed({ op: "add", id: p.id, entry: bareAdd });
        await expectMalformed({ op: "add", id: p.id, entry: bareAdd, guard: "absent" });
        const rep = await b.applyPatches([
            { op: "delete", id: p.id, baseRev: p.rev },
            { op: "add", id: p.id, entry: bareAdd },
        ]);
        assert.match(rep.conflicts.find((c) => c.op === "add")?.reason ?? "", /malformed patch refused/);
        const rep2 = await b.applyPatches([{ op: "add", id: p.id, entry: bareAdd }]);
        assert.deepStrictEqual(rep2.conflicts, []);
        assert.strictEqual((await b.getByIds([p.id]))[0]?.frontmatter.distilled, undefined);
    });
    defer("distilled PRECEDENCE — a distilled strip riding a STALE baseRev still answers the malformed refusal, never the rev-mismatch conflict", async () => {
        const b = await hooks.make();
        const p = distilledEntry("id-prod-00003", "s1", "prod-precedence", "v1", [{ id: "id-input-0004", rev: "dddddddddddddddd", superseded: true }]);
        await b.applyPatches([{ op: "add", id: p.id, entry: p, guard: "absent" }]);
        const v2 = { ...p, body: "v2", frontmatter: { ...p.frontmatter, distilled: { ...p.frontmatter.distilled } } };
        v2.rev = computeEntryRev(v2);
        const repOk = await b.applyPatches([{ op: "update", id: p.id, entry: v2, baseRev: p.rev }]);
        assert.deepStrictEqual(repOk.conflicts, []);
        const stripped = { id: p.id, scope: p.scope, slug: p.slug, frontmatter: { name: p.frontmatter.name }, body: "v3", rev: "" };
        stripped.rev = computeEntryRev(stripped);
        const rep = await b.applyPatches([{ op: "update", id: p.id, entry: stripped, baseRev: p.rev }]);
        assert.strictEqual(rep.applied.length, 0);
        assert.match(rep.conflicts[0]?.reason ?? "", /malformed patch refused/);
        assert.doesNotMatch(rep.conflicts[0]?.reason ?? "", /rev mismatch/);
    });
    defer("the distilled fact rides BOTH header faces (listHeaders + search) as carrierRev + the superseded-row projection; block-free entries carry none on either face", async () => {
        const b = await hooks.make();
        const p = distilledEntry("id-prod-00004", "s1", "prod-header", "searchable distilled kumquat", [
            { id: "id-input-0005", rev: "eeeeeeeeeeeeeeee", superseded: true },
            { id: "id-input-0006", rev: "ffffffffffffffff" },
        ]);
        const plain = entry("id-plain-0001", "s1", "plain", "searchable plain kumquat");
        await b.applyPatches([
            { op: "add", id: p.id, entry: p, guard: "absent" },
            { op: "add", id: plain.id, entry: plain },
        ]);
        const headers = await b.listHeaders(["s1"]);
        const ph = headers.find((h) => h.id === p.id);
        assert.deepStrictEqual(ph?.distilled, { carrierRev: p.rev, supersedes: [{ id: "id-input-0005", rev: "eeeeeeeeeeeeeeee" }] });
        assert.strictEqual(headers.find((h) => h.id === plain.id)?.distilled, undefined);
        const hits = await b.search("kumquat", ["s1"], { limit: 10 });
        const psh = hits.find((h) => h.id === p.id);
        assert.deepStrictEqual(psh?.distilled, { carrierRev: p.rev, supersedes: [{ id: "id-input-0005", rev: "eeeeeeeeeeeeeeee" }] }, "search reports the same committed fact");
        assert.strictEqual(hits.find((h) => h.id === plain.id)?.distilled, undefined);
    });
    defer("the plan-replay add spelling — a guard-absent re-add of the identical product is idempotent (one row, no overwrite, no conflict); a different-rev occupant answers add_guard_absent_conflict with currentRev", async () => {
        const b = await hooks.make();
        const p = distilledEntry("id-prod-00005", "s1", "prod-replay", "replayed product", [{ id: "id-input-0007", rev: "abababababababab", superseded: true }]);
        await b.applyPatches([{ op: "add", id: p.id, entry: p, guard: "absent" }]);
        const replay = await b.applyPatches([{ op: "add", id: p.id, entry: p, guard: "absent" }]);
        assert.deepStrictEqual(replay.conflicts, [], "the identical replay is a no-op apply, never a conflict");
        const rows = await b.getByIds([p.id]);
        assert.strictEqual(rows.length, 1, "one row — a replay must not mint a duplicate");
        assert.strictEqual(rows[0]?.rev, p.rev);
        assert.strictEqual((await b.listHeaders(["s1"])).filter((h) => h.id === p.id).length, 1, "one projection");
        const foreign = { ...p, body: "foreign occupant", frontmatter: { ...p.frontmatter, distilled: { ...p.frontmatter.distilled } } };
        foreign.rev = computeEntryRev(foreign);
        await b.applyPatches([{ op: "update", id: p.id, entry: foreign, baseRev: p.rev }]);
        const conflicted = await b.applyPatches([{ op: "add", id: p.id, entry: p, guard: "absent" }]);
        assert.strictEqual(conflicted.applied.length, 0);
        assert.match(conflicted.conflicts[0]?.reason ?? "", /add_guard_absent_conflict/);
        assert.strictEqual(conflicted.conflicts[0]?.currentRev, foreign.rev);
        assert.strictEqual((await b.getByIds([p.id]))[0]?.body.replace(/\s+$/, ""), "foreign occupant", "the occupant survives");
    });
    defer("the directed-arm judgment face — after an update-replay conflict, the reported currentRev and the committed read both answer the planned post-state's rev (already-applied is judgeable), and the judgment read is side-effect-free", async () => {
        const b = await hooks.make();
        const v1 = entry("id-directed-01", "s1", "directed", "v1");
        await b.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
        const terminal = entry("id-directed-01", "s1", "directed", "the intended terminal state");
        const plannedPostRev = terminal.rev;
        const first = await b.applyPatches([{ op: "update", id: v1.id, entry: terminal, baseRev: v1.rev }]);
        assert.deepStrictEqual(first.conflicts, []);
        const replay = await b.applyPatches([{ op: "update", id: v1.id, entry: terminal, baseRev: v1.rev }]);
        assert.strictEqual(replay.applied.length, 0);
        assert.strictEqual(replay.conflicts[0]?.currentRev, plannedPostRev, "the conflict's currentRev answers the already-applied judgment");
        const read1 = await b.getByIds([v1.id]);
        const read2 = await b.getByIds([v1.id]);
        assert.strictEqual(read1[0]?.rev, plannedPostRev);
        assert.strictEqual(read2[0]?.rev, plannedPostRev, "the judgment read advances no rev");
    });
    defer("consolidation cursor round-trips per scope; unset → undefined", async () => {
        const b = await hooks.make();
        assert.strictEqual(await b.getConsolidationCursor("s1"), undefined);
        await b.setConsolidationCursor("s1", "c-1");
        await b.setConsolidationCursor("s2", "c-other");
        assert.strictEqual(await b.getConsolidationCursor("s1"), "c-1");
        await b.setConsolidationCursor("s1", "c-2");
        assert.strictEqual(await b.getConsolidationCursor("s1"), "c-2");
        assert.strictEqual(await b.getConsolidationCursor("s2"), "c-other");
    });
    defer("optional audit faces: committed snapshot / scope enumeration / custody (absent ⇒ reported)", async () => {
        const b = await hooks.make();
        const seats = [
            ["committedSnapshotOf", b.committedSnapshotOf],
            ["committedSnapshotsOfScopes", b.committedSnapshotsOfScopes],
            ["custodyOf", b.custodyOf],
        ];
        for (const [member, seat] of seats) {
            assert.ok(seat === undefined || typeof seat === "function", `${member} must be undefined (absent) or a function — a non-function occupant is a defect, not absence`);
        }
        const snapshotOf = typeof seats[0]?.[1] === "function" ? seats[0][1] : undefined;
        const snapshotsOfScopes = typeof seats[1]?.[1] === "function" ? seats[1][1] : undefined;
        const custodyOf = typeof seats[2]?.[1] === "function" ? seats[2][1] : undefined;
        const e = entry("id-audit-0001", "s1", "audited", "audited body", { name: "Audited" });
        await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
        if (typeof snapshotOf !== "function") {
            hooks.onOptionalMember?.({ member: "committedSnapshotOf", status: "absent" });
        }
        else {
            const ghost = await snapshotOf.call(b, "id-ghost-9999");
            assert.strictEqual(ghost.state, "absent", "an unknown id answers state 'absent' — never a throw, never a guess");
            const snap = await snapshotOf.call(b, e.id);
            assert.strictEqual(snap.state, "row");
            if (snap.state === "row") {
                assert.strictEqual(snap.rev, e.rev, "the snapshot's rev is the committed rev");
                assert.strictEqual(snap.binding.state, "bound", "a committed add answers a bound row");
                if (snap.binding.state === "bound") {
                    assert.strictEqual(snap.binding.scope, "s1");
                    assert.strictEqual(snap.binding.slug, "audited");
                }
                assert.strictEqual(snap.content.state, "present", "a committed, in-place entry's content is servable");
                if (snap.content.state === "present")
                    assert.strictEqual(snap.content.entry.rev, e.rev);
            }
            hooks.onOptionalMember?.({ member: "committedSnapshotOf", status: "verified" });
        }
        if (typeof snapshotsOfScopes !== "function") {
            hooks.onOptionalMember?.({ member: "committedSnapshotsOfScopes", status: "absent" });
        }
        else {
            const enumerated = await snapshotsOfScopes.call(b, ["s1"]);
            if (!enumerated.complete)
                assert.fail("a quiet store enumerates complete");
            assert.deepStrictEqual(enumerated.rows.map((r) => r.id), [e.id], "the account-driven enumeration answers the committed row");
            const foreign = await snapshotsOfScopes.call(b, ["s-elsewhere"]);
            if (!foreign.complete)
                assert.fail("a quiet store enumerates complete (foreign scope)");
            assert.deepStrictEqual(foreign.rows, [], "a foreign scope enumerates empty, not the whole store");
            hooks.onOptionalMember?.({ member: "committedSnapshotsOfScopes", status: "verified" });
        }
        if (typeof custodyOf !== "function") {
            hooks.onOptionalMember?.({ member: "custodyOf", status: "absent" });
        }
        else {
            const custody = await custodyOf.call(b, e.id);
            assert.ok(custody.state === "complete" || custody.state === "damaged", "custody state is the two-valued store answer");
            assert.ok(Array.isArray(custody.events));
            for (const ev of custody.events) {
                assert.strictEqual(typeof ev.ev, "string");
                assert.strictEqual(typeof ev.channel, "string");
                assert.strictEqual(typeof ev.at, "number");
            }
            hooks.onOptionalMember?.({ member: "custodyOf", status: "verified" });
        }
    });
    defer("optional erasure face: evidenced delete / replay pinning / selector-swap refusal (absent ⇒ reported)", async () => {
        const b = await hooks.make();
        const seat = b.eraseWithEvidence;
        assert.ok(seat === undefined || typeof seat === "function", "eraseWithEvidence must be undefined (absent) or a function — a non-function occupant is a defect, not absence");
        if (typeof seat !== "function") {
            hooks.onOptionalMember?.({ member: "eraseWithEvidence", status: "absent" });
            return;
        }
        const erase = seat;
        const e = entry("id-erase-0001", "s1", "erasable-slugword", "erasable body", { name: "Erasable" });
        await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
        const att = await erase.call(b, { requestId: "req-contract-1", select: { ids: [e.id, "id-ghost-8888"] } });
        assert.strictEqual(att.v, 2, "the attestation rides the v:2 envelope");
        for (const cls of ["projection", "shadow", "indexLine", "quarantineCopy", "clearanceCustody", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"]) {
            const answer = att.residuals.carriers[cls];
            assert.ok(answer !== undefined && (answer.unverified === true || (typeof answer.removed === "number" && typeof answer.remaining === "number")), `carrier class ${cls} is answered (removed/remaining counts, or unverified)`);
        }
        assert.strictEqual(att.residuals.replay, "converges", "an evidence face's replay converges (no time limit)");
        assert.ok(!JSON.stringify(att).includes("slugword") && !JSON.stringify(att).includes("erasable body"), "the attestation names no slug and no entry text");
        assert.strictEqual(att.evidenceCapability, "journal", "a face-claiming backend answers the evidenced capability");
        assert.deepStrictEqual(att.erased.map((r) => r.id), [e.id], "the existing id is erased");
        assert.ok(typeof att.erased[0]?.evidenceEv === "string" && att.erased[0].evidenceEv.length > 0, "an evidenced erase names its evidence row");
        assert.deepStrictEqual(att.notFound.map((r) => r.id), ["id-ghost-8888"], "the unknown id answers notFound — never a throw, never a silent drop");
        assert.deepStrictEqual(await b.getByIds([e.id]), [], "an erased id is gone from the read faces");
        const replay = await erase.call(b, { requestId: "req-contract-1", select: { ids: [e.id, "id-ghost-8888"] } });
        assert.deepStrictEqual(replay.resolvedIds, att.resolvedIds, "a replay answers the FIRST resolution's pinned set");
        assert.deepStrictEqual((replay.erasedPreviously ?? []).map((r) => r.id), [e.id], "a replay claims the prior erase as erasedPreviously, never a second erase");
        await assert.rejects(async () => erase.call(b, { requestId: "req-contract-1", select: { ids: ["id-other-7777"] } }), (err) => err.code === "memory.erasure_selector_mismatch", "a reused requestId with a different selector refuses loudly");
        hooks.onOptionalMember?.({ member: "eraseWithEvidence", status: "verified" });
    });
    defer("optional erasure authorization seat: post-resolution judgment, whole-request refusal, replay bound to its set (undeclared ⇒ reported)", async () => {
        const b = await hooks.make();
        const seat = b.eraseWithEvidence;
        const declared = b.judgesErasureScopes;
        assert.ok(declared === undefined || declared === true, "judgesErasureScopes must be absent or the literal true — any other occupant is a defect, not absence");
        assert.ok(declared !== true || typeof seat === "function", "a backend declaring judgesErasureScopes must offer eraseWithEvidence");
        if (declared !== true) {
            hooks.onOptionalMember?.({ member: "judgesErasureScopes", status: "absent" });
            return;
        }
        const erase = seat;
        const mine = entry("id-grant-mine-0001", "tenant-mine", "mine", "mine body", { name: "Mine" });
        const theirs = entry("id-grant-theirs-0001", "tenant-theirs", "theirs", "theirs body", { name: "Theirs" });
        await b.applyPatches([
            { op: "add", id: mine.id, entry: mine },
            { op: "add", id: theirs.id, entry: theirs },
        ]);
        const refusedBySeat = (err) => err.code === "config.memory_erasure_scope";
        await assert.rejects(async () => erase.call(b, { requestId: "req-grant-1", select: { ids: [mine.id, theirs.id] }, expectedScopes: ["tenant-mine"] }), refusedBySeat, "an id resolving outside the set refuses the WHOLE request");
        await assert.rejects(async () => erase.call(b, { requestId: "req-grant-2", select: { ids: [mine.id, "id-grant-ghost-0001"] }, expectedScopes: ["tenant-mine"] }), refusedBySeat, "an id the store cannot attribute to a scope is not a member — refused the same way");
        await assert.rejects(async () => erase.call(b, { requestId: "req-grant-3", select: { scope: "tenant-empty" }, expectedScopes: ["tenant-mine"] }), refusedBySeat, "a place selector naming a scope outside the set refuses — even when that scope resolves to nothing");
        assert.deepStrictEqual((await b.getByIds([mine.id, theirs.id])).map((e) => e.id).sort(), [mine.id, theirs.id].sort(), "refused requests erase nothing");
        const att = await erase.call(b, { requestId: "req-grant-4", select: { ids: [mine.id] }, expectedScopes: ["tenant-mine", "tenant-mine"] });
        assert.deepStrictEqual(att.erased.map((r) => r.id), [mine.id], "inside the set the request erases");
        const replay = await erase.call(b, { requestId: "req-grant-4", select: { ids: [mine.id] }, expectedScopes: ["tenant-mine"] });
        assert.deepStrictEqual((replay.erasedPreviously ?? []).map((r) => r.id), [mine.id], "a replay under the same set (another spelling) converges — judged against the first resolution, not the live account");
        await assert.rejects(async () => erase.call(b, { requestId: "req-grant-4", select: { ids: [mine.id] }, expectedScopes: ["tenant-mine", "tenant-theirs"] }), (err) => err.code === "config.memory_erasure_scope", "a replay under another set refuses");
        await assert.rejects(async () => erase.call(b, { requestId: "req-grant-4", select: { ids: [mine.id] } }), (err) => err.code === "config.memory_erasure_scope", "a replay with no set refuses (absent and present are different authorizations)");
        assert.deepStrictEqual((await b.getByIds([theirs.id])).map((e) => e.id), [theirs.id], "the other scope's entry survives every call");
        hooks.onOptionalMember?.({ member: "judgesErasureScopes", status: "verified" });
    });
    defer("optional patch scope seat: a row owned outside the set does not exist for an update, a move or a delete (undeclared ⇒ reported)", async () => {
        const b = await hooks.make();
        const declared = b.judgesPatchScopes;
        assert.ok(declared === undefined || declared === true, "judgesPatchScopes must be absent or the literal true — any other occupant is a defect, not absence");
        if (declared !== true) {
            hooks.onOptionalMember?.({ member: "judgesPatchScopes", status: "absent" });
            return;
        }
        const theirs = entry("id-seat-theirs-001", "tenant-theirs", "theirs", "theirs body", { name: "Theirs" });
        const own = entry("id-seat-mine-0001", "tenant-mine", "mine", "mine body", { name: "Mine" });
        assert.deepStrictEqual((await b.applyPatches([{ op: "add", id: theirs.id, entry: theirs }, { op: "add", id: own.id, entry: own }])).conflicts, []);
        const set = { expectedScopes: ["tenant-mine"] };
        const notHeld = async (p) => (await hooks.make()).applyPatches([p], set);
        const moved = { ...theirs, scope: "tenant-mine" };
        for (const p of [
            { op: "update", id: theirs.id, entry: { ...theirs, body: "rewritten" }, baseRev: theirs.rev },
            { op: "update", id: theirs.id, entry: moved, baseRev: theirs.rev },
            { op: "update", id: theirs.id, entry: moved },
            { op: "delete", id: theirs.id, baseRev: theirs.rev },
            { op: "delete", id: theirs.id },
        ]) {
            const rep = await b.applyPatches([p], set);
            if (p.op === "update" && p.entry?.scope === "tenant-theirs") {
                assert.deepStrictEqual(rep, { applied: [], conflicts: [{ op: "update", id: theirs.id, reason: "target scope outside the permitted scopes (refused)" }] }, "a target scope outside the set is refused");
            }
            else {
                assert.deepStrictEqual(rep, await notHeld(p), `${p.op} of an id owned outside the set answers what an id the backend does not hold answers`);
            }
        }
        const away = entry("id-seat-away-0001", "tenant-away", "away", "away body");
        assert.deepStrictEqual(await b.applyPatches([{ op: "update", id: away.id, entry: away }], set), { applied: [], conflicts: [{ op: "update", id: away.id, reason: "target scope outside the permitted scopes (refused)" }] }, "an update naming a scope outside the set is refused although the id is free");
        assert.deepStrictEqual(await b.applyPatches([{ op: "add", id: away.id, entry: away }], set), { applied: [], conflicts: [{ op: "add", id: away.id, reason: "target scope outside the permitted scopes (refused)" }] }, "an add naming a scope outside the set is refused");
        assert.deepStrictEqual(await b.applyPatches([{ op: "add", id: theirs.id, entry: { ...theirs, body: "overwritten" } }], set), { applied: [], conflicts: [{ op: "add", id: theirs.id, reason: "target scope outside the permitted scopes (refused)" }] }, "an add into the outside scope (its idempotent overwrite) is refused");
        assert.deepStrictEqual(await b.applyPatches([{ op: "update", id: own.id, entry: { ...own, scope: "tenant-away" }, baseRev: own.rev }], set), { applied: [], conflicts: [{ op: "update", id: own.id, reason: "target scope outside the permitted scopes (refused)" }] }, "an in-set row is not moved out of the set");
        assert.deepStrictEqual((await b.applyPatches([{ op: "delete", id: own.id, baseRev: own.rev }], { expectedScopes: [] })).applied, [], "an empty set permits nothing");
        assert.deepStrictEqual((await b.applyPatches([{ op: "update", id: own.id, entry: own, baseRev: own.rev }, { op: "add", id: "id-seat-new-0001", entry: entry("id-seat-new-0001", "tenant-mine", "new", "new body") }], { expectedScopes: [] })).applied, [], "an empty set permits no update and no add");
        assert.deepStrictEqual(await b.applyPatches([{ op: "add", id: theirs.id, entry: { ...theirs, body: "overwritten" }, guard: "absent" }], set), { applied: [], conflicts: [{ op: "add", id: theirs.id, reason: "target scope outside the permitted scopes (refused)" }] }, "a guarded add into the outside scope is refused by its target");
        for (const p of [
            { op: "update", id: theirs.id, entry: moved, baseRev: "0000000000000000" },
            { op: "delete", id: theirs.id, baseRev: "0000000000000000" },
            { op: "update", id: theirs.id },
        ]) {
            assert.deepStrictEqual(await b.applyPatches([p], set), await notHeld(p), `a stale or entry-less ${p.op} of an id owned outside answers as an absent id`);
        }
        let reads = 0;
        const shifting = [];
        Object.defineProperty(shifting, "0", { get: () => (reads++ === 0 ? "tenant-mine" : "tenant-theirs"), enumerable: true });
        assert.deepStrictEqual((await b.applyPatches([{ op: "delete", id: theirs.id }], { expectedScopes: shifting })).applied, [], "the set is read once: a member that changes between reads is judged as first read");
        const [stands] = await b.getByIds([theirs.id]);
        assert.deepStrictEqual([stands?.scope, stands?.rev, stands?.body.trim()], [theirs.scope, theirs.rev, theirs.body], "the row outside the set stands as it was");
        assert.strictEqual((await b.listHeaders(["tenant-away"])).length, 0, "nothing landed outside the set");
        const next = entry(own.id, "tenant-mine", "mine", "mine body, edited", { name: "Mine" });
        assert.deepStrictEqual(await b.applyPatches([{ op: "update", id: own.id, entry: next, baseRev: own.rev }], set), { applied: [{ op: "update", id: own.id, slug: "mine" }], conflicts: [] }, "inside the set the write applies");
        const badOpts = (bad) => ({ expectedScopes: bad });
        for (const bad of ["tenant-mine", ["tenant-mine", ""], [7], null, [, "tenant-mine"], new Set(["tenant-mine"]), { length: 1, 0: "tenant-mine", *[Symbol.iterator]() { yield "tenant-mine"; } }]) {
            await assert.rejects(async () => b.applyPatches([{ op: "delete", id: theirs.id }], badOpts(bad)), (err) => err.code === "config.invalid_argument", "a set that is not a list of non-empty names refuses the whole call");
        }
        assert.strictEqual((await b.getByIds([theirs.id])).length, 1, "a refused call deletes nothing");
        hooks.onOptionalMember?.({ member: "judgesPatchScopes", status: "verified" });
    });
    defer("optional export/import faces: export composite / governance slice / custody carriage (absent ⇒ reported)", async () => {
        const b = await hooks.make();
        const seats = [
            ["exportSnapshotOf", b.exportSnapshotOf],
            ["governanceExport", b.governanceExport],
            ["custodyImport", b.custodyImport],
            ["importBundleCommit", b.importBundleCommit],
        ];
        for (const [member, seat] of seats) {
            assert.ok(seat === undefined || typeof seat === "function", `${member} must be undefined (absent) or a function — a non-function occupant is a defect, not absence`);
        }
        const e = entry("id-export-0001", "s1", "exported", "exported body", { name: "Exported" });
        await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
        const exportSnapshotOf = typeof seats[0]?.[1] === "function" ? seats[0][1] : undefined;
        if (exportSnapshotOf === undefined) {
            hooks.onOptionalMember?.({ member: "exportSnapshotOf", status: "absent" });
        }
        else {
            const snap = await exportSnapshotOf.call(b, ["s1"]);
            assert.ok(typeof snap.storeId === "string" && snap.storeId.length > 0, "the export snapshot names the store identity");
            assert.strictEqual(typeof snap.fullStore, "boolean");
            assert.deepStrictEqual(snap.entries.map((r) => r.id), [e.id], "the composite answers the committed entries of the requested scopes");
            assert.strictEqual(snap.entries[0]?.rev, e.rev, "entries carry the committed rev");
            assert.ok(Array.isArray(snap.custody) && Array.isArray(snap.unbound) && Array.isArray(snap.pendingLatch));
            hooks.onOptionalMember?.({ member: "exportSnapshotOf", status: "verified" });
        }
        const governanceExport = typeof seats[1]?.[1] === "function" ? seats[1][1] : undefined;
        if (governanceExport === undefined) {
            hooks.onOptionalMember?.({ member: "governanceExport", status: "absent" });
        }
        else {
            const slice = await governanceExport.call(b, ["s1"]);
            assert.strictEqual(slice.complete, true, "a quiet store's governance slice answers complete");
            assert.ok(Array.isArray(slice.custody) && Array.isArray(slice.unbound));
            hooks.onOptionalMember?.({ member: "governanceExport", status: "verified" });
        }
        const custodyImport = typeof seats[2]?.[1] === "function" ? seats[2][1] : undefined;
        if (custodyImport === undefined) {
            hooks.onOptionalMember?.({ member: "custodyImport", status: "absent" });
        }
        else {
            const opts = { bundleHash: "c".repeat(64), sourceStoreId: "contract-src-store" };
            const outcome = await custodyImport.call(b, [{ ev: "kit-del-1", channel: "delete", id: "id-ghost-kit-1", rev: "deadbeefdeadbeef", at: 1 }], opts);
            assert.strictEqual(outcome.appended, 1, "a well-formed delete row for an absent id is carried (anti-resurrection evidence needs no living entry)");
            assert.deepStrictEqual(outcome.withheld, []);
            const unknown = await custodyImport.call(b, [{ ev: "kit-unk-1", channel: "kit-unknown-channel", payload: 1, at: 1 }], opts);
            assert.strictEqual(unknown.appended, 0, "an unknown channel is never appended verbatim");
            assert.deepStrictEqual(unknown.withheld, [{ srcEv: "kit-unk-1", channel: "kit-unknown-channel" }], "an unknown channel is withheld AND reported — never a whole-package refusal");
            hooks.onOptionalMember?.({ member: "custodyImport", status: "verified" });
        }
        hooks.onOptionalMember?.({ member: "importBundleCommit", status: typeof seats[3]?.[1] === "function" ? "verified" : "absent" });
    });
    if (!hooks.makeSibling) {
        const reason = hooks.skipCrossInstanceCas?.trim();
        if (reason) {
            defer(`cross-instance CAS: SKIPPED (declared) — ${reason}`, async () => { });
        }
        else {
            defer("cross-instance CAS: MISSING makeSibling (the baseRev moat axis was not exercised)", async () => {
                throw new Error("memoryBackendContract: no `makeSibling` hook and no `skipCrossInstanceCas` reason — " +
                    "provide `makeSibling` (required for authoritative-backend certification), " +
                    "or declare `skipCrossInstanceCas: \"<why this store has no shared-storage second instance>\"` for a loud skip.");
            });
        }
    }
    if (hooks.makeSibling) {
        defer("cross-instance CAS: a second instance over the SAME storage sees committed revs (one wins, one conflicts)", async () => {
            const a = await hooks.make();
            const bSib = await hooks.makeSibling(a);
            const v1 = entry("id-xinst-01", "s1", "shared", "v1");
            await a.applyPatches([{ op: "add", id: v1.id, entry: v1 }]);
            const v2 = entry("id-xinst-01", "s1", "shared", "v2-by-a");
            const repA = await a.applyPatches([{ op: "update", id: "id-xinst-01", entry: v2, baseRev: v1.rev }]);
            assert.strictEqual(repA.conflicts.length, 0);
            const v2b = entry("id-xinst-01", "s1", "shared", "v2-by-b");
            const repB = await bSib.applyPatches([{ op: "update", id: "id-xinst-01", entry: v2b, baseRev: v1.rev }]);
            assert.strictEqual(repB.applied.length, 0);
            assert.strictEqual(repB.conflicts.length, 1);
            assert.strictEqual(repB.conflicts[0].currentRev, v2.rev);
        });
    }
    const run = hooks.runAssertion ?? (async (_name, fn) => fn());
    for (const [name, fn] of cases)
        await run(name, fn);
}
function governancePlan(planId, over = {}) {
    return { v: 1, planId, scope: "s1", requestId: "req-1", createdAt: 1, epoch: 0, visibleMarked: false, products: [], productStates: {}, directed: [], intents: [], state: "open", audit: [], ...over };
}
function governanceRun(scope, runId, over = {}) {
    return {
        runId,
        scope,
        attempt: 1,
        requestId: `run-${runId}`,
        contractVersion: "v1",
        model: "m",
        startedAt: 1,
        state: "pending",
        cyclesDone: 0,
        entriesSuperseded: 0,
        planIds: [],
        usage: { calls: 0, promptTokens: 0, completionTokens: 0, retries: 0, truncations: 0 },
        repairs: { hallucinatedMembers: 0, duplicateMembers: 0, nonIntegerMembers: 0, emptyGroups: 0, oversizeGroups: 0 },
        writeFailures: [],
        ...over,
    };
}
async function rejectsCoded(p, code, what) {
    let err;
    try {
        await p;
    }
    catch (e) {
        err = e;
    }
    assert.ok(err !== undefined, `${what}: expected a refusal, got an answer`);
    const field = (key) => (typeof err === "object" && err !== null ? Reflect.get(err, key) : undefined);
    const got = field("code") ?? field("name");
    if (typeof code === "string")
        assert.strictEqual(got, code, `${what}: refused with ${String(got)}`);
    else
        assert.match(String(got), code, `${what}: refused with ${String(got)}`);
}
export async function memoryGovernanceStoreContract(hooks) {
    const cases = [];
    const defer = (name, fn) => cases.push([name, fn]);
    defer("a record never written reads absent / empty — never corrupt", async () => {
        const s = await hooks.make();
        assert.deepStrictEqual(await s.readGate(), {});
        assert.deepStrictEqual(await s.readPlan("plan-absent-0001"), { state: "absent" });
        assert.deepStrictEqual(await s.listPlanIds(), []);
        assert.deepStrictEqual(await s.readIntents(), {});
        assert.strictEqual(await s.readRun("s1"), undefined);
        assert.strictEqual(await s.readMint("0190aaaa-run-a1.json"), undefined);
        assert.strictEqual(await s.eraseMint("0190aaaa-run-a1.json"), false);
    });
    for (const record of ["gate", "intents", "run"]) {
        defer(`a malformed ${record} record is refused (fail-closed), never read as empty`, async () => {
            const s = await hooks.make();
            await hooks.corrupt(s, record);
            const read = record === "gate" ? s.readGate() : record === "intents" ? s.readIntents() : s.readRun("s1");
            await rejectsCoded(read, /ControlPlaneCorruptError|corrupt/i, `${record} read over a malformed record`);
            if (record === "gate")
                await rejectsCoded(s.transact([], () => ({ writeGate: true, result: undefined })), /ControlPlaneCorruptError|corrupt/i, "a transaction over a malformed gate");
        });
    }
    defer("a transaction's row and plan writes land after it returns; a throw inside it writes nothing", async () => {
        const s = await hooks.make();
        await assert.rejects(s.transact(["plan-txn-00001"], (tx) => {
            tx.scopes["s1"] = { sessions: { count: 1, ring: ["a"] }, epoch: 0, openPlanId: "plan-txn-00001" };
            tx.writePlan(governancePlan("plan-txn-00001"));
            throw new Error("abort");
        }), /abort/);
        assert.deepStrictEqual(await s.readGate(), {});
        assert.deepStrictEqual(await s.readPlan("plan-txn-00001"), { state: "absent" });
        const answer = await s.transact(["plan-txn-00001"], (tx) => {
            assert.deepStrictEqual(tx.plan("plan-txn-00001"), { state: "absent" });
            tx.scopes["s1"] = { sessions: { count: 1, ring: ["a"] }, epoch: 0, openPlanId: "plan-txn-00001" };
            tx.writePlan(governancePlan("plan-txn-00001"));
            return { writeGate: true, result: "done" };
        });
        assert.strictEqual(answer, "done");
        assert.strictEqual((await s.readGate())["s1"]?.openPlanId, "plan-txn-00001");
        const read = await s.readPlan("plan-txn-00001");
        assert.strictEqual(read.state, "ok");
        assert.deepStrictEqual(await s.listPlanIds(), ["plan-txn-00001"]);
        await s.transact(["plan-txn-00001"], (tx) => {
            tx.scopes["s1"].epoch = 99;
            tx.writePlan(governancePlan("plan-txn-00001", { state: "applying" }));
            return { writeGate: false, result: undefined };
        });
        assert.strictEqual((await s.readGate())["s1"]?.epoch, 0);
        const after = await s.readPlan("plan-txn-00001");
        assert.ok(after.state === "ok" && after.plan.state === "applying");
    });
    defer("takeover cannot land between a transaction's owner read and its plan write (the owner fence)", async () => {
        const s = await hooks.make();
        await s.transact([], (tx) => {
            tx.writePlan(governancePlan("plan-fence-0001", { applier: "first" }));
            return { writeGate: false, result: undefined };
        });
        const holder = (me) => s.transact(["plan-fence-0001"], (tx) => {
            const cur = tx.plan("plan-fence-0001");
            if (cur.state !== "ok" || cur.plan.applier !== "first")
                return { writeGate: false, result: false };
            tx.writePlan({ ...cur.plan, applier: me });
            return { writeGate: false, result: true };
        });
        const won = await Promise.all([holder("A"), holder("B"), holder("C")]);
        assert.strictEqual(won.filter(Boolean).length, 1, `exactly one holder may take the plan over the applier it read (got ${JSON.stringify(won)})`);
        const final = await s.readPlan("plan-fence-0001");
        assert.ok(final.state === "ok" && final.plan.applier === ["A", "B", "C"][won.indexOf(true)]);
    });
    defer("the seat CAS: of racing claims on one scope's row exactly one wins", async () => {
        const s = await hooks.make();
        const claim = (planId) => s.transact([], (tx) => {
            const row = tx.scopes["s1"] ?? { sessions: { count: 0, ring: [] }, epoch: 0 };
            if (row.openPlanId !== undefined)
                return { writeGate: false, result: false };
            row.openPlanId = planId;
            tx.scopes["s1"] = row;
            return { writeGate: true, result: true };
        });
        const won = await Promise.all(["plan-cas-00001", "plan-cas-00002", "plan-cas-00003", "plan-cas-00004"].map(claim));
        assert.strictEqual(won.filter(Boolean).length, 1);
    });
    defer("the run claim: a pending run is resumed with its attempt bumped; the superseded writer is refused and writes nothing", async () => {
        const s = await hooks.make();
        const opened = await s.claimRun("s1", () => governanceRun("s1", "0190aaaa-run1"));
        assert.strictEqual(opened.resumed, false);
        assert.strictEqual(opened.row.attempt, 1);
        const resumed = await s.claimRun("s1", () => governanceRun("s1", "0190aaaa-other"));
        assert.strictEqual(resumed.resumed, true);
        assert.strictEqual(resumed.row.runId, "0190aaaa-run1");
        assert.strictEqual(resumed.row.attempt, 2);
        await rejectsCoded(s.writeRun({ ...opened.row, cyclesDone: 7 }), "memory.consolidation_driver_superseded", "the attempt-1 writer after the attempt-2 claim");
        assert.strictEqual((await s.readRun("s1"))?.cyclesDone, 0);
        await s.writeRun({ ...resumed.row, cyclesDone: 3, state: "settled" });
        assert.strictEqual((await s.readRun("s1"))?.cyclesDone, 3);
        const fresh = await s.claimRun("s1", () => governanceRun("s1", "0190aaaa-run2"));
        assert.strictEqual(fresh.resumed, false, "a settled run is not resumed: the claim opens a new one");
        assert.strictEqual(fresh.row.runId, "0190aaaa-run2");
    });
    defer("intent credentials are idempotent on requestId: the standing row wins", async () => {
        const s = await hooks.make();
        const row = { requestId: "intent-1", state: "settled", planId: "plan-int-00001", at: 1, patches: [] };
        assert.deepStrictEqual(await s.recordIntents([row]), ["intent-1"]);
        assert.deepStrictEqual(await s.recordIntents([{ ...row, state: "abandoned", planId: "plan-int-00002" }]), []);
        assert.strictEqual((await s.readIntents())["intent-1"]?.planId, "plan-int-00001");
    });
    defer("a discarded plan moves to custody: its bytes kept, out of the workbook", async () => {
        const s = await hooks.make();
        await s.transact([], (tx) => {
            tx.writePlan(governancePlan("plan-qtn-00001"));
            return { writeGate: false, result: undefined };
        });
        const custody = await s.quarantinePlan("plan-qtn-00001");
        assert.ok(typeof custody === "string" && custody.length > 0);
        assert.deepStrictEqual(await s.listPlanIds(), []);
        assert.deepStrictEqual(await s.readPlan("plan-qtn-00001"), { state: "absent" });
        assert.strictEqual(await s.quarantinePlan("plan-qtn-00001"), undefined);
    });
    defer("a mint archive is written, read back verbatim and erased (gone, not moved)", async () => {
        const s = await hooks.make();
        const plan = JSON.parse('{"kind":"llm-consolidation-plan","contractVersion":"v1","model":"m","maxInputsPerProduct":4,"products":[],"transcript":[{"role":"user","content":"the shown library"}]}');
        const name = await s.archiveMint("0190aaaa-run1", 2, plan);
        assert.deepStrictEqual(await s.readMint(name), plan);
        assert.strictEqual(await s.eraseMint(name), true);
        assert.strictEqual(await s.readMint(name), undefined);
        assert.strictEqual(await s.eraseMint(name), false);
    });
    const judgeDoc = (raw) => {
        if (raw === undefined)
            return { v: 1, owner: "", n: 0 };
        if (typeof raw !== "object" || raw === null || Reflect.get(raw, "v") !== 1)
            throw new ControlPlaneCorruptError("governance document has the wrong shape");
        return raw;
    };
    defer("every governance document never written reads undefined, and its first update is handed undefined", async () => {
        const s = await hooks.make();
        for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
            assert.strictEqual(await s.readDoc(name), undefined, `${name} before any write`);
            let handed = "not called";
            await s.updateDoc(name, (raw) => {
                handed = raw;
                return judgeDoc(raw);
            }, () => ({ result: undefined }));
            assert.strictEqual(handed, undefined, `${name}: coerce sees the never-written document as undefined`);
            assert.strictEqual(await s.readDoc(name), undefined, `${name}: an update that answers no \`next\` writes nothing`);
        }
    });
    defer("each governance document is its own: a write lands under its name only, and read back is what was written", async () => {
        const s = await hooks.make();
        for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
            const result = await s.updateDoc(name, judgeDoc, (cur) => ({ next: { ...cur, owner: name, n: cur.n + 1 }, result: `wrote ${name}` }));
            assert.strictEqual(result, `wrote ${name}`, `${name}: updateDoc answers fn's result`);
        }
        for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
            assert.deepStrictEqual(await s.readDoc(name), { v: 1, owner: name, n: 1 }, `${name} read back (no alias, no lost write)`);
        }
    });
    defer("a governance document's answers are copies: changing what was read, or the object handed back as next, changes nothing stored", async () => {
        const s = await hooks.make();
        const next = { v: 1, owner: "copy", n: 1 };
        await s.updateDoc("session-accounts", judgeDoc, () => ({ next, result: undefined }));
        next.n = 99;
        const read = (await s.readDoc("session-accounts"));
        assert.deepStrictEqual(read, { v: 1, owner: "copy", n: 1 }, "the stored document is not the caller's object");
        read.n = 42;
        let handed;
        await s.updateDoc("session-accounts", judgeDoc, (cur) => {
            handed = cur;
            return { result: undefined };
        });
        assert.strictEqual(handed?.n, 1, "a read answer is not the stored document");
        assert.deepStrictEqual(await s.readDoc("session-accounts"), { v: 1, owner: "copy", n: 1 });
    });
    defer("a throw in coerce or in fn writes nothing and propagates unchanged", async () => {
        const s = await hooks.make();
        await s.updateDoc("lineage", judgeDoc, (cur) => ({ next: { ...cur, owner: "kept", n: 1 }, result: undefined }));
        await assert.rejects(s.updateDoc("lineage", judgeDoc, () => {
            throw new Error("fn-abort");
        }), /fn-abort/);
        await assert.rejects(s.updateDoc("lineage", () => {
            throw new Error("coerce-abort");
        }, () => ({ next: { v: 1, owner: "never", n: 9 }, result: undefined })), /coerce-abort/);
        assert.deepStrictEqual(await s.readDoc("lineage"), { v: 1, owner: "kept", n: 1 });
    });
    for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
        defer(`a malformed ${name} document is refused (fail-closed) by both faces, never read as missing`, async () => {
            const s = await hooks.make();
            await hooks.corrupt(s, name);
            await rejectsCoded(s.readDoc(name), /ControlPlaneCorruptError|corrupt/i, `${name} read over a malformed document`);
            let called = false;
            await rejectsCoded(s.updateDoc(name, (raw) => {
                called = true;
                return judgeDoc(raw);
            }, (cur) => ({ next: cur, result: undefined })), /ControlPlaneCorruptError|corrupt/i, `${name} update over a malformed document`);
            assert.strictEqual(called, false, `${name}: an unparseable document never reaches coerce as if it were missing`);
        });
    }
    defer("racing updates of one governance document serialize: none is lost, on every document at once", async () => {
        const s = await hooks.make();
        const racers = 8;
        await Promise.all(MEMORY_GOVERNANCE_DOC_NAMES.flatMap((name) => Array.from({ length: racers }, () => s.updateDoc(name, judgeDoc, (cur) => ({ next: { ...cur, owner: name, n: cur.n + 1 }, result: undefined })))));
        for (const name of MEMORY_GOVERNANCE_DOC_NAMES)
            assert.deepStrictEqual(await s.readDoc(name), { v: 1, owner: name, n: racers }, `${name}: ${racers} racing updates all landed`);
    });
    defer("a name outside the governance documents is refused, never given storage of its own", async () => {
        const s = await hooks.make();
        await assert.rejects(s.readDoc("lineage.json"));
        await assert.rejects(s.updateDoc("__proto__", judgeDoc, (cur) => ({ next: cur, result: undefined })));
    });
    defer("the ledgers a host may rebuild are governance documents the store keeps", async () => {
        const s = await hooks.make();
        for (const ledger of STRICT_CONTROL_PLANE_LEDGERS) {
            assert.ok(MEMORY_GOVERNANCE_DOC_NAMES.includes(ledger), `${ledger} is a governance document`);
            assert.strictEqual(await s.readDoc(ledger), undefined, `${ledger} before any write`);
        }
    });
    const enc = (text) => new TextEncoder().encode(text);
    const same = (a, b) => a !== undefined && b !== undefined && Buffer.from(a).equals(Buffer.from(b));
    defer("every control-object kind never written lists empty, reads absent and deletes nothing", async () => {
        const s = await hooks.make();
        for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
            assert.deepStrictEqual(await s.listObjects(kind), [], `${kind} before any write`);
            assert.strictEqual(await s.getObject(kind, "obj-1.json"), undefined, `${kind}/obj-1.json before any write`);
            assert.strictEqual(await s.deleteObject(kind, "obj-1.json"), false, `${kind}: nothing to delete`);
        }
    });
    defer("an object is written once: a second put of the same bytes answers existed, a second put of other bytes is refused, and neither changes anything", async () => {
        const s = await hooks.make();
        for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
            assert.strictEqual(await s.putObject(kind, "once.json", enc(`first ${kind}`), { scope: "s1" }), "created", `${kind}: the first put creates`);
            assert.strictEqual(await s.putObject(kind, "once.json", enc(`first ${kind}`)), "existed", `${kind}: the same bytes find it`);
            await rejectsCoded(s.putObject(kind, "once.json", enc(`second ${kind}`)), /ControlPlaneCorruptError|corrupt/i, `${kind}: other bytes over a standing name`);
            assert.ok(same(await s.getObject(kind, "once.json"), enc(`first ${kind}`)), `${kind}: the first bytes stand`);
        }
    });
    defer("each kind is its own: one name under two kinds is two objects, and a listing answers its kind's names sorted", async () => {
        const s = await hooks.make();
        await s.putObject("pollution", "b.json", enc("pollution b"));
        await s.putObject("pollution", "a.json", enc("pollution a"));
        await s.putObject("quarantine", "a.json", enc("quarantine a"));
        assert.deepStrictEqual(await s.listObjects("pollution"), ["a.json", "b.json"]);
        assert.deepStrictEqual(await s.listObjects("quarantine"), ["a.json"]);
        assert.deepStrictEqual(await s.listObjects("hold"), []);
        assert.ok(same(await s.getObject("pollution", "a.json"), enc("pollution a")));
        assert.ok(same(await s.getObject("quarantine", "a.json"), enc("quarantine a")), "no alias across kinds");
    });
    defer("an object's answers are copies: changing the bytes handed in or read back changes nothing stored", async () => {
        const s = await hooks.make();
        const bytes = enc("custody");
        await s.putObject("hold", "h.md", bytes);
        bytes[0] = 0x58;
        const read = await s.getObject("hold", "h.md");
        assert.ok(same(read, enc("custody")), "the stored object is not the caller's buffer");
        read[0] = 0x59;
        assert.ok(same(await s.getObject("hold", "h.md"), enc("custody")), "a read answer is not the stored object");
    });
    defer("a move lands the bytes at the target and drops the source, a re-run resumes, and nothing is overwritten", async () => {
        const s = await hooks.make();
        await s.putObject("hold", "cap.md", enc("captured"));
        assert.strictEqual(await s.moveObject({ kind: "hold", name: "cap.md" }, { kind: "quarantine", name: "cap-disposed.md" }), "moved");
        assert.strictEqual(await s.getObject("hold", "cap.md"), undefined, "the source is gone");
        assert.ok(same(await s.getObject("quarantine", "cap-disposed.md"), enc("captured")), "the target holds the bytes");
        assert.strictEqual(await s.moveObject({ kind: "hold", name: "cap.md" }, { kind: "quarantine", name: "cap-disposed.md" }), "already-moved", "a re-run of the same move resumes");
        await rejectsCoded(s.moveObject({ kind: "hold", name: "never.md" }, { kind: "quarantine", name: "never.md" }), /ControlPlaneCorruptError|corrupt/i, "a move with neither side standing");
        await s.putObject("hold", "x.md", enc("one"));
        await s.putObject("quarantine", "y.md", enc("two"));
        await assert.rejects(s.moveObject({ kind: "hold", name: "x.md" }, { kind: "quarantine", name: "y.md" }), "a target with other bytes is never overwritten");
        assert.ok(same(await s.getObject("hold", "x.md"), enc("one")), "the refused move leaves its source");
        assert.ok(same(await s.getObject("quarantine", "y.md"), enc("two")), "the refused move leaves its target");
    });
    defer("a delete removes the bytes and answers whether they were there", async () => {
        const s = await hooks.make();
        await s.putObject("import-receipt", "r.json", enc("receipt"));
        assert.strictEqual(await s.deleteObject("import-receipt", "r.json"), true);
        assert.strictEqual(await s.getObject("import-receipt", "r.json"), undefined);
        assert.deepStrictEqual(await s.listObjects("import-receipt"), []);
        assert.strictEqual(await s.deleteObject("import-receipt", "r.json"), false);
        assert.strictEqual(await s.putObject("import-receipt", "r.json", enc("again")), "created", "a deleted name may be written again");
    });
    defer("a kind outside the closed set, or a name that is not one opaque segment, is refused memory.control_object_unknown", async () => {
        const s = await hooks.make();
        await rejectsCoded(s.putObject("ledger", "a.json", enc("x")), "memory.control_object_unknown", "an unknown kind");
        await rejectsCoded(s.listObjects("__proto__"), "memory.control_object_unknown", "a prototype key as a kind");
        for (const name of ["", ".", "..", "a/b", "../x", "a\\b", "a\u0000b", "n".repeat(256), "中".repeat(86)]) {
            await rejectsCoded(s.putObject("pollution", name, enc("x")), "memory.control_object_unknown", `put of the name ${JSON.stringify(name)}`);
            await rejectsCoded(s.getObject("pollution", name), "memory.control_object_unknown", `get of the name ${JSON.stringify(name)}`);
        }
        assert.deepStrictEqual(await s.listObjects("pollution"), [], "a refused name gave nothing storage");
    });
    defer("an object that stands but cannot be read is refused, never read as missing; a kind that cannot be enumerated is refused, never empty", async () => {
        const s = await hooks.make();
        await s.putObject("pollution", "kept.json", enc("marker"));
        await hooks.corrupt(s, { object: "pollution", name: "standing.json" });
        await rejectsCoded(s.getObject("pollution", "standing.json"), /ControlPlaneCorruptError|corrupt/i, "an unreadable object");
        await rejectsCoded(s.putObject("pollution", "standing.json", enc("over it")), /ControlPlaneCorruptError|corrupt/i, "an unreadable object still stands: a put neither overwrites it nor answers for bytes it could not compare");
        await hooks.corrupt(s, { listing: "quarantine" });
        await rejectsCoded(s.listObjects("quarantine"), /ControlPlaneCorruptError|corrupt/i, "an enumeration that fails");
    });
    const withReplica = async (fn) => {
        const replica = mkdtempSync(join(tmpdir(), "sema-adopt-"));
        try {
            await fn(replica, fileGovernanceStore(replica));
        }
        finally {
            rmSync(replica, { recursive: true, force: true });
        }
    };
    defer("adoption: what the store lacks is written, what it holds the same converges, and a pass that refused nothing removes the replica's copies beside a body-less receipt", async () => {
        const s = await hooks.make();
        await withReplica(async (replica, file) => {
            await file.updateDoc("holds", judgeDoc, () => ({ next: { v: 1, owner: "replica", n: 1 }, result: undefined }));
            await file.putObject("hold", "cap.md", enc("captured"));
            await file.putObject("pollution", "s1.json", enc("marker"));
            await s.putObject("pollution", "s1.json", enc("marker"));
            const report = await adoptReplicaControlPlane(replica, s);
            assert.deepStrictEqual(report.refused, []);
            assert.deepStrictEqual(report.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["doc:holds:written", "hold/cap.md:written", "pollution/s1.json:converged"]);
            assert.deepStrictEqual(await s.readDoc("holds"), { v: 1, owner: "replica", n: 1 });
            assert.ok(same(await s.getObject("hold", "cap.md"), enc("captured")));
            assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: [], objects: {} }, "the engine's readers read these records in the store: the replica's copies are removed");
            assert.deepStrictEqual(readControlPlaneAdoptionReceipt(replica).map((r) => r.record).sort(), ["doc:holds", "hold/cap.md", "pollution/s1.json"]);
        });
    });
    defer("adoption: a record the store holds with a different value is refused by name and left where it is; the documents wait while an object is refused", async () => {
        const s = await hooks.make();
        await withReplica(async (replica, file) => {
            await file.updateDoc("lineage", judgeDoc, () => ({ next: { v: 1, owner: "replica", n: 1 }, result: undefined }));
            await s.updateDoc("lineage", judgeDoc, () => ({ next: { v: 1, owner: "carrier", n: 7 }, result: undefined }));
            await file.updateDoc("holds", judgeDoc, () => ({ next: { v: 1, owner: "replica", n: 3 }, result: undefined }));
            await file.putObject("quarantine", "q.md", enc("replica bytes"));
            await s.putObject("quarantine", "q.md", enc("carrier bytes"));
            const report = await adoptReplicaControlPlane(replica, s);
            assert.deepStrictEqual(report.adopted, []);
            assert.deepStrictEqual(report.refused.map((r) => r.record).sort(), ["doc:holds", "doc:lineage", "quarantine/q.md"]);
            assert.strictEqual(await s.readDoc("holds"), undefined, "a document never reaches the store ahead of an object that was refused");
            assert.ok(same(await s.getObject("quarantine", "q.md"), enc("carrier bytes")));
            assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: ["lineage", "holds"], objects: { quarantine: 1 } }, "the refused records stay in the replica");
            await s.deleteObject("quarantine", "q.md");
            const again = await adoptReplicaControlPlane(replica, s);
            assert.deepStrictEqual(again.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["doc:holds:written", "quarantine/q.md:written"]);
            assert.deepStrictEqual(again.refused.map((r) => r.record), ["doc:lineage"]);
            assert.deepStrictEqual(await s.readDoc("lineage"), { v: 1, owner: "carrier", n: 7 }, "no merge is invented");
            assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: ["lineage", "holds"], objects: { quarantine: 1 } }, "a pass with a refusal removes nothing from the replica");
        });
    });
    defer("adoption: a re-run converges — an interrupted handover converges and empties the replica, and a re-run over the emptied replica hands over nothing and writes no second receipt row", async () => {
        const s = await hooks.make();
        await withReplica(async (replica, file) => {
            await file.putObject("capture", "s2.json", enc("opted out"));
            await file.updateDoc("challenges", judgeDoc, () => ({ next: { v: 1, owner: "replica", n: 2 }, result: undefined }));
            await s.putObject("capture", "s2.json", enc("opted out"));
            const first = await adoptReplicaControlPlane(replica, s);
            assert.deepStrictEqual(first.refused, []);
            assert.deepStrictEqual(first.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["capture/s2.json:converged", "doc:challenges:written"]);
            assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: [], objects: {} }, "the finished handover leaves the replica empty");
            const again = await adoptReplicaControlPlane(replica, s);
            assert.deepStrictEqual(again, { adopted: [], refused: [] }, "a finished adoption has nothing left to hand over");
            assert.deepStrictEqual(readControlPlaneAdoptionReceipt(replica).map((r) => r.record).sort(), ["capture/s2.json", "doc:challenges"], "one receipt row per record");
            assert.deepStrictEqual(await s.readDoc("challenges"), { v: 1, owner: "replica", n: 2 });
        });
    });
    const run = hooks.runAssertion ?? (async (_name, fn) => fn());
    for (const [name, fn] of cases)
        await run(name, fn);
}
export async function assertMemoryBackendSearchEquivalence(a, b) {
    const fixture = [
        entry("id-eq-0001", "s1", "notes-alpha", "alpha beta gamma delta", { name: "Alpha notes", description: "about alpha" }),
        entry("id-eq-0002", "s1", "notes-beta", "beta epsilon zeta", { name: "Beta notes" }),
        entry("id-eq-0003", "s1", "unrelated", "completely different content here"),
    ];
    for (const backend of [a, b]) {
        const rep = await backend.applyPatches(fixture.map((e) => ({ op: "add", id: e.id, entry: e })));
        assert.strictEqual(rep.conflicts.length, 0);
    }
    for (const q of ["alpha beta", "epsilon", "different content", "beta"]) {
        const pa = (await a.search(q, ["s1"])).map((h) => ({ id: h.id, slug: h.slug, score: h.score }));
        const pb = (await b.search(q, ["s1"])).map((h) => ({ id: h.id, slug: h.slug, score: h.score }));
        assert.deepStrictEqual(pa, pb, `search("${q}") diverged between backends`);
    }
}