UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

522 lines (521 loc) • 35.5 kB
import { strict as assert } from "node:assert"; import { ANONYMOUS_SCOPE } from "../isolation-scope.js"; import { PEER_TASK_ALREADY_EXISTS_CODE, PEER_TASK_DELIVERY_REGRESSION_CODE, PEER_TASK_ROW_MALFORMED_CODE, isPeerTaskSettledStatus, peerTaskRequestDigest, } from "../peer-task-store.js"; import { thrownText } from "../thrown-value.js"; import { beginContract } from "./contract-harness.js"; export const PEER_TASK_CONTRACT_SCOPE = "tenant-A"; const DEFAULT_PARAMS_JSON = JSON.stringify({ message: { role: "user", kind: "message", messageId: "msg-00000000-0000-4000-8000-000000000001", parts: [{ kind: "text", text: "reconcile invoice #1" }], }, configuration: { blocking: false }, }); export function createPeerTaskRowFixture(over = {}) { const request = over.request ?? { paramsJson: DEFAULT_PARAMS_JSON }; const requestDigest = over.requestDigest ?? peerTaskRequestDigest(request.paramsJson); const status = over.status ?? "running"; const settled = isPeerTaskSettledStatus(status); const row = { task_id: "p0000000000000001", scope: PEER_TASK_CONTRACT_SCOPE, rev: 0, owner: "task-1", sessionScoped: false, parentSessionId: "sess-1", type: "peer_task", destination: { kind: "a2a_peer", peer: "billing", boundary: "inside" }, skillId: "reconcile", messageId: "msg-00000000-0000-4000-8000-000000000001", request, requestDigest, submittedAt: 1_000, delivery: "recorded", followUps: "accepted", cancel: "not_requested", ackBy: 11_000, finalBy: 61_000, approvalWaitMs: 300_000, fallback: "stop_and_report", lastSeq: 0, status, ...(settled ? { settledAt: 2_000, outcome: { kind: "peer_task", outcome: status, provenance: "live" } } : { waitingFor: "unknown" }), ...over, }; if (!("requestDigest" in over)) row.requestDigest = requestDigest; if (settled && !("waitingFor" in over)) delete row.waitingFor; if (!settled && !("outcome" in over)) delete row.outcome; return row; } const readRows = (rows) => rows.filter((r) => !("rowVerdict" in r)); const codeOf = (e) => (typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined); const pid = (n) => `p${n.toString(16).padStart(16, "0")}`; 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, taskId, scope = PEER_TASK_CONTRACT_SCOPE) { const row = await store.get(taskId, scope); assert.notEqual(row, null, `row ${taskId} should exist in scope ${scope}`); return row; } export async function peerTaskStoreContract(mk, runAssertion, hooks) { if (hooks !== undefined && (hooks === null || typeof hooks !== "object")) { throw new TypeError(`peerTaskStoreContract: hooks must be an object (plantRow, or unplantable with a reason) or left out; got ${hooks === null ? "null" : typeof hooks}`); } if (hooks !== undefined && hooks.plantRow === undefined && (hooks.unplantable === undefined || hooks.unplantable.trim() === "")) { throw new TypeError("peerTaskStoreContract: pass plantRow, or declare unplantable with a non-empty reason"); } const { run: runRaw, settle } = beginContract(runAssertion); const run = (name, fn) => runRaw(name, () => withStores(mk, fn)); const S = PEER_TASK_CONTRACT_SCOPE; run("put is create-once, enforces rev 0 and valid scope/digest, partitions by scope, and round-trips full and minimal rows", async (make) => { const store = make(); const minimal = createPeerTaskRowFixture({ task_id: "p0000000000000001", parentSessionId: undefined, }); await store.put(minimal); await assert.rejects(store.put(createPeerTaskRowFixture({ task_id: "p0000000000000001" })), (e) => codeOf(e) === PEER_TASK_ALREADY_EXISTS_CODE, "duplicate (task_id, scope) must fail with peer_task.already_exists"); await assert.rejects(store.put(createPeerTaskRowFixture({ task_id: "p0000000000000090", rev: 1 })), (e) => codeOf(e) === PEER_TASK_ROW_MALFORMED_CODE, "put with rev !== 0 must be refused"); await assert.rejects(store.put(createPeerTaskRowFixture({ task_id: "p0000000000000091", scope: "" })), (e) => codeOf(e) === PEER_TASK_ROW_MALFORMED_CODE, "empty scope must be refused"); await assert.rejects(store.put(createPeerTaskRowFixture({ task_id: "p0000000000000092", requestDigest: "f".repeat(64) })), (e) => codeOf(e) === PEER_TASK_ROW_MALFORMED_CODE, "mismatched requestDigest must be refused"); await assert.rejects(store.put(createPeerTaskRowFixture({ task_id: "p1" })), (e) => codeOf(e) === PEER_TASK_ROW_MALFORMED_CODE, "off-shape task_id must be refused"); await assert.rejects(store.put(createPeerTaskRowFixture({ task_id: "p0000000000000093", scope: "a\u0000b" })), (e) => codeOf(e) === PEER_TASK_ROW_MALFORMED_CODE, "NUL in scope must be refused"); await assert.rejects(store.get("b\u0000x", S), (e) => codeOf(e) === "config.invalid_argument", "off-shape / NUL task_id on get must be refused"); await assert.rejects(store.get(minimal.task_id, "a\u0000b"), (e) => codeOf(e) === "config.invalid_argument", "NUL in scope on get must be refused"); const full = createPeerTaskRowFixture({ task_id: "p0000000000000002", scope: S, parentSessionId: "sess-mid", rootSessionId: "sess-root", rootSessionIncarnation: "occ-1", rootSessionScope: "box-scope", parentTaskId: "t-parent", writerId: "writer-1", destination: { kind: "a2a_peer", peer: "billing", displayName: "Billing Team", ownerTeam: "finops", boundary: "outside" }, peerFingerprint: "fp-abc123", planItem: "step-3", delivery: "accepted", remote: { taskId: "remote-task-1", contextId: "remote-ctx-1", state: "working", stateClass: "awaiting_own_approval", waitingOn: { kind: "callee_approval", since: "2026-11-24T00:00:00Z", approvalRef: "apr-99" }, clock: "paused", stateChangedAt: 1_500, }, followUps: "not_accepted", cancel: "requested", peerFinalBy: 50_000, approvalBy: 90_000, fallback: "proceed_without", reschedules: [{ by: "peer", at: 1_400, from: 61_000, to: 50_000, why: "peer shortened deadline" }], reminders: [ { n: 1, dueAt: 20_000, target: "peer", disposition: "sent", seq: 1 }, { n: 2, dueAt: 40_000, target: "peer_approver", disposition: "answered", routedTo: "run", seq: 2 }, ], lastSeq: 3, status: "failed", settledAt: 61_001, outcome: { kind: "peer_task", outcome: "failed", code: "a2a.external_no_response", provenance: "live", refused: { haltedByPerson: true }, }, remoteMayContinue: true, overdueTail: { until: 361_000 }, }); await store.put(full); const readMin = await held(store, minimal.task_id, S); assert.deepEqual(readMin, minimal); assert.equal(readMin.parentSessionId, undefined); assert.equal(readMin.remote, undefined); assert.equal(readMin.outcome, undefined); assert.equal(readMin.overdueTail, undefined); const readFull = await held(store, full.task_id, S); assert.deepEqual(readFull, full); await store.put(createPeerTaskRowFixture({ task_id: minimal.task_id, scope: "tenant-B", skillId: "other-skill" })); assert.equal((await held(store, minimal.task_id, "tenant-B")).skillId, "other-skill"); assert.equal(await store.get(minimal.task_id, "tenant-C"), null); await store.put(createPeerTaskRowFixture({ task_id: "p0000000000000003", scope: ANONYMOUS_SCOPE })); assert.equal(await store.get("p0000000000000003", S), null); assert.equal((await held(store, "p0000000000000003", ANONYMOUS_SCOPE)).scope, ANONYMOUS_SCOPE); const withExtra = { ...createPeerTaskRowFixture({ task_id: "p0000000000000004" }), futureField: "kept-tolerant" }; await store.put(withExtra); assert.equal((await held(store, "p0000000000000004", S)).skillId, "reconcile"); const splitId = pid(0x5c0); const twoFaced = createPeerTaskRowFixture({ task_id: splitId, status: "completed" }); let scopeReads = 0; Object.defineProperty(twoFaced, "scope", { enumerable: true, configurable: true, get: () => (scopeReads++ === 0 ? S : "tenant-B") }); try { await store.put(twoFaced); } catch (e) { assert.equal(codeOf(e), PEER_TASK_ROW_MALFORMED_CODE, `a refused two-faced row carries ${PEER_TASK_ROW_MALFORMED_CODE}`); } for (const sc of [S, "tenant-B"]) { const filed = await store.get(splitId, sc); if (filed !== null) assert.equal(filed.scope, sc, `the row filed under ${sc} carries scope ${sc} in its body`); const listed = readRows(await store.listByScope(sc)).some((r) => r.task_id === splitId); assert.equal(listed, filed !== null, `listByScope(${sc}) agrees with get(${splitId}, ${sc})`); } const detached = await held(store, full.task_id, S); detached.status = "cancelled"; detached.destination.peer = "mutated"; detached.remote.taskId = "mutated"; const again = await held(store, full.task_id, S); assert.equal(again.status, "failed"); assert.equal(again.destination.peer, "billing"); assert.equal(again.remote?.taskId, "remote-task-1"); }); run("updateIf enforces all four guards (rev, delivery, status, cancel), keeps key authoritative, and bumps rev by 1", async (make) => { const store = make(); const id1 = pid(1); const idMissing = pid(0xffff); const idForged = pid(0xfffe); await store.put(createPeerTaskRowFixture({ task_id: id1 })); await store.put(createPeerTaskRowFixture({ task_id: id1, scope: "tenant-B" })); const row = await held(store, id1); assert.equal(await store.updateIf(id1, "tenant-C", { ...row, delivery: "sent_unconfirmed" }, { rev: 0 }), false, "wrong scope"); assert.equal(await store.updateIf(idMissing, S, { ...row, delivery: "sent_unconfirmed" }, { rev: 0 }), false, "missing row"); assert.equal(await store.updateIf(id1, S, { ...row, delivery: "sent_unconfirmed" }, { rev: 2 }), false, "rev mismatch"); assert.equal(await store.updateIf(id1, S, { ...row, delivery: "sent_unconfirmed" }, { rev: 0, delivery: "sent_unconfirmed" }), false, "delivery mismatch"); assert.equal(await store.updateIf(id1, S, { ...row, delivery: "sent_unconfirmed" }, { rev: 0, status: "completed" }), false, "status mismatch"); assert.equal(await store.updateIf(id1, S, { ...row, delivery: "sent_unconfirmed" }, { rev: 0, cancel: "requested" }), false, "cancel mismatch"); const payload = { ...row, task_id: idForged, scope: "tenant-B", delivery: "sent_unconfirmed", cancel: "requested", lastSeq: 1, }; assert.equal(await store.updateIf(id1, S, payload, { rev: 0, delivery: "recorded", status: "running", cancel: "not_requested" }), true, "matching guards must win"); const after = await held(store, id1); assert.equal(after.task_id, id1); assert.equal(after.scope, S); assert.equal(after.rev, 1); assert.equal(after.delivery, "sent_unconfirmed"); assert.equal(after.cancel, "requested"); assert.equal(await store.get(idForged, "tenant-B"), null); assert.equal(await store.updateIf(id1, S, { ...after, delivery: "accepted" }, { rev: 0 }), false, "pre-CAS rev loses"); const otherTenant = await held(store, id1, "tenant-B"); assert.equal(otherTenant.rev, 0, "updateIf in scope S must not modify same task_id in tenant-B"); assert.equal(otherTenant.delivery, "recorded"); }); run("updateIf enforces monotone delivery progression and refuses every regression", async (make) => { const store = make(); const id1 = pid(1); const idSettled = pid(2); await store.put(createPeerTaskRowFixture({ task_id: id1, delivery: "recorded" })); const r0 = await held(store, id1); assert.equal(await store.updateIf(id1, S, { ...r0, delivery: "sent_unconfirmed" }, { rev: 0, delivery: "recorded" }), true); const r1 = await held(store, id1); assert.equal(r1.delivery, "sent_unconfirmed"); await assert.rejects(store.updateIf(id1, S, { ...r1, delivery: "recorded" }, { rev: 1, delivery: "sent_unconfirmed" }), (e) => codeOf(e) === PEER_TASK_DELIVERY_REGRESSION_CODE, "sent_unconfirmed -> recorded must throw peer_task.delivery_regression"); assert.equal((await held(store, id1)).rev, 1); assert.equal(await store.updateIf(id1, S, { ...r1, delivery: "accepted", remote: { taskId: "rt-1", state: "working", stateClass: "working" }, waitingFor: "peer" }, { rev: 1, delivery: "sent_unconfirmed" }), true); const r2 = await held(store, id1); assert.equal(r2.delivery, "accepted"); for (const badDelivery of ["sent_unconfirmed", "recorded"]) { await assert.rejects(store.updateIf(id1, S, { ...r2, delivery: badDelivery }, { rev: 2, delivery: "accepted" }), (e) => codeOf(e) === PEER_TASK_DELIVERY_REGRESSION_CODE, `accepted -> ${badDelivery} must throw peer_task.delivery_regression`); } assert.equal((await held(store, id1)).delivery, "accepted"); assert.equal((await held(store, id1)).rev, 2); assert.equal(await store.updateIf(id1, S, { ...r2, lastSeq: 1 }, { rev: 2, delivery: "accepted" }), true, "staying at accepted is allowed"); assert.equal((await held(store, id1)).rev, 3); const altParams = JSON.stringify({ message: { role: "user", kind: "message", messageId: "msg-alt", parts: [{ kind: "text", text: "alt" }] } }); const r3 = await held(store, id1); assert.equal(await store.updateIf(id1, S, { ...r3, messageId: "msg-alt" }, { rev: 3 }), false, "mint-once messageId must not change"); assert.equal(await store.updateIf(id1, S, { ...r3, request: { paramsJson: altParams }, requestDigest: peerTaskRequestDigest(altParams) }, { rev: 3 }), false, "mint-once request/digest must not change"); assert.equal(await store.updateIf(id1, S, { ...r3, destination: { kind: "a2a_peer", peer: "other", boundary: "outside" } }, { rev: 3 }), false, "mint-once destination must not change"); assert.equal(await store.updateIf(id1, S, { ...r3, parentSessionId: "sess-other" }, { rev: 3 }), false, "mint-once ownership anchor must not change"); assert.equal((await held(store, id1)).rev, 3); await store.put(createPeerTaskRowFixture({ task_id: idSettled, status: "completed" })); const s0 = await held(store, idSettled); const { outcome: _o, settledAt: _sa, ...liveShape } = s0; assert.equal(await store.updateIf(idSettled, S, { ...liveShape, status: "running", waitingFor: "unknown" }, { rev: 0 }), false, "settled row must not move back to running"); assert.equal(await store.updateIf(idSettled, S, { ...s0, overdueTail: { until: 90_000 } }, { rev: 0 }), false, "closed settled row must not re-open overdueTail"); assert.equal((await held(store, idSettled)).status, "completed"); }); run("updateIf lets exactly one writer win under concurrent two-writer contention", async (make) => { const store = make(); const idRace = pid(10); await store.put(createPeerTaskRowFixture({ task_id: idRace })); const base = await held(store, idRace); const [w1, w2] = await Promise.all([ store.updateIf(idRace, S, { ...base, delivery: "sent_unconfirmed", lastSeq: 1 }, { rev: 0, delivery: "recorded" }), store.updateIf(idRace, S, { ...base, delivery: "sent_unconfirmed", lastSeq: 2 }, { rev: 0, delivery: "recorded" }), ]); assert.equal([w1, w2].filter(Boolean).length, 1, "exactly one concurrent CAS must win"); const after = await held(store, idRace); assert.equal(after.rev, 1); assert.equal(after.lastSeq, w1 ? 1 : 2); }); run("listUnsettled returns running rows and settled rows with open overdueTail, excludes closed settled rows, newest-first and content-free", async (make) => { const store = make(); const idRun = pid(21); const idTail = pid(22); const idClosed = pid(23); const idOther = pid(24); await store.put(createPeerTaskRowFixture({ task_id: idRun, status: "running", submittedAt: 1_000 })); await store.put(createPeerTaskRowFixture({ task_id: idTail, status: "failed", settledAt: 2_500, submittedAt: 2_000, overdueTail: { until: 50_000 }, reschedules: [{ by: "caller", at: 1_500, from: 61_000, to: 50_000, why: "SECRET-WHY" }], reminders: [{ n: 1, dueAt: 1_800, target: "peer", disposition: "sent", seq: 1 }], })); await store.put(createPeerTaskRowFixture({ task_id: idClosed, status: "completed", settledAt: 3_500, submittedAt: 3_000 })); await store.put(createPeerTaskRowFixture({ task_id: idOther, scope: "tenant-B", status: "running", submittedAt: 4_000 })); const listed = readRows(await store.listUnsettled(S)); assert.deepEqual(listed.map((r) => r.task_id), [idTail, idRun]); for (const item of listed) { assert.equal(Object.hasOwn(item, "request"), false, "summary must not carry request"); assert.equal(Object.hasOwn(item, "reschedules"), false, "summary must not carry reschedules"); assert.equal(Object.hasOwn(item, "reminders"), false, "summary must not carry reminders"); } assert.deepEqual((await store.listUnsettled(S, { limit: 1 })).map((r) => r.task_id), [idTail]); assert.deepEqual((await store.listUnsettled(S, { status: "running" })).map((r) => r.task_id), [idRun]); }); run("listBySession, listByScope, and listByRoot enforce anchors, newest-first ordering, filters, and content-free summaries", async (make) => { const store = make(); const [p1, p2, p3, p4, p5] = [pid(31), pid(32), pid(33), pid(34), pid(35)]; await store.put(createPeerTaskRowFixture({ task_id: p1, parentSessionId: "sess-1", submittedAt: 1_000 })); await store.put(createPeerTaskRowFixture({ task_id: p2, owner: "sess-1", sessionScoped: true, parentSessionId: undefined, submittedAt: 2_000, status: "completed", })); await store.put(createPeerTaskRowFixture({ task_id: p3, parentSessionId: "sess-mid", rootSessionId: "sess-1", submittedAt: 3_000 })); await store.put(createPeerTaskRowFixture({ task_id: p4, parentSessionId: "sess-other", submittedAt: 4_000 })); await store.put(createPeerTaskRowFixture({ task_id: p5, scope: "tenant-B", rootSessionId: "sess-1", submittedAt: 5_000 })); const bySession = readRows(await store.listBySession(S, "sess-1")); assert.deepEqual(bySession.map((r) => r.task_id), [p3, p2, p1]); for (const item of bySession) { assert.equal(Object.hasOwn(item, "request"), false, "listBySession must not leak request"); assert.equal(Object.hasOwn(item, "reschedules"), false); assert.equal(Object.hasOwn(item, "reminders"), false); } assert.deepEqual((await store.listBySession(S, "sess-1", { status: "completed" })).map((r) => r.task_id), [p2]); assert.deepEqual((await store.listBySession(S, "sess-1", { limit: 2 })).map((r) => r.task_id), [p3, p2]); assert.deepEqual((await store.listByScope(S)).map((r) => r.task_id), [p4, p3, p2, p1]); const byRoot = readRows(await store.listByRoot("sess-1")); assert.deepEqual(byRoot.map((r) => [r.task_id, r.scope]), [ [p5, "tenant-B"], [p3, S], [p2, S], [p1, S], ]); assert.deepEqual(await store.listByRoot("sess-mid"), [], "intermediate parent is not the delegation root"); for (const bad of ["", "r".repeat(257), "sess\n1", 42, null]) { await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.listByRoot, store, [bad])), (e) => codeOf(e) === "config.invalid_argument"); } const badListOpts = [{ limit: Number.NaN }, { limit: -1 }, { limit: 1.5 }, { status: "bogus" }]; for (const badOpts of badListOpts) { await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.listByScope, store, [S, badOpts])), (e) => codeOf(e) === "config.invalid_argument"); await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.listUnsettled, store, [S, badOpts])), (e) => codeOf(e) === "config.invalid_argument"); await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.listBySession, store, [S, "sess-1", badOpts])), (e) => codeOf(e) === "config.invalid_argument"); await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.listByRoot, store, ["sess-1", badOpts])), (e) => codeOf(e) === "config.invalid_argument"); } }); run("delete is row-precise and rev-conditional; optional settleErasure leaves live rows intact", async (make) => { const store = make(); const [p1, p2] = [pid(41), pid(42)]; await store.put(createPeerTaskRowFixture({ task_id: p1, status: "completed" })); await store.put(createPeerTaskRowFixture({ task_id: p1, scope: "tenant-B", status: "completed" })); await store.put(createPeerTaskRowFixture({ task_id: p2, status: "completed" })); assert.equal(await store.delete(p1, S, { rev: 5 }), false); assert.equal(await store.delete(p1, "tenant-C"), false); assert.equal(await store.delete(p1, S, { rev: 0 }), true); assert.equal(await store.get(p1, S), null); assert.notEqual(await store.get(p1, "tenant-B"), null, "delete in scope S must leave same task_id in tenant-B untouched"); assert.equal(await store.delete(p1, S), false); await store.settleErasure?.(); await store.settleErasure?.(); assert.notEqual(await store.get(p2, S), null); assert.equal(await store.delete(p2, S), true); }); run("deleteBySession deletes every row the session sent in any status, leaves rows naming it only as their root, other sessions and tenants, and refuses empty sessionId", async (make) => { const store = make(); const [p1, p2, p3, p4, p5, p6, p7, p8, p9] = [pid(51), pid(52), pid(53), pid(54), pid(55), pid(56), pid(57), pid(58), pid(59)]; await store.put(createPeerTaskRowFixture({ task_id: p8, status: "running", parentSessionId: "sess-mid", rootSessionId: "sess-1", submittedAt: 8_000 })); await store.put(createPeerTaskRowFixture({ task_id: p9, status: "failed", overdueTail: { until: 90_000 }, parentSessionId: "sess-mid", rootSessionId: "sess-1", submittedAt: 9_000 })); await store.put(createPeerTaskRowFixture({ task_id: p1, status: "completed", submittedAt: 1_000 })); await store.put(createPeerTaskRowFixture({ task_id: p2, status: "cancelled", parentSessionId: "sess-mid", rootSessionId: "sess-1", submittedAt: 2_000 })); await store.put(createPeerTaskRowFixture({ task_id: p3, status: "killed", owner: "sess-1", sessionScoped: true, parentSessionId: undefined, submittedAt: 3_000 })); await store.put(createPeerTaskRowFixture({ task_id: p4, status: "running", submittedAt: 4_000 })); await store.put(createPeerTaskRowFixture({ task_id: p5, status: "failed", overdueTail: { until: 90_000 }, submittedAt: 5_000 })); await store.put(createPeerTaskRowFixture({ task_id: p6, status: "completed", parentSessionId: "sess-2", submittedAt: 6_000 })); await store.put(createPeerTaskRowFixture({ task_id: p7, status: "completed", scope: "tenant-B", submittedAt: 7_000 })); const deleted = await store.deleteBySession(S, "sess-1"); assert.deepEqual([...deleted].sort(), [p1, p3, p4, p5]); for (const id of [p1, p3, p4, p5]) assert.equal(await store.get(id, S), null); for (const id of [p2, p6, p8, p9]) assert.notEqual(await store.get(id, S), null); assert.notEqual(await store.get(p7, "tenant-B"), null); assert.deepEqual(await store.deleteBySession(S, "sess-1"), []); await assert.rejects(store.deleteBySession(S, ""), (e) => codeOf(e) === "config.invalid_argument"); }); run("reap is a no-op without policy, sweeps settled closed rows by maxAgeMs and keep, spares running and open-overdueTail rows, and refuses bad knobs", async (make) => { const store = make(); const [pOld, pOther, pRun, pTail] = [pid(61), pid(62), pid(63), pid(64)]; await store.put(createPeerTaskRowFixture({ task_id: pOld, status: "completed", submittedAt: 1_000, settledAt: 1_500 })); await store.put(createPeerTaskRowFixture({ task_id: pOther, scope: "tenant-B", status: "completed", submittedAt: 1_000, settledAt: 1_500 })); await store.put(createPeerTaskRowFixture({ task_id: pRun, status: "running", submittedAt: 1_000 })); await store.put(createPeerTaskRowFixture({ task_id: pTail, status: "failed", submittedAt: 1_000, settledAt: 1_500, overdueTail: { until: 999_999 } })); assert.equal(await store.reap(S, 100_000), 0); assert.equal(await store.reap(S, 100_000, {}), 0); const badReapOpts = [{ maxAgeMs: Number.NaN }, { maxAgeMs: -1 }, { keep: -1 }, { keep: 1.5 }, { maxAge: 100 }]; for (const badOpts of badReapOpts) { await assert.rejects(Promise.resolve().then(() => Reflect.apply(store.reap, store, [S, 100_000, badOpts])), (e) => codeOf(e) === "config.retention_policy_invalid"); } await assert.rejects(store.reap(S, Number.NaN, { maxAgeMs: 10 }), (e) => codeOf(e) === "config.retention_policy_invalid"); assert.equal(await store.reap(S, 100_000, { maxAgeMs: 10 }), 1); assert.equal(await store.get(pOld, S), null); assert.notEqual(await store.get(pOther, "tenant-B"), null, "reap by maxAgeMs in scope S must not sweep tenant-B"); assert.notEqual(await store.get(pRun, S), null); assert.notEqual(await store.get(pTail, S), null); const [k1, k2, k3] = [pid(71), pid(72), pid(73)]; for (const [i, id] of [k1, k2, k3].entries()) { await store.put(createPeerTaskRowFixture({ task_id: id, status: "completed", submittedAt: 2_001 + i, settledAt: 3_001 + i })); } assert.equal(await store.reap(S, 100_000, { keep: 2 }), 1); assert.deepEqual((await store.listByScope(S, { status: "completed" })).map((r) => r.task_id), [k3, k2]); assert.notEqual(await store.get(pOther, "tenant-B"), null, "reap by keep in scope S must not sweep tenant-B"); assert.notEqual(await store.get(pRun, S), null); assert.notEqual(await store.get(pTail, S), null); }); const FROM = "tenant-rekey-from"; const TO = "tenant-rekey-to"; run("rekeyScope runs plan, arrive, leave, and withdraw, re-files matching rootSessionScope, rejects conflicts without writing, and validates inputs", async (make) => { const store = make(); const [p1, p2, p3, pc1, pc2] = [pid(81), pid(82), pid(83), pid(84), pid(85)]; await store.put(createPeerTaskRowFixture({ task_id: p1, scope: FROM, rootSessionId: "sess-1", rootSessionScope: FROM })); const r0 = await held(store, p1, FROM); assert.equal(await store.updateIf(p1, FROM, { ...r0, delivery: "sent_unconfirmed" }, { rev: 0 }), true); await store.put(createPeerTaskRowFixture({ task_id: p2, scope: FROM, rootSessionId: "sess-1", rootSessionScope: "third-scope" })); await store.put(createPeerTaskRowFixture({ task_id: p3, scope: `${FROM}-extra` })); assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "plan" }), { kind: "plan", rows: 2, conflicting: 0 }); assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 2 }); const src1 = await held(store, p1, FROM); const dst1 = await held(store, p1, TO); assert.deepEqual(dst1, { ...src1, scope: TO, rootSessionScope: TO, rev: src1.rev + 1 }); assert.equal((await held(store, p2, TO)).rootSessionScope, "third-scope"); assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 2 }); assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "withdraw" }), { kind: "done", mode: "withdraw", rows: 2 }); assert.equal(await store.get(p1, TO), null); assert.deepEqual(await held(store, p1, FROM), src1); await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "arrive" }); assert.deepEqual(await store.rekeyScope({ fromScope: FROM, toScope: TO, mode: "leave" }), { kind: "done", mode: "leave", rows: 2 }); assert.equal(await store.get(p1, FROM), null); assert.deepEqual(await held(store, p1, TO), dst1); assert.notEqual(await store.get(p3, `${FROM}-extra`), null); assert.deepEqual(await store.rekeyScope({ fromScope: TO, toScope: TO, mode: "arrive" }), { kind: "done", mode: "arrive", rows: 0 }); await store.put(createPeerTaskRowFixture({ task_id: pc1, scope: FROM })); await store.put(createPeerTaskRowFixture({ task_id: pc2, scope: FROM })); await store.put(createPeerTaskRowFixture({ task_id: pc2, scope: TO, skillId: "existing-target" })); 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(pc1, TO), null); assert.equal((await held(store, pc2, TO)).skillId, "existing-target"); const unchecked = store; for (const bad of [undefined, { fromScope: FROM, toScope: TO }, { fromScope: "", toScope: TO, mode: "plan" }, { fromScope: FROM, toScope: TO, mode: "bad" }]) { await assert.rejects(unchecked.rekeyScope(bad), TypeError); } }); const plantRow = hooks?.plantRow; if (plantRow !== undefined) { const SENTINEL = "planted-peer-secret-sentinel"; const BAD = "p000000000000bad1"; const GOOD = "p0000000000000002"; const forged = (over) => ({ ...JSON.parse(JSON.stringify(createPeerTaskRowFixture({ task_id: BAD, planItem: SENTINEL }))), ...over, }); const damagedCases = [ ["tampered requestDigest", { request: { paramsJson: JSON.stringify({ message: { text: SENTINEL } }) } }], ["status outside set", { status: "parked" }], ["rev not a count", { rev: "7" }], ["settled row missing outcome", { status: "completed", waitingFor: undefined, outcome: undefined }], ["running row missing waitingFor without remote", { remote: undefined, waitingFor: undefined }], ]; for (const [label, over] of damagedCases) { run(`damaged row (${label}): listed with rowVerdict, refused on get/updateIf/rekeyScope quoting nothing planted, skipped by deleteBySession/reap, removable by delete`, async (make) => { const seeded = make(); await seeded.put(createPeerTaskRowFixture({ task_id: GOOD, submittedAt: 2_000, parentSessionId: "sess-other" })); const s = await plantRow(seeded, { task_id: BAD, scope: S }, forged(over)); try { for (const listing of [await s.listByScope(S), await s.listUnsettled(S)]) { const badEntry = listing.find((x) => x.task_id === BAD); assert.ok(badEntry !== undefined && "rowVerdict" in badEntry && badEntry.rowVerdict.code === PEER_TASK_ROW_MALFORMED_CODE); assert.equal(JSON.stringify(listing).includes(SENTINEL), false); } const refused = (e) => codeOf(e) === PEER_TASK_ROW_MALFORMED_CODE && !thrownText(e).includes(SENTINEL); await assert.rejects(s.get(BAD, S), refused); await assert.rejects(s.updateIf(BAD, S, createPeerTaskRowFixture({ task_id: BAD, delivery: "sent_unconfirmed" }), { rev: 0 }), refused); await assert.rejects(s.rekeyScope({ fromScope: S, toScope: TO, mode: "plan" }), refused); await assert.rejects(s.rekeyScope({ fromScope: S, toScope: TO, mode: "arrive" }), refused); assert.equal((await s.deleteBySession(S, "sess-1")).includes(BAD), false); await s.reap(S, 1e12, { maxAgeMs: 0, keep: 0 }); assert.equal((await s.listByScope(S)).filter((x) => "rowVerdict" in x).length, 1); assert.equal(await s.delete(BAD, S), true); assert.deepEqual((await s.listByScope(S)).map((x) => x.task_id), [GOOD]); } finally { s.close?.(); } }); } } await settle(); } export async function peerTaskStoreScopesContract(mk, runAssertion) { const { run: runRaw, settle } = beginContract(runAssertion); const run = (name, fn) => runRaw(name, () => withStores(mk, fn)); run("listScopes enumerates scopes holding rows deduplicated and sorted, and tracks delete and rekeyScope", async (make) => { const store = make(); assert.equal(typeof store.listScopes, "function"); const [p1, p2, p3] = [pid(91), pid(92), pid(93)]; await store.put(createPeerTaskRowFixture({ task_id: p1, scope: "tenant-B" })); await store.put(createPeerTaskRowFixture({ task_id: p2, scope: "tenant-A" })); await store.put(createPeerTaskRowFixture({ task_id: p3, scope: "tenant-A" })); assert.deepEqual(await store.listScopes(), ["tenant-A", "tenant-B"]); await store.delete(p1, "tenant-B"); assert.deepEqual(await store.listScopes(), ["tenant-A"]); await store.rekeyScope({ fromScope: "tenant-A", toScope: "tenant-C", mode: "arrive" }); assert.deepEqual(await store.listScopes(), ["tenant-A", "tenant-C"]); await store.rekeyScope({ fromScope: "tenant-A", toScope: "tenant-C", mode: "leave" }); assert.deepEqual(await store.listScopes(), ["tenant-C"]); }); await settle(); }