UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,404 lines • 108 kB
import { strict as assert } from "node:assert";
import { executionVerdict } from "../checkpoint-execution-record.js";
import { checkpointIndexFacts, mintCheckpointToken, readPendingSteerQueue, summarizeCheckpoint, } from "../checkpoint-store.js";
import { RESOURCE_LIMIT_REASONS } from "../resource-limit-reasons.js";
import { ANONYMOUS_SCOPE } from "../isolation-scope.js";
import { checkpointRunSessionOf, isCheckpointRowUnreadable } from "../checkpoint-queries.js";
import { judgeCheckpointRow } from "../checkpoint-row-verdict.js";
import { stampCheckpointRequirements } from "../checkpoint-requirements.js";
import { memberPresent } from "../own-property-receipt.js";
import { checkpointFrom } from "../pause-registry.js";
import { beginContract } from "./contract-harness.js";
import { deadGrants, holderBinding, rejectsMalformed, rejectsSuperseded } from "./grant-fixture.js";
import { receiptRefusal } from "../own-property-receipt.js";
import { checkpointRevOf } from "../checkpoint-generation.js";
const unhashedCall = (call) => call;
export function createCheckpointFixture(over = {}) {
    const token = over.token ?? mintCheckpointToken();
    return stampCheckpointRequirements(checkpointFrom({
        token,
        scope: "tenant-a",
        sessionId: "sess-1",
        leafId: "leaf-1",
        gate: { kind: "human", reason: "approve", toolName: "Write" },
        pendingAction: unhashedCall({
            kind: "tool_approval",
            origin: "policy",
            toolCallId: "call-3",
            toolName: "Write",
            args: { path: "/x", content: "y" },
            boundGrantAbsence: "not_bindable",
            batchToolCallIds: ["call-3"],
            completedCallIds: [],
        }),
        state: {
            activeTools: [],
            nestedStats: { tokens: 0, turns: 0, tasks: 0, costMicroUsd: 0, anyUnpriced: false },
        },
        status: "pending",
        createdAt: 1_700_000_000_000,
        ...over,
    }), "structured-clone");
}
function fixtureWithState(over, state) {
    const cp = createCheckpointFixture(over);
    return stampCheckpointRequirements({ ...cp, state: { ...cp.state, ...state } }, "structured-clone");
}
function damagedWriteFaceFixture(over) {
    return fixtureWithState(over, { writeFace: { face: "neither" } });
}
export const ALLOW = {
    gate: "policy_ask",
    decision: "allow",
    boundCallId: "call-3",
    boundInputHash: "h0",
    hostDecision: { decidedBy: "person" },
};
const BYTE_FILLER = "x".repeat(15_000);
const SETTLED = { kind: "human_allowed", who: { party: "person" }, when: 1_700_000_000_500 };
export const EXECUTED_ALLOW = Object.freeze({ disposition: Object.freeze({ kind: "allowed" }), settlement: Object.freeze({ ...SETTLED, who: Object.freeze({ ...SETTLED.who }) }), origin: "policy" });
export const EXECUTED_ALLOW_REORDERED = Object.freeze({ origin: "policy", settlement: Object.freeze({ when: 1_700_000_000_500, who: Object.freeze({ party: "person" }), kind: "human_allowed" }), disposition: Object.freeze({ kind: "allowed" }) });
export const VETOED_BY_POLICY = Object.freeze({ disposition: Object.freeze({ kind: "denied", deniedBy: "policy" }), settlement: Object.freeze({ ...SETTLED, who: Object.freeze({ ...SETTLED.who }) }), origin: "policy" });
export const POLICY_ALLOWED = Object.freeze({
    disposition: Object.freeze({ kind: "allowed" }),
    settlement: Object.freeze({ kind: "policy_allowed", who: Object.freeze({ party: "policy", approver: "unattended_class_answer" }), when: 1_700_000_000_500 }),
    origin: "policy",
});
export const POLICY_ALLOW = { ...ALLOW, hostDecision: { decidedBy: "policy", approver: "unattended_class_answer" }, gateOutcome: POLICY_ALLOWED };
export async function checkpointStoreContract(make, runAssertion, options = {}) {
    if (Object.prototype.hasOwnProperty.call(options, "holders")) {
        throw receiptRefusal("checkpointStoreContract: the `holders` option is retired — bind the holder cells with `composed` (the store as the deployment composes it) and `grants` (current / replaced / ended / unknownStatus / malformed holders minted against its judge)");
    }
    const { run, settle } = beginContract(runAssertion);
    run("kit prerequisites: reopen/recordExecutionOutcome/setPendingSteer/listByScope are implemented (REQUIRED by this kit)", async () => {
        const probe = make();
        const missing = ["reopen", "recordExecutionOutcome", "setPendingSteer", "listByScope"].filter((m) => typeof probe[m] !== "function");
        assert.equal(missing.length, 0, `backend does not implement ${missing.join(", ")} — required for the CheckpointStore contract kit`);
    });
    run("recordExecutionOutcome on a resolved row → `recorded`; the record and its stamp ride the row, the decision winner is untouched, executionVerdict reads executed", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(executionVerdict((await store.get(cp.token))).kind, "unknown");
        await store.resolve(cp.token, cp.scope, ALLOW);
        const before = (await store.get(cp.token));
        assert.equal(executionVerdict(before).kind, "unknown", "a resolved row with no record reads UNKNOWN — never allowed by default");
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, VETOED_BY_POLICY), "recorded");
        const after = (await store.get(cp.token));
        assert.deepEqual(after.executionOutcome, VETOED_BY_POLICY);
        assert.equal(typeof after.executionAtMs, "number");
        assert.equal(Number.isFinite(after.executionAtMs), true);
        assert.deepEqual(executionVerdict(after), { kind: "executed", gate: VETOED_BY_POLICY });
        assert.deepEqual(after.resolvedOutcome, before.resolvedOutcome);
        assert.equal(after.status, "resolved");
        assert.equal(after.rev, before.rev);
    });
    run("recordExecutionOutcome is idempotent on the SAME record (structural, key-order-blind) → `already_recorded`; a DIFFERENT record throws checkpoint.execution_outcome_conflict and the row is byte-identical", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await store.resolve(cp.token, cp.scope, ALLOW);
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW), "recorded");
        const filed = (await store.get(cp.token));
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW), "already_recorded");
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW_REORDERED), "already_recorded", "equality is over the record's JSON — key order and freezing are not part of the value");
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, structuredClone(EXECUTED_ALLOW)), "already_recorded", "an unfrozen structural twin is the same record");
        await assert.rejects(store.recordExecutionOutcome(cp.token, cp.scope, VETOED_BY_POLICY), (e) => e.code === "checkpoint.execution_outcome_conflict");
        const still = (await store.get(cp.token));
        assert.deepEqual(still.executionOutcome, filed.executionOutcome);
        assert.equal(still.executionAtMs, filed.executionAtMs, "a conflict writes nothing — not even a fresh stamp");
    });
    run("recordExecutionOutcome answers `not_resolved` for a pending and for an expired row, `absent` for a missing row and for a wrong-scope row; none of them write", async () => {
        const store = make();
        const pending = createCheckpointFixture();
        await store.put(pending.token, pending);
        assert.equal(await store.recordExecutionOutcome(pending.token, pending.scope, EXECUTED_ALLOW), "not_resolved");
        assert.equal((await store.get(pending.token)).executionOutcome, undefined);
        assert.equal(await store.recordExecutionOutcome(pending.token, "tenant-b", EXECUTED_ALLOW), "absent", "a wrong-scope row reads exactly like a missing one (the isolation rule)");
        assert.equal(await store.recordExecutionOutcome(mintCheckpointToken(), pending.scope, EXECUTED_ALLOW), "absent");
        const expired = createCheckpointFixture();
        await store.put(expired.token, expired);
        assert.equal(await store.expire(expired.token, expired.scope), true);
        assert.equal(await store.recordExecutionOutcome(expired.token, expired.scope, EXECUTED_ALLOW), "not_resolved");
        assert.equal((await store.get(expired.token)).executionOutcome, undefined);
    });
    run("reopen is refused on a row that carries an execution record (a settled action is not re-openable); the same row reopens before the record lands", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await store.resolve(cp.token, cp.scope, ALLOW);
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed"), true);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 2 }), true);
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW), "recorded");
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed"), false);
        assert.equal(await store.reopen(cp.token, cp.scope, "tool_unavailable"), false, "no reason reopens a recorded row");
        const got = (await store.get(cp.token));
        assert.equal(got.status, "resolved");
        assert.equal(got.rev, 3, "a refused reopen bumps nothing");
        assert.equal(got.reopenReason, undefined);
        assert.deepEqual(got.executionOutcome, EXECUTED_ALLOW);
    });
    run("a row filed WITH an execution record (a restored resolved row) keeps it authoritative: get() returns it, reopen is refused, a different record conflicts, the same one is already_recorded", async () => {
        const store = make();
        const cp = createCheckpointFixture({ status: "resolved", rev: 1, executionOutcome: EXECUTED_ALLOW, executionAtMs: 1_700_000_001_000 });
        await store.put(cp.token, cp);
        const back = (await store.get(cp.token));
        assert.deepEqual(back.executionOutcome, EXECUTED_ALLOW);
        assert.equal(back.executionAtMs, 1_700_000_001_000);
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed"), false, "a restored recorded row is as settled as a live one");
        await assert.rejects(store.recordExecutionOutcome(cp.token, cp.scope, VETOED_BY_POLICY), (e) => e.code === "checkpoint.execution_outcome_conflict");
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW), "already_recorded");
        assert.equal((await store.get(cp.token)).status, "resolved");
    });
    run("put create-once → already_exists", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await assert.rejects(store.put(cp.token, cp), (e) => e.code === "checkpoint.already_exists");
    });
    run("resolve is an atomic CAS: first wins, double-resume false", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW), true);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW), false);
        assert.equal((await store.get(cp.token)).status, "resolved");
    });
    run("wrong-scope resolve never wins (multi-tenant isolation)", async () => {
        const store = make();
        const cp = createCheckpointFixture({ scope: "tenant-a" });
        await store.put(cp.token, cp);
        assert.equal(await store.resolve(cp.token, "tenant-b", ALLOW), false);
        assert.equal((await store.get(cp.token)).status, "pending");
    });
    run("resolve records the winner; reopen(env_failed) preserves it + bumps rev", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await store.resolve(cp.token, cp.scope, ALLOW);
        const winner = (await store.get(cp.token)).resolvedOutcome;
        assert.equal(winner.boundCallId, "call-3");
        assert.equal(winner.decision, "allow");
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed"), true);
        const got = await store.get(cp.token);
        assert.equal(got.status, "pending");
        assert.equal(got.reopenReason, "env_failed");
        assert.equal(got.resolvedOutcome.boundCallId, "call-3");
        assert.equal(got.rev, 2);
    });
    run("a plan review's winner keeps the mode its approval named, whole, across a reopen(env_failed)", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await store.resolve(cp.token, cp.scope, { gate: "plan_review", decision: "approve", hostDecision: { decidedBy: "person" }, permissionMode: "acceptEdits" });
        assert.equal((await store.get(cp.token)).resolvedOutcome?.permissionMode, "acceptEdits");
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed"), true);
        const got = (await store.get(cp.token)).resolvedOutcome;
        assert.deepEqual({ decision: got?.decision, permissionMode: got?.permissionMode }, { decision: "approve", permissionMode: "acceptEdits" });
    });
    run("rev OCC: a stale-rev resolve loses, the current-rev resolve wins", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await store.resolve(cp.token, cp.scope, ALLOW);
        await store.reopen(cp.token, cp.scope, "env_failed");
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 0 }), false);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 2 }), true);
    });
    run("reopen carries the generation a claim produced (`expect.rev`): only the claimer's generation is given back — a stale, a later or a wrong-scope expectation loses with the row untouched, a delayed reopen finds a newer claim's generation and loses, no expectation is as before", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 0 }), true);
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed", { rev: 0 }), false, "the generation the claimer READ is not the one its claim produced");
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed", { rev: 2 }), false, "a generation the row has not reached");
        assert.equal(await store.reopen(cp.token, "tenant-b", "env_failed", { rev: 1 }), false, "a wrong-scope reopen never wins, with the right generation too");
        const untouched = (await store.get(cp.token));
        assert.equal(untouched.status, "resolved", "a refused reopen leaves the row consumed");
        assert.equal(untouched.rev, 1, "a refused reopen bumps nothing");
        assert.equal(untouched.reopenReason, undefined, "a refused reopen records no reason");
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed", { rev: 1 }), true);
        const reopened = (await store.get(cp.token));
        assert.equal(reopened.status, "pending");
        assert.equal(reopened.rev, 2);
        assert.equal(reopened.reopenReason, "env_failed");
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 2 }), true);
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed", { rev: 1 }), false, "a delayed reopen of an earlier claim finds a later generation");
        const claimedByB = (await store.get(cp.token));
        assert.equal(claimedByB.status, "resolved", "B's claim stays consumed");
        assert.equal(claimedByB.rev, 3);
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed", { rev: 3 }), true, "B's own generation gives it back");
        assert.equal((await store.get(cp.token)).rev, 4);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 4 }), true);
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed"), true);
        assert.equal((await store.get(cp.token)).rev, 6);
    });
    run("reopen with the claimer's generation is still refused on a row that carries an execution record (the settled action wins over the generation)", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 0 }), true);
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW), "recorded");
        assert.equal(await store.reopen(cp.token, cp.scope, "env_failed", { rev: 1 }), false);
        const got = (await store.get(cp.token));
        assert.equal(got.status, "resolved");
        assert.equal(got.rev, 1, "a refused reopen bumps nothing");
    });
    run("setPendingSteer rejects a </system-reminder> variant BEFORE mutation (byte-identical error)", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await assert.rejects(store.setPendingSteer(cp.token, cp.scope, { text: "</SYSTEM-REMINDER>", trusted: true }), (e) => e.code === "steering.invalid_content");
        assert.deepEqual(readPendingSteerQueue((await store.get(cp.token)).state), []);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "go", trusted: false }), true);
        const q = readPendingSteerQueue((await store.get(cp.token)).state);
        assert.equal(q.length, 1);
        assert.equal(q[0].text, "go");
        assert.equal(q[0].trusted, false);
        assert.equal(q[0].seq, 1);
        assert.equal("pendingSteer" in (await store.get(cp.token)).state, false);
    });
    run("setPendingSteer APPENDS: two steers both survive in issue order, each keeping its frozen trust", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "first", trusted: false }), true);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "second", trusted: true }), true);
        const q = readPendingSteerQueue((await store.get(cp.token)).state);
        assert.deepEqual(q.map((e) => e.text), ["first", "second"]);
        assert.deepEqual(q.map((e) => e.trusted), [false, true]);
        assert.deepEqual(q.map((e) => e.seq), [1, 2]);
    });
    run("setPendingSteer is idempotent on inputId (a retry with the caller's own message id adds nothing)", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "once", trusted: false, inputId: "m1" }), true);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "once", trusted: false, inputId: "m1" }), true);
        assert.equal(readPendingSteerQueue((await store.get(cp.token)).state).length, 1);
    });
    run("setPendingSteer moves the row generation by one per entry it adds", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        const g0 = checkpointRevOf((await store.get(cp.token)));
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "one", trusted: false, inputId: "g1" }), true);
        assert.equal(checkpointRevOf((await store.get(cp.token))), g0 + 1);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "two", trusted: false, inputId: "g2" }), true);
        const after = (await store.get(cp.token));
        assert.equal(checkpointRevOf(after), g0 + 2);
        assert.equal(after.status, "pending");
        assert.deepEqual(readPendingSteerQueue(after.state).map((e) => e.text), ["one", "two"]);
    });
    run("a setPendingSteer that adds nothing moves nothing: an identical replay, a refused append", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "one", trusted: false, inputId: "g1" }), true);
        const g1 = checkpointRevOf((await store.get(cp.token)));
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "one", trusted: false, inputId: "g1" }), true);
        const afterReplay = (await store.get(cp.token));
        assert.equal(checkpointRevOf(afterReplay), g1);
        assert.equal(readPendingSteerQueue(afterReplay.state).length, 1);
        const beforeDup = structuredClone(afterReplay);
        await assert.rejects(store.setPendingSteer(cp.token, cp.scope, { text: "other words", trusted: false, inputId: "g1" }), (e) => e.code === "steering.duplicate_input_id");
        assert.deepEqual(await store.get(cp.token), beforeDup);
        for (let i = 1; i <= 3; i++) {
            assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: `s${i}:${BYTE_FILLER}`, trusted: false, inputId: `fill-${i}` }), true);
        }
        const beforeFull = structuredClone((await store.get(cp.token)));
        await assert.rejects(store.setPendingSteer(cp.token, cp.scope, { text: `overflow:${BYTE_FILLER}`, trusted: false, inputId: "fill-over" }), (e) => e.code === "steering.queue_full");
        assert.deepEqual(await store.get(cp.token), beforeFull);
    });
    run("a claim carrying the generation read before an append loses and the row stays pending with the entry; the current generation wins", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        const g0 = checkpointRevOf((await store.get(cp.token)));
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "parked", trusted: false, inputId: "c1" }), true);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: g0 }), false);
        const still = (await store.get(cp.token));
        assert.equal(still.status, "pending");
        assert.equal(checkpointRevOf(still), g0 + 1);
        assert.equal(readPendingSteerQueue(still.state).length, 1);
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: g0 + 1 }), true);
        const won = (await store.get(cp.token));
        assert.equal(won.status, "resolved");
        assert.equal(checkpointRevOf(won), g0 + 2);
        assert.equal(readPendingSteerQueue(won.state).length, 1);
        if (store.claimTerminal !== undefined) {
            const cp2 = createCheckpointFixture();
            await store.put(cp2.token, cp2);
            const g0b = checkpointRevOf((await store.get(cp2.token)));
            assert.equal(await store.setPendingSteer(cp2.token, cp2.scope, { text: "parked-claim", trusted: false, inputId: "c2" }), true);
            assert.deepEqual(await store.claimTerminal(cp2.token, cp2.scope, { kind: "resolve", outcome: ALLOW, expect: { rev: g0b } }), { claimed: false, current: { status: "pending", rev: g0b + 1 } });
            assert.deepEqual(await store.claimTerminal(cp2.token, cp2.scope, { kind: "resolve", outcome: ALLOW, expect: { rev: g0b + 1 } }), { claimed: true });
        }
    });
    run("a row that has ended keeps its queue and takes no more: resolved or expired, get answers the same entries in order and setPendingSteer answers false", async () => {
        const store = make();
        const rowA = createCheckpointFixture();
        await store.put(rowA.token, rowA);
        assert.equal(await store.setPendingSteer(rowA.token, rowA.scope, { text: "first", trusted: false, inputId: "end-a1" }), true);
        assert.equal(await store.setPendingSteer(rowA.token, rowA.scope, { text: "second", trusted: true, inputId: "end-a2" }), true);
        const queueBeforeResolve = structuredClone(readPendingSteerQueue((await store.get(rowA.token)).state));
        assert.equal(await store.resolve(rowA.token, rowA.scope, ALLOW), true);
        const afterResolve = structuredClone((await store.get(rowA.token)));
        assert.deepEqual(readPendingSteerQueue(afterResolve.state), queueBeforeResolve);
        assert.equal(await store.setPendingSteer(rowA.token, rowA.scope, { text: "late", trusted: false, inputId: "end-a3" }), false);
        assert.deepEqual(await store.get(rowA.token), afterResolve);
        const rowB = createCheckpointFixture();
        await store.put(rowB.token, rowB);
        assert.equal(await store.setPendingSteer(rowB.token, rowB.scope, { text: "first", trusted: false, inputId: "end-b1" }), true);
        assert.equal(await store.setPendingSteer(rowB.token, rowB.scope, { text: "second", trusted: true, inputId: "end-b2" }), true);
        const queueBeforeExpire = structuredClone(readPendingSteerQueue((await store.get(rowB.token)).state));
        assert.equal(await store.expire(rowB.token, rowB.scope), true);
        const afterExpire = structuredClone((await store.get(rowB.token)));
        assert.deepEqual(readPendingSteerQueue(afterExpire.state), queueBeforeExpire);
        assert.equal(await store.setPendingSteer(rowB.token, rowB.scope, { text: "late", trusted: false, inputId: "end-b3" }), false);
        assert.deepEqual(await store.get(rowB.token), afterExpire);
    });
    run("the queue bound is its serialized bytes: fail-loud steering.queue_full past them, and it evicts nothing", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        for (let i = 0; i < 3; i++) {
            assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: `s${i}:${BYTE_FILLER}`, trusted: false }), true);
        }
        await assert.rejects(store.setPendingSteer(cp.token, cp.scope, { text: `overflow:${BYTE_FILLER}`, trusted: false }), (e) => e.code === "steering.queue_full");
        const q = readPendingSteerQueue((await store.get(cp.token)).state);
        assert.deepEqual(q.map((e) => e.text), [0, 1, 2].map((i) => `s${i}:${BYTE_FILLER}`));
    });
    run("there is no entry-count bound: short entries that fit are all taken, in order", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        const texts = ["stop", "use main", "skip tests", "then report", "and a fifth"];
        for (const [i, text] of texts.entries()) {
            assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text, trusted: false, inputId: `short-${i}` }), true);
        }
        assert.deepEqual(readPendingSteerQueue((await store.get(cp.token)).state).map((e) => e.text), texts);
    });
    run("a queue entry round-trips every FROZEN field (actor/inputId/priority included)", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, {
            text: "attributed",
            trusted: true,
            actor: { id: "slack:U1", hostAsserted: true, issuer: "slack-app:A1" },
            inputId: "m-42",
            priority: "now",
        }), true);
        const q = readPendingSteerQueue((await store.get(cp.token)).state);
        assert.deepEqual(q, [
            { text: "attributed", trusted: true, actor: { id: "slack:U1", hostAsserted: true, issuer: "slack-app:A1" }, inputId: "m-42", priority: "now", seq: 1 },
        ]);
    });
    run("an unknown steering field is REFUSED (a producer must not have its new field silently dropped)", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await assert.rejects(store.setPendingSteer(cp.token, cp.scope, { text: "go", trusted: false, futureField: 1 }), (e) => e.code === "steering.invalid_content");
        assert.deepEqual(readPendingSteerQueue((await store.get(cp.token)).state), []);
    });
    run("expire vs resolve on the same row → exactly one wins; reap expires past-deadline pending in scope", async () => {
        const store = make();
        const a = createCheckpointFixture();
        await store.put(a.token, a);
        const [e, r] = await Promise.all([store.expire(a.token, a.scope), store.resolve(a.token, a.scope, ALLOW)]);
        assert.equal([e, r].filter(Boolean).length, 1);
        const b = createCheckpointFixture({ deadline: 1000 });
        await store.put(b.token, b);
        assert.equal(await store.reap(b.scope, 2000), 1);
        assert.equal(await store.reap(b.scope, 2000), 0);
        assert.equal((await store.get(b.token)).status, "expired");
    });
    run("listByScope (seam #1): only pending in-scope rows; resolved + other-scope excluded; empty → []", async () => {
        const store = make();
        assert.deepEqual(await store.listByScope("tenant-a"), []);
        const pending = createCheckpointFixture({ scope: "tenant-a", sessionId: "p" });
        const resolved = createCheckpointFixture({ scope: "tenant-a", sessionId: "r" });
        const other = createCheckpointFixture({ scope: "tenant-b", sessionId: "o" });
        for (const cp of [pending, resolved, other])
            await store.put(cp.token, cp);
        await store.resolve(resolved.token, resolved.scope, ALLOW);
        const list = await store.listByScope("tenant-a");
        assert.equal(list.length, 1);
        assert.equal(list[0].sessionId, "p");
        assert.equal(list[0].token, pending.token);
        assert.equal((await store.get(pending.token)).status, "pending");
    });
    run("the anonymous working scope is a scope like any other: a card filed under ANONYMOUS_SCOPE lists and resolves under no other name, and a named scope's card never lists under it", async () => {
        const store = make();
        const anon = createCheckpointFixture({ scope: ANONYMOUS_SCOPE, sessionId: "anon" });
        const named = createCheckpointFixture({ scope: "tenant-a", sessionId: "named" });
        for (const cp of [anon, named])
            await store.put(cp.token, cp);
        assert.deepEqual((await store.listByScope(ANONYMOUS_SCOPE)).map((s) => s.token), [anon.token]);
        assert.deepEqual((await store.listByScope("tenant-a")).map((s) => s.token), [named.token]);
        assert.equal(await store.resolve(anon.token, "tenant-a", ALLOW), false, "another scope never resolves an anonymous card");
        assert.equal(await store.resolve(named.token, ANONYMOUS_SCOPE, ALLOW), false, "the anonymous scope never resolves a named scope's card");
        assert.equal(await store.expire(anon.token, "tenant-a"), false, "another scope never expires an anonymous card");
        assert.equal((await store.get(anon.token)).status, "pending");
        assert.equal((await store.get(named.token)).status, "pending");
    });
    run("rowVerdict: every listed summary's verdict equals judgeCheckpointRow of the row get hands back (an ok row, a damaged row), and editing a listed summary's preview leaves the stored row as it was", async () => {
        const store = make();
        const okRow = createCheckpointFixture({
            sessionId: "verdict-ok",
            pendingAction: unhashedCall({ kind: "tool_approval", origin: "policy", toolCallId: "call-3", toolName: "Write", args: { path: "/x", content: "y" }, preview: { lines: ["a"] }, boundGrantAbsence: "not_bindable", batchToolCallIds: ["call-3"], completedCallIds: [] }),
        });
        const damagedRow = damagedWriteFaceFixture({ sessionId: "verdict-damaged" });
        for (const cp of [okRow, damagedRow])
            await store.put(cp.token, cp);
        const listed = await store.listByScope("tenant-a");
        assert.equal(listed.length, 2);
        assert.equal(judgeCheckpointRow(okRow).kind, "ok");
        assert.equal(judgeCheckpointRow(damagedRow).kind, "damaged");
        for (const s of listed)
            assert.deepEqual(s.rowVerdict, judgeCheckpointRow((await store.get(s.token))), `the listing and the get judge one row (${s.sessionId})`);
        const byId = new Map(listed.map((s) => [s.sessionId, s]));
        byId.get("verdict-ok").preview.lines.push("edited on the summary");
        const stored = (await store.get(okRow.token)).pendingAction;
        assert.deepEqual(stored.preview, { lines: ["a"] }, "a summary's preview is a copy: editing it does not edit the stored row");
        const relisted = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.deepEqual(relisted.get("verdict-ok").preview, { lines: ["a"] });
    });
    run("rowVerdict: a listed verdict is the verdict judged now — on a second listing, and (deleteSessionCheckpoints offered) after a token's row is replaced by a damaged one", async () => {
        const store = make();
        const row = createCheckpointFixture({ sessionId: "memo-row" });
        await store.put(row.token, row);
        const first = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
        const second = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
        assert.deepEqual(first.rowVerdict, judgeCheckpointRow((await store.get(row.token))));
        assert.deepEqual(second.rowVerdict, first.rowVerdict);
        const heads = options.sessionHeads;
        if (store.deleteSessionCheckpoints === undefined || heads === undefined)
            return;
        heads.set("memo-row", { owner: null });
        if ((await store.deleteSessionCheckpoints("memo-row", { owner: null })) !== 1)
            return;
        const replaced = damagedWriteFaceFixture({ token: row.token, sessionId: "memo-row" });
        await store.put(replaced.token, replaced);
        const after = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
        assert.equal(after.rowVerdict.kind, "damaged", "a replaced row is judged again, never answered from the verdict its predecessor had");
        assert.deepEqual(after.rowVerdict, judgeCheckpointRow((await store.get(row.token))));
    });
    run("hasBidiControls three-form matrix: a row's `true` survives + projects; absent stays absent (clean args); an out-of-contract `false` reads as absent; a bit-less marked row backfills at projection", async () => {
        const store = make();
        const RLO = String.fromCodePoint(0x202e);
        const asserted = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "bidi-true" });
        asserted.pendingAction.hasBidiControls = true;
        const absent = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "bidi-absent" });
        const falsed = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "bidi-false" });
        falsed.pendingAction.hasBidiControls = false;
        const bitless = createCheckpointFixture({
            token: mintCheckpointToken(),
            sessionId: "bidi-bitless",
            pendingAction: {
                kind: "tool_approval",
                origin: "policy",
                toolCallId: "call-3",
                toolName: "Write",
                args: { path: `/x/${RLO}txt.exe` },
                boundInputHash: "h0",
                batchToolCallIds: ["call-3"],
                completedCallIds: [],
            },
        });
        for (const cp of [asserted, absent, falsed, bitless])
            await store.put(cp.token, cp);
        const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.equal(byId.get("bidi-true")?.hasBidiControls, true);
        assert.equal("hasBidiControls" in byId.get("bidi-absent"), false, "clean+absent must project the key OMITTED, not null/false");
        assert.equal("hasBidiControls" in byId.get("bidi-false"), false, "a written false is out-of-contract and must read as absent, never project");
        assert.equal(byId.get("bidi-bitless")?.hasBidiControls, true, "a marked row without the bit must be backfilled at projection time");
        assert.equal(byId.get("bidi-bitless").toolInput.includes(RLO), true);
        const stored = (await store.get(bitless.token)).pendingAction;
        assert.equal("hasBidiControls" in stored, false, "projection backfill must not write back to the row");
    });
    run("the approval object's members: a row's identity + face group and its targets (capabilityId/contractId/shapeDigest/implementationRevision + family/pathTarget/hostTarget/names + targets + targetReads + engineMounted + declarationDigest) survive the round-trip verbatim; an absent group stays absent", async () => {
        const store = make();
        const carried = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "id-carried" });
        const group = {
            capabilityId: "c3f1e7a2b94d5608",
            contractId: "acme.write@2",
            shapeDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            implementationRevision: "r7",
            family: "file-write",
            pathTarget: { param: "destination", aliases: ["path"], access: "create", skillScopeEligible: true },
            names: ["AcmeWrite", "acme_write"],
            targets: { protective: "/srv/work/out.txt", declared: "/srv/work/out.txt" },
            targetReads: { ["0123456789abcdef".repeat(4)]: "fedcba9876543210".repeat(4) },
            engineMounted: true,
            startedShell: "zsh",
            declarationDigest: "0123456789abcdef".repeat(4),
        };
        Object.assign(carried.pendingAction, group);
        const bare = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "id-bare" });
        for (const cp of [carried, bare])
            await store.put(cp.token, cp);
        const back = (await store.get(carried.token)).pendingAction;
        for (const [k, v] of Object.entries(group))
            assert.deepEqual(back[k], v, `the row's ${k} must survive the round-trip verbatim (a whitelisting serializer that drops it makes every resume-edit recheck judge by the catalog's slot for the NAME)`);
        const bareBack = (await store.get(bare.token)).pendingAction;
        for (const k of Object.keys(group))
            assert.equal(k in bareBack, false, `an absent ${k} must stay OMITTED (a row without its tool member binds no tool, never a partial one)`);
        const fetchRow = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "id-host" });
        Object.assign(fetchRow.pendingAction, { ...group, family: "web", pathTarget: undefined, targets: undefined, hostTarget: { param: "url" } });
        delete fetchRow.pendingAction.pathTarget;
        delete fetchRow.pendingAction.targets;
        await store.put(fetchRow.token, fetchRow);
        const fetchBack = (await store.get(fetchRow.token)).pendingAction;
        assert.deepEqual(fetchBack.hostTarget, { param: "url" }, "the row's hostTarget must survive the round-trip verbatim (dropped, a resume of the parked fetch reads a face that moved and is vetoed, and its pre-claim recheck judges the catalog's slot for the NAME)");
        assert.equal("hostTarget" in bareBack, false, "an absent hostTarget must stay OMITTED");
        const listRow = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "id-list" });
        const listed = { pathTarget: { param: "paths", aliases: [], access: "read", skillScopeEligible: false, each: true }, targets: { protective: ["/srv/work/a.txt", null], declared: ["/srv/work/a.txt", null] } };
        Object.assign(listRow.pendingAction, { ...group, family: "file-read", ...listed });
        await store.put(listRow.token, listRow);
        const listBack = (await store.get(listRow.token)).pendingAction;
        assert.deepEqual(listBack.pathTarget, listed.pathTarget, "the row's pathTarget.each must survive the round-trip (dropped, the face the resume reads moved and the approval is vetoed)");
        assert.deepEqual(listBack.targets, listed.targets, "the row's list of landings must survive the round-trip in order, its nulls kept (dropped or reshaped, the resume cannot tell where each element landed)");
    });
    run("previewWithheld three-form matrix: a row's spelling survives + projects; absent stays absent; an out-of-contract spelling reads as absent", async () => {
        const store = make();
        const oversize = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "pw-oversize" });
        oversize.pendingAction.previewWithheld = "oversize";
        const unavailable = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "pw-unavailable" });
        unavailable.pendingAction.previewWithheld = "unavailable";
        const absent = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "pw-absent" });
        const bogus = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "pw-bogus" });
        bogus.pendingAction.previewWithheld = "shrugged";
        for (const cp of [oversize, unavailable, absent, bogus])
            await store.put(cp.token, cp);
        const back = (await store.get(oversize.token)).pendingAction;
        assert.equal(back.previewWithheld, "oversize", "the row's previewWithheld must survive the round-trip verbatim");
        const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.equal(byId.get("pw-oversize")?.previewWithheld, "oversize");
        assert.equal(byId.get("pw-unavailable")?.previewWithheld, "unavailable");
        assert.equal("previewWithheld" in byId.get("pw-absent"), false, "absent must project the key OMITTED, not null/empty");
        assert.equal("previewWithheld" in byId.get("pw-bogus"), false, "an out-of-contract spelling must read as absent, never project verbatim");
    });
    run("existingTarget three shapes: each survives the row round-trip verbatim; absent stays absent; none is projected to the summary", async () => {
        const store = make();
        const shapes = [
            { kind: "text", text: "line one\nline two\n" },
            { kind: "absent" },
            { kind: "withheld", why: "read_refused" },
        ];
        const rows = shapes.map((existingTarget, i) => {
            const cp = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: `et-${i}` });
            cp.pendingAction.existingTarget = existingTarget;
            return cp;
        });
        const bare = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "et-bare" });
        for (const cp of [...rows, bare])
            await store.put(cp.token, cp);
        for (const [i, cp] of rows.entries()) {
            const back = (await store.get(cp.token)).pendingAction;
            assert.deepEqual(back.existingTarget, shapes[i], "the row's existingTarget must survive the round-trip verbatim (dropped, a parked write's inbox card loses what its target holds)");
        }
        assert.equal("existingTarget" in (await store.get(bare.token)).pendingAction, false, "an absent existingTarget must stay OMITTED");
        for (const s of await store.listByScope("tenant-a"))
            assert.equal("existingTarget" in s, false, "the target's text is not a summary member");
    });
    run("mandated presence bit: a row's `true` survives + projects; absent stays absent; an out-of-contract `false` or string reads as absent", async () => {
        const store = make();
        const asserted = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "md-true" });
        asserted.pendingAction.mandated = true;
        const absent = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "md-absent" });
        const falsed = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "md-false" });
        falsed.pendingAction.mandated = false;
        const stringed = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "md-string" });
        stringed.pendingAction.mandated = "yes";
        for (const cp of [asserted, absent, falsed, stringed])
            await store.put(cp.token, cp);
        const back = (await store.get(asserted.token)).pendingAction;
        assert.equal(back.mandated, true, "the row's mandated bit must survive the round-trip verbatim");
        assert.equal("mandated" in (await store.get(absent.token)).pendingAction, false, "an absent bit must stay OMITTED on the row");
        const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.equal(byId.get("md-true")?.mandated, true);
        assert.equal("mandated" in byId.get("md-absent"), false, "absent must project the key OMITTED, not null/false");
        assert.equal("mandated" in byId.get("md-false"), false, "a written false is out-of-contract and must read as absent, never project");
        assert.equal("mandated" in byId.get("md-string"), false, "a non-boolean spelling must read as absent, never project verbatim");
    });
    run("mandate word: a row's closed-set word survives + projects; absent stays absent; a word outside the set reads as absent", async () => {
        const store = make();
        const worded = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mw-word" });
        Object.assign(worded.pendingAction, { mandated: true, mandate: "probe_mandate" });
        const bare = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mw-absent" });
        Object.assign(bare.pendingAction, { mandated: true });
        const bogus = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mw-bogus" });
        Object.assign(bogus.pendingAction, { mandated: true, mandate: "bypass_ok" });
        for (const cp of [worded, bare, bogus])
            await store.put(cp.token, cp);
        assert.equal((await store.get(worded.token)).pendingAction.mandate, "probe_mandate", "the row's mandate word must survive the round-trip verbatim");
        assert.equal("mandate" in (await store.get(bare.token)).pendingAction, false, "an absent word must stay OMITTED on the row");
        const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.equal(byId.get("mw-word")?.mandate, "probe_mandate");
        assert.equal("mandate" in byId.get("mw-absent"), false, "absent must project the key OMITTED");
        assert.equal("mandate" in byId.get("mw-bogus"), false, "a word outside the closed set must read as absent, never project verbatim");
    });
    run("ask class pair: a tool_approval row's `askClass` / `classes` survive the round-trip verbatim (the array whole, in its order); an absent pair stays absent", async () => {
        const store = make();
        const single = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ac-single" });
        Object.assign(single.pendingAction, { askClass: "denial_limit_fallback", classes: ["denial_limit_fallback"] });
        const several = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ac-several" });
        Object.assign(several.pendingAction, { askClass: "transcript_write", classes: ["transcript_write", "org_rule"] });
        const absent = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ac-absent" });
        for (const cp of [single, several, absent])
            await store.put(cp.token, cp);
        for (const [cp, askClass, classes] of [[single, "denial_limit_fallback", ["denial_limit_fallback"]], [several, "transcript_write", ["transcript_write", "org_rule"]]]) {
            const back = (await store.get(cp.token)).pendingAction;
            assert.equal(back.askClass, askClass, "the row's askClass must survive the round-trip verbatim");
            assert.deepEqual(back.classes, classes, "the row's classes must survive the round-trip as the same array, in the same order");
        }
        const bare = (await store.get(absent.token)).pendingAction;
        assert.equal("askClass" in bare, false, "an absent askClass must stay OMITTED on the row");
        assert.equal("classes" in bare, false, "an absent classes must stay OMITTED on the row");
    });
    run("requirement list: a v10 row's `requires` survives the round-trip verbatim (the whole array, in its order) beside its version; a row without one stays without", async () => {
        const store = make();
        const listed = { ...createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "rq-list" }), version: 10, requires: ["binding", "hands_coordinates", "requirements_digest"], requirementsDigest: "a".repeat(64) };
        const { requires: _list, requirementsDigest: _digest, ...bare } = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "rq-none" });
        const newer = { ...createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "rq-newer" }), version: 11 };
        const older = { ...bare, token: mintCheckpointToken(), sessionId: "rq-older", version: 9 };
        for (const cp of [listed, bare, newer, older])
            await store.put(cp.token, cp);
        assert.equal((await store.get(newer.token)).version, 11, "a newer row's version must survive the round-trip");
        assert.equal((await store.get(older.token)).version, 9, "a row below the format must keep its version");
        const back = (await store.get(listed.token));
        assert.equal(back.version, 10, "the frozen stamp must survive the round-trip");
        assert.deepEqual(back.requires, ["binding", "hands_coordinates", "requirements_digest"], "the requirement list must survive the round-trip as the same array, in the same order");
        assert.equal(back.requirementsDigest, "a".repeat(64), "the row digest must survive the round-trip verbatim");
        const bareBack = (await store.get(bare.token));
        assert.equal("requires" in bareBack || "requirementsDigest" in bareBack, false, "a row without a list or digest must stay without (never [] / null / \"\")");
    });
    run("held rows: a row's `heldRows` (the conversation rows owed after its leaf) survive the round-trip verbatim — every row, in its order, each member of each (text blocks, a string content, `provenance`, `rewrittenBy`); a row without them stays without", async () => {
        const store = make();
        const heldRows = [
            { role: "user", content: "first note", timestamp: 1, provenance: "engine-note" },
            { role: "user", content: [{ type: "text", text: "second note, rewritten" }], timestamp: 2, provenance: "engine-note", rewrittenBy: ["scrubber", "tagger"] },
        ];
        const held = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "held-rows", heldRows });
        const bare = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "held-none" });
        for (const cp of [held, bare])
            await store.put(cp.token, cp);
        assert.deepEqual((await store.get(held.token)).heldRows, heldRows, "the held rows must survive the round-trip as the same rows, in the same order, every member kept");
        assert.equal("heldRows" in (await store.get(bare.token)), false, "a row without held rows must stay without (never [] / null)");
    });
    run("run origin: a row's `state.runOrigin` survives the round-trip verbatim and rides the listing; absent stays absent; a word outside the set is kept on the row and reads as absent in the listing", async () => {
        const store = make();
        const member = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ro-member" });
        Object.assign(member.state, { runOrigin: "scheduled" });
        const absent = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ro-absent" });
        const bogus = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ro-bogus" });
        Object.assign(bogus.state, { runOrigin: "weekly" });
        for (const cp of [member, absent, bogus])
            await store.put(cp.token, cp);
        const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.equal((await store.get(member.token)).state.runOrigin, "scheduled", "the row's runOrigin must survive the round-trip verbatim");
        assert.equal(byId.get("ro-member")?.runOrigin, "scheduled", "the listing must echo the row's runOrigin");
        assert.equal("runOrigin" in (await store.get(absent.token)).state, false, "an absent runOrigin must stay OMITTED on the row, never a fabricated member");
        assert.equal("runOrigin" in byId.get("ro-absent"), false, "absent must project the key OMITTED, not null / empty");
        assert.equal((await store.get(bogus.token)).state.runOrigin, "weekly", "a word outside the set must be kept on the row verbatim");
        assert.equal("runOrigin" in byId.get("ro-bogus"), false, "a word outside the closed set must read as absent in the listing, never project verbatim");
    });
    run("leg rule session: a row's `state.legIdentity.ruleSessionId` survives the round-trip verbatim and rides the listing as `sessionScope`; a row that records none lists none", async () => {
        const store = make();
        const leg = { rootSessionId: "rs-root", rootSessionScope: "tenant-a", ruleSessionId: "rs-root" };
        const shared = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "rs-shared", state: { activeTools: [], nestedStats: { tokens: 0, turns: 0, tasks: 0, costMicroUsd: 0, anyUnpriced: false }, legIdentity: leg } });
        const own = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "rs-own" });
        for (const cp of [shared, own])
            await store.put(cp.token, cp);
        assert.deepEqual((await store.get(shared.token)).state.legIdentity, leg, "the row's leg identity, its rule session among it, must survive the round-trip verbatim");
        const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
        assert.equal(byId.get("rs-shared")?.sessionScope, "rs-root", "the listing must echo the row's rule session as sessionScope");
        assert.equal("sessionScope" in byId.get("rs-own"), false, "a row that records no rule session lists none (its session is the card's own)");
    });
    run("member presence: a row whose top level and `state` carry members holding undefined reads them absent — the value undefined (`memberPresent` false), the listing without them — and judges as its twin without the keys", async () => {
        const store = make();
        const holding = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mp-holding" });
        Object.assign(holding, { deadline: undefined, humanReview: undefined });
        Object.assign(holding.state, { compositionLeg: undefined, rowTaskId: undefined });
        const omitted = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mp-omitted" });
        for (const cp of [holding, omitted])
            await store.put(cp.token, cp);
        const got = (await store.get(holding.token));
        for (const name of ["deadline", "humanReview"])
            assert.equal(memberPresent(got, name), false, `a top-level ${name} holding undefined must read absent`);
        for (const name of ["compositionLeg", "rowTaskId"])
            assert.equal(memberPresent(got.state, name), false, `a state.${name} holding undefined must read absent`);
        const listed = (await store.listByScope("tenant-a")).find((s) => s.sessionId === "mp-holding");
        assert.equal("deadline" in listed, false, "the listing must leave out a deadline that holds undefined");
        assert.deepEqual(judgeCheckpointRow(got), judgeCheckpointRow((await store.get(omitted.token))), "a member holding undefined must judge as the member left out");
    });
    run("decider pair: a policy-decided allow resolves like a person's — its `policy_allowed` record (party `policy`, the attribution) round-trips verbatim on the resolved winner and as the execution record; the same record is already_recorded, a person's record for that row conflicts", async () => {
        const store = make();
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.resolve(cp.token, cp.scope, POLICY_ALLOW), true, "a policy-decided allow is a decision the CAS takes like any other");
        const resolved = (await store.get(cp.token));
        assert.equal(resolved.status, "resolved");
        assert.equal(resolved.resolvedOutcome.decision, "allow");
        assert.deepEqual(resolved.resolvedOutcome.gateOutcome, POLICY_ALLOWED, "the decision's record rides the winner verbatim — the party word and the attribution included");
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, POLICY_ALLOWED), "recorded");
        const filed = (await store.get(cp.token));
        assert.deepEqual(filed.executionOutcome, POLICY_ALLOWED, "the policy's execution record is kept verbatim");
        assert.deepEqual(executionVerdict(filed), { kind: "executed", gate: POLICY_ALLOWED });
        assert.equal(await store.recordExecutionOutcome(cp.token, cp.scope, structuredClone(POLICY_ALLOWED)), "already_recorded", "an unfrozen structural twin is the same record");
        await assert.rejects(store.recordExecutionOutcome(cp.token, cp.scope, EXECUTED_ALLOW), (e) => e.code === "checkpoint.execution_outcome_conflict", "a person's record for a row the policy decided is a different record");
        assert.deepEqual((await store.get(cp.token)).executionOutcome, POLICY_ALLOWED);
    });
    run("index facts: every row's checkpointIndexFacts survive the round trip — an approval gate with a card, a word outside the card set, no card, a descriptor, a deadline, the directional-control bit; a tool-less park", async () => {
        const store = make();
        const descriptor = { severity: 4, axes: { egress: true }, toolName: "Write" };
        const laterWord = createCheckpointFixture({ gate: { kind: "human", reason: "approve", toolName: "Write" } });
        Object.assign(laterWord.gate, { approvalCard: "card-of-a-later-engine" });
        const rows = [
            createCheckpointFixture({ gate: { kind: "human", reason: "approve", toolName: "Write", approvalCard: "file-write", riskDescriptor: descriptor }, deadline: 1_900_000_000_000 }),
            createCheckpointFixture({ gate: { kind: "irreversible_ask", reason: "send", toolName: "Write", approvalCard: "question" } }),
            laterWord,
            createCheckpointFixture({ pendingAction: { kind: "tool_approval", origin: "policy", toolCallId: "call-b", toolName: "Write", args: {}, boundInputHash: "hb", hasBidiControls: true, batchToolCallIds: ["call-b"], completedCallIds: [] } }),
            createCheckpointFixture({ gate: { kind: "resource_limit", reason: "turns" }, pendingAction: { kind: "resource_limit", reason: "turns" }, deadline: 1_900_000_000_001 }),
        ];
        for (const cp of rows) {
            await store.put(cp.token, cp);
            const back = await store.get(cp.token);
            assert.ok(back !== null, "a row put is a row read");
            assert.deepEqual(checkpointIndexFacts(back), checkpointIndexFacts(cp), `the index facts of the row ${cp.gate.kind} came back different`);
        }
    });
    run("listOverdue (when offered): pending rows of every scope past the cutoff, one facet per call (facetOf, the question card included), deadline-then-token order, the bound cut with a cursor that resumes without a gap or a repeat, a bad query refused", async () => {
        const store = make();
        if (store.listOverdue === undefined)
            return;
        const human = (over) => createCheckpointFixture(over);
        const question = createCheckpointFixture({ token: "ov-q", deadline: 1_000, gate: { kind: "human", reason: "ask", toolName: "Write", approvalCard: "question" } });
        const rows = [
            human({ token: "ov-a2", deadline: 1_500 }),
            human({ token: "ov-a1", deadline: 1_000, scope: "tenant-b" }),
            human({ token: "ov-a0", deadline: 1_000 }),
            question,
            createCheckpointFixture({ token: "ov-r", deadline: 900, gate: { kind: "resource_limit", reason: "turns" }, pendingAction: { kind: "resource_limit", reason: "turns" } }),
            createCheckpointFixture({ token: "ov-t", deadline: 900, gate: { kind: "task_done" }, pendingAction: { kind: "task_done" } }),
            human({ token: "ov-late", deadline: 5_000 }),
            human({ token: "ov-none" }),
            human({ token: "ov-done", deadline: 1_000 }),
        ];
        for (const cp of rows)
            await store.put(cp.token, cp);
        await store.resolve("ov-done", "tenant-a", ALLOW);
        const tokensOf = (page) => page.rows.map((r) => r.token);
        assert.deepEqual(tokensOf(await store.listOverdue({ cutoff: 2_000, facet: "A" })), ["ov-a0", "ov-a1", "ov-a2"], "facet A = the approval rows past the cutoff, every scope, (deadline, token) ascending");
        assert.deepEqual(tokensOf(await store.listOverdue({ cutoff: 2_000, facet: "B" })), ["ov-r", "ov-q"], "facet B = the abandonment rows, the question parked under an approval gate kind among them");
        assert.deepEqual(tokensOf(await store.listOverdue({ cutoff: 2_000, facet: "-" })), ["ov-t"], "facet - = the non-gate park");
        const first = await store.listOverdue({ cutoff: 2_000, facet: "A", limit: 2 });
        assert.deepEqual(tokensOf(first), ["ov-a0", "ov-a1"], "the bound cuts the page");
        assert.ok(first.next !== undefined, "a cut page carries the next cursor");
        const second = await store.listOverdue({ cutoff: 2_000, facet: "A", limit: 2, after: first.next });
        assert.deepEqual(tokensOf(second), ["ov-a2"], "the cursor resumes after the last row of the page before");
        assert.equal(second.next, undefined, "the last page carries no cursor");
        assert.equal((await store.get(question.token)).status, "pending", "read-only: the listing mutates nothing");
        for (const bad of [{ cutoff: 2_000, facet: "A", limit: 0 }, { cutoff: 2_000, facet: "A", limit: 501 }, { cutoff: 2_000, facet: "A", limit: 1.5 }, { cutoff: Number.NaN, facet: "A" }, { cutoff: 2_000, facet: "C" }, { cutoff: 2_000, facet: "A", scope: "tenant-a" }]) {
            await assert.rejects(store.listOverdue(bad), (e) => e.code === "config.invalid_argument", `refused loudly: ${JSON.stringify(bad)}`);
        }
    });
    run("resource_limit rows: the listing summary (listByScope, and listOverdue when offered) carries `resourceLimit` equal to summarizeCheckpoint of the row get hands back — each of the seven causes, a usage window's `resumableAt` among them — and a row of another gate kind carries none", async () => {
        const store = make();
        const CREATED = 1_700_000_000_000;
        const HINT_MS = 90_000;
        const resourceRows = RESOURCE_LIMIT_REASONS.map((reason) => createCheckpointFixture({
            token: `rl-${reason}`,
            sessionId: `rl-${reason}`,
            createdAt: CREATED,
            deadline: 1_000,
            gate: reason === "usage_window" ? { kind: "resource_limit", reason, resumeAfterMs: HINT_MS } : { kind: "resource_limit", reason },
            pendingAction: { kind: "resource_limit", reason },
        }));
        const approval = createCheckpointFixture({ token: "rl-approval", sessionId: "rl-approval", deadline: 1_000, gate: { kind: "human", reason: "preempt", toolName: "Write" } });
        for (const cp of [...resourceRows, approval])
            await store.put(cp.token, cp);
        const judge = async (face, listed) => {
            const byToken = new Map(listed.map((s) => [s.token, s]));
            for (const cp of resourceRows) {
                const reason = cp.gate.reason;
                const s = byToken.get(cp.token);
                assert.ok(s !== undefined, `${face}: the ${reason} row is listed`);
                const read = summarizeCheckpoint((await store.get(cp.token))).resourceLimit;
                assert.deepEqual(read, reason === "usage_window" ? { reason, resumableAt: CREATED + HINT_MS } : { reason }, `the engine's own reading of the ${reason} row`);
                assert.deepEqual(s.resourceLimit, read, `${face}: the ${reason} row's listed summary carries the cause summarizeCheckpoint reads (and, for a usage window, resumableAt = createdAt + the gate's hint)`);
            }
            const listedApproval = byToken.get(approval.token);
            assert.ok(listedApproval !== undefined, `${face}: the approval row is listed`);
            assert.equal("resourceLimit" in listedApproval, false, `${face}: an approval row carries no resourceLimit member`);
        };
        await judge("listByScope", await store.listByScope("tenant-a"));
        if (store.listOverdue === undefined)
            return;
        const overdue = [];
        for (const facet of ["A", "B", "-"])
            overdue.push(...(await store.listOverdue({ cutoff: 2_000, facet })).rows);
        await judge("listOverdue", overdue);
    });
    run("listBySession (when offered): one session's rows in any status narrowed by status / gate kinds / tool call / scope / createdSince, oldest or newest first, the bound cut with a resuming cursor, an empty gate-kind list matching nothing, a bad query refused", async () => {
        const store = make();
        if (store.listBySession === undefined)
            return;
        const s = "sess-list";
        const rows = [
            createCheckpointFixture({ token: "ls-1", sessionId: s, createdAt: 1 }),
            createCheckpointFixture({ token: "ls-2", sessionId: s, createdAt: 2, pendingAction: { kind: "tool_approval", origin: "policy", toolCallId: "call-9", toolName: "Write", args: {}, boundInputHash: "h9", boundGrantAbsence: "not_bindable", batchToolCallIds: ["call-9"], completedCallIds: [] } }),
            createCheckpointFixture({ token: "ls-3", sessionId: s, createdAt: 3, gate: { kind: "resource_limit", reason: "turns" }, pendingAction: { kind: "resource_limit", reason: "turns" } }),
            createCheckpointFixture({ token: "ls-4", sessionId: s, createdAt: 4, scope: "tenant-b" }),
            createCheckpointFixture({ token: "ls-x", sessionId: "another-session", createdAt: 1 }),
        ];
        for (const cp of rows)
            await store.put(cp.token, cp);
        await store.resolve("ls-1", "tenant-a", ALLOW);
        await store.expire("ls-3", "tenant-a");
        const tokensOf = (page) => page.rows.map((r) => {
            const read = r;
            assert.equal(read.kind, "row", "a readable row is answered as a row");
            return read.checkpoint.token;
        });
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s })), ["ls-1", "ls-2", "ls-3", "ls-4"], "every status, every scope, oldest first; another session's row never");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, order: "newest" })), ["ls-4", "ls-3", "ls-2", "ls-1"]);
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, status: "pending", gateKinds: ["human"], order: "newest", limit: 1 })), ["ls-4"], "the session's newest pending row of a gate kind");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, status: "pending", gateKinds: ["human"], scope: "tenant-a" })), ["ls-2"]);
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, gateKinds: [] })), [], "an empty gate-kind list matches no row");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, status: "expired", limit: 1 })), ["ls-3"]);
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, toolCallId: "call-3" })), ["ls-1", "ls-4"], "the rows that parked this tool call (a park with no tool call never matches)");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, toolCallId: "call-9", status: "pending" })), ["ls-2"]);
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: s, createdSince: 3 })), ["ls-3", "ls-4"]);
        const first = await store.listBySession({ sessionId: s, limit: 3, order: "newest" });
        assert.deepEqual(tokensOf(first), ["ls-4", "ls-3", "ls-2"]);
        assert.ok(first.next !== undefined, "a cut page carries the next cursor");
        const second = await store.listBySession({ sessionId: s, limit: 3, order: "newest", after: first.next });
        assert.deepEqual(tokensOf(second), ["ls-1"]);
        assert.equal(second.next, undefined);
        const read = (await store.listBySession({ sessionId: s, toolCallId: "call-9" })).rows[0];
        read.checkpoint.status = "expired";
        assert.equal((await store.get("ls-2")).status, "pending", "a listed row is a copy: mutating it changes nothing stored");
        for (const bad of [{ sessionId: "" }, { sessionId: s, limit: 101 }, { sessionId: s, limit: 0 }, { sessionId: s, status: "done" }, { sessionId: s, gateKinds: ["nope"] }, { sessionId: s, order: "latest" }, { sessionId: s, createdSince: Number.POSITIVE_INFINITY }, { sessionId: s, owner: "x" }]) {
            await assert.rejects(store.listBySession(bad), (e) => e.code === "config.invalid_argument", `refused loudly: ${JSON.stringify(bad)}`);
        }
    });
    const isInvalidArgument = (e) => e.code === "config.invalid_argument";
    run("listOverdue age backstop (when offered; a store that refuses `maxAgeMs` is reported absent): a pending row with no deadline is overdue once createdAt + maxAgeMs <= cutoff and sorts at that instant, a row's own deadline outranks the backstop, no backstop = never, a bad backstop refused", async () => {
        const cell = "listOverdue.maxAgeMs";
        const store = make();
        if (store.listOverdue === undefined)
            return;
        const rows = [
            createCheckpointFixture({ token: "ag-1499", createdAt: 1_499 }),
            createCheckpointFixture({ token: "ag-1500", createdAt: 1_500 }),
            createCheckpointFixture({ token: "ag-1501", createdAt: 1_501 }),
            createCheckpointFixture({ token: "ag-dl", createdAt: 0, deadline: 2_000 }),
            createCheckpointFixture({ token: "ag-far", createdAt: 0, deadline: 9_000 }),
            createCheckpointFixture({ token: "ag-res", createdAt: 0 }),
            createCheckpointFixture({ token: "ag-b", createdAt: 0, gate: { kind: "resource_limit", reason: "turns" }, pendingAction: { kind: "resource_limit", reason: "turns" } }),
        ];
        for (const cp of rows)
            await store.put(cp.token, cp);
        await store.resolve("ag-res", "tenant-a", ALLOW);
        const tokensOf = (page) => page.rows.map((r) => r.token);
        let aged;
        try {
            aged = await store.listOverdue({ cutoff: 2_000, facet: "A", maxAgeMs: 500 });
        }
        catch (e) {
            if (!isInvalidArgument(e))
                throw e;
            options.onOptionalMember?.({ member: "listOverdue.maxAgeMs", status: "absent", cell });
            return;
        }
        assert.deepEqual(tokensOf(aged), ["ag-1499", "ag-1500", "ag-dl"], "(the instant, token) ascending: createdAt + maxAgeMs for a row with no deadline, the deadline for one with one; one past the cutoff, a resolved row, and an old row whose own deadline is ahead are not overdue");
        assert.deepEqual(tokensOf(await store.listOverdue({ cutoff: 2_000, facet: "A" })), ["ag-dl"], "no backstop: a row with no deadline is never overdue");
        assert.deepEqual(tokensOf(await store.listOverdue({ cutoff: 2_000, facet: "B", maxAgeMs: 0 })), ["ag-b"], "the backstop reads each facet's rows (maxAgeMs 0 = created at or before the cutoff)");
        const first = await store.listOverdue({ cutoff: 2_000, facet: "A", maxAgeMs: 500, limit: 1 });
        assert.deepEqual(tokensOf(first), ["ag-1499"]);
        assert.deepEqual(first.next, { deadline: 1_999, token: "ag-1499" }, "the cursor's deadline is the instant the row sorts at");
        assert.deepEqual(tokensOf(await store.listOverdue({ cutoff: 2_000, facet: "A", maxAgeMs: 500, after: first.next })), ["ag-1500", "ag-dl"], "the cursor resumes in the backstop's order");
        for (const bad of [-1, Number.NaN, Number.POSITIVE_INFINITY, "500", null]) {
            const query = { cutoff: 2_000, facet: "A", maxAgeMs: bad };
            await assert.rejects(store.listOverdue(query), isInvalidArgument, `refused loudly: maxAgeMs ${String(bad)}`);
        }
        options.onOptionalMember?.({ member: "listOverdue.maxAgeMs", status: "verified", cell });
    });
    run("listBySession run axis (when offered; a store that refuses `axis: \"run\"` is reported absent): the rows whose run session is the id — a cascade rung's and a repair restart's card under their host's, a verifier's card under its own — another session's row never, a row whose leg does not read left out (or refused at put, laying no row down)", async () => {
        const cell = "listBySession.axis";
        const store = make();
        if (store.listBySession === undefined)
            return;
        const base = createCheckpointFixture();
        const withLeg = (token, sessionId, createdAt, compositionLeg) => createCheckpointFixture({ token: token, sessionId, createdAt, state: { ...base.state, ...(compositionLeg !== undefined ? { compositionLeg } : {}) } });
        const rows = [
            withLeg("ra-host", "host-1", 1),
            withLeg("ra-rung", "rung-1", 2, { entry: "cascade", leg: 0, hostSessionId: "host-1" }),
            withLeg("ra-verify", "verifier-1", 3, { entry: "verify", leg: 1, hostSessionId: "host-1" }),
            withLeg("ra-restart", "restart-1", 4, { entry: "repair", leg: 2, hostSessionId: "host-1" }),
            withLeg("ra-other", "rung-2", 5, { entry: "cascade", leg: 0, hostSessionId: "host-2" }),
            withLeg("ra-broken", "host-1", 6, { entry: "cascade", leg: 0, hostSessionId: "" }),
            withLeg("ra-restart-broken", "restart-2", 7, { entry: "repair", leg: 2, hostSessionId: "" }),
        ];
        const refused = new Set();
        for (const cp of rows) {
            try {
                await store.put(cp.token, cp);
            }
            catch (e) {
                if (checkpointRunSessionOf(cp) !== undefined)
                    throw e;
                assert.equal(await store.get(cp.token), null, `the refused put of the ${cp.sessionId} row laid no row down`);
                refused.add(cp.token);
            }
        }
        const tokensOf = (page) => page.rows.map((r) => r.checkpoint.token);
        const held = (tokens) => tokens.filter((t) => !refused.has(t));
        let runPage;
        try {
            runPage = await store.listBySession({ sessionId: "host-1", axis: "run" });
        }
        catch (e) {
            if (!isInvalidArgument(e))
                throw e;
            options.onOptionalMember?.({ member: "listBySession.axis", status: "absent", cell });
            return;
        }
        assert.deepEqual(tokensOf(runPage), ["ra-host", "ra-rung", "ra-restart"], "the host's own row, its rung's and its restart's card; the verifier's card is not the host's run's; a row whose leg names no host is attributable to no run");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "host-1" })), held(["ra-host", "ra-broken"]), "the session axis (absent = the row's own session) is unchanged");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "host-1", axis: "session" })), held(["ra-host", "ra-broken"]));
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "rung-1", axis: "run" })), [], "a rung's card is not its own session's run");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "verifier-1", axis: "run" })), ["ra-verify"], "a verifier's card is redeemed in its own session");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "restart-1", axis: "run" })), [], "a restart's card is not its own session's run");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "restart-2", axis: "run" })), [], "a restart whose leg names no host is no run's, not its own session's");
        assert.deepEqual(tokensOf(await store.listBySession({ sessionId: "restart-2" })), held(["ra-restart-broken"]), "its own session's page lists it exactly when the store holds it — a refused put lists nothing");
        const firstRun = await store.listBySession({ sessionId: "host-1", axis: "run", order: "newest", limit: 2 });
        assert.deepEqual(tokensOf(firstRun), ["ra-restart", "ra-rung"], "the axis pages like the session axis");
        assert.ok(firstRun.next !== undefined, "a cut run page carries the next cursor");
        const secondRun = await store.listBySession({ sessionId: "host-1", axis: "run", order: "newest", limit: 2, after: firstRun.next });
        assert.deepEqual(tokensOf(secondRun), ["ra-host"], "the cursor resumes the run page after its last row");
        assert.equal(secondRun.next, undefined, "the run page's last page carries no cursor");
        for (const cp of rows) {
            assert.equal(checkpointIndexFacts(cp).runSessionId, checkpointRunSessionOf(cp) ?? null, "the index column is the axis's one function (null = no run)");
        }
        const badAxis = { sessionId: "host-1", axis: "host" };
        await assert.rejects(store.listBySession(badAxis), isInvalidArgument, "an axis outside the two words is refused");
        options.onOptionalMember?.({ member: "listBySession.axis", status: "verified", cell });
    });
    run("get: a row filed under the token that does not read as a row is refused — CheckpointError checkpoint.invalid_outcome / requirements_damaged, never null, never answered — and every other row is answered as stored, its damage the row judge's (a listing's unreadable row included)", async () => {
        const store = make();
        const refusedTyped = (e) => isCheckpointRowUnreadable(e);
        const damaged = [
            ["a scope that is not a string", (cp) => Reflect.set(cp, "scope", 7)],
            ["a status that is not a string", (cp) => Reflect.set(cp, "status", null)],
            ["another token member", (cp) => Reflect.set(cp, "token", "gt-elsewhere")],
        ];
        for (const [i, [what, damage]] of damaged.entries()) {
            const token = `gt-${i}`;
            const cp = createCheckpointFixture({ token });
            damage(cp);
            let held = true;
            try {
                await store.put(token, cp);
            }
            catch {
                held = false;
            }
            let answered;
            let refusal;
            try {
                answered = await store.get(token);
            }
            catch (e) {
                refusal = e;
            }
            if (refusal !== undefined)
                assert.ok(refusedTyped(refusal), `get refuses a held row with ${what} by the typed refusal (CheckpointError checkpoint.invalid_outcome / requirements_damaged)`);
            else
                assert.ok(!held && answered === null, `get answers a row with ${what} only by refusing it (held: ${held}; answered ${answered === null ? "null" : "a value"})`);
        }
        const unregistered = createCheckpointFixture({ token: "gt-gate", sessionId: "gt-session" });
        Reflect.set(unregistered.gate, "kind", "no_such_gate");
        await store.put(unregistered.token, unregistered);
        const answered = await store.get(unregistered.token);
        assert.ok(answered !== null, "a row whose member the shape table refuses is answered by get");
        assert.notEqual(judgeCheckpointRow(answered).kind, "ok", "the row judge reads it damaged");
        const offWord = createCheckpointFixture({ token: "gt-status", sessionId: "gt-status-session" });
        Reflect.set(offWord, "status", "archived");
        let offHeld = true;
        try {
            await store.put(offWord.token, offWord);
        }
        catch {
            offHeld = false;
        }
        const offBack = await store.get(offWord.token);
        if (!offHeld)
            assert.equal(offBack, null, "a store that refused to hold the row holds nothing");
        else
            assert.equal(offBack?.status, "archived", "a held row whose status is a string none of the three words is answered as stored");
        if (store.listBySession !== undefined) {
            const listed = (await store.listBySession({ sessionId: "gt-session" })).rows;
            assert.deepEqual(listed.map((r) => r.kind), ["unreadable"], "the listing answers the same row unreadable — the consumer that takes its token to get meets the judge's damaged verdict");
        }
        const old = { ...createCheckpointFixture({ token: "gt-old", sessionId: "gt-old-session" }), version: 5 };
        await store.put(old.token, old);
        const oldBack = await store.get(old.token);
        assert.ok(oldBack !== null, "a row below the format is answered by get, not refused");
        assert.equal(oldBack.version, 5, "answered as stored");
        const oldVerdict = judgeCheckpointRow(oldBack);
        assert.deepEqual(oldVerdict, judgeCheckpointRow(old), "its verdict is the row judge's on the row as written");
        assert.notEqual(oldVerdict.kind, "ok", "and the judge does not resume it");
        if (store.listByScope !== undefined) {
            const oldListed = (await store.listByScope(old.scope)).find((s) => s.token === old.token);
            assert.ok(oldListed !== undefined, "the listing lists it");
            assert.deepEqual(oldListed.rowVerdict, oldVerdict, "the listing's verdict and the judge's of get's answer are one answer");
        }
        assert.equal(await store.get("gt-none"), null, "no row = null");
    });
    run("deleteSessionCheckpoints (when offered): every row of the session, in any status, only when the session row exists and its owner equals the guard's (null-safe); otherwise nothing is deleted and the answer is 0", async () => {
        const store = make();
        if (store.deleteSessionCheckpoints === undefined)
            return;
        const heads = options.sessionHeads;
        assert.ok(heads !== undefined, "a store offering deleteSessionCheckpoints is judged with the binding's `sessionHeads` (the map its session head read reads)");
        heads.set("del-owned", { owner: "alice" });
        heads.set("del-anon", { owner: null });
        const owned = [
            createCheckpointFixture({ sessionId: "del-owned" }),
            createCheckpointFixture({ sessionId: "del-owned" }),
            createCheckpointFixture({ sessionId: "del-owned" }),
            createCheckpointFixture({ sessionId: "del-owned", scope: "tenant-b" }),
        ];
        const anon = createCheckpointFixture({ sessionId: "del-anon" });
        const orphan = createCheckpointFixture({ sessionId: "del-no-row" });
        const bystander = createCheckpointFixture({ sessionId: "del-other" });
        for (const cp of [...owned, anon, orphan, bystander])
            await store.put(cp.token, cp);
        await store.resolve(owned[1].token, owned[1].scope, ALLOW);
        await store.expire(owned[2].token, owned[2].scope);
        assert.equal(await store.deleteSessionCheckpoints("del-owned", { owner: "bob" }), 0, "another owner deletes nothing");
        assert.equal(await store.deleteSessionCheckpoints("del-owned", { owner: null }), 0, "the anonymous guard does not match an owned session");
        assert.equal(await store.deleteSessionCheckpoints("del-no-row", { owner: null }), 0, "no session row deletes nothing");
        assert.ok((await store.get(orphan.token)) !== null && (await store.get(owned[0].token)) !== null, "a refused guard leaves every row");
        assert.equal(await store.deleteSessionCheckpoints("del-owned", { owner: "alice" }), 4, "the owner's guard deletes the session's rows — pending, resolved, expired, in every scope");
        for (const cp of owned)
            assert.equal(await store.get(cp.token), null);
        assert.equal(await store.deleteSessionCheckpoints("del-anon", { owner: null }), 1, "the anonymous guard deletes an anonymous session's rows");
        assert.ok((await store.get(bystander.token)) !== null, "another session's row stays");
        assert.equal(await store.deleteSessionCheckpoints("del-owned", { owner: "alice" }), 0, "a second delete finds nothing");
        const deleteWith = store.deleteSessionCheckpoints;
        for (const guard of [{}, { owner: undefined }, { owner: 7 }]) {
            const call = () => Reflect.apply(deleteWith, store, ["del-other", guard]);
            await assert.rejects(call, (e) => e.code === "config.invalid_argument", `refused loudly: ${JSON.stringify(guard)}`);
        }
        assert.ok((await store.get(bystander.token)) !== null, "a refused guard deletes nothing");
    });
    const holderRun = (name, fn) => run(name, async () => {
        const bare = make();
        const binding = holderBinding("checkpoint", bare.fence !== undefined, options.composed, options.grants);
        if (binding === undefined) {
            options.onOptionalMember?.({ member: "holder", status: "absent", cell: name });
            return;
        }
        await fn(binding.composed(), binding.grants);
        options.onOptionalMember?.({ member: "holder", status: "verified", cell: name });
    });
    const rowNow = async (store, token) => {
        const row = await store.get(token);
        assert.ok(row !== null, "the row is still there");
        return [row.status, checkpointRevOf(row)];
    };
    const steerCountOf = async (store, token) => readPendingSteerQueue((await store.get(token)).state).length;
    const claimArms = async (cell, store, arms) => {
        if (store.claimTerminal === undefined) {
            options.onOptionalMember?.({ member: "claimTerminal", status: "absent", cell });
            return;
        }
        await arms();
        options.onOptionalMember?.({ member: "claimTerminal", status: "verified", cell });
    };
    holderRun("C-H0 grant holder, through the composed store: a dead grant (replaced / ended / unknown status) is refused on every write — put and setPendingSteer throw holder.superseded, expire and resolve lose, each claimTerminal arm loses (when the store implements claimTerminal) — and every row re-reads exactly as it was", async (store, grants) => {
        for (const [label, dead] of deadGrants(grants)) {
            const fresh = createCheckpointFixture();
            await rejectsSuperseded(() => store.put(fresh.token, fresh, { holder: dead }), `put (${label})`);
            assert.equal(await store.get(fresh.token), null, `put (${label}): the refused put laid no row down`);
            const cp = createCheckpointFixture();
            await store.put(cp.token, cp);
            const before = structuredClone(await store.get(cp.token));
            const unchanged = async (what) => assert.deepEqual(await store.get(cp.token), before, `${what}: the row re-reads exactly as it was`);
            await rejectsSuperseded(() => store.setPendingSteer(cp.token, cp.scope, { text: "kit steer", trusted: false }, { holder: dead }), `setPendingSteer (${label})`);
            await unchanged(`setPendingSteer (${label})`);
            assert.equal(await store.expire(cp.token, cp.scope, { holder: dead }), false, `expire (${label}) loses`);
            await unchanged(`expire (${label})`);
            assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 0, holder: dead }), false, `resolve (${label}) loses — a store that forwards rev and drops expect.holder wins it here`);
            await unchanged(`resolve (${label})`);
            await claimArms("C-H0", store, async () => {
                assert.deepEqual(await store.claimTerminal(cp.token, cp.scope, { kind: "resolve", outcome: ALLOW, expect: { rev: 0, holder: dead } }), { claimed: false, current: { status: "pending", rev: 0 } }, `claimTerminal resolve arm (${label})`);
                await unchanged(`claimTerminal resolve arm (${label})`);
                assert.deepEqual(await store.claimTerminal(cp.token, cp.scope, { kind: "expire", expect: { holder: dead } }), { claimed: false, current: { status: "pending", rev: 0 } }, `claimTerminal expire arm (${label})`);
                await unchanged(`claimTerminal expire arm (${label})`);
            });
        }
    });
    holderRun("C-H1 grant holder: a put carrying a dead grant lays no row down — get(token) is null", async (store, grants) => {
        for (const [label, dead] of deadGrants(grants)) {
            const cp = createCheckpointFixture();
            await rejectsSuperseded(() => store.put(cp.token, cp, { holder: dead }), `put (${label})`);
            assert.equal(await store.get(cp.token), null, `put (${label})`);
        }
    });
    holderRun("C-H2 grant holder: a current grant lands on every write — put, setPendingSteer, expire, resolve (and both claimTerminal arms, when implemented); no holder lands as before", async (store, grants) => {
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp, { holder: grants.current() });
        assert.equal((await store.get(cp.token))?.status, "pending", "put with the current grant lands");
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "kit steer", trusted: false }, { holder: grants.current() }), true);
        assert.equal(await steerCountOf(store, cp.token), 1, "setPendingSteer with the current grant appends");
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 1, holder: grants.current() }), true, "resolve with the current grant wins");
        assert.deepEqual(await rowNow(store, cp.token), ["resolved", 2], "the resolve landed");
        const heldWinner = (await store.get(cp.token))?.resolvedOutcome;
        const ex = createCheckpointFixture();
        await store.put(ex.token, ex);
        assert.equal(await store.expire(ex.token, ex.scope, { holder: grants.current() }), true, "expire with the current grant wins");
        assert.equal((await store.get(ex.token))?.status, "expired", "the expire landed");
        const plain = createCheckpointFixture();
        await store.put(plain.token, plain);
        assert.equal(await store.resolve(plain.token, plain.scope, ALLOW, { rev: 0 }), true, "no holder: the CAS is as before");
        assert.deepEqual(await rowNow(store, plain.token), ["resolved", 1], "no holder: the resolve landed");
        const plainWinner = (await store.get(plain.token))?.resolvedOutcome;
        assert.notEqual(plainWinner, undefined, "the resolve with no holder recorded its decision winner");
        assert.deepEqual(heldWinner, plainWinner, "the resolve carrying the current grant recorded the same decision winner as the one carrying none");
        await claimArms("C-H2", store, async () => {
            const [r, e] = [createCheckpointFixture(), createCheckpointFixture()];
            await store.put(r.token, r);
            await store.put(e.token, e);
            assert.deepEqual(await store.claimTerminal(r.token, r.scope, { kind: "resolve", outcome: ALLOW, expect: { rev: 0, holder: grants.current() } }), { claimed: true });
            assert.deepEqual(await rowNow(store, r.token), ["resolved", 1], "the claim's resolve landed");
            assert.deepEqual(await store.claimTerminal(e.token, e.scope, { kind: "expire", expect: { holder: grants.current() } }), { claimed: true });
            assert.equal((await store.get(e.token))?.status, "expired", "the claim's expire landed");
        });
        if (grants.retire !== undefined) {
            const h = grants.current();
            const first = createCheckpointFixture();
            await store.put(first.token, first, { holder: h });
            assert.equal(await store.setPendingSteer(first.token, first.scope, { text: "warm", trusted: false }, { holder: h }), true);
            const warmExpire = createCheckpointFixture();
            await store.put(warmExpire.token, warmExpire);
            assert.equal(await store.expire(warmExpire.token, warmExpire.scope, { holder: h }), true);
            const warmResolve = createCheckpointFixture();
            await store.put(warmResolve.token, warmResolve);
            assert.equal(await store.resolve(warmResolve.token, warmResolve.scope, ALLOW, { rev: 0, holder: h }), true);
            assert.deepEqual(await rowNow(store, warmResolve.token), ["resolved", 1], "the warm resolve landed");
            grants.retire(h);
            const second = createCheckpointFixture();
            await rejectsSuperseded(() => store.put(second.token, second, { holder: h }), "put after the holder was retired");
            assert.equal(await store.get(second.token), null, "the refused put laid no row down");
            await rejectsSuperseded(() => store.setPendingSteer(first.token, first.scope, { text: "late", trusted: false }, { holder: h }), "setPendingSteer after the holder was retired");
            assert.equal(await store.expire(first.token, first.scope, { holder: h }), false, "expire after the holder was retired");
            assert.equal(await store.resolve(first.token, first.scope, ALLOW, { rev: 0, holder: h }), false, "resolve after the holder was retired");
        }
    });
    holderRun("C-H3 grant holder: setPendingSteer carrying a dead grant throws holder.superseded and leaves the queue as it was", async (store, grants) => {
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: "first", trusted: false }), true);
        for (const [label, dead] of deadGrants(grants)) {
            await rejectsSuperseded(() => store.setPendingSteer(cp.token, cp.scope, { text: `late ${label}`, trusted: false }, { holder: dead }), `setPendingSteer (${label})`);
            assert.deepEqual(readPendingSteerQueue((await store.get(cp.token)).state).map((s) => s.text), ["first"], `setPendingSteer (${label}): the queue is unchanged`);
        }
    });
    holderRun("C-H4 grant holder: expire carrying a dead grant answers false with the row pending at its generation; claimTerminal's expire arm (when implemented) answers claimed:false, current pending at that rev", async (store, grants) => {
        for (const [label, dead] of deadGrants(grants)) {
            const cp = createCheckpointFixture();
            await store.put(cp.token, cp);
            assert.equal(await store.expire(cp.token, cp.scope, { holder: dead }), false, `expire (${label})`);
            assert.deepEqual(await rowNow(store, cp.token), ["pending", 0], `expire (${label})`);
            await claimArms("C-H4", store, async () => {
                assert.deepEqual(await store.claimTerminal(cp.token, cp.scope, { kind: "expire", expect: { holder: dead } }), { claimed: false, current: { status: "pending", rev: 0 } }, `claimTerminal expire arm (${label})`);
            });
        }
    });
    holderRun("C-H5 grant holder: resolve carrying a dead grant loses with the row pending at the generation the caller read (claimTerminal's resolve arm, when implemented, answers that reading)", async (store, grants) => {
        for (const [label, dead] of deadGrants(grants)) {
            const cp = createCheckpointFixture();
            await store.put(cp.token, cp);
            assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 0, holder: dead }), false, `resolve (${label})`);
            assert.deepEqual(await rowNow(store, cp.token), ["pending", 0], `resolve (${label}): the row is untouched by the lost CAS`);
            await claimArms("C-H5", store, async () => {
                assert.deepEqual(await store.claimTerminal(cp.token, cp.scope, { kind: "resolve", outcome: ALLOW, expect: { rev: 0, holder: dead } }), { claimed: false, current: { status: "pending", rev: 0 } }, `claimTerminal resolve arm (${label})`);
            });
        }
    });
    holderRun("C-H6 grant holder: a malformed holder makes every write throw (the judge throws) and moves no row", async (store, grants) => {
        const bad = grants.malformed;
        const fresh = createCheckpointFixture();
        await rejectsMalformed(() => store.put(fresh.token, fresh, { holder: bad }), "put");
        assert.equal(await store.get(fresh.token), null, "put: no row laid down");
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        const before = structuredClone(await store.get(cp.token));
        const unchanged = async (what) => assert.deepEqual(await store.get(cp.token), before, `${what}: the row re-reads exactly as it was`);
        await rejectsMalformed(() => store.setPendingSteer(cp.token, cp.scope, { text: "kit steer", trusted: false }, { holder: bad }), "setPendingSteer");
        await unchanged("setPendingSteer");
        await rejectsMalformed(() => store.expire(cp.token, cp.scope, { holder: bad }), "expire");
        await unchanged("expire");
        await rejectsMalformed(() => store.resolve(cp.token, cp.scope, ALLOW, { rev: 0, holder: bad }), "resolve");
        await unchanged("resolve");
        await claimArms("C-H6", store, async () => {
            await rejectsMalformed(() => store.claimTerminal(cp.token, cp.scope, { kind: "resolve", outcome: ALLOW, expect: { rev: 0, holder: bad } }), "claimTerminal resolve arm");
            await unchanged("claimTerminal resolve arm");
            await rejectsMalformed(() => store.claimTerminal(cp.token, cp.scope, { kind: "expire", expect: { holder: bad } }), "claimTerminal expire arm");
            await unchanged("claimTerminal expire arm");
        });
    });
    holderRun("C-H7 grant holder: a run row whose status is outside the judge's live set is not held — put and setPendingSteer refuse, expire and resolve lose (fail-closed)", async (store, grants) => {
        const fresh = createCheckpointFixture();
        await rejectsSuperseded(() => store.put(fresh.token, fresh, { holder: grants.unknownStatus() }), "put");
        assert.equal(await store.get(fresh.token), null, "put: no row laid down");
        const cp = createCheckpointFixture();
        await store.put(cp.token, cp);
        await rejectsSuperseded(() => store.setPendingSteer(cp.token, cp.scope, { text: "kit steer", trusted: false }, { holder: grants.unknownStatus() }), "setPendingSteer");
        assert.equal(await store.expire(cp.token, cp.scope, { holder: grants.unknownStatus() }), false, "expire");
        assert.equal(await store.resolve(cp.token, cp.scope, ALLOW, { rev: 0, holder: grants.unknownStatus() }), false, "resolve");
        assert.deepEqual(await rowNow(store, cp.token), ["pending", 0], "the row did not move");
        assert.equal(await steerCountOf(store, cp.token), 0, "the queue did not move");
    });
    run("identity re-key: the member is carried, and a plan over an empty store is an empty plan", async () => {
        const store = make();
        assert.equal(typeof store.rekeyIdentity, "function", "rekeyIdentity is a required member of the CheckpointStore contract");
        assert.deepEqual(await store.rekeyIdentity({ fromPrincipal: "alice", toPrincipal: "bob", scopes: [{ fromScope: "alice", toScope: "bob" }], mode: "plan" }), { kind: "plan", rows: 0, conflicting: 0, unpairedScopeRows: 0 });
    });
    run("identity re-key: leave re-files the identity cells in place at the next generation — the index facts, both listings and the scope a CAS is judged in follow; a stale generation loses; a second leave finds nothing", async () => {
        const store = make();
        const cp = fixtureWithState({ scope: "alice", principal: "alice", durableApproval: { scope: "alice" }, sessionId: "rekey-1" }, { legScope: "alice" });
        await store.put(cp.token, cp);
        const move = { fromPrincipal: "alice", toPrincipal: "bob", scopes: [{ fromScope: "alice", toScope: "bob" }] };
        assert.deepEqual(await store.rekeyIdentity({ ...move, mode: "plan" }), { kind: "plan", rows: 1, conflicting: 0, unpairedScopeRows: 0 });
        assert.deepEqual(await store.rekeyIdentity({ ...move, mode: "leave" }), { kind: "done", mode: "leave", rows: 1 });
        const row = (await store.get(cp.token));
        assert.deepEqual([row.principal, row.scope, row.state.legScope, (row.durableApproval || undefined)?.scope, row.rev ?? 0, row.status], ["bob", "bob", "bob", "bob", 1, "pending"]);
        assert.equal(checkpointIndexFacts(row).scope, "bob");
        assert.deepEqual(await store.listByScope("alice"), []);
        assert.deepEqual((await store.listByScope("bob")).map((s) => s.token), [cp.token]);
        if (store.listScopes !== undefined)
            assert.deepEqual(await store.listScopes(), ["bob"]);
        assert.equal(await store.resolve(cp.token, "alice", ALLOW), false, "the old scope no longer wins a CAS");
        assert.equal(await store.resolve(cp.token, "bob", ALLOW, { rev: 0 }), false, "a resume that read the row before the re-key loses");
        assert.deepEqual(await store.rekeyIdentity({ ...move, mode: "leave" }), { kind: "done", mode: "leave", rows: 0 });
        assert.equal(await store.resolve(cp.token, "bob", ALLOW, { rev: 1 }), true);
    });
    run("identity re-key: the candidate pre-screen misses no cell — a resource slice filed under a scope that is no name, and a row only its recorded partition holds", async () => {
        const store = make();
        const slice = fixtureWithState({ scope: "res\nscope", principal: "carol", durableApproval: { scope: "alice" }, sessionId: "rekey-slice" }, { legScope: "alice" });
        const partition = createCheckpointFixture({ scope: "tenant-x", principal: "carol", isolationScope: "alice", sessionId: "rekey-partition" });
        for (const row of [slice, partition])
            await store.put(row.token, row);
        const move = { fromPrincipal: "alice", toPrincipal: "bob", scopes: [{ fromScope: "alice", toScope: "bob" }, { fromScope: "res\nscope", toScope: "bob-slice" }] };
        assert.deepEqual(await store.rekeyIdentity({ ...move, mode: "leave" }), { kind: "done", mode: "leave", rows: 2 });
        const s = (await store.get(slice.token));
        assert.deepEqual([s.principal, s.scope, s.state.legScope, (s.durableApproval || undefined)?.scope, s.rev ?? 0], ["carol", "bob-slice", "bob", "bob", 1]);
        const p = (await store.get(partition.token));
        assert.deepEqual([p.principal, p.scope, p.isolationScope, p.rev ?? 0], ["carol", "tenant-x", "bob", 1]);
    });
    run("identity re-key: a steer filed before and one filed after a leave both stay; a leave racing a resolve ends as one of the two orders", async () => {
        const store = make();
        const cp = createCheckpointFixture({ scope: "alice", principal: "alice", sessionId: "rekey-steer" });
        await store.put(cp.token, cp);
        const move = { fromPrincipal: "alice", toPrincipal: "bob", scopes: [{ fromScope: "alice", toScope: "bob" }] };
        assert.equal(await store.setPendingSteer(cp.token, "alice", { text: "before", trusted: false }), true);
        await store.rekeyIdentity({ ...move, mode: "leave" });
        assert.equal(await store.setPendingSteer(cp.token, "bob", { text: "after", trusted: false }), true);
        assert.deepEqual(readPendingSteerQueue((await store.get(cp.token)).state).map((e) => e.text), ["before", "after"]);
        const racing = make();
        const raced = createCheckpointFixture({ scope: "tenant-a", principal: "alice", sessionId: "rekey-race" });
        await racing.put(raced.token, raced);
        const [, won] = await Promise.all([racing.rekeyIdentity({ fromPrincipal: "alice", toPrincipal: "bob", scopes: [], mode: "leave" }), racing.resolve(raced.token, "tenant-a", ALLOW, { rev: 0 })]);
        const after = (await racing.get(raced.token));
        assert.deepEqual([after.principal, after.isolationScope, after.status, after.rev ?? 0], won ? ["bob", "alice", "resolved", 2] : ["bob", "alice", "pending", 1]);
    });
    await settle();
}
const sortByToken = (a, b) => a.token.localeCompare(b.token);
export async function checkpointListByScopeSummaries(store) {
    if (typeof store.listByScope !== "function") {
        throw new Error("backend does not implement listByScope — required for checkpointListByScopeSummaries");
    }
    const escalation = createCheckpointFixture({
        token: "tok-escalation",
        scope: "tenant-a",
        sessionId: "needs-approval",
        deadline: 1_999_999_999_999,
        createdAt: 1_700_000_000_000,
        sourceSessionId: "needs-approval",
        principal: "alice@corp",
        gate: {
            kind: "human",
            reason: "approve",
            toolName: "open_pr",
            riskDescriptor: { severity: 5, axes: { egress: true, irreversible: true }, toolName: "open_pr" },
        },
        pendingAction: unhashedCall({
            kind: "tool_approval",
            origin: "policy",
            mandated: true,
            mandate: "tool_marks",
            boundGrantAbsence: "not_bindable",
            toolCallId: "call-pr",
            toolName: "open_pr",
            args: { repo: "x" },
            batchToolCallIds: ["call-pr"],
            completedCallIds: [],
        }),
    });
    const resource = createCheckpointFixture({
        token: "tok-resource",
        scope: "tenant-a",
        sessionId: "out-of-budget",
        createdAt: 1_700_000_000_001,
        gate: { kind: "resource_limit", reason: "budget_tokens" },
        pendingAction: { kind: "resource_limit", reason: "budget_tokens" },
        resourceLedger: { totalBudgetMicroUsd: 10_000_000, spentMicroUsd: 4_200_000, spentTokens: 9, spentTurns: 3, sliceCount: 2 },
    });
    const resolved = createCheckpointFixture({ token: "tok-resolved", scope: "tenant-a", sessionId: "done" });
    const other = createCheckpointFixture({ token: "tok-other", scope: "tenant-b", sessionId: "x" });
    const fixture = [escalation, resource, resolved, other];
    for (const cp of fixture)
        await store.put(cp.token, cp);
    await store.resolve(resolved.token, resolved.scope, ALLOW);
    return (await store.listByScope("tenant-a")).sort(sortByToken);
}
export const EXPECTED_LISTBYSCOPE_SUMMARIES = [
    {
        token: "tok-escalation",
        rowVerdict: { kind: "ok" },
        sessionId: "needs-approval",
        scope: "tenant-a",
        gateKind: "human",
        severity: 5,
        deadline: 1_999_999_999_999,
        createdAt: 1_700_000_000_000,
        sourceSessionId: "needs-approval",
        principal: "alice@corp",
        toolCallId: "call-pr",
        toolName: "open_pr",
        toolInput: '{"repo":"x"}',
        mandated: true,
        mandate: "tool_marks",
        origin: "policy",
        boundGrantAbsence: "not_bindable",
    },
    {
        token: "tok-resource",
        rowVerdict: { kind: "ok" },
        sessionId: "out-of-budget",
        scope: "tenant-a",
        gateKind: "resource_limit",
        resourceLimit: { reason: "budget_tokens" },
        spentMicroUsd: 4_200_000,
        createdAt: 1_700_000_000_001,
    },
];