# Writ Documentation — llms-full.txt
> Writ — bounded autonomy for agents that spend money. A self-hosted .NET
> runtime that runs an agent mission under a cryptographic writ (budget,
> scope, deadline, delegation rules), paying over Lightning (L402) and
> producing a signed, independently verifiable work record. Writ does not
> hold funds — the operator's own wallet makes payments directly.
PRIVATE PREVIEW: Writ is in private preview. To request access, write to
support@lightningenable.com. This corpus
describes the preview behavior, captured directly from the running CLI where
possible.
This file is the full documentation corpus of https://writ.lightningenable.com,
generated from the Markdown sources by docs-site/scripts/generate-llms-full.mjs
(do not edit by hand — regenerate with `npm run generate-llms-full` from docs-site/).
For a short curated index instead, see https://writ.lightningenable.com/llms.txt.
For a structured, machine-readable command manifest, see https://writ.lightningenable.com/.well-known/writ-agent.json.
==============================================================================
# For agents
Source: https://writ.lightningenable.com/docs/for-agents
==============================================================================
# For agents
:::note
Writ is in private preview. To request access, write to [support@lightningenable.com](mailto:support@lightningenable.com?subject=Writ%20private%20preview). See [Get access](/docs/getting-started/installation). This site serves the Claude Skills and the mission schema.
:::
Writ was built for agents to eventually run autonomously — it follows that setting Writ up and operating it should also work with an agent doing the driving, not just a human typing commands. This page is the index for that: what a coding agent (or an autonomous one) should read, in what order, and where the guardrails are.
## Start here: the machine-readable index
- **[`/llms.txt`](pathname:///llms.txt)** — a concise, curated index of every documentation page, with a one-line description and an absolute URL for each, following the [llms.txt convention](https://llmstxt.org). Read this first to decide what else to fetch.
- **[`/llms-full.txt`](pathname:///llms-full.txt)** — the entire documentation corpus concatenated into one plain-text file, generated from the same source these pages render from on every build. Fetch this when you want the whole thing in one shot instead of paging through individual URLs.
- **[`/.well-known/writ-agent.json`](pathname:///.well-known/writ-agent.json)** — a structured JSON manifest: every `writ` command with its arguments, options, and exit codes; the setup checks; the mission manifest schema URL; the list of Claude Skills below; and the verification procedure. This is the file to parse programmatically instead of scraping prose. Its command list is checked against the CLI's own `--help` output on every build of this site.
## Claude Skills
Three [Claude Skills](https://support.claude.com/en/articles/12512180-use-skills-in-claude) are published on this site under [`/skills/`](pathname:///skills/README.md), in the same `SKILL.md` format used by [lightning-enable-skills](https://github.com/refined-element/lightning-enable-skills) (and, per the [agentskills.io](https://agentskills.io) standard those follow, loadable unmodified by Claude Code, Claude Desktop, Cursor, and other compatible hosts):
| Skill | What it does |
|---|---|
| [`writ-setup`](pathname:///skills/writ-setup/SKILL.md) | Confirm the `writ` tool is installed, create a persistent operator identity with `writ keys init`, and confirm the setup with a smoke run. |
| [`writ-run`](pathname:///skills/writ-run/SKILL.md) | Author a mission manifest from a task description, validate it, plan it with `--dry-run`, run it in `simulated` settlement, read the result, and export a shareable bundle. |
| [`writ-verify`](pathname:///skills/writ-verify/SKILL.md) | Verify a work-record bundle received from a counterparty against a pinned public key or head attestation, and interpret every warning `writ verify` can print. |
Every skill carries the same hard guardrails, stated up front in its `SKILL.md`:
- **Never enable wallet settlement or `--production` without explicit, current-turn human confirmation.** These are the two things that make a run capable of spending real money or refusing to run without a durable key — an agent proposes; a human decides.
- **Never print a private key, `WRIT_RECEIPT_KEY` value, or macaroon** — surface only what `writ keys show` and `writ verify` already redact to.
- **Stop and hand back to the human on exit code `4`** (approval required) **or `7`** (pending reconciliation) — these are the two outcomes where an agent proceeding on its own is precisely the failure mode Writ's approval gate and reconciliation hold exist to prevent.
## The mission schema, for generation
If you're generating a mission manifest programmatically, validate it against [`/schema/mission.schema.json`](pathname:///schema/mission.schema.json) (JSON Schema draft 2020-12) before handing it to `writ validate` — catching a schema violation locally is faster than round-tripping through the CLI. The [manifest reference](/docs/reference/manifest) documents every field the schema declares, with real examples.
## JSON-LD
Every page on this site carries `SoftwareApplication`, `HowTo`, and `FAQPage` [schema.org](https://schema.org) structured data in its `
`, injected via Docusaurus's `headTags` config. A crawler or agent that reads structured data rather than prose can get the setup steps and the top FAQ answers from that alone.
## The shape of an autonomous session
A reasonable order of operations for an agent setting up and running Writ with minimal human intervention:
1. Fetch `/llms.txt`, then `/.well-known/writ-agent.json`, to build a picture of the tool without a human narrating it.
2. Follow `writ-setup`: confirm the `writ` tool is installed, create an operator identity, confirm with a smoke run.
3. Follow `writ-run` to author and run a **`simulated`**-settlement mission — no wallet, no real money, no approval risk.
4. Read the run's `run.json` and `work-record.jsonl`; on success, export a bundle with `writ record export --out`.
5. If a counterparty hands you a bundle instead, follow `writ-verify` to check it against a pinned key.
6. At any point the mission proposes `settlement.mode: wallet` or `--production`, or a run halts at exit `4`/`7`: **stop, explain the situation, and ask a human.**
## Driving the engine with no human in the loop
When your agent host calls the engine directly through `writ-mcp` or `writ-api` instead of running a mission, it has to make its own decisions without a person reading prose. The [service, MCP, and HTTP reference](/docs/reference/agent-api) is written for that case:
- **Spend under the writ you were given.** A service host serves you the agent role: you run calls, narrow your writ for sub-agents, revoke the writs you delegated (`writ_revoke_delegated`, presenting the parent writ), and read. To read your own receipts and held spends in a workspace other than the host's, pass your writ as `credential` with the `workspace`. Issuing, approving, denying, revoking by id and reconciling are the operator's, and a call to one of those tools returns `operator_only` with the command your operator runs. `writ_status` says your `role` and, if you have no writ yet, how the operator issues one. When a call returns `approval_required`, tell your operator which request is waiting and retry the same call (same idempotency key) after they decide.
- **Ask what remains before you spend.** `writ_budget` (or `POST /v1/credentials/budget`) returns `remainingSats`, `perCallMaxSats`, and `maxNextCallSats`, each the tightest value across the whole delegation chain, plus the link that binds. Stop cleanly when `maxNextCallSats` is below the price of the next call, instead of learning it from a refusal.
- **Branch on `reasonCode`, not on prose.** Every refused invoke carries a stable `reasonCode` (for example `budget_exhausted`, `price_exceeds_ceiling`, `credential_revoked`, `approval_required`) and a `retry` disposition. On `final`, stop or ask the operator. On `retry_with_change`, try something different: another capability or provider, or a cheaper call. On `retry_later`, retry the same call after a human approves or a transient fault clears. Never retry `payment_outcome_unknown` or `paid_execution_failed`: money may have moved. The full table is in [Refusal reason codes](/docs/reference/agent-api#refusal-reason-codes).
- **Retry with the same idempotency key.** Generate a key per unit of work and pass it on the call and on every retry of it (`idempotencyKey` in `writ_invoke`, the `Idempotency-Key` header over HTTP). A retry after a timeout or a lost response then never pays twice: a finished call replays its original outcome and receipt id, and one still in flight answers `in_progress`. See [Idempotent retries](/docs/reference/agent-api#idempotent-retries).
## Human-facing documentation, for context
Everything the skills reference is written out in full elsewhere on this site:
- [Manifest reference](/docs/reference/manifest)
- [Command reference](/docs/reference/commands)
- [Service, MCP, and HTTP reference](/docs/reference/agent-api)
- [Keys and verification](/docs/guides/keys-and-verification)
- [Approvals and budgets](/docs/guides/approvals-and-budgets)
- [Settlement](/docs/guides/settlement)
- [Security model and preview limitations](/docs/security-and-limitations)
- [Troubleshooting](/docs/troubleshooting)
==============================================================================
# Your first mission
Source: https://writ.lightningenable.com/docs/getting-started/first-mission
==============================================================================
# Your first mission
This walkthrough runs a real mission end to end in `simulated` settlement mode. No wallet, no API key, no model, no real money. Each step shows the command to run, then the output you should see.
**Before you start:** finish [Get access](/docs/getting-started/installation), so that `writ` works in your shell. Then make an empty directory, save the manifest below in it as `mission.yaml`, and run every command on this page from that directory. The walkthrough uses this vendor due-diligence mission because it needs nothing configured; scaffolding your own mission with `writ init` comes at the end. In a source checkout, the same mission is `examples/vendor-dossier/mission.yaml`.
```yaml title="mission.yaml"
mission:
name: vendor-dossier
goal: >
Produce a vendor due-diligence dossier on {{target_name}} ({{target_domain}}) from paid data
sources: domain registration/DNS posture and regulatory/compliance footprint.
vars:
- target_domain
- target_name
budget:
total_sats: 200 # cumulative cap, enforced atomically at the credential-chain root
per_call_max_sats: 25 # ceiling for any single capability call
settlement:
mode: simulated # simulated (no real money) | wallet (real Lightning)
approvals: {} # empty = fully autonomous within the bounds above
capabilities:
- id: dns.whois
kind: l402-http
base_url: https://api.lightningenable.com/l402/proxy/dns-and-whois-afae
path: /whois
method: GET
max_sats_per_call: 5
- id: compliance.search
kind: l402-http
base_url: https://api.lightningenable.com/l402/proxy/compliance-suite-e352
path: /search
method: GET
max_sats_per_call: 12
- id: compose.dossier
kind: internal # deterministic assembly of the paid outputs, no model
workers:
- name: infra-researcher
scope: [dns.whois]
budget_sats: 40
expires_minutes: 30
steps:
- type: call
capability: dns.whois
input:
domain: "{{target_domain}}"
output: infra.json
- name: compliance-researcher
scope: [compliance.search]
budget_sats: 60
expires_minutes: 30
steps:
- type: call
capability: compliance.search
input:
q: "{{target_name}}"
output: compliance.json
- name: writer
scope: [compose.dossier]
budget_sats: 0 # internal-only worker: no external spend authority
expires_minutes: 20
steps:
- type: call
capability: compose.dossier
input:
instruction: |
# Vendor Due-Diligence Dossier — {{target_name}} ({{target_domain}})
Compiled autonomously by Writ from paid data sources. Each section below is the
response of a capability the mission paid for over L402 under a scoped, delegated credential.
include_prior_outputs: true
output: dossier.md
work_record:
signing: dev-ephemeral
output_dir: runs/
```
In `simulated` mode, Writ never contacts the `api.lightningenable.com` URLs: each paid call is answered in-process with fixed sample data.
:::tip Reading this page
Command blocks contain only the command, so the **Copy** button gives you something you can paste. Output blocks are what the CLI printed on the author's machine. Your run id (`vendor-dossier---`), timestamps, and hashes will differ, and wherever a command below contains one of the author's values, replace it with yours.
:::
## Validate before you run
`writ validate` parses the manifest through the same validator `run` uses and never spends anything:
```bash
writ validate mission.yaml
```
```text
OK — mission 'vendor-dossier': 3 worker(s), 3 capabilities.
Worst-case total spend: 100 sats (budget cap 200 sats; sum of worker slices 100 sats).
Settlement: simulated. Signing: dev-ephemeral.
```
"Worst-case total spend" is every worker's budget slice charged at its most expensive capability ceiling: a pessimistic number you can compare with the budget cap before anything runs. A "sat" is a satoshi, one hundred-millionth of a bitcoin; in simulated mode no sats move. "dev-ephemeral" means the run signs with a throwaway key generated for this run only.
## Plan first with `--dry-run`
`--dry-run` prints which capability each worker would call and at what ceiling price. It mints no credential, calls nothing, and writes nothing:
```bash
writ run mission.yaml --var target_domain=example.com --var target_name="Example Corp" --dry-run
```
```text
Running mission 'vendor-dossier' (run vendor-dossier-20261117-002809-06f257b3e1d94e1799d95bf179c4570d) — dry run, no spend...
· infra-researcher/mission.dns.whois 5 sats planned
· compliance-researcher/mission.compliance.search 12 sats planned
· writer/mission.compose.dossier 0 sats planned
Run vendor-dossier-20261117-002809-06f257b3e1d94e1799d95bf179c4570d: Planned
Spent 0 / 200 sats · settlement simulated · 0 receipt(s)
```
Every `{{var}}` the manifest references must be supplied, or `run` refuses to start. Leave the two `--var` flags off to see that:
```bash
writ run mission.yaml --dry-run
```
```text
Manifest invalid: Manifest references variable '{{target_name}}' but no --var target_name=... was supplied.
```
## Run it for real
Drop `--dry-run`:
```bash
writ run mission.yaml --var target_domain=example.com --var target_name="Example Corp"
```
```text
Running mission 'vendor-dossier' (run vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d)...
19:28:10 warn: Writ.Engine.Runner.MissionRunner[0] No WRIT_ROOT_KEY is set — using an EPHEMERAL per-run authority root key. Credentials minted this run cannot be re-verified after the process exits, so this run cannot be resumed. Never rely on this for production authority.
19:28:16 warn: Writ.Engine.Runner.MissionRunner[0] Signing work records with a DEV-EPHEMERAL receipt key ('writ-receipt-vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d'). Receipts cannot be re-verified after this process exits; never use this signer for production evidence.
· infra-researcher/mission.dns.whois 5 sats Executed (simulated)
· compliance-researcher/mission.compliance.search 12 sats Executed (simulated)
· writer/mission.compose.dossier 0 sats Executed
Run vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d: Completed
Spent 17 / 200 sats · settlement simulated · 3 receipt(s)
Outputs:
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/infra.json
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/compliance.json
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/dossier.md
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/work-record.jsonl
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/usage.json
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/run.json
- runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d/report.html
Verify: writ verify runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d --pubkey 93178da572906641b34888d269d5ed2eefab89ba4202c729fa3f8d9f6a579e4c --signer-mode dev-ephemeral
```
Things to know about that output:
- **The two `warn:` lines are expected.** This manifest sets `work_record.signing: dev-ephemeral`: a throwaway authority key and a throwaway receipt-signing key per run, which is the zero-configuration way to try Writ. The keys are never written to disk. You can still verify this run afterwards (below) because the run's public key is recorded in `run.json`, but for evidence you can stand behind, use a persistent key: [Keys and verification](/docs/guides/keys-and-verification).
- **`(simulated)` means no money moved.** The pipeline (credential, budget reservation, payment, settlement, signed receipt) ran against an in-process Lightning endpoint. Set `settlement.mode: wallet` to pay real invoices: [Settlement](/docs/guides/settlement).
- **No model was involved.** All three steps are deterministic `call` steps; `compose.dossier` assembles the dossier from the earlier outputs. `usage.json` reports zero model tokens and zero model cost.
- **The CLI prints absolute paths on your machine** (shortened above). The run directory also holds `writ.db` (the run's local state database), `progress.jsonl` (the journal `writ resume` reads), and `run.lock`. None of them is part of the exportable evidence.
- **The last line is a ready-to-paste `Verify:` command** for this run. You will use it below.
### The outputs
`infra.json` and `compliance.json` are the two paid capabilities' simulated responses:
```json title="infra.json"
{"simulated":true,"domain":"example.com","registrar":"IANA Reserved","created":"1992-01-01","updated":"2025-08-14","status":["clientTransferProhibited"],"nameservers":["a.iana-servers.net","b.iana-servers.net"],"dnssec":"unsigned"}
```
Simulated responses are fixed sample data: they come back the same whatever `target_domain` you pass. `dossier.md` is the `writer` worker's deterministic assembly of both:
```markdown title="dossier.md"
# Vendor Due-Diligence Dossier — Example Corp (example.com)
Compiled autonomously by Writ from paid data sources. Each section below is the
response of a capability the mission paid for over L402 under a scoped, delegated credential.
--- Prior worker outputs ---
[infra-researcher/mission.dns.whois]
{"simulated":true,"domain":"example.com", ...}
[compliance-researcher/mission.compliance.search]
{"simulated":true,"query":"Example Corp", ...}
```
## Read the record back
`writ record show` prints a summary of a completed run. Replace the run id with the one your run printed:
```bash
writ record show vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d
```
```text
Mission: vendor-dossier (run vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d)
Outcome: Completed
Spent: 17 / 200 sats
Settle: simulated (no real money moved)
Spend by capability:
- mission.compliance.search: 12 sats over 1 call
- mission.dns.whois: 5 sats over 1 call
- mission.compose.dossier: 0 sats over 1 call
Evidence: 3 of 3 receipts verified · head 2:488827ea923b46b63824c23404de16fdf3bd02f830b7432c1ceee52794672ba2
WARNING: signed with a dev-ephemeral key — not production evidence.
Terminal commitment: 3 receipt(s) signed, ending at 488827ea923b46b63824c23404de16fdf3bd02f830b7432c1ceee52794672ba2 — tail truncation of this export is detectable.
```
## Verify the work record offline
`writ verify` checks every receipt's signature and hash-chain link using a public key alone. It needs no database and no access to the machine that ran the mission.
Paste the `Verify:` line your run printed (without the `Verify:` prefix). It already contains your run directory and your run's public key, which is also stored as `SignerPublicKeyHex` in `runs//run.json`. The key is 64 hex characters, passed without quotes or angle brackets:
```bash
writ verify runs/vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d --pubkey 93178da572906641b34888d269d5ed2eefab89ba4202c729fa3f8d9f6a579e4c --signer-mode dev-ephemeral
```
```text
WARNING: this work record is signed with a dev-ephemeral (throwaway) key — it is NOT production evidence.
OK — verified 3 receipt(s).
Chain head: 2:488827ea923b46b63824c23404de16fdf3bd02f830b7432c1ceee52794672ba2
Terminal commitment verified — this export cannot be truncated undetected.
WARNING: no signer identity record — the chain is not bound to a named operator (pass --require-identity to fail instead).
```
If you use the author's run id or key from this page instead of your own, verification fails, which is the point: the record and the key must match.
Now tamper with any signed field in `work-record.jsonl` (change one character of a hash) and run the same command again. Verification fails and names the row instead of passing silently. The exact number of problems depends on which field you changed, since a changed hash also breaks the link from the next receipt:
```text
WARNING: this work record is signed with a dev-ephemeral (throwaway) key — it is NOT production evidence.
FAILED — 2 problem(s) across 3 receipt(s):
[row 0] dd51a7e21eb244ae89955bcf9b95ff68: receiptHash does not match the recomputed canonical hash (tampered field)
[row 1] 382c4711a64640b786f9495aafe04ff7: broken hash-chain link: previousReceiptHash does not match the predecessor's receiptHash
```
That exits with code `5`.
## What you just showed
- The receipts record 17 sats spent of a 200-sat budget, and in simulated mode no real sats moved.
- Each worker could only call the capability its delegated credential scoped it to.
- Anyone holding the public key can check, with `writ verify` alone, that the recorded steps were signed by that key and that the chain is intact and complete.
With a throwaway `dev-ephemeral` key, the public key you checked against came from the run itself, so the check shows the record was not altered after signing, not which operator signed it. A persistent, named signer identity adds that: [Keys and verification](/docs/guides/keys-and-verification).
## Scaffold your own mission
Now that the walkthrough mission works, `writ init` writes a runnable manifest, a README, and a `.gitignore` for a mission of your own:
```bash
writ init my-mission
```
```text
Scaffolded mission at my-mission/mission.yaml
Next: edit the goal/vars, then `writ validate my-mission/mission.yaml` and `writ run my-mission/mission.yaml --var target_domain=example.com --var target_name="Example Corp"`.
The scaffold uses model.provider: anthropic, so `run` needs ANTHROPIC_API_KEY set in this shell.
```
Unlike the example above, the scaffold has an `agent` step and an `llm.write` capability, so its run calls a model. `writ validate` and `--dry-run` say so, and pass:
```text
OK — mission 'vendor-dossier': 2 worker(s), 3 capabilities.
Worst-case total spend: 40 sats (budget cap 200 sats; sum of worker slices 40 sats).
Settlement: simulated. Signing: dev-ephemeral.
Note: This mission calls a model: provider 'anthropic' needs ANTHROPIC_API_KEY at run time (not set in this shell).
```
Without `ANTHROPIC_API_KEY` set, `run` stops before any capability is invoked, with exit code `3`. It still writes a run directory with the failed run's summary and report. The last line says why:
```text
Pre-flight check failed: model provider 'anthropic' needs an API key, but ANTHROPIC_API_KEY is not set in this shell. Export ANTHROPIC_API_KEY (or set `model.provider: claude-cli` to use your installed Claude Code CLI instead). No capability was invoked and nothing was settled.
```
Model usage is billed to your provider account and is not part of the sats budget; the run summary and `report.html` show the call count and list-price cost. See the [manifest reference, `model`](/docs/reference/manifest#model).
Running `writ init my-mission` a second time refuses to overwrite your work (exit code `2`):
```text
Refusing to overwrite existing manifest: my-mission/mission.yaml
```
## Next steps
- [Keys and verification](/docs/guides/keys-and-verification): move from a throwaway key to a persistent, named signer, and see what `writ verify` shows.
- [Manifest reference](/docs/reference/manifest): every field a mission file can declare, including `agent` steps that use a model.
- [Command reference](/docs/reference/commands): every command, in depth.
- [Approvals and budgets](/docs/guides/approvals-and-budgets): what happens when a call crosses a human-approval threshold.
==============================================================================
# Get access
Source: https://writ.lightningenable.com/docs/getting-started/installation
==============================================================================
# Get access
Writ is in private preview. To request access, write to [support@lightningenable.com](mailto:support@lightningenable.com?subject=Writ%20private%20preview).
Once you have the `writ` tool, the steps on this page confirm that it works. About five minutes.
## 1. Requirements
- The [.NET 10 SDK](https://dotnet.microsoft.com/download) (LTS).
- Windows, macOS, or Linux.
That is everything you need to run missions with **simulated** money. You do not need a Lightning wallet, a model API key, or a model CLI for the first mission on the next page. See [What you don't need yet](#what-you-dont-need-yet).
Confirm your SDK:
```bash
dotnet --version
```
Expected: a version starting with `10.`.
## 2. Check the tool
```bash
writ --version
writ --help
```
Expected: `writ --version` prints a version starting with `0.1.0`, and `writ --help` prints a usage summary that starts with `Description:` and lists the commands `init`, `validate`, `run`, `resume`, `verify`, `approvals`, `revoke`, `issue`, `record`, `reconcile`, `keys`, `coding`, and `db`.
## 3. Confirm it with the smoke mission
This mission needs no wallet, no API key, no model, and no network. Make an empty directory, and save the following as `smoke.yaml` in it:
```yaml title="smoke.yaml"
mission:
name: smoke
goal: "One paid capability call under a bounded budget, settled in simulated mode."
budget:
total_sats: 100
per_call_max_sats: 25
settlement:
mode: simulated
capabilities:
- id: data.lookup
kind: l402-http
base_url: https://api.example.test/data
path: /lookup
method: GET
max_sats_per_call: 5
workers:
- name: probe
scope: [data.lookup]
budget_sats: 40
steps:
- type: call
capability: data.lookup
input: { q: smoke }
output: lookup.json
work_record:
signing: dev-ephemeral
output_dir: runs/
```
From that directory, run it:
```bash
writ run smoke.yaml
```
Expected (your run id, times, and hashes differ):
```text
Running mission 'smoke' (run smoke-20261116-213137-...)...
16:31:37 warn: Writ.Engine.Runner.MissionRunner[0] No WRIT_ROOT_KEY is set — using an EPHEMERAL per-run authority root key. ...
16:31:42 warn: Writ.Engine.Runner.MissionRunner[0] Signing work records with a DEV-EPHEMERAL receipt key (...). ...
· probe/mission.data.lookup 5 sats Executed (simulated)
Run smoke-20261116-213137-...: Completed
Spent 5 / 100 sats · settlement simulated · 1 receipt(s)
Outputs:
- /runs/smoke-20261116-213137-.../lookup.json
- /runs/smoke-20261116-213137-.../work-record.jsonl
- /runs/smoke-20261116-213137-.../usage.json
- /runs/smoke-20261116-213137-.../run.json
- /runs/smoke-20261116-213137-.../report.html
Verify: writ verify /runs/smoke-20261116-213137-... --pubkey <64 hex characters> --signer-mode dev-ephemeral
```
The CLI prints absolute paths; the output above shortens them.
The two `warn:` lines say that this run used throwaway keys, which is the zero-configuration default. [Keys and verification](/docs/guides/keys-and-verification) covers persistent keys. When you see `Completed` and a spend summary, the `writ` tool is working.
Paste the `Verify:` line your run printed (without the `Verify:` prefix) to check the signed work record offline. Your chain head differs:
```text
WARNING: this work record is signed with a dev-ephemeral (throwaway) key — it is NOT production evidence.
OK — verified 1 receipt(s).
Chain head: 0:b47e91db392063f2cdd42bbbd7b4c333e7024829603b5b149f513ad990b29999
Terminal commitment verified — this export cannot be truncated undetected.
WARNING: no signer identity record — the chain is not bound to a named operator (pass --require-identity to fail instead).
```
## Writ's programs
The `writ` command covers every command in the [command reference](/docs/reference/commands), simulated and wallet settlement, and every model provider. Writ also has these programs:
| Program | What it is |
|---|---|
| `writ` | The CLI: missions, verification, keys, approvals, and the operator commands |
| `writ-mcp` | The MCP server for agent hosts |
| `writ-api` | The HTTP API for agent hosts |
| `writ-coding-mcp` | The tool server for the governed coding agent |
| `Writ.Service` | The engine as a .NET class library |
If you need one of the programs other than `writ`, say so when you request access. These docs show every manifest the examples use, ready to save. The Claude Skills are published on this site: see [For agents](/docs/for-agents).
## What you don't need yet
Running the `writ` tool in the default `simulated` settlement mode needs the .NET 10 SDK and nothing else. Specifically, you do **not** need:
- **A Lightning wallet or node.** Only `settlement.mode: wallet` (real payments) needs one. See [Settlement](/docs/guides/settlement).
- **A model API key or model CLI.** A mission whose steps are all `call` steps against `l402-http` capabilities or `compose`/`compose.*` internal capabilities never invokes a model, and Writ does not probe for one. Missions with `agent` steps, or with any other `internal` capability, call a model and need a model provider: the `anthropic` provider with `ANTHROPIC_API_KEY`, or your installed Claude Code or Codex CLI. See the [manifest reference](/docs/reference/manifest#model).
- **Persistent signing keys.** The default `work_record.signing: dev-ephemeral` generates a throwaway key per run.
## Next step
Continue to [Your first mission](/docs/getting-started/first-mission): validate, dry-run, run, and verify a complete simulated mission, with the real output at every step.
==============================================================================
# Approvals and budgets
Source: https://writ.lightningenable.com/docs/guides/approvals-and-budgets
==============================================================================
# Approvals and budgets
Writ bounds spend two ways: a hard **budget cap** that every call is checked against before it proceeds, and an optional **human approval gate** for calls at or above a threshold you set, or that would take the spend made without your approval over a cumulative or per-window threshold.
## Budget enforcement
`budget.total_sats` is a cumulative cap enforced at the credential-chain root: every sat any worker or delegated sub-worker spends counts against the same pool. `budget.per_call_max_sats` and each capability's own `max_sats_per_call` further cap any single call (the lower of the two wins).
Before a call runs, Writ reserves its ceiling against the remaining budget in one database update that succeeds only when the reservation fits. Concurrent calls are checked against the same remaining amount, so together they never reserve more than the cap.
A mission with a paid (`l402-http`) capability and a zero or missing `budget.total_sats` is refused by `writ validate` and `writ run` before anything runs (exit `2`):
```text
Manifest invalid (2 problem(s)):
- Top-level worker budgets sum to 40 sats, which exceeds budget.total_sats (0).
- budget.total_sats must be greater than 0 when the mission declares a paid (l402-http) capability; a zero or missing cap would allow unbounded spend.
```
## The approval gate
Set `approvals.threshold_sats` in the manifest to require a human decision on any call at or above that amount:
```yaml
approvals:
threshold_sats: 10
```
`0` means every paid call needs approval. Omit `approvals` (or leave it `{}`) for fully autonomous operation.
:::note Simulated-mode pricing
In `settlement.mode: simulated`, a call is charged its **capability ceiling** (`max_sats_per_call`), so whether a capability trips the threshold depends only on the manifest. A mission with `threshold_sats: 10` and a capability whose ceiling is `20` suspends on every call to that capability.
:::
When a call crosses the threshold, the run suspends instead of failing (exit `4`). To approve the call and finish the same run, the run must be resumable, which takes the setup in the next section.
## Approve and resume a run, end to end {#approve-and-resume}
A suspended run continues with `writ resume`. A run can be resumed only when it started with both of these:
- **`WRIT_ROOT_KEY` set**, to the same value when you resume. Writ derives the run's authority key from it; the value is any secret string you choose and keep. Without it, Writ uses a throwaway authority key that no other process can verify.
- **A persistent signer**: `work_record.signing: key-file` (or `env`). A `dev-ephemeral` key exists only in the process that ran the run.
Run these from an empty directory.
**1. Create a signing key.** This writes `keys/receipt.key` (private) and `keys/signer-identity.json` (public):
```bash
writ keys init --operator-name "Example Operator"
```
**2. Save this manifest as `mission.yaml`.** It makes one paid call whose 20-sat ceiling is above the 10-sat threshold:
```yaml title="mission.yaml"
mission:
name: approval-demo
goal: "One paid call that needs a person's approval."
budget:
total_sats: 50
per_call_max_sats: 25
settlement:
mode: simulated
approvals:
threshold_sats: 10
capabilities:
- id: data.premium
kind: l402-http
base_url: https://api.example.test/data
path: /fetch
method: GET
max_sats_per_call: 20
workers:
- name: buyer
scope: [data.premium]
budget_sats: 40
steps:
- type: call
capability: data.premium
input: { q: premium }
output: premium.json
work_record:
signing: key-file
key_file: keys/receipt.key
output_dir: runs/
```
**3. Set `WRIT_ROOT_KEY` to a long random secret.** These commands generate one without printing it:
```bash
export WRIT_ROOT_KEY="$(openssl rand -hex 32)"
```
```powershell
$env:WRIT_ROOT_KEY = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
```
Keep the value where you keep other secrets, for example a password manager: `writ resume` needs the same value. To copy it there, print it once with `printenv WRIT_ROOT_KEY` (bash) or `$env:WRIT_ROOT_KEY` (PowerShell).
**4. Run the mission.** It suspends at the gated call (exit `4`):
```bash
writ run mission.yaml
```
```text
Running mission 'approval-demo' (run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931)...
· buyer/mission.data.premium 0 sats ApprovalRequired
Run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931: ApprovalRequired
Spent 0 / 50 sats · settlement simulated · 0 receipt(s)
Outputs:
- runs/approval-demo-20261117-002310-.../work-record.jsonl
- runs/approval-demo-20261117-002310-.../usage.json
- runs/approval-demo-20261117-002310-.../run.json
- runs/approval-demo-20261117-002310-.../report.html
Suspended — pending approval #1. Approve with: writ approvals approve 1 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Then continue the run with: writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 mission.yaml
Spend requires human approval.
```
The CLI prints absolute paths; the samples on this page shorten them. Replace the run id in the next commands with the one your run printed.
**5. Review the request, then approve it:**
```bash
writ approvals list --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
```
```text
Pending approvals for run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931':
#1 mission.data.premium 20 sats — buyer:data.premium
resource /fetch → api.example.test (invocation #1); valid 15 min once approved
```
```bash
writ approvals approve 1 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
```
```text
Approved #1. Continue the run with: writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 (the manifest it started with).
```
To refuse it instead, run `writ approvals deny 1 --run `, which prints `Denied #1.`
**6. Resume the run** in a shell where `WRIT_ROOT_KEY` holds the same value:
```bash
writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 mission.yaml
```
```text
Resuming mission 'approval-demo' (run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931)...
· buyer/mission.data.premium 20 sats Executed (simulated)
Run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931: Completed
Spent 20 / 50 sats · settlement simulated · 1 receipt(s)
Outputs:
- runs/approval-demo-20261117-002310-.../premium.json
- runs/approval-demo-20261117-002310-.../work-record.jsonl
- runs/approval-demo-20261117-002310-.../usage.json
- runs/approval-demo-20261117-002310-.../run.json
- runs/approval-demo-20261117-002310-.../report.html
Verify: writ verify runs/approval-demo-20261117-002310-... --pubkey 3b2b9a7e0db5ae925b90f772737618fe99ddf0af751ed4013d8a43192dec9a3a
```
A run that started without `WRIT_ROOT_KEY`, or with a `dev-ephemeral` signer, still suspends at the gate, and says what to set before you run the mission again:
```text
Suspended — pending approval #1.
This run cannot be resumed: it started without WRIT_ROOT_KEY. To approve and continue a run, set WRIT_ROOT_KEY to a secret you keep and use work_record.signing: key-file (or env), then run the mission again.
Spend requires human approval.
```
## Cumulative and windowed thresholds {#cumulative-and-windowed-thresholds}
`threshold_sats` looks at one call at a time, so an agent could split a large spend into many calls just under it. Two more thresholds bound what an agent spends **without** you, across calls:
```yaml
approvals:
threshold_sats: 50 # per call (optional)
cumulative_threshold_sats: 200 # total unapproved spend for the run
window_threshold_sats: 60 # unapproved spend per rolling window...
window_seconds: 3600 # ...of one hour
```
A call needs approval when **any** of these holds:
- **Per call:** the call's ceiling is at or above `threshold_sats`.
- **Cumulative:** the spend already made without approval in this run, plus this call's ceiling, would be more than `cumulative_threshold_sats`.
- **Window:** the spend made without approval in the last `window_seconds`, plus this call's ceiling, would be more than `window_threshold_sats`.
How the count works:
- **It is read from the database, not from memory**, so it survives a crash and `writ resume`. A call whose payment is reserved, awaiting reconciliation, or completed with its receipt pending recovery counts at its ceiling (an in-flight payment counts as spent). A settled call counts at what actually moved: the amount the ledger charged, plus any proven payment the budget caps had no room for.
- **Spend you approved is not counted.** Approving does **not** reset the count either.
- **Headroom still runs.** A call is held only when it would not fit. While a larger call waits for you, a smaller call that still fits under the threshold runs without asking.
- **A denial does not stick.** Denying a request refuses that attempt. The same call is judged again the next time it is made, and runs without asking if it fits by then (for example, after older spend has left the window).
- **The window is keyed on reservation time:** spend counts in the window when its budget hold was taken within the last `window_seconds`, whenever it settled.
- **The scope of a manifest's thresholds is the run.** Every worker and delegated sub-worker in the run shares one count; a worker cannot start a fresh count by delegating.
- **Concurrent calls cannot both slip under.** The check is repeated inside the same database transaction that reserves the budget, so when two calls race for the last few sats, one of them is asked. That transaction holds the database's write lock while it reads the count: one aggregate query over the scope's rows (a host-wide cumulative threshold reads every row in the host's database), so each paid call under an aggregate threshold costs that query twice (once to decide whether to ask, once inside the reservation), and its cost grows with the history it reads. Measured on Windows with 50,000 settled rows in scope: about 120 ms per query, and about 240 ms added to each paid call.
- **A request that was raised waits for a decision.** If the window rolls over while a request is pending, the same call still waits for you; approve or deny it.
The count is designed to keep the spend made without approval at or under the threshold, but it can end up above it:
- when a payment proven after the fact moved more than the call reserved (a late extra payment, or a payment that arrived after its hold was released);
- when spend was made before the threshold was set or lowered (a service host whose configuration changed).
`writ approvals list` says which threshold raised each request, with the numbers. For three 5-sat calls under `cumulative_threshold_sats: 10`, the third is held:
```text
Pending approvals for run 'cumulative-demo-20261117-002355-5e66825e19f746aba578932ede6d75eb':
#1 mission.data.lookup 5 sats — researcher:data.lookup
resource /lookup → api.example.test (invocation #3); valid 15 min once approved
why: cumulative threshold: 10 sats already spent without approval + this call's 5 sats would exceed 10 sats for this run
```
A service host sets the same thresholds with `WRIT_APPROVAL_CUMULATIVE_SATS`, `WRIT_APPROVAL_WINDOW_SATS` and `WRIT_APPROVAL_WINDOW_SECONDS` (each greater than 0 when set). A host's thresholds are **host-wide**: they count the spend made without approval under every writ and in every workspace in that host's database, so issuing a new writ or naming another workspace does not start a fresh count. One workspace's spend therefore affects every other workspace on that host, and is visible to them in aggregate: the `countedSats` a held call reports for a `host_cumulative` or `host_window` gate is the host's total unapproved spend, across all workspaces, not that workspace's own. No request field changes them. `writ_invoke` returns `approvalGate` with the same details (`host_cumulative` or `host_window`), and `writ_approvals` lists them under `gate`.
With all three unset, the gate is per call only.
### Who decides on a service host
The service hosts, `writ-mcp` (MCP server) and `writ-api` (HTTP API), are separate programs from the `writ` CLI: see [Writ's programs](/docs/getting-started/installation#writs-programs). A service host serves two roles. The **agent** role runs calls, reads what remains and what happened, and sees the requests waiting for a decision. The **operator** role decides them, issues writs, and revokes. A spend held for approval waits for the operator's decision.
- `writ-mcp` serves the agent role by default; `writ-mcp --role operator` adds `writ_approve`, `writ_deny`, `writ_issue` and `writ_revoke`.
- The HTTP API gives the agent token the agent routes and the operator token every route.
- The operator can also decide from the CLI, against the host's database:
```bash
writ approvals list --service-db ./.writ/writ.db
writ approvals approve 3 --service-db ./.writ/writ.db
```
After an approval, the agent retries the same call (same idempotency key) and it runs. In a mission run (`writ run`) the agent has no approval tool at all; requests are decided with `writ approvals --run`.
Run these with the host's `WRIT_ROOT_KEY` in the environment, after the host has started once. For how to set up the host so the operator's configuration stays the operator's, see [Setting up the host](/docs/reference/agent-api#setting-up-the-host).
## What a grant is bound to
An approval isn't a blanket "yes": it's a grant for **one specific call**. A grant is bound to the exact combination of: **workspace** (run), **credential**, **capability**, **amount ceiling**, **resource path**, **stated purpose**, **destination** (the endpoint's authority, or the capability kind for an internal capability), and the **invocation id** that raised it. A full match on every one of those is required to consume it, so an approval for one purpose or path never authorizes a different call of the same capability because the amount happens to fit.
`writ approvals list` prints the dimensions that matter for a human decision: capability, amount, purpose, resource, and destination.
Approving the same request twice fails cleanly:
```text
$ writ approvals approve 1 --run approval-demo-...
Could not approve #1: Approval request is already approved.
```
Exit `2`. Same for denying (or approving) an id that doesn't exist:
```text
$ writ approvals deny 999 --run approval-demo-...
Could not deny #999: Approval request not found.
```
Exit `2`.
## Approval TTL {#approval-ttl}
A granted approval stays usable for **15 minutes by default** after approval. After that it expires and is retired as a distinct outcome (`expired`), and a fresh pending request is raised in its place. A mission sets another value with `approvals.approval_ttl_minutes` (greater than 0; see the [manifest reference](/docs/reference/manifest#approvals)), and a service host with `WRIT_APPROVAL_TTL_MINUTES`.
**Superseded grants:** at most one open grant (pending or approved-but-unconsumed) exists per binding. If the pipeline resolves an open grant against an invocation that's no longer a clean match (a failed or released attempt that gets a new invocation id, or an inconsistent state), the old grant is retired as `superseded` and a fresh pending request takes its place, instead of reusing a stale approval.
## Resuming a suspended run {#resuming-a-suspended-run}
After a human approves, continue the same run with `writ resume`, passing the manifest it started with (and the same `--var` values); [Approve and resume a run, end to end](#approve-and-resume) walks through it. The resume reopens the run's own database and progress journal, reuses the credentials the run already issued, skips the steps that already completed, and consumes the recorded approval for the gated step. A later gated step suspends the run again (exit `4`); approve it and resume again. Running the manifest with `writ run` instead starts a new run that cannot see this run's approvals.
Worker credentials keep their original expiry (`expires_minutes`). Decide an approval within that time; a call resumed after it is refused as expired, and the remaining work needs a new run.
A resume that cannot be safe is refused before anything is opened, and changes nothing (exit `3`). With a different `WRIT_ROOT_KEY`:
```text
Resume refused: WRIT_ROOT_KEY is not the authority key run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931' was started with (its journal does not authenticate under it), or the journal was edited. Nothing was changed.
```
With none:
```text
Resume refused: WRIT_ROOT_KEY must be set to resume a run: its credentials were issued under that key, and only it can verify them. Nothing was changed.
```
## Reconciling a pending wallet payment {#reconciling-a-pending-wallet-payment}
A different kind of hold happens only in `settlement.mode: wallet`: if a wallet payment's outcome is unknown (the network call errored or timed out *after* the payment might have gone out), Writ keeps the budget hold as `pending_reconciliation` instead of guessing, and the run exits `7`. See [Settlement](/docs/guides/settlement#ambiguous-payment-outcomes) for the full mechanics.
`writ reconcile` records what it decides as a signed audit row, under the key in `WRIT_AUDIT_KEY`. Set it the same way as `WRIT_ROOT_KEY`, to a different secret you keep. Without it, `writ reconcile` and `writ revoke` stop with `AuditKeyNotConfigured` (exit `2`); `--development-audit-key` uses a key built into Writ instead, for tests only.
`simulated` settlement never produces a pending payment, so `writ reconcile` on a simulated run finds nothing to do:
```text
$ writ reconcile approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
No invocations pending reconciliation for run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931'.
```
Exit `0`.
Resolving one for real (wallet mode):
```bash
writ reconcile --invocation --resolve paid # your wallet shows the payment went through
writ reconcile --invocation --resolve not-paid # the wallet reports it failed; return the hold
writ reconcile --invocation # omit --resolve to ask a lookup-capable wallet first
```
`--resolve not-paid` on a hold with a payment hash asks the wallet by that hash first, and returns the hold only when the wallet that paid reports the payment failed. Run `writ reconcile` from a shell configured with the wallet the run pays from. Without `--resolve`, and on `writ resume`, a not-paid answer returns the hold only from the kind of wallet that paid.
Upgrading a database to schema 13 charges earlier late payments that exceeded a cap to the links that had room, which lowers those links' remaining budget; `writ db upgrade` lists each charge. When no wallet can say (Strike, or no lookup-capable wallet configured) and you have checked the payment yourself, add `--allow-unconfirmed-not-paid`; the audit log records that you did. A wallet that reports the payment paid refuses `not-paid` either way. The codes and the full rules are in [`writ reconcile`](/docs/reference/commands#writ-reconcile).
`--resolve` only accepts exactly `paid` or `not-paid`:
```text
$ writ reconcile approval-demo-... --resolve maybe
--resolve must be exactly 'paid' or 'not-paid' (was 'maybe').
```
Exit `2`. A manual `paid` resolution settles the budget hold but produces **no new work-record receipt**: there's no preimage to commit to, since the wallet call is what would have produced one.
## Next steps
- [Settlement](/docs/guides/settlement): simulated and wallet mode, and the ambiguous-payment case in full.
- [Security model and preview limitations](/docs/security-and-limitations#preview-limitations-stated-plainly): what the approval thresholds do and do not cover, in the limitations table.
==============================================================================
# Keys and verification
Source: https://writ.lightningenable.com/docs/guides/keys-and-verification
==============================================================================
# Keys and verification
This guide walks the full signer lifecycle with real captured output: create a persistent key, run a mission with it, verify the result, publish a head attestation, share a bundle, rotate the key, run again, and revoke it, showing what `writ verify` checks at each step. Run the commands from one empty directory. The samples shorten absolute paths, and shorten a public key where `writ keys` prints it on its own line; the full key appears in the `verify` commands.
:::note Verify the run directory
Verify a run directory or an exported bundle, not a bare `work-record.jsonl`. On its own, with no `run.json`, `--expect-head`, or `--pinned-head`, a `work-record.jsonl` reports `INCOMPLETE` (exit `8`): the receipts check out, but nothing binds the end of the chain, so a shortened export would look identical. `--allow-no-terminal-commitment` accepts such a record anyway.
:::
## The signing modes
| `work_record.signing` | What it does | When to use it |
|---|---|---|
| `dev-ephemeral` (default) | Generates a throwaway signing key **in memory only** for the run, then discards it. Receipts are stamped `signerMode: dev-ephemeral` and `writ verify` warns that they aren't production evidence. | Trying Writ out, demos, CI smoke tests. |
| `key-file` | Signs with a persistent key at `work_record.key_file`, created by `writ keys init`. The public key and a self-signed operator identity record ship with every run. | Any evidence you intend to keep, share, or stand behind. |
| `env` | The same persistent-identity behavior as `key-file`, with the key read from the `WRIT_RECEIPT_KEY` environment variable. | A service host that takes its secrets from the environment. |
## Create a persistent key
```text
$ writ keys init --operator-name "Example Operator" --operator-url https://operator.example --operator-contact ops@operator.example
Created receipt signing key: keys/receipt.key (private; no other account is granted access)
Created signer identity: /keys/signer-identity.json (public; ships with every run)
key_id: 48d196ae736139f2
pubkey: 1f9a2598...82b214ca
operator: Example Operator (https://operator.example)
Next: in mission.yaml set
work_record:
signing: key-file
key_file: keys/receipt.key
and share the pubkey with anyone who will run `writ verify`.
```
The private key never appears in any command's output. On disk, `keys/receipt.key` is created private: POSIX mode `0600`, or on Windows a protected ACL (nothing inherited from the folder) that grants full control to the account that ran `keys init` and to no other account, set as the file is created. From an elevated Windows shell the file's owner is `BUILTIN\Administrators`, not your account, and administrators and `SYSTEM` can take over any file; `keys init` grants no other account access. `keys/signer-identity.json` is the **public**, self-signed identity record it wrote beside the key:
```json
{
"protocol": "writ.signer-identity/1",
"algorithm": "bip340-secp256k1",
"pubkey": "1f9a2598...82b214ca",
"key_id": "48d196ae736139f2",
"operator": {
"name": "Example Operator",
"url": "https://operator.example",
"contact": "ops@operator.example"
},
"created_at": "2026-11-17T00:21:48.8562729+00:00",
"signature": "e35897bc742bb94326594a399f7825b0193c3b68140aabf776223065709a1bcca3b8b4a61ae2b391d57c735e77c52a2c6caf0660093e96643dbca1a83b05fd68"
}
```
`writ keys init` refuses to overwrite an existing key or identity (exit `2`); use `--out ` to create a second key elsewhere. `writ keys show` reprints the public facts, and cross-checks the key file against the identity record:
```text
$ writ keys show
Signer identity: /keys/signer-identity.json
key_id: 48d196ae736139f2
pubkey: 1f9a2598...82b214ca
algorithm: bip340-secp256k1
operator: Example Operator (https://operator.example)
created_at: 2026-11-17T00:21:48Z
identity_hash: 02a5d571a02b3aad2fff15b873613ea78945f728ec41a8a089f42e5bd7dce3e8
self-signature: valid
key file: keys/receipt.key (matches this identity)
```
`key_file` is resolved from the directory you run `writ` in, like the rest of the manifest's relative paths. Run your missions from the directory that holds `keys/`, or give `key_file` an absolute path.
### Who may read the key file
Every command that reads a receipt key **file** applies the same custody rule before it reads a byte: `writ run` (the manifest's `key_file`), the service hosts' `WRIT_RECEIPT_KEY_FILE`, `keys show`, `keys rotate`, `keys revoke`, `record publish-head`, and the `coding` commands that sign with the key. A key another account can read is a key another account can sign receipts with, so such a file is refused, and no other key is used in its place.
- **Windows:** every entry that grants read (or the right to change permissions or take ownership) must name the file's owner, `SYSTEM`, or `BUILTIN\Administrators`, or the account running Writ when the file is owned by that account, `Administrators`, or `SYSTEM`. Entries inherited from the folder count.
- **Linux and macOS:** the mode is `0600` or stricter, and Writ is not running as root.
- **Everywhere:** the key path must name the key file itself. A path that is a symbolic link, junction, or other reparse point is refused, whatever it points at. Linked parent folders are followed, and the file they lead to must still pass the rule.
Writ opens the key file once, applies the rule to that open file, and reads the key from it, so a file swapped in after the check is never the one read.
`writ run` and the service hosts name the file, the account or mode that makes it too open, and the fix. The other commands print `KeyFileTooOpen` and the rule. `--allow-open-key-file` lets those other CLI commands read an open key file on a test host. It never admits a linked key path, and it doesn't apply to `writ run` or the service hosts.
**An existing key file:** if `writ run` refuses yours, restrict it (`chmod 600 keys/receipt.key`, or on Windows `icacls keys\receipt.key /inheritance:r /grant:r "\:F"` and remove any other account it still lists). If another account may have read it, rotate the key with `writ keys rotate` and revoke the old one.
**`WRIT_RECEIPT_KEY` is a different channel.** A key passed in the environment (`signing: env`) is not a file, and this rule does not judge it; it is protected only as well as the process environment and wherever you set it. Prefer `key-file` on a host shared with other accounts.
## Run a mission signed with that key
Save this manifest as `mission.yaml` beside the `keys/` directory. It is the install page's smoke mission with `work_record` pointed at the key:
```yaml title="mission.yaml"
mission:
name: keyed-demo
goal: "One paid capability call, signed with a persistent key."
budget:
total_sats: 100
per_call_max_sats: 25
settlement:
mode: simulated
capabilities:
- id: data.lookup
kind: l402-http
base_url: https://api.example.test/data
path: /lookup
method: GET
max_sats_per_call: 5
workers:
- name: probe
scope: [data.lookup]
budget_sats: 40
steps:
- type: call
capability: data.lookup
input: { q: smoke }
output: lookup.json
work_record:
signing: key-file
key_file: keys/receipt.key
output_dir: runs/
```
```text
$ writ run mission.yaml
Running mission 'keyed-demo' (run keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32)...
19:21:51 warn: Writ.Engine.Runner.MissionRunner[0] No WRIT_ROOT_KEY is set — using an EPHEMERAL per-run authority root key. Credentials minted this run cannot be re-verified after the process exits, so this run cannot be resumed. Never rely on this for production authority.
· probe/mission.data.lookup 5 sats Executed (simulated)
Run keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32: Completed
Spent 5 / 100 sats · settlement simulated · 1 receipt(s)
Outputs:
- runs/keyed-demo-20261117-002151-.../lookup.json
- runs/keyed-demo-20261117-002151-.../work-record.jsonl
- runs/keyed-demo-20261117-002151-.../usage.json
- runs/keyed-demo-20261117-002151-.../run.json
- runs/keyed-demo-20261117-002151-.../report.html
Verify: writ verify runs/keyed-demo-20261117-002151-... --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca
```
The `warn:` line is about the authority key, not the signing key: the receipts are signed with your persistent key, and the run cannot be resumed later. To make runs resumable, set `WRIT_ROOT_KEY` as shown in [Approve and resume a run, end to end](/docs/guides/approvals-and-budgets#approve-and-resume). The CLI prints absolute paths; the samples on this page shorten them.
The run directory carries the identity record alongside the usual artifacts:
```text
lookup.json
progress.jsonl
report.html
run.json
run.lock
signer-identity.json
usage.json
work-record.jsonl
writ.db
```
## Verify, and what it shows
```text
$ writ verify runs/keyed-demo-... --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca --require-identity
OK — verified 1 receipt(s).
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
Terminal commitment verified — this export cannot be truncated undetected.
Signed by Example Operator (https://operator.example) , key 48d196ae736139f2 — identity record verified and bound to the chain.
```
`writ verify` checks, offline, from the public key you supply:
- **Every receipt's signature.** Each receipt is BIP-340-signed; a forged or altered receipt fails signature verification.
- **The hash chain.** Each receipt commits to the hash of the one before it (`previousReceiptHash`); reordering, deleting, or inserting a receipt breaks the chain.
- **The terminal commitment.** When `run.json` carries a signed commitment over the chain's final `(sequence, hash)`, `verify` requires the chain to end exactly there, so dropping the last few receipts of an export fails verification.
- **Signer identity**, when `--require-identity` is set or an identity record is present: the record's self-signature is valid and the first receipt commits to its hash, so `verify` can print the operator the key belongs to.
A clean `verify` shows that the recorded steps were attested by the holder of this key, and that the chain is intact and complete. It does not independently establish authorization, payment, completion, or quality: those are the signer's attestations. See [Security model and preview limitations](/docs/security-and-limitations).
### A wrong public key fails
```text
$ writ verify runs/keyed-demo-... --pubkey 0000000000000000000000000000000000000000000000000000000000000000
FAILED — 3 problem(s) across 1 receipt(s):
[row 0] 5fab3d822eb24a29a5d95e21375e94d1: signature verification failed
the run summary's terminal commitment signature does not verify under the supplied public key — refusing to trust it (the run summary may have been tampered with).
the signer identity record describes key 48d196ae736139f2 (1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca), which is not the --pubkey you pinned and is not reachable from it: key 48d196ae736139f2 is not reachable from the trusted anchor 66687aadf862bd77: no rotation record continues from key 66687aadf862bd77. — the record does not belong to a key you trust.
```
Exit `5`.
### Tampering names the row
A copy of the run directory with one field of `work-record.jsonl` edited (`resultCode` changed from `completed`) gives:
```text
FAILED — 1 problem(s) across 1 receipt(s):
[row 0] 5fab3d822eb24a29a5d95e21375e94d1: receiptHash does not match the recomputed canonical hash (tampered field)
```
Exit `5`. The failure names the row and the reason.
## Share a run with a counterparty
`writ record export --out ` writes a bundle with ordinary file permissions: the work record, `run.json`, the report, `usage.json`, the signer identity record, and the rotation and revocation records when the run has them. It never includes `writ.db`, key material, or step outputs:
```text
$ writ record export keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32 --out share-bundle
Exported run 'keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32' to /share-bundle
work-record.jsonl (1504 bytes, sha256 fa86bd0a321fab11f05de3add6c78c3c1837d2091ffa89ad200ee651ed8cd8c8)
run.json (2115 bytes, sha256 75baefa915634c7c24bde4744ad36123eed0f76c867b17df02f2a255f45f6ea5)
report.html (3776 bytes, sha256 b17704f88a3431762f97ae5219c1a28cb6d5330c0f39936a2ec9b67e40f18b38)
usage.json (182 bytes, sha256 e230184836060050d94f7016905ac25349993f830db241a16e2379a6737d2cae)
signer-identity.json (531 bytes, sha256 a7e7fefe3d966d03e2e2685516f1376bb3248600245affa9364bdb46231d2a07)
manifest.json
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a (1 receipts).
Not included (never exported): writ.db and its sidecars, key material, and step outputs.
Recipient check: writ verify --pubkey --expect-head 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
```
Give the recipient your public key separately, through a channel they already trust, not inside the bundle. They verify the bundle directory with it:
```text
$ writ verify share-bundle --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca
OK — verified 1 receipt(s).
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
Terminal commitment verified — this export cannot be truncated undetected.
Signed by Example Operator (https://operator.example) , key 48d196ae736139f2 — identity record verified and bound to the chain.
```
## Head attestations
`writ record publish-head` signs a small attestation over a run's terminal receipt with the run's key. A counterparty who keeps it and passes it to `--pinned-head` detects any later shortening of the record without having to type in the head themselves.
```text
$ writ record publish-head keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32
Head attestation for run keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32: seq 0, head 526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
signed by key 48d196ae736139f2 at 2026-11-17T00:22:09.1117481Z
written to runs/keyed-demo-.../head-attestation.json
Counterparties verify with: writ verify --pubkey --pinned-head head-attestation.json
```
```json title="head-attestation.json"
{
"protocol": "writ.head-attestation/1",
"run_id": "keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32",
"seq": 0,
"head_hash": "526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a",
"signer_key_id": "48d196ae736139f2",
"attested_at": "2026-11-17T00:22:09.1117481+00:00",
"signature": "ba3d2837b8793d73e1064f37aee0e15ed67963c7483dbd6a41ea5c6f3efcadb1b9e688202a7dc9ae5513cfcede5b1993c3a9f114cbb6dc28b8398006fc4b3a5c"
}
```
```text
$ writ verify runs/keyed-demo-... --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca --pinned-head runs/keyed-demo-.../head-attestation.json
OK — verified 1 receipt(s).
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
Terminal commitment verified — this export cannot be truncated undetected.
Signed by Example Operator (https://operator.example) , key 48d196ae736139f2 — identity record verified and bound to the chain.
Pinned head verified — attested by key 48d196ae736139f2 at 2026-11-17T00:22:09.1117481Z: the chain ends exactly at 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a.
```
An attestation names the signer by `signer_key_id`, not by public key: the verifier still supplies the public key out of band. `publish-head` needs the private key on disk, so it can't attest a `dev-ephemeral` run (exit `2`):
```text
Run 'smoke-20261117-002246-a33f66e03fa5434ebd1e0279df95a1ed' was signed with a dev-ephemeral key, which existed only in the process that ran it, so no key can attest its head. Use work_record.signing: env or key-file for runs whose head you publish. Nothing was written.
```
`--post ` also sends the attestation JSON in an HTTP POST to a URL you choose. `--relay ` also publishes it as a signed Nostr event (kind 38410) to a relay you choose; `wss://agents.lightningenable.com` accepts these events. `writ record verify-head --relay --pubkey ` later checks every head the relay returns against the local record. A relay is not a transparency log: it can withhold a later head, so publish to and check more than one relay to detect a withheld head. The relay is public and learns the run id, receipt count, head hash and the signer's public key. See [`record publish-head`](/docs/reference/commands#record-publish-head) and [`record verify-head`](/docs/reference/commands#record-verify-head).
## Rotation: keep working with a new key
```text
$ writ keys rotate
Rotated receipt signing key: 48d196ae736139f2 -> 7c3e2347e1046914
new pubkey: c98f986f...a8df5401
new key: keys/receipt.key (old key archived as receipt.48d196ae736139f2.key)
new identity: /keys/signer-identity.json (predecessor_key_id 48d196ae736139f2)
rotation: appended to /keys/rotations.jsonl (signed by the old key)
Verifiers pinned to the OLD pubkey keep working: `writ verify --pubkey ` walks the rotation to the new key.
```
The mission's `key_file: keys/receipt.key` path stays the same; the file now holds the new key. A run made after rotation is signed by the new key, and the runner copies `rotations.jsonl` into the run directory beside the identity record, and `record export` copies it into the bundle. Verifying that run with the **old** public key works with no extra flag:
```text
$ writ verify runs/keyed-demo--... --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca
OK — verified 1 receipt(s).
Chain head: 0:8ff7d89d3be8e4d659d7cc861615b85237484c9bda4ca6daa190e69d228a60af
Terminal commitment verified — this export cannot be truncated undetected.
Signed by Example Operator (https://operator.example) , key 7c3e2347e1046914 — identity record verified and bound to the chain.
Key chain: reached the signer from the pinned anchor through 1 verified rotation(s).
```
`--rotations ` names a rotation record explicitly, for evidence that doesn't carry its own copy.
## Revocation: a lost or compromised key stops producing evidence
The right order is to rotate first, then revoke the old key, signed by its successor. This example revokes the current key to show what a revoked key does to later evidence:
```text
$ writ keys revoke --key-id 7c3e2347e1046914 --reason "key retired"
Revoked key 7c3e2347e1046914 as of 2026-11-17T00:22:33Z (signed by 7c3e2347e1046914).
appended to /keys/revocations.jsonl
Receipts that key signed after this instant fail `writ verify`; earlier evidence stays valid. Share the revocations file with your verifiers.
WARNING: you revoked the CURRENT key. It can no longer sign receipts or a rotation verifiers will honour — the right order is `writ keys rotate` FIRST, then revoke the old key with the successor. From here, create a fresh key with `writ keys init --out ` and have verifiers pin its pubkey.
```
Revoking a key that isn't the current signer and isn't reachable from it is refused, so a stranger can never revoke your key (exit `2`):
```text
$ writ keys revoke --key-id deadbeefdeadbeef --reason "unrelated key id"
Key deadbeefdeadbeef is not the current key (7c3e2347e1046914), and the current key is not a successor of it per '/keys/rotations.jsonl' (no valid forward rotation chain leads from that key to this one); a revocation must be signed by the revoked key or a successor of it.
```
`writ run` does not check revocation when it signs: a run made with a revoked key still completes. Revocation is enforced when the evidence is **verified**:
```text
$ writ verify runs/keyed-demo--... --pubkey c98f986f72c4fe8716b1b13330025ef900a568d8fbac4cd086c2a686a8df5401
FAILED — 1 problem(s) across 1 receipt(s):
key 7c3e2347e1046914 was revoked at 2026-11-17T00:22:33.5412252Z but 1 receipt(s) (first: sequence 0, occurred 2026-11-17T00:22:40.6554204Z) were signed at/after that instant — not evidence.
```
Exit `5`. `revocations.jsonl` is copied into every run directory made while it exists on disk, and into exported bundles, so this fails without an explicit `--revocations` flag. A verifier who keeps their own copy of your revocations file passes it with `--revocations `.
After revoking the current key, create a new one with `writ keys init --out ` and give its public key to your verifiers.
## Trust-anchor summary
| You pin (`--pubkey`) | What `verify` does |
|---|---|
| The run's signer key | Direct signature check. No rotation walk needed. |
| An **earlier** key in the operator's rotation chain | Walks `rotations.jsonl` forward, hop by hop, each signed by the previous key, until it reaches the run's signer, or fails if it can't. |
| A key that was later revoked | Fails, if any receipt in the chain was signed at or after that key's recorded revocation instant. |
`--require-identity` turns "no identity record present" from a warning into a failure (exit `5`). Use it whenever you need to know which operator signed, not only that a valid signature exists.
## Next steps
- [Run artifacts and export](/docs/guides/run-artifacts-and-export): what a run writes, and what the shareable bundle contains.
- [Security model and preview limitations](/docs/security-and-limitations#signer-identity-is-self-asserted): what a self-signed identity record shows.
==============================================================================
# Run artifacts and export
Source: https://writ.lightningenable.com/docs/guides/run-artifacts-and-export
==============================================================================
# Run artifacts and export
## What a run writes
Every run creates `runs//` (or wherever `work_record.output_dir` / `--output-dir` points) and fills it with, at minimum, the files below. The exception is a run refused before it starts — no `WRIT_ROOT_KEY` with `--production`, a paid mission with no positive `budget.total_sats`, or a `model.endpoint` the URL guard refuses. That run creates no directory and writes no files; the refusal is printed instead.
| File | What it is |
|---|---|
| Named step outputs (e.g. `dossier.md`, `infra.json`) | Whatever each step's `output:` field named. |
| `work-record.jsonl` | The signed, hash-chained receipt chain: one JSON object per line, one per completed capability call. |
| `run.json` | A machine-readable run summary: outcome, spend, receipt count, chain head, signer info, model provider. |
| `report.html` | A human-readable report of the same information. |
| `usage.json` | Model token/cost usage. Written wherever `run.json` is, with zero totals when no model call reported usage (see the [manifest reference](/docs/reference/manifest#model) for which providers report it). |
| `writ.db` | The run's private SQLite database: the ledger, credentials, and audit trail. **Never exported.** |
| `progress.jsonl` | The run's progress journal, which `writ resume` reads to continue the run. |
| `run.lock` | The lock that keeps a second `writ run` or `writ resume` process out of this run while one holds it. |
| `signer-identity.json`, `rotations.jsonl`, `revocations.jsonl` | Copied in when the run used `key-file` or `env` signing: see [Keys and verification](/docs/guides/keys-and-verification). |
| `head-attestation.json` | Present after `writ record publish-head`. |
## Private by default
Everything under `runs//` can carry capability responses and model output that contain private business data. Writ creates the runs root, every run directory, and every file in it **owner-only**: `0700` directories and `0600` files on Linux and macOS, and on Windows an access control list with inheritance removed that grants only the current user. If the file system can't express the restriction, Writ prints a warning to stderr and continues; a completed run is never turned into a failed one over a permissions error.
Sharing a run is therefore a deliberate action.
## `writ record export`
Without `--out`, `record export` prints the signed chain (`work-record.jsonl`) to stdout, one receipt per line, for piping into another tool.
With `--out `, it writes a **shareable bundle** with ordinary file permissions. The bundle holds what a recipient needs to verify the run, and leaves the private working data out. For the key-signed run in [Keys and verification](/docs/guides/keys-and-verification):
```text
$ writ record export keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32 --out share-bundle
Exported run 'keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32' to /share-bundle
work-record.jsonl (1504 bytes, sha256 fa86bd0a321fab11f05de3add6c78c3c1837d2091ffa89ad200ee651ed8cd8c8)
run.json (2115 bytes, sha256 75baefa915634c7c24bde4744ad36123eed0f76c867b17df02f2a255f45f6ea5)
report.html (3776 bytes, sha256 b17704f88a3431762f97ae5219c1a28cb6d5330c0f39936a2ec9b67e40f18b38)
usage.json (182 bytes, sha256 e230184836060050d94f7016905ac25349993f830db241a16e2379a6737d2cae)
signer-identity.json (531 bytes, sha256 a7e7fefe3d966d03e2e2685516f1376bb3248600245affa9364bdb46231d2a07)
manifest.json
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a (1 receipts).
Not included (never exported): writ.db and its sidecars, key material, and step outputs.
Recipient check: writ verify --pubkey --expect-head 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
```
### The bundle contents
| File | What it is |
|---|---|
| `work-record.jsonl` | The signed receipt chain. |
| `run.json` | The machine summary, with the signed terminal commitment `writ verify` checks the chain's end against. |
| `report.html` | The human-readable report. |
| `usage.json` | Model usage. |
| `signer-identity.json` | The signer's public identity record, for a run signed with `key-file` or `env`. |
| `rotations.jsonl`, `revocations.jsonl` | The signer's rotation and revocation records, when the run has them. |
| `manifest.json` | Every other file's name, size, and SHA-256, the chain head, and the recipient's `writ verify` command. |
`manifest.json` lists exactly the files the bundle holds:
```json
{
"runId": "keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32",
"exportedAt": "2026-11-17T00:22:10.5399381+00:00",
"tool": "writ record export",
"receiptCount": 1,
"chainHead": {
"sequence": 0,
"hash": "526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a"
},
"files": [
{"name": "work-record.jsonl", "bytes": 1504, "sha256": "fa86bd0a..."},
{"name": "run.json", "bytes": 2115, "sha256": "75baefa9..."},
{"name": "report.html", "bytes": 3776, "sha256": "b17704f8..."},
{"name": "usage.json", "bytes": 182, "sha256": "e2301848..."},
{"name": "signer-identity.json", "bytes": 531, "sha256": "a7e7fefe..."}
],
"verify": "writ verify --pubkey --expect-head 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a"
}
```
**Never included:** `writ.db` and its sidecar files (the ledger, credentials, and internal audit trail), any private key material, and the step outputs (`dossier.md`, `lookup.json`, and so on). The bundle carries the evidence, not a copy of the run's private working data.
### The recipient's check
A recipient verifies the bundle directory with the bundle and the signer's public key, and no access to your systems. Give them the public key separately, through a channel they already trust (for example, the output of `writ keys show` sent to them directly), never only inside the bundle they are checking:
```text
$ writ verify share-bundle --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca
OK — verified 1 receipt(s).
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
Terminal commitment verified — this export cannot be truncated undetected.
Signed by Example Operator (https://operator.example) , key 48d196ae736139f2 — identity record verified and bound to the chain.
```
For a `dev-ephemeral` run, add `--signer-mode dev-ephemeral`; `verify` then warns that the record is not production evidence.
## Next steps
- [Keys and verification](/docs/guides/keys-and-verification): persistent signing, head attestations, and what `writ verify` shows.
- [Security model and preview limitations](/docs/security-and-limitations#preview-limitations-stated-plainly): the limits of the preview.
==============================================================================
# Settlement
Source: https://writ.lightningenable.com/docs/guides/settlement
==============================================================================
# Settlement
Every capability call that costs sats goes through one settlement pipeline: verify authority, reserve budget, approval gate (if configured), execute, settle or release, sign a receipt. The two `settlement.mode` values differ in whether real money moves.
## `simulated` (default)
```yaml
settlement:
mode: simulated
```
The **entire** pipeline runs (credential minting, budget reservation, payment, settlement, signed receipt) against an in-process L402 endpoint. No wallet, no keys, no network call to a real capability provider. Every artifact from a simulated run is marked `"simulated": true` in its output (see the `infra.json` example in [Your first mission](/docs/getting-started/first-mission#the-outputs)). This is the recommended mode for evaluation, development, and demos, and it's the default if a manifest omits `settlement` entirely.
## `wallet` (real Lightning)
```yaml
settlement:
mode: wallet
```
Wallet mode makes **real Lightning payments** from your own wallet, bounded by the manifest budget. It is opt-in per manifest; nothing in Writ switches it on for you.
### Set up a wallet
Writ finds your wallet from environment variables in the shell that runs `writ run`. Set the variables for one wallet. When several are set, Writ uses the first it finds in this order: LND, NWC, Strike.
| Wallet | Variables |
|---|---|
| LND | `LND_REST_HOST`: your node's REST URL, for example `https://localhost:8080`. `LND_MACAROON_HEX`: a macaroon that can pay invoices, hex-encoded. `LND_TLS_CERT_PATH` (optional): the node's TLS certificate. |
| NWC (Nostr Wallet Connect) | `NWC_CONNECTION_STRING`: the `nostr+walletconnect://` connection string your wallet app creates. `NWC_ENCRYPTION` (optional): `auto` (default), `nip04`, or `nip44_v2`; some wallets need `nip44_v2` and others `nip04`. |
| Strike | `STRIKE_API_KEY`: an API key from your Strike account. |
These values are secrets: keep them out of manifests (Writ refuses to interpolate them) and out of shell history. Give the wallet connection its own spending limit in your wallet app where it offers one, so the most it can spend is bounded outside Writ too. An `OPENNODE_API_KEY` is also detected, but OpenNode returns no payment preimage, so it cannot pay L402 invoices and Writ refuses it before any money moves.
`writ run` prints this warning **before anything executes** whenever a manifest resolves to wallet settlement and it isn't a dry run:
```
WARNING: wallet settlement — this run makes REAL Lightning payments, bounded by the mission budget (100 sats total).
```
A `--dry-run` on a wallet-mode manifest never prints this banner and never touches the wallet; it only plans.
**Preimage requirement:** L402 needs a wallet that returns a **payment preimage** on completion; it is the proof a receipt commits to. LND, NWC (most implementations), and Strike return one.
**The price check happens before money moves.** Every invoice's amount must be strictly positive and at or under both the capability's own ceiling and `budget.per_call_max_sats` before Writ pays it. An amountless, zero, or over-cap invoice is refused, and nothing is sent.
## The model-CLI pre-flight probe {#the-model-cli-pre-flight-probe}
If a manifest declares a paid (`l402-http`) capability, resolves to a CLI-backed model provider (`claude-cli` or `codex` — see the [manifest reference](/docs/reference/manifest#model)), *and* has at least one step that will call the model (an `agent` step, or a `call` to any `internal` capability other than `compose` or `compose.*`), Writ runs a one-time pre-flight probe of that CLI at the very start of the run: a trivial completion using the exact flags and tool restrictions the real call would use, under a 30-second timeout, spending nothing.
Why: without the probe, a broken or unauthenticated CLI would only surface on the run's *first model call* — which, in a mission shaped "paid step first, model step second," is after real sats have already settled. The probe catches that before any capability is invoked:
```
15:33:22 warn: Writ.Engine.Llm.ClaudeCliLlmClient[0] claude CLI exited non-zero: ExitCode=1. Stderr (first 200 chars): ...
```
If the probe fails, the run fails **pre-flight**, before any capability call happens, naming the exit code and a bounded stderr excerpt (never the prompt or response body; see [What the guardrails are designed to do](/docs/security-and-limitations#what-the-guardrails-are-designed-to-do)). A manifest with no paid capability, or one whose steps never call the model (such as the [first mission](/docs/getting-started/first-mission)), skips the probe, so a missing `claude` binary can't fail a mission that never needed it. When the probe can't even start the executable, the run fails with exit `3` and a single line, no stack trace:
```
Pre-flight check failed: model provider 'claude-cli' needs the 'claude' executable, which could not be started (not installed, or not on PATH). Install it and make sure it is on PATH, or use the HTTP API instead: set `model.provider: anthropic` and export ANTHROPIC_API_KEY (removing the `model:` block does the same). No capability was invoked and nothing was settled.
```
The same step-aware rule applies to the service hosts: a catalog that serves only `compose` and paid capabilities does not probe the CLI at startup.
:::note claude-cli on Windows
On Windows, Writ launches the target of npm's `claude.cmd` shim directly, without `cmd.exe`, so `claude-cli` steps run there with multi-line arguments intact. The `claude --version` command must work in the shell that runs Writ.
:::
## Ambiguous payment outcomes {#ambiguous-payment-outcomes}
Wallet-mode payments are the one place Writ can't retry or roll back on its own. The invoice's payment hash is read *before* paying (an invoice with no payment hash is never paid). If the wallet call afterward times out, errors, or returns proof Writ can't use, Writ does **not** assume the money stayed put, because it might not have.
Instead:
1. The budget hold is kept as **`pending_reconciliation`**, tagged with the invoice's payment hash.
2. The run halts and exits **`7`**, naming the invocation and the payment hash.
3. Nothing is released, and nothing is double-counted as spent, until you run `writ reconcile`.
```
Invocation 3 is still pending reconciliation (payment hash 1b44320d..., 25 sats held):
Check the payment in your wallet by that hash, then run: writ reconcile --invocation 3 --resolve paid|not-paid
```
`writ reconcile` first asks the wallet itself to look the payment up by hash: LND and NWC can usually answer; Strike's API has no lookup of an outgoing payment by hash, so a Strike hold needs your explicit `--resolve paid|not-paid` attestation, and `--resolve not-paid` on it also needs `--allow-unconfirmed-not-paid`, which the audit log records. See [Approvals and budgets](/docs/guides/approvals-and-budgets#reconciling-a-pending-wallet-payment) for the walkthrough. `simulated` mode never produces this state.
## `--production`
`writ run --production` takes a fail-closed posture: no `dev-ephemeral` signer (a persistent `key-file` or `env` signer and its identity record are required), `WRIT_ROOT_KEY` must be set, and wallet settlement is required. Use it for runs that spend real money and whose evidence you keep.
## Next steps
- [Approvals and budgets](/docs/guides/approvals-and-budgets): the human gate, and reconciling a stuck payment.
- [Keys and verification](/docs/guides/keys-and-verification): persistent signer identity, which `--production` requires.
- [Security model and preview limitations](/docs/security-and-limitations): SSRF guards, model-CLI sandboxing, and the manifest's semi-trusted-input boundary.
==============================================================================
# Introduction
Source: https://writ.lightningenable.com/docs/intro
==============================================================================
# Introduction to Writ
:::caution Private preview
Writ is in private preview. To request access, write to [support@lightningenable.com](mailto:support@lightningenable.com?subject=Writ%20private%20preview). The core loop works end to end and is covered by an extensive test suite. This documentation describes the preview behavior, captured directly from the running CLI. See [Security model and preview limitations](/docs/security-and-limitations) for what's still open.
:::
**Writ is bounded autonomy for agents that spend money.** It's a self-hosted .NET runtime that runs an agent *mission* under a cryptographic writ — a budget cap, a scope list, a deadline, and delegation rules, enforced at the credential layer — paying for the capabilities it needs over Lightning ([L402](https://github.com/lightninglabs/L402) / HTTP 402) as it works, and producing a **signed, independently verifiable work record** when it's done.
You bring the model and the task. Writ supplies the parts that make letting an agent spend money safe: **pay, bound, delegate, and prove.**
:::info Writ does not hold funds
Writ does not hold funds. Your own wallet (LND, NWC, or Strike) makes the Lightning payments; the capability providers settle directly with that wallet. Writ issues and verifies *authority*, and records *what happened* — it never sits in the money path.
:::
## Four words you'll see everywhere
- **Writ**: historically, a sealed written order granting someone authority to act. Here, the cryptographic credential a mission runs under.
- **Sat (satoshi)**: the smallest unit of bitcoin, one hundred-millionth of a coin. Budgets and prices in Writ are in sats. In the default `simulated` mode, no sats move.
- **L402**: a protocol in which a web API answers `HTTP 402 Payment Required` with a Lightning invoice, and the client pays per call. Writ pays these on your mission's behalf.
- **Macaroon**: a bearer credential whose restrictions ("caveats") can only be added to, never removed. Writ's delegated credentials are macaroons, which is why a sub-agent's authority can only narrow.
## Why Writ exists
Agents can now call APIs, buy data, and hire other agents. What's missing is the seatbelt: a way to let an agent act on its own *and* keep it from overspending or wandering outside the job, and leaves evidence you can check without trusting its own report.
Writ closes that gap with three ideas:
- **Authority that only narrows.** When a mission delegates a sub-task, the sub-agent's credential can only ever carry *less* authority than its parent — a smaller budget slice, a narrower capability, a shorter expiry, one less level of delegation. Widening isn't a policy choice you could get wrong; macaroon caveats intersect, and an unknown caveat fails closed.
- **A budget that's real and atomic.** Every sat is reserved against the credential-chain root (the top of the chain of delegated credentials) before a call, then settled or released after, so concurrent calls are checked against one shared cap. A revoked credential stops spending immediately, and the revocation cascades to the whole delegated subtree.
- **A work record you can verify offline.** Every completed action appends a BIP-340–signed, hash-chained receipt committing to what was authorized, what it cost, and that it completed — never a raw prompt, key, or preimage. Anyone with the signer's public key can run `writ verify` and check the chain with zero access to the machine that ran it.
Sub-cent per-call settlement over Lightning, with no processor fee (only the network's routing fee, which your wallet pays outside the budget), makes a 3-sat data call economical.
## Who this documentation is for
This site covers two audiences:
- **People** who run Writ, author mission manifests, and operate keys and approvals. Start at [Get access](/docs/getting-started/installation).
- **Agents** — coding assistants and autonomous agents that need to set up and run Writ with little human intervention. Start at [For agents](/docs/for-agents), which points at the [llms.txt index](pathname:///llms.txt), the [machine-readable agent manifest](pathname:///.well-known/writ-agent.json), and the Claude Skills shipped alongside Writ.
## The shape of a mission
A mission is one YAML file: a goal, a budget, the capabilities the mission is allowed to call, one or more delegated workers, a settlement mode, and how the work record gets signed.
```yaml
mission:
name: vendor-dossier
goal: "Produce a due-diligence dossier on {{target_name}} ({{target_domain}})"
budget:
total_sats: 200 # cumulative, enforced atomically at the credential-chain root
per_call_max_sats: 25 # ceiling for any single call
settlement:
mode: simulated # simulated (zero-config) | wallet (real Lightning)
capabilities:
- { id: dns.whois, kind: l402-http, base_url: https://…/dns-and-whois, path: /whois, max_sats_per_call: 5 }
- { id: compliance.search, kind: l402-http, base_url: https://…/compliance-suite, path: /search, max_sats_per_call: 12 }
- { id: compose.dossier, kind: internal }
workers:
- name: infra-researcher # gets a delegated credential scoped to DNS only
scope: [dns.whois]
budget_sats: 40
steps: [{ type: call, capability: dns.whois, input: { domain: "{{target_domain}}" } }]
work_record:
signing: dev-ephemeral
output_dir: runs/
```
The runner mints a root credential bounded by the manifest, delegates a strictly-narrower child credential to each worker, runs the steps — every capability call goes through one pipeline (verify authority → reserve budget → approval gate → execute → settle-or-release → sign a receipt) — and writes the outputs, the signed work record, and a human-readable report to `runs//`.
Continue to [Get access](/docs/getting-started/installation), or jump straight to [Your first mission](/docs/getting-started/first-mission) for a full walkthrough with real command output.
## Next steps
- [Get access](/docs/getting-started/installation) — request access and confirm the `writ` tool works.
- [Your first mission](/docs/getting-started/first-mission) — a complete, simulated, end-to-end run.
- [Manifest reference](/docs/reference/manifest) — every field a mission file can declare.
- [Command reference](/docs/reference/commands) — every `writ` command, its options, and its exit codes.
- [For agents](/docs/for-agents) — how an agent sets up and drives Writ on its own.
==============================================================================
# Service, MCP, and HTTP reference
Source: https://writ.lightningenable.com/docs/reference/agent-api
==============================================================================
# Service, MCP, and HTTP reference
A mission manifest decides the order of the work. When your agent host wants to decide that itself, the same engine is available three ways. All three share one authority engine, one budget ledger, one invocation pipeline, and one signed receipt chain, so a host enforces the same bounds and keeps the same record that a mission run does.
| Surface | How you reach it | Authentication |
|---|---|---|
| `Writ.Service` | A .NET class library: `IWritService` | In-process |
| `writ-mcp` | An MCP server over stdio | The process boundary; the role is set by the launch command |
| `writ-api` | JSON endpoints under `/v1`, bound to loopback by default | `Authorization: Bearer `, one token per role |
`Writ.Service`, `writ-mcp`, and `writ-api` are separate programs from the `writ` CLI: see [Writ's programs](/docs/getting-started/installation#writs-programs). The operator commands on this page (`writ issue`, `writ approvals`, `writ revoke`, and `writ reconcile` with `--service-db`) are part of the `writ` CLI.
A credential (a *writ*) crosses every surface as an opaque string. It is a bearer token: it authorizes spend up to its bounds, so hold it like one. No result ever echoes it back except the one returned by issue or delegate.
## Roles
A service host serves two roles.
- **Agent**: runs capability calls under a writ it holds, asks what a writ can still spend, narrows its writ for a sub-agent, revokes a writ it delegated, and reads the host's status, receipts and pending approvals. It reads the host's own workspace, and any workspace where it presents a live writ. It verifies receipt chains.
- **Operator**: everything the agent does, plus issuing root writs, approving and denying held spends, revoking any writ, reconciling payments whose outcome is unknown, and reading any workspace.
A writ comes from the operator, and a spend over a threshold waits for the operator's decision.
### `writ-mcp`
`writ-mcp` serves the agent role. Add `--role operator` to its launch command for an operator's own client; that adds `writ_issue`, `writ_approve`, `writ_deny`, `writ_revoke`, `writ_reconciliations` and `writ_reconcile`. The role is set only by the launch command, never by an environment variable.
On an agent-role server, a call to one of those six tools returns `ok: false`, `errorCode: "operator_only"`, `retry: "final"`, and `operatorCommand`, the CLI line the operator runs instead. A read that names another workspace without presenting a writ returns `errorCode: "workspace_not_allowed"`. `writ_status` reports the server's `role` and, for the agent role, a `bootstrap` line that says how the operator issues a writ.
### `writ-api`
`writ-api` takes one token per role.
| Variable | Reaches |
|---|---|
| `WRIT_API_AGENT_TOKEN` | The agent routes (marked *agent* below), with reads in the host's own workspace and in any workspace where the caller presents a live writ. |
| `WRIT_API_OPERATOR_TOKEN` | Every route. |
Both tokens are compared in constant time on every request. The agent token on an operator route gets `403` with `errorCode: "operator_only"`, `operatorRoutesEnabled`, and `operatorCommand`; on a read of another workspace without a writ it gets `403` with `errorCode: "workspace_not_allowed"`. The host starts only with at least one token, with two different tokens, and with at most one of `WRIT_API_TOKEN` and `WRIT_API_AGENT_TOKEN`.
A host configured with only `WRIT_API_TOKEN` uses it as the agent token, and its operator routes answer `403 operator_only` with `operatorRoutesEnabled: false` (the startup log says so). To turn the operator routes on, set `WRIT_API_OPERATOR_TOKEN` to a different value and send it for issuing, approving, denying, revoking and reconciling.
### The operator CLI
The operator also acts on the host's database directly:
```bash
writ issue --service-db ./.writ/writ.db --principal researcher --budget 200 --per-call 25
writ approvals list --service-db ./.writ/writ.db
writ approvals approve 3 --service-db ./.writ/writ.db
writ revoke 1 --service-db ./.writ/writ.db
writ reconcile --service-db ./.writ/writ.db --invocation 12 --resolve not-paid
```
Run every host that shares one database (`writ-mcp` and `writ-api` on the same `WRIT_DB_PATH`) with the same `WRIT_ROOT_KEY`. Run these with the host's settings in the environment, including its `WRIT_ROOT_KEY`. Each command first checks that key against the database: the host records its key there when it starts, so start the host once before the first command. The commands work on a database at this build's schema version and do not upgrade it; to upgrade, stop the host and run `writ db upgrade`. `writ issue` prints the writ's credential for you to hand to the agent. `operatorCommand` and the agent's next steps write the database path as ``.
### Setting up the host
The roles hold when the operator's configuration stays the operator's:
- Run the host under a different OS account from the agent, and keep the host's database, its `WRIT_ROOT_KEY`, and its launch configuration readable only by that account.
- Give the agent the agent token or an agent-role server entry, and keep the operator token and any `--role operator` entry in the operator's own client.
- Set the same persistent `WRIT_ROOT_KEY` for the host and for the operator CLI.
- An agent-role caller reads every approval and receipt of the host's own workspace (`WRIT_WORKSPACE`). To keep agents from reading each other's records, issue their writs in other workspaces; each agent then reads its own records by presenting its writ.
## Operations
| Operation | Role | `IWritService` | MCP tool | HTTP |
|---|---|---|---|---|
| What this host serves | agent | `Describe` | `writ_status` | `GET /v1/status` |
| Mint a root writ | operator | `IssueCredentialAsync` | `writ_issue` | `POST /v1/credentials` |
| Narrow a writ for a sub-agent | agent | `DelegateAsync` | `writ_delegate` | `POST /v1/credentials/delegate` |
| What a writ can still spend | agent | `GetBudgetAsync` | `writ_budget` | `POST /v1/credentials/budget` |
| Run one capability call | agent | `InvokeAsync` | `writ_invoke` | `POST /v1/invocations` |
| Revoke a writ and its subtree | operator | `RevokeAsync` | `writ_revoke` | `POST /v1/credentials/{id}/revoke` |
| Revoke a writ you delegated, or your own | agent | `RevokeDelegatedAsync` | `writ_revoke_delegated` | `POST /v1/credentials/revoke-delegated` |
| The delegation chain, as bounds | operator | `GetChainAsync` | — | `GET /v1/credentials/{id}/chain` |
| The signed work record | agent | `GetReceiptsAsync` | `writ_receipts` | `GET /v1/receipts`; with a writ, `POST /v1/credentials/receipts` |
| Verify a receipt chain | agent | `VerifyChainAsync` | `writ_verify` | `POST /v1/receipts/verify` |
| Spends waiting on a human (read-only) | agent | `ListApprovalsAsync` | `writ_approvals` | `GET /v1/approvals`; with a writ, `POST /v1/credentials/approvals` |
| Approve or deny one | operator | `ApproveAsync` / `DenyAsync` | `writ_approve` / `writ_deny` | `POST /v1/approvals/{id}/approve` / `deny` |
| Payments waiting on reconciliation | operator | `ListReconciliationsAsync` | `writ_reconciliations` | `GET /v1/reconciliations`, `GET /v1/reconciliations/{invocationId}` |
| Reconcile one | operator | `ReconcileAsync` | `writ_reconcile` | `POST /v1/reconciliations/{invocationId}/resolve` |
`GET /health` needs no token. `IWritService` itself has no roles: it is a library, and the host that wraps it decides who reaches what.
Every business failure is a typed result, never an exception: `ok: false`, a stable `errorCode`, and a caller-safe `error` sentence. Over HTTP the same result arrives as `application/problem+json` with the `errorCode` extension.
| `errorCode` | Meaning | HTTP status |
|---|---|---|
| `invalid_request` | The request is malformed. Nothing was created or spent. | 400 |
| `unknown_capability` | The capability is not in this host's catalog. | 404 |
| `not_found` | The named credential or approval does not exist here, or the invocation is not pending reconciliation. | 404 |
| `denied` | Authority verification refused the call, or the writ you presented is not a live writ in that workspace. | 403 |
| `operator_only` | The action needs the operator role and the caller holds the agent role. Nothing was done; `operatorCommand` names the command the operator runs instead. | 403 |
| `workspace_not_allowed` | An agent-role read named a workspace other than the host's own and presented no writ. Nothing was read. | 403 |
| `budget_exceeded` | The chain-wide budget reserve failed. Nothing ran or was paid. | 409 |
| `approval_required` | The spend needs a human. Nothing ran or was paid. | 202 (not an error) |
| `execution_failed` | The capability call failed. | 502 |
| `replayed` | The payment reference was already settled. | 409 |
| `pending_reconciliation` | The wallet outcome is unknown and the hold is retained. Do not retry. | 409 |
| `widening_rejected` | A delegation asked for more than its parent holds. | 400 |
| `conflict` | This exact credential already exists. | 409 |
| `in_progress` | A call with this idempotency key is still in flight. Nothing new was reserved or paid. | 409 |
| `idempotency_conflict` | This idempotency key was already used for a different request. Nothing ran. | 422 |
| `verification_failed` | A receipt chain did not verify. | 422 |
| `internal_error` | Something unexpected failed; the detail is logged host-side. | 500 |
## Acting on a writ you hold
Four agent operations take the writ you hold as `credential` and act only on that writ and the writs delegated beneath it: three reads, which work in any workspace where the writ is live, and revoking a writ you delegated. Writ verifies the writ in full on every call: its signature under the host's key, its workspace, every expiry on it and its chain, and that nothing on its chain is revoked.
### Reading your own records
Pass `credential` (and `workspace`, when the writ is not in the host's own workspace) to `writ_receipts`, `writ_approvals` or `writ_verify`. Over HTTP, send it in a `POST` body to `/v1/credentials/receipts`, `/v1/credentials/approvals` or `/v1/receipts/verify`.
| Read | What it covers |
|---|---|
| `writ_receipts` | The receipts of your writ and of every writ delegated beneath it, in chain order, with `scope: "writ"`. Each receipt carries every field of the unscoped view; `previousReceiptHash` is present when the receipt before it on the chain is also yours (or it is the first receipt of the workspace), and omitted when that receipt belongs to another writ. A sibling's, a parent's or another principal's receipts are not included. The exportable JSONL and the chain's terminal are the whole workspace's, so they are not returned here. |
| `writ_approvals` | The pending requests raised under your writ or a writ beneath it. |
| `writ_verify` | Writ checks the workspace's whole chain and answers for your receipts: `receiptCount` and the terminal are your last receipt, a pinned head names your last receipt, and problems in other writs' receipts appear as one count without their ids. `jsonl` and `publicKeyHex` cannot be combined with `credential`. |
Sequence numbers are the workspace chain's own. A writ that does not verify as a live writ of the named workspace gets `denied` with one message, the same whether the workspace exists or not.
### Revoking a writ you delegated
`writ_revoke_delegated` (HTTP `POST /v1/credentials/revoke-delegated`) takes the writ you hold as `credential` and the `credentialId` of the writ to revoke: one that `writ_delegate` returned for a writ beneath yours, or your own writ's id. The target and every writ beneath it stop verifying at once, exactly as with the operator's revoke. A sibling, an ancestor, another principal's writ and an id that does not exist all get the same `denied` answer. Revoking an already revoked writ answers `ok: true` with `changed: false`. The signed audit event names your writ (principal, credential id, macaroon hash).
## Reconciliation on a service host
When a wallet payment's outcome is unknown, the call keeps its budget hold and waits for the operator. The operator role resolves it in process with `writ_reconciliations` and `writ_reconcile` (HTTP `GET /v1/reconciliations` and `POST /v1/reconciliations/{invocationId}/resolve` with the operator token), or out of band with `writ reconcile --service-db`. Both paths call the same reconciliation service, so the same rules apply.
- Without `resolve`, the host asks its wallet about the payment by hash. A simulated host has no wallet, and `walletLookupAvailable` in the list says whether this host has one.
- With `resolve: "paid"` or `"not-paid"`, your attestation decides it and is recorded in the signed audit log. Check the payment in your wallet by its hash first. Pass `decidedBy` (a name of at most 128 characters, no control or line-separator characters) to record who decided; the audit event's actor is then `host-operator:`.
- `"not-paid"` on a hold with a payment hash follows the rule of [`writ reconcile`](/docs/reference/commands#writ-reconcile): the host's wallet must report the payment failed. Otherwise the answer carries `refusalCode` (`wallet_reports_paid`, `wallet_cannot_confirm` or `no_lookup_wallet`) and nothing changes. When you have checked the payment yourself and it failed, add `allowUnconfirmedNotPaid: true`, as `--allow-unconfirmed-not-paid` does; `walletCheck` in the answer and the audit event records which way it was accepted.
- A recorded payment proof settles the call as paid at the proven amount and refuses `not-paid`.
- A row that stays unresolved answers `pending_reconciliation` (HTTP `409`) and keeps its hold.
- A resolve is safe to retry: nothing moves twice. Once a row is resolved it is no longer pending, so a second resolve answers `not_found`.
- `proofJournalPendingLines` counts proofs in the host's proof journal that are not yet applied. Apply them with `writ reconcile --service-db --apply-proof-journal` before you resolve a row as not paid.
## Remaining budget
An agent told to "stop when the budget runs out" asks what remains instead of learning it from a refusal. The query is read-only: it reserves nothing and changes nothing.
You present the writ itself, so you can only ask about a writ you hold. Writ checks that it is live first. A writ that is unregistered, revoked, expired, or whose chain is broken is refused with `denied`, the same as an invocation would be.
Every number takes the **tightest value across the whole delegation chain**. A reserve has to fit on every capped hop, so a sibling that spent your parent's budget shrinks what you can do even when your own slice is untouched.
| Field | Meaning |
|---|---|
| `remainingSats` | The minimum, over every capped link, of `limit − reserved − spent`. What your next calls can still reserve in total. `null` when no link declares a total cap. |
| `depth`, `bindingDepth` | Your writ's depth in its chain and the depth of the link that sets `remainingSats` (0 = the root). `bindingIsAncestor` is `true` when a parent binds, not your writ. Links are named by depth only: an ancestor's identity and per-hop detail are on the operator-facing chain endpoint (`GET /v1/credentials/{id}/chain`), not in this answer. |
| `totalLimitSats`, `spentSats`, `reservedSats` | The binding link's own numbers. A parent's `spentSats` includes spend by every writ delegated beneath it. |
| `overCapSats` | Sats that moved under the binding link beyond `spentSats`: a payment proven after its hold was released, when the link's cap was already full. `spentSats + overCapSats` is what moved. Usually `0`; `null` when no link declares a total cap. Every link with room is charged the full proven amount, so only a full link reports over-cap spend. |
| `perCallMaxSats` | The tightest per-call cap on the chain, set by the link at `perCallBindingDepth`. A capability's own price ceiling can be lower still: see `writ_status`. |
| `maxNextCallSats` | `min(remainingSats, perCallMaxSats)`: the most one next call can reserve. |
| `expiresAt` | The earliest expiry on the chain, set by the link at `expiryBindingDepth`. |
| `own` | Your writ's own link: `limitSats`, `reservedSats`, `spentSats`, `remainingSats`, `perCallMaxSats`, `expiresAt`, and `overCapSats`. |
Over HTTP the query is a `POST` with the credential in the body. It is never a `GET`, because a bearer credential in a URL ends up in proxy and access logs.
```bash
curl -s -X POST http://127.0.0.1:8787/v1/credentials/budget \
-H "Authorization: Bearer $WRIT_API_AGENT_TOKEN" -H "Content-Type: application/json" \
-d '{"credential": ""}'
```
```json
{
"ok": true,
"credentialId": 2,
"totalLimitSats": 100,
"spentSats": 30,
"reservedSats": 0,
"overCapSats": 0,
"remainingSats": 70,
"depth": 1,
"bindingDepth": 0,
"bindingIsAncestor": true,
"perCallMaxSats": 25,
"perCallBindingDepth": 1,
"maxNextCallSats": 25,
"expiresAt": "2026-11-13T18:15:00+00:00",
"expiryBindingDepth": 1,
"own": { "limitSats": 80, "reservedSats": 0, "spentSats": 0, "remainingSats": 80, "perCallMaxSats": 25, "expiresAt": "2026-11-13T18:15:00+00:00", "overCapSats": 0 }
}
```
In this example the writ's own slice is 80 sats and untouched, but a sibling spent 30 of the parent's 100, so the parent binds at 70.
## Refusal reason codes
Every non-success invoke result carries two codes. `errorCode` is the coarse class in the table above. `reasonCode` names the exact refusal, one code per refusal path, so an agent with no human in the loop can decide what to do without parsing the `error` sentence. `retry` says what that decision is:
- **`final`**: this writ will not get this call through, whatever you retry. Stop, or ask the operator.
- **`retry_with_change`**: worth a different attempt. Try another capability or provider, a cheaper call, or the right workspace.
- **`retry_later`**: worth the same call later, after a human approves or a transient fault clears.
The MCP tool returns `reasonCode` and `retry` beside `errorCode`. Over HTTP they are `reasonCode` and `retry` extensions on the problem+json body (with `invocationId` and `receiptId` when there is one); a `202` approval answer carries them in its body. A success has neither. Codes are stable: a published code is never renamed or reused.
| `reasonCode` | `errorCode` | `retry` | Meaning |
|---|---|---|---|
| `invalid_request` | `invalid_request` | `retry_with_change` | The request is malformed: a missing credential or capability, bad query JSON, a negative threshold. |
| `capability_not_served` | `unknown_capability` | `retry_with_change` | The capability is not in this host's catalog. Pick one from `writ_status`. |
| `credential_malformed` | `denied` | `final` | The credential cannot be parsed, or one of its caveats is malformed. |
| `credential_signature_invalid` | `denied` | `final` | The credential does not verify under this host's authority key: tampered, minted by another host, or minted before an ephemeral-key restart. |
| `workspace_mismatch` | `denied` | `retry_with_change` | The credential belongs to a different workspace. |
| `principal_mismatch` | `denied` | `final` | The credential's principal caveats are missing or contradict each other. |
| `capability_out_of_scope` | `denied` | `retry_with_change` | The capability is outside the writ's scope. Call something within it. |
| `capability_not_in_set` | `denied` | `retry_with_change` | The capability is not in the writ's permitted capability set (`capability_in`). Call one that is. |
| `capability_set_invalid` | `denied` | `final` | The writ's permitted capability set (`capability_in`) is malformed. |
| `path_out_of_scope` | `denied` | `retry_with_change` | The resource path is outside the writ's path caveat. |
| `credential_expired` | `denied` | `final` | The credential's own expiry has passed. |
| `unknown_caveat` | `denied` | `final` | The credential carries a caveat this host does not recognize. |
| `reserved_caveat` | `denied` | `final` | The credential carries a reserved caveat (`condition_hash`, `bond_id`) that cannot be satisfied yet. |
| `authority_check_error` | `denied` | `retry_later` | The authority check itself could not run on the host. |
| `exceeds_total_cap` | `denied` | `retry_with_change` | The call's price ceiling is larger than the writ's whole budget. Choose a cheaper capability. |
| `exceeds_per_call_cap` | `denied` | `retry_with_change` | The call's price ceiling is larger than the writ's per-call cap. |
| `credential_unregistered` | `denied` | `final` | This host never registered the credential. |
| `credential_chain_broken` | `denied` | `final` | The delegation chain does not reach a genuine root. |
| `credential_revoked` | `denied` | `final` | The writ, or an ancestor, was revoked. |
| `credential_chain_expired` | `denied` | `final` | The writ, or an ancestor, has expired according to the host's records. |
| `negative_ceiling` | `denied` | `final` | The host derived a negative price ceiling: a misconfigured capability. |
| `approval_required` | `approval_required` | `retry_later` | The spend needs a human. Retry the same call after the request in `approvalRequestId` is approved. |
| `approval_expired` | `approval_required` | `retry_later` | The approval expired before it was used. A fresh request is pending; retry after it is approved. |
| `budget_exhausted` | `budget_exceeded` | `retry_with_change` | Some capped link of the chain has less left than this call's ceiling. A cheaper call may still fit: check `writ_budget`. |
| `reserve_per_call_cap` | `budget_exceeded` | `retry_with_change` | The call's ceiling exceeds the tightest per-call cap the host records for the chain. |
| `reserve_chain_revoked` | `budget_exceeded` | `final` | A writ on the chain was revoked between verification and the reserve. |
| `reserve_chain_expired` | `budget_exceeded` | `final` | A writ on the chain expired between verification and the reserve. |
| `reserve_chain_broken` | `budget_exceeded` | `final` | The chain, or a capped link's budget account, could not be established at reserve time. |
| `reserve_conflict` | `budget_exceeded` | `retry_later` | A concurrent attempt moved the invocation first. |
| `reserve_store_error` | `budget_exceeded` | `retry_later` | The reserve hit a database error and rolled back. |
| `executor_threw` | `execution_failed` | `retry_later` | The executor failed unexpectedly. Nothing was paid. |
| `destination_blocked` | `execution_failed` | `final` | The SSRF guard refused the capability's endpoint (a private, loopback, or metadata address). |
| `destination_unresolved` | `execution_failed` | `retry_later` | The capability's endpoint host could not be resolved (DNS) at call time. Likely transient. Nothing was paid. |
| `host_error` | `internal_error` | `final` | The host failed unexpectedly; the detail is logged host-side. You cannot know whether it paid: check `writ_budget` and `writ_receipts`, or re-send it with the SAME idempotency key to read its outcome. Never re-send it without a key. |
| `capability_unroutable` | `execution_failed` | `final` | The capability has no usable endpoint or internal route on this host. |
| `provider_unreachable` | `execution_failed` | `retry_later` | The provider could not be reached. Nothing was paid. |
| `provider_error` | `execution_failed` | `retry_later` | The provider answered with an error status or a redirect. Nothing was paid. |
| `payment_challenge_invalid` | `execution_failed` | `retry_with_change` | The provider answered 402 without a payment challenge Writ can read. Try another provider. |
| `price_exceeds_ceiling` | `execution_failed` | `retry_with_change` | The provider's invoice is above this call's ceiling (the lower of the capability's price and the writ's per-call cap). Refused before paying. |
| `payment_refused` | `execution_failed` | `retry_with_change` | The payment was refused before anything was sent: an unreadable amount, no payment hash, or a wallet that cannot return a preimage. |
| `model_call_failed` | `execution_failed` | `retry_later` | An internal model step failed. |
| `execution_failed` | `execution_failed` | `retry_later` | The executor reported a failure it did not classify. Nothing was paid. |
| `payment_outcome_unknown` | `pending_reconciliation` | `final` | The wallet outcome is unknown and the hold is kept. Money may have moved: do not retry. The operator reconciles it. |
| `paid_execution_failed` | `execution_failed` | `final` | The payment settled but the capability did not deliver. The spend is in the work record; do not retry blindly. |
| `payment_replayed` | `replayed` | `final` | Another invocation already settled this payment reference. No second spend. |
| `settlement_rejected` | `execution_failed` | `retry_later` | The ledger refused to settle a call that charged nothing; its hold was released. |
| `idempotency_in_progress` | `in_progress` | `retry_later` | The call with this idempotency key is still in flight: executing, reserved, waiting for a human, or pending reconciliation. Retry the same call with the same key later. |
| `invocation_abandoned` | `execution_failed` | `final` | The keyed call was abandoned before it reserved any budget (its process went away) and, after an hour, was resolved as not paid. A new key may attempt the work again. |
| `reconciliation_required` | `pending_reconciliation` | `final` | The keyed call holds budget for a payment whose outcome is unknown (an unknown wallet outcome, or a reservation stuck for 30 minutes). An operator must reconcile it; do not attempt the work again under any key until then. |
| `reconciled_not_paid` | `execution_failed` | `final` | A replayed call whose unknown payment an operator or wallet later reconciled as not paid; its hold was returned. `retryWithNewKey` is `true`. |
| `operator_discarded` | `executed` or `execution_failed` | `final` | A replayed call whose work record the operator discarded (`writ outbox discard`). The call ran, and paid when `paid` says so; `receiptEmitted` is `false`: the chain holds a signed `work_record_discarded` record for it, not a work record. Do not retry it under any key. |
| `outcome_unknown` | `execution_failed` | `final` | A replayed call finished but its outcome was never recorded and no receipt says how it ended. `paid` and `paidSats` come from the ledger; when it paid, never attempt the work again. |
| `idempotency_key_reused` | `idempotency_conflict` | `retry_with_change` | This idempotency key was already used for a different request under this writ. Use a new key for a new request. |
### On the signed record
A refusal recorded with `recordDenials` (a "denied" work-record receipt) also commits its `reasonCode` into the signed receipt. Such a receipt identifies itself as protocol version `writ.execution-receipt/2` (signing domain tag `writ.execution-receipt.v2`): the version-1 format plus one trailing canonical field, `reasonCode`. Every other receipt is minted as `writ.execution-receipt/1`. Changing or stripping the code, or relabelling the version, breaks the signature.
Receipt result codes: `completed`, `paid_execution_failed` (paid, then the capability failed), `denied` (a recorded refusal, with its `reasonCode`), and `work_record_discarded`. A `work_record_discarded` receipt (reason code `operator_discarded`, protocol version 2) is not a work record: it is the host's signed statement that the operator discarded the work record of that invocation with `writ outbox discard`. It names the invocation, capability, principal and the payment hash the ledger recorded; its input, output and policy hashes are SHA-256 of the empty string and carry no information. `writ_receipts` lists it; an invoke replayed by its idempotency key answers with `reasonCode` `operator_discarded` and `receiptEmitted` `false`.
**Verifier version.** `writ verify` in Writ 0.1.0 checks both receipt versions.
## Idempotent retries
An agent that times out or loses a response cannot know whether its call ran. Without protection, retrying it pays a fresh invoice. Send an **idempotency key** and reuse it on every retry of the same call, and a retry never pays twice.
| Surface | How you send it |
|---|---|
| `IWritService` | `InvokeRequest.IdempotencyKey` |
| MCP | the `idempotencyKey` argument of `writ_invoke` |
| HTTP | an `Idempotency-Key` request header on `POST /v1/invocations` (exactly one) |
A key is 1 to 128 printable ASCII characters with no spaces; a UUID you generate per unit of work is ideal. It is scoped to the writ that presents it, so two writs can use the same key independently. Writ binds the key to a fingerprint of the request: the capability, resource path, query, body, purpose, and the derived price ceiling. A JSON body is compared in canonical form (member order, whitespace, and number spelling such as `1` versus `1.0` do not matter), so re-serializing the same request on a retry is safe; a body that is not JSON is compared byte for byte. Run id, approval threshold, and `recordDenials` are not part of it.
What a repeat with the same key returns:
| The original call | The repeat returns | Reserved, executed, or paid again? |
|---|---|---|
| Finished (succeeded, refused after authorization, failed, or replayed) | The original `outcome`, `reasonCode`, `invocationId`, `paidSats`, and receipt id, with `idempotentReplay: true`. The output body is **not** stored, so `output` is `null` on a replay. | No |
| Still in flight: executing or reserved | `errorCode: in_progress`, `reasonCode: idempotency_in_progress`, the `invocationId`. Retry later with the same key. | No |
| Its payment outcome is unknown (pending reconciliation), or it sat reserved for 30 minutes (the operator resolves it with `writ_reconcile` or `writ reconcile --service-db`; agents cannot) | `errorCode: pending_reconciliation`, `reasonCode: reconciliation_required`. The hold is kept and an operator must reconcile; a stale reservation is moved to reconciliation, never released by age. Do not attempt the work under any key until then. | No |
| Its process went away before it reserved anything, over an hour ago | The replay `reasonCode: invocation_abandoned`, `paid: false`, `retryWithNewKey: true`. Nothing can have been paid: a payment needs a reservation first. | No |
| Waiting for a human approval | `in_progress` with the `approvalRequestId` to resolve. Once a human approves, the same call with the same key resumes that same invocation and runs once. | No, until approved |
| Approval denied or expired | A fresh approval request bound to the same invocation (`approval_required`). Never a second invocation. | No |
| The key was used for a different request | `errorCode: idempotency_conflict`, `reasonCode: idempotency_key_reused`. | No |
A replay is the key's permanent answer, so on a non-success replay `retry` is always `final`, whatever the original reason, and a second field says what to do next:
- **`retryWithNewKey: true`**: the ledger proves the original paid nothing (it ended without settling a payment). You may attempt the work again under a NEW key; read `reasonCode` first, because the same request may fail the same way.
- **`retryWithNewKey: false`**: money moved or may have moved. Do not attempt the work again under any key. Read `writ_receipts` and `writ_budget`, or ask the operator.
`paid` and `paidSats` on a replay come from the ledger as well as the recorded outcome, so a call whose recording was lost (the process died after paying) still reads as paid, with `reasonCode: outcome_unknown`.
**A payment proof always wins.** When the paid capability returns a proof of payment (a preimage that opens the invoice's payment hash), Writ records the hash and the proven amount on the invocation and makes the ledger reflect exactly that amount as spent, whatever happened to the invocation meanwhile: still reserved, routed to reconciliation, reconciled by an operator as paid at the full hold (the excess is returned) or as not paid (a late settlement charges it again, audited and naming that reconciliation), or abandoned. From then on every answer for that invocation and its key says `paid` with that amount and `retryWithNewKey: false`. If the ledger cannot apply the proof at that moment, the call answers `paid: true`, `paidSats`, `reasonCode: reconciliation_required`, and the next re-send of the same key applies it. If the database refuses the proof itself, the host writes it to an authenticated, owner-only proof journal beside the database; only the operator can apply that journal (`writ reconcile --apply-proof-journal --yes`), after Writ verifies each line's MAC, checks that the line was written for this database, and checks it against the ledger. Agents cannot reach reconciliation or the journal: the reconcile tools and routes are the operator role's, and applying the journal is a CLI step. A call that ended `payment_outcome_unknown` replays that outcome even after the operator reconciles it, because money may have moved. Authority is still checked first, so a retry under a writ that has since been revoked or has expired is refused like any other call.
Concurrent calls with the same key are safe: the key is unique per writ in the database, so exactly one call creates the invocation and can pay; every other caller is answered `in_progress` or with the replay. Without a key, nothing changes: every call is a new invocation.
```bash
curl -s -X POST http://127.0.0.1:8787/v1/invocations \
-H "Authorization: Bearer $WRIT_API_AGENT_TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: " \
-d '{"credential": "", "capability": "demo.search", "query": {"q": "lightning"}}'
```
==============================================================================
# Command reference
Source: https://writ.lightningenable.com/docs/reference/commands
==============================================================================
# Command reference
Every example on this page is output captured from the `writ` 0.1.0 tool. Run ids, hashes, timestamps, and file paths differ on your machine; the shape doesn't. The CLI prints absolute paths; the samples shorten them.
The `writ` CLI includes every command on this page. The examples that run `mission.yaml` use the vendor-dossier manifest from [Your first mission](/docs/getting-started/first-mission); the approval and key examples use the `approval-demo` and `keyed-demo` manifests from [Approvals and budgets](/docs/guides/approvals-and-budgets#approve-and-resume) and [Keys and verification](/docs/guides/keys-and-verification#run-a-mission-signed-with-that-key). The `--service-db` forms act on the database of a `writ-mcp` or `writ-api` host, and the `coding` commands are the operator side of a governed coding task whose agent uses `writ-coding-mcp`. Those three programs are separate from the `writ` CLI: see [Writ's programs](/docs/getting-started/installation#writs-programs).
## Exit codes
`writ` uses a small, stable set of process exit codes. Scripts and CI can gate on these directly:
| Code | Name | Meaning |
|---|---|---|
| `0` | `Ok` | Success / all-valid. |
| `1` | (unexpected) | An unhandled internal error, which is a bug in Writ. Prints `Unexpected error: ` with no stack trace. No anticipated failure maps here. |
| `2` | `ValidationError` | A manifest failed validation, an input file couldn't be read/parsed, or the command line was wrong: no command, an unknown command, a missing or malformed argument, an invalid `--pubkey` or `--signer-mode`. |
| `3` | `RunFailed` | A mission run failed (budget, execution, or authority). |
| `4` | `ApprovalRequired` | A mission run is suspended awaiting human approval. |
| `5` | `VerificationFailed` | Offline receipt-chain verification found at least one failure. |
| `6` | `MissingWorkRecord` | Every step ran, but the evidence is degraded (run outcome `ExecutedReceiptPendingRecovery`): at least one executed step's signed work record is not on the chain (its append failed, or the process died before it), or `work-record.jsonl` could not be exported. Never reported as clean success. The work records are staged in the run database; `writ resume` appends them and re-exports. |
| `7` | `PendingReconciliation` | A wallet payment's outcome is unknown: the run halted and the budget hold is **retained** pending `writ reconcile`. Never reported as clean failure or success — funds may have moved. |
| `8` | `VerificationIncomplete` | `writ verify` found every receipt valid but had no terminal commitment to check the chain's end against (a bare `work-record.jsonl` with no `run.json`, `--expect-head`, or `--pinned-head`), so tail truncation can't be ruled out. Pass `--allow-no-terminal-commitment` to accept the record without one. |
| `9` | `PreflightExpectationUnmet` | `writ coding preflight-host` observed at least one thing other than its expectations file says: a path reachable that shouldn't be (or not reachable that should be), a name present that must be absent, or an elevated token where none was expected. |
| `10` | `RelayUnavailable` | A Nostr relay named with `--relay` could not be used: the connection failed, the deadline passed, the relay refused the event or the query, or it answered outside the protocol or the size limits. `record publish-head` has still written the attestation and the signed event locally, so it can be run again; `record verify-head` has reached no conclusion. |
| `11` | `WorkRecordDiscarded` | Every step ran, at least one executed step has no signed work record, and the operator discarded each missing one with `writ outbox discard` (run outcome `ExecutedReceiptDiscarded`). Never reported as clean success. Unlike `6`, nothing is left for `writ resume` to append. Each discard is a signed `work_record_discarded` receipt in the chain, and `run.json` lists each record in `DiscardedWorkRecords` with its reason. A still-pending staged record, or one marked discarded without the command, keeps the run at `6`. |
| `130` | (interrupted) | Ctrl-C or SIGTERM. Prints `Interrupted.` to stderr. A run that had not yet spent or recorded anything has its empty run directory removed. |
Every anticipated failure maps to one of these codes, so a caller can tell *what kind* of problem it hit. Usage mistakes print the problem and a pointer, for example `Unknown command 'xyz'. Run `writ --help`.` or `No command given. Run `writ --help` to see the commands.`
## `writ init`
```
writ init []
```
Scaffolds a `mission.yaml` + `README.md` + `.gitignore` into a directory (default `.`). Refuses to overwrite an existing manifest.
```
$ writ init my-mission
Scaffolded mission at my-mission/mission.yaml
Next: edit the goal/vars, then `writ validate my-mission/mission.yaml` and `writ run my-mission/mission.yaml --var target_domain=example.com --var target_name="Example Corp"`.
The scaffold uses model.provider: anthropic, so `run` needs ANTHROPIC_API_KEY set in this shell.
```
```
$ writ init my-mission
Refusing to overwrite existing manifest: my-mission/mission.yaml
```
Exit `2` on refusal, `0` on success.
The scaffolded manifest is a vendor-dossier-shaped mission with `model.provider: anthropic` and an `agent`-type step — see [Your first mission](/docs/getting-started/first-mission#scaffold-your-own-mission) for what that means for a first run.
## `writ validate`
```
writ validate
```
Parses a manifest through the same authoritative parser + validator `run` uses, and prints either an `OK` summary or the validation errors. Never mints a credential, calls a capability, or spends anything.
```
$ writ validate mission.yaml
OK — mission 'vendor-dossier': 3 worker(s), 3 capabilities.
Worst-case total spend: 100 sats (budget cap 200 sats; sum of worker slices 100 sats).
Settlement: simulated. Signing: dev-ephemeral.
```
A manifest with an `allow_local` capability gets an extra warning block:
```
!! 1 capability permit LOCAL targets (allow_local):
! capability 'test.local' permits LOCAL/loopback targets (allow_local) — cloud-metadata endpoints are still denied.
~ Capability 'test.local' sets allow_local=true — it may reach loopback/private targets (cloud-metadata endpoints stay denied). Intended only for local mock/demo endpoints.
```
`validate` takes no `--var`, so it stands in a placeholder for every `{{name}}` the manifest references. A `{{name}}` that isn't listed under `mission.vars` is a warning, not an error, because `run --var name=value` accepts it. `validate` still exits `0` when that is the only finding:
```
~ '{{topic}}' is referenced but not declared in mission.vars; add it there so the manifest lists every value a run must supply.
```
Error path (exit `2`):
```
$ writ validate /tmp/bad-mission.yaml
Manifest invalid (1 problem(s)):
- mission is missing required field 'goal'.
```
See the full error catalog in [Troubleshooting](/docs/troubleshooting) and every field in the [manifest reference](/docs/reference/manifest).
## `writ run`
```
writ run [--var name=value]... [--dry-run] [--production] [--output-dir ]
```
| Option | Meaning |
|---|---|
| `--var ` | Set a manifest var (repeatable). |
| `--dry-run` | Plan + cost estimate only; mints nothing, pays nothing, writes no `runs/` directory. |
| `--production` | Fail-closed posture: no dev-ephemeral signer, wallet settlement required. See [Security model](/docs/security-and-limitations). |
| `--output-dir ` | Override the manifest's `work_record.output_dir`. |
Planned (`--dry-run`):
```
$ writ run mission.yaml --var target_domain=example.com --var target_name="Example Corp" --dry-run
Running mission 'vendor-dossier' (run vendor-dossier-20261117-002809-06f257b3e1d94e1799d95bf179c4570d) — dry run, no spend...
· infra-researcher/mission.dns.whois 5 sats planned
· compliance-researcher/mission.compliance.search 12 sats planned
· writer/mission.compose.dossier 0 sats planned
Run vendor-dossier-20261117-002809-06f257b3e1d94e1799d95bf179c4570d: Planned
Spent 0 / 200 sats · settlement simulated · 0 receipt(s)
```
Completed (real run — see [Your first mission](/docs/getting-started/first-mission) for the full walkthrough):
```
$ writ run mission.yaml --var target_domain=example.com --var target_name="Example Corp"
Running mission 'vendor-dossier' (run vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d)...
· infra-researcher/mission.dns.whois 5 sats Executed (simulated)
· compliance-researcher/mission.compliance.search 12 sats Executed (simulated)
· writer/mission.compose.dossier 0 sats Executed
Run vendor-dossier-20261117-002810-53a59cab5a76490480b2142075b6cb2d: Completed
Spent 17 / 200 sats · settlement simulated · 3 receipt(s)
Outputs:
- runs/vendor-dossier-.../infra.json
- runs/vendor-dossier-.../compliance.json
- runs/vendor-dossier-.../dossier.md
- runs/vendor-dossier-.../work-record.jsonl
- runs/vendor-dossier-.../usage.json
- runs/vendor-dossier-.../run.json
- runs/vendor-dossier-.../report.html
Verify: writ verify runs/vendor-dossier-... --pubkey 93178da572... --signer-mode dev-ephemeral
```
Exit `0`. The `Verify:` line is printed for every completed run and is ready to paste. A `Model` line appears only when a step called a model, and then includes the call count and list-price cost billed to your provider account (for example `Model claude-cli · 2 call(s) · $0.117 billed to your claude-cli account (list price, not part of the sats budget)`). If an HTTP provider's API key variable is unset, the run fails pre-flight with `Pre-flight check failed: model provider 'anthropic' needs an API key, but ANTHROPIC_API_KEY is not set in this shell. ...` (exit `3`) before any capability is invoked.
Suspended for approval (exit `4`; see [Approvals and budgets](/docs/guides/approvals-and-budgets)). A run started with `WRIT_ROOT_KEY` set and a persistent signer prints the commands that continue it:
```
$ writ run mission.yaml
Running mission 'approval-demo' (run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931)...
· buyer/mission.data.premium 0 sats ApprovalRequired
Run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931: ApprovalRequired
Spent 0 / 50 sats · settlement simulated · 0 receipt(s)
Outputs:
- runs/approval-demo-.../work-record.jsonl
- runs/approval-demo-.../usage.json
- runs/approval-demo-.../run.json
- runs/approval-demo-.../report.html
Suspended — pending approval #1. Approve with: writ approvals approve 1 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Then continue the run with: writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 mission.yaml
Spend requires human approval.
```
A run that cannot be resumed (no `WRIT_ROOT_KEY`, or a `dev-ephemeral` signer) says so instead:
```
Suspended — pending approval #1.
This run cannot be resumed: it started without WRIT_ROOT_KEY. To approve and continue a run, set WRIT_ROOT_KEY to a secret you keep and use work_record.signing: key-file (or env), then run the mission again.
```
A dry run of a mission that calls a model ends with a note that says what the run will need for it, for example `Note: This mission calls a model: provider 'anthropic' needs ANTHROPIC_API_KEY at run time (not set in this shell).` `writ validate` prints the same note. Neither fails because of it.
Wallet-mode real-money banner (printed before anything executes, never on a dry run):
```
WARNING: wallet settlement — this run makes REAL Lightning payments, bounded by the mission budget (100 sats total).
```
Missing a required `--var`:
```
$ writ run mission.yaml --dry-run
Manifest invalid: Manifest references variable '{{target_name}}' but no --var target_name=... was supplied.
```
Exit `2`.
## `writ resume`
```
writ resume [--var name=value]... [--production] [--output-dir ]
```
Continues an existing run: one suspended for approval (exit `4`), one whose process was interrupted (a crash, a kill, a power loss), or one that finished with degraded evidence (exit `6`). It reopens the run's own database and its progress journal (`progress.jsonl`), reuses the credentials the run already issued, restores the steps that completed (their outputs feed later steps exactly as before), and resolves every interrupted call from the ledger by the call's idempotency key:
- a call that finished is answered from the ledger and is not run again;
- a call that never reserved budget is proven unpaid and is issued again once, under a new key;
- a call whose payment may have gone out but was never recorded keeps its budget hold and halts the run for `writ reconcile` (exit `7`); it is never executed again;
- a work record that was staged but not appended is appended.
It needs the same manifest and `--var` values (checked against the journal), the same `WRIT_ROOT_KEY` the run started with, and a persistent receipt signer (`work_record.signing: env` or `key-file`); [Approve and resume a run, end to end](/docs/guides/approvals-and-budgets#approve-and-resume) sets these up. Resuming a completed run re-exports its work record and changes nothing else. Exit codes are those of `writ run`.
```
$ writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 mission.yaml
Resuming mission 'approval-demo' (run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931)...
· buyer/mission.data.premium 20 sats Executed (simulated)
Run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931: Completed
Spent 20 / 50 sats · settlement simulated · 1 receipt(s)
Outputs:
- runs/approval-demo-.../premium.json
- runs/approval-demo-.../work-record.jsonl
- runs/approval-demo-.../usage.json
- runs/approval-demo-.../run.json
- runs/approval-demo-.../report.html
Verify: writ verify runs/approval-demo-... --pubkey 3b2b9a7e0db5ae925b90f772737618fe99ddf0af751ed4013d8a43192dec9a3a
```
A resume that cannot be safe is refused before anything is opened, and changes nothing (exit `3`). With a different `WRIT_ROOT_KEY`:
```
$ writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 mission.yaml
Resuming mission 'approval-demo' (run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931)...
Resume refused: WRIT_ROOT_KEY is not the authority key run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931' was started with (its journal does not authenticate under it), or the journal was edited. Nothing was changed.
```
Only one process runs a run at a time: `writ run` and `writ resume` hold `run.lock` in the run directory, and a second process is refused.
## `writ approvals`
```
writ approvals list (--run | --service-db [--workspace ])
writ approvals approve (--run | --service-db [--workspace ])
writ approvals deny (--run | --service-db [--workspace ])
```
All three take `--runs-root ` (default `runs`). Give exactly one of `--run` and `--service-db`; both or neither exits `2`.
```
$ writ approvals list --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Pending approvals for run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931':
#1 mission.data.premium 20 sats — buyer:data.premium
resource /fetch → api.example.test (invocation #1); valid 15 min once approved
```
```
$ writ approvals list --run keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32
No pending approvals for run 'keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32'.
```
```
$ writ approvals approve 1 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Approved #1. Continue the run with: writ resume approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931 (the manifest it started with).
```
Approving twice:
```
$ writ approvals approve 1 --run approval-demo-...
Could not approve #1: Approval request is already approved.
```
Exit `2`.
Denying an id that doesn't exist:
```
$ writ approvals deny 999 --run approval-demo-...
Could not deny #999: Approval request not found.
```
Exit `2`.
After approving, continue the run with [`writ resume`](#writ-resume). Re-running the manifest with `writ run` starts a new run that cannot see this run's approvals. See [Approvals and budgets](/docs/guides/approvals-and-budgets#resuming-a-suspended-run).
### On a service host
With `--service-db`, the same verbs act on a `writ-mcp` or `writ-api` host's database (its `WRIT_DB_PATH`), in the given workspace (default `WRIT_WORKSPACE`, else `default`). This is how the operator decides a spend an agent-role host is holding. Run it with the host's `WRIT_ROOT_KEY` in the environment. Before reading anything else it checks that key against the database (the host records its key when it starts, so start the host once first), and it works on a database at this build's schema version without creating or upgrading it: to upgrade, stop the host and run [`writ db upgrade`](#writ-db). A wrong key, an unbound database, or another schema version exits `2` and changes nothing.
```
$ writ approvals list --service-db ./host/writ.db
Pending approvals in workspace 'default' of ./host/writ.db:
#1 writ.demo.search 10 sats writ #1
resource /search → capabilities.writ.example (invocation #1); valid 15 min once approved
```
```
$ writ approvals approve 1 --service-db ./host/writ.db
Approved #1. The agent's retry of the same call now runs; the approval is consumed by exactly one invocation.
```
A coding scope-expansion request is refused here as on the run path; decide it with `writ coding approvals`.
## `writ issue`
```
writ issue --service-db --principal [--scope ] [--budget ] [--per-call ]
[--ttl-minutes ] [--depth ] [--purpose ] [--workspace ] [--json]
```
Issues a root writ on a `writ-mcp` or `writ-api` host's database and prints its credential, for the operator to hand to the agent. An agent-role host serves no issue tool, so this is how its agent gets authority. It reads the host's settings from the environment, as the host does: `WRIT_ROOT_KEY` (required: the host's own value, checked against the database before anything is written), `WRIT_CAPABILITIES` for a concrete `--scope`, `WRIT_WORKSPACE`, and the budget and TTL defaults. `--depth` defaults to `1`. It makes the same database checks as `writ approvals --service-db`.
```
$ writ issue --service-db ./host/writ.db --principal researcher --budget 200 --per-call 25
Issued writ #1 to 'researcher' in workspace 'default': scope writ.*, 200 sats total, 25 per call, delegation depth 1, expires 2026-11-15T07:54:19Z.
Hand this credential to the agent and to nobody else; it is a bearer token for spend up to those bounds:
MDAxZWxvY2F0aW9uIHdyaXQ6Ly9hdXRob3JpdHkKMDA1YWlkZW50aWZpZXIg...
```
`--json` prints one object with `credentialId`, `credential`, and the bounds. Without `WRIT_ROOT_KEY`:
```
$ writ issue --service-db ./host/writ.db --principal researcher
Writ service configuration is not usable:
- WRIT_ROOT_KEY is required: set it to the host's value. A writ issued under any other key does not verify on the host, and the audit events this writes must verify alongside the host's own.
```
Exit `2`.
## `writ revoke`
```
writ revoke (--run | --service-db [--workspace ])
```
The kill switch: revokes a credential and its entire delegated subtree. Writ checks revocation whenever it verifies a credential, so a revoked credential fails verification even though the macaroon itself is still well formed. `writ revoke` records the revocation as a signed audit row under the key in `WRIT_AUDIT_KEY` (any secret you choose and keep); without it, the command stops with `AuditKeyNotConfigured` (exit `2`), and `--development-audit-key` uses a key built into Writ, for tests only. With `--service-db` it revokes on a `writ-mcp` or `writ-api` host's database (revoking is the operator's on those hosts), with the host's `WRIT_ROOT_KEY` in the environment and the same checks as `writ approvals --service-db`.
```
$ writ revoke 1 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Revoked credential #1 and its delegated subtree. Any token in that subtree now fails verification.
```
Revoking the same credential again succeeds again (it is idempotent):
```
$ writ revoke 1 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Revoked credential #1 and its delegated subtree. Any token in that subtree now fails verification.
```
A credential id that never existed:
```
$ writ revoke 9999 --run approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
Credential #9999 was not found in run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931'.
```
Exit `2`.
## `writ record`
```
writ record show
writ record export [--out ]
writ record publish-head [--out ] [--post ] [--key ] [--relay ] [--relay-timeout ] [--json]
writ record verify-head --relay --pubkey [--revocations ] [--relay-timeout ] [--json]
```
### `record show`
Human-readable summary — see [Your first mission](/docs/getting-started/first-mission#read-the-record-back) for a full captured example.
### `record export`
Without `--out`, prints the signed chain (`work-record.jsonl`) to stdout, one JSON object per line. With `--out `, writes a **shareable bundle**: `work-record.jsonl`, `run.json`, `report.html`, `usage.json`, the signer records of a key-signed run (`signer-identity.json`, and `rotations.jsonl` and `revocations.jsonl` when the run has them), and a `manifest.json` listing each file's SHA-256 and the chain head. It never includes `writ.db`, key material, or step outputs (see [Run artifacts and export](/docs/guides/run-artifacts-and-export)). A recipient verifies the bundle directory with the signer's public key, which you give them separately.
```
$ writ record export keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32 --out share-bundle
Exported run 'keyed-demo-20261117-002151-f665d63865054f42a2bdc7b8c21c7a32' to /share-bundle
work-record.jsonl (1504 bytes, sha256 fa86bd0a321fab11f05de3add6c78c3c1837d2091ffa89ad200ee651ed8cd8c8)
run.json (2115 bytes, sha256 75baefa915634c7c24bde4744ad36123eed0f76c867b17df02f2a255f45f6ea5)
report.html (3776 bytes, sha256 b17704f88a3431762f97ae5219c1a28cb6d5330c0f39936a2ec9b67e40f18b38)
usage.json (182 bytes, sha256 e230184836060050d94f7016905ac25349993f830db241a16e2379a6737d2cae)
signer-identity.json (531 bytes, sha256 a7e7fefe3d966d03e2e2685516f1376bb3248600245affa9364bdb46231d2a07)
manifest.json
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a (1 receipts).
Not included (never exported): writ.db and its sidecars, key material, and step outputs.
Recipient check: writ verify --pubkey --expect-head 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
```
### `record publish-head`
Signs a **head attestation** over the run's terminal receipt, using the run's own signer key (or a successor of it, per the run's rotation records), and writes `/head-attestation.json`. It needs the key on disk, so a `dev-ephemeral` run, whose key was never written, is refused (exit `2`):
```
$ writ record publish-head smoke-20261117-002246-a33f66e03fa5434ebd1e0279df95a1ed
Run 'smoke-20261117-002246-a33f66e03fa5434ebd1e0279df95a1ed' was signed with a dev-ephemeral key, which existed only in the process that ran it, so no key can attest its head. Use work_record.signing: env or key-file for runs whose head you publish. Nothing was written.
```
See [Keys and verification](/docs/guides/keys-and-verification#head-attestations) for the walkthrough with a persistent key.
With `--relay `, the attestation is also published to that Nostr relay, a relay you choose, so a copy of the head is held outside the machine that ran the run. `wss://agents.lightningenable.com` is a public relay that accepts these events. No relay is contacted without `--relay`. A relay is not a transparency log: it can withhold or lose a later head, so publish to and check more than one relay to detect a withheld head.
- Before anything is signed for a relay, the run's local chain is verified as `writ verify` does, anchored at the run's own signer. A chain that does not verify exits `5`, and nothing is written or sent.
- The event is kind `38410`, an addressable kind dedicated to Writ head attestations. It is signed by the same key that signed the attestation. A Writ receipt key is a BIP-340 secp256k1 key, which is what a Nostr key is, so the event's author is the receipt signer (or the successor key that attested).
- Its content is the attestation JSON exactly as written to `head-attestation.json`. Its tags are `d` = `writ.head::`, the NIP-32 label `["L","writ.run"]` and `["l","","writ.run"]`, `seq`, `count`, `head`, `key_id`, `protocol` and `alt`. When a successor key attests, the event also carries one `rotation` tag per signed rotation record from the run's signer to that key (at most 16).
- Each head position is its own event, so publishing a later head does not replace an earlier one on the relay.
- The signed event is also written to `/head-attestation.nostr.json`. The private key is wiped from memory before any file is written or the relay is contacted.
- Only `wss://` is accepted, of printable ASCII, with no user information, query string, fragment or percent-encoding. `--relay-timeout` (1 to 120 seconds, default 15) bounds the whole exchange. A relay that refuses the event, times out, or cannot be reached exits `10`; everything is still written locally, and running the command again retries.
- `--json` prints one JSON object on stdout on every path, including usage errors (`outcome`, `exit_code`, `errors`, and when they exist the attestation's fields, the files written, the relay's status and event id, and the `--post` status).
**What the relay sees.** A relay is public. It learns the run id, the receipt count, the head hash, the signer's key id, the time of the attestation, the signer's public key (which links every run that key signs), and any rotation records between the run's signer and the attesting key. No receipt contents, prices, endpoints, prompts or outputs are sent.
### `record verify-head`
Checks the copy a relay holds against the local record. It reads only and publishes nothing.
1. It verifies the local run directory as `writ verify` does, under `--pubkey` (the trust anchor). A local chain that does not verify exits `5` before the relay is asked. A run with no `run.json` (an in-progress or interrupted run) is accepted at this step, so deleting `run.json` is not caught here; the relay's heads are the end-of-chain check this command adds.
2. The run's `rotations.jsonl` and `revocations.jsonl` must be readable and well formed. An unreadable file or a malformed line exits `5` (`local_records_invalid`) rather than counting as "no records".
3. It asks the relay for every event of kind `38410` labelled with this run, from any author. It does not filter by author, because the set of authors would have to come from the directory under test.
4. It treats everything the relay returns as untrusted, and sets an event aside only when it is provably not a head of this run by the anchor's key chain: its shape, id or signature does not hold and it does not claim this run under a key on the anchor's chain (anyone can send such an event), it names another run in every run field (`l`, `d` parsed exactly as `writ.head::`, and the content's `run_id`) or is another kind, or its author has no validly signed rotation path from `--pubkey` in any record the command holds (the run's `rotations.jsonl` and the rotations every returned event carries). Those are counted as `invalid` or `foreign`.
5. An event whose author does have such a path must be fully usable, or the outcome is not `match`: exactly one of each tag the command relies on, each agreeing with the attestation in its content; an attestation that names this run and is signed by the event's author; an author the chain resolves to, not through a rotation dated after its old key's revocation; and an author not revoked before the attestation. An event that fails any of these is counted as `blocking`.
6. If the validly signed rotation records rooted at `--pubkey` fork (one key with two different rotations that are not dated after its revocation) or loop, which key is in force cannot be decided: the outcome is `key_chain_ambiguous` (exit `5`). Two copies of one rotation (the same signed statement, however encoded or re-signed) are one rotation. Signature and key hex must be lowercase.
7. Every remaining head must name a receipt the local chain holds, with the same hash.
| Exit | Outcome | Meaning |
|---|---|---|
| `0` | `match` | Every head this relay returned is the local head or an earlier receipt of it. The output says how many local receipts are newer than the latest published head. |
| `8` | `not_published` | The relay returned no valid head for this run. That is also what a deleted or withheld publication looks like, so it is not evidence either way. |
| `5` | `mismatch`, `key_chain_ambiguous` | A returned head is past the end of the local chain (a rollback: receipts the relay saw are missing locally), names a different hash at a position the local chain holds (a fork), or two returned heads disagree at one position; or a head signed by a key on the anchor's chain cannot be used (`blocking`); or the key chain forks or loops. Also `local_chain_invalid` and `local_records_invalid`. |
| `10` | `relay_unavailable`, `relay_incomplete`, `relay_altered` | The relay could not be used; or it returned as many events as this command asks for (500), so its answer may have been cut; or it returned an event that claims this run under a key on the anchor's chain but whose id or signature does not verify, so it altered data (for example stripped a tag). No match is claimed. |
**What `match` means.** `match` means the local record is consistent with what this relay returned, and nothing more. A relay that withholds a later head, or has lost it, makes a rollback look like a match. Checking more than one relay reduces that risk; this command checks one.
**Relay limits.** A relay whose own per-query limit is below 500 can cut the answer without saying so, and the cut can drop the head that disagrees. Check a relay whose limit you know, or several.
**Junk under the run id.** Anyone can post events labelled with a run id. Strangers' events are set aside and counted, but 500 of them fill the answer and force `relay_incomplete`. That can prevent a `match`; it can never produce one.
**A compromised key.** Whoever holds any key on the anchor's chain, including a revoked one, can sign a second rotation or an unusable head and so force `key_chain_ambiguous` or `mismatch`. That is deliberate: it is a real incident, and the operator should see it rather than a `match`.
**Key holder.** None of this protects against whoever holds the signing key: they can publish a different head at the same position, or delete events (the relay supports NIP-09 deletion).
**Revocations.** The run directory's `revocations.jsonl` can be deleted by whoever can edit the directory. Deleting it can only make more heads count (a revoked key's later heads are then accepted), so it cannot hide a head that contradicts the local chain; but it does let receipts or heads signed with a revoked key after its revocation pass. Pass `--revocations ` with a copy you keep elsewhere to use that instead.
## `writ reconcile`
```
writ reconcile [--invocation N] [--resolve paid|not-paid [--allow-unconfirmed-not-paid]]
writ reconcile --service-db [--workspace ] [--invocation N] [--resolve paid|not-paid [--allow-unconfirmed-not-paid]]
writ reconcile ( | --service-db [--workspace ]) --apply-proof-journal [--yes] [--allow-legacy-proof-lines]
```
`writ reconcile` records each decision as a signed audit row under the key in `WRIT_AUDIT_KEY`, as `writ revoke` does; without it, the command stops with `AuditKeyNotConfigured` (exit `2`).
With `--service-db`, the same reconciliation runs against a `writ-mcp` or `writ-api` host's database (its `WRIT_DB_PATH`) in the given workspace (default `WRIT_WORKSPACE`, else `default`). It is an operator command: it needs the database file. A running host also offers the same reconciliation to its operator role (`writ_reconcile` on a `--role operator` server, `POST /v1/reconciliations/{invocationId}/resolve` with the operator token); agents reach neither. `WRIT_ROOT_KEY` must be set to the host's value: the command refuses without it, and refuses a key that verifies none of the database's existing audit events, so every audit row it writes verifies alongside the host's own. The database must be at the schema version of the `writ` you run; `--service-db` never upgrades a host's database. For an older one, or one without a database identity, stop the host, run `writ db upgrade `, and start the host again. Use one root key per service database, and never reuse a root key on another database or bring one back after it has been replaced.
Run `writ reconcile` from a shell configured with the wallet the host or run pays from (the same `LND_*`, `NWC_CONNECTION_STRING` or Strike settings), so the wallet that answers a lookup is the wallet that paid.
**`--resolve not-paid` on a hold with a payment hash.** Writ first asks the wallet to look the payment up by the hash in the hold's signed audit record, and accepts the attestation only when the wallet reports the payment failed. When that record names the kind of wallet that paid (LND, NWC, Strike), only that kind of wallet can confirm it. A hold counts as having no payment hash only when its signed record says so. Otherwise Writ refuses, prints a code, changes nothing, and exits `7`:
| Code | What the wallet said | What to do |
| --- | --- | --- |
| `wallet_reports_paid` | The payment went out. | Run `writ reconcile` without `--resolve` to settle it from the wallet's answer. `--allow-unconfirmed-not-paid` does not change this. |
| `wallet_cannot_confirm` | It could not tell (an in-flight payment, a lookup that timed out, or Strike, which has no lookup by hash); another kind of wallet answered than the one that paid; or the hold has no signed record of its payment hash. | Wait and retry, run from a shell configured with the wallet that paid, or check the payment by its hash yourself. |
| `no_lookup_wallet` | No wallet that can look payments up is configured. | Check the payment by its hash yourself. |
Plain `writ reconcile` and a resumed run follow the same rules when they ask the wallet: a not-paid answer returns the hold only from the kind of wallet that paid, about the hash in the signed record, and otherwise the hold stays pending. A record written by an earlier Writ names no wallet; resolve such a hold with `--resolve not-paid`.
When you have checked the payment yourself and it failed, add `--allow-unconfirmed-not-paid`. The signed audit event for the reconciliation records which way the attestation was accepted (`walletCheck` is `confirmed-not-paid` or `unconfirmed-override`), which wallet answered (`wallet`), and which kind of wallet paid (`walletPaidWith`).
```
$ writ reconcile vendor-dossier-... --invocation 3 --resolve not-paid
Could not reconcile invocation 3 (no_lookup_wallet): A not-paid attestation on a row with a payment hash needs the wallet that paid to report the payment failed. No wallet that can look payments up is configured, so nothing can confirm the payment failed. Check the payment by its hash in your wallet; if it failed, re-run with --allow-unconfirmed-not-paid, which the audit log records. Nothing was changed.
```
Exit `7`.
An invocation that carries a payment proof (the executor returned a preimage) is resolved as paid for exactly the proven amount, with or without `--resolve paid`, whatever state it is in; `--resolve not-paid` is refused for it, because the proof shows the payment went out. **The proof journal.** If the host could not write a payment proof to its database, it appends it to `.proofs.jsonl` beside it: hash and amount only, never the preimage, in a file created owner-only (a protected ACL on Windows, mode `0600` on POSIX). Each line is authenticated with an HMAC-SHA256 keyed from the host's audit key material (the same key that signs its audit events, under its own domain), over the database's identity, workspace, invocation id, payment hash, amount, and timestamp. A journal line applies only in the database it was written for. Every Writ database gets its own identity when it is created, or when an upgrade brings it to schema version 13; a copy, backup or restore of the file keeps it, and the database refuses an update or deletion of it. Applying the journal is an explicit step:
- Plain `writ reconcile` only reports that a journal with N unapplied lines exists.
- `--apply-proof-journal` lists every line and what it would do. Nothing is applied without `--yes`.
- A line is applied only if its MAC verifies with this host's key, it names this database's identity, and it is consistent with the ledger: the invocation exists in the workspace, the amount is positive and no more than the hold reserved for that call, the call was reserved at some point, and the invocation is not already settled under a payment hash. Each line applies at most once.
- A line that fails any check is refused and reported by line number (exit `2`). The journal file is never edited or deleted.
**Legacy journal lines.** A line written before its database had an identity names no database, so it is refused unless you add `--allow-legacy-proof-lines` to `--apply-proof-journal`. With it, a legacy line applies only in a database that an upgrade gave an identity (`writ db upgrade`, a host's start, or a command that opens a run's database), and only when the line was recorded before that upgrade; it still passes every other check, and its audit event records `journalLine: legacy-allowed-by-operator`. Use it only for lines you know were written for this database.
`--resolve not-paid` on a pending invocation with no payment hash (one routed to reconciliation because it sat reserved too long) is refused until the paid-call runtime bound has passed since its reservation: a paid call is cancelled after at most 10 minutes (two HTTP requests of at most 100 s each and a wallet payment of at most 120 s, plus slack), so after that no execution of it can still be running. The message says from when it is allowed.
Resolves a budget hold retained because a wallet payment's outcome was unknown (exit `7`). Simulated-settlement runs never produce a pending hold:
```
$ writ reconcile approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931
No invocations pending reconciliation for run 'approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931'.
```
Exit `0`.
```
$ writ reconcile approval-demo-... --resolve maybe
--resolve must be exactly 'paid' or 'not-paid' (was 'maybe').
```
Exit `2`.
See [Approvals and budgets](/docs/guides/approvals-and-budgets#reconciling-a-pending-wallet-payment) for the full reconciliation model.
## `writ db`
```
writ db status
writ db upgrade
```
A Writ database records its schema version in SQLite's `PRAGMA user_version`. `status` prints it, the version this build understands, and any pending upgrade steps, and changes nothing. `upgrade` writes a backup beside the database (`.backups/.schema-v-.bak`, in an owner-only directory), then applies every pending step in one transaction. Every other command that opens an older run database performs the same upgrade, with the same backup, implicitly; a command given `--service-db` never upgrades a host's database and tells you to run `writ db upgrade` with the host stopped. Upgrading a database to schema 13 charges earlier late payments that exceeded a cap to the links that had room, which lowers those links' remaining budget; `writ db upgrade` lists each charge, and a host or command that upgrades a database implicitly reports the totals. A database written by a newer Writ is refused and left unchanged (exit `2`). To roll back, stop every Writ process using the database and replace it with the backup; there are no down-migrations.
```
$ writ db status runs/approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931/writ.db
Database: /runs/approval-demo-20261117-002310-8cd93b408d164e67a903ca0b80dea931/writ.db
Schema version: 12
This build: 12
Status: current.
```
## `writ outbox`
```
writ outbox list ( | --service-db [--workspace ] [--previous-root-key-env ]) [--json] [--runs-root ]
writ outbox discard ( | --service-db [--workspace ]) --invocation --reason [--json]
writ outbox resign --service-db [--workspace ] --invocation --previous-root-key-env [--json]
```
The operator's tool for staged work records (the receipt outbox) that the recovery job will not append on its own. A paid call's work record is staged before the ledger moves, with a MAC keyed from the host's `WRIT_ROOT_KEY`; `writ resume` (for a run) or a service host's restart appends it when the MAC verifies under the current key and the request matches the ledger. Run any host that stages receipts with a persistent `WRIT_ROOT_KEY`, and drain the outbox before rotating the key (restart the host, check that `writ outbox list` shows nothing pending, then rotate). Keep the host database writable only by the host account. Use one root key per service database: never reuse it on another database, and never bring it back after it has been replaced. Point the command at the same database path the host uses (its `WRIT_DB_PATH`), not a copy.
**Before you run `resign` or `discard`:** stop the service host, or make sure no `writ run` or `writ resume` is running the run. The commands refuse while the run holds `run.lock`, or while a service host holds `.host.lock` (hosts hold it for as long as they run, and do not start while the command holds it). `writ issue`, `writ approvals` and `writ revoke --service-db` do not take that lock and work while the host runs.
- **`list`** reads only. For each pending record: invocation, capability, amount, payment hash, staged time, one reason code, whether the MAC verifies and under which key (`mac_verified_under`), the re-sign cross-check's verdict, the proof events for the invocation (how many count as evidence for this record, how many do not, and how many verify but name another payment; not checked without `WRIT_ROOT_KEY`), and the actions open to you. `list` offers `resign` when every check it can run passes (the same checks `resign` runs), so pass the same `--previous-root-key-env` to `list` as you would to `resign`; `resign` can still answer `unchanged`, or refuse while a host holds the database lock. When `WRIT_ROOT_KEY` is not the host's current key, `list` offers `resign` for no record and prints the refusal `resign` would give. Reason codes: `mac_invalid`, `unkeyed` (re-sign on a service database, or discard), `ledger_mismatch`, `invocation_missing`, `request_unreadable` (discard), and the ones the recovery job handles by itself: `replayable`, `awaiting_ledger` (reconcile first), `already_on_chain`, `no_receipt_owed`. Discarded records are listed with their reasons and whether their signed discard receipt is on the chain. Without `WRIT_ROOT_KEY` the MACs are reported `not_checked`.
- **`resign`** (service databases only) re-authenticates a record under the host's current key. Use it after a key change, for a record this host staged under its earlier key. Put the previous `WRIT_ROOT_KEY` in an environment variable and pass the variable's NAME with `--previous-root-key-env` (the key is never written on the command line, printed or recorded); it must be a key that signed a `host.key_bound` record in this file, and `WRIT_ROOT_KEY` must be the host's current key. Evidence under it counts only from its first period, before the binding that replaced it. If the previous key was replaced because it may have been exposed, use `discard`, not `resign`. `resign` replaces the record's MAC and nothing else, and only when all of these hold:
- the record's own MAC verifies under the previous key, and the times it carries predate the key change (the binding that replaced the previous key);
- every request field with a stored counterpart matches the ledger: invocation and workspace; capability (record, request and invocation); payment hash and proven amount of the invocation's recorded proof; authority mode and connector; payment-verification time and request time within the invocation's lifetime; the result code against the outcome recorded for a keyed call; the principal and authority hash of the invocation's credential; no other receipt for the same payment; and no proof event that verifies under a key you hold naming another payment;
- for a paid record, a proof event with the same payment hash and amount (a reconcile event only with a `Paid` verdict) verifies under the current key, or under the previous key with a time before the key change.
Without `--previous-root-key-env` it refuses with `previous_root_key_required`; a record that does not verify under the previous key is refused with `record_not_authenticated`. Discard either. The output says which key the record verified under (`mac_verified_under`) and which key the proof event verified under. The signed `receipt_outbox.resigned` audit event records the evidence, the binding record the previous key verified, and the digest before and after. Restart the host to append the receipt.
- **`discard`** writes a record off. Use it for a record you cannot explain, for one the cross-check refuses, and for every stranded record on a run (a run's records and its journal are keyed from the same root key, so a record on a run whose MAC does not verify was not written by the run's own process: `resign` refuses it with `resign_not_available_on_run`). The record is kept; your `--reason` goes into a signed `receipt_outbox.discarded` audit event, together with the invocation's capability, credential and the payment hash the ledger records at that moment. The next `writ resume` of a run, or the host's next start, appends a signed receipt of result code `work_record_discarded` (reason code `operator_discarded`) stating those facts, to the chain the terminal commitment covers; it is not appended when the invocation or its credential was missing at the discard, and `list` shows whether it is on the chain. A run then ends `ExecutedReceiptDiscarded` (exit `11`) and lists the record in `run.json`'s `DiscardedWorkRecords`; `writ verify` counts the discard receipts and prints a warning for each. A record the recovery job appends or will append (`replayable`, `awaiting_ledger`) is refused (`not_stranded`), whatever its current status. A record marked discarded without the command is put back to pending by the next recovery.
Both write commands need `WRIT_ROOT_KEY`, and check it before they take the lock. On a service database the key must match the newest key binding the host recorded at its start (`host.key_bound`); a host restarted under a new key records a new binding, so its new key matches. On a run, the run's journal must authenticate under it. The database's schema version is read without changing it; an older version is refused with the `writ db upgrade` command to run. Each write is one transaction holding the audit event and the record's update: an interrupted command changes nothing and can be run again, and running it again after it succeeded changes nothing (`unchanged`). Neither `writ-mcp` nor the HTTP API exposes these commands.
Exit `0` when the command did what was asked, including an idempotent no-op; exit `2` when it refused or the input was wrong. With `--json`, one object on stdout on every path; a refusal carries `error.code`: `usage_error`, `target_not_found`, `target_busy`, `host_settings_invalid`, `root_key_missing`, `root_key_unrecognized`, `root_key_not_bound`, `previous_root_key_missing`, `previous_root_key_unrecognized`, `previous_root_key_required`, `record_not_authenticated`, `schema_error`, `store_error`, `not_staged`, `not_pending`, `not_stranded`, `cross_check_failed`, `no_receipt_owed`, `resign_not_available_on_run`, `concurrent_change`.
A run with a record that does not verify under its key:
```
$ writ outbox list demo-run
Receipt outbox of run 'demo-run': 1 pending, 0 discarded by the operator.
Root key: recognized (MACs checked under it).
invocation 1 mission.data.lookup 5 sats payment hash f76a0574fc945a9ec02b074dab53b62c17bdf8916b5abfa1edcaef12136153c1 staged 2026-11-15T08:29:06Z invocation Settled
reason: mac_invalid — its MAC does not verify under the run's key, so the run's own process did not write it as it stands
MAC: invalid; cross-check: passes
proof events: 1 verify under this key, 0 do not
actions: discard
$ writ outbox discard demo-run --invocation 1 --reason "does not verify under the run key; not written by this run"
Discarded the staged work record of invocation 1 (audit event 4). Its receipt stays missing and is reported as discarded: the run ends `ExecutedReceiptDiscarded` (exit 11) on its next `writ resume`, which also appends a signed record of the discard.
```
Exit `0`. `writ outbox resign demo-run ...` exits `2` with `resign_not_available_on_run`. The next `writ resume` ends `Run demo-run: ExecutedReceiptDiscarded`, exit `11`, and `writ verify` on the run (exit `0`: the chain that exists is intact) prints `OK — verified 2 receipt(s), 1 of them a discard record (work_record_discarded).` and adds:
```
WARNING: receipt 1 (signed) records that the work record of invocation 1 (mission.data.lookup, payment hash f76a0574fc945a9ec02b074dab53b62c17bdf8916b5abfa1edcaef12136153c1) was discarded by the operator: no receipt describes that call.
WARNING: run.json (unsigned) records 1 work record(s) discarded by the operator; no receipt exists for them: invocation 1 mission.data.lookup 5 sats payment hash f76a0574fc945a9ec02b074dab53b62c17bdf8916b5abfa1edcaef12136153c1 — reason: does not verify under the run key; not written by this run.
```
## `writ keys`
```
writ keys init [--out ] --operator-name [--operator-url ] [--operator-contact ]
writ keys show [--key ] [--identity ]
writ keys rotate [--key ] [--operator-name ] [--operator-url ] [--operator-contact ]
writ keys revoke [--key ] --key-id [--reason ]
```
The full walkthrough with real output (init, show, rotate, and revoke, and what each does to `writ verify`) is in [Keys and verification](/docs/guides/keys-and-verification). Quick reference:
```
$ writ keys init --operator-name "Example Operator" --operator-url https://operator.example --operator-contact ops@operator.example
Created receipt signing key: keys/receipt.key (private; no other account is granted access)
Created signer identity: /keys/signer-identity.json (public; ships with every run)
key_id: 48d196ae736139f2
pubkey: 1f9a2598...82b214ca
operator: Example Operator (https://operator.example)
Next: in mission.yaml set
work_record:
signing: key-file
key_file: keys/receipt.key
and share the pubkey with anyone who will run `writ verify`.
```
`keys init` refuses to overwrite an existing key (exit `2`); `keys show` prints the public identity only, never the private key; `keys rotate` replaces the key in place and archives the old one; `keys revoke` appends a signed revocation that `writ verify` honors going forward.
## `writ verify`
```
writ verify [] --pubkey [--algorithm ] [--key-id ] [--signer-mode ]
[--expect-head ] [--summary ] [--record ]
[--require-identity] [--identity ] [--rotations ] [--revocations ]
[--pinned-head ] [--allow-no-terminal-commitment]
```
`` is a run directory or an exported bundle (containing `work-record.jsonl` and, when present, `run.json` and the signer records), or a direct path to `work-record.jsonl`. It reads `signer-identity.json`, `rotations.jsonl` and `revocations.jsonl` from beside the work record unless `--identity`, `--rotations` or `--revocations` names another file. Fully offline: no database, no network, no access to the machine that produced the run.
`--pubkey` must be the signer's 32-byte public key as 64 hex characters (an optional `0x` prefix is accepted). Anything else is a usage error (exit `2`): `Invalid --pubkey '': expected the signer's 32-byte public key as 64 hex characters ... Copy SignerPublicKeyHex from the run's run.json.` Likewise `--signer-mode` must be `production` or `dev-ephemeral`.
**Incomplete (exit `8`).** When nothing binds the end of the chain (no `run.json` terminal commitment, no `--expect-head`, no `--pinned-head`), every receipt can be valid and the record can still have been shortened. `verify` then says so instead of printing `OK`:
```
$ writ verify runs/keyed-demo-.../work-record.jsonl --pubkey 1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca
INCOMPLETE — 1 receipt(s) verified, but no terminal commitment is available, so tail truncation cannot be ruled out.
Chain head: 0:526ba45c4d925e41bb7845bc2910150a2994e9367cc6537298adac7d074b4c3a
Verify the run directory (with its run.json), or pin the head with --expect-head : or --pinned-head; pass --allow-no-terminal-commitment to accept a legacy record without one.
```
`--allow-no-terminal-commitment` accepts a record that has no terminal commitment: `OK — verified N receipt(s).` with exit `0` and a warning. When `--expect-head` alone binds the tail, a successful verify prints `Chain ends exactly at the pinned head — tail truncation ruled out.`
Success:
```
$ writ verify runs/vendor-dossier-... --pubkey 93178da572906641b34888d269d5ed2eefab89ba4202c729fa3f8d9f6a579e4c --signer-mode dev-ephemeral
WARNING: this work record is signed with a dev-ephemeral (throwaway) key — it is NOT production evidence.
OK — verified 3 receipt(s).
Chain head: 2:488827ea923b46b63824c23404de16fdf3bd02f830b7432c1ceee52794672ba2
Terminal commitment verified — this export cannot be truncated undetected.
WARNING: no signer identity record — the chain is not bound to a named operator (pass --require-identity to fail instead).
```
Wrong public key, on the key-signed run:
```
FAILED — 3 problem(s) across 1 receipt(s):
[row 0] 5fab3d822eb24a29a5d95e21375e94d1: signature verification failed
the run summary's terminal commitment signature does not verify under the supplied public key — refusing to trust it (the run summary may have been tampered with).
the signer identity record describes key 48d196ae736139f2 (1f9a25988803ebda461fc30b4e29f9149b94b95d4c2d885179ab7ce082b214ca), which is not the --pubkey you pinned and is not reachable from it: key 48d196ae736139f2 is not reachable from the trusted anchor 66687aadf862bd77: no rotation record continues from key 66687aadf862bd77. — the record does not belong to a key you trust.
```
Exit `5`.
`--require-identity` on a chain with no identity record:
```
WARNING: this work record is signed with a dev-ephemeral (throwaway) key — it is NOT production evidence.
FAILED — 1 problem(s) across 3 receipt(s):
--require-identity: no signer identity record was found and the chain is not bound to one.
```
Exit `5`.
Tampered receipt field:
```
FAILED — 1 problem(s) across 1 receipt(s):
[row 0] 5fab3d822eb24a29a5d95e21375e94d1: receiptHash does not match the recomputed canonical hash (tampered field)
```
Exit `5`.
More on `--require-identity`, `--rotations`, `--revocations`, `--pinned-head`, `--expect-head`, and what each shows: [Keys and verification](/docs/guides/keys-and-verification).
## Help for each command
`writ --help` lists the commands and the global options, and `writ --help` (for example `writ record publish-head --help`) prints that command's arguments and every option with its description. The installed tool is the reference for its own help text; the synopses and option tables above summarize it.
==============================================================================
# Manifest reference
Source: https://writ.lightningenable.com/docs/reference/manifest
==============================================================================
# Manifest reference
A Writ mission manifest is one YAML (or JSON) file. This page documents every field in [`mission.schema.json`](pathname:///schema/mission.schema.json), the schema `writ validate` and `writ run` both parse against. `additionalProperties: false` applies at every object level shown here, so an unrecognized field is a validation error.
:::caution The manifest is semi-trusted input
A mission file is shareable and may be agent-authored. `${NAME}` environment-variable interpolation is opt-in per variable, secret-shaped names are refused even when declared, and every output path is confined to the run directory. See [Security model and preview limitations](/docs/security-and-limitations#what-the-guardrails-are-designed-to-do) before running a manifest you didn't author.
:::
## Top level
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `mission` | object | yes | — | See [`mission`](#mission) below. |
| `env` | array of string | no | — | Env vars this manifest may read via `${NAME}`. See [`env`](#env). |
| `model` | object | no | — | Model provider config for `agent` steps and model-backed `internal` capabilities. See [`model`](#model). |
| `budget` | object | yes | — | See [`budget`](#budget). |
| `settlement` | object | no | `{ mode: simulated }` | See [`settlement`](#settlement). |
| `approvals` | object | no | — | Human-in-the-loop gate. See [`approvals`](#approvals). |
| `capabilities` | array (min 1) | yes | — | See [`capabilities`](#capabilities). |
| `workers` | array (min 1) | yes | — | See [`workers`](#workers). |
| `work_record` | object | no | `{ signing: dev-ephemeral }` | See [`work_record`](#work_record). |
## `mission`
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `name` | string | yes | — | Pattern `^[a-z0-9][a-z0-9-]*$`. Slug used in run ids and output paths. |
| `goal` | string | yes | — | What the mission should accomplish. May reference `{{vars}}`. |
| `schedule` | string | no | `"manual"` | `'manual'` or a cron expression — only `manual` is executed in v1. |
| `vars` | array of string | no | — | Pattern per item `^[A-Za-z_][A-Za-z0-9_]*$`. Names supplied at run time via `--var name=value` and referenced as `{{name}}`. A referenced-but-unsupplied var is a hard error (`writ run` refuses to start). |
Example:
```yaml
mission:
name: vendor-dossier
goal: "Produce a due-diligence dossier on {{target_name}} ({{target_domain}})"
vars: [target_domain, target_name]
```
## `env`
```yaml
env: [DEPLOY_REGION]
```
Array of environment variable names (pattern `^[A-Za-z_][A-Za-z0-9_]*$`) this manifest is allowed to read through `${NAME}`. Reading the environment is **opt-in per variable**: a `${NAME}` reference resolves only when `NAME` is listed here or is prefixed `WRIT_VAR_` (an operator-namespaced escape hatch that needs no declaration). Every other reference is a hard validation error naming the variable and both allowed forms — confirmed directly:
```
Manifest references environment variable '${SOME_VAR}' but it is not allowed to read it. Only two forms may be
interpolated: a name listed in the manifest's top-level 'env:' block (add 'env: [SOME_VAR]'), or a name prefixed
'WRIT_VAR_'. Anything else must be passed with --var.
```
Secret-shaped names — containing `KEY`, `SECRET`, `TOKEN`, `PASSWORD`, `CRED`, `NWC`, `MACAROON`, `MNEMONIC`, `SEED`, or `PRIVATE` — are refused **even when declared here**:
```
Refusing to interpolate a sensitive environment variable '${MY_API_KEY}' into a manifest. Secret values (keys, tokens,
credentials) must never flow into a manifest field; declaring the name in 'env:' or prefixing it does not change that.
Use a non-secret variable or pass configuration via --var.
```
A declared-but-unset variable is a hard error too, never a silent empty string. Omit the block entirely for a mission that reads no environment at all. Prefer `--var` over `${ENV}` for ordinary configuration.
## `model`
The model provider for `agent` steps and for `call` steps to any `internal` capability other than `compose` or `compose.*`: every such internal capability is a model call, whatever its name. Bring your own model. A mission with no `agent` steps and only `compose`/`compose.*` internal capabilities never invokes the provider, and you can omit this block. `writ validate` and `writ run --dry-run` print a note when a mission calls a model, naming what the run will need.
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `provider` | enum | no | `"anthropic"` | One of `anthropic`, `openai-compatible`, `claude-cli`, `codex`. The two HTTP providers are the default path; the two CLI providers are opt-in (see below). |
| `endpoint` | string | no | — | Base URL for `openai-compatible`/`anthropic`. Supports `${ENV}` for a declared or `WRIT_VAR_`-prefixed name. SSRF-guarded: an endpoint resolving to loopback/private/cloud-metadata is refused, and the client follows no redirects. |
| `model` | string | no | — | Model id for the provider. |
| `api_key_env` | string | no | — | Name of the env var holding the API key (the key itself is never in the manifest). **May not name a protected Writ/system secret**: `WRIT_ROOT_KEY`, `WRIT_RECEIPT_KEY`, `WRIT_AUDIT_KEY`, `DB_ENCRYPTION_KEY`, `NWC_CONNECTION_STRING`, `LND_MACAROON_HEX`, `STRIKE_API_KEY`, `OPENNODE_API_KEY`. |
| `timeout_seconds` | integer | no | provider-specific | Per-call LLM timeout override in seconds; **at least 1**. Omit to use the default: `claude-cli`/`codex` default to **1800 seconds (30 minutes)** because they run a full headless agentic session (tool use, MCP calls, builds), not a single completion; `openai-compatible`/`anthropic` keep their own client default. |
```yaml
model:
provider: anthropic # default — set ANTHROPIC_API_KEY (or name another var with api_key_env)
```
**Provider notes:**
- `anthropic` is the default even when the `model:` block is omitted. A manifest whose steps never call a model never constructs or calls the provider, so it needs no `ANTHROPIC_API_KEY`, and its run summary prints no `Model` line.
- `claude-cli` and `codex` need no API key — they authenticate via your existing CLI sign-in — but are opt-in and **not recommended for reproducible runs**: each shells a local coding assistant that inherits its working directory's project context, so neither is a clean, deterministic model API.
- **Usage capture (`usage.json`).** Every provider reports tokens. `anthropic` prices them from a built-in list-price table, and `claude-cli` reports its own cost. `openai-compatible` reads the response's `usage` block (`prompt_tokens`, `completion_tokens`, and `prompt_tokens_details.cached_tokens`, which is moved out of `input_tokens` into `cache_read_input_tokens`); `codex` reads the `input_tokens` and `output_tokens` of its `turn.completed` events. Neither of those two is priced, so each call counts toward `unpriced_calls`. `reported_cost_usd` is `null` when no call reported a price, so an unknown cost does not read as `0`; otherwise it equals `total_cost_usd`. Prompt-cache writes that `anthropic` reports appear as `cache_creation_input_tokens`.
- When a manifest declares **any** paid (`l402-http`) capability and resolves to a CLI provider (`claude-cli`/`codex`), Writ runs a one-time pre-flight probe of that CLI at run start — see [Settlement](/docs/guides/settlement#the-model-cli-pre-flight-probe) — so a broken CLI is caught before any sats are spent, not on the first model call.
## `budget`
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `total_sats` | integer (min 0) | yes | — | Cumulative spend cap for the whole mission, enforced atomically at the credential-chain root. **Must be greater than 0 if any capability is `l402-http`** — a zero or missing cap on a mission with a paid capability is refused before it runs (`budget.total_sats must be greater than 0 when the mission declares a paid (l402-http) capability; a zero or missing cap would allow unbounded spend.`). |
| `per_call_max_sats` | integer (min 0) | no | — | Ceiling for any single capability call. A call is refused before payment if the price exceeds this **or** the capability's own `max_sats_per_call`, whichever is lower. |
| `currency_display` | enum | no | `"sats"` | `sats` or `usd` — display unit for human output only. All accounting is in sats regardless. |
```yaml
budget:
total_sats: 200
per_call_max_sats: 25
```
`writ validate` reports the worst-case total (every worker's budget slice charged at its capability ceiling) against this cap, and refuses a manifest whose worker budgets sum to more than `total_sats`.
## `settlement`
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `mode` | enum | no | `"simulated"` | `simulated` runs the full pipeline — credential, reserve, pay, settle, receipt — against an in-process L402 endpoint, no real money. `wallet` pays real Lightning invoices via a detected wallet (LND → NWC → Strike), bounded by the manifest budget. |
```yaml
settlement:
mode: simulated
```
See [Settlement](/docs/guides/settlement) for the full comparison, including the `--production` fail-closed posture and the real-money banner `writ run` prints for wallet mode.
## `approvals`
Human-in-the-loop gate. Omit the block, or leave it empty (`approvals: {}`), for fully autonomous operation within the budget/scope bounds.
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `threshold_sats` | integer (min 0) | no | — | Any single call at or above this sat amount suspends the run for human approval. `0` means every paid call needs approval. |
| `cumulative_threshold_sats` | integer (min 0) | no | — | The total sats the run may spend **without** approval. A call that would take the run's unapproved spend over this suspends for approval. See [Cumulative and windowed thresholds](/docs/guides/approvals-and-budgets#cumulative-and-windowed-thresholds). |
| `window_threshold_sats` | integer (min 0) | no | — | The sats the run may spend without approval in any rolling window of `window_seconds`. Requires `window_seconds`. |
| `window_seconds` | integer (1 to 31536000) | with `window_threshold_sats` | — | Length of the rolling window, in seconds. Requires `window_threshold_sats`. |
| `approval_ttl_minutes` | integer (min 1) | no | `15` | How long a granted approval stays usable. |
```yaml
approvals:
threshold_sats: 50 # any single call at or above 50 sats asks first
cumulative_threshold_sats: 200 # at most 200 sats in total without asking
window_threshold_sats: 60 # at most 60 sats per rolling hour without asking
window_seconds: 3600
```
The block is active when any of `threshold_sats`, `cumulative_threshold_sats` or `window_threshold_sats` is present; each one you omit is off. `writ validate` refuses a negative threshold, a `window_threshold_sats` without `window_seconds` (or the reverse), and a `window_seconds` outside 1 to 31536000 (one year).
## `capabilities`
Array (minimum 1) of capabilities the mission may call. A worker's `scope` must reference these ids.
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `id` | string | yes | — | Pattern `^[a-z0-9]+([.][a-z0-9]+)*$` (hierarchical, e.g. `dns.whois`, `llm.write`). Capability caveats match against this. |
| `kind` | enum | yes | — | `internal` (in-process, no sats: a model call, except `compose` and `compose.*`, which assemble prior outputs with no model), `http` (plain HTTP, SSRF-guarded, no payment), `l402-http` (paid per-call over L402). |
| `base_url` | string | required for `http`/`l402-http` | — | SSRF-guarded and DNS re-resolved at call time. |
| `path` | string | no | — | Resource path appended to `base_url`. |
| `method` | enum | no | `"GET"` | `GET` or `POST`. |
| `max_sats_per_call` | integer (min 0) | no | `0` | Per-call price ceiling for this capability. An L402 challenge above this is refused before payment. `0` for internal. |
| `allow_local` | boolean | no | `false` | Permit loopback/private targets for **this capability only** (local mock/demo endpoints). Cloud-metadata endpoints are still denied. `writ validate` flags this loudly. |
```yaml
capabilities:
- id: dns.whois
kind: l402-http
base_url: https://api.lightningenable.com/l402/proxy/dns-and-whois-afae
path: /whois
method: GET
max_sats_per_call: 5
- id: llm.write
kind: internal
```
Real `writ validate` output for a capability with `allow_local: true`:
```
!! 1 capability permit LOCAL targets (allow_local):
! capability 'test.local' permits LOCAL/loopback targets (allow_local) — cloud-metadata endpoints are still denied.
```
A duplicate capability id is a hard error: `Capability id 'a.b' is declared more than once.`
## `workers`
Array (minimum 1). Each worker receives a delegated child credential — strictly narrower than the mission root (its scope, a slice of the budget, a shorter expiry). Workers run **in order** (v1 has no parallel execution).
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `name` | string | yes | — | Pattern `^[a-z0-9][a-z0-9-]*$`. Appears as the actor in the work record. |
| `scope` | array of string | yes | — | The capability ids this worker's delegated credential may call. Must be a subset of the declared capabilities. A worker scoped to one capability gets that exact capability in its credential; a worker scoped to several gets a `capability_in` caveat listing exactly those ids, so the credential itself refuses anything else. When `scope` lists more than one capability, each id may contain only letters, digits, `.`, `_`, and `-` (the `capability_in` member charset); anything else is a validation error (`Worker 'w1' scope entry 'c d' may contain only letters, digits, '.', '_' and '-' when a worker is scoped to more than one capability.`). The `id` pattern above already satisfies this. A worker attempting a capability outside its `scope` is a validation error (`Worker 'w1' call step references capability 'c.d' which is not in the worker's scope.`) unless the step sets `expect_refusal: true`. |
| `budget_sats` | integer (min 0) | no | — | Cumulative sat slice for this worker. Sum across top-level workers must not exceed `budget.total_sats` (`writ validate` enforces this: `Top-level worker budgets sum to 16 sats, which exceeds budget.total_sats (10).`). `0` = an internal-only worker with no external spend authority. |
| `expires_minutes` | integer (min 1) | no | `30` | Lifetime of the worker's delegated credential. |
| `parent` | string | no | — | Name of another worker (declared **earlier**) that delegates authority to this one — a real agent→agent hop: this worker's credential is attenuated from the parent's, not from the mission root. The grant must be strictly narrower than the parent's (scope ⊆ parent, budget ≤ parent, expiry ≤ parent); the authority engine enforces this cryptographically. Omit for a top-level worker delegated straight from the root. A child's budget is a sub-allocation of its parent's slice — it does **not** count again toward `budget.total_sats`. |
| `steps` | array (min 1) | yes | — | See [steps](#steps) below. |
```yaml
workers:
- name: infra-researcher
scope: [dns.whois]
budget_sats: 40
expires_minutes: 30
steps: [{ type: call, capability: dns.whois, input: { domain: "{{target_domain}}" }, output: infra.json }]
```
### Steps
Each item in `workers[].steps`:
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `type` | enum | yes | — | `call` = one deterministic capability call. `agent` = a bounded LLM tool-loop choosing only among the worker's scoped capabilities. |
| `capability` | string | required for `type: call` | — | The capability id to invoke. |
| `task` | string | required for `type: agent` | — | The instruction to the worker model. May reference `{{vars}}`. |
| `max_iterations` | integer (min 1) | no | `6` | For `type: agent`: hard cap on tool-loop iterations. Each iteration is one real LLM completion call. |
| `input` | object | no | — | For `type: call`: structured input for the capability (query params / body / internal-executor instruction). |
| `output` | string | no | — | Filename to write this step's output under `runs//` (e.g. `dossier.md`). Must be a relative path confined to the run directory — absolute paths and `..` escapes are refused. The file holds untrusted capability/LLM content; don't open it directly in a browser. |
| `expect_refusal` | boolean | no | `false` | `type: call` only: assert this call is **expected to be refused** by the authority/budget guard (an overreach — out of scope, over budget, expired). A refusal is recorded as a signed `denied` work-record entry and the run **continues**. If the call unexpectedly *succeeds*, the run fails — the delegated bound had no teeth. |
`writ run --dry-run`'s planning estimate for an `agent` step is `max(scoped capability ceiling) × max_iterations`, capped at the worker's own `budget_sats` if set. For the `writ init` scaffold, whose researcher is scoped to two 5-sat capabilities with `max_iterations: 6` and `budget_sats: 40`:
```
· infra-researcher/infra-researcher:agent 30 sats planned
```
## `work_record`
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `signing` | enum | no | `"dev-ephemeral"` | `dev-ephemeral` generates a throwaway per-run key (loud warning; refused under `--production`). `env` reads `WRIT_RECEIPT_KEY`. `key-file` reads the path at `key_file`. |
| `key_file` | string | required when `signing: key-file` | — | Path to the signing key. |
| `identity_file` | string | no | — | Path to the signer identity record (`signer-identity.json`, written by `writ keys init`) for `signing: env`/`key-file`. Defaults to the file next to `key_file`, or `WRIT_RECEIPT_IDENTITY_FILE` for `env`. The record is copied into the run directory and its hash is committed into the first receipt. Required under `--production`; a warning when missing otherwise. |
| `output_dir` | string | no | `"runs/"` | Root directory for run outputs. Must be a relative path with no `..` escape — an absolute/rooted path is refused. |
```yaml
work_record:
signing: key-file
key_file: keys/receipt.key
output_dir: runs/
```
See [Keys and verification](/docs/guides/keys-and-verification) for the full `writ keys init` → run → `writ verify` lifecycle, including rotation and revocation.
## Where the schema and the real validator agree — and one place they don't
`writ validate` and `writ run` share one parser and one validator, so an `OK` from `validate` means `run` accepts the same file. `validate` lists every validation problem it finds (`Manifest invalid (2 problem(s)):` and so on); a file that cannot be parsed at all reports the parse error alone.
==============================================================================
# Security model and preview limitations
Source: https://writ.lightningenable.com/docs/security-and-limitations
==============================================================================
# Security model and preview limitations
This page describes what Writ's guardrails are **designed to do**. Writ's authority-narrowing engine is covered by an adversarial internal test suite and has been through two internal security-review passes. It has **not** had a formal external security review.
## What the guardrails are designed to do
- **Writ does not hold funds.** Your own wallet makes Lightning payments; the capability providers settle directly with it. Writ issues and verifies spending authority, and records what happened. It never holds funds, but in wallet mode it does instruct your wallet to pay each capability's invoice, and only within the ceiling the credential authorizes.
- **Fail-closed by default.** An unknown macaroon caveat denies. A missing budget account on a capped credential denies. An unresolvable clock denies. Under `--production`, a missing signing key refuses to run rather than falling back to a throwaway one.
- **No secrets in evidence.** Receipts and logs carry hashes and safe identifiers only — never a macaroon, preimage, key, or raw prompt/response body. When a CLI model provider's stderr might echo prompt content back (an argv-echoing parse error, for instance), Writ suppresses that snippet outright rather than risk leaking it into a log.
- **Idempotent money path.** Paying once executes once; a replayed settlement moves budget once. Reservations are released on every *proven* no-funds-moved failure path — and deliberately **retained**, not released, when the outcome is merely unknown (see [Settlement](/docs/guides/settlement#ambiguous-payment-outcomes)).
- **Approvals are bound to the exact request.** Covered in full in [Approvals and budgets](/docs/guides/approvals-and-budgets#what-a-grant-is-bound-to).
- **Authority on a service host comes from the operator.** The service hosts, `writ-mcp` and the HTTP API (`writ-api`), are separate programs from the `writ` CLI. They serve an agent role and an operator role. The agent role runs calls under a writ it holds, narrows that writ for sub-agents, revokes the writs beneath it, reads its host's workspace, and reads its own records in any workspace where it presents a live writ; issuing writs, approving and denying held spends, revoking by id and reconciling payments are the operator's (`writ-mcp --role operator`, the operator token, or `writ issue|approvals|revoke|reconcile --service-db`). Run the host under its own OS account, with its database, `WRIT_ROOT_KEY` and launch configuration readable only by that account: see [Setting up the host](/docs/reference/agent-api#setting-up-the-host).
- **SSRF-guarded.** Every capability URL, and the LLM `endpoint`, is checked — DNS re-resolved at call time — and loopback/private/cloud-metadata targets are denied unless a capability explicitly opts in with `allow_local` for local testing (and `allow_local` is a hard error under wallet settlement / `--production`). In wallet mode, the connection is pinned to the vetted IP so a DNS rebind can't swap in an internal target after the check.
- **Model CLIs run with no tool surface.** Writ feeds a model the bodies of paid third-party responses, so a prompt injection arriving inside purchased content is an expected input, not a hypothetical one. The `claude-cli` provider runs with `--tools "" --strict-mcp-config` (no built-in tools, no MCP servers); `codex` runs with `--sandbox read-only`, web search off, and a fresh empty temp directory as its workspace — nothing on disk for an injected instruction to read back into the work record.
- **The manifest is semi-trusted input.** A mission file is shareable, and may be agent-authored. `${ENV}` reads are opt-in per variable (declared in the manifest's own `env:` block, or `WRIT_VAR_`-prefixed), and secret-shaped names are refused even when declared — see the [manifest reference](/docs/reference/manifest#env) for the error text. A `model.api_key_env` can't name a protected Writ/system secret. A `total_sats: 0` mission with a paid capability is refused outright. Every output path is confined to the run directory. Step-output files hold untrusted capability/LLM content — don't open them directly in a browser.
## What `writ verify` shows, and what it doesn't
`writ verify` offline-checks that every receipt in a work record is validly signed by the claimed key, correctly hash-chained to the receipt before it, and — when a terminal commitment is present — that the exported chain wasn't truncated after the fact. Full walkthrough with real output: [Keys and verification](/docs/guides/keys-and-verification).
**It verifies:** each receipt's signature, every hash-chain link, strict sequence continuity, and the receipt protocol version — plus, when present or supplied, the terminal commitment, a pinned head attestation, the signer identity record, and the rotation and revocation records.
**It does not re-derive:** authorization (the call was within a delegated credential's scope and budget), payment (a receipt for a paid capability commits to a payment witness), or completion (the step ran and produced a result). The verifier has no access to the credentials, ledger, or wallet; those facts are what the operator's signer *attested* in each receipt. A clean verify shows that the attestations were signed by that key and that the chain is intact, for exactly the steps recorded in it.
**It does not show:** that the underlying work was *good*. Writ does not verify output quality: a signed receipt is the signer's attestation that an authorized, paid, completed action happened, never that its result was correct, unbiased, or useful.
## Signer identity is self-asserted
`writ verify` binds a chain to a self-signed operator identity record, walks signed rotation and revocation records forward from one pinned anchor key, and checks head attestations. The identity itself is asserted by the key that created it: trust it the way you trust the public key you chose to pin. Writ has no hosted signer registry or transparency log. `writ record publish-head --relay ` publishes a head attestation to a Nostr relay you choose, as event kind 38410, and `writ record verify-head` checks a relay's copy against the local record; `wss://agents.lightningenable.com` is a public relay that accepts these events. A relay is not a transparency log: it can withhold or lose a later head, so publish to and check more than one relay to detect a withheld head. `--post ` sends the attestation to a URL you choose. See [`record publish-head`](/docs/reference/commands#record-publish-head).
## Preview limitations, stated plainly
Each row states a limit of the preview and how Writ handles it:
| Limitation | Status |
|---|---|
| **Resuming needs a persistent authority key and signer.** `writ resume` continues a suspended or interrupted run only when the run started with `WRIT_ROOT_KEY` set and a `work_record.signing: env` or `key-file` signer; a run started without them is refused, unchanged. Worker credentials keep their original expiry, so a run whose approval takes longer than the worker's `expires_minutes` cannot continue. A call that may have paid but was never recorded halts the resume for `writ reconcile`, and when it is reconciled as paid its output is lost, so the remaining steps need a new run. Free (no-sats) calls are at-least-once across a crash: one killed after it ran but before its result was recorded runs again on resume, and the abandoned first attempt is listed in run.json's `AbandonedAttempts`. A wrong `writ reconcile --resolve not-paid` (the payment did go out) makes the resume pay that call a second time: attest only what your wallet shows. `run.lock` is an operating-system file lock: advisory on Linux and macOS (only processes that take it are kept out) and unreliable on network file systems (NFS, SMB), so keep run directories on a local disk and never run one run from two hosts. If the end of a run's journal is lost and an agent step is asked again and decides differently, that step fails on the idempotency fingerprint and the remaining work needs a new run; nothing is paid twice. | By design (fail closed): see [Approvals and budgets](/docs/guides/approvals-and-budgets#resuming-a-suspended-run). |
| **A receipt that was never staged keeps the run at exit `6` permanently.** When the store refused both a receipt and its staged request, the payment is in the ledger (and in the proof journal when one was written), but the signed receipt cannot be reconstructed, and no command clears the gap. Automation gating on exit `6` must treat it as "work done, evidence incomplete" and must not re-run the mission. | By design (Writ does not invent evidence): see [Troubleshooting](/docs/troubleshooting#receipt-never-staged). |
| **Staged work records are bound to the host's root key.** Run hosts that stage receipts with a persistent `WRIT_ROOT_KEY`, keep the host database writable only by the host account, and drain the outbox before rotating the key. Records already stuck are handled with `writ outbox`: re-signed on a service host after a ledger cross-check, or discarded with a recorded reason (a run then exits `11`). | Runbook in [Troubleshooting](/docs/troubleshooting#outbox-key-mismatch). |
| **Strike can't confirm an ambiguous wallet payment automatically.** `writ reconcile` asks the wallet to look a held payment up by hash first: LND and NWC can usually answer; Strike's API has no such lookup, so a Strike hold needs your explicit `--resolve paid\|not-paid`, and `not-paid` there also needs `--allow-unconfirmed-not-paid`, which the audit log records. | Writ retains the hold instead of guessing, and looks the payment up automatically on LND and NWC. The Strike gap is a constraint of Strike's API. |
| **Aggregate approval thresholds are opt-in.** `threshold_sats` alone is per call: repeated spends just below it are bounded only by the budget caps. Set `cumulative_threshold_sats` and/or `window_threshold_sats` + `window_seconds` to bound the spend made without approval across a run; a service host's `WRIT_APPROVAL_CUMULATIVE_SATS`, `WRIT_APPROVAL_WINDOW_SATS`, `WRIT_APPROVAL_WINDOW_SECONDS` count across every writ and workspace in its database (so one workspace's spend affects, and is visible in aggregate to, every workspace on that host). On a service host the operator decides held spends and issues writs. Approving does not reset the count, a denial does not stick, and a few cases can leave the unapproved spend above the threshold (see the guide). Each paid call under an aggregate threshold runs an aggregate query over the scope's history twice, once inside the reservation's write transaction (about 120 ms each at 50,000 rows in scope, measured on Windows). | Opt-in by design: see [Cumulative and windowed thresholds](/docs/guides/approvals-and-budgets#cumulative-and-windowed-thresholds). |
| **Schema upgrades are forward-only.** The database is stamped with a schema version. Opening one from an older Writ applies the known upgrades in order, in one transaction. They are additive, except two steps that rebuild a table, copying every row and index, because SQLite can't alter a CHECK constraint; one written by a newer Writ, or one that is not a Writ database, is refused unchanged with an actionable error. Every upgrade first writes a backup beside the database (`.backups/.schema-v-.bak`, in an owner-only directory), and is refused if the backup cannot be written; `writ db status` and `writ db upgrade` show and perform it explicitly. There are no down-migrations: to roll back, restore the backup with no Writ process using the database. | By design: every upgrade writes a backup first. |
| **Rail-neutral architecture; Lightning-native today.** L402 over Lightning is the only implemented settlement rail. | By design, not tracked as a bug. |
| **Delegation is manifest-declared.** Multi-hop delegation narrows real cryptographic authority between workers *you* declare in the manifest (budget, expiry, and capability scope all narrow in the credential: a worker scoped to one capability carries that exact capability, and a worker scoped to several carries a `capability_in` caveat listing exactly those capabilities, so its credential alone refuses any capability outside its scope; the orchestrator's own scope check stays as defense in depth) — Writ doesn't discover, contract, or hire arbitrary external agents at runtime. | By design, not tracked as a bug. |
| **Model cost is priced for the `anthropic` and `claude-cli` providers only.** `openai-compatible` and `codex` record tokens in `usage.json` but no price, so each call counts toward `unpriced_calls` and `total_cost_usd` is a lower bound rather than a silent `$0`; `reported_cost_usd` is `null` when no call reported a price. A priced-table miss on `anthropic` shows up the same way. An OpenAI-compatible server that omits the `usage` block contributes no tokens. | By design: Writ has no price table for those providers. |
Run artifacts are private by default (see [Run artifacts and export](/docs/guides/run-artifacts-and-export#private-by-default)), and an approval is bound to the exact request it was granted for (see [Approvals and budgets](/docs/guides/approvals-and-budgets#what-a-grant-is-bound-to)).
## What leaves your machine
Writ sends **no telemetry, analytics, or crash reports**. There is no account, no sign-in, and no Writ-operated service in the loop. The only network traffic a run produces is what the mission manifest declares:
- **Capability calls** (`kind: l402-http`) go to the `base_url` of each capability, with the request body the step builds. In `simulated` mode, no capability call leaves the process: the example missions in these docs name `api.lightningenable.com` proxy URLs, and Writ contacts them only in `wallet` mode. Lightning Enable is a separate product of the same company, Refined Element, LLC; each capability's price ceiling is the `max_sats_per_call` you declare in the manifest, and the provider's actual invoice must come in at or under it.
- **Model calls** go to the provider you configure: Anthropic's API for `anthropic`, your configured endpoint for `openai-compatible`, or your locally installed Claude Code or Codex CLI (which bills your own account). A step calls the model when it is an `agent` step, or a `call` to any `internal` capability other than `compose` / `compose.*`, and the prompt (including the paid data the step feeds it) goes to that provider. A mission whose steps are all `l402-http` or `compose` calls, such as the [first mission](/docs/getting-started/first-mission), makes no model call and no model probe, and names no model in its outputs. Model call count and list-price cost appear in the run summary, `report.html`, `writ record show`, and `usage.json`; that cost is billed by your provider and is outside the sats budget.
- **Wallet traffic** (`settlement.mode: wallet`) goes to your own LND, NWC, or Strike wallet.
Nothing in a run directory is uploaded anywhere unless you run `writ record publish-head` with `--post` or `--relay`, against a URL or relay you choose.
## What's explicitly out of scope for v1 (by design)
- No hosted control plane or SaaS: Writ is a self-hosted runtime you run.
- No marketplace or service discovery: a mission calls the capabilities its manifest declares.
- No output-quality verification, as above.
- No custody of funds.
## Next steps
- [Troubleshooting](/docs/troubleshooting): the errors you are most likely to meet and how to fix them.
- [Keys and verification](/docs/guides/keys-and-verification): the full signer lifecycle.
==============================================================================
# Troubleshooting
Source: https://writ.lightningenable.com/docs/troubleshooting
==============================================================================
# Troubleshooting
Every error message on this page is output from the `writ` 0.1.0 tool. Search this page for the message you're looking at. The full list of exit codes, including `1`, `8`, `9`, `10` and `130`, is in the [command reference](/docs/reference/commands#exit-codes).
## Exit code 2 — validation error
Something about the manifest, or the command's own input, is wrong. Nothing was minted, called, or spent.
**Manifest structurally invalid** (missing a required field):
```
Manifest invalid (1 problem(s)):
- mission is missing required field 'goal'.
```
Fix: add the missing field. `writ validate` lists every problem it finds, for example:
```
Manifest invalid (2 problem(s)):
- Top-level worker budgets sum to 40 sats, which exceeds budget.total_sats (0).
- budget.total_sats must be greater than 0 when the mission declares a paid (l402-http) capability; a zero or missing cap would allow unbounded spend.
```
A manifest that cannot be parsed at all reports the parse error alone.
**File not found:**
```
Manifest invalid (1 problem(s)):
- Manifest file not found: /does-not-exist/mission.yaml
```
```
Manifest could not be read: Could not find a part of the path 'F:\...\mission.yaml'.
```
Fix: check the path. `writ validate` and `writ run` word the same problem differently; both mean the file isn't there.
**Not valid YAML/JSON:**
```
Manifest invalid (1 problem(s)):
- Manifest is not valid YAML/JSON: While parsing a flow sequence, did not find expected ',' or ']'.
```
**Worker budgets exceed the mission cap:**
```
Manifest invalid (1 problem(s)):
- Top-level worker budgets sum to 16 sats, which exceeds budget.total_sats (10).
```
**A worker calls a capability outside its scope:**
```
Manifest invalid (1 problem(s)):
- Worker 'w1' call step references capability 'c.d' which is not in the worker's scope.
```
Fix: add the capability to that worker's `scope:` list, or set `expect_refusal: true` on the step if the overreach is the point of the test.
**A zero/missing budget on a mission with a paid capability:**
```
Manifest invalid (1 problem(s)):
- budget.total_sats must be greater than 0 when the mission declares a paid (l402-http) capability; a zero or missing cap would allow unbounded spend.
```
**Duplicate capability id:**
```
Manifest invalid (1 problem(s)):
- Capability id 'a.b' is declared more than once.
```
**An undeclared `${ENV}` reference:**
```
Manifest invalid (1 problem(s)):
- Manifest references environment variable '${SOME_VAR}' but it is not allowed to read it. Only two forms may be
interpolated: a name listed in the manifest's top-level 'env:' block (add 'env: [SOME_VAR]'), or a name prefixed
'WRIT_VAR_'. Anything else must be passed with --var.
```
Fix: add `env: [SOME_VAR]` to the manifest, prefix the variable `WRIT_VAR_` in your shell, or (preferred) pass the value with `--var`.
**A secret-shaped `${ENV}` reference (refused even when declared):**
```
Manifest invalid (1 problem(s)):
- Refusing to interpolate a sensitive environment variable '${MY_API_KEY}' into a manifest. Secret values (keys,
tokens, credentials) must never flow into a manifest field; declaring the name in 'env:' or prefixing it does
not change that. Use a non-secret variable or pass configuration via --var.
```
Fix: secrets never go into a manifest field. Read the secret in your own tooling instead of interpolating it into the mission file.
**Missing a required `--var`:**
```
Manifest invalid: Manifest references variable '{{target_name}}' but no --var target_name=... was supplied.
```
Fix: `writ run mission.yaml --var target_name=...`.
**Bad `--var` syntax:**
```
--var must be name=value (was '').
```
**`writ revoke` or `writ reconcile` without an audit key:**
```
AuditKeyNotConfigured: WRIT_AUDIT_KEY is not set, and this command signs audit rows under it. Set WRIT_AUDIT_KEY to this host's audit key, or pass --development-audit-key to use the development audit key built into Writ, which is the same in every copy of Writ and proves nothing about who signed.
```
Fix: set `WRIT_AUDIT_KEY` to a secret you choose and keep, the same way as `WRIT_ROOT_KEY` in [Approve and resume a run, end to end](/docs/guides/approvals-and-budgets#approve-and-resume). Use `--development-audit-key` only for tests.
**`writ keys` / `writ record` / `writ approvals` / `writ revoke` / `writ reconcile` input errors** (a sample; all exit `2`):
```
--operator-name is required: the identity record names who operates this key (it is published with every run).
Refusing to overwrite existing key file 'keys/receipt.key'. Use --out to create a new key at a different path.
No signer identity record at 'keys/signer-identity.json'. Run `writ keys init --operator-name ` to create a key + identity.
A run id is required.
No database found for run '' at runs\\writ.db.
Credential #9999 was not found in run ''.
Could not approve #1: Approval request is already approved.
Could not deny #999: Approval request not found.
--resolve must be exactly 'paid' or 'not-paid' (was 'maybe').
```
### Database schema error
Every Writ database is stamped with a schema version. When `writ approvals`, `writ revoke`, `writ reconcile`, or a `writ-mcp` / `writ-api` host opens a database from an older Writ, it applies the known additive upgrades in order and carries on. It refuses, and changes nothing, in two cases:
```
Database schema error: This Writ database is at schema version 13, which is newer than this build of Writ understands (up to 12). It was written by a newer Writ release. ...
Database schema error: This database (schema version 0) cannot be upgraded to Writ schema version 12: table 'ApprovalRequests' is missing; ... It is either not a Writ database or it is damaged. Nothing was changed. ...
```
The first means a newer Writ release wrote the database: upgrade Writ to that release. The second means the file is not a Writ database, or it is damaged: point the host at a different database (`WRIT_DB_PATH`), or restore it from a backup. A service host reports the same messages as a configuration error at startup. Copy the database file, and its `-wal` and `-shm` files, before you upgrade Writ.
## Exit code 3 — run failed {#exit-code-3}
The mission started but didn't complete. Check budget, execution, and authority first.
#### Agent model returned no usable response {#agent-model-returned-no-usable-response}
```
Worker 'researcher' agent model returned no usable response.
```
This appears when an `agent`-type step's LLM call fails or returns nothing usable. The log line before it gives the reason, for example, with `model.provider: claude-cli`:
```
warn: Writ.Engine.Llm.ClaudeCliLlmClient[0] claude CLI exited non-zero: ExitCode=1. Stderr (first 200 chars): ...
```
Confirm that `claude --version` works in the same shell, or use the `anthropic` provider (`model.provider: anthropic` + `ANTHROPIC_API_KEY`).
**Agent response wasn't valid JSON:**
```
Worker '' agent response was not a valid tool/final JSON object: .
```
**Agent attempted a capability outside its scope:**
```
Worker '' agent attempted capability '' outside its scope.
```
The model chose a capability its worker isn't scoped to. This is the authority engine doing its job — nothing to fix in the manifest unless you meant to grant that scope.
**Unhandled run exception:**
```
Run failed:
```
`writ run` prints the message without a stack trace.
## Exit code 4 — approval required
The run suspended, not failed: a call crossed an approval threshold. Approve it, then continue the same run with `writ resume`. [Approve and resume a run, end to end](/docs/guides/approvals-and-budgets#approve-and-resume) shows the setup a resumable run needs.
```
Suspended — pending approval #1. Approve with: writ approvals approve 1 --run
Then continue the run with: writ resume
Spend requires human approval.
```
A run that started without `WRIT_ROOT_KEY`, or with a `dev-ephemeral` signer, cannot be resumed, and says what to set before you run the mission again:
```
Suspended — pending approval #1.
This run cannot be resumed: it started without WRIT_ROOT_KEY. To approve and continue a run, set WRIT_ROOT_KEY to a secret you keep and use work_record.signing: key-file (or env), then run the mission again.
Spend requires human approval.
```
## Exit code 5 — verification failed
`writ verify` found at least one problem. See [Keys and verification](/docs/guides/keys-and-verification) for the full catalog with context; quick reference:
```
FAILED — problem(s) across receipt(s):
[row 0] : signature verification failed # wrong --pubkey
[row 0] : receiptHash does not match the recomputed canonical hash (tampered field) # tampered content
the run summary's terminal commitment signature does not verify under the supplied public key — refusing to trust it (the run summary may have been tampered with).
--require-identity: no signer identity record was found and the chain is not bound to one.
key was revoked at but receipt(s) (first: sequence , occurred ) were signed at/after that instant — not evidence.
```
`writ verify` requires `--pubkey`:
```
Option '--pubkey' is required.
Run `writ verify --help` for usage.
```
(exit `2`, not `5`: a missing required option is a usage error, not a verification failure.)
## Exit code 8 — verification incomplete
Every receipt verified, but nothing binds the end of the chain, so a shortened record would look the same:
```
INCOMPLETE — 1 receipt(s) verified, but no terminal commitment is available, so tail truncation cannot be ruled out.
```
Fix: verify the run directory or the exported bundle (which holds `run.json`), not `work-record.jsonl` on its own, or pass `--expect-head` or `--pinned-head`.
## Exit code 6 — missing work record
Every step ran, but the run's evidence is incomplete (outcome `ExecutedReceiptPendingRecovery`). Writ never reports this as clean success. `run.json` says which case you are in:
- **`ReceiptsPendingRecovery`**: the receipt's request is staged in the run database. `writ resume ` appends it, and the run then exits `0`. If a resume leaves it pending, `writ outbox list ` says why; see [staged work records that never replay](#outbox-key-mismatch).
- **`WorkRecordExportError`**: the receipts are in the run database, but `work-record.jsonl` could not be written. `writ resume` re-exports it.
- **`MissingReceipts` with nothing staged**: see the next section.
### A receipt that was never staged {#receipt-never-staged}
If the store refused both the receipt and its staged request (for example, a full or failing disk at that instant), the payment still happened and is recorded. The signed receipt, however, **cannot be reconstructed**. The facts it would commit to, such as the output hash and the payment witness, were never written anywhere durable. Writ does not invent a receipt after the fact.
- **What it means:** the invocation is settled in the ledger. When it paid, its payment hash and proven amount are on the invocation row (or in the signed proof journal `.proofs.jsonl`). There is just no signed receipt in the chain for it.
- **No command clears it.** Every later `writ resume` reads the gap from the ledger and keeps the run at exit `6`. This is deliberate: the evidence really is incomplete.
- **Your evidence instead:**
- the run database's invocation and budget rows for that invocation id;
- the signed audit log (`invocation.proof_applied` and related events);
- the proof journal, if one was written;
- your wallet's record of the payment hash.
- **Automation that gates on exit `6`** should treat it as "work done, evidence incomplete". Do not re-run the mission to "fix" it, because a new run pays again. Do not retry the same call under a new idempotency key. Flag the run for a human, and record the invocation ids listed in `MissingReceipts` alongside it.
### Staged work records that never replay {#outbox-key-mismatch}
Each staged request is authenticated by a key derived from the host's `WRIT_ROOT_KEY`, and is appended only when it verifies under the current key and matches the ledger. A service host (`writ-mcp`, `writ-api`) that ran without a persistent `WRIT_ROOT_KEY`, or whose key was rotated while records were pending, leaves records that a restart does not append; the host logs them once per start.
Setup that avoids it:
- Run any host that stages receipts with a **persistent** `WRIT_ROOT_KEY`, and keep its database writable only by the host account.
- **Before replacing a host's root key, clear what the operator commands show:** restart the host (or `writ resume` a run), run `writ reconcile --service-db --workspace ` and `writ outbox list --service-db --workspace `, and clear what they list, because holds and records signed under the old key need the operator afterwards. Then rotate.
When records are already stuck, use [`writ outbox`](/docs/reference/commands#writ-outbox):
1. **Stop the host**, or make sure no `writ run` / `writ resume` is running the run. Set `WRIT_ROOT_KEY` to the host's current key, and point the command at the same database path the host uses (its `WRIT_DB_PATH`) and the host's workspace (its `WRIT_WORKSPACE`, else `default`). If a command answers `root_key_unrecognized` while `WRIT_ROOT_KEY` is the host's key, restart the host so it records its key, then run the command again.
2. **List the records and why each is stuck.** After a key change on a service database, read the previous key first (as in step 3) and pass it, so the list offers `resign` for each record that can be re-signed:
```
writ outbox list --service-db --workspace --previous-root-key-env WRIT_PREVIOUS_ROOT_KEY
writ outbox list --service-db --workspace
writ outbox list
```
3. **On a service database, re-sign a record this host staged under its earlier key.** Read the host's previous `WRIT_ROOT_KEY` into an environment variable without echoing it or writing it to your shell history, then pass the variable's name. If the previous key was replaced because it may have been exposed, use `discard`, not `resign`.
```
read -rs WRIT_PREVIOUS_ROOT_KEY && export WRIT_PREVIOUS_ROOT_KEY
writ outbox resign --service-db --workspace --invocation --previous-root-key-env WRIT_PREVIOUS_ROOT_KEY
```
In PowerShell:
```powershell
$env:WRIT_PREVIOUS_ROOT_KEY = Read-Host -MaskInput "Previous WRIT_ROOT_KEY"
writ outbox resign --service-db --workspace --invocation --previous-root-key-env WRIT_PREVIOUS_ROOT_KEY
```
The record is re-signed only when its own MAC verifies under the previous key, it matches the ledger, and, for a paid call, a proof event naming the same payment verifies under the current or the previous key. `writ outbox list` with the same `--previous-root-key-env` shows `resign` among a record's actions when these checks pass. Restart the host: it appends the receipt. If the previous key is gone, discard the record. A `record_not_authenticated` refusal that says the record carries a time later than the key change can happen when the host's clock was behind the previous host's when the key changed; discard that record.
4. **Discard a record you cannot explain, one the commands refuse, and any stranded record on a run** (a run's key never changes, so such a record was not written by the run's own process):
```
writ outbox discard --service-db --workspace --invocation --reason "staged under a key we no longer hold"
writ outbox discard --invocation --reason "does not verify under the run key; not ours"
```
The record is kept and the reason is recorded in the signed audit log. The next `writ resume` (or host start) appends a signed `work_record_discarded` receipt for it, and a run ends with exit `11`.
5. **After rotating a service host's key, discard again** any record you had discarded under the earlier key whose discard receipt is not yet on the chain: `writ outbox list` shows it pending again. A discard receipt already on the chain stays.
## Exit code 11 — work records discarded by the operator
Every step ran, at least one executed step has no signed work record, and the operator discarded each missing one with `writ outbox discard` (outcome `ExecutedReceiptDiscarded`). It is never clean success, and nothing is left for `writ resume` to append. Each discard is recorded in a signed `receipt_outbox.discarded` audit event; `run.json` keeps each invocation in `MissingReceipts` and lists it in `DiscardedWorkRecords` with the reason; and the resume appends a signed `work_record_discarded` receipt to the chain for each discard whose invocation and credential the ledger holds (`writ outbox list` shows which are on the chain). Treat it like exit `6`: work done, evidence incomplete; do not re-run the mission.
## Exit code 7 — pending reconciliation
A wallet payment's outcome is unknown, and the budget hold is **retained**, not released or counted as spent. It is neither a success nor a failure. See [Settlement](/docs/guides/settlement#ambiguous-payment-outcomes) and [Approvals and budgets](/docs/guides/approvals-and-budgets#reconciling-a-pending-wallet-payment).
```
Invocation is still pending reconciliation (payment hash , sats held):
Check the payment in your wallet by that hash, then run: writ reconcile