@sema-agent/core
Version:
Stateless, task-oriented AI agent core
503 lines (502 loc) • 33.4 kB
JavaScript
import { strict as assert } from "node:assert";
import { executionVerdict } from "../checkpoint-execution-record.js";
import { MAX_PENDING_STEER_ENTRIES, mintCheckpointToken, readPendingSteerQueue, } from "../checkpoint-store.js";
import { checkpointFrom } from "../pause-registry.js";
import { beginContract } from "./contract-harness.js";
export function createCheckpointFixture(over = {}) {
const token = over.token ?? mintCheckpointToken();
return checkpointFrom({
token,
scope: "tenant-a",
sessionId: "sess-1",
leafId: "leaf-1",
gate: { kind: "human", reason: "approve", toolName: "Write" },
pendingAction: {
kind: "tool_approval",
origin: "policy",
toolCallId: "call-3",
toolName: "Write",
args: { path: "/x", content: "y" },
boundInputHash: "h0",
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,
});
}
export const ALLOW = {
gate: "policy_ask",
decision: "allow",
boundCallId: "call-3",
boundInputHash: "h0",
hostDecision: { decidedBy: "person" },
};
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) {
const { run, settle } = beginContract(runAssertion);
run("kit prerequisites: reopen/setPendingSteer/listByScope are implemented (REQUIRED by this kit)", async () => {
const probe = make();
const missing = ["reopen", "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("execution declaration: the backend declares execution.outcome === true (a REQUIRED member of the contract)", async () => {
const probe = make();
assert.equal(probe.execution?.outcome, true, "backend does not declare `execution = { outcome: true }` — the run refuses the store at its first read");
assert.equal(typeof probe.recordExecutionOutcome, "function", "backend does not implement recordExecutionOutcome — required by the CheckpointStore contract");
});
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("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("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("the queue bound is fail-loud steering.queue_full and evicts nothing", async () => {
const store = make();
const cp = createCheckpointFixture();
await store.put(cp.token, cp);
for (let i = 0; i < MAX_PENDING_STEER_ENTRIES; i++) {
assert.equal(await store.setPendingSteer(cp.token, cp.scope, { text: `s${i}`, trusted: false }), true);
}
await assert.rejects(store.setPendingSteer(cp.token, cp.scope, { text: "overflow", trusted: false }), (e) => e.code === "steering.queue_full");
const q = readPendingSteerQueue((await store.get(cp.token)).state);
assert.equal(q.length, MAX_PENDING_STEER_ENTRIES);
assert.deepEqual(q.map((e) => e.text), Array.from({ length: MAX_PENDING_STEER_ENTRIES }, (_, i) => `s${i}`));
});
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("#438 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("design/388 B18 × B6 identity + face group: a row's eight optional members (capabilityId/contractId/shapeDigest/implementationRevision/rosterDigest + family/pathTarget/names) 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: "caller::Write@acme.write@2",
contractId: "acme.write@2",
shapeDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
implementationRevision: "r7",
rosterDigest: "sha256:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210",
family: "file-write",
pathTarget: { param: "destination", aliases: ["path"], access: "create", skillScopeEligible: true },
names: ["AcmeWrite", "acme_write"],
};
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 pre-388 row reads name-only, never a partial face)`);
});
run("#457 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("#1079 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("#1214 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("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);
});
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,
sourceTaskId: "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: {
kind: "tool_approval",
origin: "policy",
mandated: true,
mandate: "tool_marks",
toolCallId: "call-pr",
toolName: "open_pr",
args: { repo: "x" },
boundInputHash: "h0",
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",
sessionId: "needs-approval",
scope: "tenant-a",
gateKind: "human",
severity: 5,
deadline: 1_999_999_999_999,
createdAt: 1_700_000_000_000,
sourceTaskId: "needs-approval",
principal: "alice@corp",
toolCallId: "call-pr",
toolName: "open_pr",
toolInput: '{"repo":"x"}',
mandated: true,
mandate: "tool_marks",
origin: "policy",
},
{
token: "tok-resource",
sessionId: "out-of-budget",
scope: "tenant-a",
gateKind: "resource_limit",
spentMicroUsd: 4_200_000,
createdAt: 1_700_000_000_001,
},
];