diff --git a/pm-stack/aggregator/src/work-action-contract.ts b/pm-stack/aggregator/src/work-action-contract.ts new file mode 100644 index 0000000000..091eacc370 --- /dev/null +++ b/pm-stack/aggregator/src/work-action-contract.ts @@ -0,0 +1,485 @@ +// The MOB-05 preview/apply action envelope (#9472, pm-stack design +// package `2026-11-13T03-20-24Z_design_pm-stack-fleet-orchestration`, +// component 9201 §3.2, slice MOB-05). +// +// Why this module exists: the dashboard's action store (src/actions.ts) +// is a REQUEST LEDGER. A record leaving state "new" proves a consumer +// picked the request up; it does not prove the fact was applied, and +// it has no notion of an expected work version, an operation key, or a +// server-side authorization decision made at apply time. MOB-05 asks +// for a contract with exactly those three properties: +// +// 1. operation key — one apply per key, replays return the original +// receipt and produce no second effect; +// 2. expected work version — apply proceeds only when the expected +// revision still matches the authoritative fixture; a stale +// expectation ends in `conflict` (or `uncertain` when the +// authoritative version cannot be read), never a silent apply; +// 3. server-side authorization — the actor is re-checked at apply +// time, so a role revoked between preview and apply fails before +// any downstream effect. +// +// The envelope also carries an explicit state machine, so every +// terminal outcome the design names (draft, previewed, accepted, +// running, pending_sync, partial, conflict, uncertain, rejected, +// verified_complete) is reachable only through a declared edge and a +// named oracle can assert each one. +// +// Boundaries: pure module, no I/O, no clock, no downstream client. The +// caller supplies the authoritative fixture reader, the authorization +// check and the effect sink. Production adoption, the Fleet-side +// operations seam and live acceptance stay with their own slices; this +// file is the executable contract the design asks for. + +/** The design's envelope lifecycle. `verified_complete` and `rejected` are terminal. */ +export const WORK_ACTION_STATES = [ + "draft", + "previewed", + "accepted", + "running", + "pending_sync", + "partial", + "conflict", + "uncertain", + "rejected", + "verified_complete", +] as const; + +export type WorkActionState = (typeof WORK_ACTION_STATES)[number]; + +/** Declared edges. Anything absent here is a programming error, not a runtime outcome. */ +export const WORK_ACTION_EDGES: Readonly< + Record +> = { + // Preview, accept and apply each re-read the authoritative version, so + // each can end in `conflict` (it moved) or `uncertain` (unreadable). + draft: ["previewed", "rejected", "conflict", "uncertain"], + previewed: ["accepted", "rejected", "conflict", "uncertain"], + accepted: ["running", "rejected", "conflict", "uncertain"], + running: [ + "pending_sync", + "partial", + "conflict", + "uncertain", + "rejected", + "verified_complete", + ], + pending_sync: ["verified_complete", "partial", "uncertain"], + partial: ["verified_complete", "conflict"], + conflict: [], + uncertain: [], + rejected: [], + verified_complete: [], +}; + +export function isTerminalState(state: WorkActionState): boolean { + return WORK_ACTION_EDGES[state].length === 0; +} + +export function canTransition( + from: WorkActionState, + to: WorkActionState, +): boolean { + return WORK_ACTION_EDGES[from].includes(to); +} + +export interface WorkActionActor { + kind: string; + id: string; + /** Roles the SERVER believes this actor holds right now. Never client-supplied. */ + roles: readonly string[]; +} + +/** Everything preview needs that the client asserts. The server re-derives the rest. */ +export interface WorkActionRequest { + /** Stable key: one apply per key. A replay returns the first receipt. */ + operationKey: string; + kind: string; + objectRef: string; + action: string; + payload: Readonly>; + /** The work version the client believes it is acting on. */ + expectedWorkVersion: string; +} + +export interface WorkActionEnvelope { + state: WorkActionState; + request: WorkActionRequest; + /** Server-computed authorization verdict recorded at preview. */ + authorized: boolean; + /** The authoritative version observed when the preview was accepted. */ + previewedVersion: string | null; + /** Populated once the envelope reaches a terminal state, except `partial`/`pending_sync`. */ + receipt: WorkActionReceipt | null; + /** Ordered audit trail: one entry per accepted edge, plus rejections. */ + transitions: readonly WorkActionTransition[]; + /** Whether an effect has been handed to the downstream. At most once. */ + effectIssued: boolean; +} + +export interface WorkActionTransition { + from: WorkActionState; + to: WorkActionState; + /** The oracle that decided the edge, recorded so a review can read the reasoning. */ + oracle: string; +} + +export interface WorkActionReceipt { + operationKey: string; + outcome: + | "verified_complete" + | "rejected" + | "conflict" + | "uncertain" + | "partial" + | "pending_sync"; + workVersion: string | null; + note: string; +} + +/** Server-side collaborators. Injected so the contract has no ambient authority. */ +export interface WorkActionAuthority { + /** Current authoritative work version for the object, or null when unreadable. */ + readWorkVersion(objectRef: string): string | null; + /** Current roles for the actor, re-read at each gate. */ + readRoles(actorId: string): readonly string[]; + /** The downstream effect. Called at most once per operation key. */ + issueEffect(request: WorkActionRequest): void; + /** + * Atomically claim an operation key for apply. The first claim wins and + * returns `{ claimed: true }`; every later claim, from any envelope, + * returns `{ claimed: false }` with the receipt recorded for the key, or + * null while the first apply is still in flight. This is what makes + * "one effect per operation key" hold across envelopes, not just across + * replays of one envelope object. + */ + claimOperation( + operationKey: string, + ): { claimed: true } | { claimed: false; receipt: WorkActionReceipt | null }; + /** Record the receipt for a claimed key so later claims can return it. */ + recordReceipt(receipt: WorkActionReceipt): void; +} + +const ROLES_BY_STATE: Partial> = { + previewed: "work-action/preview", + accepted: "work-action/accept", + running: "work-action/apply", +}; + +/** + * A rejected edge keeps the audit trail and produces a terminal envelope; + * the refusal itself is the receipt, so a caller can never mistake a + * refusal for an unapplied draft. + */ +function refuse( + envelope: WorkActionEnvelope, + to: "rejected" | "conflict" | "uncertain", + oracle: string, + note: string, +): WorkActionEnvelope { + const transition: WorkActionTransition = { from: envelope.state, to, oracle }; + return { + ...envelope, + state: to, + authorized: false, + receipt: { + operationKey: envelope.request.operationKey, + outcome: to, + workVersion: envelope.previewedVersion, + note, + }, + transitions: [...envelope.transitions, transition], + }; +} + +function invalid(envelope: WorkActionEnvelope, reason: string): never { + throw new Error( + `work-action-contract: illegal edge ${envelope.state} — ${reason} (operation ${envelope.request.operationKey})`, + ); +} + +/** Create the draft envelope. Validation is structural only; authorization is preview's job. */ +export function createWorkAction( + request: WorkActionRequest, +): WorkActionEnvelope { + if (!request.operationKey.trim()) + throw new Error("work-action-contract: operation key is required"); + if (!request.expectedWorkVersion.trim()) { + throw new Error("work-action-contract: expected work version is required"); + } + return { + state: "draft", + request, + authorized: false, + previewedVersion: null, + receipt: null, + transitions: [], + effectIssued: false, + }; +} + +/** + * draft → previewed, or → rejected. + * + * Oracles, in order: the actor holds the preview role; the expected work + * version matches the authoritative fixture. An unreadable authoritative + * version is `uncertain` (never a silent apply), a mismatch is `conflict`. + */ +export function previewWorkAction( + envelope: WorkActionEnvelope, + actor: WorkActionActor, + authority: WorkActionAuthority, +): WorkActionEnvelope { + if (envelope.state !== "draft") + invalid(envelope, "preview requires a draft envelope"); + + const roles = authority.readRoles(actor.id); + if ( + !roles.includes("work-action/preview") || + !actor.roles.includes("work-action/preview") + ) { + return refuse( + envelope, + "rejected", + "work-action/authorized-actor", + "actor lacks the preview role", + ); + } + + const version = authority.readWorkVersion(envelope.request.objectRef); + if (version === null) { + const transition: WorkActionTransition = { + from: "draft", + to: "uncertain", + oracle: "work-action/expected-version-readable", + }; + return { + ...envelope, + state: "uncertain", + authorized: false, + receipt: { + operationKey: envelope.request.operationKey, + outcome: "uncertain", + workVersion: null, + note: "authoritative work version is unreadable", + }, + transitions: [...envelope.transitions, transition], + }; + } + if (version !== envelope.request.expectedWorkVersion) { + return refuse( + envelope, + "conflict", + "work-action/expected-version", + `expected ${envelope.request.expectedWorkVersion}, authoritative ${version}`, + ); + } + + return { + ...envelope, + state: "previewed", + authorized: true, + previewedVersion: version, + transitions: [ + ...envelope.transitions, + { + from: "draft", + to: "previewed", + oracle: "work-action/expected-version", + }, + ], + }; +} + +/** previewed → accepted. The version and the actor's role are re-read here. */ +export function acceptWorkAction( + envelope: WorkActionEnvelope, + actor: WorkActionActor, + authority: WorkActionAuthority, +): WorkActionEnvelope { + if (envelope.state !== "previewed") + invalid(envelope, "accept requires a previewed envelope"); + + const roles = authority.readRoles(actor.id); + if ( + !roles.includes("work-action/accept") || + !actor.roles.includes("work-action/accept") + ) { + return refuse( + envelope, + "rejected", + "work-action/authorized-actor", + "actor lacks the accept role", + ); + } + const version = authority.readWorkVersion(envelope.request.objectRef); + if (version === null) { + const transition: WorkActionTransition = { + from: "previewed", + to: "uncertain", + oracle: "work-action/expected-version-readable", + }; + return { + ...envelope, + state: "uncertain", + authorized: false, + receipt: { + operationKey: envelope.request.operationKey, + outcome: "uncertain", + workVersion: null, + note: "authoritative work version became unreadable after preview", + }, + transitions: [...envelope.transitions, transition], + }; + } + if (version !== envelope.previewedVersion) { + return refuse( + envelope, + "conflict", + "work-action/expected-version", + `work moved from ${envelope.previewedVersion} to ${version} after preview`, + ); + } + return { + ...envelope, + state: "accepted", + transitions: [ + ...envelope.transitions, + { + from: "previewed", + to: "accepted", + oracle: "work-action/authorized-actor", + }, + ], + }; +} + +/** + * accepted → running, issuing the downstream effect exactly once, then to + * the outcome the downstream reports. + * + * Gates, in order, all before any effect: + * - authorization is re-read (a revoked role ends in `rejected`); + * - the authoritative version is re-read (unreadable ends in `uncertain`, + * moved since preview ends in `conflict`), so work that changed after + * accept is never applied; + * - the operation key is claimed through the authority. A key another + * envelope already claimed ends this envelope in `rejected` with no + * effect, and its receipt is the ORIGINAL operation's receipt (or a + * rejected receipt saying the first apply is still in flight). + * + * Replaying apply on the same envelope object returns it unchanged, so the + * cheap in-process replay never reaches the authority at all. + */ +export function applyWorkAction( + envelope: WorkActionEnvelope, + actor: WorkActionActor, + authority: WorkActionAuthority, + report: { + outcome: + | "verified_complete" + | "partial" + | "pending_sync" + | "conflict" + | "uncertain"; + note?: string; + }, +): WorkActionEnvelope { + if (envelope.effectIssued) return envelope; + if (envelope.state !== "accepted") + invalid(envelope, "apply requires an accepted envelope"); + + // Authorization is re-read at the apply gate: a role revoked between + // accept and apply must fail before any consumer effect. + const roles = authority.readRoles(actor.id); + if (!roles.includes("work-action/apply")) { + return refuse( + envelope, + "rejected", + "work-action/authorized-actor", + "actor lost the apply role before apply", + ); + } + + const current = authority.readWorkVersion(envelope.request.objectRef); + if (current === null) { + return refuse( + envelope, + "uncertain", + "work-action/expected-version-readable", + "authoritative work version became unreadable before apply", + ); + } + if (current !== envelope.previewedVersion) { + return refuse( + envelope, + "conflict", + "work-action/expected-version", + `work moved from ${envelope.previewedVersion} to ${current} before apply`, + ); + } + + const claim = authority.claimOperation(envelope.request.operationKey); + if (!claim.claimed) { + const refused = refuse( + envelope, + "rejected", + "work-action/operation-key", + "operation key already applied by another envelope", + ); + return claim.receipt === null + ? { + ...refused, + receipt: { + ...(refused.receipt as WorkActionReceipt), + note: "operation key already claimed; the first apply is still in flight", + }, + } + : { ...refused, receipt: claim.receipt }; + } + + authority.issueEffect(envelope.request); + + const running: WorkActionEnvelope = { + ...envelope, + state: "running", + effectIssued: true, + transitions: [ + ...envelope.transitions, + { from: "accepted", to: "running", oracle: "work-action/effect-issued" }, + ], + }; + + const workVersion = authority.readWorkVersion(envelope.request.objectRef); + const target = report.outcome; + if (!canTransition("running", target)) + invalid({ ...running, state: "running" }, `downstream reported ${target}`); + + const receipt: WorkActionReceipt = { + operationKey: envelope.request.operationKey, + outcome: target, + workVersion, + note: report.note ?? "", + }; + authority.recordReceipt(receipt); + return { + ...running, + state: target, + receipt, + transitions: [ + ...running.transitions, + { from: "running", to: target, oracle: "work-action/downstream-outcome" }, + ], + }; +} + +/** + * The receipt oracle: for a finished envelope, the receipt names the same + * operation key the request carried and no second effect was issued. Used by + * the replay test and by callers that dedupe on the operation key. + */ +export function receiptFor( + envelope: WorkActionEnvelope, +): WorkActionReceipt | null { + return envelope.receipt; +} diff --git a/pm-stack/aggregator/test/work-action-contract.test.ts b/pm-stack/aggregator/test/work-action-contract.test.ts new file mode 100644 index 0000000000..7faf1a6804 --- /dev/null +++ b/pm-stack/aggregator/test/work-action-contract.test.ts @@ -0,0 +1,426 @@ +// MOB-05 contract tests (#9472). Model-based: the state table below IS the +// design's lifecycle, and each test names the oracle that decides its edge. +// +// Oracles used here: +// - the declared edge table (WORK_ACTION_EDGES) — a transition the design does +// not name must be impossible, and every state the design names must be +// reachable through the declared chain; +// - the expected-work-version fixture (an authoritative version per object) +// — stale or unreadable versions never reach an effect; +// - the effect sink's call count — one effect per operation key, proven by +// replaying apply on the same envelope and applying a second envelope +// that carries the same key; +// - edge conformance — every transition any operation records is one the +// edge table declares. +import { describe, expect, test } from "bun:test"; +import { + type WorkActionReceipt, + WORK_ACTION_EDGES, + WORK_ACTION_STATES, + acceptWorkAction, + applyWorkAction, + canTransition, + createWorkAction, + isTerminalState, + previewWorkAction, + type WorkActionActor, + type WorkActionAuthority, + type WorkActionEnvelope, + type WorkActionRequest, + type WorkActionState, +} from "../src/work-action-contract.ts"; + +const ALL_ROLES = [ + "work-action/preview", + "work-action/accept", + "work-action/apply", +] as const; + +const actor = (roles: readonly string[] = ALL_ROLES): WorkActionActor => ({ + kind: "drew", + id: "drew", + roles, +}); + +/** The authoritative fixture: one work version per object, mutable so a test + * can move the work between preview and apply. */ +function fixture(objectRef: string, version: string | null) { + const versions = new Map([[objectRef, version]]); + const effects: WorkActionRequest[] = []; + const rolesByActor = new Map([ + ["drew", ALL_ROLES], + ]); + // The server's operation-key store: present means claimed, the value is + // the receipt once the first apply finished. + const operations = new Map(); + const authority: WorkActionAuthority = { + readWorkVersion: (ref) => versions.get(ref) ?? null, + readRoles: (id) => rolesByActor.get(id) ?? [], + issueEffect: (request) => effects.push(request), + claimOperation: (key) => { + if (!operations.has(key)) { + operations.set(key, null); + return { claimed: true }; + } + return { claimed: false, receipt: operations.get(key) ?? null }; + }, + recordReceipt: (receipt) => operations.set(receipt.operationKey, receipt), + }; + return { + authority, + effects, + operations, + setVersion: (v: string | null) => versions.set(objectRef, v), + setRoles: (id: string, roles: readonly string[]) => + rolesByActor.set(id, roles), + }; +} + +const request = (over: Partial = {}): WorkActionRequest => ({ + operationKey: "op-9472-0001", + kind: "triage", + objectRef: "orch:item-9472", + action: "reprioritize", + payload: { priority: 30 }, + expectedWorkVersion: "wv-7", + ...over, +}); + +/** draft → previewed → accepted → running → verified_complete, the happy chain. */ +function accepted(over: Partial = {}) { + const fx = fixture( + request(over).objectRef, + request(over).expectedWorkVersion, + ); + const envelope = acceptWorkAction( + previewWorkAction(createWorkAction(request(over)), actor(), fx.authority), + actor(), + fx.authority, + ); + return { fx, envelope }; +} + +describe("work action contract — state machine (oracle: declared edge table)", () => { + test("every design state is declared and terminal states have no outgoing edge", () => { + const expectedStates: WorkActionState[] = [ + "draft", + "previewed", + "accepted", + "running", + "pending_sync", + "partial", + "conflict", + "uncertain", + "rejected", + "verified_complete", + ]; + expect([...WORK_ACTION_STATES].sort()).toEqual([...expectedStates].sort()); + for (const state of [ + "conflict", + "uncertain", + "rejected", + "verified_complete", + ] as WorkActionState[]) { + expect(WORK_ACTION_EDGES[state]).toEqual([]); + expect(isTerminalState(state)).toBe(true); + } + }); + + test("the happy chain draft→previewed→accepted→running→verified_complete is the only path to complete", () => { + const { fx, envelope } = accepted(); + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(applied.state).toBe("verified_complete"); + expect(applied.transitions.map((t) => `${t.from}->${t.to}`)).toEqual([ + "draft->previewed", + "previewed->accepted", + "accepted->running", + "running->verified_complete", + ]); + // No shortcut: a draft cannot jump to complete. + expect(canTransition("draft", "verified_complete")).toBe(false); + expect(canTransition("previewed", "running")).toBe(false); + }); + + test("downstream outcomes land on their declared state and keep the receipt", () => { + for (const outcome of [ + "partial", + "pending_sync", + "conflict", + "uncertain", + ] as const) { + const { fx, envelope } = accepted({ operationKey: `op-${outcome}` }); + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome, + note: outcome, + }); + expect(applied.state).toBe(outcome); + expect(applied.receipt?.outcome).toBe(outcome); + expect(applied.receipt?.operationKey).toBe(`op-${outcome}`); + } + }); + + test("illegal edges throw instead of silently advancing", () => { + const { fx } = accepted({ operationKey: "op-illegal" }); + const draft = createWorkAction(request({ operationKey: "op-illegal" })); + expect(() => + applyWorkAction(draft, actor(), fx.authority, { + outcome: "verified_complete", + }), + ).toThrow(/illegal edge draft/); + const complete = applyWorkAction( + acceptWorkAction( + previewWorkAction( + createWorkAction(request({ operationKey: "op-illegal" })), + actor(), + fx.authority, + ), + actor(), + fx.authority, + ), + actor(), + fx.authority, + { outcome: "verified_complete" }, + ); + expect(() => acceptWorkAction(complete, actor(), fx.authority)).toThrow( + /illegal edge verified_complete/, + ); + }); +}); + +describe("work action contract — expected work version (oracle: authoritative fixture)", () => { + test("work_action_stale_version_conflicts_without_effect", () => { + const fx = fixture("orch:item-9472", "wv-9"); // the work moved on + const envelope = createWorkAction(request({ expectedWorkVersion: "wv-7" })); + const previewed = previewWorkAction(envelope, actor(), fx.authority); + expect(previewed.state).toBe("conflict"); + expect(previewed.authorized).toBe(false); + expect(previewed.receipt).toMatchObject({ + outcome: "conflict", + operationKey: "op-9472-0001", + }); + expect(fx.effects).toHaveLength(0); // no effect on a stale expectation + }); + + test("a version moved between preview and apply conflicts before the effect", () => { + const fx = fixture("orch:item-9472", "wv-7"); + const previewed = previewWorkAction( + createWorkAction(request()), + actor(), + fx.authority, + ); + expect(previewed.state).toBe("previewed"); + fx.setVersion("wv-8"); // someone else applied first + const moved = acceptWorkAction(previewed, actor(), fx.authority); + expect(moved.state).toBe("conflict"); + expect(moved.effectIssued).toBe(false); + expect(fx.effects).toHaveLength(0); + }); + + test("an unreadable authoritative version is uncertain, never a silent apply", () => { + const fx = fixture("orch:item-9472", null); + const previewed = previewWorkAction( + createWorkAction(request()), + actor(), + fx.authority, + ); + expect(previewed.state).toBe("uncertain"); + expect(previewed.receipt?.outcome).toBe("uncertain"); + expect(fx.effects).toHaveLength(0); + }); +}); + +describe("work action contract — idempotency (oracle: effect sink call count)", () => { + test("replaying apply on the same envelope issues one effect and returns the same receipt", () => { + const { fx, envelope } = accepted(); + const first = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + const replay = applyWorkAction(first, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(fx.effects).toHaveLength(1); + expect(replay.receipt).toEqual(first.receipt); + expect(replay.transitions.length).toBe(first.transitions.length); + expect(replay.state).toBe("verified_complete"); + }); + + test("the effect carries the operation key exactly once per applied envelope", () => { + const { fx, envelope } = accepted(); + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(applied.effectIssued).toBe(true); + expect(fx.effects).toHaveLength(1); + expect(fx.effects[0]?.operationKey).toBe("op-9472-0001"); + }); +}); + +describe("work action contract — operation key across envelopes (oracle: effect sink call count)", () => { + test("a second envelope with the same operation key issues no effect and returns the original receipt", () => { + const { fx, envelope } = accepted(); + const first = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + note: "first", + }); + const second = acceptWorkAction( + previewWorkAction(createWorkAction(request()), actor(), fx.authority), + actor(), + fx.authority, + ); + expect(second.state).toBe("accepted"); + const replayed = applyWorkAction(second, actor(), fx.authority, { + outcome: "verified_complete", + note: "second", + }); + expect(fx.effects).toHaveLength(1); + expect(replayed.effectIssued).toBe(false); + expect(replayed.state).toBe("rejected"); + expect(replayed.receipt).toEqual(first.receipt); + }); + + test("a key claimed by an apply still in flight refuses the second envelope without an effect", () => { + const { fx, envelope } = accepted(); + fx.operations.set("op-9472-0001", null); // first apply claimed, not finished + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(fx.effects).toHaveLength(0); + expect(applied.state).toBe("rejected"); + expect(applied.receipt?.note).toMatch(/still in flight/); + }); +}); + +describe("work action contract — version re-read at apply (oracle: authoritative fixture)", () => { + test("work that moved after accept conflicts at apply with no effect", () => { + const { fx, envelope } = accepted(); + fx.setVersion("wv-8"); + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(applied.state).toBe("conflict"); + expect(applied.effectIssued).toBe(false); + expect(fx.effects).toHaveLength(0); + }); + + test("an authoritative version unreadable at apply is uncertain with no effect", () => { + const { fx, envelope } = accepted(); + fx.setVersion(null); + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(applied.state).toBe("uncertain"); + expect(fx.effects).toHaveLength(0); + }); +}); + +describe("work action contract — edge conformance (oracle: declared edge table)", () => { + test("every transition any operation records is a declared edge", () => { + const seen: WorkActionEnvelope[] = []; + // preview: conflict and uncertain + seen.push( + previewWorkAction( + createWorkAction(request()), + actor(), + fixture("orch:item-9472", "wv-9").authority, + ), + previewWorkAction( + createWorkAction(request()), + actor(), + fixture("orch:item-9472", null).authority, + ), + ); + // accept and apply: moved, unreadable, revoked, and every outcome + for (const move of ["wv-8", null] as const) { + const fx = fixture("orch:item-9472", "wv-7"); + const previewed = previewWorkAction( + createWorkAction(request()), + actor(), + fx.authority, + ); + fx.setVersion(move); + seen.push(acceptWorkAction(previewed, actor(), fx.authority)); + const later = accepted(); + later.fx.setVersion(move); + seen.push( + applyWorkAction(later.envelope, actor(), later.fx.authority, { + outcome: "verified_complete", + }), + ); + } + for (const outcome of [ + "verified_complete", + "partial", + "pending_sync", + "conflict", + "uncertain", + ] as const) { + const { fx, envelope } = accepted({ operationKey: `op-edge-${outcome}` }); + seen.push(applyWorkAction(envelope, actor(), fx.authority, { outcome })); + } + for (const envelope of seen) { + for (const t of envelope.transitions) { + expect(`${t.from}->${t.to}:${canTransition(t.from, t.to)}`).toBe( + `${t.from}->${t.to}:true`, + ); + } + } + }); +}); + +describe("work action contract — server-side authorization (oracle: re-read roles)", () => { + test("an actor without the preview role is rejected before any read of the work", () => { + const fx = fixture("orch:item-9472", "wv-7"); + const previewed = previewWorkAction( + createWorkAction(request()), + actor([]), + fx.authority, + ); + expect(previewed.state).toBe("rejected"); + expect(previewed.receipt?.outcome).toBe("rejected"); + expect(fx.effects).toHaveLength(0); + }); + + test("a role revoked between accept and apply fails before the consumer effect", () => { + const { fx, envelope } = accepted(); + fx.setRoles("drew", ["work-action/preview", "work-action/accept"]); // apply revoked + const applied = applyWorkAction(envelope, actor(), fx.authority, { + outcome: "verified_complete", + }); + expect(applied.state).toBe("rejected"); + expect(applied.receipt?.outcome).toBe("rejected"); + expect(fx.effects).toHaveLength(0); + }); + + test("a client claiming a role the server does not grant is refused at preview", () => { + const fx = fixture("orch:item-9472", "wv-7"); + fx.setRoles("drew", []); // server says: no roles + const previewed = previewWorkAction( + createWorkAction(request()), + actor(ALL_ROLES), + fx.authority, + ); + expect(previewed.state).toBe("rejected"); + expect(fx.effects).toHaveLength(0); + }); +}); + +describe("work action contract — structural validation", () => { + test("an envelope needs an operation key and an expected version", () => { + expect(() => createWorkAction(request({ operationKey: " " }))).toThrow( + /operation key is required/, + ); + expect(() => + createWorkAction(request({ expectedWorkVersion: " " })), + ).toThrow(/expected work version is required/); + }); + + test("a fresh envelope starts as a draft with no effect and no receipt", () => { + const envelope: WorkActionEnvelope = createWorkAction(request()); + expect(envelope.state).toBe("draft"); + expect(envelope.effectIssued).toBe(false); + expect(envelope.receipt).toBeNull(); + expect(envelope.authorized).toBe(false); + }); +});