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 workflow
Section titled “The workflow”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.
What is real, what is simulated
Section titled “What is real, what is simulated”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 (
HUMANfor a human principal,DETERMINISTICotherwise) 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
recoverand a read-onlyreconcilerun 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.
Authority
Section titled “Authority”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.
Root-grant authoring
Section titled “Root-grant authoring”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.
Denied escalation
Section titled “Denied escalation”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 approval binding
Section titled “The approval binding”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.
Effects in the documented order
Section titled “Effects in the documented order”Every effect, the reads, the draft, the case write and the notification alike, runs through one host function, perform:
- reserve the attempt in the limits ledger;
- admit the mission attempt; a refused admission releases the unused reservation;
- record ledger dispatch, before any external call;
- call
Coordinator.dispatch, which commits DISPATCHED, calls the adapter and settles its outcome; - 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.
Start-up recovery
Section titled “Start-up recovery”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,
reconcilefinds 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
reconcilereports UNKNOWN too, so the notification keeps its reservation in both stores and the follow-up run stays held.
Outcomes the adapters report
Section titled “Outcomes the adapters report”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
reconcilereports 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
reconcileis 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
executeandreconcilealike. A host wired to an adapter that is not written yet therefore holds the node, instead of claiming the effect happened or did not.
The record it prints
Section titled “The record it prints”Each language prints one canonical JSON record, and the records are identical:
result, in the shape of Annex B’s illustrative result, withexampleOnly: true: run 1 is COMPLETED, INCONCLUSIVE and DEFERRED,issue-identifiedandengineering-reviewedare 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 reasonsEXECUTION_NOT_COMPLETEDandEFFECT_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,denialsandrejections: 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, andtelemetry, 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 outcomeconst 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 orderconst attemptIdOf=(operationId:string)=>operationId+':attempt:1'; // each operation runs one attempt hereclass 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();}use aiws_sdk::limits_store::{LimitAuthorizer, LimitCoordinator, LimitStore};use aiws_sdk::observability::{classify_response, TelemetryExporter};use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use aiws_sdk::workflow::ready_nodes;use aiws_sdk::*;use serde_json::{json, Value};use std::cell::{Cell, RefCell};use std::collections::{HashMap, VecDeque};use std::io::Write;use std::path::PathBuf;use std::rc::Rc;// 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: &str = "example:run:guarding-17";const FOLLOW_UP: &str = "example:run:guarding-17:implementation";const WORK_ORDER: &str = "example:work-order:guarding-17";const GRANT: &str = "example:grant:investigator";const CASE: &str = "example:case:guarding-17";const APPROVAL: &str = "example:approval:engineering-review";const VERIFICATION: &str = "example:verification:guarding-17:1";const FOLLOW_UP_VERIFICATION: &str = "example:verification:guarding-17:2";const CRITERIA: [&str; 4] = ["issue-identified", "engineering-reviewed", "implementation-evidenced", "effectiveness-accepted"];const POLICY: &str = "policy:example:annex-b:1";const TERMINAL: [&str; 4] = ["COMPLETED", "FAILED", "CANCELED", "REJECTED"];type Shared<T> = Rc<RefCell<T>>;
// 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.struct UtcClock;impl Clock for UtcClock { fn now_ms(&self) -> String { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).expect("the system clock reads after 1970").as_millis().to_string() }}#[derive(Clone)]struct ScriptedClock(Rc<Cell<u64>>);impl Clock for ScriptedClock { fn now_ms(&self) -> String { self.0.get().to_string() }}
// 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.struct Session { actor: &'static str, kind: &'static str }static RUNNER: Session = Session { actor: "host:runner", kind: "RULE" };static WORKER: Session = Session { actor: "host:worker-1", kind: "RULE" };static AGENT: Session = Session { actor: "agent:investigator", kind: "AGENT" };static OWNER: Session = Session { actor: "human:case-owner", kind: "HUMAN" };static REVIEWER: Session = Session { actor: "human:engineering-reviewer", kind: "HUMAN" };static TECHNICIAN: Session = Session { actor: "human:authorized-technician", kind: "HUMAN" };static VERIFIER: Session = Session { actor: "human:designated-verifier", kind: "HUMAN" };fn is(a: &Session, b: &Session) -> bool { std::ptr::eq(a, b) }
// Deny by default: a command is allowed only when a rule below names its session.const AGENT_ACTIONS: [&str; 4] = ["read-records inspection-records", "draft case-draft", "update-case case:guarding-17", "notify case-owner-inbox"];struct Policy { session: &'static Session, routes: Shared<HashMap<String, String>> } // wait id -> the one principal routed to answer itfn permits(s: &Session, c: &Value, routes: &HashMap<String, String>) -> bool { let text = |v: &Value| v.as_str().unwrap_or_default().to_owned(); match text(&c["type"]).as_str() { "startRun" | "continueRun" | "registerGraph" | "attachGraph" | "completeNode" | "wait" | "join" | "transition" => is(s, &RUNNER), "admit" => is(s, &AGENT) && c["subject"] == AGENT.actor && AGENT_ACTIONS.contains(&format!("{} {}", text(&c["action"]["capability"]), text(&c["action"]["resource"])).as_str()) && (c["action"]["capability"] != "update-case" || c.get("approvalId").is_some()), "dispatch" | "settle" => is(s, &WORKER), "grant" => is(s, &OWNER), "approve" => is(s, &REVIEWER) && c["approval"]["approver"] == REVIEWER.actor, "resume" => routes.get(&text(&c["waitId"])).is_some_and(|actor| actor == s.actor), "verify" => is(s, &VERIFIER) && c["assessor"] == VERIFIER.actor, "accept" => is(s, &VERIFIER) && c["authority"] == VERIFIER.actor, // Annex B: accepted by the designated verifier _ => false, }}impl Authorizer for Policy { fn authorize(&mut self, command: &Command, _: &Snapshot, _: &str) -> Result<Authorization> { let allowed = permits(self.session, command.as_value(), &self.routes.borrow()); Ok(Authorization { allowed, policy: if allowed { "ALLOW" } else { "DENY" }.into(), mandatory_checks_ok: true, context: json!({"actor":self.session.actor,"policyRevision":POLICY,"decisionClass":if self.session.kind=="HUMAN"{"HUMAN"}else{"DETERMINISTIC"}}) }) }}struct LedgerPolicy { session: &'static Session, evidence: Shared<HashMap<String, String>> } // attempt id -> digest of the artifact that evidences its outcomeimpl LimitAuthorizer for LedgerPolicy { fn authorize(&mut self, request: &Value, state: &Value, now: &str) -> Result<Value> { let kind = request["command"]["type"].as_str().unwrap_or_default(); let attempt_id = request["command"]["attemptId"].as_str().unwrap_or_default(); let evidence_ref = if kind == "settle" { self.evidence.borrow().get(attempt_id).cloned() } else { None }; let allowed = if kind == "reserve" { is(self.session, &AGENT) } // Only a human settles an UNKNOWN ledger attempt, on the evidence that resolved it. else if kind == "settle" && is(self.session, &OWNER) { state["attempts"][attempt_id]["status"] == "UNKNOWN" } else { ["dispatch", "settle", "unknown", "release"].contains(&kind) && is(self.session, &WORKER) }; Ok(json!({"allowed":allowed&&(kind!="settle"||evidence_ref.is_some()),"actorId":self.session.actor,"actorKind":self.session.kind, "policyRef":POLICY,"evidenceRef":evidence_ref,"authorizedAtMs":now})) }}
// Immutable local artifacts: content-addressed, written once with create-new and fsync, never rewritten.fn artifact_path(directory: &PathBuf, revision: &str) -> PathBuf { directory.join(format!("{}.json", &revision["sha256:".len()..])) }fn artifact(directory: &PathBuf, value: &Value) -> Result<String> { let (bytes, revision) = (canonical(value)?, digest(value)?); let path = artifact_path(directory, &revision); match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) { Ok(mut file) => { file.write_all(bytes.as_bytes()).and_then(|_| file.sync_all()).map_err(|_| error("FILE_ERROR"))?; } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && std::fs::read_to_string(&path).ok() == Some(bytes) => {} Err(_) => return Err(error("FILE_ERROR")), } Ok(revision)}fn applied(effect: &str, cost: &str) -> Outcome { Outcome { effect: effect.into(), actual_cost: cost.into() } }
// A local stand-in for the approved-records system: replace before deployment.fn records() -> Value { json!([ {"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"}])}struct RecordsReader { directory: PathBuf, evidence: Shared<HashMap<String, String>> }impl EffectAdapter for RecordsReader { fn execute(&mut self, operation: &Value, attempt: &Value) -> Result<Outcome> { let kind = &operation["action"]["payload"]["kind"]; let found: Vec<Value> = records().as_array().unwrap().iter().filter(|r| r["approved"] == true && &r["kind"] == kind).cloned().collect(); let revision = artifact(&self.directory, &json!({"kind":kind,"records":found}))?; self.evidence.borrow_mut().insert(attempt["id"].as_str().unwrap().into(), revision); Ok(applied("CONFIRMED_APPLIED", "1")) } // A read leaves nothing at the source to look up, so a lost response stays UNKNOWN for a human to resolve. fn reconcile(&mut self, _: &Value, _: &Value) -> Result<Outcome> { Ok(applied("UNKNOWN", "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: [&str; 3] = ["inspection", "maintenance", "training"];struct Drafter { directory: PathBuf, evidence: Shared<HashMap<String, String>> }impl EffectAdapter for Drafter { fn execute(&mut self, operation: &Value, attempt: &Value) -> Result<Outcome> { let mut based_on = vec![]; for revision in operation["action"]["payload"]["records"].as_array().unwrap() { let path = artifact_path(&self.directory, revision.as_str().unwrap()); let bundle = parse_strict(&std::fs::read_to_string(path).map_err(|_| error("FILE_ERROR"))?)?; based_on.extend(bundle["records"].as_array().unwrap().iter().map(|r| r["id"].clone())); } let revision = artifact(&self.directory, &json!({"caseId":CASE,"basedOn":based_on, "proposedAction":"Replace the press 4 interlock switch, retest the guard interlock and brief operators"}))?; self.evidence.borrow_mut().insert(attempt["id"].as_str().unwrap().into(), revision); Ok(applied("CONFIRMED_APPLIED", "1")) } fn reconcile(&mut self, _: &Value, _: &Value) -> Result<Outcome> { Ok(applied("UNKNOWN", "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.struct CaseRecord { directory: PathBuf, evidence: Shared<HashMap<String, String>>, acknowledgments_to_drop: Rc<Cell<u32>> }impl CaseRecord { fn path(&self) -> PathBuf { self.directory.join("case-record.json") } fn read(&self) -> Result<Value> { parse_strict(&std::fs::read_to_string(self.path()).map_err(|_| error("FILE_ERROR"))?) } fn record(&self, attempt: &Value, value: &Value) -> Result<()> { let revision = artifact(&self.directory, value)?; self.evidence.borrow_mut().insert(attempt["id"].as_str().unwrap().into(), revision); Ok(()) }}impl EffectAdapter for CaseRecord { fn execute(&mut self, operation: &Value, attempt: &Value) -> Result<Outcome> { let (record, action) = (self.read()?, &operation["action"]); if record["history"].as_array().unwrap().iter().any(|h| h["operationId"] == operation["id"]) { self.record(attempt, &record)?; return Ok(applied("CONFIRMED_APPLIED", "1")); } if record["version"] != action["preconditions"]["version"] { self.record(attempt, &record)?; return Ok(applied("CONFIRMED_NOT_APPLIED", "1")); } let version = record["version"].as_u64().unwrap() + 1; let mut history = record["history"].as_array().unwrap().clone(); history.push(json!({"version":version,"operationId":operation["id"]})); let mut next = json!({"caseId":record["caseId"],"version":version,"evidence":action["payload"]["evidence"],"history":history}); for (key, value) in action["payload"]["update"].as_object().unwrap() { next[key] = value.clone(); } let staged = self.directory.join("case-record.json.next"); std::fs::write(&staged, canonical(&next)?).and_then(|_| std::fs::rename(&staged, self.path())).map_err(|_| error("FILE_ERROR"))?; if self.acknowledgments_to_drop.get() > 0 { self.acknowledgments_to_drop.set(self.acknowledgments_to_drop.get() - 1); return Err(error("TIMEOUT")); // the case-record system did not acknowledge the update } self.record(attempt, &next)?; Ok(applied("CONFIRMED_APPLIED", "1")) } // Read-only: the history shows this operation wrote its version, or the outcome stays UNKNOWN. The record it read is // the evidence. fn reconcile(&mut self, operation: &Value, attempt: &Value) -> Result<Outcome> { let record = self.read()?; let version = operation["action"]["preconditions"]["version"].as_u64().unwrap() + 1; let wrote = record["history"].as_array().unwrap().iter().any(|h| h["operationId"] == operation["id"] && h["version"] == version); if !wrote { return Ok(applied("UNKNOWN", "0")); } self.record(attempt, &record)?; Ok(applied("CONFIRMED_APPLIED", "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.struct Placeholder;impl EffectAdapter for Placeholder { fn execute(&mut self, _: &Value, _: &Value) -> Result<Outcome> { Ok(applied("UNKNOWN", "0")) } fn reconcile(&mut self, _: &Value, _: &Value) -> Result<Outcome> { Ok(applied("UNKNOWN", "0")) }}
// Simulated telemetry export: replace before deployment with a collector client that has a timeout and redirects disabled.struct Collector;impl TelemetryExporter for Collector { fn send(&mut self, _: &str, _: &Value) -> Value { classify_response(200, "{}", None) }}
// 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.struct Ask { to: &'static Session, node_id: String, wait_id: String, correlation: String }fn wait_id_of(node_id: &str) -> String { format!("example:wait:{node_id}") }fn attempt_id_of(operation_id: &str) -> String { format!("{operation_id}:attempt:1") } // each operation runs one attempt here// 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.const STOPPED: &str = "HOST_STOPPED";
struct Host { store: Option<SqliteStore>, ledger_store: Option<LimitStore>, contract: Contract, envelope: Value, clock: ScriptedClock, directory: PathBuf, routes: Shared<HashMap<String, String>>, evidence: Shared<HashMap<String, String>>, acknowledgments_to_drop: Rc<Cell<u32>>, trail: Vec<(String, Vec<String>)>, // attempt id -> the steps the host committed, in order inbox: VecDeque<Ask>, collected: Vec<String>, record_revisions: Vec<String>, attestation: String, start_ups: Vec<Value>, denials: Vec<Value>,}impl Host { // One worker, so one mission store and one ledger store. Another worker opens its own; a store is never shared. // Each verified session gets its own coordinator over the worker's store. fn mission(&mut self, session: &'static Session, command: Value) -> Result<Snapshot> { self.with_mission(session, |c| c.apply(&Command::from_value(command)?, None)) } fn with_mission<T>(&mut self, session: &'static Session, f: impl FnOnce(&mut Coordinator<Policy, ScriptedClock>) -> Result<T>) -> Result<T> { let policy = Policy { session, routes: self.routes.clone() }; let mut coordinator = Coordinator::new(self.store.take().unwrap(), policy, self.clock.clone()); let result = f(&mut coordinator); self.store = Some(coordinator.store); result } fn ledger(&mut self, session: &'static Session, command: Value) -> Result<()> { let clock = self.clock.clone(); let mut coordinator = LimitCoordinator { store: self.ledger_store.take().unwrap(), authorize: LedgerPolicy { session, evidence: self.evidence.clone() }, clock: move || clock.now_ms() }; let mut apply = || { let revision = coordinator.store.snapshot()?["revision"].clone(); let subject = command.get("attemptId").unwrap_or(&command["scopeId"]).as_str().unwrap(); let request_id = format!("{}:{}", command["type"].as_str().unwrap(), subject); coordinator.apply(&json!({"requestId":request_id,"expectedRevision":revision,"command":command})) }; let result = apply(); self.ledger_store = Some(coordinator.store); result.map(|_| ()) } fn snapshot(&self) -> Result<Value> { Ok(self.store.as_ref().unwrap().snapshot()?.as_value().clone()) } fn evidence_of(&self, operation_id: &str) -> String { self.evidence.borrow()[&attempt_id_of(operation_id)].clone() } fn steps(&mut self, attempt_id: &str) -> &mut Vec<String> { &mut self.trail.iter_mut().find(|(id, _)| id == attempt_id).unwrap().1 } fn case_record(&self) -> CaseRecord { CaseRecord { directory: self.directory.clone(), evidence: self.evidence.clone(), acknowledgments_to_drop: self.acknowledgments_to_drop.clone() } }
// 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. fn perform(&mut self, run_id: &str, node_id: &str, operation_id: &str, action: Value, adapter: &mut impl EffectAdapter, approval_id: Option<&str>) -> Result<String> { // A restarted host never repeats an operation: it completes the node only on a confirmed outcome. if let Some(existing) = self.snapshot()?["operations"].get(operation_id) { if existing["effect"] != "CONFIRMED_APPLIED" { eprintln!("stopped: {operation_id} is {}", existing["effect"]); return Err(error(STOPPED)); } return Ok(operation_id.to_owned()); } let (attempt_id, amount) = (attempt_id_of(operation_id), "1"); let mut steps = vec![]; self.ledger(&AGENT, json!({"type":"reserve","attemptId":attempt_id,"operationId":operation_id,"scopeId":run_id,"runId":run_id,"purpose":"ORDINARY","amount":amount,"maxActiveMs":"60000"}))?; steps.push("ledger reserve".to_owned()); let mut admit = json!({"type":"admit","runId":run_id,"operationId":operation_id,"attemptId":attempt_id,"grantId":GRANT,"subject":AGENT.actor,"action":action,"amount":amount, "authorizationCheckedAt":"0","policy":"INDETERMINATE","mandatoryChecksOk":false}); // the coordinator fills the policy fields if let Some(id) = approval_id { admit["approvalId"] = json!(id); } if let Err(e) = self.mission(&AGENT, admit) { self.ledger(&WORKER, json!({"type":"release","attemptId":attempt_id}))?; return Err(e); } steps.push("mission admit".to_owned()); self.ledger(&WORKER, json!({"type":"dispatch","attemptId":attempt_id}))?; steps.push("ledger dispatch".to_owned()); let state = self.with_mission(&WORKER, |c| c.dispatch(&attempt_id, adapter, Some(node_id)))?; let settled = state.as_value()["attempts"][&attempt_id].clone(); let effect = settled["effect"].as_str().unwrap().to_owned(); steps.extend(["mission dispatch".to_owned(), format!("mission settle {effect}")]); // UNKNOWN keeps the whole reservation: only reconciliation or a human decision resolves it, never a retry. if effect == "UNKNOWN" { self.ledger(&WORKER, json!({"type":"unknown","attemptId":attempt_id}))?; } else { self.ledger(&WORKER, json!({"type":"settle","attemptId":attempt_id,"actualCost":settled["actualCost"]}))?; } steps.push(if effect == "UNKNOWN" { "ledger unknown" } else { "ledger settle" }.to_owned()); self.trail.push((attempt_id.clone(), steps)); // 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 effect != "CONFIRMED_APPLIED" { eprintln!("stopped: {attempt_id} is {effect}"); return Err(error(STOPPED)); } Ok(operation_id.to_owned()) } fn missing_kind(&self) -> Option<&'static str> { REQUIRED_KINDS.into_iter().find(|kind| !self.collected.iter().any(|c| c == kind)) } fn collect(&mut self, node_id: &str, kind: &str) -> Result<String> { let action = json!({"capability":"read-records","resource":"inspection-records","payload":{"caseId":CASE,"kind":kind},"preconditions":{}}); let mut adapter = RecordsReader { directory: self.directory.clone(), evidence: self.evidence.clone() }; let operation_id = self.perform(RUN, node_id, &format!("example:operation:records-{kind}"), action, &mut adapter, None)?; self.collected.push(kind.to_owned()); let revision = self.evidence_of(&operation_id); self.record_revisions.push(revision); Ok(operation_id) } // The case update the reviewer approves: the exact new state, the evidence revisions behind it and the version it replaces. fn case_update(&self) -> Value { json!({"capability":"update-case","resource":"case:guarding-17","preconditions":{"version":1},"payload":{"caseId":CASE, "update":{"status":"CORRECTIVE_ACTION_PROPOSED","correctiveAction":self.evidence_of("example:operation:draft-action")},"evidence":self.record_revisions}}) } fn ask(&mut self, to: &'static Session, run_id: &str, node_id: &str, kind: &str) -> Result<Option<Value>> { let (wait_id, correlation) = (wait_id_of(node_id), format!("example:correlation:{node_id}")); let deadline = (self.clock.0.get() + 3600000).to_string(); self.mission(&RUNNER, json!({"type":"wait","runId":run_id,"waitId":wait_id,"correlation":correlation,"kind":kind,"deadline":deadline}))?; self.mission(&RUNNER, json!({"type":"transition","runId":run_id,"to":"WAITING"}))?; self.routes.borrow_mut().insert(wait_id.clone(), to.actor.to_owned()); self.inbox.push_back(Ask { to, node_id: node_id.to_owned(), wait_id, correlation }); Ok(None) } // The package: the record revisions, the draft and the case receipt. fn package_evidence(&self) -> Vec<String> { let mut all = self.record_revisions.clone(); all.extend([self.evidence_of("example:operation:draft-action"), self.evidence_of("example:operation:update-case")]); all } // 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. fn answer(&mut self, item: &Ask) -> Result<()> { self.clock.0.set(self.clock.0.get() + 600000); let later = (self.clock.0.get() + 3600000).to_string(); match item.node_id.as_str() { "engineering-review" => { let reviewed = fingerprint(&Action::from_value(self.case_update())?)?; self.mission(&REVIEWER, json!({"type":"approve","approval":{"id":APPROVAL,"runId":RUN, "approver":REVIEWER.actor,"fingerprint":reviewed,"expiresAt":later,"uses":"1"}}))?; } "implementation-evidence" => { // 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. let event = json!({"source":"example:maintenance-system","type":"implementation-attested","correlation":item.correlation, "data":{"caseId":CASE,"work":"Interlock switch replaced and guard interlock retested"}}); let mut attested = event["data"].clone(); attested["attestedBy"] = json!(item.to.actor); self.attestation = artifact(&self.directory, &attested)?; } "verification" => { let results: serde_json::Map<String, Value> = CRITERIA.iter().map(|id| (id.to_string(), json!("PASS"))).collect(); let mut evidence = self.package_evidence(); evidence.push(self.attestation.clone()); self.mission(&VERIFIER, json!({"type":"verify","runId":FOLLOW_UP,"assessor":VERIFIER.actor,"revision":FOLLOW_UP_VERIFICATION,"results":results, "evidence":evidence,"rationale":"Records, reviewed draft, case receipt and implementation attestation support every criterion"}))?; } "acceptance" => { self.mission(&VERIFIER, json!({"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"}))?; } _ => {} } self.mission(item.to, json!({"type":"resume","waitId":item.wait_id,"correlation":item.correlation}))?; Ok(()) } // Each node returns its completion proof, or None 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. fn node(&mut self, node_id: &str, state: &Value) -> Result<Option<Value>> { let (directory, evidence) = (self.directory.clone(), self.evidence.clone()); Ok(Some(match node_id { "collect-records" => json!({"operationId":self.collect(node_id, "inspection")?}), // The bounded loop: each iteration requests one missing kind of record, at most maxIterations times. "request-more-records" => { let kind = self.missing_kind().unwrap(); let operation_id = self.collect(node_id, kind)?; json!({"operationId":operation_id,"done":self.missing_kind().is_none()}) } "draft-action" => { let action = json!({"capability":"draft","resource":"case-draft","payload":{"caseId":CASE,"records":self.record_revisions},"preconditions":{}}); json!({"operationId":self.perform(RUN, node_id, "example:operation:draft-action", action, &mut Drafter { directory, evidence }, None)?}) } "engineering-review" if state["approvals"].get(APPROVAL).is_some() => json!({"approvalId":APPROVAL}), "engineering-review" => return self.ask(&REVIEWER, RUN, node_id, "AUTHORIZATION"), // The approval-bound case-record write: the SDK admits it only when its fingerprint matches an unexpired, unused approval. "update-case" => { let (action, mut adapter) = (self.case_update(), self.case_record()); json!({"operationId":self.perform(RUN, node_id, "example:operation:update-case", action, &mut adapter, Some(APPROVAL))?}) } "implementation-evidence" if state["waits"][wait_id_of(node_id)]["status"] == "SATISFIED" => json!({"waitId":wait_id_of(node_id)}), "implementation-evidence" => return self.ask(&TECHNICIAN, FOLLOW_UP, node_id, "EXTERNAL"), "verification" if state["assessments"].get(FOLLOW_UP).is_some() => json!({"revision":FOLLOW_UP_VERIFICATION}), "verification" => return self.ask(&VERIFIER, FOLLOW_UP, node_id, "INPUT"), "acceptance" if state["assessments"][FOLLOW_UP]["acceptance"] != "NOT_REQUESTED" => json!({"revision":FOLLOW_UP_VERIFICATION}), "acceptance" => return self.ask(&VERIFIER, FOLLOW_UP, node_id, "INPUT"), // The case owner decides return to service, so the follow-up run notifies them of the acceptance. "notify-case-owner" => { let action = json!({"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":{}}); json!({"operationId":self.perform(FOLLOW_UP, node_id, "example:operation:notify-case-owner", action, &mut Placeholder, None)?}) } _ => json!({"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. fn start_up(&mut self) -> Result<()> { self.store = Some(SqliteStore::open(self.directory.join("mission.db").to_str().unwrap(), Some(&self.contract))?); self.ledger_store = Some(LimitStore::open(self.directory.join("ledger.db").to_str().unwrap(), Some(&self.envelope))?); let mut recovered = vec![]; for run in self.snapshot()?["runs"].as_object().unwrap().values() { if TERMINAL.contains(&run["state"].as_str().unwrap()) { continue; } let run_id = run["id"].as_str().unwrap().to_owned(); let segment_id = format!("{run_id}:segment:{}", run["segments"].as_array().unwrap().len()); let (_, unresolved) = self.with_mission(&RUNNER, |c| c.recover(&run_id, &segment_id))?; let mut reconciled = vec![]; for attempt_id in unresolved { let before = self.snapshot()?; let capability = before["operations"][before["attempts"][&attempt_id]["operationId"].as_str().unwrap()]["action"]["capability"].clone(); let (directory, evidence, mut case_record) = (self.directory.clone(), self.evidence.clone(), self.case_record()); let state = self.with_mission(&WORKER, |c| match capability.as_str().unwrap() { "read-records" => c.reconcile(&attempt_id, &mut RecordsReader { directory, evidence }), "draft" => c.reconcile(&attempt_id, &mut Drafter { directory, evidence }), "update-case" => c.reconcile(&attempt_id, &mut case_record), _ => c.reconcile(&attempt_id, &mut Placeholder), })?; let settled = state.as_value()["attempts"][&attempt_id].clone(); let effect = settled["effect"].as_str().unwrap().to_owned(); self.steps(&attempt_id).extend(["mission recover".to_owned(), format!("mission reconcile {effect}")]); reconciled.push(json!({"attemptId":attempt_id,"effect":effect})); if effect == "UNKNOWN" { continue; } // Simulated human decision: replace before deployment. The case owner reviews the read-back and settles the ledger. self.ledger(&OWNER, json!({"type":"settle","attemptId":attempt_id,"actualCost":settled["actualCost"]}))?; self.steps(&attempt_id).push("ledger settle".to_owned()); } recovered.push(json!({"runId":run_id,"segmentId":segment_id,"reconciled":reconciled})); } self.start_ups.push(json!({"recovered":recovered})); Ok(()) } // 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. fn root_grant(&self) -> Value { let c = self.contract.as_value(); json!({"id":GRANT,"subject":AGENT.actor,"profile":"finite-v1","actions":c["actions"],"resources":c["resources"], "notBefore":"0","expiresAt":c["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. fn refused<T>(&mut self, command: &str, result: Result<T>) { match result { Err(e) => self.denials.push(json!({"command":command,"actor":AGENT.actor,"refused":e.code})), Ok(_) => panic!("{command} was not refused"), } } fn overstep(&mut self) { let mut widened = self.root_grant(); widened["id"] = json!(format!("{GRANT}:widened")); widened["limit"] = self.contract.as_value()["budget"].clone(); let grant = self.mission(&AGENT, json!({"type":"grant","grant":widened})); self.refused("grant", grant); let adjust = self.ledger(&AGENT, json!({"type":"adjust","scopeId":WORK_ORDER, "limits":{"cost":"1000","handoff":"10","activeMs":null,"elapsedMs":"28800000","attempts":"100"}})); self.refused("adjust", adjust); } fn until_stopped(&mut self, run_id: &str) -> Result<()> { match self.drive(run_id) { Err(e) if e.code == STOPPED => { self.store = None; self.ledger_store = None; Ok(()) } other => other, } } // The run loop over the graph: dispatch each ready node and complete it with its proof. fn drive(&mut self, run_id: &str) -> Result<()> { loop { let state = self.store.as_ref().unwrap().snapshot()?; let run_state = state.as_value()["runs"][run_id]["state"].as_str().unwrap().to_owned(); if TERMINAL.contains(&run_state.as_str()) { return Ok(()); } if run_state == "WAITING" { let item = self.inbox.pop_front().unwrap(); self.answer(&item)?; self.mission(&RUNNER, json!({"type":"join","runId":run_id,"waitIds":[item.wait_id],"mode":"ALL"}))?; continue; } let Some(node_id) = ready_nodes(&state, run_id)?.into_iter().next() else { self.mission(&RUNNER, json!({"type":"transition","runId":run_id,"to":"COMPLETED"}))?; continue; }; if let Some(proof) = self.node(&node_id, state.as_value())? { self.mission(&RUNNER, json!({"type":"completeNode","runId":run_id,"nodeId":node_id,"result":proof}))?; } } } fn start(&mut self, run_id: &str, graph: &Value) -> Result<()> { self.mission(&RUNNER, json!({"type":"startRun","runId":run_id}))?; self.mission(&RUNNER, json!({"type":"registerGraph","graph":graph}))?; self.mission(&RUNNER, json!({"type":"attachGraph","runId":run_id,"graphId":graph["id"]}))?; Ok(()) }}
fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { let contract = Contract::parse(&json!({ "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"]}).to_string())?; // The resource envelope, approved by a human before the run: 100 capability calls and 8 elapsed hours. let run_scope = |run_id: &str| json!({"id":run_id,"parentId":WORK_ORDER,"kind":"RUN","workOrderId":WORK_ORDER,"runId":run_id,"nodeId":null,"dependsOn":[],"startMs":"0", "limits":{"cost":null,"handoff":"0","activeMs":null,"elapsedMs":null,"attempts":null}}); let envelope = parse_strict(&json!({"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_scope(RUN), run_scope(FOLLOW_UP)]}).to_string())?; // 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. let package_graph = json!({"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":{}}]}); let follow_up_graph = json!({"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":{}}]}); let directory = std::env::temp_dir().join(format!("aiws-annex-b-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos())); std::fs::create_dir(&directory)?; std::fs::write(directory.join("case-record.json"), canonical(&json!({"caseId":CASE,"version":1,"status":"OPEN","correctiveAction":null,"evidence":[],"history":[]}))?)?; let mut host = Host { store: None, ledger_store: None, contract: contract.clone(), envelope, clock: ScriptedClock(Rc::new(Cell::new(0))), directory: directory.clone(), routes: Rc::default(), evidence: Rc::default(), acknowledgments_to_drop: Rc::new(Cell::new(1)), trail: vec![], inbox: VecDeque::new(), collected: vec![], record_revisions: vec![], attestation: String::new(), start_ups: vec![], denials: vec![], }; host.start_up()?; host.start(RUN, &package_graph)?; let grant = host.root_grant(); host.mission(&OWNER, json!({"type":"grant","grant":grant}))?; host.overstep(); host.until_stopped(RUN)?; host.start_up()?; host.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. host.clock.0.set(host.clock.0.get() + 600000); let evidence = host.package_evidence(); host.mission(&VERIFIER, json!({"type":"verify","runId":RUN,"assessor":VERIFIER.actor,"revision":VERIFICATION, "results":{"issue-identified":"PASS","engineering-reviewed":"PASS","implementation-evidenced":"INCONCLUSIVE","effectiveness-accepted":"INCONCLUSIVE"}, "evidence":evidence,"rationale":"Records, reviewed draft and case receipt support the first two criteria; no implementation evidence yet"}))?; host.clock.0.set(host.clock.0.get() + 600000); host.mission(&VERIFIER, json!({"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. host.start(FOLLOW_UP, &follow_up_graph)?; host.until_stopped(FOLLOW_UP)?; // The notification is still UNKNOWN after this start-up, so the host holds the follow-up run for a human. host.start_up()?; let now = host.clock.now_ms(); let exported = host.store.as_mut().unwrap().flush_telemetry(&mut Collector, &now, 1000)?; let snapshot = host.store.as_ref().unwrap().snapshot()?; let final_state = snapshot.as_value(); let audit = parse_strict(&host.store.as_ref().unwrap().export_audit()?)?; let ledger_store = host.ledger_store.as_ref().unwrap(); let approval = &final_state["approvals"][APPROVAL]; let update = &final_state["operations"]["example:operation:update-case"]; let settles: Vec<Value> = ledger_store.export_events()?.into_iter().filter(|e| e["request"]["command"]["type"] == "settle").collect(); let ledger_state = ledger_store.snapshot()?; let usage = ledger_store.report(&now)?["scopes"].as_array().unwrap().iter().find(|s| s["scopeId"] == WORK_ORDER).unwrap()["usage"].clone(); let effects: Vec<Value> = host.trail.iter().map(|(attempt_id, order)| { let (attempt, held) = (&final_state["attempts"][attempt_id], &ledger_state["attempts"][attempt_id]); let operation = &final_state["operations"][attempt["operationId"].as_str().unwrap()]; let facts = settles.iter().find(|e| e["request"]["command"]["attemptId"] == attempt_id.as_str()).map(|e| e["facts"].clone()).unwrap_or(Value::Null); json!({"operationId":operation["id"],"nodeId":operation["nodeId"],"effect":attempt["effect"],"actualCost":attempt["actualCost"],"order":order, "ledger":{"status":held["status"],"amount":held["amount"],"actualCost":held["actualCost"],"evidenceRef":facts["evidenceRef"],"settledBy":facts["actorId"]}}) }).collect(); let outcome = |run_id: &str| -> Result<Value> { let (assessment, success) = (&final_state["assessments"][run_id], assess_success(&snapshot, run_id)?); Ok(json!({"executionState":final_state["runs"][run_id]["state"],"verificationState":assessment["verification"],"acceptanceState":assessment["acceptance"], "verifiedSuccessful":success["verifiedSuccessful"],"reasons":success["reasons"]})) }; let (package_outcome, mut follow_up) = (outcome(RUN)?, outcome(FOLLOW_UP)?); follow_up["runId"] = json!(FOLLOW_UP); let c = contract.as_value(); let grant = &final_state["grants"][GRANT]; let granted_by = &final_state["events"].as_array().unwrap().iter().find(|e| e["command"]["type"] == "grant").unwrap()["command"]["context"]["actor"]; let assessments: Vec<Value> = [RUN, FOLLOW_UP].iter().map(|run_id| { let a = &final_state["assessments"][run_id]; json!({"runId":run_id,"revision":a["revision"],"assessor":a["assessor"],"verification":a["verification"],"evidence":a["evidence"], "authority":a["acceptanceRecord"]["authority"],"acceptance":a["acceptance"]}) }).collect(); let record = json!({ // Annex B's illustrative result record, for run 1. "result":{"exampleOnly":true,"runId":RUN,"executionState":package_outcome["executionState"],"verificationState":package_outcome["verificationState"], "acceptanceState":package_outcome["acceptanceState"],"missionId":c["missionId"],"contractRevision":c["id"], "verifiedSuccessful":package_outcome["verifiedSuccessful"], "criterionResults":CRITERIA.iter().map(|id| json!({"criterionId":id,"verdict":final_state["assessments"][RUN]["results"][id]})).collect::<Vec<_>>(), "disposition":final_state["assessments"][RUN]["acceptanceRecord"]["rationale"]}, "followUp":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":effects, "startUps":host.start_ups, "grant":{"id":GRANT,"grantedBy":granted_by,"limit":grant["limit"],"canDelegate":grant["canDelegate"],"depth":grant["depth"], "grants":final_state["grants"].as_object().unwrap().keys().collect::<Vec<_>>(),"workOrderCostLimit":ledger_state["scopes"][WORK_ORDER]["limits"]["cost"]}, "denials":host.denials, "rejections":audit["diagnostics"].as_array().unwrap().iter().map(|d| json!({"rejectedType":d["command"]["rejectedType"],"code":d["command"]["code"], "actor":d["command"]["context"]["actor"]})).collect::<Vec<_>>(), "assessments":assessments, "accounting":{"missionSpent":final_state["spent"],"missionReserved":final_state["reserved"],"ledgerCost":usage["cost"],"ledgerAttempts":usage["attempts"]}, "telemetry":{"exported":exported.as_array().unwrap().len(),"allSent":exported.as_array().unwrap().iter().all(|r| r["status"] == "SENT")}, }); // Run 1 ends exactly as Annex B's illustrative result after physical implementation evidence is missing. assert_eq!(record["result"], json!({"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_eq!(record["followUp"], json!({"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 assessment in record["assessments"].as_array().unwrap() { assert_eq!(json!([assessment["assessor"], assessment["authority"]]), json!([VERIFIER.actor, VERIFIER.actor])); } // The approval is bound to the exact case update: same fingerprint, consumed once, by that write alone. const REVIEWED_FINGERPRINT: &str = "sha256:dc6286da8ce3fcc52283ea5fa2cba15dea085ecc67213a4f4bf18426888154ab"; assert_eq!(record["approval"]["fingerprint"], REVIEWED_FINGERPRINT); assert_eq!(record["approval"]["caseUpdate"]["fingerprint"], REVIEWED_FINGERPRINT); assert_eq!(record["approval"]["consumedBy"], json!(["example:operation:update-case"])); assert_eq!(record["approval"]["caseUpdate"]["preconditions"], json!({"version":1})); // Every effect was reserved before dispatch and settled after it, with the evidence that settled it. let effects = record["effects"].as_array().unwrap(); let nodes: Vec<&Value> = effects.iter().map(|e| &e["nodeId"]).collect(); assert_eq!(nodes, ["collect-records", "request-more-records", "request-more-records", "draft-action", "update-case", "notify-case-owner"]); for effect in &effects[..5] { assert_eq!(json!([effect["effect"], effect["actualCost"], effect["ledger"]["status"], effect["ledger"]["amount"], effect["ledger"]["actualCost"]]), json!(["CONFIRMED_APPLIED", "1", "SETTLED", "1", "1"])); let evidence_ref = effect["ledger"]["evidenceRef"].as_str().unwrap(); assert!(evidence_ref.starts_with("sha256:") && evidence_ref.len() == 71); } for effect in &effects[..4] { assert_eq!(effect["order"], json!(["ledger reserve", "mission admit", "ledger dispatch", "mission dispatch", "mission settle CONFIRMED_APPLIED", "ledger settle"])); assert_eq!(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_eq!(effects[4]["order"], json!(["ledger reserve", "mission admit", "ledger dispatch", "mission dispatch", "mission settle UNKNOWN", "ledger unknown", "mission recover", "mission reconcile CONFIRMED_APPLIED", "ledger settle"])); assert_eq!(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_eq!(effects[5], json!({"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_eq!(record["startUps"], json!([{"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"}]}]}])); let package_evidence = record["assessments"][0]["evidence"].as_array().unwrap(); let follow_up_evidence = record["assessments"][1]["evidence"].as_array().unwrap(); assert_eq!(effects[4]["ledger"]["evidenceRef"], package_evidence[4]); // the case receipt assert_eq!(record["approval"]["caseUpdate"]["evidence"].as_array().unwrap()[..], package_evidence[..3]); // the record revisions it approved assert_eq!(std::fs::read_to_string(directory.join("case-record.json"))?, canonical(&json!({"caseId":CASE,"version":2,"status":"CORRECTIVE_ACTION_PROPOSED", "correctiveAction":package_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_eq!(follow_up_evidence[..5], package_evidence[..]); assert_eq!(follow_up_evidence.len(), 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_eq!(record["grant"], json!({"id":GRANT,"grantedBy":OWNER.actor,"limit":"10","canDelegate":false,"depth":"0","grants":[GRANT],"workOrderCostLimit":"100"})); assert_eq!(record["denials"], json!([{"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_eq!(record["rejections"], json!([{"rejectedType":"grant","code":"AUTHORITY_DENIED","actor":AGENT.actor}])); // Five settled capability calls, and the UNKNOWN notification's reservation still held in both stores. assert_eq!(record["accounting"], json!({"missionSpent":"5","missionReserved":"1","ledgerCost":"6","ledgerAttempts":"6"})); assert_eq!(record["telemetry"]["allSent"], true); // The real clock reads canonical epoch milliseconds, past the scripted contract's deadline. let utc = UtcClock.now_ms(); assert!(!utc.starts_with('0') && utc.parse::<u128>()? > c["deadline"].as_str().unwrap().parse::<u128>()?); println!("{}", canonical(&record)?); Ok(())}import jsonimport osimport tempfileimport timefrom pathlib import Pathfrom aiws import assess_success, canonical, digest, fingerprint, parse_contract, parse_strict, ready_nodesfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinatorfrom aiws.observability import classify_responsefrom aiws.limits_store import LimitCoordinator, LimitStore# 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.RUN, FOLLOW_UP, WORK_ORDER = 'example:run:guarding-17', 'example:run:guarding-17:implementation', 'example:work-order:guarding-17'GRANT, CASE, APPROVAL = 'example:grant:investigator', 'example:case:guarding-17', 'example:approval:engineering-review'VERIFICATION, FOLLOW_UP_VERIFICATION = 'example:verification:guarding-17:1', 'example:verification:guarding-17:2'CRITERIA = ['issue-identified', 'engineering-reviewed', 'implementation-evidenced', 'effectiveness-accepted']POLICY = 'policy:example:annex-b:1'TERMINAL = ('COMPLETED', 'FAILED', 'CANCELED', 'REJECTED')contract = parse_contract(json.dumps(dict( 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.envelope = parse_strict(json.dumps(dict(protocol='aiws-limits/1', ledgerId='example:ledger:guarding-17', costUnit='capability-call', approvalRef='example:approval:resource-envelope', scopes=[ dict(id=WORK_ORDER, parentId=None, kind='WORK_ORDER', workOrderId=WORK_ORDER, runId=None, nodeId=None, dependsOn=[], startMs='0', limits=dict(cost='100', handoff='10', activeMs=None, elapsedMs='28800000', attempts='100')), *[dict(id=run_id, parentId=WORK_ORDER, kind='RUN', workOrderId=WORK_ORDER, runId=run_id, nodeId=None, dependsOn=[], startMs='0', limits=dict(cost=None, handoff='0', activeMs=None, elapsedMs=None, attempts=None)) for run_id in (RUN, FOLLOW_UP)]])))# 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.package_graph = dict(id='example:graph:corrective-action', revision='1', nodes=[ dict(id='collect-records', kind='TASK', dependsOn=[], config=dict(executionKind='AGENT')), dict(id='request-more-records', kind='LOOP', dependsOn=['collect-records'], config=dict(maxIterations='3')), dict(id='draft-action', kind='TASK', dependsOn=['request-more-records'], config=dict(executionKind='AGENT')), dict(id='engineering-review', kind='APPROVAL', dependsOn=['draft-action'], config={}), dict(id='update-case', kind='TASK', dependsOn=['engineering-review'], config=dict(executionKind='TOOL')), dict(id='end', kind='END', dependsOn=['update-case'], config={})])follow_up_graph = dict(id='example:graph:implementation-evidence', revision='1', nodes=[ dict(id='implementation-evidence', kind='WAIT', dependsOn=[], config={}), dict(id='verification', kind='VERIFICATION', dependsOn=['implementation-evidence'], config={}), dict(id='acceptance', kind='ACCEPTANCE', dependsOn=['verification'], config={}), dict(id='notify-case-owner', kind='TASK', dependsOn=['acceptance'], config=dict(executionKind='TOOL')), dict(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.def utc_clock(): return str(time.time_ns() // 1_000_000)scripted_ms = 0def scripted_clock(): return str(scripted_ms)clock = scripted_clock
# 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.RUNNER, WORKER = dict(actor='host:runner', kind='RULE'), dict(actor='host:worker-1', kind='RULE')AGENT, OWNER = dict(actor='agent:investigator', kind='AGENT'), dict(actor='human:case-owner', kind='HUMAN')REVIEWER, TECHNICIAN = dict(actor='human:engineering-reviewer', kind='HUMAN'), dict(actor='human:authorized-technician', kind='HUMAN')VERIFIER = dict(actor='human:designated-verifier', kind='HUMAN')
routes = {} # wait id -> the one principal routed to answer it# Deny by default: a command is allowed only when a rule below names its session.AGENT_ACTIONS = ['read-records inspection-records', 'draft case-draft', 'update-case case:guarding-17', 'notify case-owner-inbox']def permits(session, c): kind = c['type'] if kind in ('startRun', 'continueRun', 'registerGraph', 'attachGraph', 'completeNode', 'wait', 'join', 'transition'): return session is RUNNER if kind == 'admit': return (session is AGENT and c['subject'] == AGENT['actor'] and c['action']['capability'] + ' ' + c['action']['resource'] in AGENT_ACTIONS and (c['action']['capability'] != 'update-case' or 'approvalId' in c)) if kind in ('dispatch', 'settle'): return session is WORKER if kind == 'grant': return session is OWNER if kind == 'approve': return session is REVIEWER and c['approval']['approver'] == REVIEWER['actor'] if kind == 'resume': return routes.get(c['waitId']) == session['actor'] if kind == 'verify': return session is VERIFIER and c['assessor'] == VERIFIER['actor'] if kind == 'accept': return session is VERIFIER and c['authority'] == VERIFIER['actor'] # Annex B: accepted by the designated verifier return Falsedef authorizer_for(session): def authorize(command, state, now): allowed = permits(session, command) return dict(allowed=allowed, policy='ALLOW' if allowed else 'DENY', mandatoryChecksOk=True, context=dict(actor=session['actor'], policyRevision=POLICY, decisionClass='HUMAN' if session['kind'] == 'HUMAN' else 'DETERMINISTIC')) return authorizeevidence = {} # attempt id -> digest of the artifact that evidences its outcomedef ledger_authorizer_for(session): def authorize(request, state, now): kind = request['command']['type'] evidence_ref = evidence.get(request['command']['attemptId']) if kind == 'settle' else None if kind == 'reserve': allowed = session is AGENT # Only a human settles an UNKNOWN ledger attempt, on the evidence that resolved it. elif kind == 'settle' and session is OWNER: allowed = state['attempts'].get(request['command']['attemptId'], {}).get('status') == 'UNKNOWN' else: allowed = kind in ('dispatch', 'settle', 'unknown', 'release') and session is WORKER return dict(allowed=allowed and (kind != 'settle' or evidence_ref is not None), actorId=session['actor'], actorKind=session['kind'], policyRef=POLICY, evidenceRef=evidence_ref, authorizedAtMs=now) return authorize
# 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.directory = Path(tempfile.mkdtemp(prefix='aiws-annex-b-'))store = ledger_store = Nonedef mission(session): return Coordinator(store, authorizer_for(session), clock)def ledger(session, command): return LimitCoordinator(ledger_store, ledger_authorizer_for(session), clock).apply(dict( requestId=command['type'] + ':' + command.get('attemptId', command.get('scopeId')), expectedRevision=ledger_store.snapshot()['revision'], command=command))
# Immutable local artifacts: content-addressed, written once with create-new and fsync, never rewritten.def artifact_path(revision): return directory / (revision[len('sha256:'):] + '.json')def artifact(value): data, revision = canonical(value), digest(value) path = artifact_path(revision) try: with path.open('x', encoding='utf-8', newline='') as out: out.write(data); out.flush(); os.fsync(out.fileno()) except FileExistsError: if path.read_text(encoding='utf-8') != data: raise return revision
# A local stand-in for the approved-records system: replace before deployment.RECORDS = [ dict(id='example:record:inspection-17', kind='inspection', approved=True, text='Press 4 interlock guard lifts while the ram is energized'), dict(id='example:record:field-note-17', kind='inspection', approved=False, text='Unreviewed field note'), dict(id='example:record:maintenance-press-4', kind='maintenance', approved=True, text='Guard hinge replaced; interlock switch not retested'), dict(id='example:record:training-press-4', kind='training', approved=True, text='Operator lockout training is current')]class RecordsReader: def execute(self, operation, attempt): kind = operation['action']['payload']['kind'] evidence[attempt['id']] = artifact(dict(kind=kind, records=[r for r in RECORDS if r['approved'] and r['kind'] == kind])) return dict(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. def reconcile(self, operation, attempt): return dict(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.REQUIRED_KINDS, collected = ['inspection', 'maintenance', 'training'], []def missing_kind(): return next((kind for kind in REQUIRED_KINDS if kind not in collected), None)class Drafter: def execute(self, operation, attempt): bundles = [parse_strict(artifact_path(revision).read_text(encoding='utf-8')) for revision in operation['action']['payload']['records']] evidence[attempt['id']] = artifact(dict(caseId=CASE, basedOn=[r['id'] for b in bundles for r in b['records']], proposedAction='Replace the press 4 interlock switch, retest the guard interlock and brief operators')) return dict(effect='CONFIRMED_APPLIED', actualCost='1') def reconcile(self, operation, attempt): return dict(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.case_path = directory / 'case-record.json'case_path.write_text(canonical(dict(caseId=CASE, version=1, status='OPEN', correctiveAction=None, evidence=[], history=[])), encoding='utf-8', newline='')class CaseRecord: acknowledgments_to_drop = 1 def execute(self, operation, attempt): record, action = parse_strict(case_path.read_text(encoding='utf-8')), operation['action'] if any(h['operationId'] == operation['id'] for h in record['history']): evidence[attempt['id']] = artifact(record); return dict(effect='CONFIRMED_APPLIED', actualCost='1') if record['version'] != action['preconditions']['version']: evidence[attempt['id']] = artifact(record); return dict(effect='CONFIRMED_NOT_APPLIED', actualCost='1') following = dict(caseId=record['caseId'], version=record['version'] + 1, **action['payload']['update'], evidence=action['payload']['evidence'], history=[*record['history'], dict(version=record['version'] + 1, operationId=operation['id'])]) Path(str(case_path) + '.next').write_text(canonical(following), encoding='utf-8', newline='') os.replace(str(case_path) + '.next', case_path) if CaseRecord.acknowledgments_to_drop > 0: CaseRecord.acknowledgments_to_drop -= 1 raise TimeoutError('the case-record system did not acknowledge the update') evidence[attempt['id']] = artifact(following) return dict(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. def reconcile(self, operation, attempt): record, version = parse_strict(case_path.read_text(encoding='utf-8')), operation['action']['preconditions']['version'] + 1 if dict(version=version, operationId=operation['id']) not in record['history']: return dict(effect='UNKNOWN', actualCost='0') evidence[attempt['id']] = artifact(record) return dict(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.class Placeholder: def execute(self, operation, attempt): return dict(effect='UNKNOWN', actualCost='0') def reconcile(self, operation, attempt): return dict(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.trail = {} # attempt id -> the steps the host committed, in orderdef attempt_id_of(operation_id): return operation_id + ':attempt:1' # each operation runs one attempt hereclass Stopped(Exception): passdef perform(run_id, node_id, operation_id, action, adapter, approval_id=None): # A restarted host never repeats an operation: it completes the node only on a confirmed outcome. existing = store.snapshot()['operations'].get(operation_id) if existing: if existing['effect'] != 'CONFIRMED_APPLIED': raise Stopped(f"stopped: {operation_id} is {existing['effect']}") return operation_id attempt_id, amount, steps = attempt_id_of(operation_id), '1', [] trail[attempt_id] = steps ledger(AGENT, dict(type='reserve', attemptId=attempt_id, operationId=operation_id, scopeId=run_id, runId=run_id, purpose='ORDINARY', amount=amount, maxActiveMs='60000')) steps.append('ledger reserve') try: mission(AGENT).apply(dict(type='admit', runId=run_id, operationId=operation_id, attemptId=attempt_id, grantId=GRANT, subject=AGENT['actor'], action=action, amount=amount, **({'approvalId': approval_id} if approval_id else {}), authorizationCheckedAt='0', policy='INDETERMINATE', mandatoryChecksOk=False)) # the coordinator fills the policy fields except Exception: ledger(WORKER, dict(type='release', attemptId=attempt_id)); raise steps.append('mission admit') ledger(WORKER, dict(type='dispatch', attemptId=attempt_id)) steps.append('ledger dispatch') settled = mission(WORKER).dispatch(attempt_id, adapter, node_id)['attempts'][attempt_id] steps.extend(['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': ledger(WORKER, dict(type='unknown', attemptId=attempt_id)) else: ledger(WORKER, dict(type='settle', attemptId=attempt_id, actualCost=settled['actualCost'])) steps.append('ledger unknown' if settled['effect'] == 'UNKNOWN' else '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': raise Stopped(f"stopped: {attempt_id} is {settled['effect']}") return operation_id
def read(kind): return dict(capability='read-records', resource='inspection-records', payload=dict(caseId=CASE, kind=kind), preconditions={})def evidence_of(operation_id): return evidence[attempt_id_of(operation_id)]record_revisions = []def collect(node_id, kind): operation_id = perform(RUN, node_id, f'example:operation:records-{kind}', read(kind), RecordsReader()) collected.append(kind); record_revisions.append(evidence_of(operation_id)) return operation_id# The case update the reviewer approves: the exact new state, the evidence revisions behind it and the version it replaces.def case_update(): return dict(capability='update-case', resource='case:guarding-17', preconditions=dict(version=1), payload=dict(caseId=CASE, update=dict(status='CORRECTIVE_ACTION_PROPOSED', correctiveAction=evidence_of('example:operation:draft-action')), evidence=list(record_revisions)))
# 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.inbox = []def wait_id_of(node_id): return 'example:wait:' + node_iddef ask(to, run_id, node_id, kind): wait_id, correlation = wait_id_of(node_id), 'example:correlation:' + node_id mission(RUNNER).apply(dict(type='wait', runId=run_id, waitId=wait_id, correlation=correlation, kind=kind, deadline=str(scripted_ms + 3600000))) mission(RUNNER).apply(dict(type='transition', runId=run_id, to='WAITING')) routes[wait_id] = to['actor']; inbox.append(dict(to=to, nodeId=node_id, waitId=wait_id, correlation=correlation)) return None# 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.attestation = ''# The package: the record revisions, the draft and the case receipt.def package_evidence(): return [*record_revisions, evidence_of('example:operation:draft-action'), evidence_of('example:operation:update-case')]def attest_implementation(item): global attestation # 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. event = dict(source='example:maintenance-system', type='implementation-attested', correlation=item['correlation'], data=dict(caseId=CASE, work='Interlock switch replaced and guard interlock retested')) attestation = artifact({**event['data'], 'attestedBy': item['to']['actor']})answers = { 'engineering-review': lambda item: mission(REVIEWER).apply(dict(type='approve', approval=dict(id=APPROVAL, runId=RUN, approver=REVIEWER['actor'], fingerprint=fingerprint(case_update()), expiresAt=str(scripted_ms + 3600000), uses='1'))), 'implementation-evidence': attest_implementation, 'verification': lambda item: mission(VERIFIER).apply(dict(type='verify', runId=FOLLOW_UP, assessor=VERIFIER['actor'], revision=FOLLOW_UP_VERIFICATION, results={criterion: 'PASS' for criterion in CRITERIA}, evidence=[*package_evidence(), attestation], rationale='Records, reviewed draft, case receipt and implementation attestation support every criterion')), 'acceptance': lambda item: mission(VERIFIER).apply(dict(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')),}def answer(item): global scripted_ms scripted_ms += 600000 answers[item['nodeId']](item) mission(item['to']).apply(dict(type='resume', waitId=item['waitId'], correlation=item['correlation']))# Each node returns its completion proof, or None 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.def request_more_records(state): # The bounded loop: each iteration requests one missing kind of record, at most maxIterations times. operation_id = collect('request-more-records', missing_kind()) return dict(operationId=operation_id, done=missing_kind() is None)nodes = { 'collect-records': lambda state: dict(operationId=collect('collect-records', 'inspection')), 'request-more-records': request_more_records, 'draft-action': lambda state: dict(operationId=perform(RUN, 'draft-action', 'example:operation:draft-action', dict(capability='draft', resource='case-draft', payload=dict(caseId=CASE, records=list(record_revisions)), preconditions={}), Drafter())), 'engineering-review': lambda state: dict(approvalId=APPROVAL) if APPROVAL in state['approvals'] else 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': lambda state: dict(operationId=perform(RUN, 'update-case', 'example:operation:update-case', case_update(), CaseRecord(), APPROVAL)), 'end': lambda state: dict(disposition='COMPLETED'), 'implementation-evidence': lambda state: dict(waitId=wait_id_of('implementation-evidence')) if state['waits'].get(wait_id_of('implementation-evidence'), {}).get('status') == 'SATISFIED' else ask(TECHNICIAN, FOLLOW_UP, 'implementation-evidence', 'EXTERNAL'), 'verification': lambda state: dict(revision=FOLLOW_UP_VERIFICATION) if FOLLOW_UP in state['assessments'] else ask(VERIFIER, FOLLOW_UP, 'verification', 'INPUT'), 'acceptance': lambda state: dict(revision=FOLLOW_UP_VERIFICATION) if state['assessments'][FOLLOW_UP]['acceptance'] != 'NOT_REQUESTED' else 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': lambda state: dict(operationId=perform(FOLLOW_UP, 'notify-case-owner', 'example:operation:notify-case-owner', dict(capability='notify', resource='case-owner-inbox', payload=dict(caseId=CASE, runId=FOLLOW_UP, message='The corrective-action package is accepted; return to service is your decision'), preconditions={}), Placeholder())), 'follow-up-end': lambda state: dict(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.adapters = {'read-records': RecordsReader(), 'draft': Drafter(), 'update-case': CaseRecord(), 'notify': Placeholder()}start_ups = []def start_up(): global store, ledger_store store = SqliteStore(str(directory / 'mission.db'), contract) ledger_store = LimitStore(str(directory / 'ledger.db'), envelope) recovered = [] for run in list(store.snapshot()['runs'].values()): if run['state'] in TERMINAL: continue segment_id, reconciled = run['id'] + ':segment:' + str(len(run['segments'])), [] unresolved = mission(RUNNER).recover(run['id'], segment_id)['unresolved'] for attempt_id in unresolved: before = store.snapshot() operation = before['operations'][before['attempts'][attempt_id]['operationId']] settled = mission(WORKER).reconcile(attempt_id, adapters[operation['action']['capability']])['attempts'][attempt_id] trail[attempt_id].extend(['mission recover', 'mission reconcile ' + settled['effect']]) reconciled.append(dict(attemptId=attempt_id, effect=settled['effect'])) if settled['effect'] == 'UNKNOWN': continue # Simulated human decision: replace before deployment. The case owner reviews the read-back and settles the ledger. ledger(OWNER, dict(type='settle', attemptId=attempt_id, actualCost=settled['actualCost'])) trail[attempt_id].append('ledger settle') recovered.append(dict(runId=run['id'], segmentId=segment_id, reconciled=reconciled)) start_ups.append(dict(recovered=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.def root_grant(): return dict(id=GRANT, subject=AGENT['actor'], profile='finite-v1', 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.denials = []def refused(command, work): try: work() except Exception as e: denials.append(dict(command=command, actor=AGENT['actor'], refused=e.code)); return raise RuntimeError(command + ' was not refused')def overstep(): refused('grant', lambda: mission(AGENT).apply(dict(type='grant', grant={**root_grant(), 'id': GRANT + ':widened', 'limit': contract['budget']}))) refused('adjust', lambda: ledger(AGENT, dict(type='adjust', scopeId=WORK_ORDER, limits=dict(cost='1000', handoff='10', activeMs=None, 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.def until_stopped(work, *args): try: work(*args) except Stopped: store.close(); ledger_store.close()# The run loop over the graph: dispatch each ready node and complete it with its proof.def drive(run_id): while True: state = store.snapshot() if state['runs'][run_id]['state'] in TERMINAL: return if state['runs'][run_id]['state'] == 'WAITING': item = inbox.pop(0) answer(item) mission(RUNNER).apply(dict(type='join', runId=run_id, waitIds=[item['waitId']], mode='ALL')) continue ready = ready_nodes(state, run_id) if not ready: mission(RUNNER).apply(dict(type='transition', runId=run_id, to='COMPLETED')); continue proof = nodes[ready[0]](state) if proof is not None: mission(RUNNER).apply(dict(type='completeNode', runId=run_id, nodeId=ready[0], result=proof))def start(run_id, graph): mission(RUNNER).apply(dict(type='startRun', runId=run_id)) mission(RUNNER).apply(dict(type='registerGraph', graph=graph)) mission(RUNNER).apply(dict(type='attachGraph', runId=run_id, graphId=graph['id']))
class Collector: """Simulated telemetry export: replace before deployment with a collector client that has a timeout and redirects disabled.""" def send(self, signal, payload): return classify_response(200, '{}')
start_up()try: start(RUN, package_graph) mission(OWNER).apply(dict(type='grant', grant=root_grant())) overstep() until_stopped(drive, RUN) start_up() 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. scripted_ms += 600000 mission(VERIFIER).apply(dict(type='verify', runId=RUN, assessor=VERIFIER['actor'], revision=VERIFICATION, results={'issue-identified': 'PASS', 'engineering-reviewed': 'PASS', 'implementation-evidenced': 'INCONCLUSIVE', 'effectiveness-accepted': 'INCONCLUSIVE'}, evidence=package_evidence(), rationale='Records, reviewed draft and case receipt support the first two criteria; no implementation evidence yet')) scripted_ms += 600000 mission(VERIFIER).apply(dict(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. start(FOLLOW_UP, follow_up_graph) until_stopped(drive, FOLLOW_UP) # The notification is still UNKNOWN after this start-up, so the host holds the follow-up run for a human. start_up() exported = store.flush_telemetry(Collector(), clock(), 1000) final = store.snapshot() approval, update = final['approvals'][APPROVAL], final['operations']['example:operation:update-case'] settles = [e for e in ledger_store.export_events() if e['request']['command']['type'] == 'settle'] ledger_state = ledger_store.snapshot() ledger_attempts = ledger_state['attempts'] usage = next(s['usage'] for s in ledger_store.report(clock())['scopes'] if s['scopeId'] == WORK_ORDER) def settlement_of(attempt_id): facts = next((e['facts'] for e in settles if e['request']['command']['attemptId'] == attempt_id), None) return dict(evidenceRef=facts['evidenceRef'] if facts else None, settledBy=facts['actorId'] if facts else None) def outcome(run_id): assessment = final['assessments'][run_id] return dict(executionState=final['runs'][run_id]['state'], verificationState=assessment['verification'], acceptanceState=assessment['acceptance']) def effect_record(attempt_id): attempt = final['attempts'][attempt_id]; operation = final['operations'][attempt['operationId']]; held = ledger_attempts[attempt_id] return dict(operationId=operation['id'], nodeId=operation['nodeId'], effect=attempt['effect'], actualCost=attempt['actualCost'], order=trail[attempt_id], ledger=dict(status=held['status'], amount=held['amount'], actualCost=held['actualCost'], **settlement_of(attempt_id))) def assessment_record(run_id): assessment = final['assessments'][run_id] return dict(runId=run_id, revision=assessment['revision'], assessor=assessment['assessor'], verification=assessment['verification'], evidence=assessment['evidence'], authority=assessment['acceptanceRecord']['authority'], acceptance=assessment['acceptance']) grant = final['grants'][GRANT] record = dict( # Annex B's illustrative result record, for run 1. result=dict(exampleOnly=True, runId=RUN, **outcome(RUN), missionId=contract['missionId'], contractRevision=contract['id'], verifiedSuccessful=assess_success(final, RUN)['verifiedSuccessful'], criterionResults=[dict(criterionId=criterion, verdict=final['assessments'][RUN]['results'][criterion]) for criterion in CRITERIA], disposition=final['assessments'][RUN]['acceptanceRecord']['rationale']), followUp=dict(runId=FOLLOW_UP, **outcome(FOLLOW_UP), **assess_success(final, FOLLOW_UP)), approval=dict(id=APPROVAL, approver=approval['approver'], fingerprint=approval['fingerprint'], expiresAt=approval['expiresAt'], uses=approval['uses'], consumedBy=approval['operations'], caseUpdate=dict(fingerprint=update['fingerprint'], preconditions=update['action']['preconditions'], update=update['action']['payload']['update'], evidence=update['action']['payload']['evidence'])), effects=[effect_record(attempt_id) for attempt_id in trail], startUps=start_ups, grant=dict(id=GRANT, grantedBy=next(e for e in final['events'] if e['command']['type'] == 'grant')['command']['context']['actor'], limit=grant['limit'], canDelegate=grant['canDelegate'], depth=grant['depth'], grants=list(final['grants']), workOrderCostLimit=ledger_state['scopes'][WORK_ORDER]['limits']['cost']), denials=denials, rejections=[dict(rejectedType=d['command']['rejectedType'], code=d['command']['code'], actor=d['command']['context']['actor']) for d in parse_strict(store.export_audit())['diagnostics']], assessments=[assessment_record(run_id) for run_id in (RUN, FOLLOW_UP)], accounting=dict(missionSpent=final['spent'], missionReserved=final['reserved'], ledgerCost=usage['cost'], ledgerAttempts=usage['attempts']), telemetry=dict(exported=len(exported), allSent=all(r['status'] == 'SENT' for r in exported))) # Run 1 ends exactly as Annex B's illustrative result after physical implementation evidence is missing. assert record['result'] == dict(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=[dict(criterionId='issue-identified', verdict='PASS'), dict(criterionId='engineering-reviewed', verdict='PASS'), dict(criterionId='implementation-evidenced', verdict='INCONCLUSIVE'), dict(criterionId='effectiveness-accepted', verdict='INCONCLUSIVE')], disposition='Await authorized implementation evidence and assessment'), record['result'] # 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 record['followUp'] == dict(runId=FOLLOW_UP, executionState='RUNNING', verificationState='PASSED', acceptanceState='ACCEPTED', verifiedSuccessful=False, reasons=['EXECUTION_NOT_COMPLETED', 'EFFECT_UNKNOWN']), record['followUp'] # Annex B: the effectiveness assessment is made and accepted by the designated verifier. for assessment in record['assessments']: assert [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. REVIEWED_FINGERPRINT = 'sha256:dc6286da8ce3fcc52283ea5fa2cba15dea085ecc67213a4f4bf18426888154ab' assert record['approval']['fingerprint'] == REVIEWED_FINGERPRINT assert record['approval']['caseUpdate']['fingerprint'] == REVIEWED_FINGERPRINT assert record['approval']['consumedBy'] == ['example:operation:update-case'] assert record['approval']['caseUpdate']['preconditions'] == {'version': 1} # Every effect was reserved before dispatch and settled after it, with the evidence that settled it. assert [e['nodeId'] for e in record['effects']] == ['collect-records', 'request-more-records', 'request-more-records', 'draft-action', 'update-case', 'notify-case-owner'] for effect in record['effects'][:5]: assert [effect['effect'], effect['actualCost'], effect['ledger']['status'], effect['ledger']['amount'], effect['ledger']['actualCost']] == ['CONFIRMED_APPLIED', '1', 'SETTLED', '1', '1'] assert effect['ledger']['evidenceRef'].startswith('sha256:') and len(effect['ledger']['evidenceRef']) == 71 for effect in record['effects'][:4]: assert effect['order'] == ['ledger reserve', 'mission admit', 'ledger dispatch', 'mission dispatch', 'mission settle CONFIRMED_APPLIED', 'ledger settle'] assert 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 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 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 record['effects'][5] == dict(operationId='example:operation:notify-case-owner', nodeId='notify-case-owner', effect='UNKNOWN', actualCost=None, order=['ledger reserve', 'mission admit', 'ledger dispatch', 'mission dispatch', 'mission settle UNKNOWN', 'ledger unknown', 'mission recover', 'mission reconcile UNKNOWN'], ledger=dict(status='UNKNOWN', amount='1', actualCost=None, evidenceRef=None, settledBy=None)), record['effects'][5] assert record['startUps'] == [dict(recovered=[]), dict(recovered=[dict(runId=RUN, segmentId='example:run:guarding-17:segment:1', reconciled=[dict(attemptId='example:operation:update-case:attempt:1', effect='CONFIRMED_APPLIED')])]), dict(recovered=[dict(runId=FOLLOW_UP, segmentId='example:run:guarding-17:implementation:segment:1', reconciled=[dict(attemptId='example:operation:notify-case-owner:attempt:1', effect='UNKNOWN')])])], record['startUps'] package_assessment, follow_up_assessment = record['assessments'] assert record['effects'][4]['ledger']['evidenceRef'] == package_assessment['evidence'][4] # the case receipt assert record['approval']['caseUpdate']['evidence'] == package_assessment['evidence'][:3] # the record revisions it approved assert case_path.read_text(encoding='utf-8') == canonical(dict(caseId=CASE, version=2, status='CORRECTIVE_ACTION_PROPOSED', correctiveAction=package_assessment['evidence'][3], evidence=record['approval']['caseUpdate']['evidence'], history=[dict(version=2, operationId='example:operation:update-case')])) # The follow-up assessment cites the same package and adds the implementation attestation. assert follow_up_assessment['evidence'][:5] == package_assessment['evidence'] assert len(follow_up_assessment['evidence']) == 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 record['grant'] == dict(id=GRANT, grantedBy=OWNER['actor'], limit='10', canDelegate=False, depth='0', grants=[GRANT], workOrderCostLimit='100'), record['grant'] assert record['denials'] == [dict(command='grant', actor=AGENT['actor'], refused='AUTHORITY_DENIED'), dict(command='adjust', actor=AGENT['actor'], refused='AUTHORIZATION_DENIED')], record['denials'] # The mission store records the denied grant, attributed to the agent; it is the run's only refused command. assert record['rejections'] == [dict(rejectedType='grant', code='AUTHORITY_DENIED', actor=AGENT['actor'])], record['rejections'] # Five settled capability calls, and the UNKNOWN notification's reservation still held in both stores. assert record['accounting'] == dict(missionSpent='5', missionReserved='1', ledgerCost='6', ledgerAttempts='6'), record['accounting'] assert record['telemetry']['allSent'] is True # The real clock reads canonical epoch milliseconds, past the scripted contract's deadline. assert utc_clock().isdigit() and not utc_clock().startswith('0') and int(utc_clock()) > int(contract['deadline']) print(canonical(record))finally: store.close(); ledger_store.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.