UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

847 lines • 62 kB
import assert from "node:assert";
import { computeEntryRev } from "./frontmatter.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("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("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("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 current rev is reported for the §3 ladder");
        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("design/336: 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("design/336: 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("design/336: 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("design/336: 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("design/336 §4 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("design/336 §4 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("design/336: 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("design/339 c35: 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("design/339 c36: 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("design/339 c37: 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("design/339 c38: 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("design/339 c39: 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("design/339 c40: 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("design/178 v2-a 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("design/178 v2-b 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", "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, 1, "the attestation rides the v:1 envelope");
        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("design/178 v2-c 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, design/142 §6.1(a)), " +
                    "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);
}
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`);
    }
}