Skip to content

Effects, operation identities and retries

An operation is one intended external change. An attempt is one authorized effort to perform it. Keeping those identities separate lets the application retry safely without pretending that a second attempt represents a different business action.

An interactive operation effect lifecycle diagram shows every effect state, UNKNOWN reconciliation and epoch fencing.

Implement execute(operation, attempt) and reconcile(operation, attempt). Execution may change the external world; reconciliation must discover external truth without repeating that change. Both return an effect disposition and decimal-string actual cost. Exceptions during execution become UNKNOWN in the coordinator. They do not prove that nothing happened.

Use a stable operation ID as the basis for an external idempotency key where the target supports it. Include material/precondition checks so that changed requests cannot reuse a key silently. A target’s idempotency retention period is an integration contract; the SDK cannot discover it for you. If no safe target deduplication or reliable readback exists, do not retry an uncertain effect.

Disposition Meaning Permitted next step
NOT_DISPATCHED No dispatch has been committed for this operation Current prepared owner may dispatch after checks
UNKNOWN Dispatch occurred or its outcome cannot be established Human-controlled reconciliation; retain reservation
CONFIRMED_NOT_APPLIED The intended effect is known not to have occurred Checked retry if authority and limits still permit
CONFIRMED_APPLIED Intended effect is known to have occurred Record dependent work; do not replay as a retry

An adapter reports an effect, never an attempt status. FAILED and SUCCEEDED are what the reducer records when it settles the attempt: CONFIRMED_NOT_APPLIED produces FAILED and opens a checked retry, so an adapter reports it only with proof that nothing changed.

Write the operation contract (STANDARD E-01) before the adapter code: the effect, its preconditions and postconditions, the target’s timeout, what each exit means, how to reconcile and when a retry is safe. Then derive the idempotency key from the operation, not the attempt, so a retry reuses it. Inject the transport so tests can replace the target. Keep reconcile read-only: it looks the key and the target revision up and never resubmits.

Write an effect adapter first: contract, idempotency key, injected transport, read-only reconcile · Executable local adapter demonstration; SDK 0.4.0 APIs; fixed demo identity and an in-memory target

import assert from 'node:assert/strict';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { canonical, parseCommand, parseContract } from '@aiws/sdk';
import { SqliteStore } from '@aiws/sdk/sqlite';
import { Coordinator, type EffectAdapter, type Outcome } from '@aiws/sdk/runtime';
/*
* Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below.
* - Effect: sets the document to `action.payload`. Idempotent under the key: the target records
* the key with the change in one transaction, applies a key at most once, and refuses a key
* whose fingerprint differs. It keeps a key record for 24 hours.
* - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload
* is stored and the revision has advanced. Every change advances the revision.
* - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the
* request before changing anything, at no cost. Any other exit, a timeout or a transport error
* proves nothing: the outcome is UNKNOWN.
* - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the
* change; an absent key with the revision unchanged proves nothing changed. Anything else
* stays UNKNOWN for a human.
* - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target
* absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window.
*/
type Submission = { exitCode: number } | { timedOut: true };
/** Own-property check on the transport's plain reply object, never `in`. */
const timedOut = (reply: Submission): reply is { timedOut: true } => Object.hasOwn(reply, 'timedOut');
interface Lookup { keyRecorded: boolean; revision: number }
interface WriteRequest { key: string; fingerprint: string; resource: string; payload: unknown; expectedRevision: number; timeoutMs: number }
/** Injected by the host: the real client in production, a fake target in tests. */
interface Transport {
submit(request: WriteRequest): Promise<Submission>;
/** Read-only: never changes the target. */
lookup(key: string, resource: string): Promise<Lookup>;
}
/** Mission, operation and action fingerprint: stable across attempts, different for a changed action. */
const idempotencyKey = (missionId: string, operation: Readonly<Record<string, any>>): string =>
`${missionId}/${operation.id}/${operation.fingerprint}`;
const applied: Outcome = { effect: 'CONFIRMED_APPLIED', actualCost: '3' };
const notApplied: Outcome = { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' };
const unknown: Outcome = { effect: 'UNKNOWN', actualCost: '0' };
class KeyedWriteAdapter implements EffectAdapter {
private missionId: string;
private transport: Transport;
constructor(missionId: string, transport: Transport) { this.missionId = missionId; this.transport = transport; }
async execute(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> {
const { resource, payload, preconditions } = operation.action;
let reply: Submission;
try {
reply = await this.transport.submit({ key: idempotencyKey(this.missionId, operation), fingerprint: operation.fingerprint, resource, payload, expectedRevision: preconditions.revision, timeoutMs: 30_000 });
} catch {
return unknown; // A thrown transport error does not show whether the target applied the write.
}
if (timedOut(reply)) return unknown; // A timeout never proves the action did not happen.
if (reply.exitCode === 0) return applied;
if (reply.exitCode === 3) return notApplied; // The contract: exit 3 is a refusal before any change.
return unknown; // Other nonzero exits carry no proof that nothing changed.
}
async reconcile(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> {
let found: Lookup;
try {
found = await this.transport.lookup(idempotencyKey(this.missionId, operation), operation.action.resource);
} catch {
return unknown;
}
if (found.keyRecorded) return applied;
if (found.revision === operation.action.preconditions.revision) return notApplied;
return unknown; // The target moved without our key: an expired key record or another writer.
}
}
// ---- A local target that applies a write and then loses the response. ----
class LossyTarget implements Transport {
revision = 1;
document: unknown = null;
keys = new Map<string, string>();
async submit(request: WriteRequest): Promise<Submission> {
const recorded = this.keys.get(request.key);
if (recorded !== undefined) return { exitCode: recorded === request.fingerprint ? 0 : 3 };
if (request.expectedRevision !== this.revision) return { exitCode: 3 };
this.document = request.payload;
this.revision++;
this.keys.set(request.key, request.fingerprint);
return { timedOut: true }; // Applied, but the response never arrived.
}
async lookup(key: string): Promise<Lookup> {
return { keyRecorded: this.keys.has(key), revision: this.revision };
}
}
// Demo identity only: replace with authenticated, versioned policy and a human for settle.
const contract = parseContract(canonical({ id: 'c', missionId: 'm', aiwsEdition: '0.4', profile: 'finite-v1', budget: '100', deadline: '10000', criteria: ['review'], actions: ['write'], resources: ['doc'], requiresApproval: false, maxAttempts: '2', maxAuthorizationAgeMs: '10', features: [] }));
const directory = mkdtempSync(join(tmpdir(), 'aiws-effect-adapter-'));
const store = new SqliteStore(join(directory, 'mission.db'), contract);
const coordinator = new Coordinator(store, async (command) => ({ allowed: true, policy: 'ALLOW', mandatoryChecksOk: true, context: { actor: command.type === 'settle' ? 'demo:reviewer' : 'demo:operator', policyRevision: 'policy:1', decisionClass: command.type === 'settle' ? 'HUMAN' : 'DETERMINISTIC' } }), () => '10');
const target = new LossyTarget();
const adapter = new KeyedWriteAdapter(contract.missionId, target);
try {
await coordinator.apply(parseCommand(canonical({ type: 'startRun', runId: 'r' })));
await coordinator.apply(parseCommand(canonical({ type: 'grant', grant: { id: 'g', subject: 'agent', profile: 'finite-v1', actions: ['write'], resources: ['doc'], notBefore: '0', expiresAt: '10000', limit: '100', canDelegate: false, depth: '0' } })));
await coordinator.apply(parseCommand(canonical({ type: 'admit', runId: 'r', operationId: 'o', attemptId: 'a', grantId: 'g', subject: 'agent', action: { capability: 'write', resource: 'doc', payload: { value: 1 }, preconditions: { revision: 1 } }, amount: '10', authorizationCheckedAt: '10', policy: 'ALLOW', mandatoryChecksOk: true })));
let state = await coordinator.dispatch('a', adapter);
assert.equal(state.attempts.a.status, 'UNKNOWN'); // The write applied, but a timeout proves nothing.
assert.equal(state.reserved, '10'); // UNKNOWN keeps the reservation.
state = await coordinator.reconcile('a', adapter); // Read-only: looks the key up, never resubmits.
assert.equal(state.attempts.a.status, 'SUCCEEDED');
assert.equal(state.operations.o.effect, 'CONFIRMED_APPLIED');
assert.equal(state.spent, '3');
assert.equal(state.reserved, '0');
assert.equal(target.revision, 2); // Applied exactly once.
assert.deepEqual(target.document, { value: 1 });
assert.deepEqual([...target.keys.keys()], [idempotencyKey('m', state.operations.o)]);
console.log('PASS: effect-adapter');
} finally {
store.close();
}

The program dispatches through the coordinator to a local target that applies the write and then loses the response. The adapter reports UNKNOWN, the attempt keeps its reservation, and a read-only reconcile finds the key and settles CONFIRMED_APPLIED, with the write applied once. It uses only SDK 0.5.1 APIs. The demo identity, the in-memory target and its exit codes stand in for an authenticated host and a real target’s documented contract.

Each outcome rule gets its own case, driven through the adapter’s execute and reconcile with a scripted transport:

Case Outcome
Success: exit 0 CONFIRMED_APPLIED
Proven non-application: an exit the contract defines as a refusal before any change CONFIRMED_NOT_APPLIED
Timeout UNKNOWN
Thrown transport error UNKNOWN
Nonzero exit the contract does not cover UNKNOWN
Reconcile finds the key CONFIRMED_APPLIED
Reconcile shows the target unchanged after a nonzero exit CONFIRMED_NOT_APPLIED
Reconcile cannot decide: the target moved without the key, or the read-back failed UNKNOWN

A timeout, a signal, a null exit code or a thrown error never proves the action did not happen. A nonzero exit reports CONFIRMED_NOT_APPLIED only with evidence that nothing changed: the operation contract saying so for that exit, or a read-only reconcile showing the target unchanged. Without either, it is UNKNOWN. These are the SDK forms of NG-01 and NG-02 from the governance rule set. The tests also check that reconcile never calls the mutating transport and that no outcome is FAILED or SUCCEEDED.

Test outcome classification: success, non-application, timeout, transport error, nonzero exit, reconcile · Executable adapter test program; SDK 0.4.0 APIs; scripted transports, no external calls

import assert from 'node:assert/strict';
import type { EffectAdapter, Outcome } from '@aiws/sdk/runtime';
/*
* Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below.
* - Effect: sets the document to `action.payload`. Idempotent under the key: the target records
* the key with the change in one transaction, applies a key at most once, and refuses a key
* whose fingerprint differs. It keeps a key record for 24 hours.
* - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload
* is stored and the revision has advanced. Every change advances the revision.
* - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the
* request before changing anything, at no cost. Any other exit, a timeout or a transport error
* proves nothing: the outcome is UNKNOWN.
* - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the
* change; an absent key with the revision unchanged proves nothing changed. Anything else
* stays UNKNOWN for a human.
* - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target
* absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window.
*/
type Submission = { exitCode: number } | { timedOut: true };
/** Own-property check on the transport's plain reply object, never `in`. */
const timedOut = (reply: Submission): reply is { timedOut: true } => Object.hasOwn(reply, 'timedOut');
interface Lookup { keyRecorded: boolean; revision: number }
interface WriteRequest { key: string; fingerprint: string; resource: string; payload: unknown; expectedRevision: number; timeoutMs: number }
/** Injected by the host: the real client in production, a fake target in tests. */
interface Transport {
submit(request: WriteRequest): Promise<Submission>;
/** Read-only: never changes the target. */
lookup(key: string, resource: string): Promise<Lookup>;
}
/** Mission, operation and action fingerprint: stable across attempts, different for a changed action. */
const idempotencyKey = (missionId: string, operation: Readonly<Record<string, any>>): string =>
`${missionId}/${operation.id}/${operation.fingerprint}`;
const applied: Outcome = { effect: 'CONFIRMED_APPLIED', actualCost: '3' };
const notApplied: Outcome = { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' };
const unknown: Outcome = { effect: 'UNKNOWN', actualCost: '0' };
class KeyedWriteAdapter implements EffectAdapter {
private missionId: string;
private transport: Transport;
constructor(missionId: string, transport: Transport) { this.missionId = missionId; this.transport = transport; }
async execute(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> {
const { resource, payload, preconditions } = operation.action;
let reply: Submission;
try {
reply = await this.transport.submit({ key: idempotencyKey(this.missionId, operation), fingerprint: operation.fingerprint, resource, payload, expectedRevision: preconditions.revision, timeoutMs: 30_000 });
} catch {
return unknown; // A thrown transport error does not show whether the target applied the write.
}
if (timedOut(reply)) return unknown; // A timeout never proves the action did not happen.
if (reply.exitCode === 0) return applied;
if (reply.exitCode === 3) return notApplied; // The contract: exit 3 is a refusal before any change.
return unknown; // Other nonzero exits carry no proof that nothing changed.
}
async reconcile(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> {
let found: Lookup;
try {
found = await this.transport.lookup(idempotencyKey(this.missionId, operation), operation.action.resource);
} catch {
return unknown;
}
if (found.keyRecorded) return applied;
if (found.revision === operation.action.preconditions.revision) return notApplied;
return unknown; // The target moved without our key: an expired key record or another writer.
}
}
// ---- Outcome-classification tests: one scripted transport per case. ----
interface Script { submit?: Submission | Error; lookup?: Lookup | Error }
class ScriptedTarget implements Transport {
submits = 0;
private script: Script;
constructor(script: Script) { this.script = script; }
async submit(): Promise<Submission> {
this.submits++;
const reply = this.script.submit;
if (reply === undefined) throw Error('submit was not scripted');
if (reply instanceof Error) throw reply;
return reply;
}
async lookup(): Promise<Lookup> {
const reply = this.script.lookup;
if (reply === undefined) throw Error('lookup was not scripted');
if (reply instanceof Error) throw reply;
return reply;
}
}
const operation = { id: 'o', fingerprint: 'sha256:example', action: { capability: 'write', resource: 'doc', payload: { value: 1 }, preconditions: { revision: 1 } } };
const attempt = { id: 'a', operationId: 'o' };
const key = idempotencyKey('m', operation);
const executeCases: [string, Script, Outcome][] = [
['success: exit 0', { submit: { exitCode: 0 } }, { effect: 'CONFIRMED_APPLIED', actualCost: '3' }],
['proven non-application: exit 3 is contracted as refused before any change', { submit: { exitCode: 3 } }, { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' }],
['timeout', { submit: { timedOut: true } }, { effect: 'UNKNOWN', actualCost: '0' }],
['thrown transport error', { submit: Error('connection reset') }, { effect: 'UNKNOWN', actualCost: '0' }],
['nonzero exit the contract does not cover', { submit: { exitCode: 1 } }, { effect: 'UNKNOWN', actualCost: '0' }],
];
const reconcileCases: [string, Script, Outcome][] = [
['reconcile finds the effect', { lookup: { keyRecorded: true, revision: 2 } }, { effect: 'CONFIRMED_APPLIED', actualCost: '3' }],
['reconcile proves nothing changed after a nonzero exit', { lookup: { keyRecorded: false, revision: 1 } }, { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' }],
['reconcile cannot decide: the target moved and the key is not recorded', { lookup: { keyRecorded: false, revision: 2 } }, { effect: 'UNKNOWN', actualCost: '0' }],
['reconcile cannot decide: the read-back failed', { lookup: Error('target unavailable') }, { effect: 'UNKNOWN', actualCost: '0' }],
];
const seen = new Set<string>();
for (const [name, script, expected] of executeCases) {
const target = new ScriptedTarget(script);
const outcome = await new KeyedWriteAdapter('m', target).execute(operation, attempt);
assert.deepEqual(outcome, expected, name);
assert.equal(target.submits, 1, name + ': one submission per attempt');
seen.add(outcome.effect);
}
for (const [name, script, expected] of reconcileCases) {
const target = new ScriptedTarget(script);
const outcome = await new KeyedWriteAdapter('m', target).reconcile(operation, attempt);
assert.deepEqual(outcome, expected, name);
assert.equal(target.submits, 0, name + ': reconcile is read-only');
seen.add(outcome.effect);
}
// No adapter outcome is an attempt status: FAILED and SUCCEEDED are the reducer's to record.
assert.deepEqual([...seen].sort(), ['CONFIRMED_APPLIED', 'CONFIRMED_NOT_APPLIED', 'UNKNOWN']);
assert.equal(key, 'm/o/sha256:example');
console.log('PASS: effect-outcomes');

Retry confirmed nonapplication and handle duplicate results · Executable control simulation

import assert from 'node:assert/strict';
import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.
const contract = parseContract(JSON.stringify({
"id": "c",
"missionId": "m",
"aiwsEdition": "0.4",
"profile": "finite-v1",
"budget": "100",
"deadline": "10000",
"criteria": [
"review"
],
"actions": [
"write"
],
"resources": [
"doc"
],
"requiresApproval": false,
"maxAttempts": "2",
"maxAuthorizationAgeMs": "10",
"features": [
"triggers",
"graphs"
]
}));
let state = createMission(contract);
// Step 1
state = reduce(state, parseCommand(JSON.stringify({
"type": "startRun",
"runId": "r"
})), '10');
// Step 2
state = reduce(state, parseCommand(JSON.stringify({
"type": "grant",
"grant": {
"id": "g",
"subject": "agent",
"profile": "finite-v1",
"actions": [
"write"
],
"resources": [
"doc"
],
"notBefore": "0",
"expiresAt": "10000",
"limit": "100",
"canDelegate": true,
"depth": "2"
}
})), '10');
// Step 3
state = reduce(state, parseCommand(JSON.stringify({
"type": "admit",
"runId": "r",
"operationId": "o",
"attemptId": "a",
"grantId": "g",
"subject": "agent",
"action": {
"capability": "write",
"resource": "doc",
"payload": {
"value": 1
},
"preconditions": {
"revision": 1
}
},
"amount": "10",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 4
state = reduce(state, parseCommand(JSON.stringify({
"type": "dispatch",
"attemptId": "a",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 5
state = reduce(state, parseCommand(JSON.stringify({
"type": "settle",
"attemptId": "a",
"effect": "CONFIRMED_NOT_APPLIED",
"actualCost": "0"
})), '10');
// Step 6
state = reduce(state, parseCommand(JSON.stringify({
"type": "retry",
"operationId": "o",
"attemptId": "a2",
"amount": "10",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 7
state = reduce(state, parseCommand(JSON.stringify({
"type": "dispatch",
"attemptId": "a2",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 8
state = reduce(state, parseCommand(JSON.stringify({
"type": "settle",
"attemptId": "a",
"effect": "CONFIRMED_NOT_APPLIED",
"actualCost": "0"
})), '10');
// Step 9
state = reduce(state, parseCommand(JSON.stringify({
"type": "settle",
"attemptId": "a2",
"effect": "CONFIRMED_APPLIED",
"actualCost": "2"
})), '10');
assert.deepEqual(state["spent"], "2");
assert.deepEqual(state["reserved"], "0");
console.log('PASS: retry');

The example also checks a late duplicate settlement. An identical result is accepted without charging again, while inconsistent results are rejected. Accepted duplicates still produce a new control event; semantic idempotence does not mean the event count stays unchanged.

The retry must reuse the operation identity but have a fresh attempt identity. maxAttempts includes the initial attempt. Every attempt reserves exposure; prior recorded costs remain spent. Retrying never renews an expired grant, approval or contract deadline.

Keep the task under human review when the external outcome is uncertain. Read target-side receipts, repository state or provider request status using the original identity. If evidence proves the action applied, settle that attempt with its actual cost. If evidence proves nonapplication, settle accordingly before requesting a retry. If evidence remains ambiguous, keep UNKNOWN. Human intervention must record evidence and a decision; it must not fabricate certainty.

A compensating action is a new governed operation with its own cost, permission and outcome. It references an earlier applied operation but does not delete history or claim that the original action never happened. Some changes are not reversible. Verify the resulting state of the target rather than assuming successful compensation restored every property.

Record reconciliation and a separate compensating effect · Executable control simulation

import assert from 'node:assert/strict';
import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.
const contract = parseContract(JSON.stringify({
"id": "c",
"missionId": "m",
"aiwsEdition": "0.4",
"profile": "finite-v1",
"budget": "100",
"deadline": "10000",
"criteria": [
"review"
],
"actions": [
"write"
],
"resources": [
"doc"
],
"requiresApproval": false,
"maxAttempts": "2",
"maxAuthorizationAgeMs": "10",
"features": [
"triggers",
"graphs"
]
}));
let state = createMission(contract);
// Step 1
state = reduce(state, parseCommand(JSON.stringify({
"type": "startRun",
"runId": "r"
})), '10');
// Step 2
state = reduce(state, parseCommand(JSON.stringify({
"type": "registerGraph",
"graph": {
"id": "graph",
"revision": "1",
"nodes": [
{
"id": "task",
"kind": "TASK",
"dependsOn": [],
"config": {
"executionKind": "FUNCTION"
}
},
{
"id": "reconcile",
"kind": "RECONCILIATION",
"dependsOn": [
"task"
],
"config": {}
},
{
"id": "undo",
"kind": "COMPENSATION",
"dependsOn": [
"reconcile"
],
"config": {}
},
{
"id": "end",
"kind": "END",
"dependsOn": [
"undo"
],
"config": {}
}
]
}
})), '10');
// Step 3
state = reduce(state, parseCommand(JSON.stringify({
"type": "attachGraph",
"runId": "r",
"graphId": "graph"
})), '10');
// Step 4
state = reduce(state, parseCommand(JSON.stringify({
"type": "grant",
"grant": {
"id": "g",
"subject": "agent",
"profile": "finite-v1",
"actions": [
"write"
],
"resources": [
"doc"
],
"notBefore": "0",
"expiresAt": "10000",
"limit": "100",
"canDelegate": true,
"depth": "2"
}
})), '10');
// Step 5
state = reduce(state, parseCommand(JSON.stringify({
"type": "admit",
"runId": "r",
"operationId": "o",
"attemptId": "a",
"grantId": "g",
"subject": "agent",
"action": {
"capability": "write",
"resource": "doc",
"payload": {
"value": 1
},
"preconditions": {
"revision": 1
}
},
"amount": "10",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 6
state = reduce(state, parseCommand(JSON.stringify({
"type": "dispatch",
"attemptId": "a",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true,
"nodeId": "task"
})), '10');
// Step 7
state = reduce(state, parseCommand(JSON.stringify({
"type": "settle",
"attemptId": "a",
"effect": "CONFIRMED_APPLIED",
"actualCost": "3"
})), '10');
// Step 8
state = reduce(state, parseCommand(JSON.stringify({
"type": "completeNode",
"runId": "r",
"nodeId": "task",
"result": {
"operationId": "o"
}
})), '10');
// Step 9
state = reduce(state, parseCommand(JSON.stringify({
"type": "completeNode",
"runId": "r",
"nodeId": "reconcile",
"result": {
"operationId": "o"
}
})), '10');
// Step 10
state = reduce(state, parseCommand(JSON.stringify({
"type": "admit",
"runId": "r",
"operationId": "undo",
"attemptId": "au",
"grantId": "g",
"subject": "agent",
"action": {
"capability": "write",
"resource": "doc",
"payload": {
"value": 1
},
"preconditions": {
"revision": 1
}
},
"amount": "10",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true
})), '10');
// Step 11
state = reduce(state, parseCommand(JSON.stringify({
"type": "dispatch",
"attemptId": "au",
"authorizationCheckedAt": "10",
"policy": "ALLOW",
"mandatoryChecksOk": true,
"nodeId": "undo"
})), '10');
// Step 12
state = reduce(state, parseCommand(JSON.stringify({
"type": "settle",
"attemptId": "au",
"effect": "CONFIRMED_APPLIED",
"actualCost": "2"
})), '10');
// Step 13
state = reduce(state, parseCommand(JSON.stringify({
"type": "completeNode",
"runId": "r",
"nodeId": "undo",
"result": {
"operationId": "undo",
"originalOperationId": "o"
}
})), '10');
console.log('PASS: compensation');

The example exercises current checkpoint semantics. It is not an automatic rollback manager. Your application chooses and authorizes a compensating adapter and must handle uncertainty or failure in that operation too.