UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

667 lines • 50.3 kB
import { strict as assert } from "node:assert";
import { BACKGROUND_AGENT_ROW_MALFORMED_CODE, STALE_RUNNING_REAP_ATTRIBUTION, } from "../background-agent-store.js";
import { CLAMP_SEATS, CLAMP_SET } from "../child-clamp-seats.js";
import { ANONYMOUS_SCOPE } from "../isolation-scope.js";
import { beginContract } from "./contract-harness.js";
import { thrownText } from "../thrown-value.js";
const readRows = (rows) => rows.filter((r) => !("rowVerdict" in r));
export const BACKGROUND_AGENT_CONTRACT_SCOPE = "tenant-A";
function record(over = {}) {
    return {
        handle: "a0000000000000001",
        scope: BACKGROUND_AGENT_CONTRACT_SCOPE,
        owner: "task-1",
        sessionScoped: false,
        parentSessionId: "sess-1",
        name: "contract-agent",
        writerId: "writer-1",
        spawnedAt: 1_000,
        updatedAt: 1_000,
        status: "running",
        rev: 0,
        ...over,
    };
}
async function withStores(mk, fn) {
    const live = [];
    const make = () => {
        const s = mk();
        live.push(s);
        return s;
    };
    try {
        await fn(make);
    }
    finally {
        for (const s of live.splice(0))
            s.close?.();
    }
}
async function held(store, handle, scope = BACKGROUND_AGENT_CONTRACT_SCOPE) {
    const row = await store.get(handle, scope);
    assert.notEqual(row, null, `row ${handle} should exist in scope ${scope}`);
    return row;
}
const codeOf = (e) => (typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined);
export async function backgroundAgentStoreContract(mk, runAssertion, hooks) {
    if (hooks !== undefined && hooks.plantRow === undefined && (hooks.unplantable === undefined || hooks.unplantable.trim() === "")) {
        throw new TypeError("backgroundAgentStoreContract: pass plantRow, or declare unplantable with the reason this backend keeps no bytes a foreign writer could damage");
    }
    const { run: runRaw, settle } = beginContract(runAssertion);
    const run = (name, fn) => runRaw(name, () => withStores(mk, fn));
    const S = BACKGROUND_AGENT_CONTRACT_SCOPE;
    run("put is create-once and scope-partitioned; get round-trips the row and is null cross-scope", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", finalOutput: "result-text" }));
        await assert.rejects(store.put(record({ handle: "a1" })), (e) => e.code === "agent_record.already_exists", "a second put under the same (handle, scope) must throw the typed already_exists error");
        await store.put(record({ handle: "a1", scope: "tenant-B" }));
        const row = await held(store, "a1");
        assert.equal(row.finalOutput, "result-text");
        assert.equal(row.owner, "task-1");
        assert.equal(await store.get("a1", "tenant-C"), null, "an unrelated scope must not see the row");
        assert.equal(await store.get("a-missing", S), null);
    });
    run("the org-admission fields round-trip, and ABSENT stays absent (a backend must not invent a verdict)", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", admittedOrgScopes: ["org:acme", "org:beta"], admittedOrgWriteScope: "org:acme" }));
        const withVerdict = await held(store, "a1");
        assert.deepEqual(withVerdict.admittedOrgScopes, ["org:acme", "org:beta"]);
        assert.equal(withVerdict.admittedOrgWriteScope, "org:acme");
        await store.put(record({ handle: "a2", admittedOrgScopes: [], admittedOrgWriteScope: null }));
        const readOnly = await held(store, "a2");
        assert.deepEqual(readOnly.admittedOrgScopes, []);
        assert.equal(readOnly.admittedOrgWriteScope, null);
        await store.put(record({ handle: "a3" }));
        const untouched = await held(store, "a3");
        assert.equal(untouched.admittedOrgScopes, undefined);
        assert.equal(untouched.admittedOrgWriteScope, undefined);
        await store.update("a3", S, { ...untouched, admittedOrgScopes: ["org:acme"], admittedOrgWriteScope: null }, { rev: untouched.rev });
        const afterCas = await held(store, "a3");
        assert.deepEqual(afterCas.admittedOrgScopes, ["org:acme"]);
        assert.equal(afterCas.admittedOrgWriteScope, null);
    });
    run("the birth floor round-trips verbatim — `{}` stays `{}`, ABSENT stays absent, a CAS carries it", async (make) => {
        const store = make();
        const restricting = Object.fromEntries(CLAMP_SEATS.flatMap((seat) => {
            const row = CLAMP_SET[seat];
            if (row.law !== "restricting")
                return [];
            const field = row.field;
            return [[seat, field === undefined ? row.value : { [field]: row.value }]];
        }));
        const floor = { ...restricting, readDenyPatterns: [".ssh", { pattern: "Secrets", caseSensitive: true }] };
        await store.put(record({ handle: "a1", policyFloor: floor }));
        assert.deepEqual((await held(store, "a1")).policyFloor, floor);
        await store.put(record({ handle: "a2", policyFloor: {} }));
        assert.deepEqual((await held(store, "a2")).policyFloor, {}, "an empty floor is a statement — it must not read back absent");
        await store.put(record({ handle: "a3" }));
        const untouched = await held(store, "a3");
        assert.equal(untouched.policyFloor, undefined, "a row that states no floor must not read back with one");
        for (const handle of ["a1", "a2"]) {
            const before = await held(store, handle);
            assert.equal(await store.update(handle, S, { ...before, status: "completed", settledAt: 2_000 }, { rev: before.rev }), true, `a CAS on a floor-bearing row (${handle}) must land`);
            const after = await held(store, handle);
            assert.equal(after.status, "completed");
            assert.equal(after.rev, before.rev + 1);
            assert.deepEqual(after.policyFloor, before.policyFloor, `a CAS update must carry the floor it did not change (${handle})`);
        }
    });
    run("the agent's birth delegation depth round-trips — ABSENT stays absent, a CAS carries it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", spawnDepth: 2 }));
        const withDepth = await held(store, "a1");
        assert.equal(withDepth.spawnDepth, 2);
        await store.put(record({ handle: "a2" }));
        assert.equal((await held(store, "a2")).spawnDepth, undefined, "a row that records no depth must not read back with one");
        const after = { ...withDepth, status: "completed", settledAt: 2_000 };
        assert.equal(await store.update("a1", S, after, { rev: withDepth.rev }), true, "a CAS on a depth-bearing row must land");
        assert.equal((await held(store, "a1")).spawnDepth, 2, "a CAS update must carry the depth it did not change");
    });
    run("the agent's birth in a ledger run round-trips — ABSENT stays absent, a CAS carries it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", bornInLedgerRun: true }));
        const born = await held(store, "a1");
        assert.equal(born.bornInLedgerRun, true);
        await store.put(record({ handle: "a2" }));
        assert.equal((await held(store, "a2")).bornInLedgerRun, undefined, "a row that records no birth must not read back with one");
        const after = { ...born, status: "completed", settledAt: 2_000 };
        assert.equal(await store.update("a1", S, after, { rev: born.rev }), true, "a CAS on a row that records its birth must land");
        assert.equal((await held(store, "a1")).bornInLedgerRun, true, "a CAS update must carry the birth it did not change");
        await store.put(record({ handle: "a3", bornInLedgerRun: true, status: "parked", parkedCheckpointToken: "cp-1", parkedAt: 1_500 }));
        const parked = await held(store, "a3");
        const guard = { rev: parked.rev, status: "parked", parkedCheckpointToken: "cp-1", parkClaimId: null };
        assert.equal(await store.updateIf("a3", S, { ...parked, parkClaimId: "claim-1" }, guard), true, "the park claim's guarded CAS must land");
        assert.equal((await held(store, "a3")).bornInLedgerRun, true, "the park claim's guarded CAS must carry the birth it did not change");
        const claimed = await held(store, "a3");
        const { parkedCheckpointToken: _token, parkedAt: _at, ...running } = { ...claimed, status: "running" };
        assert.equal(await store.updateIf("a3", S, running, { rev: claimed.rev, status: "parked", parkedCheckpointToken: "cp-1", parkClaimId: "claim-1" }), true, "the consume flip's guarded CAS must land");
        assert.equal((await held(store, "a3")).bornInLedgerRun, true, "the consume flip must carry the birth it did not change");
    });
    run("the root anchor's occupant round-trips beside the anchor — ABSENT stays absent, a CAS carries it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", rootSessionId: "sess-root", rootSessionIncarnation: "occ-root-1" }));
        const withOccupant = await held(store, "a1");
        assert.equal(withOccupant.rootSessionId, "sess-root");
        assert.equal(withOccupant.rootSessionIncarnation, "occ-root-1");
        await store.put(record({ handle: "a2", rootSessionId: "sess-root" }));
        const without = await held(store, "a2");
        assert.equal(without.rootSessionIncarnation, undefined, "a row that records no root occupant must not read back with one");
        const after = { ...withOccupant, status: "completed", settledAt: 2_000 };
        assert.equal(await store.update("a1", S, after, { rev: withOccupant.rev }), true);
        assert.equal((await held(store, "a1")).rootSessionIncarnation, "occ-root-1", "a CAS update must carry the root occupant it did not change");
    });
    run("the root anchor's box scope round-trips beside the anchor — ABSENT stays absent, a CAS carries it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", rootSessionId: "sess-root", rootSessionIncarnation: "occ-root-1", rootSessionScope: "box-scope" }));
        const withScope = await held(store, "a1");
        assert.equal(withScope.rootSessionScope, "box-scope");
        await store.put(record({ handle: "a2", rootSessionId: "sess-root" }));
        assert.equal((await held(store, "a2")).rootSessionScope, undefined, "a row that records no box scope must not read back with one");
        assert.equal(await store.update("a1", S, { ...withScope, status: "completed", settledAt: 2_000 }, { rev: withScope.rev }), true);
        assert.equal((await held(store, "a1")).rootSessionScope, "box-scope", "a CAS update must carry the box scope it did not change");
    });
    run("the member outcome round-trips whole — ABSENT stays absent, a CAS carries it", async (make) => {
        const store = make();
        const outcome = {
            kind: "background_agent",
            provenance: "live",
            outcome: "completed",
            refused: { unansweredAsks: { listed: [{ toolName: "wipe", toolCallId: "c1", cause: "no_approver_wired", remedy: "approve it live" }], unlisted: 2 }, haltedByPerson: true },
        };
        await store.put(record({ handle: "a1", status: "completed", outcome }));
        const withOutcome = await held(store, "a1");
        assert.deepEqual(withOutcome.outcome, outcome);
        await store.put(record({ handle: "a2" }));
        assert.equal((await held(store, "a2")).outcome, undefined, "a row that records no outcome must not read back with one");
        assert.equal(await store.update("a1", S, { ...withOutcome, settledAt: 2_000 }, { rev: withOutcome.rev }), true);
        assert.deepEqual((await held(store, "a1")).outcome, outcome, "a CAS update must carry the outcome it did not change");
    });
    run("put refuses a scopeless row (a row with no tenant partition would be world-readable)", async (make) => {
        const store = make();
        await assert.rejects(store.put(record({ scope: "" })), "an empty scope must be refused loudly, not stored");
    });
    run("a row carrying a key this build does not declare round-trips: no refusal, every declared field intact", async (make) => {
        const store = make();
        await store.put({ ...record({ handle: "a-extra", name: "worker", agentType: "reader" }), teamName: "retired-column" });
        const row = await held(store, "a-extra");
        assert.equal(row.name, "worker");
        assert.equal(row.agentType, "reader");
        assert.equal(row.status, "running");
        await store.update("a-extra", S, { ...row, status: "completed" }, { rev: row.rev });
        assert.equal((await held(store, "a-extra")).status, "completed", "a CAS update over such a row still lands");
    });
    run("get returns DETACHED copies: mutating a read never reaches the stored row", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", usage: { totalTokens: 5 } }));
        const first = await held(store, "a1");
        first.status = "failed";
        first.usage.totalTokens = 999;
        const second = await held(store, "a1");
        assert.equal(second.status, "running");
        assert.equal(second.usage?.totalTokens, 5);
    });
    run("update is a rev-CAS: stale rev loses, wrong scope loses, the winner bumps rev by EXACTLY 1", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1" }));
        const row = await held(store, "a1");
        assert.equal(await store.update("a1", "tenant-B", { ...row, status: "completed" }, { rev: row.rev }), false, "wrong scope");
        assert.equal(await store.update("a1", S, { ...row, status: "completed" }, { rev: row.rev + 5 }), false, "rev ahead");
        assert.equal(await store.update("a-missing", S, { ...row, status: "completed" }, { rev: row.rev }), false, "missing row");
        assert.equal(await store.update("a1", S, { ...row, status: "completed" }, { rev: row.rev }), true);
        const after = await held(store, "a1");
        assert.equal(after.status, "completed");
        assert.equal(after.rev, row.rev + 1);
        assert.equal(await store.update("a1", S, { ...row, status: "failed" }, { rev: row.rev }), false);
        assert.equal((await held(store, "a1")).status, "completed");
    });
    run("update keeps the KEY authoritative: a payload naming another handle/scope cannot repartition the row", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1" }));
        const row = await held(store, "a1");
        assert.equal(await store.update("a1", S, { ...row, handle: "a-other", scope: "tenant-B", status: "failed" }, { rev: row.rev }), true);
        const after = await held(store, "a1");
        assert.equal(after.handle, "a1", "the key's handle wins over the payload's");
        assert.equal(after.scope, S, "scope is the partition key and an update must never rewrite it");
        assert.equal(await store.get("a-other", "tenant-B"), null, "no second row may appear");
    });
    run("updateIf keeps the rev guard AND adds the field guards (status / checkpoint token / claim id)", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "parked", parkedCheckpointToken: "cp-1" }));
        const row = await held(store, "a1");
        assert.equal(await store.updateIf("a1", S, { ...row, status: "running" }, { rev: row.rev + 3 }), false, "stale rev");
        assert.equal(await store.updateIf("a1", S, { ...row, status: "running" }, { rev: row.rev, status: "running" }), false, "status mismatch");
        assert.equal(await store.updateIf("a1", S, { ...row, status: "running" }, { rev: row.rev, status: "parked", parkedCheckpointToken: "cp-OTHER" }), false, "checkpoint token mismatch");
        assert.equal(await store.updateIf("a1", S, { ...row, status: "running" }, { rev: row.rev, parkedCheckpointToken: null }), false, "null must mean 'this field is absent', and it is present");
        assert.equal(await store.updateIf("a1", S, { ...row, status: "running" }, { rev: row.rev, parkClaimId: "claim-1" }), false, "claim id expected but absent");
        const next = { ...row, status: "running", parkClaimId: "claim-1" };
        assert.equal(await store.updateIf("a1", S, next, { rev: row.rev, status: "parked", parkedCheckpointToken: "cp-1", parkClaimId: null }), true, "matching guards (incl. null-as-absent on the claim id) must win");
        const after = await held(store, "a1");
        assert.equal(after.status, "running");
        assert.equal(after.parkClaimId, "claim-1");
        assert.equal(after.rev, row.rev + 1);
    });
    run("listBySession anchors on (sessionScoped ? owner : parentSessionId) OR rootSessionId, newest-first", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", spawnedAt: 1_000, finalOutput: "SECRET", summary: "s", error: "e", recentSteps: [] }));
        await store.put(record({ handle: "a2", owner: "sess-1", sessionScoped: true, parentSessionId: undefined, spawnedAt: 2_000 }));
        await store.put(record({ handle: "a3", parentSessionId: "sess-mid", rootSessionId: "sess-1", spawnedAt: 3_000 }));
        await store.put(record({ handle: "a4", parentSessionId: "sess-other", spawnedAt: 4_000 }));
        const rows = await store.listBySession(S, "sess-1");
        assert.deepEqual(rows.map((r) => r.handle), ["a3", "a2", "a1"], "newest-first by spawnedAt");
        for (const row of rows) {
            for (const field of ["finalOutput", "summary", "error", "recentSteps", "editedFiles"]) {
                assert.equal(Object.hasOwn(row, field), false, `list projections must not carry ${field}`);
            }
        }
        assert.deepEqual((await store.listBySession(S, "sess-1", { limit: 2 })).map((r) => r.handle), ["a3", "a2"], "limit keeps the NEWEST n");
        assert.deepEqual(await store.listBySession("tenant-B", "sess-1"), [], "another tenant sees nothing");
        assert.deepEqual((await store.listBySession(S, "sess-mid")).map((r) => r.handle), ["a3"], "the intermediate anchor still lists its direct child");
    });
    run("a list summary carries the record's completion identity verbatim — identity, not content; ABSENT stays absent", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "completed", settledAt: 2_000, completionId: "cid-a1" }));
        await store.put(record({ handle: "a2", status: "running", spawnedAt: 2_000 }));
        for (const rows of [await store.listBySession(S, "sess-1"), await store.listByScope(S)]) {
            const settled = rows.find((r) => r.handle === "a1");
            const running = rows.find((r) => r.handle === "a2");
            assert.notEqual(settled, undefined);
            assert.notEqual(running, undefined);
            assert.equal("rowVerdict" in settled ? undefined : settled.completionId, "cid-a1", "the summary must carry the record's completion identity unchanged");
            assert.equal(Object.hasOwn(running, "completionId"), false, "a row that records no completion identity must not list with one");
        }
    });
    run("a list summary carries the refusal record of the row's ending — ABSENT when it carries none; an earlier engine's asks list too", async (make) => {
        const ask = { toolName: "wipe", toolCallId: "call-1", cause: "no_approver_wired" };
        const store = make();
        await store.put(record({ handle: "a1", status: "completed", settledAt: 2_000, outcome: { kind: "background_agent", outcome: "completed", provenance: "live", refused: { unansweredAsks: { listed: [ask], unlisted: 3 } } } }));
        await store.put(record({ handle: "a2", status: "completed", settledAt: 2_000, spawnedAt: 2_000, outcome: { kind: "background_agent", outcome: "completed", provenance: "live" } }));
        await store.put(record({ handle: "a3", status: "completed", settledAt: 2_000, spawnedAt: 3_000, refusedAsks: [ask] }));
        await store.put(record({ handle: "a4", status: "running", spawnedAt: 4_000 }));
        await store.put(record({ handle: "a5", status: "parked", spawnedAt: 5_000, outcome: { kind: "background_agent", outcome: "parked", provenance: "live", refused: { unansweredAsks: { listed: [ask] } } } }));
        for (const rows of [await store.listBySession(S, "sess-1"), await store.listByScope(S), await store.listByRoot("sess-1")]) {
            const of = (handle) => {
                const row = readRows(rows).find((r) => r.handle === handle);
                assert.notEqual(row, undefined, `${handle} must list as a row that reads`);
                return row;
            };
            assert.deepEqual(of("a1").refused, { unansweredAsks: { listed: [ask], unlisted: 3 } }, "the summary must carry the ending's refusal record unchanged");
            assert.equal(Object.hasOwn(of("a2"), "refused"), false, "an ending that carries no refusal record must not list with one");
            assert.deepEqual(of("a3").refused, { unansweredAsks: { listed: [ask] } }, "a row an earlier engine wrote lists the asks it kept");
            assert.equal(Object.hasOwn(of("a4"), "refused"), false, "a running row must not list with one");
            assert.equal(Object.hasOwn(of("a5"), "refused"), false, "a parked row has not settled: it must not list with one, whatever it stores");
        }
    });
    run("the anonymous working scope is a scope like any other: a row filed under ANONYMOUS_SCOPE reads and lists under no other name, and a named tenant's row never under it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a-anon", scope: ANONYMOUS_SCOPE }));
        await store.put(record({ handle: "a-named", scope: "tenant-B" }));
        assert.equal(await store.get("a-anon", "tenant-B"), null);
        assert.equal(await store.get("a-named", ANONYMOUS_SCOPE), null);
        assert.equal((await store.get("a-anon", ANONYMOUS_SCOPE))?.handle, "a-anon");
        assert.deepEqual((await store.listByScope(ANONYMOUS_SCOPE)).map((r) => r.handle), ["a-anon"]);
        assert.deepEqual((await store.listByScope("tenant-B")).map((r) => r.handle), ["a-named"]);
    });
    run("listBySession/listByScope filter one status; listByScope enumerates the whole tenant", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "running", spawnedAt: 1_000 }));
        await store.put(record({ handle: "a2", status: "completed", spawnedAt: 2_000 }));
        await store.put(record({ handle: "a3", status: "completed", parentSessionId: "sess-other", spawnedAt: 3_000 }));
        await store.put(record({ handle: "a4", status: "completed", scope: "tenant-B", spawnedAt: 4_000 }));
        assert.deepEqual((await store.listByScope(S)).map((r) => r.handle), ["a3", "a2", "a1"], "scope-wide, newest-first");
        assert.deepEqual((await store.listByScope(S, { status: "completed" })).map((r) => r.handle), ["a3", "a2"]);
        assert.deepEqual((await store.listByScope(S, { status: "completed", limit: 1 })).map((r) => r.handle), ["a3"]);
        assert.deepEqual((await store.listBySession(S, "sess-1", { status: "completed" })).map((r) => r.handle), ["a2"]);
        assert.deepEqual((await store.listByScope("tenant-B")).map((r) => r.handle), ["a4"], "tenants are separate ledgers");
    });
    run("every list summary carries the scope its row lives in", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1" }));
        await store.put(record({ handle: "a2", scope: "tenant-B" }));
        assert.deepEqual(readRows(await store.listByScope(S)).map((r) => [r.handle, r.scope]), [["a1", S]]);
        assert.deepEqual(readRows(await store.listBySession("tenant-B", "sess-1")).map((r) => [r.handle, r.scope]), [["a2", "tenant-B"]]);
        assert.deepEqual(readRows(await store.listByRoot("sess-1")).map((r) => [r.handle, r.scope]).sort(), [["a1", S], ["a2", "tenant-B"]]);
    });
    run("listByRoot lists one delegation tree in EVERY scope by its root (rootSessionId ?? parentSessionId ?? session-scoped owner), newest-first", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", rootSessionId: "sess-1", spawnedAt: 1_000, finalOutput: "SECRET", summary: "s", error: "e", recentSteps: [] }));
        await store.put(record({ handle: "a2", scope: "tenant-B", owner: "sess-1", sessionScoped: true, parentSessionId: undefined, spawnedAt: 2_000 }));
        await store.put(record({ handle: "a3", parentSessionId: "sess-mid", rootSessionId: "sess-1", spawnedAt: 3_000 }));
        await store.put(record({ handle: "a4", spawnedAt: 4_000 }));
        await store.put(record({ handle: "a5", rootSessionId: "sess-other", spawnedAt: 5_000 }));
        await store.put(record({ handle: "a6", parentSessionId: "sess-other", spawnedAt: 6_000 }));
        await store.put(record({ handle: "a7", owner: "sess-1", parentSessionId: undefined, spawnedAt: 7_000 }));
        const rows = readRows(await store.listByRoot("sess-1"));
        assert.deepEqual(rows.map((r) => [r.handle, r.scope]), [["a4", S], ["a3", S], ["a2", "tenant-B"], ["a1", S]], "the whole tree, every scope, newest-first");
        for (const row of rows) {
            for (const field of ["finalOutput", "summary", "error", "recentSteps", "editedFiles"]) {
                assert.equal(Object.hasOwn(row, field), false, `list projections must not carry ${field}`);
            }
        }
        assert.deepEqual((await store.listByRoot("sess-1", { limit: 2 })).map((r) => r.handle), ["a4", "a3"], "limit keeps the NEWEST n");
        assert.deepEqual(await store.listByRoot("sess-mid"), [], "an intermediate session is not a tree root: its child's root is sess-1");
        assert.deepEqual((await store.listByRoot("sess-other")).map((r) => r.handle), ["a6", "a5"]);
        for (const row of rows)
            assert.equal(await store.delete(row.handle, row.scope), true, `${row.handle} is deleted in ${row.scope}`);
        assert.deepEqual(await store.listByRoot("sess-1"), []);
    });
    run("listByRoot filters one status like the other lists", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "running", spawnedAt: 1_000 }));
        await store.put(record({ handle: "a2", status: "completed", scope: "tenant-B", spawnedAt: 2_000 }));
        await store.put(record({ handle: "a3", status: "completed", spawnedAt: 3_000 }));
        assert.deepEqual((await store.listByRoot("sess-1", { status: "completed" })).map((r) => r.handle), ["a3", "a2"]);
        assert.deepEqual((await store.listByRoot("sess-1", { status: "completed", limit: 1 })).map((r) => r.handle), ["a3"]);
    });
    run("listByRoot refuses a root that is not a non-empty string of at most 256 characters without a control character", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", rootSessionId: "r".repeat(256) }));
        for (const bad of ["", "r".repeat(257), "sess\n1", "sess\u00001", "sess\u00851", 42, null, undefined, { id: "sess-1" }]) {
            await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.listByRoot, store, [bad])), (e) => e.code === "config.invalid_argument", `root ${typeof bad === "string" ? JSON.stringify(bad.length > 20 ? `${bad.slice(0, 8)}…(${bad.length})` : bad) : String(bad)} must be refused with config.invalid_argument`);
        }
        assert.deepEqual((await store.listByRoot("r".repeat(256))).map((r) => r.handle), ["a1"], "256 characters is a root");
        assert.deepEqual(await store.listByRoot("sess.1:x/y"), [], "a root is not held to the peer lane's id alphabet");
    });
    run("delete is row-precise and CONDITIONAL when a rev is supplied (a concurrent revival must win)", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "completed" }));
        await store.put(record({ handle: "a2", status: "completed" }));
        const row = await held(store, "a1");
        assert.equal(await store.delete("a1", S, { rev: row.rev + 1 }), false, "a stale rev must not delete");
        assert.notEqual(await store.get("a1", S), null);
        assert.equal(await store.delete("a1", "tenant-B"), false, "cross-scope delete is a miss");
        assert.equal(await store.delete("a1", S, { rev: row.rev }), true);
        assert.equal(await store.get("a1", S), null);
        assert.equal(await store.delete("a1", S), false, "deleting a gone row reports false, not true");
        assert.equal(await store.delete("a2", S), true, "an unconditional delete still works");
        await store.put(record({ handle: "a3", status: "completed" }));
        await store.settleErasure?.();
        await store.settleErasure?.();
        assert.equal(await store.get("a1", S), null);
        assert.equal(await store.get("a2", S), null);
        assert.notEqual(await store.get("a3", S), null, "the batch's end deletes nothing of its own");
    });
    run("deleteBySession deletes the session's TERMINAL rows in the scope — the rows listBySession names for it, by its parent or owner anchor or its root — and no other row; answers their handles; a repeat answers []", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "completed", spawnedAt: 1_000 }));
        await store.put(record({ handle: "a2", status: "failed", parentSessionId: "sess-mid", rootSessionId: "sess-1", spawnedAt: 2_000 }));
        await store.put(record({ handle: "a3", status: "killed", owner: "sess-1", sessionScoped: true, parentSessionId: undefined, spawnedAt: 3_000 }));
        await store.put(record({ handle: "a4", status: "running", spawnedAt: 4_000 }));
        await store.put(record({ handle: "a5", status: "parked", spawnedAt: 5_000 }));
        await store.put(record({ handle: "a6", status: "completed", parentSessionId: "sess-2", spawnedAt: 6_000 }));
        await store.put(record({ handle: "a7", status: "completed", scope: "tenant-B", spawnedAt: 7_000 }));
        const deleted = await store.deleteBySession(S, "sess-1");
        assert.deepEqual([...deleted].sort(), ["a1", "a2", "a3"], "the session's terminal rows of the scope, by every anchor listBySession reads");
        for (const handle of ["a1", "a2", "a3"])
            assert.equal(await store.get(handle, S), null, `${handle} is gone`);
        for (const handle of ["a4", "a5", "a6"])
            assert.notEqual(await store.get(handle, S), null, `${handle} stays`);
        assert.notEqual(await store.get("a7", "tenant-B"), null, "the same session's row in another scope stays");
        assert.deepEqual(readRows(await store.listBySession(S, "sess-1")).map((r) => r.handle).sort(), ["a4", "a5"], "listBySession names only the live rows after it");
        assert.deepEqual(await store.deleteBySession(S, "sess-1"), [], "a repeat deletes nothing");
        assert.deepEqual(await store.deleteBySession(S, "sess-none"), [], "a session with no rows deletes nothing");
    });
    run("reap with NO policy is a no-op (retention is always explicit)", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "completed", settledAt: 1_000 }));
        assert.equal(await store.reap(S, 100_000), 0);
        assert.equal(await store.reap(S, 100_000, {}), 0);
        assert.notEqual(await store.get("a1", S), null);
    });
    run("reap deletes terminal rows by age and by keep-bound; running and parked rows survive BOTH", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "completed", spawnedAt: 1_000, settledAt: 1_000 }));
        await store.put(record({ handle: "a2", status: "running", spawnedAt: 1_000, updatedAt: 1_000 }));
        await store.put(record({ handle: "a3", status: "parked", spawnedAt: 1_000, updatedAt: 1_000, parkedCheckpointToken: "cp-1" }));
        assert.equal(await store.reap(S, 100_000, { maxAgeMs: 10 }), 1, "only the terminal row ages out");
        assert.equal(await store.get("a1", S), null);
        assert.equal((await held(store, "a2")).status, "running");
        assert.equal((await held(store, "a3")).status, "parked");
        for (const i of [1, 2, 3])
            await store.put(record({ handle: `b${i}`, status: "completed", spawnedAt: 1_000 + i, settledAt: 2_000 + i }));
        assert.equal(await store.reap(S, 100_000, { keep: 2 }), 1);
        assert.deepEqual((await store.listByScope(S, { status: "completed" })).map((r) => r.handle), ["b3", "b2"]);
        assert.notEqual(await store.get("a2", S), null);
        assert.notEqual(await store.get("a3", S), null);
    });
    run("reap's stale-running arm flips to a terminal `failed` WITH the shared attribution, and never overwrites real failure text", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "running", updatedAt: 1_000 }));
        await store.put(record({ handle: "a2", status: "running", updatedAt: 1_000, error: "the child reported a real failure" }));
        assert.equal(await store.reap(S, 100_000, { staleRunningMaxAgeMs: 50_000 }), 2);
        const flipped = await held(store, "a1");
        assert.equal(flipped.status, "failed", "an interrupted host's row settles as a terminal, not a perpetual running");
        assert.equal(flipped.stoppedBy, "system");
        assert.equal(flipped.settledAt, 100_000);
        assert.equal(flipped.updatedAt, 100_000);
        assert.equal(flipped.error, STALE_RUNNING_REAP_ATTRIBUTION);
        assert.equal(flipped.summary, STALE_RUNNING_REAP_ATTRIBUTION);
        assert.equal((await held(store, "a2")).error, "the child reported a real failure");
        await store.put(record({ handle: "a3", status: "running", updatedAt: 99_000 }));
        assert.equal(await store.reap(S, 100_000, { staleRunningMaxAgeMs: 50_000 }), 0);
        assert.equal((await held(store, "a3")).status, "running");
    });
    run("reap's stale-running flip gives each row its own completion identity, and the summary replays it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "running", updatedAt: 1_000 }));
        await store.put(record({ handle: "a2", status: "running", updatedAt: 1_000, spawnedAt: 2_000 }));
        assert.equal(await store.reap(S, 100_000, { staleRunningMaxAgeMs: 50_000 }), 2);
        const first = await held(store, "a1");
        const second = await held(store, "a2");
        for (const row of [first, second]) {
            assert.equal(typeof row.completionId, "string", `the flipped row ${row.handle} must carry a completion identity`);
            assert.notEqual(row.completionId, "", `the flipped row ${row.handle} must carry a non-empty completion identity`);
        }
        assert.notEqual(first.completionId, second.completionId, "two completions, two identities");
        const listed = await store.listByScope(S);
        assert.equal(((a1) => (a1 === undefined || "rowVerdict" in a1 ? undefined : a1.completionId))(listed.find((r) => r.handle === "a1")), first.completionId, "the summary replays the flipped row's identity");
    });
    run("reap counts each ROW once even when the same sweep flips it AND removes it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", status: "running", spawnedAt: 1_000, updatedAt: 1_000 }));
        assert.equal(await store.reap(S, 100_000, { staleRunningMaxAgeMs: 50_000, keep: 0 }), 1, "one row changed, so the count is 1");
        assert.equal(await store.get("a1", S), null, "and it really is gone (flipped, then trimmed)");
    });
    const plantRow = hooks?.plantRow;
    if (plantRow !== undefined) {
        const SENTINEL = "planted-marker-1023";
        const BAD = "a0000000000000001";
        const GOOD = "a0000000000000002";
        const forged = (over) => ({ ...JSON.parse(JSON.stringify(record({ handle: BAD, agentType: SENTINEL }))), ...over });
        const damaged = [
            ["owner retyped", { owner: 42 }],
            ["status outside the set", { status: "paused-later" }],
            ["rev not a count", { rev: "7" }],
            ["sessionScoped not a boolean", { sessionScoped: "yes" }],
        ];
        for (const [what, over] of damaged) {
            run(`damaged row (${what}): listed as its handle and verdict, the other row intact; get and update refuse in the family code quoting nothing planted; the stale sweep leaves it; delete by handle removes it`, async (make) => {
                const seeded = make();
                await seeded.put(record({ handle: GOOD, spawnedAt: 2_000 }));
                const s = await plantRow(seeded, { handle: BAD, scope: S }, forged(over));
                try {
                    const listed = await s.listByScope(S);
                    assert.deepEqual(listed.map((x) => x.handle), [GOOD, BAD]);
                    const bad = listed[1];
                    assert.ok("rowVerdict" in bad && bad.rowVerdict.code === BACKGROUND_AGENT_ROW_MALFORMED_CODE, "the planted row is listed as damaged");
                    assert.ok(!JSON.stringify(listed).includes(SENTINEL), "the listing carries no planted value");
                    const refused = (e) => codeOf(e) === BACKGROUND_AGENT_ROW_MALFORMED_CODE && !thrownText(e).includes(SENTINEL);
                    await assert.rejects(s.get(BAD, S), refused, "get refuses in the family code");
                    await assert.rejects(s.update(BAD, S, record({ handle: BAD, status: "completed" }), { rev: 0 }), refused, "update refuses in the family code");
                    await s.reap(S, 1e12, { staleRunningMaxAgeMs: 0 });
                    assert.equal((await s.listByScope(S)).filter((x) => "rowVerdict" in x).length, 1, "the stale sweep leaves it as stored");
                    assert.equal(await s.delete(BAD, S), true, "deletion by its handle goes on");
                    assert.deepEqual((await s.listByScope(S)).map((x) => x.handle), [GOOD]);
                }
                finally {
                    s.close?.();
                }
            });
        }
    }
    const FROM = "tenant-rekey-from";
    const TO = "tenant-rekey-to";
    run("rekeyScope plan → arrive → leave re-files a row: the copy carries the new scope and rev + 1 with every other member as stored, and leave removes the source", async (make) => {
        const store = make();
        assert.equal(typeof store.rekeyScope, "function");
        await store.put(record({ handle: "a1", scope: FROM, owner: "task-9", writerEpoch: 3, finalOutput: "kept", rev: 4 }));
        await store.put(record({ handle: "a2", scope: "tenant-elsewhere" }));
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" }), { kind: "plan", rows: 1, conflicting: 0 });
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 1 });
        const source = await held(store, "a1", FROM);
        const copy = await held(store, "a1", TO);
        assert.deepEqual(copy, { ...source, scope: TO, rev: source.rev + 1 }, "owner, writer fields and history are not the axis");
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" }), { kind: "done", mode: "leave", rows: 1 });
        assert.equal(await store.get("a1", FROM), null);
        assert.deepEqual(await held(store, "a1", TO), copy);
        assert.notEqual(await store.get("a2", "tenant-elsewhere"), null, "another scope's row is not the source's");
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" }), { kind: "plan", rows: 0, conflicting: 0 });
    });
    run("every rekeyScope step re-run writes nothing more, and a move onto the same scope moves nothing", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", scope: FROM }));
        await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" });
        const copy = await held(store, "a1", TO);
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 1 });
        assert.deepEqual(await held(store, "a1", TO), copy, "the arrival is recognized, not filed again");
        await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" });
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" }), { kind: "done", mode: "leave", rows: 0 });
        assert.deepEqual(await store.rekeyScope({ fromScope: TO, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 0 });
        assert.deepEqual(await held(store, "a1", TO), copy);
    });
    run("a target row that is not the arrival makes arrive a conflict with nothing written; withdraw deletes only an arrival", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", scope: FROM }));
        await store.put(record({ handle: "a2", scope: FROM }));
        await store.put(record({ handle: "a2", scope: TO, finalOutput: "the target's own row" }));
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" }), { kind: "plan", rows: 2, conflicting: 1 });
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }), { kind: "conflict", mode: "arrive", rows: 2, conflicting: 1 });
        assert.equal(await store.get("a1", TO), null, "a conflicting call files no row at all");
        assert.equal((await held(store, "a2", TO)).finalOutput, "the target's own row");
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "withdraw" }), { kind: "done", mode: "withdraw", rows: 0 });
        assert.equal((await held(store, "a2", TO)).finalOutput, "the target's own row", "withdraw never deletes a row that is not the arrival");
    });
    run("withdraw deletes the arrival and leaves the source as it was", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", scope: FROM }));
        const before = await held(store, "a1", FROM);
        await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" });
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "withdraw" }), { kind: "done", mode: "withdraw", rows: 1 });
        assert.equal(await store.get("a1", TO), null);
        assert.deepEqual(await held(store, "a1", FROM), before);
    });
    run("a source row updated after arrive is not left: its arrival no longer matches, and a plan reports it", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", scope: FROM }));
        await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" });
        const live = await held(store, "a1", FROM);
        assert.equal(await store.update("a1", FROM, { ...live, status: "completed" }, { rev: live.rev }), true);
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" }), { kind: "done", mode: "leave", rows: 0 });
        assert.equal((await held(store, "a1", FROM)).status, "completed", "the confirmed write is not lost");
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" }), { kind: "plan", rows: 1, conflicting: 1 });
    });
    run("the rekeyScope input is read before anything else: a malformed one is a TypeError and nothing is written", async (make) => {
        const store = make();
        const unchecked = store;
        await store.put(record({ handle: "a1", scope: FROM }));
        const bad = [
            undefined,
            { fromScope: FROM, toScope: TO },
            { fromScope: FROM, toScope: TO, mode: "apply" },
            { fromScope: FROM, toScope: TO, mode: "plan", dryRun: false },
            { fromScope: "", toScope: TO, mode: "arrive" },
            { fromScope: FROM, toScope: 7, mode: "arrive" },
        ];
        for (const input of bad)
            await assert.rejects(unchecked.rekeyScope(input), TypeError, JSON.stringify(input) ?? "undefined");
        assert.equal(await store.get("a1", TO), null);
    });
    run("put refuses a row whose scope is not a non-empty string — the one scope reading the re-key input reads too", async (make) => {
        const store = make();
        const unchecked = store;
        await assert.rejects(unchecked.put({ ...record(), scope: 7 }), (e) => codeOf(e) === BACKGROUND_AGENT_ROW_MALFORMED_CODE);
        await assert.rejects(unchecked.put({ ...record(), scope: "" }), (e) => codeOf(e) === BACKGROUND_AGENT_ROW_MALFORMED_CODE && /without a scope/.test(thrownText(e)));
    });
    run("rekeyScope moves only the rows filed under fromScope: a scope that begins with the same characters, and another scope, keep theirs", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", scope: FROM }));
        await store.put(record({ handle: "a2", scope: `${FROM}-extra` }));
        await store.put(record({ handle: "a3", scope: "tenant-elsewhere" }));
        const kept = [await held(store, "a2", `${FROM}-extra`), await held(store, "a3", "tenant-elsewhere")];
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" }), { kind: "plan", rows: 1, conflicting: 0 });
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 1 });
        assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" }), { kind: "done", mode: "leave", rows: 1 });
        assert.deepEqual([await held(store, "a2", `${FROM}-extra`), await held(store, "a3", "tenant-elsewhere")], kept, "their rows as they were");
        assert.equal(await store.get("a2", TO), null);
        assert.equal(await store.get("a3", TO), null);
    });
    if (plantRow !== undefined) {
        const MARK = "planted-marker-rekey";
        const READS = "a0000000000000002";
        const DAMAGED = "a0000000000000001";
        const damagedRow = (handle, scope) => ({ ...JSON.parse(JSON.stringify(record({ handle, scope, agentType: MARK }))), owner: 42 });
        const bothScopes = async (s) => JSON.stringify([await s.listByScope(FROM), await s.listByScope(TO)]);
        const refusedStep = (e) => codeOf(e) === BACKGROUND_AGENT_ROW_MALFORMED_CODE && !thrownText(e).includes(MARK);
        const everyStep = (s) => [
            ["plan", () => s.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" })],
            ["arrive", () => s.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" })],
            ["leave", () => s.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" })],
            ["withdraw", () => s.rekeyScope({ fromScope: FROM, toScope: TO, mode: "withdraw" })],
        ];
        run("rekeyScope over a source row that does not read: every step refuses in the family code, and neither scope changes by a byte", async (make) => {
            const seeded = make();
            await seeded.put(record({ handle: READS, scope: FROM }));
            const s = await plantRow(seeded, { handle: DAMAGED, scope: FROM }, damagedRow(DAMAGED, FROM));
            try {
                const before = await bothScopes(s);
                for (const [mode, step] of everyStep(s)) {
                    await assert.rejects(step(), refusedStep, mode);
                    assert.equal(await bothScopes(s), before, `${mode}: both scopes as they were`);
                }
                assert.equal(await s.get(READS, TO), null, "the row that reads did not move either");
            }
            finally {
                s.close?.();
            }
        });
        run("rekeyScope onto a target row that does not read: every step refuses in the family code, and neither scope changes by a byte", async (make) => {
            const seeded = make();
            await seeded.put(record({ handle: READS, scope: FROM }));
            const s = await plantRow(seeded, { handle: READS, scope: TO }, damagedRow(READS, TO));
            try {
                const before = await bothScopes(s);
                for (const [mode, step] of everyStep(s)) {
                    await assert.rejects(step(), refusedStep, mode);
                    assert.equal(await bothScopes(s), before, `${mode}: both scopes as they were`);
                }
            }
            finally {
                s.close?.();
            }
        });
    }
    await settle();
}
export async function backgroundAgentStoreScopesContract(mk, runAssertion) {
    const { run: runRaw, settle } = beginContract(runAssertion);
    const run = (name, fn) => runRaw(name, () => withStores(mk, fn));
    run("listScopes enumerates the scopes that currently HOLD rows, deduplicated and sorted", async (make) => {
        const store = make();
        assert.equal(typeof store.listScopes, "function", "this layer is only for backends that implement listScopes");
        await store.put(record({ handle: "a1", scope: "tenant-B" }));
        await store.put(record({ handle: "a2", scope: "tenant-A" }));
        await store.put(record({ handle: "a3", scope: "tenant-A" }));
        assert.deepEqual(await store.listScopes(), ["tenant-A", "tenant-B"], "deduplicated and sorted — a retention loop drives itself off this");
        await store.delete("a1", "tenant-B");
        assert.deepEqual(await store.listScopes(), ["tenant-A"]);
    });
    run("listScopes follows a re-key: both scopes while the rows are in two places, only the target once they left", async (make) => {
        const store = make();
        await store.put(record({ handle: "a1", scope: "tenant-from" }));
        await store.rekeyScope({ fromScope: "tenant-from", toScope: "tenant-to", mode: "arrive" });
        assert.deepEqual(await store.listScopes(), ["tenant-from", "tenant-to"]);
        await store.rekeyScope({ fromScope: "tenant-from", toScope: "tenant-to", mode: "leave" });
        assert.deepEqual(await store.listScopes(), ["tenant-to"]);
    });
    await settle();
}