UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,998 lines • 152 kB
import { strict as assert } from "node:assert";
import { readdirSync, statSync } from "node:fs";
import { isAbsolute, join } from "node:path";
import { SessionError, StoredSession, uuidv7 } from "../../internal/harness.js";
import { promptIdentityOf, walkPromptEpochCarriers } from "../../prompt-assembly/epoch.js";
import { textContentHashOf } from "../canonical-json.js";
import { SESSION_LIST_LIMITS, hasSessionFork, isSessionConflict, } from "../session.js";
import { readMember, thrownText } from "../thrown-value.js";
import { describeRejectedValue } from "../tool-search-setting.js";
import { receiptRefusal, receiveOwnProperties } from "../own-property-receipt.js";
import { beginContract } from "./contract-harness.js";
import { readStoreFence, sessionStorageJudges } from "../checkpoint-generation.js";
import { deadGrants, holderBinding, rejectsMalformed, rejectsSuperseded } from "./grant-fixture.js";
const AT = "2026-10-18T00:00:00.000Z";
const AT_MS = Date.parse(AT);
const STAMP = { api: "openai-completions", provider: "contract-kit", model: "contract-kit-model" };
const ZERO_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
function userEntry(id, parentId, text = `t-${id}`) {
    return { id, parentId, type: "message", timestamp: AT, message: { role: "user", content: [{ type: "text", text }], timestamp: AT_MS } };
}
function assistantEntry(id, parentId, ...toolCalls) {
    const content = toolCalls.length > 0 ? toolCalls.map((call) => ({ type: "toolCall", id: call, name: "Read", arguments: { file_path: "/kit/x" } })) : [{ type: "text", text: `a-${id}` }];
    return { id, parentId, type: "message", timestamp: AT, message: { role: "assistant", content, ...STAMP, usage: ZERO_USAGE, stopReason: toolCalls.length > 0 ? "toolUse" : "stop", timestamp: AT_MS } };
}
function toolResultEntry(id, parentId, toolCallId) {
    return { id, parentId, type: "message", timestamp: AT, message: { role: "toolResult", toolCallId, toolName: "Read", content: [{ type: "text", text: "ok" }], isError: false, timestamp: AT_MS } };
}
function compactionEntry(id, parentId, firstKeptEntryId) {
    return { id, parentId, type: "compaction", timestamp: AT, summary: "summary of the turns above the floor", firstKeptEntryId, tokensBefore: 1000 };
}
function epochPin() {
    const layers = { catalog: textContentHashOf("contract-kit catalog"), renderers: { kit: 1 }, binding: textContentHashOf("contract-kit binding") };
    return { epoch: 1, identity: promptIdentityOf(layers), layers, activatedBy: "session_start" };
}
const freshId = () => uuidv7();
function placementFor(scope, handle = `a${uuidv7().slice(-12)}`) {
    return { kind: "subagent", scope: scope ?? `kit-${uuidv7().slice(-12)}`, ...(handle !== null ? { handle } : {}) };
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 20));
async function append(session, entry, opts) {
    await session.getStorage().appendEntry(entry, opts);
}
async function pathIds(session, leafId) {
    const storage = session.getStorage();
    const leaf = leafId === undefined ? await storage.getLeafId() : leafId;
    return (await storage.getPathToRoot(leaf)).map((e) => e.id);
}
async function entryIds(session) {
    return (await session.getStorage().getEntries()).map((e) => e.id);
}
async function thrownBy(fn, what) {
    try {
        await fn();
    }
    catch (err) {
        return err;
    }
    assert.fail(`${what}: expected a refusal, got a result`);
}
function assertFormStated(err, expected, what) {
    assert.equal(readMember(readMember(err, "detail"), "form"), expected, `${what}: a corrupt_session refusal must state its form — "${expected}" for this fault (SessionError's fourth argument)`);
}
async function rejectsWithCode(fn, code, what, form) {
    const err = await thrownBy(fn, what);
    assert.equal(readMember(err, "code"), code, `${what}: the refusal must carry code ${code}`);
    if (form !== undefined)
        assertFormStated(err, form, what);
}
function conflictMiss(err) {
    if (isSessionConflict(err))
        return undefined;
    return readMember(err, "code") === "conflict"
        ? `the refusal carries code "conflict" but is not this package's SessionError — a second copy of @sema-agent/core, or a hand-rolled error; the engine's reconcile retry does not recognize it either`
        : `the refusal must be the engine's session conflict (SessionError "conflict"), got code ${String(readMember(err, "code"))}`;
}
async function rejectsWithConflict(fn, what) {
    const miss = conflictMiss(await thrownBy(fn, what));
    assert.equal(miss, undefined, `${what}: ${miss}`);
}
const LOOP_WALK_BUDGET_MS = 2000;
async function refusedAsLoop(storage, leafId, loopMembers, what) {
    let timer;
    const expiry = new Promise((_, reject) => {
        timer = setTimeout(() => reject(new assert.AssertionError({ message: `${what}: no answer within ${LOOP_WALK_BUDGET_MS} ms — the walk does not end on a parent chain that loops back on itself` })), LOOP_WALK_BUDGET_MS);
    });
    const settled = Promise.resolve()
        .then(() => storage.getPathToRoot(leafId))
        .then((path) => ({ path }), (err) => ({ err }));
    const outcome = await Promise.race([settled, expiry]).finally(() => clearTimeout(timer));
    if ("path" in outcome)
        assert.fail(`${what}: a parent chain that loops back on itself answered a path of ${outcome.path.length} entries instead of refusing`);
    assert.equal(readMember(outcome.err, "code"), "corrupt_session", `${what}: the refusal must carry code corrupt_session`);
    assertFormStated(outcome.err, "parent_loop", what);
    const sentence = String(readMember(outcome.err, "message"));
    assert.ok(loopMembers.some((id) => sentence.includes(id)), `${what}: the refusal must name an entry of the loop (${loopMembers.join(" / ")}), got "${sentence}"`);
}
function rowOf(rows, sessionId) {
    return rows.find((r) => r.sessionId === sessionId);
}
function assertNewestFirst(rows) {
    for (let i = 1; i < rows.length; i++) {
        assert.ok(rows[i - 1].lastActiveAt >= rows[i].lastActiveAt, `list() must be newest-first by lastActiveAt (row ${i - 1} ${rows[i - 1].lastActiveAt} before row ${i} ${rows[i].lastActiveAt})`);
    }
}
function registerUntyped(store, sessionId, owner) {
    return Reflect.apply(store.register, store, [sessionId, owner]);
}
const hasHead = (s) => typeof s.headOf === "function";
const hasOwnership = (s) => hasHead(s) && typeof s.register === "function";
const declaresPlacements = (s) => s.placements?.subagent !== undefined;
const headOf = (store, sessionId) => store.headOf(sessionId);
async function ownerOf(store, sessionId, what) {
    const head = await headOf(store, sessionId);
    assert.ok(head !== undefined, `${what}: the row exists, so headOf must answer it`);
    return head.owner;
}
async function gateHead(store, sessionId, what) {
    const head = await headOf(store, sessionId);
    assert.ok(head !== undefined, `${what}: the row exists, so headOf must answer it`);
    return head;
}
async function tokenOf(store, sessionId, what) {
    const head = await headOf(store, sessionId);
    assert.ok(head !== undefined, `${what}: the row exists, so headOf must answer it`);
    assert.equal(typeof head.incarnation, "string", `${what}: a session row created through this store must carry an incarnation`);
    assert.notEqual(head.incarnation, "", `${what}: an empty token names nobody`);
    return head.incarnation;
}
async function honorsRequireExisting(store) {
    const probe = freshId();
    await store.acquire(probe);
    try {
        await store.acquire(probe, { requireExisting: true });
        return true;
    }
    catch {
        return false;
    }
}
async function readBack(store, sessionId) {
    return (await store.acquire(sessionId, (await honorsRequireExisting(store)) ? { requireExisting: true } : undefined)).session;
}
function assertActivityOrder(rows, newerToOlder, what) {
    for (let i = 1; i < newerToOlder.length; i++) {
        const newer = rowOf(rows, newerToOlder[i - 1]);
        const older = rowOf(rows, newerToOlder[i]);
        assert.ok(newer !== undefined && older !== undefined, `${what}: both sessions are listed`);
        assert.ok(newer.lastActiveAt >= older.lastActiveAt, `${what}: ${newerToOlder[i - 1]} was active after ${newerToOlder[i]} (lastActiveAt ${newer.lastActiveAt} < ${older.lastActiveAt})`);
    }
}
const HOOK_WORDS = { subject: "SessionStoreContractHooks", unit: "hook", moment: "at sessionStoreContract" };
const REQUIRED_HOOKS = ["deleteSession", "reopen"];
const OPTIONAL_HOOKS = ["replica", "tokenlessRow", "openRefusedRow", "unreadableRow", "ageIdle", "idleClockOf", "composed", "runAssertion", "onOptionalMember"];
const GRANT_FIXTURE_FUNCTIONS = ["current", "replaced", "ended", "unknownStatus"];
function receiveHooks(make, hooks) {
    if (typeof make !== "function")
        throw receiptRefusal(`sessionStoreContract: make must be a function that returns a fresh SessionStore, got ${typeof make}`);
    if (typeof hooks !== "object" || hooks === null)
        throw receiptRefusal(`sessionStoreContract: hooks must be a ${HOOK_WORDS.subject} record, got ${hooks === null ? "null" : typeof hooks}`);
    const got = receiveOwnProperties(hooks, HOOK_WORDS);
    for (const name of REQUIRED_HOOKS) {
        const hook = readMember(got, name);
        if (typeof hook !== "function")
            throw receiptRefusal(`${HOOK_WORDS.subject}.${name} is required and must be a function, got ${typeof hook}`);
    }
    for (const name of OPTIONAL_HOOKS) {
        const hook = readMember(got, name);
        if (hook !== undefined && typeof hook !== "function")
            throw receiptRefusal(`${HOOK_WORDS.subject}.${name} must be a function when present, got ${typeof hook}`);
    }
    const none = readMember(got, "noTokenlessRows");
    if (none !== undefined && (typeof none !== "string" || none.trim() === ""))
        throw receiptRefusal(`${HOOK_WORDS.subject}.noTokenlessRows must say why the store holds no row written before occupant tokens (a non-empty string) when present, got ${describeRejectedValue(none)}`);
    if (none !== undefined && readMember(got, "tokenlessRow") !== undefined)
        throw receiptRefusal(`${HOOK_WORDS.subject} gives tokenlessRow and declares noTokenlessRows — a store holds such rows (the hook writes one) or says why it holds none, not both`);
    if ((readMember(got, "ageIdle") === undefined) !== (readMember(got, "idleClockOf") === undefined))
        throw receiptRefusal(`${HOOK_WORDS.subject} gives one of ageIdle and idleClockOf — the idle clock seam is the two together (put a session past the idle window, read its clock), or neither`);
    const grants = readMember(got, "grants");
    if (grants !== undefined) {
        if (typeof grants !== "object" || grants === null)
            throw receiptRefusal(`${HOOK_WORDS.subject}.grants must be a grant fixture record when present, got ${describeRejectedValue(grants)}`);
        for (const name of GRANT_FIXTURE_FUNCTIONS)
            if (typeof readMember(grants, name) !== "function")
                throw receiptRefusal(`${HOOK_WORDS.subject}.grants.${name} must be a function minting a holder`);
        if (typeof readMember(grants, "malformed") !== "string")
            throw receiptRefusal(`${HOOK_WORDS.subject}.grants.malformed must be a string no grant is encoded as`);
        const retire = readMember(grants, "retire");
        if (retire !== undefined && typeof retire !== "function")
            throw receiptRefusal(`${HOOK_WORDS.subject}.grants.retire must be a function when present`);
    }
    if ((grants === undefined) !== (readMember(got, "composed") === undefined))
        throw receiptRefusal(`${HOOK_WORDS.subject} gives ${grants === undefined ? "composed without grants" : "grants without composed"} — the holder cells take both: the composed store and the holders minted against its judge`);
    return got;
}
export function sessionStoreContract(make, hooks) {
    return runSessionStoreContract(make, receiveHooks(make, hooks));
}
async function runSessionStoreContract(make, hooks) {
    const { run: runRaw, settle } = beginContract(hooks.runAssertion);
    const report = (member, status) => hooks.onOptionalMember?.({ member, status });
    const run = (name, fn) => runRaw(name, async () => {
        const store = make();
        const extra = [];
        const open = async (s) => {
            const opened = await s;
            extra.push(opened);
            return opened;
        };
        try {
            await fn(store, open);
        }
        finally {
            for (const s of extra.reverse())
                await s.dispose();
            await store.dispose();
        }
    });
    const FACE_PRESENT = {
        requireExisting: honorsRequireExisting,
        forget: (s) => typeof s.forget === "function",
        fork: hasSessionFork,
        list: (s) => typeof s.list === "function",
        noteTaskRun: (s) => typeof s.noteTaskRun === "function",
        listPlaced: (s) => declaresPlacements(s) && typeof s.listPlaced === "function",
        placements: declaresPlacements,
        headOf: hasHead,
        ownership: hasOwnership,
        replica: () => hooks.replica !== undefined,
        tokenlessRow: () => hooks.tokenlessRow !== undefined,
        openRefusedRow: () => hooks.openRefusedRow !== undefined,
        logTransfer: (s) => hasHead(s) && typeof s.logTransfer === "object" && s.logTransfer !== null,
        delete: (s) => hasHead(s) && typeof s.delete === "function",
        deleteUnreadable: (s) => hasHead(s) && typeof s.deleteUnreadable === "function",
        holder: (s) => s.fence !== undefined || hooks.composed !== undefined,
        recordOwner: (s) => hasOwnership(s) && typeof s.recordOwner === "function",
        readRow: (s) => typeof s.readRow === "function",
        idleClock: () => hooks.ageIdle !== undefined && hooks.idleClockOf !== undefined,
        unreadableRow: () => hooks.unreadableRow !== undefined,
    };
    const FACE_OWED = {
        tokenlessRow: (s) => s.durability === "durable" && hooks.noTokenlessRows === undefined
            ? `the store declares durability "durable" — its rows outlive a process, so rows written before occupant tokens may stand among them: give the tokenlessRow hook (write such a row), or say in noTokenlessRows why this store holds none`
            : undefined,
    };
    const faceRun = (name, needs, fn) => run(name, async (store, open) => {
        const missing = [];
        for (const m of needs)
            if (!(await FACE_PRESENT[m](store)))
                missing.push(m);
        if (missing.length > 0) {
            const owed = missing.length === 1 ? FACE_OWED[missing[0]]?.(store) : undefined;
            assert.ok(owed === undefined, owed);
            for (const m of missing)
                report(m, "absent");
            return;
        }
        await fn(store, open);
        for (const m of needs)
            report(m, "verified");
    });
    const holderRun = (name, fn) => run(name, async (bare, open) => {
        const binding = holderBinding("session", bare.fence !== undefined, hooks.composed, hooks.grants);
        if (binding === undefined) {
            report("holder", "absent");
            return;
        }
        await fn(await open(binding.composed()), binding.grants, open);
        report("holder", "verified");
    });
    const heldSession = async (store) => {
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("h0", null));
        return { id, session };
    };
    holderRun("[holder] S-H0 through the composed store, a dead grant (replaced / ended / unknown status) is refused holder.superseded on an append and on a leaf move, and another fresh handle reads the log and the leaf unchanged", async (store, grants, open) => {
        const { id, session } = await heldSession(store);
        for (const [label, dead] of deadGrants(grants)) {
            await rejectsSuperseded(() => append(session, userEntry(`x-${label}`, "h0"), { holder: dead }), `append (${label})`);
            await rejectsSuperseded(() => session.getStorage().setLeafId(null, { holder: dead }), `setLeafId (${label})`);
        }
        assert.deepEqual(await entryIds(session), ["h0"], "the refused writes appended nothing");
        const other = await open(hooks.reopen(store));
        const again = (await other.acquire(id)).session;
        assert.deepEqual(await entryIds(again), ["h0"], "a fresh handle reads the log unchanged");
        assert.equal(await again.getStorage().getLeafId(), "h0", "a fresh handle reads the leaf unchanged");
    });
    holderRun("[holder] S-H1 a current grant lands: an append and a leaf move carrying it are written; no holder lands as before", async (store, grants) => {
        const { session } = await heldSession(store);
        await append(session, userEntry("h1", "h0"), { holder: grants.current() });
        assert.equal(await session.getStorage().getLeafId(), "h1", "the append carrying the current grant landed");
        await session.getStorage().setLeafId("h0", { holder: grants.current(), expectedLeafId: "h1" });
        assert.equal(await session.getStorage().getLeafId(), "h0", "the leaf move carrying the current grant landed");
        await append(session, userEntry("h2", "h0"), { expectedLeafId: "h0" });
        assert.deepEqual(await pathIds(session), ["h0", "h2"], "the writes carrying the current grant and the one carrying none all landed");
        if (grants.retire !== undefined) {
            const h = grants.current();
            await append(session, userEntry("h3", "h2"), { holder: h });
            await session.getStorage().setLeafId("h2", { holder: h });
            assert.equal(await session.getStorage().getLeafId(), "h2", "the warm leaf move landed");
            grants.retire(h);
            await rejectsSuperseded(() => append(session, userEntry("h4", "h2"), { holder: h }), "an append after the holder was retired");
            await rejectsSuperseded(() => session.getStorage().setLeafId("h3", { holder: h }), "a leaf move after the holder was retired");
            assert.equal(await session.getStorage().getLeafId(), "h2", "the refused leaf move moved nothing");
            assert.equal((await entryIds(session)).includes("h4"), false, "the refused append wrote nothing");
        }
    });
    holderRun("[holder] S-H3 a dead grant beside a stale expected leaf is answered holder.superseded, not conflict — the holder is judged first", async (store, grants) => {
        const { session } = await heldSession(store);
        for (const [label, dead] of deadGrants(grants)) {
            await rejectsSuperseded(() => append(session, userEntry(`x-${label}`, "h0"), { holder: dead, expectedLeafId: "kit-stale-leaf" }), `append (${label})`);
            await rejectsSuperseded(() => session.getStorage().setLeafId(null, { holder: dead, expectedLeafId: "kit-stale-leaf" }), `setLeafId (${label})`);
        }
        assert.deepEqual(await entryIds(session), ["h0"], "nothing was written");
    });
    holderRun("[holder] S-H3b on the composed store, a dead grant through a handle whose row was deleted and created again (another occupant) is still answered holder.superseded — append and leaf move", async (store, grants) => {
        const { id, session } = await heldSession(store);
        await hooks.deleteSession(store, id);
        await store.acquire(id);
        for (const [label, dead] of deadGrants(grants)) {
            await rejectsSuperseded(() => append(session, userEntry(`x-${label}`, "h0"), { holder: dead }), `append (${label})`);
            await rejectsSuperseded(() => session.getStorage().setLeafId(null, { holder: dead }), `setLeafId (${label})`);
        }
    });
    holderRun("[holder] S-H4 no holder: a write is judged exactly as before — it lands, and a stale expected leaf is the engine's conflict", async (store) => {
        const { session } = await heldSession(store);
        await append(session, userEntry("h1", "h0"), { expectedLeafId: "h0" });
        await rejectsWithConflict(() => append(session, userEntry("h2", "h0"), { expectedLeafId: "h0" }), "a stale expected leaf");
        assert.deepEqual(await pathIds(session), ["h0", "h1"]);
    });
    holderRun("[holder] S-H5 two handles on one row: a write refused for its dead grant leaves the other handle's view and its compare-and-set as they were", async (store, grants) => {
        const { id, session } = await heldSession(store);
        const second = (await store.acquire(id)).session;
        for (const [label, dead] of deadGrants(grants)) {
            await rejectsSuperseded(() => append(session, userEntry(`x-${label}`, "h0"), { holder: dead }), `append (${label})`);
        }
        await append(second, userEntry("h1", "h0"), { expectedLeafId: "h0" });
        assert.deepEqual(await pathIds(second), ["h0", "h1"]);
    });
    holderRun("[holder] S-H6 a malformed holder: the judge throws, the write throws, and nothing was written", async (store, grants) => {
        const { session } = await heldSession(store);
        await rejectsMalformed(() => append(session, userEntry("x", "h0"), { holder: grants.malformed }), "append");
        await rejectsMalformed(() => session.getStorage().setLeafId(null, { holder: grants.malformed }), "setLeafId");
        assert.deepEqual(await entryIds(session), ["h0"]);
        assert.equal(await session.getStorage().getLeafId(), "h0");
    });
    holderRun("[holder] S-H7 a run row whose status is outside the judge's live set is not held: an append and a leaf move are refused holder.superseded (fail-closed)", async (store, grants) => {
        const { session } = await heldSession(store);
        await rejectsSuperseded(() => append(session, userEntry("x", "h0"), { holder: grants.unknownStatus() }), "append");
        await rejectsSuperseded(() => session.getStorage().setLeafId(null, { holder: grants.unknownStatus() }), "setLeafId");
        assert.deepEqual(await entryIds(session), ["h0"]);
    });
    run("[durableFence] a store declaring durableFence declares the one shape, and the storage it hands out answers for itself where it lives and whether it judges (durable ⇒ a fence)", async (store) => {
        if (store.durableFence === undefined)
            return;
        readStoreFence("session", "the store's durableFence", store, "durableFence");
        const routes = [() => store.acquire(), () => store.acquire(freshId()), ...(declaresPlacements(store) ? [() => store.acquire(freshId(), { placement: placementFor() })] : [])];
        for (const route of routes)
            sessionStorageJudges(undefined, (await route()).session.getStorage());
    });
    run("[transcriptDirectory] absent, or an absolute path that is a directory once a session was written — the one directory the Runner's transcript gate guards", async (store) => {
        const dir = store.transcriptDirectory;
        if (dir === undefined)
            return;
        assert.equal(typeof dir, "string", "transcriptDirectory is a path string when present");
        assert.ok(isAbsolute(dir), `transcriptDirectory ${JSON.stringify(dir)} is an absolute path`);
        const written = await store.acquire(freshId());
        await append(written.session, userEntry("t1", null));
        assert.ok(statSync(dir).isDirectory(), `transcriptDirectory ${JSON.stringify(dir)} is a directory once a session was written`);
    });
    run("[acquire] acquire() with no id mints a fresh, empty session whose id is the one handed back; two calls are two sessions", async (store) => {
        const first = await store.acquire();
        assert.equal(typeof first.sessionId, "string");
        assert.notEqual(first.sessionId, "", "a minted id names a session");
        assert.equal((await first.session.getMetadata()).id, first.sessionId, "the id acquire hands back is the session's own");
        assert.equal(await first.session.getStorage().getLeafId(), null, "a fresh session has no leaf");
        assert.deepEqual(await entryIds(first.session), [], "a fresh session has no entries");
        const second = await store.acquire();
        assert.notEqual(second.sessionId, first.sessionId, "two id-less acquires are two sessions");
    });
    run("[acquire] acquire(id) creates on a miss and reopens on a hit — the same history, never a wipe", async (store) => {
        const id = freshId();
        const created = await store.acquire(id);
        assert.equal(created.sessionId, id);
        assert.equal((await created.session.getMetadata()).id, id, "the created session carries the id it was asked for");
        await append(created.session, userEntry("e1", null));
        assert.deepEqual(await entryIds((await store.acquire(id)).session), ["e1"], "a re-acquire reopens the history");
        assert.deepEqual(await entryIds(await readBack(store, id)), ["e1"], "a require-existing reopen (where honored) reads the same history");
    });
    run("[acquire] acquire(id, {requireExisting:true}) never creates: on a missing id it rejects not_found — or, on a store that rejects the option, it is refused on every id", async (store) => {
        const id = freshId();
        const honored = await honorsRequireExisting(store);
        if (honored) {
            await rejectsWithCode(() => store.acquire(id, { requireExisting: true }), "not_found", "require-existing on a missing id");
            await rejectsWithCode(() => store.acquire(id, { requireExisting: true }), "not_found", "the refused acquire must not have created the session");
        }
        else {
            await thrownBy(() => store.acquire(id, { requireExisting: true }), "a store that rejects the option, on a missing id");
        }
        if (typeof store.list === "function")
            assert.equal(rowOf(await store.list(), id), undefined, "the refused acquire must not surface on the session list");
        if (hasHead(store))
            assert.equal(await headOf(store, id), undefined, "nor have a row");
        report("requireExisting", honored ? "verified" : "absent");
    });
    run("[acquire] two concurrent acquires of one id are one session: one log, and the second write on the same parent loses the CAS", async (store) => {
        const id = freshId();
        const [a, b] = await Promise.all([store.acquire(id), store.acquire(id)]);
        assert.equal(a.sessionId, id);
        assert.equal(b.sessionId, id);
        await append(a.session, userEntry("e1", null), { expectedLeafId: null });
        await rejectsWithConflict(() => append(b.session, userEntry("e2", null), { expectedLeafId: null }), "a second write on the empty session through the other caller's handle");
        assert.deepEqual(await entryIds((await readBack(store, id))), ["e1"], "two callers must not have created two sessions (the second wiping the first)");
    });
    run("[acquire] a create-capable acquire racing a require-existing acquire of the same missing id still creates (the not_found is the require-existing caller's alone)", async (store) => {
        for (const order of ["require-first", "create-first"]) {
            const id = freshId();
            const calls = order === "require-first" ? [store.acquire(id, { requireExisting: true }), store.acquire(id)] : [store.acquire(id), store.acquire(id, { requireExisting: true })];
            const settled = await Promise.allSettled(calls);
            const createCapable = settled[order === "require-first" ? 1 : 0];
            assert.equal(createCapable.status, "fulfilled", `${order}: the create-capable acquire must create on the miss, never inherit the require-existing caller's not_found`);
            assert.equal(createCapable.value.sessionId, id);
        }
    });
    run("[tree] a fresh session has no leaf and an empty path; appends advance the leaf and the path walks root → leaf", async (store) => {
        const { session } = await store.acquire(freshId());
        const storage = session.getStorage();
        assert.equal(await storage.getLeafId(), null);
        assert.deepEqual(await storage.getPathToRoot(null), [], "the path to no leaf is empty");
        await append(session, userEntry("e1", null));
        await append(session, assistantEntry("e2", "e1"));
        assert.equal(await storage.getLeafId(), "e2", "an append moves the leaf onto the appended entry");
        const path = await storage.getPathToRoot("e2");
        assert.deepEqual(path.map((e) => e.id), ["e1", "e2"]);
        assert.equal(path[0].parentId, null, "an unbounded path starts at a root");
        assert.equal((await storage.getEntry("e1"))?.id, "e1");
        assert.equal(await storage.getEntry("kit-never-written"), undefined, "an id the session never held reads as absent");
    });
    run("[tree] setLeafId moves the active leaf, a later append branches from it, and the log keeps both branches", async (store) => {
        const { session } = await store.acquire(freshId());
        const storage = session.getStorage();
        await append(session, userEntry("e1", null));
        await append(session, assistantEntry("e2", "e1"));
        await storage.setLeafId("e1");
        assert.equal(await storage.getLeafId(), "e1");
        await append(session, userEntry("e3", "e1"));
        assert.equal(await storage.getLeafId(), "e3");
        assert.deepEqual(await pathIds(session, "e3"), ["e1", "e3"], "the new branch");
        assert.deepEqual(await pathIds(session, "e2"), ["e1", "e2"], "the abandoned branch is still in the log");
        const ids = await entryIds(session);
        for (const id of ["e1", "e2", "e3"])
            assert.ok(ids.includes(id), `getEntries keeps ${id}`);
        assert.ok(ids.indexOf("e1") < ids.indexOf("e2") && ids.indexOf("e2") < ids.indexOf("e3"), "getEntries is oldest-first");
    });
    run("[tree] a leaf this session never held is refused — setLeafId and getPathToRoot answer not_found, never an empty path, and the leaf stays", async (store) => {
        const { session } = await store.acquire(freshId());
        const storage = session.getStorage();
        await append(session, userEntry("e1", null));
        await rejectsWithCode(() => storage.setLeafId("kit-never-written"), "not_found", "setLeafId onto an id the session never held");
        assert.equal(await storage.getLeafId(), "e1", "a refused setLeafId leaves the leaf where it was");
        await rejectsWithCode(() => storage.getPathToRoot("kit-never-written"), "not_found", "getPathToRoot from an id the session never held");
    });
    run("[tree] a path stops at a root or at the storage's declared floor; a parent missing above the floor reads corrupt_session, never a truncated path", async (store) => {
        const { session } = await store.acquire(freshId());
        await append(session, userEntry("e1", null));
        let accepted = true;
        try {
            await append(session, userEntry("orphan", "kit-absent-parent"));
        }
        catch {
            accepted = false;
        }
        if (accepted) {
            await rejectsWithCode(() => session.getStorage().getPathToRoot("orphan"), "corrupt_session", "the path through an entry whose parent was never written", "parent_missing");
        }
        const head = (await session.getStorage().getPathToRoot("e1"))[0];
        assert.ok(head.parentId === null || head.id === session.getStorage().getFloorId?.(), "a path's head is a root or the declared floor");
    });
    run("[tree] a parent chain that loops back on itself — an entry that is its own parent, two entries that parent each other, a leaf that walks into such a pair — reads corrupt_session naming an entry of the loop, and the walk ends (also for a ring of three)", async (store) => {
        const { session } = await store.acquire(freshId());
        await append(session, userEntry("e1", null));
        const accepted = async (...entries) => {
            try {
                for (const e of entries)
                    await append(session, e);
                return true;
            }
            catch {
                return false;
            }
        };
        const storage = session.getStorage();
        if (await accepted(userEntry("kit-loop-self", "kit-loop-self"))) {
            await refusedAsLoop(storage, "kit-loop-self", ["kit-loop-self"], "the path from an entry that is its own parent");
        }
        if (await accepted(userEntry("kit-loop-p", "kit-loop-q"), userEntry("kit-loop-q", "kit-loop-p"))) {
            await refusedAsLoop(storage, "kit-loop-q", ["kit-loop-p", "kit-loop-q"], "the path from one of two entries that parent each other");
            if (await accepted(userEntry("kit-loop-t", "kit-loop-p"))) {
                await refusedAsLoop(storage, "kit-loop-t", ["kit-loop-p", "kit-loop-q"], "the path from a leaf outside the loop that walks into it");
            }
        }
        if (await accepted(userEntry("kit-ring-1", "kit-ring-3"), userEntry("kit-ring-2", "kit-ring-1"), userEntry("kit-ring-3", "kit-ring-2"))) {
            await refusedAsLoop(storage, "kit-ring-3", ["kit-ring-1", "kit-ring-2", "kit-ring-3"], "the path from one of three entries that parent each other in a ring");
        }
        assert.deepEqual(await pathIds(session, "e1"), ["e1"], "a path that does not touch the loop still reads");
    });
    run("[tree] the write CAS: an append or setLeafId whose expectedLeafId is stale is refused with the engine's conflict and writes nothing", async (store) => {
        const { session } = await store.acquire(freshId());
        const storage = session.getStorage();
        await append(session, userEntry("e1", null), { expectedLeafId: null });
        await rejectsWithConflict(() => append(session, userEntry("e2", null), { expectedLeafId: null }), "an append expecting an empty session after e1 landed");
        await rejectsWithConflict(() => storage.setLeafId("e1", { expectedLeafId: "kit-stale-leaf" }), "a setLeafId expecting a leaf the session does not have");
        assert.deepEqual(await entryIds(session), ["e1"], "a refused write leaves no entry behind");
        assert.equal(await storage.getLeafId(), "e1");
        await append(session, userEntry("e2", "e1"), { expectedLeafId: "e1" });
        assert.equal(await storage.getLeafId(), "e2", "a current expectedLeafId writes");
    });
    run("[tree] two concurrent appends on one parent: exactly one lands, the other is refused with the engine's conflict", async (store) => {
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("e1", null));
        const settled = await Promise.allSettled([append(session, userEntry("x", "e1"), { expectedLeafId: "e1" }), append(session, userEntry("y", "e1"), { expectedLeafId: "e1" })]);
        const won = settled.flatMap((s, i) => (s.status === "fulfilled" ? [i === 0 ? "x" : "y"] : []));
        assert.equal(won.length, 1, "two writers on one parent: one wins, never both (a silent fork) and never neither");
        const lost = settled.find((s) => s.status === "rejected");
        const miss = conflictMiss(lost.reason);
        assert.equal(miss, undefined, `the loser: ${miss}`);
        assert.deepEqual(await pathIds((await readBack(store, id))), ["e1", won[0]], "the log holds the winner's branch");
    });
    faceRun("[tree] a handle held across forget and a fresh handle from the re-acquire share one CAS", ["forget"], async (store) => {
        const id = freshId();
        const held = (await store.acquire(id)).session;
        await append(held, userEntry("e1", null));
        await store.forget(id);
        const fresh = (await readBack(store, id));
        await append(held, userEntry("x", "e1"), { expectedLeafId: "e1" });
        await rejectsWithConflict(() => append(fresh, userEntry("y", "e1"), { expectedLeafId: "e1" }), "the fresh handle writing on the parent the held handle already advanced");
        assert.deepEqual(await pathIds((await readBack(store, id))), ["e1", "x"]);
    });
    faceRun("[tree] a write through one replica and a write through another on the same parent: one lands, the other conflicts", ["replica"], async (store, open) => {
        const id = freshId();
        const other = await open(hooks.replica(store));
        const here = (await store.acquire(id)).session;
        await append(here, userEntry("e1", null));
        const there = (await readBack(other, id));
        await append(here, userEntry("x", "e1"), { expectedLeafId: "e1" });
        await rejectsWithConflict(() => append(there, userEntry("y", "e1"), { expectedLeafId: "e1" }), "the second replica writing on the parent the first replica already advanced");
        assert.deepEqual(await pathIds((await readBack(other, id))), ["e1", "x"], "the replica reads the winner's branch");
    });
    run("[rows] a session lives in the rows, not in an instance: entries, a branch switch and the leaf read back through require-existing on a reopened store", async (store, open) => {
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("e1", null));
        await append(session, assistantEntry("e2", "e1"));
        await session.getStorage().setLeafId("e1");
        await append(session, userEntry("e3", "e1"));
        const before = await entryIds(session);
        const second = await open(hooks.reopen(store));
        const woken = (await readBack(second, id));
        assert.equal(await woken.getStorage().getLeafId(), "e3", "the leaf a branch switch set survives the reopen");
        assert.deepEqual(await pathIds(woken), ["e1", "e3"]);
        const after = await entryIds(woken);
        for (const e of ["e1", "e2", "e3"])
            assert.ok(after.includes(e), `the reopened log keeps ${e}`);
        assert.deepEqual(after.filter((e) => before.includes(e)), before.filter((e) => after.includes(e)), "the reopened log keeps the written order");
    });
    run("[rows] a leaf switch persists by itself: setLeafId onto an earlier entry, then onto null, each reads back on a reopened store with nothing appended after it", async (store, open) => {
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("e1", null));
        await append(session, assistantEntry("e2", "e1"));
        await session.getStorage().setLeafId("e1");
        const second = await open(hooks.reopen(store));
        const woken = await readBack(second, id);
        assert.equal(await woken.getStorage().getLeafId(), "e1", "setLeafId records the active leaf in the rows — a rewind must survive the instance");
        assert.deepEqual(await pathIds(woken), ["e1"]);
        await woken.getStorage().setLeafId(null);
        const third = await open(hooks.reopen(second));
        assert.equal(await (await readBack(third, id)).getStorage().getLeafId(), null, "a switch to no leaf persists too");
    });
    run("[rows] a reopened session builds the context the writer saw; its path is a suffix of the written one that starts at a root or at the declared floor", async (store, open) => {
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("u1", null));
        await append(session, assistantEntry("a1", "u1"));
        await append(session, userEntry("u2", "a1"));
        await append(session, assistantEntry("a2", "u2"));
        await append(session, compactionEntry("c1", "a2", "u2"));
        await append(session, userEntry("u3", "c1"));
        const written = await pathIds(session);
        const context = await session.buildContext();
        const second = await open(hooks.reopen(store));
        const woken = (await readBack(second, id));
        const path = await woken.getStorage().getPathToRoot(await woken.getStorage().getLeafId());
        const floor = woken.getStorage().getFloorId?.() ?? null;
        assert.ok(path[0].parentId === null || path[0].id === floor, "a woken path's head is a root or the floor the storage declares — a headless window it does not declare is a corrupt log");
        assert.deepEqual(path.map((e) => e.id), written.slice(written.length - path.length), "the woken path is the written path, or its tail from the floor");
        assert.deepEqual(await woken.buildContext(), context, "waking from the rows (bounded or whole) rebuilds the same context");
    });
    run("[rows] a stored epoch record that does not read never hides an older pin: a reopened session answers what the same log without it answers, woken whole or bounded, and the walk counts what it passed over", async (store, open) => {
        const pin = epochPin();
        const write = async (unreadable) => {
            const id = freshId();
            const { session } = await store.acquire(id);
            await append(session, { id: "p1", parentId: null, type: "prompt_epoch", timestamp: AT, ...pin });
            await append(session, userEntry("u1", "p1"));
            await append(session, assistantEntry("a1", "u1"));
            const x1 = unreadable
                ? { id: "x1", parentId: "a1", type: "prompt_epoch", timestamp: AT, ...pin, epoch: 2, identity: textContentHashOf("not the layers' digest") }
                : { id: "x1", parentId: "a1", type: "session_info", timestamp: AT, name: "kit" };
            await append(session, x1);
            await append(session, userEntry("u2", "x1"));
            await append(session, assistantEntry("a2", "u2"));
            await append(session, compactionEntry("c1", "a2", "u2"));
            await append(session, userEntry("u3", "c1"));
            return id;
        };
        const withIt = await write(true);
        const without = await write(false);
        const second = await open(hooks.reopen(store));
        const woken = (await readBack(second, withIt)).getStorage();
        const control = (await readBack(second, without)).getStorage();
        assert.deepEqual(await new StoredSession(woken).getPromptEpoch(), await new StoredSession(control).getPromptEpoch(), "a stored epoch record that does not read changes nothing about the pin the session answers — a store that wakes a bounded window answers getEpochAnchor with the nearest record below its floor whose record READS (walkPromptEpochCarriers' found.record), never the one that does not read");
        const bounded = (woken.getFloorId?.() ?? null) !== null;
        if (!bounded)
            assert.deepEqual(await new StoredSession(control).getPromptEpoch(), { kind: "pin", descriptor: pin }, "a whole wake answers the pin its branch holds");
        const path = await woken.getPathToRoot(await woken.getLeafId());
        const heldAt = path.findIndex((e) => e.id === "x1");
        assert.ok(heldAt >= 0 || bounded, "a whole wake holds every written entry — the record that does not read is stored as written, not dropped");
        if (heldAt >= 0) {
            const walked = await walkPromptEpochCarriers((below) => (below > 0 ? { entry: path[below - 1], seq: below - 1 } : undefined), path.length);
            assert.deepEqual(walked.skipped, { count: 1, newestSeq: heldAt }, "the walk over the woken path passes over exactly the record that does not read, and names its position");
        }
    });
    faceRun("[rows] forget drops only the cached view: the history survives and the next acquire reopens it", ["forget"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id)).session, userEntry("e1", null));
        await store.forget(id);
        assert.deepEqual(await entryIds((await readBack(store, id))), ["e1"], "forget must never delete history");
    });
    faceRun("[fork] fork copies the committed history into a new id stamped with its source, and the two logs are independent", ["fork"], async (store) => {
        const src = freshId();
        const source = (await store.acquire(src)).session;
        await append(source, userEntry("e1", null));
        await append(source, assistantEntry("e2", "e1"));
        const forkedId = await store.fork(src);
        assert.ok(forkedId !== null && forkedId !== src, "a fork of an existing session is a new id");
        const forked = (await readBack(store, forkedId));
        assert.deepEqual(await pathIds(forked), ["e1", "e2"], "the fork carries the source's committed history");
        assert.equal((await forked.getMetadata()).forkedFrom, src, "the fork names its source");
        await append(forked, userEntry("f3", "e2"));
        await append(source, userEntry("s3", "e2"));
        assert.deepEqual(await pathIds((await readBack(store, src))), ["e1", "e2", "s3"], "writes to the fork never reach the source");
        assert.deepEqual(await pathIds((await readBack(store, forkedId))), ["e1", "e2", "f3"], "writes to the source never reach the fork");
    });
    faceRun("[fork] a fork given an id lands on that id; a second fork onto it is refused conflict and the row the first laid down is unchanged; of two forks onto one free id at once exactly one lands", ["fork"], async (store, open) => {
        const src = freshId();
        const source = (await store.acquire(src)).session;
        await append(source, userEntry("e1", null));
        await append(source, assistantEntry("e2", "e1"));
        const target = freshId();
        assert.equal(await store.fork(src, undefined, { id: target }), target, "a fork given an id lands on that id");
        const forked = await readBack(store, target);
        assert.deepEqual(await pathIds(forked), ["e1", "e2"], "the fork on the given id carries the source's committed history");
        assert.equal((await forked.getMetadata()).forkedFrom, src, "the fork on the given id names its source");
        await append(forked, userEntry("f3", "e2"));
        const rowOf = async (s) => {
            const m = await s.getMetadata();
            const cells = [m.createdAt, m.owner ?? null, m.incarnation ?? null, m.forkedFrom ?? null, m.forkedFromIncarnation ?? null, m.placement ?? null];
            return structuredClone([cells, await s.getStorage().getEntries()]);
        };
        const laidDown = await rowOf(forked);
        await rejectsWithConflict(() => store.fork(src, undefined, { id: target }), "a second fork onto the id the first laid down");
        const second = await open(hooks.reopen(store));
        const after = await readBack(second, target);
        assert.deepEqual(await pathIds(after), ["e1", "e2", "f3"], "the refused fork wrote nothing: the row keeps the log the first fork laid down and was written since");
        assert.deepEqual(await rowOf(after), laidDown, "the refused fork wrote nothing: the row keeps every cell and every entry whole");
        const other = freshId();
        await append((await second.acquire(other)).session, userEntry("o1", null));
        const raced = freshId();
        const settled = await Promise.allSettled([second.fork(src, undefined, { id: raced }), second.fork(other, undefined, { id: raced })]);
        const landed = settled.flatMap((s, i) => (s.status === "fulfilled" ? [i] : []));
        assert.equal(landed.length, 1, "two forks onto one free id at once: exactly one lands");
        const loser = settled[1 - landed[0]];
        assert.equal(loser.status === "rejected" ? conflictMiss(loser.reason) : "it landed too", undefined, "and the other is refused the engine's session conflict");
        const won = await readBack(await open(hooks.reopen(second)), raced);
        assert.equal((await won.getMetadata()).forkedFrom, landed[0] === 0 ? src : other, "the row is the one fork that landed");
        assert.deepEqual(await pathIds(won), landed[0] === 0 ? ["e1", "e2"] : ["o1"], "and holds that fork's history alone");
    });
    faceRun("[fork] fork of a missing source answers null and creates nothing", ["fork"], async (store) => {
        const missing = freshId();
        assert.equal(await store.fork(missing), null);
        if (await honorsRequireExisting(store))
            await rejectsWithCode(() => store.acquire(missing, { requireExisting: true }), "not_found", "a fork of a missing source must not create it");
        if (hasHead(store))
            assert.equal(await headOf(store, missing), undefined, "a fork of a missing source must not create it");
    });
    faceRun("[fork] a fork never inherits an in-flight assistant turn: a turn with a tool call no result answers yet (with or without sibling results already in) is left out; a turn every call of which is answered is kept", ["fork"], async (store) => {
        const parallel = freshId();
        const p = (await store.acquire(parallel)).session;
        await append(p, userEntry("u1", null));
        await append(p, assistantEntry("a1", "u1", "call-1"));
        const pf = await store.fork(parallel);
        assert.deepEqual(await pathIds((await readBack(store, pf))), ["u1"], "a leaf assistant turn with an unanswered call is in flight");
        const sequential = freshId();
        const q = (await store.acquire(sequential)).session;
        await append(q, userEntry("u1", null));
        await append(q, assistantEntry("a1", "u1", "call-1", "call-2"));
        await append(q, toolResultEntry("r1", "a1", "call-1"));
        const qf = await store.fork(sequential);
        assert.deepEqual(await pathIds((await readBack(store, qf))), ["u1"], "a sibling call's committed result does not settle the turn: call-2 has none");
        const answered = freshId();
        const t = (await store.acquire(answered)).session;
        await append(t, userEntry("u1", null));
        await append(t, assistantEntry("a1", "u1", "call-1", "call-2"));
        await append(t, toolResultEntry("r1", "a1", "call-2"));
        await append(t, toolResultEntry("r2", "r1", "call-1"));
        const tf = await store.fork(answered);
        assert.deepEqual(await pathIds((await readBack(store, tf))), ["u1", "a1", "r1", "r2"], "a tool turn every call of which has its result is settled: a fork keeps it");
        const settled = freshId();
        const s = (await store.acquire(settled)).session;
        await append(s, userEntry("u1", null));
        await append(s, assistantEntry("a1", "u1"));
        const sf = await store.fork(settled);
        assert.deepEqual(await pathIds((await readBack(store, sf))), ["u1", "a1"], "a settled text turn forks whole");
    });
    faceRun("[list] list projects each session row once, newest-first by lastActiveAt, and a touch counts as activity", ["list"], async (store) => {
        const [a, b, c] = [freshId(), freshId(), freshId()];
        await store.acquire(a);
        await tick();
        await store.acquire(b);
        await tick();
        await store.acquire(c);
        let rows = await store.list();
        assertNewestFirst(rows);
        for (const id of [a, b, c])
            assert.equal(rows.filter((r) => r.sessionId === id).length, 1, `session ${id} is listed exactly once`);
        assertActivityOrder(rows, [c, b, a], "a session created later is more recent");
        for (const r of rows)
            assert.ok(r.createdAt === undefined || (typeof r.createdAt === "string" && r.createdAt !== ""), "createdAt is a real timestamp or absent, never an empty placeholder");
        const before = rowOf(rows, a).lastActiveAt;
        await tick();
        await store.touch(a);
        rows = await store.list();
        assertNewestFirst(rows);
        assert.ok(rowOf(rows, a).lastActiveAt >= before, "a touch never moves a session's activity back");
        assertActivityOrder(rows, [a, c, b], "a touch makes a session the most recently active");
    });
    faceRun("[list] a fork's summary names its source; an unforked session's names none", ["list", "fork"], async (store) => {
        const src = freshId();
        await append((await store.acquire(src)).session, userEntry("e1", null));
        const forkedId = await store.fork(src);
        const rows = await store.list();
        assert.equal(rowOf(rows, forkedId)?.forkedFrom, src, "the fork's row carries its lineage");
        assert.equal(rowOf(rows, src)?.forkedFrom, undefined, "the source is no fork");
    });
    faceRun("[list] noteTaskRun lands on the summary; a call without a run id clears lastTaskRunId; an unknown id never throws", ["noteTaskRun"], async (store) => {
        await store.noteTaskRun(freshId(), "kit-task", "kit-run");
        if (typeof store.list !== "function")
            return;
        const a = freshId();
        await store.acquire(a);
        await store.noteTaskRun(a, "task-1", "run-1");
        let rows = await store.list();
        assert.equal(rowOf(rows, a)?.lastTaskId, "task-1");
        assert.equal(rowOf(rows, a)?.lastTaskRunId, "run-1");
        await store.noteTaskRun(a, "task-2");
        rows = await store.list();
        assert.equal(rowOf(rows, a)?.lastTaskId, "task-2");
        assert.equal(rowOf(rows, a)?.lastTaskRunId, undefined, "the two seats describe one run: a newer task with no run id must not keep the older run's id");
    });
    faceRun("[list] the list reads the rows, not a cache: sessions are listed after their cached view is dropped and on a store reopened over the same rows (a restart), newest first", ["list"], async (store, open) => {
        const [a, b] = [freshId(), freshId()];
        await append((await store.acquire(a)).session, userEntry("e1", null));
        await tick();
        await append((await store.acquire(b)).session, userEntry("e1", null));
        if (typeof store.forget === "function") {
            await store.forget(a);
            assert.ok(rowOf(await store.list({ limit: SESSION_LIST_LIMITS.max }), a) !== undefined, "a session whose cached view was dropped is still a row");
        }
        const second = await open(hooks.reopen(store));
        const rows = await second.list({ limit: SESSION_LIST_LIMITS.max });
        assertNewestFirst(rows);
        assertActivityOrder(rows, [b, a], "a restart keeps the activity order the rows recorded");
    });
    faceRun("[list] a touch is recorded on the row: the touched session is still the most recent on a store reopened over the same rows (a restart)", ["list"], async (store, open) => {
        const [a, b] = [freshId(), freshId()];
        await append((await store.acquire(a)).session, userEntry("e1", null));
        await tick();
        await append((await store.acquire(b)).session, userEntry("e1", null));
        await tick();
        await store.touch(a);
        const second = await open(hooks.reopen(store));
        assertActivityOrder(await second.list({ limit: SESSION_LIST_LIMITS.max }), [a, b], "the touch outlives the process that made it");
    });
    faceRun("[list] a cached view of an occupant the listed row does not name lends it nothing: after another instance deleted the row and registered the id to another owner, the row lists without the old occupant's run", ["list", "noteTaskRun", "ownership", "replica"], async (store, open) => {
        const id = freshId();
        const other = await open(hooks.replica(store));
        await store.register(id, "kit-alice");
        await store.acquire(id);
        await store.noteTaskRun(id, "alice-task", "alice-run");
        await other.acquire(id);
        await hooks.deleteSession(other, id);
        await other.register(id, "kit-bob");
        const row = rowOf(await store.list({ owner: "kit-bob", limit: SESSION_LIST_LIMITS.max }), id);
        assert.ok(row !== undefined, "the new owner's row is listed");
        assert.equal(row.lastTaskId, undefined, "the previous occupant's run is not lent to the new owner's row");
        assert.equal(row.lastTaskRunId, undefined);
    });
    faceRun("[list] paging survives a dropped cache: a session whose cached view is dropped between two pages is not read again", ["list", "ownership", "forget"], async (store) => {
        const owner = `kit-forget-${uuidv7().slice(-12)}`;
        const ids = [freshId(), freshId(), freshId()];
        for (const id of ids) {
            await store.register(id, owner);
            await tick();
        }
        for (const id of ids)
            await store.acquire(id);
        const first = await store.list({ owner, limit: 1 });
        assert.equal(first.length, 1);
        const top = first[0];
        await store.forget(top.sessionId);
        const rest = await store.list({ owner, after: { lastActiveAt: top.lastActiveAt, sessionId: top.sessionId } });
        assert.ok(!rest.some((r) => r.sessionId === top.sessionId), "the first page's row is not on the next page");
        assert.equal(rest.length, ids.length - 1, "and every other row is");
    });
    faceRun("[list] owner filters by the row's owner cell: an owner's rows only; with includeUnowned the unowned rows too; no owner = every owner's rows", ["list", "ownership"], async (store) => {
        const [alice, bob] = [`kit-alice-${uuidv7().slice(-12)}`, `kit-bob-${uuidv7().slice(-12)}`];
        const [a1, a2, b1, u1] = [freshId(), freshId(), freshId(), freshId()];
        await store.register(a1, alice);
        await store.register(a2, alice);
        await store.register(b1, bob);
        await store.acquire(u1);
        const ids = (rows) => new Set(rows.map((r) => r.sessionId));
        const own = ids(await store.list({ owner: alice, limit: SESSION_LIST_LIMITS.max }));
        assert.ok(own.has(a1) && own.has(a2), "the owner's rows are listed");
        assert.ok(!own.has(b1) && !own.has(u1), "another owner's row and an unowned row are not");
        const withUnowned = ids(await store.list({ owner: alice, includeUnowned: true, limit: SESSION_LIST_LIMITS.max }));
        assert.ok(withUnowned.has(a1) && withUnowned.has(a2) && withUnowned.has(u1), "includeUnowned adds the unowned rows");
        assert.ok(!withUnowned.has(b1), "and never another owner's");
        const all = ids(await store.list({ limit: SESSION_LIST_LIMITS.max }));
        for (const id of [a1, a2, b1, u1])
            assert.ok(all.has(id), `no owner filter lists every owner's rows (${id})`);
    });
    faceRun("[list] keyset paging reads each row once: pages cut with limit and the after cursor, concatenated, are the one-page list — ties ordered by session id, descending", ["list", "ownership"], async (store) => {
        const owner = `kit-pager-${uuidv7().slice(-12)}`;
        const ids = [freshId(), freshId(), freshId(), freshId(), freshId()];
        for (const id of ids)
            await store.register(id, owner);
        const whole = await store.list({ owner, limit: SESSION_LIST_LIMITS.max });
        assert.deepEqual(new Set(whole.map((r) => r.sessionId)), new Set(ids), "the owner's five rows");
        for (let i = 1; i < whole.length; i++) {
            const [prev, row] = [whole[i - 1], whole[i]];
            assert.ok(prev.lastActiveAt > row.lastActiveAt || (prev.lastActiveAt === row.lastActiveAt && prev.sessionId > row.sessionId), `row ${i} follows row ${i - 1} in (lastActiveAt, sessionId) descending order`);
        }
        const paged = [];
        let after;
        for (let pages = 0; pages < 10; pages++) {
            const page = await store.list({ owner, limit: 2, ...(after !== undefined ? { after } : {}) });
            assert.ok(page.length <= 2, "a page holds at most limit rows");
            if (page.length === 0)
                break;
            paged.push(...page.map((r) => r.sessionId));
            const last = page[page.length - 1];
            after = { lastActiveAt: last.lastActiveAt, sessionId: last.sessionId };
        }
        assert.deepEqual(paged, whole.map((r) => r.sessionId), "the pages, in order, are the one-page list: no row twice, none skipped");
    });
    faceRun("[list] a query without limit reads the default page; an explicit limit reads that many", ["list", "ownership"], async (store) => {
        const owner = `kit-page-${uuidv7().slice(-12)}`;
        const total = SESSION_LIST_LIMITS.default + 1;
        for (let i = 0; i < total; i++)
            await store.register(freshId(), owner);
        assert.equal((await store.list({ owner })).length, SESSION_LIST_LIMITS.default, `no limit = the first ${SESSION_LIST_LIMITS.default} rows`);
        assert.equal((await store.list({ owner, limit: total })).length, total);
        assert.equal((await store.list({ owner, limit: 1 })).length, 1);
    });
    faceRun("[list] a bad query is refused config.invalid_argument, never read as a default: a limit out of 1..max or not an integer, a member of the wrong type, includeUnowned without owner, a malformed cursor, a member the store does not read", ["list"], async (store) => {
        const bad = [
            ["limit 0", { limit: 0 }],
            ["a negative limit", { limit: -1 }],
            ["a fractional limit", { limit: 1.5 }],
            ["a limit past the bound", { limit: SESSION_LIST_LIMITS.max + 1 }],
            ["a limit spelled as a string", { limit: "10" }],
            ["a NaN limit", { limit: Number.NaN }],
            ["an owner that is not a string", { owner: 7 }],
            ["includeUnowned that is not a boolean", { owner: "kit-x", includeUnowned: "yes" }],
            ["includeUnowned without owner", { includeUnowned: true }],
            ["a cursor without a session id", { after: { lastActiveAt: 1 } }],
            ["a cursor whose time is not a finite number", { after: { lastActiveAt: Number.POSITIVE_INFINITY, sessionId: "x" } }],
            ["a cursor carrying another member", { after: { lastActiveAt: 1, sessionId: "x", page: 2 } }],
            ["a member the store does not read", { kitUnreadFilter: "x" }],
            ["a query that is not an object", 7],
        ];
        for (const [what, query] of bad) {
            await rejectsWithCode(() => Reflect.apply(store.list, store, [query]), "config.invalid_argument", `list(${what})`);
        }
    });
    faceRun("[placements] a placed session stays off the host list — before and after a restart, also when read back with require-existing", ["placements"], async (store, open) => {
        const placed = freshId();
        const plain = freshId();
        await store.acquire(placed, { placement: placementFor() });
        await store.acquire(plain);
        if (typeof store.list !== "function")
            return;
        let rows = await store.list();
        assert.equal(rowOf(rows, placed), undefined, "obligation 2: a placed session is not a host session");
        assert.ok(rowOf(rows, plain) !== undefined, "an ordinary session is listed");
        const second = await open(hooks.reopen(store));
        await second.acquire(placed, { requireExisting: true });
        await readBack(second, plain);
        rows = await second.list();
        assert.equal(rowOf(rows, placed), undefined, "obligation 2 is restart-stable, read-back included");
    });
    faceRun("[placements] a claim-form acquire of an existing placed id is refused placement_refused — on a cache hit, after forget, and after a restart", ["placements"], async (store, open) => {
        const id = freshId();
        await store.acquire(id, { placement: placementFor() });
        await rejectsWithCode(() => store.acquire(id), "placement_refused", "obligation 6 on the instance that created it");
        if (typeof store.forget === "function") {
            await store.forget(id);
            await rejectsWithCode(() => store.acquire(id), "placement_refused", "obligation 6 after the cached view was dropped");
        }
        const second = await open(hooks.reopen(store));
        await rejectsWithCode(() => second.acquire(id), "placement_refused", "obligation 6 after a restart");
    });
    faceRun("[placements] require-existing re-opens a placed session — with no placement, its own, or a foreign one — on the same history, and rewrites nothing", ["placements"], async (store) => {
        const id = freshId();
        const own = placementFor();
        await append((await store.acquire(id, { placement: own })).session, userEntry("e1", null));
        assert.deepEqual(await entryIds((await store.acquire(id, { requireExisting: true })).session), ["e1"], "obligation 5: the read form");
        assert.deepEqual(await entryIds((await store.acquire(id, { requireExisting: true, placement: own })).session), ["e1"]);
        assert.deepEqual(await entryIds((await store.acquire(id, { requireExisting: true, placement: placementFor() })).session), ["e1"], "a foreign placement on the read form attaches to the same session");
        await store.acquire(id, { placement: own });
        await rejectsWithCode(() => store.acquire(id), "placement_refused", "and the session is still placed");
    });
    faceRun("[placements] release of a placed id is a real deletion, whatever the evict policy — not_found here and after a restart", ["placements"], async (store, open) => {
        const id = freshId();
        await append((await store.acquire(id, { placement: placementFor() })).session, userEntry("e1", null));
        await store.release(id);
        await rejectsWithCode(() => store.acquire(id, { requireExisting: true }), "not_found", "obligation 4: the released transcript is gone");
        const second = await open(hooks.reopen(store));
        await rejectsWithCode(() => second.acquire(id, { requireExisting: true }), "not_found", "obligation 4 holds on the durable rows, not only in the cache");
    });
    faceRun("[placements] an acquire carrying a placement onto an existing ordinary id, or onto one placed under another tuple, is refused placement_refused; the same tuple re-acquires", ["placements"], async (store, open) => {
        const ordinary = freshId();
        await store.acquire(ordinary);
        await rejectsWithCode(() => store.acquire(ordinary, { placement: placementFor() }), "placement_refused", "a placement onto a session that exists outside the partition (cache hit)");
        if (typeof store.forget === "function") {
            await store.forget(ordinary);
            await rejectsWithCode(() => store.acquire(ordinary, { placement: placementFor() }), "placement_refused", "the same after the cached view was dropped");
        }
        const tuple = placementFor();
        const placed = freshId();
        await store.acquire(placed, { placement: tuple });
        await rejectsWithCode(() => store.acquire(placed, { placement: { ...tuple, handle: `${tuple.handle}-other` } }), "placement_refused", "a placement whose handle differs from the persisted one");
        await rejectsWithCode(() => store.acquire(placed, { placement: { ...tuple, scope: `${tuple.scope}-other` } }), "placement_refused", "a placement whose scope differs from the persisted one");
        await store.acquire(placed, { placement: tuple });
        const second = await open(hooks.reopen(store));
        await rejectsWithCode(() => second.acquire(ordinary, { placement: placementFor() }), "placement_refused", "the same after a restart");
        await second.acquire(placed, { placement: tuple });
    });
    faceRun("[placements] a placed creation racing a claim-form acquire of the same id: exactly one of them gets the id, and what it got is what later reads see", ["placements"], async (store) => {
        const id = freshId();
        const tuple = placementFor();
        const [placedCall, claimCall] = await Promise.allSettled([store.acquire(id, { placement: tuple }), store.acquire(id)]);
        const winners = [placedCall, claimCall].filter((s) => s.status === "fulfilled").length;
        assert.equal(winners, 1, "the placed creator and the claimant can never both attach (a squat or a claim of a transcript), nor both be refused");
        if (placedCall.status === "fulfilled") {
            await rejectsWithCode(() => store.acquire(id), "placement_refused", "the placed creator won: the id is a transcript");
        }
        else {
            assert.equal(readMember(placedCall.reason, "code"), "placement_refused");
            await rejectsWithCode(() => store.acquire(id, { placement: tuple }), "placement_refused", "the claimant won: the id is an ordinary session");
        }
    });
    run("[placements] a store that does not declare placements still creates the session for an acquire carrying one (ignoring it is legal, refusing the creation is not)", async (store) => {
        if (declaresPlacements(store))
            return;
        const id = freshId();
        const acquired = await store.acquire(id, { placement: placementFor() });
        assert.equal(acquired.sessionId, id);
        await append(acquired.session, userEntry("e1", null));
        assert.deepEqual(await entryIds((await readBack(store, id))), ["e1"]);
    });
    faceRun("[placements] the placing acquire records exactly its owner as the row's owner (none named ⇒ anonymous), and headOf answers the placed row with the occupant the acquired session carries — before and after a restart", ["placements"], async (store, open) => {
        assert.ok(hasHead(store), "a store that declares placements answers headOf (obligation 7): the revival entry judges the owner of the row it re-opens through it");
        const named = freshId();
        const anonymous = freshId();
        const owner = `kit-tree-${freshId()}`;
        const acquired = await store.acquire(named, { placement: placementFor(), owner });
        await store.acquire(anonymous, { placement: placementFor() });
        const token = await tokenOf(store, named, "a placed row this store created");
        assert.equal((await acquired.session.getMetadata()).incarnation, token, "the placed session handed out is the occupant the head names");
        assert.equal(await ownerOf(store, named, "a placed row"), owner, "the placing acquire recorded the owner it named");
        assert.equal(await ownerOf(store, anonymous, "a placed row of an anonymous tree"), null, "a placing acquire that names no owner creates an anonymous row");
        const tuple = (await (await readBack(store, named)).getMetadata()).placement ?? {};
        assert.equal(Object.prototype.hasOwnProperty.call(tuple, "owner"), false, "the tuple carries no owner — the owner is the row's cell");
        const second = await open(hooks.reopen(store));
        assert.deepEqual(await headOf(second, named), await headOf(store, named), "the owner lives in the row, not in an instance");
    });
    faceRun("[placements] listPlaced returns each placed session with its full (scope, handle) tuple or the honest tupleIncomplete, filters by scope and age, and never lists an ordinary session", ["listPlaced"], async (store) => {
        const scope = `kit-${uuidv7().slice(-12)}`;
        const full = placementFor(scope);
        const [complete, incomplete, ordinary, elsewhere] = [freshId(), freshId(), freshId(), freshId()];
        await store.acquire(complete, { placement: full });
        await store.acquire(incomplete, { placement: placementFor(scope, null) });
        await store.acquire(ordinary);
        await store.acquire(elsewhere, { placement: placementFor() });
        const rows = await store.listPlaced("subagent");
        const row = (id) => rows.find((r) => r.sessionId === id);
        const c = row(complete);
        assert.ok(c !== undefined && !("tupleIncomplete" in c), "a placed session with both join halves is a full row");
        assert.equal(c.scope, full.scope);
        assert.equal(c.handle, full.handle);
        assert.equal(typeof c.placedAt, "number");
        const i = row(incomplete);
        assert.ok(i !== undefined && "tupleIncomplete" in i && i.tupleIncomplete === true, "a placed session missing a join half is the tupleIncomplete row, never a guessed tuple");
        assert.equal(row(ordinary), undefined, "an ordinary session is not in the placed partition");
        assert.ok(row(elsewhere) !== undefined);
        const scoped = (await store.listPlaced("subagent", { scope })).map((r) => r.sessionId);
        assert.ok(scoped.includes(complete) && scoped.includes(incomplete) && !scoped.includes(elsewhere), "scope narrows to one tenant");
        assert.ok(!(await store.listPlaced("subagent", { olderThanMs: 60 * 60 * 1000 })).some((r) => r.sessionId === complete), "a session placed just now is not an hour old");
    });
    faceRun("[placements] a fork carrying a placement is created into the partition — the tuple reads back on the forked row, which stays off the host list, refuses a claim-form acquire, is listed placed and is deleted by its release, while its source stays ordinary — before and after a restart", ["placements", "fork"], async (store, open) => {
        const src = freshId();
        await append((await store.acquire(src)).session, userEntry("e1", null));
        const tuple = placementFor(`kit-${uuidv7().slice(-12)}`);
        const forkedId = await store.fork(src, null, { placement: { ...tuple, parentSessionId: src, rootSessionId: src } });
        assert.ok(forkedId !== null && forkedId !== src, "a placed fork of an existing session is a new id");
        const meta = await (await readBack(store, forkedId)).getMetadata();
        assert.equal(meta.forkedFrom, src, "a placed fork still names its source");
        assert.deepEqual({ kind: meta.placement?.kind, scope: meta.placement?.scope, handle: meta.placement?.handle, parentSessionId: meta.placement?.parentSessionId, rootSessionId: meta.placement?.rootSessionId }, { kind: "subagent", scope: tuple.scope, handle: tuple.handle, parentSessionId: src, rootSessionId: src }, "the fork's creating write laid the tuple down");
        assert.equal(typeof meta.placement?.placedAt, "number", "the store stamped placedAt");
        assert.deepEqual(await pathIds(await readBack(store, forkedId)), ["e1"], "the placed fork carries the source's committed history");
        await rejectsWithCode(() => store.acquire(forkedId), "placement_refused", "obligation 6: a placed fork is not claimable");
        await store.acquire(src);
        if (typeof store.list === "function") {
            const rows = await store.list();
            assert.equal(rowOf(rows, forkedId), undefined, "obligation 2: a placed fork is not a host session");
            assert.ok(rowOf(rows, src) !== undefined, "its source stays an ordinary, listed session");
        }
        if (typeof store.listPlaced === "function") {
            const listed = (await store.listPlaced("subagent", { scope: tuple.scope })).find((r) => r.sessionId === forkedId);
            assert.ok(listed !== undefined && !("tupleIncomplete" in listed) && listed.handle === tuple.handle, "the placed listing carries the fork with its join tuple");
        }
        const second = await open(hooks.reopen(store));
        assert.equal((await readBack(second, forkedId).then((s) => s.getMetadata())).placement?.handle, tuple.handle, "the tuple lives in the row, not in an instance");
        await rejectsWithCode(() => second.acquire(forkedId), "placement_refused", "obligation 6 after a restart");
        await second.release(forkedId);
        await rejectsWithCode(() => second.acquire(forkedId, { requireExisting: true }), "not_found", "obligation 4: the placed fork's release is a real deletion");
        assert.deepEqual(await pathIds(await readBack(second, src)), ["e1"], "the source is untouched");
    });
    run("[placements] a store that does not declare placements still forks for a fork carrying a placement (ignoring it is legal, refusing the fork is not)", async (store) => {
        if (declaresPlacements(store) || !hasSessionFork(store))
            return;
        const src = freshId();
        await append((await store.acquire(src)).session, userEntry("e1", null));
        const forkedId = await store.fork(src, null, { placement: placementFor() });
        assert.ok(forkedId !== null && forkedId !== src);
        assert.deepEqual(await pathIds(await readBack(store, forkedId)), ["e1"]);
    });
    faceRun("[head] headOf answers undefined for an id with no row; for a row, its owner, its occupant and its active leaf — the leaf follows appends and a branch switch", ["headOf"], async (store) => {
        const id = freshId();
        assert.equal(await headOf(store, id), undefined, "no row ⇒ undefined");
        const { session } = await store.acquire(id);
        assert.deepEqual(await headOf(store, id), { owner: null, incarnation: (await session.getMetadata()).incarnation, leafId: null }, "a row acquire created: no owner, its occupant, no leaf");
        await append(session, userEntry("e1", null));
        await append(session, assistantEntry("e2", "e1"));
        assert.equal((await headOf(store, id))?.leafId, "e2", "an append moves the head's leaf");
        await session.getStorage().setLeafId("e1");
        assert.equal((await headOf(store, id))?.leafId, "e1", "a branch switch moves it back");
        await session.getStorage().setLeafId(null);
        assert.equal((await headOf(store, id))?.leafId, null);
    });
    faceRun("[head] the head lives in the row: a store reopened over the same rows (a restart) answers the same owner, occupant and leaf", ["headOf"], async (store, open) => {
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("e1", null));
        await append(session, assistantEntry("e2", "e1"));
        await session.getStorage().setLeafId("e1");
        const before = await headOf(store, id);
        const second = await open(hooks.reopen(store));
        assert.deepEqual(await headOf(second, id), before, "a head an instance kept for itself would answer differently after every restart");
    });
    faceRun("[head] one read, one generation: while an id is deleted and created again under other owners, no head pairs one generation's owner with another's occupant", ["ownership"], async (store) => {
        const id = freshId();
        const generations = [];
        const reads = [];
        const probe = () => {
            for (let k = 0; k < 3; k++)
                reads.push(headOf(store, id));
        };
        for (let i = 0; i < 12; i++) {
            if (i > 0) {
                probe();
                await hooks.deleteSession(store, id);
            }
            probe();
            await store.register(id, `kit-gen-${i}`);
            probe();
            await store.acquire(id);
            generations.push((await headOf(store, id)));
        }
        const whole = new Set(generations.map((g) => `${g.owner}|${g.incarnation}`));
        assert.equal(whole.size, generations.length, "each generation is its own owner and occupant");
        for (const head of await Promise.all(reads)) {
            if (head === undefined)
                continue;
            assert.ok(whole.has(`${head.owner}|${head.incarnation}`), `a head read ${head.owner} with occupant ${head.incarnation}, a pair no generation of the row ever held`);
        }
    });
    faceRun("[head] a row written before occupant tokens (the tokenlessRow hook) answers a head naming no occupant — no incarnation, not incarnation: null", ["headOf", "tokenlessRow"], async (store) => {
        const id = freshId();
        await hooks.tokenlessRow(store, id);
        const head = await gateHead(store, id, "the row written before tokens");
        assert.equal(head.incarnation, undefined, `a row with no occupant token answers a head with no incarnation (got ${describeRejectedValue(head.incarnation)}): a gate hands the head as it came to a write's expect.row, where an occupant that is not a token is no expectation — every move of the row is refused config.invalid_argument`);
    });
    faceRun("[ownership] register on an id with no row creates its row recording the owner — a string, or null for anonymous; a row an acquire naming no owner created records null", ["ownership"], async (store) => {
        const [owned, anonymous, acquired] = [freshId(), freshId(), freshId()];
        await store.register(owned, "kit-alice");
        await store.register(anonymous, null);
        await store.acquire(acquired);
        assert.equal(await ownerOf(store, owned, "a registered id"), "kit-alice");
        assert.equal(await ownerOf(store, anonymous, "an anonymous registration"), null);
        assert.equal(await ownerOf(store, acquired, "a row acquire created"), null, "an acquire that names no owner creates an anonymous row");
        const token = await tokenOf(store, owned, "a registered row");
        assert.equal((await (await readBack(store, owned)).getMetadata()).incarnation, token, "the registered row is the session acquire then hands out");
    });
    faceRun("[ownership] a create-capable acquire records the owner it names in the row it creates — a name, or null for anonymous, on a caller's id and on an id the store mints — and the occupant headOf names is the session it handed out; the owner reads back after the cached view is dropped and on a store reopened over the same rows (a restart)", ["ownership"], async (store, open) => {
        const [named, anonymous] = [freshId(), freshId()];
        const owner = `kit-tree-${freshId()}`;
        const a = await store.acquire(named, { owner });
        await store.acquire(anonymous, { owner: null });
        const minted = await store.acquire(undefined, { owner });
        for (const [id, want, what, held] of [[named, owner, "a caller's id", a], [anonymous, null, "an anonymous acquire", undefined], [minted.sessionId, owner, "an id the store minted", minted]]) {
            assert.equal(await ownerOf(store, id, what), want, `${what}: the creating acquire recorded the owner it named`);
            if (held !== undefined)
                assert.equal((await held.session.getMetadata()).incarnation, await tokenOf(store, id, what), `${what}: the session handed out is the occupant the head names`);
        }
        await store.forget?.(named);
        assert.equal(await ownerOf(store, named, "after the cached view is dropped"), owner, "the owner is a cell of the row, not of the cached view");
        const second = await open(hooks.reopen(store));
        assert.equal(await ownerOf(second, named, "on a reopened store"), owner, "the owner lives in the row, not in an instance");
        assert.equal(await ownerOf(second, minted.sessionId, "on a reopened store (minted id)"), owner);
    });
    faceRun("[ownership] an acquire naming an owner resolves an EXISTING row without changing it — an owned row, an anonymous row, a row an acquire created — whatever it names, and the row's log is the one it held", ["ownership"], async (store) => {
        const [owned, anonymous, acquired] = [freshId(), freshId(), freshId()];
        await store.register(owned, "kit-alice");
        await store.register(anonymous, null);
        await append((await store.acquire(acquired)).session, userEntry("e1", null));
        for (const [id, recorded, what] of [[owned, "kit-alice", "an owned row"], [anonymous, null, "an anonymous row"], [acquired, null, "a row an acquire created"]]) {
            const token = await tokenOf(store, id, what);
            for (const named of [`kit-claimant-${freshId()}`, null]) {
                const got = await store.acquire(id, { owner: named });
                assert.equal(got.sessionId, id, `${what}: the acquire resolved the existing row`);
                assert.equal(await ownerOf(store, id, what), recorded, `${what}: an acquire naming ${named === null ? "null" : "another owner"} left the owner its creating write recorded`);
                assert.equal(await tokenOf(store, id, what), token, `${what}: the occupant is the one created first — the acquire created nothing`);
            }
        }
        assert.deepEqual(await entryIds(await readBack(store, acquired)), ["e1"], "the existing row's log is untouched");
    });
    faceRun("[ownership] register on a row that exists does nothing, whatever it carries — an owned row, an anonymous row, a row acquire created, a placed row", ["ownership"], async (store) => {
        const [owned, anonymous, acquired] = [freshId(), freshId(), freshId()];
        await store.register(owned, "kit-alice");
        await store.register(owned, "kit-bob");
        await store.register(owned, null);
        await registerUntyped(store, owned, undefined);
        assert.equal(await ownerOf(store, owned, "an owned row"), "kit-alice");
        await store.register(anonymous, null);
        await store.register(anonymous, "kit-bob");
        assert.equal(await ownerOf(store, anonymous, "an anonymous row"), null, "an anonymous row is not claimable by a later register");
        await store.acquire(acquired);
        await store.register(acquired, "kit-carol");
        assert.equal(await ownerOf(store, acquired, "a row acquire created"), null, "there is no claiming of a row that exists");
        if (declaresPlacements(store)) {
            for (const owner of [`kit-claimant-${freshId()}`, null]) {
                const placed = freshId();
                await store.acquire(placed, { placement: placementFor(), owner: `kit-tree-${freshId()}` });
                const recorded = await ownerOf(store, placed, "a placed row");
                await store.register(placed, owner);
                assert.equal(await ownerOf(store, placed, "a placed row after a register"), recorded, `a register carrying ${owner === null ? "null" : "an owner"} left the placed row's owner as its placing write recorded it`);
            }
            const sequenced = freshId();
            await store.acquire(sequenced, { placement: placementFor(), owner: `kit-tree-${freshId()}` });
            const recordedSeq = await ownerOf(store, sequenced, "a placed row (sequence)");
            await store.register(sequenced, null);
            await store.register(sequenced, `kit-claimant-${freshId()}`);
            assert.equal(await ownerOf(store, sequenced, "a placed row after two registers"), recordedSeq, "two registers in sequence (null, then a name) left the placed row's owner as its placing write recorded it");
        }
    });
    faceRun("[ownership] a FIRST register whose owner is neither a principal name nor null is refused loudly and leaves no row behind — a blank string, or one holding a control or invisible character, names nobody", ["ownership"], async (store) => {
        const id = freshId();
        await thrownBy(() => registerUntyped(store, id, undefined), "a first register with owner undefined");
        await thrownBy(() => registerUntyped(store, id, 42), "a first register with a numeric owner");
        await thrownBy(() => registerUntyped(store, id, ""), "a first register with the empty string as owner");
        await thrownBy(() => registerUntyped(store, id, " \t "), "a first register with a blank string as owner");
        await thrownBy(() => registerUntyped(store, id, "ali\u0000ce"), "a first register with a control character inside the owner");
        await thrownBy(() => registerUntyped(store, id, "\u200b"), "a first register with an invisible character as owner");
        assert.equal(await headOf(store, id), undefined, "the refused writes stored nothing");
        await store.register(id, "kit-carol");
        assert.equal(await ownerOf(store, id, "the first well-formed register"), "kit-carol", "the id is still ownable");
    });
    faceRun("[ownership] two concurrent first registers: each caller's own re-read sees the same winner, one of the two", ["ownership"], async (store) => {
        const id = freshId();
        const caller = async (owner) => {
            await store.register(id, owner);
            return ownerOf(store, id, "after a register");
        };
        const [x, y] = await Promise.all([caller("kit-x"), caller("kit-y")]);
        assert.equal(x, y, "the loser must see the winner on its own re-read, or both callers attach to one session");
        assert.ok(x === "kit-x" || x === "kit-y");
        assert.equal(await ownerOf(store, id, "the settled row"), x, "and the row keeps that winner");
    });
    faceRun("[ownership] the owner is a cell of the row: it reads back after the cached view is dropped and on a store reopened over the same rows (a restart)", ["ownership"], async (store, open) => {
        const [owned, acquired] = [freshId(), freshId()];
        await store.register(owned, "kit-alice");
        await append((await store.acquire(owned)).session, userEntry("e1", null));
        await store.acquire(acquired);
        if (typeof store.forget === "function") {
            await store.forget(owned);
            assert.equal(await ownerOf(store, owned, "a forgotten session"), "kit-alice", "a live session must never lose its owner with the cached view");
        }
        const second = await open(hooks.reopen(store));
        assert.equal(await ownerOf(second, owned, "after a restart"), "kit-alice", "an owner an instance kept for itself is lost on every restart, and the session is then anyone's");
        assert.equal(await ownerOf(second, acquired, "after a restart"), null);
        await second.register(owned, "kit-bob");
        assert.equal(await ownerOf(second, owned, "a register after a restart"), "kit-alice", "a restart opens no claiming window");
    });
    faceRun("[ownership] a fork records its owner in its own row: no owner or null ⇒ the source's (an owned copy is never downgraded), an explicit owner ⇒ that owner, an anonymous source ⇒ anonymous", ["ownership", "fork"], async (store) => {
        const owned = freshId();
        await store.register(owned, "kit-alice");
        await append((await store.acquire(owned)).session, userEntry("e1", null));
        assert.equal(await ownerOf(store, (await store.fork(owned)), "a fork"), "kit-alice", "no owner argument ⇒ the source's owner");
        assert.equal(await ownerOf(store, (await store.fork(owned, null)), "a fork"), "kit-alice", "an explicit null never downgrades a copy of an owned history to anonymous");
        assert.equal(await ownerOf(store, (await store.fork(owned, "kit-bob")), "a fork"), "kit-bob", "an explicit owner scopes the fork");
        const anonymous = freshId();
        await append((await store.acquire(anonymous)).session, userEntry("e1", null));
        assert.equal(await ownerOf(store, (await store.fork(anonymous)), "a fork"), null);
        assert.equal(await ownerOf(store, (await store.fork(anonymous, null)), "a fork"), null);
    });
    faceRun("[ownership] an id registered first is an ordinary row: a placement-carrying acquire of it is refused placement_refused", ["ownership", "placements"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        await rejectsWithCode(() => store.acquire(id, { placement: placementFor() }), "placement_refused", "a placed creation onto an id a register already created");
        assert.equal(await ownerOf(store, id, "the registered row"), "kit-alice", "the refused acquire rewrote nothing");
    });
    faceRun("[ownership] acquire serves only the occupant the row holds: after another instance deleted the row and registered the id to another owner, this instance's next acquire serves the new occupant, never its cached view of the old one", ["ownership", "replica"], async (store, open) => {
        const id = freshId();
        const other = await open(hooks.replica(store));
        await store.register(id, "kit-alice");
        await append((await store.acquire(id)).session, userEntry("alice-only", null));
        await other.acquire(id);
        await hooks.deleteSession(other, id);
        await other.register(id, "kit-bob");
        const head = await headOf(store, id);
        assert.equal(head?.owner, "kit-bob", "this instance's head reads the row");
        const served = (await store.acquire(id)).session;
        assert.equal((await served.getMetadata()).incarnation, head?.incarnation, "the session handed out is the row the owner was read from");
        assert.deepEqual(await entryIds(served), [], "the previous occupant's transcript is not served under the new owner");
    });
    faceRun("[ownership] the metadata a session hands out is not the row: writing to it changes no owner or occupant the head answers", ["ownership"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        const before = await headOf(store, id);
        try {
            Object.assign(await (await store.acquire(id)).session.getMetadata(), { owner: null, incarnation: "kit-forged" });
        }
        catch {
        }
        assert.deepEqual(await headOf(store, id), before, "admission changes only through a write of the row");
    });
    const claimOf = (head) => ({ row: { owner: null, ...(head.incarnation !== undefined ? { incarnation: head.incarnation } : {}) } });
    faceRun("[recordOwner] a row that records no owner, claimed naming the occupant its caller read: the owner is recorded and nothing else of the row changes (its occupant, its log, its leaf); the answer is that head; it reads back after the cached view is dropped and on a store reopened over the same rows (a restart)", ["recordOwner"], async (store, open) => {
        const [registered, acquired] = [freshId(), freshId()];
        await store.register(registered, null);
        const held = await store.acquire(acquired);
        await append(held.session, userEntry("c1", null));
        for (const [id, what] of [[registered, "a row registered anonymous"], [acquired, "a row an acquire naming no owner created"]]) {
            const before = await gateHead(store, id, what);
            assert.equal(before.owner, null, `${what}: records no owner`);
            const answered = await store.recordOwner(id, "kit-alice", claimOf(before));
            assert.deepEqual(answered, { ...before, owner: "kit-alice" }, `${what}: the answer is the head the write committed — the owner recorded, the occupant and the leaf as they were`);
            assert.deepEqual(await headOf(store, id), answered, `${what}: the head read agrees`);
        }
        assert.deepEqual(await entryIds(await readBack(store, acquired)), ["c1"], "the log is the one the row held");
        await store.forget?.(acquired);
        assert.equal(await ownerOf(store, acquired, "after the cached view is dropped"), "kit-alice");
        const second = await open(hooks.reopen(store));
        assert.equal(await ownerOf(second, acquired, "on a reopened store"), "kit-alice", "the claim is a write of the row, not of an instance");
        assert.equal(await ownerOf(second, registered, "on a reopened store"), "kit-alice");
    });
    faceRun("[recordOwner] a row that records a name is left as it is, whatever the call carries — another principal's name, the same name: the answer is its head as read and nothing is written; a claim never changes an owner", ["recordOwner"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-bob");
        const before = await gateHead(store, id, "an owned row");
        assert.deepEqual(await store.recordOwner(id, "kit-alice", claimOf(before)), before, "another principal's claim answers the owned head, unwritten");
        assert.deepEqual(await store.recordOwner(id, "kit-bob", claimOf(before)), before, "the owner's own claim changes nothing either");
        assert.deepEqual(await headOf(store, id), before, "the row still records its owner");
    });
    faceRun("[recordOwner] a claim naming another occupant than the row holds — the row deleted and created again under the id — is refused conflict with nothing written; an id with no row answers undefined and creates none", ["recordOwner"], async (store) => {
        const id = freshId();
        await store.acquire(id);
        const stale = await gateHead(store, id, "the first occupant");
        await hooks.deleteSession(store, id);
        await store.register(id, null);
        const now = await gateHead(store, id, "the second occupant");
        await assert.rejects(() => store.recordOwner(id, "kit-alice", claimOf(stale)), (err) => isSessionConflict(err), "a claim of an occupant the row no longer holds is refused conflict");
        assert.deepEqual(await headOf(store, id), now, "the row standing is untouched");
        const missing = freshId();
        assert.equal(await store.recordOwner(missing, "kit-alice", { row: { owner: null } }), undefined, "no row: undefined");
        assert.equal(await headOf(store, missing), undefined, "and no row was created");
    });
    faceRun("[recordOwner] two concurrent claims of one row by two principals: exactly one owner is recorded, and both answers name that one", ["recordOwner"], async (store) => {
        for (let round = 0; round < 4; round++) {
            const id = freshId();
            await store.register(id, null);
            const head = await gateHead(store, id, "an anonymous row");
            const settled = await Promise.allSettled([store.recordOwner(id, "kit-x", claimOf(head)), store.recordOwner(id, "kit-y", claimOf(head))]);
            const owners = settled.map((s) => (s.status === "fulfilled" ? s.value?.owner : `rejected: ${thrownText(s.reason)}`));
            const winner = await ownerOf(store, id, "the settled row");
            assert.ok(winner === "kit-x" || winner === "kit-y", `round ${round}: one of the two claims recorded its owner, got ${String(winner)}`);
            assert.deepEqual(owners, [winner, winner], `round ${round}: each claimant's answer names the one recorded owner — a claim that answers its own name over another's is two owners of one row`);
        }
    });
    faceRun("[recordOwner] an owner that is not a principal name — null, a blank string, one with a control character, a non-string — is refused config.invalid_argument before the row is read, nothing written", ["recordOwner"], async (store) => {
        const id = freshId();
        await store.register(id, null);
        const head = await gateHead(store, id, "an anonymous row");
        for (const bad of [null, "", "  ", "kit\u0007bell", 7, undefined]) {
            await assert.rejects(() => Reflect.apply(store.recordOwner, store, [id, bad, claimOf(head)]), (err) => readMember(err, "code") === "config.invalid_argument", `owner ${describeRejectedValue(bad)} is refused config.invalid_argument`);
        }
        assert.deepEqual(await headOf(store, id), head, "the row still records no owner");
    });
    faceRun("[recordOwner] a session handed out for the row before the claim keeps writing to it: its appends land on the claimed row, the head follows them, and a store reopened over the same rows (a restart) serves the whole log under the recorded owner", ["recordOwner"], async (store, open) => {
        const id = freshId();
        const held = await store.acquire(id);
        await append(held.session, userEntry("before", null));
        const head = await gateHead(store, id, "an anonymous row");
        await store.recordOwner(id, "kit-alice", claimOf(head));
        await append(held.session, userEntry("after", "before"));
        assert.equal((await held.session.getMetadata()).owner ?? null, "kit-alice", "the session handed out before the claim answers the recorded owner");
        const now = await gateHead(store, id, "after an append through the held session");
        assert.deepEqual({ owner: now.owner, leafId: now.leafId }, { owner: "kit-alice", leafId: "after" }, "the append through the session held across the claim is the row's leaf");
        const served = (await store.acquire(id)).session;
        assert.deepEqual(await entryIds(served), ["before", "after"], "the store serves the row with both entries");
        assert.equal((await served.getMetadata()).owner ?? null, "kit-alice", "the session this store serves after the claim answers the recorded owner (its cached view follows the claim)");
        const second = await open(hooks.reopen(store));
        assert.deepEqual(await entryIds(await readBack(second, id)), ["before", "after"], "the append after the claim is in the row, not only in a cached view");
        assert.equal(await ownerOf(second, id, "on a reopened store"), "kit-alice");
    });
    faceRun("[recordOwner] a claim is not activity: the listing's order and every row's lastActiveAt are what they were before it", ["recordOwner", "list"], async (store) => {
        const [older, newer] = [freshId(), freshId()];
        await append((await store.acquire(older)).session, userEntry("o1", null));
        await new Promise((r) => setTimeout(r, 20));
        await append((await store.acquire(newer)).session, userEntry("n1", null));
        await store.touch(newer);
        const before = (await store.list({ includeUnowned: true, owner: "kit-alice" })).filter((r) => r.sessionId === older || r.sessionId === newer);
        await store.recordOwner(older, "kit-alice", claimOf(await gateHead(store, older, "the older row")));
        const after = (await store.list({ includeUnowned: true, owner: "kit-alice" })).filter((r) => r.sessionId === older || r.sessionId === newer);
        assert.deepEqual(after.map((r) => [r.sessionId, r.lastActiveAt]), before.map((r) => [r.sessionId, r.lastActiveAt]), "the claimed row keeps its place and its activity time");
    });
    faceRun("[recordOwner] no write that names no owner clears a name: on a row that records one, register(id, null) and acquire(id, { owner: null }) leave it as it was", ["recordOwner"], async (store) => {
        const id = freshId();
        await store.acquire(id);
        await store.recordOwner(id, "kit-alice", claimOf(await gateHead(store, id, "an anonymous row")));
        await store.register(id, null);
        await store.acquire(id, { owner: null });
        assert.equal(await ownerOf(store, id, "after writes naming no owner"), "kit-alice", "a claim is never undone by a write that names no owner");
    });
    faceRun("[incarnation] a session created through acquire carries a token, and every later read of the row answers the same one", ["headOf", "requireExisting"], async (store) => {
        const id = freshId();
        await store.acquire(id);
        const first = await tokenOf(store, id, "after acquire");
        await store.acquire(id);
        assert.equal(await tokenOf(store, id, "a re-acquire"), first, "a re-acquire reopens the same occupant");
        await store.forget?.(id);
        assert.equal(await tokenOf(store, id, "after forget"), first, "the token is the row's, not the cache's: forgetting the cached view must not change it");
        await store.acquire(id, { requireExisting: true });
        assert.equal(await tokenOf(store, id, "a require-existing reopen"), first, "a require-existing reopen after the cache forgot it is still the same occupant");
    });
    faceRun("[incarnation] the session acquire hands back carries the token headOf answers — a run's memory seat reads the former", ["headOf", "requireExisting"], async (store) => {
        const id = freshId();
        const acquired = await store.acquire(id);
        const byId = await tokenOf(store, id, "by-id read");
        assert.equal((await acquired.session.getMetadata()).incarnation, byId, "two faces of one row cell must agree, or the seat and the by-id read name two occupants");
    });
    faceRun("[incarnation] a second store over the same rows (a restart, a replica) answers the same token — the token lives in the row, not in an instance", ["headOf", "requireExisting"], async (store, open) => {
        const id = freshId();
        await store.acquire(id);
        const first = await tokenOf(store, id, "first instance");
        const second = await open(hooks.reopen(store));
        assert.equal(await tokenOf(second, id, "second instance"), first, "an instance-local token would name a different occupant after every restart");
        await second.acquire(id, { requireExisting: true });
        assert.equal(await tokenOf(second, id, "reopened on the second instance"), first, "reopening the session on the second instance is still the same occupant");
    });
    faceRun("[incarnation] two sessions never share a token, and an id with no session has no head (unknown — not an error, not a token)", ["headOf", "requireExisting"], async (store) => {
        const id = freshId();
        await store.acquire(id);
        const generated = await store.acquire();
        const a = await tokenOf(store, id, "explicit id");
        const g = await tokenOf(store, generated.sessionId, "generated id");
        assert.notEqual(a, g, "two sessions are two occupants");
        assert.equal(await headOf(store, freshId()), undefined, "no row ⇒ unknown");
    });
    faceRun("[incarnation] a deleted id handed out again is a NEW occupant: a fresh token, never the previous occupant's", ["headOf", "requireExisting"], async (store) => {
        const id = freshId();
        await store.acquire(id);
        const before = await tokenOf(store, id, "first occupant");
        await hooks.deleteSession(store, id);
        assert.equal(await headOf(store, id), undefined, "a deleted row has no occupant");
        await store.acquire(id);
        const after = await tokenOf(store, id, "second occupant");
        assert.notEqual(after, before, "the id was recycled — the previous occupant's records must not bind this one");
    });
    faceRun("[incarnation] a fork is a new occupant: a fresh token, and the source keeps its own", ["headOf", "requireExisting", "fork"], async (store) => {
        const src = freshId();
        await store.acquire(src);
        const source = await tokenOf(store, src, "fork source");
        const forkedId = await store.fork(src);
        assert.ok(forkedId !== null, "forking an existing session returns the fork's id");
        assert.notEqual(await tokenOf(store, forkedId, "fork"), source, "a fork copies the history, never the occupant");
        assert.equal(await tokenOf(store, src, "fork source after"), source, "forking does not touch the source's occupant");
    });
    run("[transfer] the read half answers the whole log oldest-first, resumes after a position, and says null for an id with no row; a bad read option is refused", async (store) => {
        if (!(await FACE_PRESENT.logTransfer(store)))
            return report("logTransfer", "absent");
        const t = store.logTransfer;
        const id = freshId();
        const session = (await store.acquire(id)).session;
        for (const e of [userEntry("e1", null), assistantEntry("e2", "e1"), userEntry("e3", "e2")])
            await append(session, e);
        assert.deepEqual(await t.listEntryIds(id), ["e1", "e2", "e3"]);
        assert.deepEqual(await streamIds(t, id), ["e1", "e2", "e3"]);
        assert.deepEqual(await streamIds(t, id, { afterSeq: 0, batchSize: 1 }), ["e2", "e3"], "afterSeq resumes after that position, whatever the page");
        assert.deepEqual(await streamIds(t, id, { afterSeq: -1 }), ["e1", "e2", "e3"]);
        const absent = freshId();
        assert.equal(await t.listEntryIds(absent), null, "no row ⇒ null, never an empty log");
        assert.equal(await t.exportStream(absent), null);
        for (const bad of [{ afterSeq: -2 }, { afterSeq: 1.5 }, { batchSize: 0 }, { afterSeq: "0" }, { cursor: 1 }]) {
            await rejectsWithCode(() => Reflect.apply(t.exportStream, t, [id, bad]), "config.invalid_argument", `exportStream(${JSON.stringify(bad)})`);
        }
        report("logTransfer", "verified");
    });
    faceRun("[transfer] a commit onto the committer's own row replaces the log and keeps the row: the occupant and owner stay, and the new log is what this store and a reopened one serve", ["logTransfer", "ownership"], async (store, open) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        const held = (await store.acquire(id)).session;
        await append(held, userEntry("old1", null));
        const before = await tokenOf(store, id, "before the commit");
        const done = await commitLog(store, id, { owner: "kit-alice" }, [userEntry("n1", null), assistantEntry("n2", "n1")]);
        assert.equal(done.outcome, "replaced");
        assert.deepEqual({ owner: done.head.owner, incarnation: done.head.incarnation, leafId: done.head.leafId }, { owner: "kit-alice", incarnation: before, leafId: "n2" }, "the head the commit answers is the row it left");
        assert.deepEqual(await headOf(store, id), done.head);
        assert.deepEqual(await entryIds((await store.acquire(id)).session), ["n1", "n2"], "a cached view of the replaced log is not served again");
        const second = await open(hooks.reopen(store));
        assert.deepEqual(await entryIds(await readBack(second, id)), ["n1", "n2"]);
        assert.equal(await tokenOf(second, id, "after a restart"), before, "the occupant is the row's: a commit onto an existing row keeps it");
    });
    faceRun("[transfer] a commit onto an id with no row creates it: the committer is its owner (null = anonymous) and it is a new occupant", ["logTransfer", "headOf"], async (store) => {
        const [owned, anonymous] = [freshId(), freshId()];
        const a = await commitLog(store, owned, { owner: "kit-alice" }, [userEntry("e1", null)]);
        assert.equal(a.outcome, "replaced");
        assert.equal(a.head.owner, "kit-alice");
        const token = await tokenOf(store, owned, "a row a commit created");
        assert.equal(a.head.incarnation, token);
        const b = await commitLog(store, anonymous, { owner: null }, [userEntry("e1", null)]);
        assert.equal(b.head.owner, null);
        assert.notEqual(await tokenOf(store, anonymous, "a second created row"), token, "two rows are two occupants");
    });
    faceRun("[transfer] a commit lands only on the committer's row: another owner's, an anonymous row by a principal, an owned row by an anonymous commit — each refused conflict, decide never asked, nothing written", ["logTransfer", "ownership"], async (store) => {
        const owned = freshId();
        await store.register(owned, "kit-alice");
        await append((await store.acquire(owned)).session, userEntry("a1", null));
        const anonymous = freshId();
        await append((await store.acquire(anonymous)).session, userEntry("z1", null));
        for (const [id, owner, keep] of [[owned, "kit-bob", "a1"], [owned, null, "a1"], [anonymous, "kit-bob", "z1"]]) {
            for (const verdict of ["replace", "keep"]) {
                let asked = false;
                await rejectsWithConflict(() => commitLog(store, id, { owner, decide: () => {
                        asked = true;
                        return verdict;
                    } }, [userEntry("x1", null)]), `a ${verdict} commit by ${String(owner)} onto another's row`);
                assert.equal(asked, false, "the relation is not judged for a row the committer may not write");
                assert.deepEqual(await store.logTransfer.listEntryIds(id), [keep], "a refused commit writes nothing");
            }
        }
        assert.equal(await ownerOf(store, owned, "the owned row"), "kit-alice");
        assert.equal(await ownerOf(store, anonymous, "the anonymous row"), null);
    });
    faceRun("[transfer] a row another writer creates while a staging is open: the commit is refused conflict and that row stands — and a row of the committer's own that appears is shown to decide", ["logTransfer", "ownership"], async (store) => {
        const id = freshId();
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("x1", null)]);
        await store.register(id, "kit-bob");
        await rejectsWithConflict(() => staging.commit({ owner: "kit-alice", decide: () => "replace" }), "a commit onto a row another principal created after the staging opened");
        assert.equal(await ownerOf(store, id, "the other writer's row"), "kit-bob", "the commit took nobody's row");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), []);
        const mine = freshId();
        const staged = store.logTransfer.beginReplace(mine);
        await staged.append([userEntry("x1", null)]);
        await store.register(mine, "kit-alice");
        let seen;
        await rejectsWithCode(() => staged.commit({ owner: "kit-alice", decide: (v) => { seen = v.current; throw new SessionError("conflict", "the committer expected no row"); } }), "conflict", "a committer refusing a row it did not expect");
        assert.deepEqual(seen, [], "decide sees the row as it stands now — present, with its (empty) log, not the absence the staging began on");
        assert.deepEqual(await store.logTransfer.listEntryIds(mine), []);
    });
    faceRun("[transfer] a placed row's log is not replaced: the commit is refused placement_refused and the transcript stays", ["logTransfer", "placements"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id, { placement: placementFor() })).session, userEntry("p1", null));
        await rejectsWithCode(() => commitLog(store, id, { owner: null }, [userEntry("x1", null)]), "placement_refused", "a commit onto a placed row");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["p1"]);
    });
    faceRun("[transfer] every staged entry passes the import gate: a refused batch ends the staging, a staged log that does not close is refused at the commit, and either way nothing is written", ["logTransfer", "headOf"], async (store) => {
        const id = freshId();
        const broken = store.logTransfer.beginReplace(id);
        await rejectsWithCode(() => broken.append([userEntry("e2", "missing-parent")]), "invalid_session", "a batch whose entry's parent never appears");
        await rejectsWithCode(() => broken.append([userEntry("e1", null)]), "invalid_session", "a staging after a refused batch");
        await rejectsWithCode(() => broken.commit({ owner: null, decide: () => "replace" }), "invalid_session", "a commit of a refused staging");
        const tworoots = store.logTransfer.beginReplace(id);
        let early;
        try {
            await tworoots.append([userEntry("r1", null), userEntry("r2", null)]);
        }
        catch (err) {
            early = err;
        }
        if (early !== undefined)
            assert.equal(readMember(early, "code"), "invalid_session", "a two-root batch refused at append is refused invalid_session");
        await rejectsWithCode(() => tworoots.commit({ owner: null, decide: () => "replace" }), "invalid_session", "a staged log with two roots");
        assert.equal(await headOf(store, id), undefined, "no row was created");
    });
    faceRun("[transfer] before its commit a staging is invisible; decide reads both sides, and its throw writes nothing; an abort writes nothing and ends the staging; a decide answer outside the two is refused", ["logTransfer", "ownership"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        await append((await store.acquire(id)).session, userEntry("old1", null));
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("n1", null)]);
        await staging.append([assistantEntry("n2", "n1")]);
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["old1"], "nothing staged is read before the commit");
        assert.deepEqual(await entryIds((await store.acquire(id)).session), ["old1"]);
        const boom = new Error("the committer's own refusal");
        let reads = [];
        const thrown = await thrownBy(() => staging.commit({
            owner: "kit-alice",
            decide: async (v) => {
                assert.deepEqual(v.current, ["old1"]);
                assert.deepEqual(v.staged, ["n1", "n2"]);
                const current = await v.read("current", ["old1"]);
                reads = [...current, ...(await v.read("staged", ["n2", "n1"]))].map((e) => e.id);
                firstTextBlock(current[0]).text = "written by decide";
                throw boom;
            },
        }), "a commit whose decide throws");
        assert.equal(thrown, boom, "the commit rejects with decide's own throw");
        assert.deepEqual(reads, ["old1", "n2", "n1"], "read answers the entries asked for, in the order asked");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["old1"]);
        const kept = (await (await store.acquire(id)).session.getStorage().getEntries())[0];
        assert.equal(firstTextBlock(kept).text, "t-old1", "an entry decide read is a copy: writing to it changes no log");
        await rejectsWithCode(() => staging.commit({ owner: "kit-alice", decide: () => "replace" }), "invalid_session", "a second commit of one staging");
        const aborted = store.logTransfer.beginReplace(id);
        await aborted.append([userEntry("n1", null)]);
        await aborted.abort();
        await aborted.abort();
        await rejectsWithCode(() => aborted.commit({ owner: "kit-alice", decide: () => "replace" }), "invalid_session", "a commit after an abort");
        const odd = store.logTransfer.beginReplace(id);
        await odd.append([userEntry("n1", null)]);
        await rejectsWithCode(() => Reflect.apply(odd.commit, odd, [{ owner: "kit-alice", decide: () => "restamp" }]), "config.invalid_argument", "a decide answer outside replace / keep");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["old1"], "nothing was written by any of them");
    });
    faceRun("[transfer] decide answering keep leaves the log as it is and answers the row's head; keep for an id with no row is refused and creates nothing", ["logTransfer", "ownership"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        await append((await store.acquire(id)).session, userEntry("e1", null));
        const done = await commitLog(store, id, { owner: "kit-alice", decide: () => "keep" }, [userEntry("e1", null)]);
        assert.equal(done.outcome, "kept");
        assert.deepEqual(done.head, await headOf(store, id));
        assert.equal(done.head.leafId, "e1");
        const absent = freshId();
        await rejectsWithCode(() => commitLog(store, absent, { owner: null, decide: () => "keep" }, [userEntry("e1", null)]), "invalid_session", "keep for an id with no row");
        assert.equal(await headOf(store, absent), undefined);
    });
    faceRun("[transfer] a commit through another instance: this instance's cached view of the replaced log is not served again", ["logTransfer", "ownership", "replica"], async (store, open) => {
        const id = freshId();
        const other = await open(hooks.replica(store));
        await store.register(id, "kit-alice");
        await append((await store.acquire(id)).session, userEntry("old1", null));
        await commitLog(other, id, { owner: "kit-alice" }, [userEntry("n1", null), assistantEntry("n2", "n1")]);
        assert.deepEqual(await entryIds((await store.acquire(id)).session), ["n1", "n2"], "the occupant is the same, the log is not — a view of the old log is a view of a log the row no longer holds");
    });
    faceRun("[transfer] a write through another instance while decide weighs the destination (an append to it): the commit is refused conflict, nothing written, and that write stands", ["logTransfer", "ownership", "replica"], async (store, open) => {
        const id = freshId();
        const other = await open(hooks.replica(store));
        await store.register(id, "kit-alice");
        await append((await store.acquire(id)).session, userEntry("e1", null));
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("n1", null)]);
        const decide = async () => {
            await append((await other.acquire(id)).session, assistantEntry("e2", "e1"));
            return "replace";
        };
        await rejectsWithConflict(() => staging.commit({ owner: "kit-alice", decide }), "a commit whose destination another instance wrote while decide weighed it");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["e1", "e2"], "the other instance's write stands, and nothing of the staged log was written");
    });
    faceRun("[transfer] a commit naming the row it judged (expect: { row: head }, the head its gate read) lands only on that row: the same row takes a replace and a keep and keeps its occupant, the leaf not judged; the id deleted and created again under the same (anonymous) owner (a replace or a keep), a row with no occupant named against a row holding one, and the id deleted — each refused conflict, decide never asked, nothing written", ["logTransfer"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id)).session, userEntry("old1", null));
        const judged = await gateHead(store, id, "the row the committer judged");
        const same = await commitLog(store, id, { owner: null, expect: { row: judged } }, [userEntry("n1", null)]);
        assert.equal(same.outcome, "replaced");
        assert.equal(same.head.incarnation, judged.incarnation, "the commit landed on the row it named, and the row keeps its occupant");
        const kept = await commitLog(store, id, { owner: null, expect: { row: judged }, decide: () => "keep" }, [userEntry("n1", null)]);
        assert.equal(kept.outcome, "kept", "the head's leaf moved with the replace, and the leaf is not what the row expectation judges");
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("x1", null)]);
        await store.acquire(id);
        await hooks.deleteSession(store, id);
        await append((await store.acquire(id)).session, userEntry("y1", null));
        const now = await gateHead(store, id, "the row created again under the id");
        assert.notEqual(now.incarnation, judged.incarnation, "a row created again under the id is another occupant");
        let asked = false;
        const decide = (verdict) => () => {
            asked = true;
            return verdict;
        };
        await rejectsWithConflict(() => staging.commit({ owner: null, expect: { row: judged }, decide: decide("replace") }), "a commit naming the row the id held before it was deleted and created again");
        await rejectsWithConflict(() => commitLog(store, id, { owner: null, expect: { row: judged }, decide: decide("keep") }, [userEntry("y1", null)]), "a keep naming the row the id held before it was deleted and created again");
        await rejectsWithConflict(() => commitLog(store, id, { owner: null, expect: { row: { owner: null } }, decide: decide("replace") }, [userEntry("z1", null)]), "a commit expecting a row with no occupant token, onto a row holding one");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["y1"], "nothing of a refused commit landed on the new occupant");
        assert.equal(await tokenOf(store, id, "after the refused commits"), now.incarnation, "the new occupant's row stands as it was");
        await store.acquire(id);
        await hooks.deleteSession(store, id);
        await rejectsWithConflict(() => commitLog(store, id, { owner: null, expect: { row: now }, decide: decide("replace") }, [userEntry("z1", null)]), "a commit naming a row that was deleted");
        assert.equal(asked, false, "the relation is never judged for a row that is not the one the committer judged");
        assert.equal(await headOf(store, id), undefined, "a refused commit creates no row");
    });
    faceRun("[transfer] a commit naming no row (expect: { row: null }, its gate read none) lands only where the id still has none: it creates the row; a row created under the id since — the committer's own included — and a row that was there all along refuse it conflict, decide never asked, and that row stands", ["logTransfer"], async (store) => {
        const fresh = freshId();
        const created = await commitLog(store, fresh, { owner: null, expect: { row: null } }, [userEntry("c1", null)]);
        assert.equal(created.outcome, "replaced");
        assert.equal((await gateHead(store, fresh, "the row the commit created")).owner, null);
        const id = freshId();
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("x1", null)]);
        await store.acquire(id);
        let asked = false;
        const decide = () => {
            asked = true;
            return "replace";
        };
        await rejectsWithConflict(() => staging.commit({ owner: null, expect: { row: null }, decide }), "a commit expecting no row, onto a row of the committer's own created since its gate read none");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), [], "the row created since stands as it was");
        await rejectsWithConflict(() => commitLog(store, fresh, { owner: null, expect: { row: null }, decide }, [userEntry("z1", null)]), "a commit expecting no row, onto a row that is there");
        assert.deepEqual(await store.logTransfer.listEntryIds(fresh), ["c1"]);
        assert.equal(asked, false, "the relation is never judged for a row the committer did not expect");
    });
    faceRun("[transfer] a commit naming the log its committer judged (expect.log, the log's mark as read) lands only on that log: an append since refuses it conflict, decide never asked, and the append stands; the mark read again lands", ["logTransfer"], async (store) => {
        const id = freshId();
        const held = (await store.acquire(id)).session;
        await append(held, userEntry("e1", null));
        const judged = { row: await gateHead(store, id, "the row the committer judged"), log: logMarkOf(await store.logTransfer.listEntryIds(id)) };
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("s1", null)]);
        await append(held, assistantEntry("e2", "e1"));
        let asked = false;
        const decide = () => {
            asked = true;
            return "replace";
        };
        await rejectsWithConflict(() => staging.commit({ owner: null, expect: judged, decide }), "a commit naming the log as its gate read it, onto that log appended since");
        assert.equal(asked, false);
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["e1", "e2"], "the append stands, and nothing of the staged log was written");
        const again = { row: await gateHead(store, id, "the row read again"), log: logMarkOf(await store.logTransfer.listEntryIds(id)) };
        const done = await commitLog(store, id, { owner: null, expect: again }, [userEntry("s1", null)]);
        assert.equal(done.outcome, "replaced");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["s1"]);
    });
    faceRun("[transfer] the write law comes before the expected row: a placed row is refused placement_refused whatever row the commit names", ["logTransfer", "placements"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id, { placement: placementFor() })).session, userEntry("p1", null));
        await rejectsWithCode(() => commitLog(store, id, { owner: null, expect: { row: { owner: null, incarnation: "kit-not-its-occupant" } } }, [userEntry("x1", null)]), "placement_refused", "a commit naming another occupant onto a placed row");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["p1"]);
    });
    faceRun("[transfer] the id deleted and created again through another instance while decide weighs it: a commit naming the row it judged is refused conflict and nothing lands on the new occupant — the row judged is the one the write lands on", ["logTransfer", "replica"], async (store, open) => {
        const id = freshId();
        const other = await open(hooks.replica(store));
        await store.acquire(id);
        const judged = await gateHead(store, id, "the row the committer judged");
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("s1", null)]);
        const decide = async () => {
            await other.acquire(id);
            await hooks.deleteSession(other, id);
            await other.acquire(id);
            return "replace";
        };
        await rejectsWithConflict(() => staging.commit({ owner: null, expect: { row: judged }, decide }), "a commit whose row another instance deleted and created again while decide weighed it");
        assert.notEqual(await tokenOf(other, id, "the row created again"), judged.incarnation);
        assert.deepEqual(await other.logTransfer.listEntryIds(id), [], "the new occupant's row holds nothing of the staged log");
    });
    faceRun("[transfer] a commit's row expectation is read as the commit's other members are: absent (or undefined) names none — a commit onto a row created again under the id lands, as it always did; a value not of the shape (not an object, a row neither the row nor null, an owner or occupant of the wrong kind, a log mark that is none) is refused config.invalid_argument, ends the staging and writes nothing", ["logTransfer"], async (store) => {
        const id = freshId();
        await store.acquire(id);
        const before = await gateHead(store, id, "the first occupant");
        await hooks.deleteSession(store, id);
        await store.acquire(id);
        const now = await tokenOf(store, id, "the row created again");
        for (const commit of [{ owner: null }, { owner: null, expect: undefined }]) {
            const done = await commitLog(store, id, commit, [userEntry("n1", null)]);
            assert.equal(done.outcome, "replaced", "no expectation: the commit lands on whichever row the id holds");
            assert.equal(done.head.incarnation, now);
        }
        assert.notEqual(now, before.incarnation);
        const shapes = [
            ["null", null],
            ["a string", "kit-head"],
            ["a number", 7],
            ["no row member", {}],
            ["a row that is a string", { row: "kit-head" }],
            ["an owner that is a number", { row: { owner: 7, incarnation: now } }],
            ["no owner", { row: { incarnation: now } }],
            ["an occupant that is a number", { row: { owner: null, incarnation: 7 } }],
            ["a log mark of a negative length", { row: { owner: null, incarnation: now }, log: { length: -1, lastEntryId: null } }],
        ];
        for (const [what, bad] of shapes) {
            const staging = store.logTransfer.beginReplace(id);
            await staging.append([userEntry("b1", null)]);
            await rejectsWithCode(() => Reflect.apply(staging.commit, staging, [{ owner: null, decide: () => "replace", expect: bad }]), "config.invalid_argument", `an expectation of ${what}`);
            await rejectsWithCode(() => staging.commit({ owner: null, decide: () => "replace" }), "invalid_session", "a staging after a commit refused for its expectation (the first commit call ends it)");
        }
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["n1"], "a refused expectation writes nothing");
    });
    for (const [what, onAbsentId, build] of READER_ONLY_SHAPES) {
        faceRun(`[transfer] a commit's row expectation is read by the root's strict reading of it (readRowExpectationMember), and what that reading refuses is a bad argument: ${what} — refused config.invalid_argument, the staging ended, nothing written`, ["logTransfer"], async (store) => {
            const id = freshId();
            await append((await store.acquire(id)).session, userEntry("e1", null));
            const head = await gateHead(store, id, "the row the committer judged");
            const target = onAbsentId ? freshId() : id;
            const staging = store.logTransfer.beginReplace(target);
            await staging.append([userEntry("b1", null)]);
            await rejectsWithCode(() => Reflect.apply(staging.commit, staging, [{ owner: null, decide: () => "replace", expect: build(head, id) }]), "config.invalid_argument", `an expectation of ${what}`);
            await rejectsWithCode(() => staging.commit({ owner: null, decide: () => "replace" }), "invalid_session", "a staging after a commit refused for its expectation (the first commit call ends it)");
            assert.deepEqual(await store.logTransfer.listEntryIds(id), ["e1"], "a refused expectation writes nothing");
            if (onAbsentId)
                assert.equal(await headOf(store, target), undefined, "a refused expectation creates no row");
        });
    }
    faceRun("[transfer] a row written before occupant tokens (the tokenlessRow hook): a token named against it is refused conflict and nothing is written; a commit naming it as its gate read it ({ row: head }) lands and the row keeps no token", ["logTransfer", "tokenlessRow"], async (store) => {
        const id = freshId();
        await hooks.tokenlessRow(store, id);
        const head = await gateHead(store, id, "the row written before tokens");
        const before = await store.logTransfer.listEntryIds(id);
        await rejectsWithConflict(() => commitLog(store, id, { owner: head.owner, expect: { row: { owner: head.owner, incarnation: "kit-not-its-occupant" } } }, [userEntry("w1", null)]), "a commit naming a token, onto a row that holds none");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), before, "a refused commit writes nothing");
        const done = await commitLog(store, id, { owner: head.owner, expect: { row: head } }, [userEntry("l1", null)]);
        assert.equal(done.outcome, "replaced", "the head the gate read, passed as it came, names the row");
        assert.equal(done.head.incarnation, undefined, "a commit onto an existing row keeps its occupant cell: no token is invented");
        assert.deepEqual(await store.logTransfer.listEntryIds(id), ["l1"]);
    });
    faceRun("[transfer] two transfers onto one row, each naming the row it judged: neither lands on another occupant — each is replaced keeping it or refused conflict, at least one lands, and the row holds one staged log whole", ["logTransfer"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id)).session, userEntry("old1", null));
        const judged = await gateHead(store, id, "the row both committers judged");
        const a = store.logTransfer.beginReplace(id);
        await a.append([userEntry("a1", null), assistantEntry("a2", "a1")]);
        const b = store.logTransfer.beginReplace(id);
        await b.append([userEntry("b1", null)]);
        const settled = await Promise.allSettled([a, b].map((s) => s.commit({ owner: null, expect: { row: judged }, decide: () => "replace" })));
        for (const s of settled) {
            if (s.status === "fulfilled")
                assert.equal(s.value.head.incarnation, judged.incarnation, "a commit that landed kept the occupant it named");
            else
                assert.equal(conflictMiss(s.reason), undefined, `a commit that did not land is the engine's conflict: ${conflictMiss(s.reason)}`);
        }
        assert.ok(settled.some((s) => s.status === "fulfilled"), "two commits onto the row both judged: at least one lands");
        const log = await store.logTransfer.listEntryIds(id);
        const holds = (want) => log !== null && log.length === want.length && want.every((entryId, i) => log[i] === entryId);
        assert.ok(holds(["a1", "a2"]) || holds(["b1"]), `the row holds one staged log whole (a1 a2, or b1), never a mix or the old log, got ${describeRejectedValue(log)}`);
        assert.equal(await tokenOf(store, id, "after both commits"), judged.incarnation);
    });
    faceRun("[transfer] a commit naming its row racing the id's deletion and creation again: whatever the order, the staged log never lands on a new occupant — when the deletion took the row, the commit landed before it (on the row it named) or was refused conflict; when it took nothing, the commit lands on the row it named", ["logTransfer"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id)).session, userEntry("old1", null));
        const judged = await gateHead(store, id, "the row the committer judged");
        const staging = store.logTransfer.beginReplace(id);
        await staging.append([userEntry("s1", null)]);
        const recreate = (async () => {
            await store.acquire(id);
            await hooks.deleteSession(store, id);
            await store.acquire(id);
        })();
        const [commit] = await Promise.allSettled([staging.commit({ owner: null, expect: { row: judged }, decide: () => "replace" }), recreate]);
        await recreate;
        const now = await tokenOf(store, id, "the row after the race");
        const log = await store.logTransfer.listEntryIds(id);
        if (now !== judged.incarnation) {
            if (commit.status === "fulfilled")
                assert.equal(commit.value.head.incarnation, judged.incarnation, "a commit that landed, landed on the row it named");
            else
                assert.equal(conflictMiss(commit.reason), undefined, `a commit that did not land is the engine's conflict: ${conflictMiss(commit.reason)}`);
            assert.ok(log !== null && !log.includes("s1"), "the new occupant's row holds nothing of the staged log");
        }
        else {
            assert.equal(commit.status, "fulfilled", `the row the commit named still stands, so the commit lands: ${commit.status === "rejected" ? describeRejectedValue(readMember(commit.reason, "code")) : ""}`);
            assert.deepEqual(log, ["s1"], "the staged log is on the row the commit named");
        }
    });
    faceRun("[delete] only the owner's delete deletes: another owner's or an anonymous guard on an owned row, and an owner's guard on an anonymous row, answer false and leave the row; the right guard answers true, the id is gone, a repeat answers false, and a later create is a new occupant", ["delete", "ownership"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        await append((await store.acquire(id)).session, userEntry("e1", null));
        const before = await tokenOf(store, id, "the owned row");
        assert.equal(await store.delete(id, { owner: "kit-bob" }), false);
        assert.equal(await store.delete(id, { owner: null }), false, "null is no wildcard: it deletes only an anonymous row");
        assert.equal(await ownerOf(store, id, "after two refused deletes"), "kit-alice");
        assert.equal(await store.delete(id, { owner: "kit-alice" }), true);
        assert.equal(await headOf(store, id), undefined, "a deleted row answers nothing");
        assert.equal(await store.delete(id, { owner: "kit-alice" }), false, "a repeat is harmless");
        assert.deepEqual(await entryIds((await store.acquire(id)).session), [], "the deleted log is not served under the id again");
        assert.notEqual(await tokenOf(store, id, "the id created again"), before, "a later create under the id is a new occupant");
        const anonymous = freshId();
        await append((await store.acquire(anonymous)).session, userEntry("z1", null));
        assert.equal(await store.delete(anonymous, { owner: "kit-alice" }), false);
        assert.equal(await store.delete(anonymous, { owner: null }), true);
        assert.equal(await store.delete(freshId(), { owner: null }), false, "no row ⇒ false");
    });
    faceRun("[delete] a guard that names no owner is refused before anything is deleted: an absent owner, a blank one, a non-object guard", ["delete", "ownership"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        for (const guard of [{}, { owner: undefined }, { owner: "" }, { owner: " " }, { owner: 7 }, null, "kit-alice"]) {
            await thrownBy(() => Reflect.apply(store.delete, store, [id, guard]), `delete with guard ${JSON.stringify(guard)}`);
        }
        assert.equal(await ownerOf(store, id, "after the refused deletes"), "kit-alice");
    });
    faceRun("[delete] the occupant form { row: { owner, incarnation } } deletes only the occupant a read answered: the row deleted and created again under the id by the same owner is not deleted by the first occupant's guard, and is by its own; row null, a log mark and a guard naming both forms are refused", ["delete", "ownership"], async (store) => {
        const id = freshId();
        await store.register(id, "kit-alice");
        const first = await tokenOf(store, id, "the first occupant");
        assert.equal(await store.delete(id, { owner: "kit-alice" }), true);
        await store.register(id, "kit-alice");
        const second = await tokenOf(store, id, "the id created again by the same owner");
        assert.notEqual(second, first, "a later create under the id is a new occupant");
        assert.equal(await store.delete(id, { row: { owner: "kit-alice", incarnation: first } }), false, "the first occupant's guard does not take the second");
        assert.equal(await store.delete(id, { row: { owner: "kit-bob", incarnation: second } }), false, "another owner's occupant guard deletes nothing");
        assert.equal(await ownerOf(store, id, "after two refused occupant deletes"), "kit-alice");
        for (const guard of [{ row: null }, { row: { owner: "kit-alice", incarnation: second }, log: { length: 0, lastEntryId: null } }, { owner: "kit-alice", row: { owner: "kit-alice", incarnation: second } }]) {
            await thrownBy(() => Reflect.apply(store.delete, store, [id, guard]), `delete with guard ${JSON.stringify(guard)}`);
        }
        assert.equal(await store.delete(id, { row: { owner: "kit-alice", incarnation: second } }), true, "its own occupant's guard deletes it");
        assert.equal(await headOf(store, id), undefined, "the row is gone");
    });
    faceRun("[delete] a row whose head reads and whose open is refused corrupt_session (the openRefusedRow hook) is judged on its head alone: another owner's guard answers false, its owner's answers true and the id answers nothing; the operator's delete, where present, answers false for it first (its head reads)", ["delete", "ownership", "openRefusedRow"], async (store) => {
        const id = freshId();
        await hooks.openRefusedRow(store, id, "kit-alice");
        const opened = await store.acquire(id).then(() => undefined, (err) => err);
        assert.equal(readMember(opened, "code"), "corrupt_session", "the hook's row: its open is refused corrupt_session");
        assert.equal(await ownerOf(store, id, "the hook's row"), "kit-alice", "the hook's row: its head reads");
        if (typeof store.deleteUnreadable === "function")
            assert.equal(await store.deleteUnreadable(id), false, "the head reads: not the operator's");
        assert.equal(await store.delete(id, { owner: "kit-bob" }), false, "another owner's guard deletes nothing");
        assert.equal(await store.delete(id, { owner: "kit-alice" }), true, "its owner's delete takes it: a deletion never reads the log");
        assert.equal(await headOf(store, id), undefined, "the row is gone");
    });
    faceRun("[delete] a placed row is not deleted here: its deletion is release's", ["delete", "placements"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id, { placement: placementFor() })).session, userEntry("p1", null));
        assert.equal(await store.delete(id, { owner: null }), false);
        assert.ok((await headOf(store, id)) !== undefined, "the placed row stands");
    });
    faceRun("[deleteUnreadable] a row that reads is not unreadable: an anonymous row (and an owned one, where the store keeps owners) and an id with no row answer false and delete nothing", ["deleteUnreadable"], async (store) => {
        const anonymous = freshId();
        await append((await store.acquire(anonymous)).session, userEntry("u1", null));
        assert.equal(await store.deleteUnreadable(anonymous), false, "an anonymous row reads: it is not unreadable");
        assert.ok((await headOf(store, anonymous)) !== undefined, "the anonymous row stands");
        assert.deepEqual(await entryIds((await store.acquire(anonymous)).session), ["u1"], "and keeps its log");
        if (hasOwnership(store)) {
            const owned = freshId();
            await store.register(owned, "kit-alice");
            assert.equal(await store.deleteUnreadable(owned), false, "an owned row reads: it is not unreadable");
            assert.equal(await ownerOf(store, owned, "after the refused operator delete"), "kit-alice");
        }
        const none = freshId();
        assert.equal(await store.deleteUnreadable(none), false, "no row ⇒ false");
        assert.equal(await headOf(store, none), undefined, "and nothing is created under the id");
    });
    faceRun("[readRow] a read sweeps nothing: a session past the store's idle window is still held, and still reads, after another session's read", ["readRow", "idleClock"], async (store) => {
        const idle = freshId();
        const read = freshId();
        await append((await store.acquire(idle)).session, userEntry("i1", null));
        await append((await store.acquire(read)).session, userEntry("r1", null));
        await hooks.ageIdle(store, idle);
        const agedAt = await hooks.idleClockOf(store, idle);
        assert.ok(agedAt !== undefined, "the aged session is held before the read");
        assert.ok((await store.readRow(read)) !== undefined, "the read session's row is answered");
        assert.equal(await hooks.idleClockOf(store, idle), agedAt, "the idle session is still held, its clock where it was: the read evicted nothing");
        assert.deepEqual((await store.readRow(idle))?.entries.map((e) => e.id), ["i1"], "and its row still reads, its log whole: the read deleted nothing");
    });
    faceRun("[readRow] a read is no activity: the read session's idle clock does not move, nor its listed time", ["readRow", "idleClock"], async (store) => {
        const id = freshId();
        await append((await store.acquire(id)).session, userEntry("r1", null));
        await hooks.ageIdle(store, id);
        const before = await hooks.idleClockOf(store, id);
        const listedBefore = typeof store.list === "function" ? rowOf(await store.list(), id)?.lastActiveAt : undefined;
        assert.ok(before !== undefined, "the session is held before the read");
        assert.ok((await store.readRow(id)) !== undefined, "the row is answered");
        assert.equal(await hooks.idleClockOf(store, id), before, "the read moved the session's idle clock (or evicted it)");
        if (typeof store.list === "function")
            assert.equal(rowOf(await store.list(), id)?.lastActiveAt, listedBefore, "the read moved the session's listed time");
    });
    faceRun("[readRow] a read writes nothing: no row, entry, listed time or transcript file appears or changes — an id with no row included", ["readRow"], async (store) => {
        const id = freshId();
        const none = freshId();
        await append((await store.acquire(id)).session, userEntry("r1", null));
        const dir = store.transcriptDirectory;
        const files = () => (typeof dir === "string" ? readdirSync(dir, { recursive: true }).map(String).sort().map((f) => `${f}:${statSync(join(dir, f)).size}:${statSync(join(dir, f)).mtimeMs}`) : []);
        const listed = async () => (typeof store.list === "function" ? (await store.list()).map((r) => `${r.sessionId}:${r.lastActiveAt}`).sort() : []);
        const head = typeof store.headOf === "function" ? await store.headOf(id) : undefined;
        const [filesBefore, listedBefore] = [files(), await listed()];
        await store.readRow(id);
        assert.equal(await store.readRow(none), undefined, "an id with no row answers no row");
        assert.deepEqual(files(), filesBefore, "no transcript file appeared or changed");
        assert.deepEqual(await listed(), listedBefore, "no listed row appeared or moved");
        if (typeof store.headOf === "function") {
            assert.deepEqual(await store.headOf(id), head, "the read row's head is the one it had");
            assert.equal(await store.headOf(none), undefined, "nothing is created under an id with no row");
        }
    });
    faceRun("[readRow] an id with no row resolves undefined — a definite no — and a row resolves its metadata, head and whole log of one generation", ["readRow"], async (store) => {
        const none = freshId();
        assert.equal(await store.readRow(none), undefined, "no row ⇒ undefined, never a rejection");
        const id = freshId();
        const { session } = await store.acquire(id);
        await append(session, userEntry("r1", null));
        await append(session, assistantEntry("r2", "r1"));
        const row = await store.readRow(id);
        assert.ok(row !== undefined, "a row ⇒ answered");
        assert.equal(row.metadata.id, id, "the row's own metadata");
        assert.deepEqual(row.entries.map((e) => e.id), ["r1", "r2"], "its whole log, oldest first");
        assert.equal(row.head.leafId, "r2", "its head names the leaf of that log");
        assert.equal(row.head.incarnation, (await session.getMetadata()).incarnation, "and the occupant the store handed out");
    });
    faceRun("[readRow] a row that is there and cannot be read rejects coded (corrupt_session) — never the undefined of no row", ["readRow", "unreadableRow"], async (store) => {
        const id = freshId();
        await hooks.unreadableRow(store, id);
        const answer = await store.readRow(id).then((row) => ({ resolved: row }), (err) => ({ rejected: readMember(err, "code") }));
        assert.deepEqual(answer, { rejected: "corrupt_session" }, "a row whose header cannot be read is a failed read, told apart from no row");
    });
    await settle();
}
function firstTextBlock(entry) {
    const content = entry.type === "message" ? entry.message.content : undefined;
    const block = Array.isArray(content) ? content[0] : undefined;
    assert.ok(block !== undefined && typeof block.text === "string", "a kit user entry carries one text block");
    return block;
}
async function streamIds(t, sessionId, opts) {
    const stream = await t.exportStream(sessionId, opts);
    assert.ok(stream !== null, "the row exists, so exportStream must answer a stream");
    const ids = [];
    for await (const e of stream)
        ids.push(e.id);
    return ids;
}
async function commitLog(store, sessionId, commit, entries) {
    const staging = store.logTransfer.beginReplace(sessionId);
    await staging.append(entries);
    return staging.commit({ owner: commit.owner, decide: commit.decide ?? (() => "replace"), ...(Object.hasOwn(commit, "expect") ? { expect: commit.expect } : {}) });
}
class KitRowObject {
    owner;
    incarnation;
    constructor(owner, incarnation) {
        this.owner = owner;
        this.incarnation = incarnation;
    }
}
const READER_ONLY_SHAPES = [
    ["a row that is a class instance", false, (head) => ({ row: new KitRowObject(head.owner, head.incarnation) })],
    ["a row carrying a key the type has not", false, (head, sessionId) => ({ row: { ...head, sessionId } })],
    ["a row whose occupant its prototype supplies", false, (head) => ({ row: Object.assign(Object.create({ incarnation: head.incarnation }), { owner: head.owner }) })],
    [
        "a row whose occupant is an accessor that throws",
        false,
        (head) => ({
            row: {
                owner: head.owner,
                get incarnation() {
                    throw new Error("kit: the accessor was run");
                },
            },
        }),
    ],
    ["row null beside the mark of a log with entries (a row that is not there holds none)", true, () => ({ row: null, log: { length: 1, lastEntryId: "e1" } })],
];
function logMarkOf(ids) {
    assert.ok(ids !== null, "the row exists, so its log is listed");
    return { length: ids.length, lastEntryId: ids.length === 0 ? null : ids[ids.length - 1] };
}