> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Governed Execution and Replay

> Execute a typed command under operator-owned identity and policy, then verify same-key replay across a process restart.

The native kernel wraps selected domain mutations in a command, policy decision, and durable
receipt. It is separate from direct accessors: `commerce.orders.createExact()` does not
become governed merely because an agent called it.

## Keep authority outside model arguments

A command carries identity/delegation, tenant/store, command type, stable retry key, mode,
payload, and optional versions, deadline, approval and exact commitment. Policy is deny by
default. Required approval binds the intended scope/key; signed authority binds semantic
intent. A host must authenticate identity and load policy from operator-owned configuration.

`EconomicAgent` and `EconomicAuthority` support explicit delegated actors, autonomous and
approval ceilings, and deny ranges. Economic intents provide a framework-neutral vocabulary;
their existence does not implement every business verb as one atomic workflow. Economic
receipt signatures need an independently trusted key map; embedded keys do not establish trust.

## Run a local receipt example

Install `@stateset/embedded@1.39.0` in a fresh directory. The policy below is an application-owned
fixture allowing one reservation command in one test store. Do not accept this policy or its
principal from an agent's tool arguments. Save as `governed-reservation.mjs`:

```javascript theme={null}
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { writeFileSync } from 'node:fs';
import { Commerce } from '@stateset/embedded';

const commerce = await Commerce.open('./governed.db');
try {
  await commerce.inventory.createItem({ sku: 'GOV-MUG', name: 'Test mug', initialQuantity: 10 });
  const policy = {
    version: 'docs-v1',
    commands: {
      'inventory.reserve': {
        required_capabilities: ['inventory.reserve'],
        requires_approval: false,
        requires_tenant: true,
        requires_store: true,
        allowed_tenant_ids: ['tenant:docs'],
        allowed_store_ids: ['store:docs'],
        requires_agent_delegation: true,
        requires_signed_authority: false,
      },
    },
    trusted_authority_keys: {},
  };
  const command = {
    contract_version: '1.0',
    command_id: randomUUID(),
    idempotency_key: `docs-reservation-${randomUUID()}`,
    command_type: 'inventory.reserve',
    principal: {
      id: 'agent:docs', kind: 'agent', tenant_id: 'tenant:docs',
      delegated_by: 'operator:docs', capabilities: ['inventory.reserve'],
    },
    store_id: 'store:docs', policy_version: policy.version,
    mode: 'preview', issued_at: new Date().toISOString(),
    payload: {
      sku: 'GOV-MUG', quantity: '2', reference_type: 'checkout', reference_id: 'docs-cart',
    },
  };
  const preview = await commerce.executeKernelCommand(command, policy);
  assert.equal(preview.status, 'previewed');
  assert.equal((await commerce.inventory.getStock('GOV-MUG')).totalAllocated, '0');
  command.mode = 'apply';
  writeFileSync('reservation-request.json', JSON.stringify({ command, policy }));
  const receipt = await commerce.executeKernelCommand(command, policy);
  assert.equal(receipt.status, 'succeeded');
  assert.equal((await commerce.inventory.getStock('GOV-MUG')).totalAllocated, '2');
  writeFileSync('reservation-receipt.json', JSON.stringify(receipt));
  console.log('Preview changed no stock; apply reserved exactly two units.');
} finally {
  await commerce.close();
}
```

## Replay from another process

Retain the exact request before dispatch. Save as `replay-reservation.mjs` and run after the
first process exits. This test repeats the original command, not a new business action.

```javascript theme={null}
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { Commerce } from '@stateset/embedded';

const { command, policy } = JSON.parse(readFileSync('reservation-request.json', 'utf8'));
const original = JSON.parse(readFileSync('reservation-receipt.json', 'utf8'));
const commerce = await Commerce.open('./governed.db');
try {
  const replay = await commerce.executeKernelCommand(command, policy);
  assert.equal(replay.status, 'succeeded');
  assert.equal(replay.receipt_id, original.receipt_id);
  assert.deepEqual(replay.result, original.result);
  assert.equal((await commerce.inventory.getStock('GOV-MUG')).totalAllocated, '2');
  console.log('Restart replay returned the original receipt with no second reservation.');
} finally {
  await commerce.close();
}
```

```bash theme={null}
node governed-reservation.mjs
node replay-reservation.mjs
```

The governed mutation, its receipt, and receipt-audit chain commit together. Inspect receipt
status, error/retry disposition, versions and event IDs. A preview, rejection, succeeded local
mutation, and external completion establish different facts. Preserve original identity after
response loss; new keys can create new effects. This fixture does not test host power loss.

## Strict MCP configuration

For an autonomous endpoint load `--kernel-policy`, `--kernel-principal`, and
`--kernel-store-id` from protected operator files before enabling `--apply`. The matching
`STATESET_KERNEL_POLICY`, `STATESET_KERNEL_PRINCIPAL`, and `STATESET_KERNEL_STORE_ID`
environment settings are available. Strict discovery exposes typed governed writes and
available reads; a domain profile does not grant capabilities or make an unsupported write
governed. Inspect the actual catalog and policy.

See [MCP](/stateset-icommerce/stateset-icommerce-mcp.md),
[CLI safety](/stateset-icommerce/stateset-icommerce-cli-safety.md), and
[recovery](/stateset-icommerce/stateset-icommerce-backup-restore.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.