Skip to content

Reference host: the Annex B corrective action

The other recipes each isolate one rule. This one assembles them into a host. It runs the corrective action from STANDARD.md Annex B end to end, with released SDK 0.5.1 APIs, and prints the same record in TypeScript, Rust and Python.

Annex B is informative. It illustrates the semantic contract; it is not a regulatory procedure, and its thresholds are project choices for the adopting organisation. The recipe keeps that status: every id the run records, such as the mission, contract, run, case, operation, approval and wait ids, carries the example: prefix, and the result record is marked exampleOnly. Principal, policy and resource names such as human:designated-verifier, policy:example:annex-b:1 and case:guarding-17 are local to the recipe and do not take the prefix. Physical implementation and the decision to return the equipment to service stay separate human responsibilities, outside the workflow.

The recipe runs the working path and the failure paths a host must handle truthfully: a case write that times out and is resolved by a read-only reconcile at the next start-up, an agent’s denied attempt to widen its own grant, a denied adjust, a placeholder adapter that reports UNKNOWN, and an acceptance that ends INCONCLUSIVE and DEFERRED. It is the known-good host the agent skills compare against.

The work order has two runs. Run 1, example:run:guarding-17, assembles the corrective-action package. Its plan is assembling and assessing the available package, so it can complete while acceptance is deferred, as Annex B allows:

Node Kind What happens Completion proof
collect-records TASK (AGENT) The investigator agent reads the approved inspection records The confirmed read operation
request-more-records LOOP, at most 3 iterations The agent requests each kind of record it still lacks One confirmed read per iteration, and done
draft-action TASK (AGENT) The agent drafts the corrective action from the records it read The confirmed draft operation
engineering-review APPROVAL The engineering reviewer approves the exact case update The unexpired approval
update-case TASK (TOOL) The case record is updated under that approval and a version precondition The confirmed write operation
end END The package is assembled Disposition COMPLETED

Once run 1 completes, the designated verifier assesses it. No implementation evidence exists yet, so the two criteria that need it are INCONCLUSIVE, and the verifier defers acceptance. The run’s result is Annex B’s illustrative result exactly: COMPLETED, INCONCLUSIVE, DEFERRED, and not a verified success.

The assessment of run 1 sits outside its graph because the SDK completes a VERIFICATION node only on a PASSED verification and an ACCEPTANCE node only on an ACCEPTED decision. Those nodes belong to the linked follow-up run, example:run:guarding-17:implementation, whose active task is obtaining the evidence:

Node Kind What happens Completion proof
implementation-evidence WAIT The authorized technician’s attestation arrives as an event The satisfied wait
verification VERIFICATION The designated verifier assesses every criterion against the package and the attestation The PASSED verification revision
acceptance ACCEPTANCE The designated verifier accepts that verification revision, as Annex B’s criteria require The ACCEPTED revision
notify-case-owner TASK (TOOL) The host notifies the case owner, who decides return to service The confirmed notification operation
follow-up-end END The follow-up is complete Disposition COMPLETED

The notification goes through a placeholder adapter, so it never confirms: the follow-up run is verified and accepted but stays held at notify-case-owner, and is not a verified success either.

The run loop is plain host code. It reads the snapshot, answers the inbox while the run is WAITING, otherwise takes the next node from readyNodes, performs that node’s work and completes it with its proof. The SDK checks each proof by kind in completeNode, so a node cannot complete without a confirmed effect, a live approval, a satisfied wait or the right assessment. A wait opens a durable wait record, moves the run to WAITING, and routes the wait to exactly one principal; join brings the run back to READY once that principal resumes it.

Real, not mocked:

  • the run loop over the graph, with ready nodes, dispatch, per-kind completion proofs, waits and the loop bound;
  • a deny-by-default authorizer that returns an attributed decision: the session’s actor, the decision class (HUMAN for a human principal, DETERMINISTIC otherwise) and the policy revision;
  • the limits ledger reservation paired with mission dispatch in the order the budgets chapter documents;
  • truthful effect outcomes, evidence and verification;
  • start-up recovery: the host closes its stores when it stops and reopens them at the next start-up, where recover and a read-only reconcile run before any new work;
  • one mission store and one ledger store for the one worker;
  • an injected clock, the same one for both stores;
  • immutable local artifacts: content-addressed, created once with create-new and fsync, never rewritten.

Simulated, and each marked “replace before deployment” in the code:

Simulated part In the recipe Replace it with
Human identity Fixed sessions for the runner, worker, agent, owner, reviewer, technician and verifier Authenticated principals, verified before a command reaches the authorizer
The inbox An in-memory queue that the script answers An authenticated application inbox; a notification is an application effect with its own outcome
Event ingress The technician’s attestation built in the script An authenticated event source and a check of the attesting person’s authority
Telemetry export A collector that accepts every payload A collector client with a timeout and redirects disabled
The records system, the agent and the case-record system Local stand-ins with fixed records, a deterministic drafter and a versioned JSON file The real systems, each behind its own effect adapter and operation contract
The notification client A placeholder adapter that calls nothing and reports UNKNOWN The application’s notification client, behind an adapter with its own operation contract
An agent that oversteps A scripted request for a wider grant and a higher cost limit Nothing: a real agent’s requests reach the same authorizers
The ledger settlement after reconciliation The case owner settles the ledger on the read-back, scripted An authenticated human decision on the reconciliation evidence

The restart happens inside one process. It closes and reopens both stores, but the recipe’s evidence index (which artifact evidences which attempt) and its trail of committed steps stay in memory; a deployed host keeps them durable beside its artifacts.

The clock the recipe injects is scripted, so every language prints the same record. Beside it the recipe defines the real clock a deployed host injects instead, which reads trusted UTC time in epoch milliseconds from the system clock. The recipe’s contract deadline is 8 hours after the epoch, long past on the real clock, so it checks only that the real clock reads canonical epoch milliseconds past that deadline.

Out of scope, and nothing here covers them: secrets, sandboxing, child runs and deployment verification. The recipe delivers no credential, isolates no process, starts no child run and does not verify a deployment.

The authorizer allows a command only when a rule names its session; everything else is denied. The rules:

Session Allowed
Runner (host:runner) startRun, continueRun (which recover issues), registerGraph, attachGraph, wait, transition, join, completeNode
Agent (agent:investigator) admit for its own subject, for an action on the contract’s list; update-case only with an approval
Worker (host:worker-1) dispatch and settle, which the coordinator issues around the adapter call and in reconcile
Case owner (human:case-owner) grant
Engineering reviewer approve, naming itself as approver
Designated verifier verify, naming itself as assessor, and accept, naming itself as authority
The principal a wait is routed to resume of that wait

The agent can request work but cannot report its outcome, approve it, verify it or change any grant. The ledger has its own deny-by-default authorizer: the agent may reserve; the worker may dispatch, settle, unknown and release; the case owner may settle an attempt the ledger holds as UNKNOWN; and a settle is allowed only with the digest of the artifact that evidences the outcome. No session may adjust.

The case owner, a human, writes the agent’s root grant. A root grant has no parent, so the contract is its only bound: the SDK refuses a grant that lists an action or resource the contract does not, a limit above the budget or an expiry after the deadline. This one is narrower than the contract: 10 capability calls against a budget of 100, with no delegation.

Before the run loop starts, a scripted agent oversteps. It submits a grant for a wider grant of its own, with the contract’s whole budget as its limit; the mission authorizer denies it as AUTHORITY_DENIED, and the store records the rejection, attributed to the agent. It then requests a ledger adjust to raise the work order’s cost limit; the ledger authorizer allows no adjustment, so the ledger refuses it as AUTHORIZATION_DENIED and records nothing. The record shows the grant and the work order’s limit unchanged. Only a human changes an agent’s permissions or limits, and in the ledger an adjust also needs a human actor with an evidence reference.

The engineering-review node opens an authorization wait routed to the reviewer. The case update under review is one exact action: the new status, the digest of the drafted corrective action, the digests of the record revisions behind it, and the precondition that the record is still at version 1. The reviewer approves that action’s fingerprint, with an expiry an hour ahead and a use count of one. The update-case admission carries the approval. The SDK recomputes the fingerprint from the admitted action, so a changed draft, a different set of records or another version would be refused as APPROVAL_INVALID, and a second write would be refused as APPROVAL_CONSUMED. The record shows the approval consumed by that one operation.

The reviewer’s tool derives the fingerprint from the action it shows, with the SDK’s fingerprint function, the same function admission uses; no hash is typed in. The recipe’s assertions check it against a known value.

Every effect, the reads, the draft, the case write and the notification alike, runs through one host function, perform:

  1. reserve the attempt in the limits ledger;
  2. admit the mission attempt; a refused admission releases the unused reservation;
  3. record ledger dispatch, before any external call;
  4. call Coordinator.dispatch, which commits DISPATCHED, calls the adapter and settles its outcome;
  5. settle the ledger with the actual cost and the evidence digest, or mark it unknown, which keeps the whole reservation.

The two stores do not share a commit. A crash between them conservatively keeps exposure, and only reconciliation or a human decision resolves it. An outcome other than CONFIRMED_APPLIED stops the host before the node completes, so no further work starts; the host never retries on its own. A restarted host never repeats an operation it already admitted: it completes the node only when that operation’s outcome is confirmed. The record of an UNKNOWN attempt is its outcome and the ledger’s unknown mark; the recipe writes no separate hold.

Before it takes any work, the host opens its stores and recovers every run that is not terminal. Coordinator.recover continues the run in a new segment, which fences any attempt prepared under the old one, and lists the run’s unresolved attempts. The host reconciles each through the adapter that dispatched it, read-only. When reconciliation confirms the outcome, the case owner settles the ledger on the read-back; the ledger accepts a settlement of an UNKNOWN attempt only from a human with evidence. When the outcome is still UNKNOWN, nothing settles it and the run stays held for a human.

The recipe starts the host at each of these points:

  • At the first start-up there is no open run.
  • The case write commits and then loses its acknowledgment, as STANDARD.md Annex C.1 suggests a test target should, so the attempt is UNKNOWN and the host stops. At the next start-up, reconcile finds the operation’s own version in the case record and settles the attempt CONFIRMED_APPLIED, with the record it read as evidence; the case owner settles the ledger on it, and run 1 continues to completion.
  • The follow-up run’s notification is UNKNOWN and the host stops again. At the next start-up the placeholder’s reconcile reports UNKNOWN too, so the notification keeps its reservation in both stores and the follow-up run stays held.

The adapters follow the SDK forms of NG-01 and NG-02 from the governance rule set. A thrown error reaches the coordinator, which records UNKNOWN; no adapter turns a timeout or an exception into CONFIRMED_APPLIED or CONFIRMED_NOT_APPLIED.

  • The records reader and the drafter report CONFIRMED_APPLIED once their artifact is durable. A read leaves nothing at the source to look up, so their reconcile reports UNKNOWN for a human to resolve.
  • The case-record stand-in has an operation contract: it applies an update only at the expected version, applies nothing when that precondition fails, and keeps a history of which operation wrote each version. A repeated operation is therefore recognised rather than applied twice, and a failed precondition is CONFIRMED_NOT_APPLIED, with the record it read as evidence, only for an operation the history shows wrote no version. Its reconcile is read-only: CONFIRMED_APPLIED, with the record it read as evidence, when the history shows this operation wrote its version, otherwise UNKNOWN.
  • The placeholder adapter calls nothing and reports UNKNOWN from execute and reconcile alike. A host wired to an adapter that is not written yet therefore holds the node, instead of claiming the effect happened or did not.

Each language prints one canonical JSON record, and the records are identical:

  • result, in the shape of Annex B’s illustrative result, with exampleOnly: true: run 1 is COMPLETED, INCONCLUSIVE and DEFERRED, issue-identified and engineering-reviewed are PASS, and the two criteria that need implementation evidence are INCONCLUSIVE.
  • followUp: the follow-up run is RUNNING, PASSED and ACCEPTED, and not a verified success, with the reasons EXECUTION_NOT_COMPLETED and EFFECT_UNKNOWN.
  • approval: the approver, fingerprint, expiry, use count and consuming operation, beside the case update it is bound to.
  • effects: for each operation, its node, outcome and actual cost, the steps the host committed in order, including recovery and reconciliation, and the ledger attempt’s final status, amount, cost, evidence digest and the actor that settled it.
  • startUps: for each start-up, the runs it recovered, each with its new segment and the outcome reconciliation reached for each unresolved attempt.
  • grant, denials and rejections: the root grant as authored and who granted it, each request of the agent’s that was refused, with its code, and the mission store’s record of the refused grant.
  • assessments: for each run, the assessor, the evidence digests, the verification state, the acceptance authority and the decision.
  • accounting: mission spend and reservation beside the ledger’s cost and attempt usage, with the notification’s reservation still held, and telemetry, the export result.

Run the Annex B corrective action through a reference host · Executable reference host; simulated identity, inbox, event ingress, telemetry export and external systems, each marked replace before deployment

import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {closeSync,fsyncSync,mkdtempSync,openSync,readFileSync,renameSync,writeFileSync,writeSync} from 'node:fs';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {assessSuccess,canonical,fingerprint,parseContract,parseStrict,readyNodes,type Action,type Command,type Snapshot} from '@aiws/sdk';
import {SqliteStore} from '@aiws/sdk/sqlite';
import {Coordinator,type Authorizer,type Clock,type EffectAdapter} from '@aiws/sdk/runtime';
import {classifyResponse} from '@aiws/sdk/observability';
import {LimitCoordinator,LimitStore,type LimitAuthorizer,type LimitConfig} from '@aiws/sdk/limits';
// STANDARD.md Annex B, the EH&S corrective action, run by a reference host. Annex B illustrates the semantic
// contract; it is not a regulatory procedure. Every id the run records keeps the example: prefix (principal, policy and
// resource names are local to the recipe) and the result is exampleOnly.
// Out of scope, and not covered here: secrets, sandboxing, child runs and deployment verification.
// Run 1 assembles and assesses the corrective-action package; the linked follow-up run obtains the implementation evidence.
const RUN='example:run:guarding-17',FOLLOW_UP='example:run:guarding-17:implementation',WORK_ORDER='example:work-order:guarding-17';
const GRANT='example:grant:investigator',CASE='example:case:guarding-17',APPROVAL='example:approval:engineering-review';
const VERIFICATION='example:verification:guarding-17:1',FOLLOW_UP_VERIFICATION='example:verification:guarding-17:2';
const CRITERIA=['issue-identified','engineering-reviewed','implementation-evidenced','effectiveness-accepted'];
const POLICY='policy:example:annex-b:1';
const TERMINAL=['COMPLETED','FAILED','CANCELED','REJECTED'];
const contract=parseContract(JSON.stringify({
id:'example:contract:guarding-17:1',missionId:'example:mission:guarding-17',aiwsEdition:'0.4',profile:'finite-v1',
budget:'100',deadline:'28800000',maxAttempts:'2',maxAuthorizationAgeMs:'1000',requiresApproval:false,features:['graphs'],
criteria:CRITERIA,
actions:['read-records','draft','update-case','notify'],resources:['inspection-records','case-draft','case:guarding-17','case-owner-inbox'],
}));
// The resource envelope, approved by a human before the run: 100 capability calls and 8 elapsed hours.
const envelope=parseStrict(JSON.stringify({protocol:'aiws-limits/1',ledgerId:'example:ledger:guarding-17',costUnit:'capability-call',
approvalRef:'example:approval:resource-envelope',scopes:[
{id:WORK_ORDER,parentId:null,kind:'WORK_ORDER',workOrderId:WORK_ORDER,runId:null,nodeId:null,dependsOn:[],startMs:'0',
limits:{cost:'100',handoff:'10',activeMs:null,elapsedMs:'28800000',attempts:'100'}},
...[RUN,FOLLOW_UP].map(runId=>({id:runId,parentId:WORK_ORDER,kind:'RUN',workOrderId:WORK_ORDER,runId,nodeId:null,dependsOn:[],startMs:'0',
limits:{cost:null,handoff:'0',activeMs:null,elapsedMs:null,attempts:null}}))]})) as unknown as LimitConfig;
// Run 1's plan is assembling and assessing the available package, so it can complete while acceptance is deferred.
// The SDK completes a VERIFICATION node only on PASSED and an ACCEPTANCE node only on ACCEPTED, so run 1 is assessed
// after it completes, and those nodes belong to the follow-up run, whose active task is obtaining the evidence.
const packageGraph={id:'example:graph:corrective-action',revision:'1',nodes:[
{id:'collect-records',kind:'TASK',dependsOn:[],config:{executionKind:'AGENT'}},
{id:'request-more-records',kind:'LOOP',dependsOn:['collect-records'],config:{maxIterations:'3'}},
{id:'draft-action',kind:'TASK',dependsOn:['request-more-records'],config:{executionKind:'AGENT'}},
{id:'engineering-review',kind:'APPROVAL',dependsOn:['draft-action'],config:{}},
{id:'update-case',kind:'TASK',dependsOn:['engineering-review'],config:{executionKind:'TOOL'}},
{id:'end',kind:'END',dependsOn:['update-case'],config:{}}]};
const followUpGraph={id:'example:graph:implementation-evidence',revision:'1',nodes:[
{id:'implementation-evidence',kind:'WAIT',dependsOn:[],config:{}},
{id:'verification',kind:'VERIFICATION',dependsOn:['implementation-evidence'],config:{}},
{id:'acceptance',kind:'ACCEPTANCE',dependsOn:['verification'],config:{}},
{id:'notify-case-owner',kind:'TASK',dependsOn:['acceptance'],config:{executionKind:'TOOL'}},
{id:'follow-up-end',kind:'END',dependsOn:['notify-case-owner'],config:{}}]};
// Two clocks, each trusted UTC time in epoch milliseconds as a canonical decimal string. A deployed host injects the
// real one, read from the system clock. This recipe injects the scripted one, which only moves forward, so every
// language prints the same record; its contract deadline is 8 hours after the epoch, long past on the real clock.
const utcClock:Clock=()=>String(Date.now());
let scriptedMs=0n;
const scriptedClock:Clock=()=>scriptedMs.toString();
const clock=scriptedClock;
// Simulated human identity: replace before deployment. A deployed host authenticates every principal before
// its command reaches an authorizer; identity never comes from a command field or an event payload.
type Session={actor:string;kind:'HUMAN'|'AGENT'|'RULE'};
const RUNNER:Session={actor:'host:runner',kind:'RULE'},WORKER:Session={actor:'host:worker-1',kind:'RULE'};
const AGENT:Session={actor:'agent:investigator',kind:'AGENT'},OWNER:Session={actor:'human:case-owner',kind:'HUMAN'};
const REVIEWER:Session={actor:'human:engineering-reviewer',kind:'HUMAN'},TECHNICIAN:Session={actor:'human:authorized-technician',kind:'HUMAN'};
const VERIFIER:Session={actor:'human:designated-verifier',kind:'HUMAN'};
const routes=new Map<string,string>(); // wait id -> the one principal routed to answer it
// Deny by default: a command is allowed only when a rule below names its session.
const AGENT_ACTIONS=['read-records inspection-records','draft case-draft','update-case case:guarding-17','notify case-owner-inbox'];
function permits(session:Session,c:any):boolean{
switch(c.type){
case 'startRun':case 'continueRun':case 'registerGraph':case 'attachGraph':case 'completeNode':case 'wait':case 'join':case 'transition':
return session===RUNNER;
case 'admit':return session===AGENT&&c.subject===AGENT.actor&&AGENT_ACTIONS.includes(c.action.capability+' '+c.action.resource)
&&(c.action.capability!=='update-case'||c.approvalId!==undefined);
case 'dispatch':case 'settle':return session===WORKER;
case 'grant':return session===OWNER;
case 'approve':return session===REVIEWER&&c.approval.approver===REVIEWER.actor;
case 'resume':return routes.get(c.waitId)===session.actor;
case 'verify':return session===VERIFIER&&c.assessor===VERIFIER.actor;
case 'accept':return session===VERIFIER&&c.authority===VERIFIER.actor; // Annex B: accepted by the designated verifier
default:return false;
}
}
const authorizerFor=(session:Session):Authorizer=>async command=>{
const allowed=permits(session,command);
return {allowed,policy:allowed?'ALLOW':'DENY',mandatoryChecksOk:true,
context:{actor:session.actor,policyRevision:POLICY,decisionClass:session.kind==='HUMAN'?'HUMAN':'DETERMINISTIC'}};
};
const evidence=new Map<string,string>(); // attempt id -> digest of the artifact that evidences its outcome
const ledgerAuthorizerFor=(session:Session):LimitAuthorizer=>(request,state,now)=>{
const type=request.command.type,evidenceRef=type==='settle'?evidence.get(request.command.attemptId)??null:null;
const allowed=type==='reserve'?session===AGENT
// Only a human settles an UNKNOWN ledger attempt, on the evidence that resolved it.
:type==='settle'&&session===OWNER?state.attempts[request.command.attemptId]?.status==='UNKNOWN'
:['dispatch','settle','unknown','release'].includes(type)&&session===WORKER;
return {allowed:allowed&&(type!=='settle'||evidenceRef!==null),actorId:session.actor,actorKind:session.kind,policyRef:POLICY,evidenceRef,authorizedAtMs:now};
};
// One worker, so one mission store and one ledger store. Another worker opens its own; a store is never shared.
// The host opens both at each start-up; a restart closes and reopens them.
const directory=mkdtempSync(join(tmpdir(),'aiws-annex-b-'));
let store!:SqliteStore,ledgerStore!:LimitStore;
const mission=(session:Session)=>new Coordinator(store,authorizerFor(session),clock);
const ledger=(session:Session,command:Record<string,any>)=>new LimitCoordinator(ledgerStore,ledgerAuthorizerFor(session),clock)
.apply({requestId:command.type+':'+(command.attemptId??command.scopeId),expectedRevision:ledgerStore.snapshot().revision,command});
// Immutable local artifacts: content-addressed, written once with create-new and fsync, never rewritten.
const artifactPath=(digest:string)=>join(directory,digest.slice('sha256:'.length)+'.json');
function artifact(value:unknown):string{
const bytes=canonical(value),digest='sha256:'+createHash('sha256').update(bytes).digest('hex'),path=artifactPath(digest);
try{const file=openSync(path,'wx');try{writeSync(file,bytes);fsyncSync(file);}finally{closeSync(file);}}
catch(e:any){if(e.code!=='EEXIST'||readFileSync(path,'utf8')!==bytes)throw e;}
return digest;
}
// A local stand-in for the approved-records system: replace before deployment.
const RECORDS=[
{id:'example:record:inspection-17',kind:'inspection',approved:true,text:'Press 4 interlock guard lifts while the ram is energized'},
{id:'example:record:field-note-17',kind:'inspection',approved:false,text:'Unreviewed field note'},
{id:'example:record:maintenance-press-4',kind:'maintenance',approved:true,text:'Guard hinge replaced; interlock switch not retested'},
{id:'example:record:training-press-4',kind:'training',approved:true,text:'Operator lockout training is current'}];
const recordsReader:EffectAdapter={
async execute(operation,attempt){
const kind=operation.action.payload.kind;
evidence.set(attempt.id,artifact({kind,records:RECORDS.filter(r=>r.approved&&r.kind===kind)}));
return {effect:'CONFIRMED_APPLIED',actualCost:'1'};
},
// A read leaves nothing at the source to look up, so a lost response stays UNKNOWN for a human to resolve.
async reconcile(){return {effect:'UNKNOWN',actualCost:'0'};},
};
// A deterministic stand-in for the investigator agent's model calls: replace before deployment. It asks for the kinds
// of record it still lacks and drafts the corrective action from the records it read.
const REQUIRED_KINDS=['inspection','maintenance','training'],collected:string[]=[];
const missingKind=()=>REQUIRED_KINDS.find(kind=>!collected.includes(kind));
const drafter:EffectAdapter={
async execute(operation,attempt){
const bundles=operation.action.payload.records.map((digest:string)=>parseStrict(readFileSync(artifactPath(digest),'utf8')) as any);
evidence.set(attempt.id,artifact({caseId:CASE,basedOn:bundles.flatMap((b:any)=>b.records.map((r:any)=>r.id)),
proposedAction:'Replace the press 4 interlock switch, retest the guard interlock and brief operators'}));
return {effect:'CONFIRMED_APPLIED',actualCost:'1'};
},
async reconcile(){return {effect:'UNKNOWN',actualCost:'0'};},
};
// A local stand-in for the external case-record system: replace before deployment. Its operation contract: it applies
// an update only at the expected version, applies nothing when that precondition fails, and keeps a history of which
// operation wrote each version. So a repeated operation is recognised instead of applied twice, and a failed
// precondition proves non-application only for an operation the history shows wrote no version.
// As STANDARD.md Annex C.1 suggests for a test target, it commits the first update and then drops the acknowledgment:
// the call times out, and the coordinator records UNKNOWN.
const casePath=join(directory,'case-record.json');
writeFileSync(casePath,canonical({caseId:CASE,version:1,status:'OPEN',correctiveAction:null,evidence:[],history:[]}));
let acknowledgmentsToDrop=1;
const caseRecord:EffectAdapter={
async execute(operation,attempt){
const record=parseStrict(readFileSync(casePath,'utf8')) as any,{payload,preconditions}=operation.action;
if(record.history.some((h:any)=>h.operationId===operation.id)){evidence.set(attempt.id,artifact(record));return {effect:'CONFIRMED_APPLIED',actualCost:'1'};}
if(record.version!==preconditions.version){evidence.set(attempt.id,artifact(record));return {effect:'CONFIRMED_NOT_APPLIED',actualCost:'1'};}
const next={caseId:record.caseId,version:record.version+1,...payload.update,evidence:payload.evidence,
history:[...record.history,{version:record.version+1,operationId:operation.id}]};
writeFileSync(casePath+'.next',canonical(next));renameSync(casePath+'.next',casePath);
if(acknowledgmentsToDrop>0){acknowledgmentsToDrop--;throw new Error('timeout: the case-record system did not acknowledge the update');}
evidence.set(attempt.id,artifact(next));
return {effect:'CONFIRMED_APPLIED',actualCost:'1'};
},
// Read-only: the history shows this operation wrote its version, or the outcome stays UNKNOWN. The record it read is
// the evidence.
async reconcile(operation,attempt){
const record=parseStrict(readFileSync(casePath,'utf8')) as any,version=operation.action.preconditions.version+1;
if(!record.history.some((h:any)=>h.operationId===operation.id&&h.version===version))return {effect:'UNKNOWN',actualCost:'0'};
evidence.set(attempt.id,artifact(record));
return {effect:'CONFIRMED_APPLIED',actualCost:'1'};
},
};
// A placeholder for an adapter not written yet: replace before deployment with the application's notification client.
// It calls nothing and reports UNKNOWN from execute and reconcile alike, so a host wired to it holds the node instead
// of claiming that the notification was, or was not, delivered.
const placeholder:EffectAdapter={
async execute(){return {effect:'UNKNOWN',actualCost:'0'};},
async reconcile(){return {effect:'UNKNOWN',actualCost:'0'};},
};
// One effect, in the documented order: reserve in the ledger, prepare the mission attempt, record ledger dispatch,
// then the coordinator commits DISPATCHED before calling the adapter and settles its outcome.
const trail=new Map<string,string[]>(); // attempt id -> the steps the host committed, in order
const attemptIdOf=(operationId:string)=>operationId+':attempt:1'; // each operation runs one attempt here
class Stopped extends Error {}
async function perform(runId:string,nodeId:string,operationId:string,action:Action,adapter:EffectAdapter,approvalId?:string):Promise<string>{
// A restarted host never repeats an operation: it completes the node only on a confirmed outcome.
const existing=store.snapshot().operations[operationId];
if(existing){if(existing.effect!=='CONFIRMED_APPLIED')throw new Stopped(`stopped: ${operationId} is ${existing.effect}`);return operationId;}
const attemptId=attemptIdOf(operationId),amount='1',steps:string[]=[];
trail.set(attemptId,steps);
await ledger(AGENT,{type:'reserve',attemptId,operationId,scopeId:runId,runId,purpose:'ORDINARY',amount,maxActiveMs:'60000'});
steps.push('ledger reserve');
try{
await mission(AGENT).apply({type:'admit',runId,operationId,attemptId,grantId:GRANT,subject:AGENT.actor,action,amount,
...(approvalId?{approvalId}:{}),authorizationCheckedAt:'0',policy:'INDETERMINATE',mandatoryChecksOk:false}); // the coordinator fills the policy fields
}catch(e){await ledger(WORKER,{type:'release',attemptId});throw e;}
steps.push('mission admit');
await ledger(WORKER,{type:'dispatch',attemptId});
steps.push('ledger dispatch');
const settled=(await mission(WORKER).dispatch(attemptId,adapter,nodeId)).attempts[attemptId];
steps.push('mission dispatch','mission settle '+settled.effect);
// UNKNOWN keeps the whole reservation: only reconciliation or a human decision resolves it, never a retry.
if(settled.effect==='UNKNOWN')await ledger(WORKER,{type:'unknown',attemptId});
else await ledger(WORKER,{type:'settle',attemptId,actualCost:settled.actualCost});
steps.push(settled.effect==='UNKNOWN'?'ledger unknown':'ledger settle');
// Any other outcome stops the host before the node completes. This recipe records no hold beyond the attempt's
// outcome and, for UNKNOWN, the ledger's unknown mark.
if(settled.effect!=='CONFIRMED_APPLIED')throw new Stopped(`stopped: ${attemptId} is ${settled.effect}`);
return operationId;
}
const read=(kind:string):Action=>({capability:'read-records',resource:'inspection-records',payload:{caseId:CASE,kind},preconditions:{}});
const evidenceOf=(operationId:string)=>evidence.get(attemptIdOf(operationId))!;
const recordRevisions:string[]=[];
async function collect(nodeId:string,kind:string):Promise<string>{
const operationId=await perform(RUN,nodeId,`example:operation:records-${kind}`,read(kind),recordsReader);
collected.push(kind);recordRevisions.push(evidenceOf(operationId));
return operationId;
}
// The case update the reviewer approves: the exact new state, the evidence revisions behind it and the version it replaces.
const caseUpdate=():Action=>({capability:'update-case',resource:'case:guarding-17',preconditions:{version:1},payload:{caseId:CASE,
update:{status:'CORRECTIVE_ACTION_PROPOSED',correctiveAction:evidenceOf('example:operation:draft-action')},evidence:recordRevisions}});
// Simulated inbox: an in-memory queue the script answers. Replace before deployment with an authenticated application
// inbox; delivering a notification is an application effect with its own outcome.
// Each item names the node that opened it; a node's wait id is derived from its id in one place.
type Ask={to:Session;nodeId:string;waitId:string;correlation:string};
const inbox:Ask[]=[];
const waitIdOf=(nodeId:string)=>'example:wait:'+nodeId;
async function ask(to:Session,runId:string,nodeId:string,kind:'AUTHORIZATION'|'EXTERNAL'|'INPUT'):Promise<null>{
const waitId=waitIdOf(nodeId),correlation='example:correlation:'+nodeId;
await mission(RUNNER).apply({type:'wait',runId,waitId,correlation,kind,deadline:(scriptedMs+3600000n).toString()});
await mission(RUNNER).apply({type:'transition',runId,to:'WAITING'});
routes.set(waitId,to.actor);inbox.push({to,nodeId,waitId,correlation});
return null;
}
// The scripted principals answer their inbox items, ten minutes later each. Replace before deployment.
// The reviewer approves the exact case update it was shown: its review tool derives the fingerprint from that action
// with the SDK's fingerprint, the function admission uses, so no hash is typed in.
let attestation='';
// The package: the record revisions, the draft and the case receipt.
const packageEvidence=()=>[...recordRevisions,evidenceOf('example:operation:draft-action'),evidenceOf('example:operation:update-case')];
const answers:Record<string,(item:Ask)=>Promise<unknown>>={
'engineering-review':()=>mission(REVIEWER).apply({type:'approve',approval:{id:APPROVAL,runId:RUN,
approver:REVIEWER.actor,fingerprint:fingerprint(caseUpdate()),expiresAt:(scriptedMs+3600000n).toString(),uses:'1'}}),
'implementation-evidence':async item=>{
// Simulated event ingress: replace before deployment. A deployed host authenticates the event source and the
// attesting person; the host, not the payload, names who attested.
const event={source:'example:maintenance-system',type:'implementation-attested',correlation:item.correlation,
data:{caseId:CASE,work:'Interlock switch replaced and guard interlock retested'}};
attestation=artifact({...event.data,attestedBy:item.to.actor});
},
'verification':()=>mission(VERIFIER).apply({type:'verify',runId:FOLLOW_UP,assessor:VERIFIER.actor,
revision:FOLLOW_UP_VERIFICATION,results:Object.fromEntries(CRITERIA.map(id=>[id,'PASS'])),evidence:[...packageEvidence(),attestation],
rationale:'Records, reviewed draft, case receipt and implementation attestation support every criterion'}),
'acceptance':()=>mission(VERIFIER).apply({type:'accept',runId:FOLLOW_UP,authority:VERIFIER.actor,
verificationRevision:FOLLOW_UP_VERIFICATION,decision:'ACCEPTED',rationale:'Corrective-action package accepted; return to service stays a separate decision'}),
};
async function answer(item:Ask){
scriptedMs+=600000n;
await answers[item.nodeId](item);
await mission(item.to).apply({type:'resume',waitId:item.waitId,correlation:item.correlation});
}
// Each node returns its completion proof, or null after it opens a wait: an operation for TASK, an operation and done
// for LOOP, an approval for APPROVAL, a satisfied wait for WAIT, the assessment revision for VERIFICATION and
// ACCEPTANCE, and a disposition for END.
const nodes:Record<string,(state:Snapshot)=>Promise<Record<string,unknown>|null>>={
'collect-records':async()=>({operationId:await collect('collect-records','inspection')}),
// The bounded loop: each iteration requests one missing kind of record, at most maxIterations times.
'request-more-records':async()=>{const operationId=await collect('request-more-records',missingKind()!);return {operationId,done:missingKind()===undefined};},
'draft-action':async()=>({operationId:await perform(RUN,'draft-action','example:operation:draft-action',
{capability:'draft',resource:'case-draft',payload:{caseId:CASE,records:recordRevisions},preconditions:{}},drafter)}),
'engineering-review':async state=>state.approvals[APPROVAL]?{approvalId:APPROVAL}:ask(REVIEWER,RUN,'engineering-review','AUTHORIZATION'),
// The approval-bound case-record write: the SDK admits it only when its fingerprint matches an unexpired, unused approval.
'update-case':async()=>({operationId:await perform(RUN,'update-case','example:operation:update-case',caseUpdate(),caseRecord,APPROVAL)}),
'end':async()=>({disposition:'COMPLETED'}),
'implementation-evidence':async state=>state.waits[waitIdOf('implementation-evidence')]?.status==='SATISFIED'
?{waitId:waitIdOf('implementation-evidence')}:ask(TECHNICIAN,FOLLOW_UP,'implementation-evidence','EXTERNAL'),
'verification':async state=>state.assessments[FOLLOW_UP]?{revision:FOLLOW_UP_VERIFICATION}:ask(VERIFIER,FOLLOW_UP,'verification','INPUT'),
'acceptance':async state=>state.assessments[FOLLOW_UP].acceptance!=='NOT_REQUESTED'?{revision:FOLLOW_UP_VERIFICATION}
:ask(VERIFIER,FOLLOW_UP,'acceptance','INPUT'),
// The case owner decides return to service, so the follow-up run notifies them of the acceptance.
'notify-case-owner':async()=>({operationId:await perform(FOLLOW_UP,'notify-case-owner','example:operation:notify-case-owner',
{capability:'notify',resource:'case-owner-inbox',payload:{caseId:CASE,runId:FOLLOW_UP,
message:'The corrective-action package is accepted; return to service is your decision'},preconditions:{}},placeholder)}),
'follow-up-end':async()=>({disposition:'COMPLETED'}),
};
// Start-up, before the host takes any work: open the stores, then recover every run left open. recover fences the
// run with a new segment and lists its unresolved attempts, and each is reconciled read-only through the adapter that
// dispatched it. A human settles a confirmed outcome in the ledger, on the read-back; an outcome still UNKNOWN stays
// held for a human, and the host neither retries nor claims it.
const adapters:Record<string,EffectAdapter>={'read-records':recordsReader,'draft':drafter,'update-case':caseRecord,'notify':placeholder};
const startUps:{recovered:{runId:string;segmentId:string;reconciled:{attemptId:string;effect:string}[]}[]}[]=[];
async function startUp(){
store=new SqliteStore(join(directory,'mission.db'),contract);
ledgerStore=new LimitStore(join(directory,'ledger.db'),envelope);
const recovered=[];
for(const run of Object.values(store.snapshot().runs)){
if(TERMINAL.includes(run.state))continue;
const segmentId=run.id+':segment:'+run.segments.length,reconciled=[];
const {unresolved}=await mission(RUNNER).recover(run.id,segmentId);
for(const attemptId of unresolved){
const before=store.snapshot(),operation=before.operations[before.attempts[attemptId].operationId];
const {effect,actualCost}=(await mission(WORKER).reconcile(attemptId,adapters[operation.action.capability])).attempts[attemptId];
trail.get(attemptId)!.push('mission recover','mission reconcile '+effect);
reconciled.push({attemptId,effect});
if(effect==='UNKNOWN')continue;
// Simulated human decision: replace before deployment. The case owner reviews the read-back and settles the ledger.
await ledger(OWNER,{type:'settle',attemptId,actualCost});
trail.get(attemptId)!.push('ledger settle');
}
recovered.push({runId:run.id,segmentId,reconciled});
}
startUps.push({recovered});
}
// Root-grant authoring: the case owner, a human, writes the agent's grant. A root grant has no parent, so the contract
// is its only bound: the SDK refuses one that lists an action or resource the contract does not, a limit above the
// budget or an expiry after the deadline. This one is narrower than the contract: 10 capability calls, no delegation.
const rootGrant=()=>({id:GRANT,subject:AGENT.actor,profile:'finite-v1' as const,actions:contract.actions,resources:contract.resources,
notBefore:'0',expiresAt:contract.deadline,limit:'10',canDelegate:false,depth:'0'});
// A deterministic stand-in for an agent that oversteps: replace before deployment. It asks for a wider grant of its own
// and for a higher cost limit on the work order. Only a human changes permissions or limits, so the mission authorizer
// denies the grant and the ledger authorizer, which allows no adjust here, denies the adjustment.
const denials:{command:string;actor:string;refused:string}[]=[];
async function refused(command:string,work:()=>Promise<unknown>){
try{await work();}catch(e:any){denials.push({command,actor:AGENT.actor,refused:e.code});return;}
throw new Error(command+' was not refused');
}
async function overstep(){
await refused('grant',()=>mission(AGENT).apply({type:'grant',grant:{...rootGrant(),id:GRANT+':widened',limit:contract.budget}}));
await refused('adjust',()=>ledger(AGENT,{type:'adjust',scopeId:WORK_ORDER,limits:{cost:'1000',handoff:'10',activeMs:null,elapsedMs:'28800000',attempts:'100'}}));
}
// A host stop: an outcome other than CONFIRMED_APPLIED stops the host, which closes its stores; the next start-up
// recovers. The restart here stays in one process, so the evidence index and the trail stay in memory; a deployed host
// keeps them durable beside its artifacts.
async function untilStopped(work:Promise<void>){try{await work;}catch(e){if(!(e instanceof Stopped))throw e;store.close();ledgerStore.close();}}
// The run loop over the graph: dispatch each ready node and complete it with its proof.
async function drive(runId:string){
for(;;){
const state=store.snapshot();
if(TERMINAL.includes(state.runs[runId].state))return;
if(state.runs[runId].state==='WAITING'){
const item=inbox.shift()!;
await answer(item);
await mission(RUNNER).apply({type:'join',runId,waitIds:[item.waitId],mode:'ALL'});
continue;
}
const [nodeId]=readyNodes(state,runId);
if(nodeId===undefined){await mission(RUNNER).apply({type:'transition',runId,to:'COMPLETED'});continue;}
const proof=await nodes[nodeId](state);
if(proof)await mission(RUNNER).apply({type:'completeNode',runId,nodeId,result:proof});
}
}
async function start(runId:string,graph:{id:string}){
await mission(RUNNER).apply({type:'startRun',runId});
await mission(RUNNER).apply({type:'registerGraph',graph} as Command);
await mission(RUNNER).apply({type:'attachGraph',runId,graphId:graph.id});
}
await startUp();
try{
await start(RUN,packageGraph);
await mission(OWNER).apply({type:'grant',grant:rootGrant()});
await overstep();
await untilStopped(drive(RUN));
await startUp();
await drive(RUN);
// The designated verifier assesses the completed package. Implementation evidence is missing, so the criteria that
// need it are INCONCLUSIVE and acceptance is DEFERRED; neither is turned into a pass.
scriptedMs+=600000n;
await mission(VERIFIER).apply({type:'verify',runId:RUN,assessor:VERIFIER.actor,revision:VERIFICATION,
results:{'issue-identified':'PASS','engineering-reviewed':'PASS','implementation-evidenced':'INCONCLUSIVE','effectiveness-accepted':'INCONCLUSIVE'},
evidence:packageEvidence(),rationale:'Records, reviewed draft and case receipt support the first two criteria; no implementation evidence yet'});
scriptedMs+=600000n;
await mission(VERIFIER).apply({type:'accept',runId:RUN,authority:VERIFIER.actor,verificationRevision:VERIFICATION,decision:'DEFERRED',
rationale:'Await authorized implementation evidence and assessment'});
// The linked follow-up run obtains the implementation evidence and is verified and accepted on it.
await start(FOLLOW_UP,followUpGraph);
await untilStopped(drive(FOLLOW_UP));
// The notification is still UNKNOWN after this start-up, so the host holds the follow-up run for a human.
await startUp();
// Simulated telemetry export: replace before deployment with a collector client that has a timeout and redirects disabled.
const exported=await store.flushTelemetry({send:async()=>classifyResponse(200,'{}')},clock(),1000);
const final=store.snapshot(),approval=final.approvals[APPROVAL];
const update=final.operations['example:operation:update-case'],settles=ledgerStore.exportEvents().filter(e=>e.request.command.type==='settle');
const ledgerAttempts=ledgerStore.snapshot().attempts,usage=ledgerStore.report(clock()).scopes.find((s:any)=>s.scopeId===WORK_ORDER).usage;
const settlementOf=(attemptId:string)=>{const facts=settles.find(e=>e.request.command.attemptId===attemptId)?.facts;
return {evidenceRef:facts?.evidenceRef??null,settledBy:facts?.actorId??null};};
const outcome=(runId:string)=>{const assessment=final.assessments[runId];
return {executionState:final.runs[runId].state,verificationState:assessment.verification,acceptanceState:assessment.acceptance}};
const record={
// Annex B's illustrative result record, for run 1.
result:{exampleOnly:true,runId:RUN,...outcome(RUN),missionId:contract.missionId,contractRevision:contract.id,
verifiedSuccessful:assessSuccess(final,RUN).verifiedSuccessful,
criterionResults:CRITERIA.map(criterionId=>({criterionId,verdict:final.assessments[RUN].results[criterionId]})),
disposition:final.assessments[RUN].acceptanceRecord.rationale},
followUp:{runId:FOLLOW_UP,...outcome(FOLLOW_UP),...assessSuccess(final,FOLLOW_UP)},
approval:{id:APPROVAL,approver:approval.approver,fingerprint:approval.fingerprint,expiresAt:approval.expiresAt,uses:approval.uses,
consumedBy:approval.operations,caseUpdate:{fingerprint:update.fingerprint,preconditions:update.action.preconditions,
update:update.action.payload.update,evidence:update.action.payload.evidence}},
effects:[...trail.keys()].map(attemptId=>{const attempt=final.attempts[attemptId],operation=final.operations[attempt.operationId];
return {operationId:operation.id,nodeId:operation.nodeId,effect:attempt.effect,actualCost:attempt.actualCost,order:trail.get(attemptId),
ledger:{status:ledgerAttempts[attemptId].status,amount:ledgerAttempts[attemptId].amount,actualCost:ledgerAttempts[attemptId].actualCost,
...settlementOf(attemptId)}};}),
startUps,
grant:{id:GRANT,grantedBy:final.events.find(e=>e.command.type==='grant').command.context.actor,limit:final.grants[GRANT].limit,
canDelegate:final.grants[GRANT].canDelegate,depth:final.grants[GRANT].depth,grants:Object.keys(final.grants),
workOrderCostLimit:ledgerStore.snapshot().scopes[WORK_ORDER].limits.cost},
denials,
rejections:(parseStrict(store.exportAudit()) as any).diagnostics.map((d:any)=>({rejectedType:d.command.rejectedType,code:d.command.code,actor:d.command.context.actor})),
assessments:[RUN,FOLLOW_UP].map(runId=>{const assessment=final.assessments[runId];
return {runId,revision:assessment.revision,assessor:assessment.assessor,verification:assessment.verification,evidence:assessment.evidence,
authority:assessment.acceptanceRecord.authority,acceptance:assessment.acceptance};}),
accounting:{missionSpent:final.spent,missionReserved:final.reserved,ledgerCost:usage.cost,ledgerAttempts:usage.attempts},
telemetry:{exported:exported.length,allSent:exported.every((r:any)=>r.status==='SENT')},
};
// Run 1 ends exactly as Annex B's illustrative result after physical implementation evidence is missing.
assert.deepEqual(record.result,{exampleOnly:true,runId:'example:run:guarding-17',executionState:'COMPLETED',verificationState:'INCONCLUSIVE',
acceptanceState:'DEFERRED',missionId:'example:mission:guarding-17',contractRevision:'example:contract:guarding-17:1',verifiedSuccessful:false,
criterionResults:[{criterionId:'issue-identified',verdict:'PASS'},{criterionId:'engineering-reviewed',verdict:'PASS'},
{criterionId:'implementation-evidenced',verdict:'INCONCLUSIVE'},{criterionId:'effectiveness-accepted',verdict:'INCONCLUSIVE'}],
disposition:'Await authorized implementation evidence and assessment'});
// The follow-up run, given the implementation evidence, is verified and accepted, but it is not a verified success:
// its notification is UNKNOWN, so the run stays held and cannot complete.
assert.deepEqual(record.followUp,{runId:FOLLOW_UP,executionState:'RUNNING',verificationState:'PASSED',acceptanceState:'ACCEPTED',
verifiedSuccessful:false,reasons:['EXECUTION_NOT_COMPLETED','EFFECT_UNKNOWN']});
// Annex B: the effectiveness assessment is made and accepted by the designated verifier.
for(const assessment of record.assessments)assert.deepEqual([assessment.assessor,assessment.authority],[VERIFIER.actor,VERIFIER.actor]);
// The approval is bound to the exact case update: same fingerprint, consumed once, by that write alone.
const REVIEWED_FINGERPRINT='sha256:dc6286da8ce3fcc52283ea5fa2cba15dea085ecc67213a4f4bf18426888154ab';
assert.equal(record.approval.fingerprint,REVIEWED_FINGERPRINT);
assert.equal(record.approval.caseUpdate.fingerprint,REVIEWED_FINGERPRINT);
assert.deepEqual(record.approval.consumedBy,['example:operation:update-case']);
assert.deepEqual(record.approval.caseUpdate.preconditions,{version:1});
// Every effect was reserved before dispatch and settled after it, with the evidence that settled it.
assert.deepEqual(record.effects.map(e=>e.nodeId),['collect-records','request-more-records','request-more-records','draft-action','update-case','notify-case-owner']);
for(const effect of record.effects.slice(0,5)){
assert.deepEqual([effect.effect,effect.actualCost,effect.ledger.status,effect.ledger.amount,effect.ledger.actualCost],['CONFIRMED_APPLIED','1','SETTLED','1','1']);
assert.match(effect.ledger.evidenceRef!,/^sha256:[0-9a-f]{64}$/);
}
for(const effect of record.effects.slice(0,4)){
assert.deepEqual(effect.order,['ledger reserve','mission admit','ledger dispatch','mission dispatch','mission settle CONFIRMED_APPLIED','ledger settle']);
assert.equal(effect.ledger.settledBy,WORKER.actor);
}
// The case write times out once: the write lands but its acknowledgment is lost, so the attempt is UNKNOWN and the
// host stops. At the next start-up, recover fences the run and the read-only reconcile finds this operation's version
// in the record. The ledger keeps the whole reservation until a human settles it on that read-back.
assert.deepEqual(record.effects[4].order,['ledger reserve','mission admit','ledger dispatch','mission dispatch','mission settle UNKNOWN',
'ledger unknown','mission recover','mission reconcile CONFIRMED_APPLIED','ledger settle']);
assert.equal(record.effects[4].ledger.settledBy,OWNER.actor);
// The placeholder adapter reports UNKNOWN from execute and reconcile alike. At the next start-up the notification is
// still UNKNOWN: the ledger keeps its reservation, nothing settles it, and the host holds the run for a human.
assert.deepEqual(record.effects[5],{operationId:'example:operation:notify-case-owner',nodeId:'notify-case-owner',effect:'UNKNOWN',actualCost:null,
order:['ledger reserve','mission admit','ledger dispatch','mission dispatch','mission settle UNKNOWN','ledger unknown','mission recover','mission reconcile UNKNOWN'],
ledger:{status:'UNKNOWN',amount:'1',actualCost:null,evidenceRef:null,settledBy:null}});
assert.deepEqual(record.startUps,[{recovered:[]},{recovered:[{runId:RUN,segmentId:'example:run:guarding-17:segment:1',
reconciled:[{attemptId:'example:operation:update-case:attempt:1',effect:'CONFIRMED_APPLIED'}]}]},
{recovered:[{runId:FOLLOW_UP,segmentId:'example:run:guarding-17:implementation:segment:1',
reconciled:[{attemptId:'example:operation:notify-case-owner:attempt:1',effect:'UNKNOWN'}]}]}]);
const [packageAssessment,followUpAssessment]=record.assessments;
assert.equal(record.effects[4].ledger.evidenceRef,packageAssessment.evidence[4]); // the case receipt
assert.deepEqual(record.approval.caseUpdate.evidence,packageAssessment.evidence.slice(0,3)); // the record revisions it approved
assert.equal(readFileSync(casePath,'utf8'),canonical({caseId:CASE,version:2,status:'CORRECTIVE_ACTION_PROPOSED',
correctiveAction:packageAssessment.evidence[3],evidence:record.approval.caseUpdate.evidence,history:[{version:2,operationId:'example:operation:update-case'}]}));
// The follow-up assessment cites the same package and adds the implementation attestation.
assert.deepEqual(followUpAssessment.evidence.slice(0,5),packageAssessment.evidence);
assert.equal(followUpAssessment.evidence.length,6);
// The human-authored root grant is narrower than the contract, and the agent could not widen it: its grant and its
// request to raise the work order's cost limit were both denied, and nothing changed.
assert.deepEqual(record.grant,{id:GRANT,grantedBy:OWNER.actor,limit:'10',canDelegate:false,depth:'0',grants:[GRANT],workOrderCostLimit:'100'});
assert.deepEqual(record.denials,[{command:'grant',actor:AGENT.actor,refused:'AUTHORITY_DENIED'},{command:'adjust',actor:AGENT.actor,refused:'AUTHORIZATION_DENIED'}]);
// The mission store records the denied grant, attributed to the agent; it is the run's only refused command.
assert.deepEqual(record.rejections,[{rejectedType:'grant',code:'AUTHORITY_DENIED',actor:AGENT.actor}]);
// Five settled capability calls, and the UNKNOWN notification's reservation still held in both stores.
assert.deepEqual(record.accounting,{missionSpent:'5',missionReserved:'1',ledgerCost:'6',ledgerAttempts:'6'});
assert.equal(record.telemetry.allSent,true);
// The real clock reads canonical epoch milliseconds, past the scripted contract's deadline.
assert.match(utcClock(),/^[1-9][0-9]*$/);
assert.ok(BigInt(utcClock())>BigInt(contract.deadline));
console.log(canonical(record));
}finally{store.close();ledgerStore.close();}

Run it with every other recipe, from the source root, with node scripts/check-guide-examples.mjs. Adapting it to a real case system starts with the simulated parts above, then the integration tests the cookbook asks for.