Assemble a governed application
The application owns identity, user interaction, credentials, adapters and evidence assessment. The SDK owns validation and the finite-v1 state transitions it checks. Keeping those responsibilities explicit avoids accidentally giving untrusted agent code a raw ledger connection.
The execution path
Section titled “The execution path”A request enters your authenticated application. Your policy evaluates the requested command, actor, mission and current restrictions. The coordinator injects that decision, checks the expected state revision and asks SQLite to commit it. Only a successful dispatch commit permits the adapter call. The adapter reports a known outcome or uncertainty. Completion, verification and acceptance follow as separate recorded decisions.
Construct one store for one mission, supply a trusted clock and an authorizer, then pass only controlled command operations to callers. In Rust and Python the coordinator is synchronous; move blocking calls to dedicated workers in an async application. TypeScript awaits the authorizer and adapter, while its SQLite operations remain synchronous.
Run an actual local effect
Section titled “Run an actual local effect”This complete example writes a local artifact in a new temporary directory, records a graph checkpoint, completes the run and demonstrates the verification/acceptance sequence. It reads examples/review.json. The identity, clock, cost and evidence values in this fixture are explicitly demonstrations; they must be replaced for a real coding service.
Execute an adapter through the trusted coordinator · Executable local adapter demonstration; fixed demo identity and fixture evidence
import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { parseContract, parseCommand, canonical, assessSuccess } from '@aiws/sdk';import { SqliteStore } from '@aiws/sdk/sqlite';import { Coordinator, type EffectAdapter } from '@aiws/sdk/runtime';// A local demonstration. Replace this fixed demo identity with authenticated policy.const demo = JSON.parse(readFileSync('examples/review.json', 'utf8'));const directory = mkdtempSync(join(tmpdir(), 'aiws-review-'));const store = new SqliteStore(join(directory, 'mission.db'), parseContract(canonical(demo.contract)));const coordinator = new Coordinator(store, async () => ({ allowed: true, policy: 'ALLOW', mandatoryChecksOk: true,context:{actor:"demo:operator",policyRevision:"policy:1",decisionClass:"DETERMINISTIC"} }), () => '10');const adapter: EffectAdapter = { async execute(operation) { writeFileSync(join(directory, 'review.txt'), canonical(operation.action.payload), { flag: 'wx' }); return { effect: 'CONFIRMED_APPLIED', actualCost: '3' }; }, async reconcile(operation) { try { return { effect: readFileSync(join(directory, 'review.txt'), 'utf8') === canonical(operation.action.payload) ? 'CONFIRMED_APPLIED' : 'UNKNOWN', actualCost: '3' }; } catch { return { effect: 'UNKNOWN', actualCost: '0' }; } }};try { for (const raw of demo.commands) { const command = parseCommand(canonical(raw)); if (command.type === 'dispatch') await coordinator.dispatch(command.attemptId, adapter, command.nodeId); else await coordinator.apply(command); } console.log(JSON.stringify({ directory, ...assessSuccess(store.snapshot(), 'r') })); writeFileSync(join(directory, 'audit.json'), store.exportAudit());}finally { store.close();}use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use aiws_sdk::*;use serde_json::{json, Value};struct DemoIdentity;impl Authorizer for DemoIdentity { fn authorize(&mut self, _: &Command, _: &Snapshot, _: &str) -> Result<Authorization> { Ok(Authorization { allowed: true, policy: "ALLOW".into(), mandatory_checks_ok: true, context: json!({"actor":"demo:operator","policyRevision":"policy:1","decisionClass":"DETERMINISTIC"}), }) }}struct Fixed;impl Clock for Fixed { fn now_ms(&self) -> String { "10".into() }}struct LocalReview(std::path::PathBuf);impl EffectAdapter for LocalReview { fn execute(&mut self, operation: &Value, _: &Value) -> Result<Outcome> { use std::io::Write; let mut file = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&self.0) .map_err(|_| error("FILE_ERROR"))?; file.write_all(canonical(&operation["action"]["payload"])?.as_bytes()) .map_err(|_| error("FILE_ERROR"))?; file.sync_all().map_err(|_| error("FILE_ERROR"))?; Ok(Outcome { effect: "CONFIRMED_APPLIED".into(), actual_cost: "3".into(), }) } fn reconcile(&mut self, operation: &Value, _: &Value) -> Result<Outcome> { let effect = if std::fs::read_to_string(&self.0).ok() == Some(canonical(&operation["action"]["payload"])?) { "CONFIRMED_APPLIED" } else { "UNKNOWN" }; Ok(Outcome { effect: effect.into(), actual_cost: "3".into(), }) }}fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { let demo: Value = serde_json::from_str(include_str!("../../../../../examples/review.json"))?; let directory = std::env::temp_dir().join(format!( "aiws-review-{}-{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_nanos() )); std::fs::create_dir(&directory)?; let store = SqliteStore::open( directory.join("mission.db").to_str().unwrap(), Some(&Contract::from_value(demo["contract"].clone())?), )?; let mut c = Coordinator::new(store, DemoIdentity, Fixed); let mut adapter = LocalReview(directory.join("review.txt")); for raw in demo["commands"].as_array().unwrap() { let command = Command::from_value(raw.clone())?; if raw["type"] == "dispatch" { c.dispatch( raw["attemptId"].as_str().unwrap(), &mut adapter, raw["nodeId"].as_str(), )?; } else { c.apply(&command, None)?; } } println!( "{}", json!({"directory":directory,"result":assess_success(&c.store.snapshot()?,"r")?}) ); std::fs::write(directory.join("audit.json"), c.store.export_audit()?)?; Ok(())}"""Run a governed file effect with the independently implemented Python SDK."""import jsonimport tempfilefrom pathlib import Pathfrom aiws.core import canonical, assess_successfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinator
demo = json.loads(Path('examples/review.json').read_text())directory = Path(tempfile.mkdtemp(prefix='aiws-python-review-'))class Adapter: def execute(self, operation, attempt): with (directory/'review.txt').open('x') as out: out.write(canonical(operation['action']['payload'])) return {'effect':'CONFIRMED_APPLIED','actualCost':'3'} def reconcile(self, operation, attempt): try: effect='CONFIRMED_APPLIED' if (directory/'review.txt').read_text()==canonical(operation['action']['payload']) else 'UNKNOWN' except OSError: effect='UNKNOWN' return {'effect':effect,'actualCost':'3' if effect=='CONFIRMED_APPLIED' else '0'}with SqliteStore(str(directory/'mission.db'),demo['contract']) as store: # Demo identity only: replace with real authenticated and versioned policy. c=Coordinator(store,lambda *_:dict(allowed=True,policy='ALLOW',mandatoryChecksOk=True,context=dict(actor='demo:operator',policyRevision='policy:1',decisionClass='DETERMINISTIC')),lambda:'10') for command in demo['commands']: if command['type']=='dispatch': c.dispatch(command['attemptId'],Adapter(),command.get('nodeId')) else: c.apply(command) print(json.dumps({'directory':str(directory),**assess_success(store.snapshot(),'r')})) (directory/'audit.json').write_text(store.export_audit())The expected output contains a temporary directory and verifiedSuccessful: true. Inspect the artifact, mission.db and audit.json there. The directory is intentionally retained for inspection. The mock evidence string in the supplied review fixture is not a cryptographic attestation; production assessment must compute and verify actual evidence.
Turn the demonstration into a coding service
Section titled “Turn the demonstration into a coding service”- Authenticate the user outside the agent and resolve the repository and permitted branch from trusted application state.
- Store an approved plan artifact with an immutable revision and explicit test criteria. The current SDK’s plan ID records lineage; your application must enforce the human plan-approval gate.
- Resolve capabilities such as repository editing or test execution through a fixed adapter registry. An agent must not select arbitrary shell commands or credential scopes merely by filling a JSON property.
- Create an isolated working directory, record its base commit and give the adapter only authorized paths and tools.
- Capture test command, exit status, output artifact digest, tool versions and repository revision. Read those results when creating the assessment.
- Request acceptance from the configured human or authorized policy for that exact verification revision. A materially changed artifact requires reassessment.
The SDK does not execute an LLM, clone a repository, open a pull request, launch a sandbox or validate a domain claim automatically. It provides the checked command boundary around your implementations of those operations.
Success and failure paths
Section titled “Success and failure paths”Never put a generic “retry on every exception” wrapper around dispatch. A response can be lost after the external change happened. Let the coordinator preserve uncertainty, then use a human-controlled reconciliation path. If a result is known not to have applied, a checked retry can create another attempt of the same operation.
If the authorizer or ledger is unavailable, do not call the adapter through an alternate path. If recording settlement fails after the adapter returns, preserve the external receipt and reconcile after storage recovers. Re-running the whole HTTP request is not a substitute for identifying which phase committed.
Application integration is complete only when both its happy path and its interrupted path are exercised against the real adapter. Use testing recipes to build those checks.