package cabal_workflow_runner

All checked builds pass
  1. Overview
  2. Docs

Description

A deterministic interpreter for declarative agentic workflows (sequence, governed loop, branch, gate, agent, terminal commit). Agents return structured JSON; gate/branch/loop decisions are a total predicate DSL over a run context. Structural control flow runs deterministically in OCaml; agent steps dispatch through cabal. A fail-closed validator enforces a safety floor as an engine invariant (commit requires a runtime human-approval token plus floor gates guaranteed on every path; loops may be unbounded but must declare a governor). Recorded traces replay byte-identically.

Tags

agentic workflow deterministic engine cabal

Added to opam-repository:

README

cabal-workflow-runner

Deterministic v2 package

scripts/package-v2.sh seals an already built and normalized CWR executable, its schema, dependency lock, installed opam solution, Cabal package lock, and an external build-authority record and a separately admitted verifier-authority record into a fresh package directory. The producer requires clean CWR and Cabal checkouts at the exact revisions and trees named by the authority. cwr-build-authority@2 binds the exact normalized executable, schema, the exact canonical cwr-build-recipe@3, locks, and build/normalizer identities, versions and digests. cwr-package-verifier-authority@1 independently binds the verifier implementation and the build authority it may approve. The tools reject aliases, duplicate or non-canonical JSON, extra files and digest drift, emit cwr-build-receipt@2, and atomically publishes only after scripts/verify-package-v2.sh has created and rechecked cwr-package-verification@1. It does not create an admission or deployment claim.

scripts/build-package-v2.py executes that recipe in fresh private roots. Every recipe step runs with the workspace bind-mounted at the fixed root /var/tmp/cwr-v2-build, inside a private user and mount namespace (unshare), under the caller's uid. The compiler, opam and the private dune embed absolute build paths, so a workspace-dependent path would make the build tool's bytes, and therefore build.tool_sha256, differ between two honest builds. With the fixed root, independent builds in different directories produce byte-identical build authorities, and the authority keeps binding the exact bytes of the dune that ran. The builder creates the host directory if it is missing and refuses it unless it is an empty directory owned by the builder and not writable by group or others; the bind is private to each build, so concurrent builds do not interfere. The host needs unprivileged user namespaces and util-linux unshare with --map-user and --map-group; the builder checks this before copying any input. Host-side probes and the final verifier run with a minimal environment (PATH=/usr/bin:/bin, LC_ALL=C), not the private build environment.

The package is deterministic for identical input bytes. Binary normalization is an upstream build concern: the authority and receipt bind its format and tool, while this producer verifies rather than rewrites the reviewed binary. Hashing, JSON parsing and the executable probe operate on stable open file descriptions; publication uses a no-replace rename. The executable test in test/test_package_v2.sh builds and packages the real CWR executable and is the canonical end-to-end example.

Observe a durable channel

channel-observe validates a workflow and one operator-bound channel root, without running the workflow or creating a ledger, execution, receipt, or channel state. Example:

cabal-workflow-runner channel-observe workflow.json \
  --channel candidates --now 1791979200 \
  --channel-root '{"alias":"audit-root","root":"/srv/cwr/channels","identity":"audit-root-v1","principal":"scheduler"}'

Success is one compact JSON line with the fixed version-1 field order: schema_version, available, leased, acknowledged, retained_total, and oldest_available_age_seconds. The age may be null and is original-publication backpressure age, not processing lag. Exit 0 has empty stderr; authenticated domain rejection exits 1 with empty stdout and a coarse JSON error; output or other operational failure exits at least 2. Aggregate output intentionally contains no message, payload, principal, digest, token, or filesystem identity. Observation and every normal writer share a 128 MiB ceiling over canonical persisted state bytes. Writers reject the candidate state before mutable-state publication, and observation applies that same ceiling before JSON decoding; declaration-specific retained-message and finite live-receipt ceilings remain additional constraints. Root, state, message, status, receipt-wrapper, and versioned-receipt objects are exact and duplicate-free. Interruption after a snapshot does not change authenticated bytes, modes, mtimes, or artifacts; only pre-existing lock metadata may change. Store-open failures cross the C boundary as the stable classes invalid authority, busy contention, or operational I/O; classification does not inspect localized diagnostics. The production command has no ambient observation-test environment hook; deterministic post-snapshot interruption is injected only by the test-linked command boundary.

Inherited host-control boundary

Controlled execution is an explicit CLI opt-in over an already-open, unnamed Unix socket. CWR-to-controller Run requests expose only a closed public projection: opaque request, effect, and profile references plus required digests. Raw argv, selected input, working paths, schemas, credentials, authentication material, provider configuration, prompts/transcripts, and transport endpoints never appear in that outbound direction. The controller resolves secret-bearing invocation details from its trusted pinned profile. Controller replies intentionally carry executable identity and bounded Run result data, including arbitrary stdout, stderr, and file paths; these may be sensitive. They rely on same-process-tree trust in the private inherited socket, are never logged by the transport, and enter the sensitive durable journal under its access, size, retention, and redaction policy. Exact local digests preserve journal identity and replay correlation without disclosing request preimages.

A deterministic workflow engine on cabal (the Caml Agent Backend Abstraction Library). It interprets a declarative workflow — sequence, governed loop, branch, gate, and a terminal commit — running the control-flow deterministically in OCaml and dispatching agent steps via cabal.

Reusable workflow registry and composition

CWR can publish exact workflow bytes to an owner-private local registry and compose digest-pinned workflows before any workflow-consuming command acts:

exec 3<examples/reusable-check.workflow.json 4<.cwr-registry
cabal-workflow-runner registry-add --registry-root-fd 4 --workflow-fd 3
# Or omit --workflow-fd and provide the workflow on stdin.
exec 5<examples/composed.workflow.json 6>resolution-receipt.json
CWR_RESOLUTION_RECEIPT_FD=6 cabal-workflow-runner validate \
  --registry-root-fd 4 --workflow-fd 5

An import is a closed descriptor containing alias, kind: "workflow", exact sha256: digest, byte size, and the literal media type application/vnd.cwr.workflow+json;version=1. A compose step names the import and a unique ASCII namespace; expansion rewrites declarations and classified references as namespace::id. Types.workflow and Workflow_json remain the closed execution API; unresolved documents use Workflow_source, and all CLI consumers share one loader that invokes Workflow_resolver for imported documents before validation, execution, replay, compilation, digesting, or attestation verification while retaining the exact legacy no-import path.

Registry entries and locks are private, single-link regular files beneath a pinned private root. With no registry FD, imports use the owner-private ~/.cwr-registry; nondefault registry and workflow capabilities use inherited --registry-root-fd and --workflow-fd descriptors, so absolute capability paths and workflow bytes never enter argv. Publication is atomic/no-replace and fsynced. Registry command results use cwr-registry-result@1; exit 2 means invalid input, 3 a security/integrity failure, and 4 unavailable/not-found/busy authority. --cache-root is optional and disposable: it is populated only from verified registry bytes and is never a fallback authority. --resolver-root confines optional relative source locators; network access and mutable tags are not supported. Use source-schema or schema/workflow-source.schema.json for the unresolved format. The existing schema command remains unchanged for closed workflows.

Every resolving CLI consumer writes its closed success or partial-failure receipt to the inherited descriptor named by CWR_RESOLUTION_RECEIPT_FD, when set. The channel is deterministic NDJSON and contains no workflow bytes or absolute paths.

Durable channel delivery modes

A channel declaration accepts "mode": "fifo", "mailbox", or "priority". Omitting mode keeps the existing FIFO format and behavior. The modes are exclusive, and a stored channel cannot be reopened under a different mode.

On a mailbox channel, each send step supplies a nonempty recipient; a receive step can lease only messages addressed to its operator-bound principal. Within that mailbox, the oldest eligible publication wins. The principal is a routing identity supplied by the operator, not a new credential or an authentication check.

On a priority channel, each send supplies an integer priority from 0 to 9. The highest eligible priority wins; ties use publication order. An active lease is never preempted, and an expired message becomes eligible again. Strict priority can defer low-priority work indefinitely. In all modes, ordering governs lease selection, not completion order or exactly-once processing.

See the delivery-mode contract and the Quint checks for the precise guarantees.

Static Spawn experiment

{"kind":"spawn","id":"delegation","children":[{"id":"research","steps":[...]}, ...]} executes finite child bodies in declaration order against the shared CWR context. Child IDs are non-empty and unique within a Spawn; each body is non-empty. Spawn is rejected below Spawn, Parallel, Loop, and Foreach, and the compiler rejects it explicitly because its replay evidence cannot be represented faithfully in JS.

Agents return structured JSON bound into a run context; gate / branch / loop decisions are a total predicate DSL over that context (always terminating, never raising). Every loop is hard-bounded by an engine iteration ceiling (default 10_000) — the termination guarantee; Max_iters / Budget / Deadline / Fixpoint / until are early-stop heuristics under it (a loop must still declare ≥1 governor, by intent). A floor Gate that evaluates false blocks the run.

You get data-driven workflows without losing determinism, because the interpreter is deterministic, the safety floor is enforced by the engine/validator as an invariant over any workflow (not by the workflow author), and runs replay from a recorded trace — the governor's inputs (and the constant ceiling) are recorded, so even a loop that hits the ceiling replays byte-identically. See SPEC.md and CHANGELOG.md.

The Deadline governor

{"kind":"deadline"} stops a loop once an operator-supplied wall-clock instant has passed. The instant is not in the workflow file — it is supplied at runtime (Engine.run ~deadline), like the approval token and the Run allowlist. A workflow declaring Deadline under a runtime that supplies none never fires it, exactly as Budget never fires against a constant budget stub.

What it does not do. Deadline does not bound the duration of a step. Governors are checked between iterations, so a single long-running agent step can overrun the deadline by any amount; what the governor bounds is how many further iterations start. Agent steps carry no timeout, so "the run ends by T" is not a guarantee this feature provides — if you need a hard stop, you still need one outside the engine.

Replay is clock-free. Each check records its verdict (deadline_read, a bool — never a float, so the ledger round-trips byte-identically) and replay re-feeds the recorded verdict instead of re-reading the clock. Without that, a recorded run would stop being reproducible the moment its deadline passed. The JS compiler refuses a Deadline governor for the same reason: a JS target has no engine-recorded clock reading, so any emitted approximation would be a governor that looks present and behaves differently.

The project is domain-neutral. examples/bounty.workflow.json is just one illustration — the bounty pipeline expressed as a single workflow file. examples/proof-carrying-change.workflow.json is another: it gates an agent-authored code change on arch-index's change-impact and fitness-function verdicts rather than on an LLM's opinion of its own diff. See docs/proof-carrying-change.md.

  • Library cabal_workflow_runner (lib/): types, fail-closed validator, deterministic engine + replay, backend abstraction, JSON loader, and native Ed25519 attestation. It does not depend on cabal.
  • Executable cabal-workflow-runner (bin/): a small CLI; this is the only place that links cabal.

Planned workflow diagrams

Render a validated workflow without executing any step:

cabal-workflow-runner graph workflow.json > workflow.svg
cabal-workflow-runner graph --format mermaid workflow.json > workflow.mmd
cabal-workflow-runner graph --format json workflow.json > workflow.graph.json

SVG is the default and is standalone. The JSON form is the versioned cwr-workflow-graph@1 intermediate representation for dashboards and other consumers. All formats are deterministic for the same workflow and include its digest. They describe the declared, planned control flow only: they are not an execution trace, a reachability proof, or evidence that any step ran. Use the ledger and observation facilities for actual execution.

The SVG uses an automaton-style layout: the main transition spine is vertical, mutually exclusive and parallel routes fan out into separate lanes and rejoin through one explicit bus, and governed loops have a labelled return arc. Decision nodes contain their total predicate; gates state their pass/fail consequence; Run and Shell nodes expose a bounded tool identity rather than copying arbitrary arguments that could contain sensitive data.

Build & test

Built and tested in the cabal opam switch (cabal, eio, cmdliner, alcotest, yojson):

eval $(opam env --switch=/path/to/cabal --set-switch)
dune build
dune test

Private provider observation sidecar

run optionally persists host-owned call metadata separately from its replay ledger. Supply both flags; omission preserves existing behavior:

cabal-workflow-runner run workflow.json --telemetry-file private/calls.jsonl \
  --telemetry-run-id unique-run-id

The existing parent directory must be trusted and contain no symlink ancestors. The regular sink is owner-only, exclusively locked, appended rather than truncated, and fsynced before dispatch (call.started) and before returning (call.finished). Reusing the same run ID/path resumes occurrence numbers. Interrupted starts remain open; no usage is invented. A sink error refuses success, including errors caught by parallel execution. Replay emits no calls.

Records contain bounded identifiers, selected backend, requested model, status, exit code, session, nullable input/output/cache tokens and Cabal elapsed time. Failed calls additionally carry only a closed failure classification and exact byte-count/SHA-256 pairs for captured stdout and stderr. No prompt, output, error prose, environment or transcript is serialized. Observed zero remains zero; absent counts remain null. Failure usage is partial. Backend-reported USD costs are retained with basis estimated, never billed. Explicit zero remains zero; missing, negative or non-finite estimates remain null with basis unknown. These observations do not guarantee a hard billing cap. Codex token usage is retained only after Cabal reduces the provider stream to one complete, non-negative terminal observation; CWR neither parses nor infers provider events itself. Codex monetary cost remains unknown. A nonempty sink missing its final newline is refused before dispatch, without modifying its retained bytes. For Pi calls, call.finished.provider_lifecycle holds Cabal's cabal.pi-lifecycle@1 reduction of Pi's compaction and retry events, re-validated by Provider_lifecycle.sanitize (other backends: null):

Field

Meaning

counts.compaction_started / compaction_completed / compaction_failed / compaction_aborted

compaction outcomes

counts.auto_retry_started / auto_retry_succeeded / auto_retry_exhausted

assistant-turn retries (e.g. after a 429)

counts.summarization_retry_scheduled

compaction or branch-summary retries

final_stop_reason

stop, length, toolUse, error, aborted or other

truncated_output

the final answer stopped at the output token limit

events[]

at most 64, oldest dropped first (events_dropped)

events[].seq, kind, anchor_timestamp_ms

line in Pi's stdout, Pi event type, timestamp of the last message before it

events[].reason, source

closed vocabularies (manual/threshold/overflow/other; compaction/branchSummary/other)

events[].attempt, max_attempts, delay_ms, success, aborted, will_retry

retry and compaction metadata

events[].tokens_before, estimated_tokens_after

successful compaction

events[].error_class, error_bytes, error_sha256

closed class (context-overflow, provider-rate-limited, provider-quota, provider-authentication, provider-overloaded, provider-timeout, provider-error), length and digest of Pi's error string

events[].error_excerpt

always null in the sidecar

error_sha256 digests Pi's unredacted error string so that calls can be correlated; a short, guessable error string can be confirmed by hashing a guess, so treat it as metadata, not as a secret.

A Pi answer cut at the output token limit is classified provider-truncated-output in failure_diagnostic.

Provider identity, observed model, monetary cost and input-category semantics remain unknown; this is not an invoice or a sub-agent/request accounting ledger. Elapsed time is Cabal's measured wall-clock duration, not a monotonic claim. Consumers own campaign correlation, ingestion deduplication and pricing.

Requires Cabal's additive Claude cost/session parser API; the core library still has no Cabal dependency. See Observation's public interface and the deterministic provider/sink tests for the v1 sidecar contract.

Bounded Claude read-only host policy

Trusted launchers can narrow agent capabilities independently of workflow prompts. All three opt-in flags are required together:

cabal-workflow-runner run workflow.json --read-only-tools Read,Glob,Grep \
  --agent-max-budget-usd 1 --agent-max-turns 8

Tools must be a nonempty unique subset of Read,Glob,Grep; budget must be finite and positive and turns positive. The policy refuses mutable agents and any backend other than the handwritten Claude Code adapter, without fallback. Legacy behavior is unchanged when all flags are absent. Limits apply to each provider invocation, not the entire workflow or campaign; native spend is a CLI ceiling, not proof of billing or a refund guarantee.

The command uses Claude's native exact --tools set, --safe-mode, --restricted, --permission-mode dontAsk, --strict-mcp-config with an empty MCP configuration, --max-budget-usd and --max-turns. It removes legacy permission bypass and allow/deny flags. Thus Read/Glob/Grep are available but Bash, writes, network-fetch/search and sub-agent tools are not selected. Native safe mode disables user customizations/hooks while preserving OAuth auth; admin-managed policy still applies. --bare is not used because it disables OAuth discovery. Unsupported native options fail the invocation; there is no permissive retry. Installed Claude 2.1.291 help was inspected for these native safety controls. Older CLI versions need compatible options or will fail closed.

This policy controls agent tool dispatch, not engine Run authority or OS isolation. Do not enable --allow-run in a read-only audit; use a read-only OS sandbox and sanitized environment for filesystem/configuration defense in depth. It is not a claim that the provider transport itself is offline.

Read-only monitor

The optional TypeScript monitor exposes only GET routes. It reads CWR ledgers from CWR_LEDGER_ROOT (default ./ledgers) and Pi v3 JSONL sessions from PI_SESSION_ROOT (default ./pi-sessions):

npm run build
PI_SESSION_ROOT=/path/to/pi/sessions PORT=8787 npm start

GET /v1/pi-sessions lists bounded, normalized session summaries and GET /v1/pi-sessions/{id} returns a chronological, server-redacted transcript. Source filenames must be path-safe and files cannot escape the configured root. Reads are capped by PI_SESSION_MAX_BYTES (8 MiB), PI_SESSION_MAX_LINES (10,000), and PI_SESSION_MAX_FILES (500). The API reports truncation rather than silently presenting a partial transcript as complete. A Pi↔CWR relationship is displayed only when a ledger contains an explicit session_id equal to the Pi session id.

Secure immutable artifact transaction

secure-publish is a generic stdin/stdout protocol for callers that must publish a related set of private artifacts without owning filesystem lock authority themselves. The helper pins the root directory, retains a private exclusive lock for the complete request, rejects path aliases, and publishes the ordered artifacts immutably. Put the transaction manifest last: its presence is then the commit marker after a crash.

printf '%s' '{
  "version": 1,
  "root": "/private/campaign",
  "lock_path": ".publish.lock",
  "artifacts": [
    {"path":"evidence/report.md","content_base64":"IyBSZXBvcnQK","expected_existing_base64":null},
    {"path":"manifest.json","content_base64":"e30=","expected_existing_base64":null}
  ]
}' | cabal-workflow-runner secure-publish

The request is closed and bounded: unknown fields, invalid UTF-8, duplicate or unsafe paths, more than 256 artifacts, and more than 64 MiB of decoded bytes are rejected before publication. expected_existing_base64 is an optional compare-and-set guard. Existing byte-identical mode-0600 files make replay idempotent; different bytes are a conflict. Stable response statuses are published, idempotent, busy, conflict, invalid_request, publication_uncertain, and io_error. The response never contains artifact bytes.

CLI

# Lint a workflow (parse-tolerant: malformed JSON / bad shape become diagnostics).
# Human table by default; --json prints {"diagnostics":[..]}. Exits non-zero ONLY
# on an error-severity diagnostic (warnings alone exit 0).
cabal-workflow-runner lint examples/bounty.workflow.json \
  --floor g-validated --floor g-observed --floor g-independent
cabal-workflow-runner lint examples/smoke.workflow.json --floor g-observed --json

# Fail-closed validation against an embedder-supplied safety floor:
cabal-workflow-runner validate examples/bounty.workflow.json \
  --floor g-validated --floor g-observed --floor g-independent

# Run it. --approve is the runtime human-approval token required by any Commit
# (hashed for the trace, never stored raw). Omit it and a Commit is Blocked.
cabal-workflow-runner run examples/bounty.workflow.json \
  --floor g-validated --floor g-observed --floor g-independent \
  --approve "$APPROVAL_TOKEN"

# A `run` step executes a shell command, but ONLY if its binary is in the
# operator-supplied, RUNTIME-only allowlist (--allow-run, repeatable; '*' = all).
# With no --allow-run flag the allowlist is empty and NO run step ever executes
# (fail-closed). A workflow file can NEVER grant itself the allowlist.
cabal-workflow-runner run examples/run-demo.workflow.json --allow-run mkdir

# Persist a run's trace as an on-disk ledger (NDJSON), then replay it
# byte-identically in a LATER process. `replay` re-feeds the recorded results —
# it never dispatches an agent or executes a command — and exits non-zero on a
# corrupt ledger, a validation error, or a Replay_mismatch (incl. a
# workflow/ledger mismatch).
cabal-workflow-runner run examples/run-demo.workflow.json \
  --allow-run mkdir --ledger run.ndjson
cabal-workflow-runner replay examples/run-demo.workflow.json \
  --floor g-ran-ok --ledger run.ndjson

Authenticated engine-output export

attest is an engine-native step that selects prior context values and atomically writes a canonical Ed25519-signed JSON envelope. It binds the canonical workflow digest and identity, step ID, selection paths and values, workflow replay domain, and an operator-supplied run/session nonce.

{ "kind": "attest", "id": "export-proof",
  "select": ["outputs.prove", "campaign"],
  "replay_domain": "bounty-triage/v1",
  "output": "artifacts/proof.attestation.json" }

Private key material is accepted only through an inherited descriptor: CWR reads exactly 32 bytes and closes it before constructing or dispatching any backend.

cabal-workflow-runner attestation-public-key --attestation-key-fd 3 > signer.public.json
# Loaded from protected deployment/campaign configuration over an independent
# provisioning channel. Never derive this pin from the mutable workflow at run time.
WORKFLOW_DIGEST=$(protected-config read cwr.workflow_digest)
cabal-workflow-runner run workflow.json --attestation-key-fd 3 \
  --attestation-root "$PWD/trusted-artifacts" \
  --attestation-session "$UNIQUE_RUN_NONCE" --ledger run.ndjson \
  --require-attestation export-proof \
  --expected-workflow-digest "$WORKFLOW_DIGEST"
cabal-workflow-runner replay workflow.json --ledger run.ndjson \
  --attestation-public-key signer.public.json \
  --attestation-session "$UNIQUE_RUN_NONCE" \
  --require-attestation export-proof \
  --expected-workflow-digest "$WORKFLOW_DIGEST"

# Verify the durable artifact directly, without a backend or ledger.
cabal-workflow-runner verify-attestation workflow.json \
  --attestation trusted-artifacts/artifacts/proof.attestation.json \
  --step export-proof --attestation-public-key signer.public.json \
  --attestation-session "$UNIQUE_RUN_NONCE" --ctx-file expected-context.json \
  --expected-workflow-digest "$WORKFLOW_DIGEST"

workflow-digest is a provisioning-time tool: an authorized release process may use it before pinning the result in protected configuration. Runtime run/replay/verification must compare against that independently stored value; computing it from the same mutable workflow immediately before verification provides no substitution protection.

Do not pass a private key or key pathname as a command-line argument. Output paths must be normalized and relative; traversal, ambiguous components, and symlinks fail closed. Descriptor-relative openat/renameat2 traversal prevents symlink and same-user directory/target swap attacks. Replay never signs or writes: it recomputes every binding and verifies against the pinned key and expected nonce. This authenticates the attestation entry, not the rest of the ledger. Run scripts/attestation-selftest.sh for an end-to-end check.

Signed values use a restricted canonical JSON profile: valid UTF-8, recursively sorted object keys, no duplicate keys, and only null/boolean/string/native integer/array/object values (no floats or oversized Intlit). Legacy non-attestation workflows retain their existing numeric behavior. Each repeated Loop/Foreach occurrence is signed with a zero-based occurrence index. Distinct attest steps must have globally unique IDs and output paths; Attest is forbidden beneath Parallel. CWR→JS compilation refuses any workflow containing Attest rather than silently dropping signing authority.

An Attest selection of outputs.<agent-id> is valid only when every Agent producer with that ID is declared read_only. Lint and validation enforce this statically. Runtime read-only dispatch does not trust registry capability metadata or YAML adapters: only cabal's available handwritten claude-code and codex implementations are eligible. Claude receives --disallowedTools Bash,Edit,Write,NotebookEdit; Codex receives -s read-only. Unsafe or unknown explicit agent_type values fail closed without fallback or dispatch. scripts/read-only-selftest.sh exercises exact argv, YAML-ID spoof resistance, and zero target mutation with fake CLIs.

An Agent step may declare "skills": ["relative/path/SKILL.md", ...]. Entries must be unique, normalized, non-empty paths relative to the workflow execution root (no absolute paths, ./.. components, empty components, or backslashes). The native engine forwards the ordered list to Cabal; Pi keeps ambient discovery disabled and loads only those explicit skills. The legacy Claude Workflow JS compiler rejects non-empty skills fail-closed because that target cannot represent this authority boundary.

A read-only Agent may declare input as a non-empty, unique list of dotted paths produced earlier on every path. CWR sends the restricted-canonical projection in a prompt envelope and records engine-owned request/result receipts under receipts.<agent-id>. The request binds the session dispatch ID, backend capability, role, read_only=true, declared selectors, exact selected input and its digest. The result binds the request digest, success/outcome, exact output and output digest. Attest.select may sign either receipt. Structured Agents are rejected beneath Parallel, and replay reconstructs the receipts rather than trusting ledger fields.

# Print the canonical JSON Schema (draft 2020-12) of the workflow format. Point a
# workflow generator at this so it emits conformant workflows by construction.
cabal-workflow-runner schema > workflow.schema.json

validate rejects (exit 1) any workflow with an ungoverned loop (empty governors, or a Max_iters/Fixpoint with an out-of-range bound) or a commit that is not guaranteed-gated by the floor gates on every path. run dispatches agent steps to the first available cabal backend (forcing structured output, failing closed if none or if the agent returns no parseable JSON) and prints the outcome plus the recorded trace. schema is a thin wrapper printing Workflow_schema.to_string () (the committed copy lives at schema/workflow.schema.json).

Live run against a backend

A run dispatches each agent step through cabal. Two environment variables target a specific (typically small/cheap/fast) model:

  • CWR_BACKEND — the cabal backend id to use (e.g. claude-code). Unset ⇒ the first available backend in the registry.
  • CWR_MODEL — the model to pin (e.g. haiku). Unset ⇒ the backend's default.
  • CWR_BUDGET — a genuine consumable total-run budget for the Budget governor (default 1,000,000). Each Budget-governor check consumes one unit; with CWR_BUDGET=N the run performs at most N budget-governed loop iterations total (shared across all loops in the run) before the governor stops the loop. (It is the engine ceiling, not the budget, that is the unconditional termination guarantee.)
CWR_BACKEND=claude-code CWR_MODEL=haiku \
  cabal-workflow-runner run examples/smoke.workflow.json \
    --floor g-observed --approve "$APPROVAL_TOKEN"

examples/smoke.workflow.json is a dumb end-to-end workflow (structured output + schema, a gate, a governed loop, a branch, a token-gated commit) whose agents just echo fixed JSON so it runs cheaply; it was verified live all the way to Committed.

The run step (observable shell command)

A run step executes an observable shell command and binds its result into the run context:

{ "kind": "run", "id": "mk", "cmd": ["mkdir", "-p", "out"],
  "working_dir": "scratch", "timeout_ms": 30000, "observe": ["out"],
  "input": ["outputs.plan.commands"],
  "stdout_schema": { "ok": "bool", "summary": "string" },
  "executable_digest": "sha256:<64 lowercase hex characters>" }
  • cmd — a non-empty argv array, executed without a shell (no implicit sh -c; a workflow wanting a shell must spell ["sh","-c","…"]).
  • working_dir — required, relative, rejected at parse if absolute or containing ... It is the command's cwd, the effect scope, and the snapshot root.
  • timeout_ms — optional bounded wall-clock cap.
  • observe — optional relative paths to snapshot; default = the whole working_dir. Set it explicitly to [] to skip the before/after filesystem walk. The command, stdout/stderr capture, exit status and run receipt are still retained; only the files observation is empty.
  • input — optional non-empty, duplicate-free dotted context paths. CWR resolves them exactly and writes a restricted-canonical JSON object, keyed by the original paths, to the child process's stdin.
  • stdout_schema — optional required-field schema using the same vocabulary as agent output_schema. When present, stdout must be a restricted-canonical JSON object satisfying the schema or the run aborts fail-closed. A truncated=true result is always rejected before parsing, even when its captured prefix is valid JSON.
  • executable_digest — optional SHA-256 identity pin for the command head. CWR resolves the bare name through the runtime PATH, securely reads a single-link non-symlink executable, checks its exact bytes before dispatch, and executes a private snapshot of those bytes. A missing executable or pin mismatch blocks the step before the command runs. Omitting this field retains the legacy Run behavior. For scripts, the pin authenticates the script bytes; it does not implicitly authenticate the shebang interpreter or files loaded by the script.

The result is bound under outputs.<id> as { "exit", "stdout", "stderr", "truncated", "files":[{ "path","change","size","digest" }] }, so the DSL can read outputs.mk.exit, exists(outputs.mk.files), etc. stdout/stderr are size-capped (64 KiB) with a truncated flag. digest is an MD5 content digest (Digest) for change-detection / observability — NOT a cryptographic integrity guarantee.

When structured I/O is requested, that object additionally contains input_digest (sha256:<hex>) and/or parsed (the validated stdout object). When executable_digest is present, it also contains executable={"path":<resolved absolute path>,"digest":<sha256 pin>}. Both are recorded in Run_executed; replay recomputes the selected-input digest, revalidates the parsed stdout and executable-identity bindings, and never starts the child process. Structured Runs are rejected anywhere beneath Parallel; embedded branch traces do not yet support these bindings. Plain unstructured Runs remain valid in Parallel.

Approval-time Commit preflight

A Commit may include a preflight object with required cmd, input, and stdout_schema, plus optional working_dir (default .) and timeout_ms. The preflight is not a separately schedulable workflow step: after all gates pass, CWR first requires the runtime approval token, then executes the allowlisted bare command immediately before Commit with the canonical selected input on stdin. Nonzero exit, truncated output, invalid JSON/schema, missing input, unsafe command path, or missing allowlist authority blocks the Commit. The trusted executable owns domain rules such as ready=true by returning nonzero when they are not met.

On success CWR records an adjacent engine receipt containing step_id, input_digest, process_exit, output_digest, and the canonical parsed output. The Commit trace entry binds that exact receipt and its digest. Replay recomputes the input/output/receipt bindings and never starts the executable. A legacy Commit without preflight behaves and serializes exactly as before.

For state shared with concurrent writers, preflight.lock_file names the normalized lock path relative to working_dir (for campaign state, the canonical value is .campaign-state/.manifest-write.lock). CWR securely opens/creates a single-link regular non-symlink file, takes an exclusive BSD flock without waiting, and holds the verified FD from before input selection through validated receipt construction and adjacent Committed_step emission. A busy or unsafe lock blocks without dispatch. The path is re-opened and its device/inode rechecked before Commit, so removal or replacement cannot silently move the lock to another inode.

The parent-held lock is represented in preflight stdin by the reserved flat key cwr.commit_lock with {path,held:true,device,inode}; device and inode are digit strings. It is included in the input digest and receipt, and lets a cooperating preflight validator verify the exact live inode and avoid deadlocking by reacquiring the same lock. Workflow selectors may not use that reserved path. The validated terminal receipt is the Commit linearization point: its target_digest/evidence digests identify the immutable committed subject. Mutation after lock release may change live files but cannot change what the receipt and Commit authorized.

The allowlist is the trust control — it is operator-supplied at RUNTIME and never read from the workflow file. cmd[0] must be a bare command name resolved via PATH: a cmd[0] containing a / (an absolute or relative path) is Blocked before the allowlist is checked (closing the bypass where a path-bearing cmd[0] passes the basename match yet runs an attacker-chosen binary). Otherwise a run step executes only if Filename.basename of its command head is in Engine.run's ?run_allowlist (CLI --allow-run BIN, repeatable), or the allowlist contains "*" (allow all). Otherwise the step is Blocked (fail-closed); with the default empty allowlist, no run step ever executes. A workflow file cannot grant itself the allowlist.

The run effect never crashes the engine: a spawn failure (exit 127), an output-buffer overflow (exit 125, truncated=true), or a timeout (exit 124) is turned into a recorded run_result, so the run is always recorded and replayable.

working_dir bounds the cwd and the snapshot scope but does NOT sandbox the command from touching absolute paths in its args; full isolation (container/chroot) is out of scope — the allowlist is the trust boundary. The command runs exactly once, on the live run: its full result is recorded in the trace (Run_executed), and replay re-feeds the recorded result and NEVER re-executes (so rm runs once and replay is byte-identical + side-effect-free). Lint emits an informational run-step-executes-commands warning for every run step (and a louder run-step-destructive-command for known-destructive binaries like rm/dd); both are warnings, best-effort, not a security control. See examples/run-demo.workflow.json.

Embedding the library

Supply a backend and the floor gates; everything else is enforced for you:

open Cabal_workflow_runner

let backend : Backend.t =
  { run_agent = (fun ~id:_ ~prompt:_ ~read_only:_ ~agent_type:_ ~model:_
      ~skills:_ ~output_schema:_ ->
      (true, `Assoc [ ("severity", `String "high") ]));
    budget = (fun () -> 1_000_000);
    (* the run-step effect; in bin/ this snapshots the dir + spawns a process. *)
    run_command = (fun ~id:_ ~argv:_ ~working_dir:_ ~timeout_ms:_ ~observe:_ ~stdin_content:_ ->
      { Types.exit = 0; stdout = ""; stderr = ""; truncated = false; files = [] }) }

let () =
  match Workflow_json.of_file "wf.json" with
  | Error e -> prerr_endline e
  | Ok wf ->
    match Validate.workflow ~floor_gates:["g-observed"; "g-independent"] wf with
    | Error reason -> Printf.eprintf "rejected: %s\n" reason
    | Ok validated ->
      let outcome, trace = Engine.run ~backend ~token:(Some "approve") validated in
      assert (Engine.replay ~trace validated = outcome);  (* in-process replay *)
      (* Persist the trace on disk and replay it byte-identically in a LATER
         process (no backend consulted): *)
      let path = "run.ndjson" in
      Out_channel.with_open_bin path (fun oc ->
        Out_channel.output_string oc (Ledger.to_ndjson trace));
      (* ... later, possibly another process ... *)
      (match Ledger.of_ndjson (In_channel.with_open_bin path In_channel.input_all) with
       | Error e -> Printf.eprintf "corrupt ledger: %s\n" e
       | Ok trace' -> assert (Engine.replay ~trace:trace' validated = outcome))

On the CLI, run … --ledger run.ndjson writes the ledger and replay wf.json --ledger run.ndjson --floor g-observed re-runs it in a separate process, exiting non-zero on a corrupt ledger or a Replay_mismatch. Tooling such as tools/bounty-pipeline thus gains persisted replay: a run's trace survives the process and can be audited / re-verified later.

When --approve is supplied, the CLI initializes the ledger before workflow execution with an approval_supplied header immediately after ctx_snapshot. It contains only the domain-separated SHA-256 token digest plus the actual validated workflow digest, optional attestation session, and a SHA-256 digest of their canonical run-context binding. The raw token is never written. This prefix is retained even when a gate blocks before Commit; a run without --approve cannot claim it. Replay validates header position, workflow/session/context binding, and equality with any committed_step.token_digest. This is consistency validation, not reauthentication of the unavailable raw token.

The requested ledger path is opened once without following symlinks, locked before truncation, required to name a single-link regular file, forced to mode 0600, and retained as the same descriptor for both phases. CWR flushes the prefix before executing the workflow. If initialization fails, the workflow is not run; if the terminal write, flush, pathname-identity check, or close fails after execution, CWR refuses success and warns that effects may have occurred.

Meta-agent: building workflows dynamically

Three layers guard a generated workflow, each tighter than the last:

  1. Schema (shape at generation). Workflow_schema (lib/workflow_schema.ml(i), pure, yojson-only) publishes the canonical JSON Schema (draft 2020-12) of the workflow format — derived from Workflow_json (the actual parser), so it describes exactly what the parser accepts. Governing principle: Workflow_json.of_string accepts a workflow iff that workflow is structurally valid per the schema; every structural constraint is enforced by both, and a behavioral parity test drives the parser over a battery of inputs to prove it. Workflow / step / governor objects are closed with a _-metadata escape hatch (unknown keys rejected by both, but _doc / _note accepted by both). Expr operator objects are strictly closed — a single operator key, no _ metadata — so {"lit":true,"_x":1} is rejected by both. The bounded integers max_iters.n / fixpoint.window are 1 ≤ v ≤ max_int (so 1073741824 is valid; a literal beyond max_int is rejected by both); a loop's governors array must be non-empty. output_schema is the one intentionally-open field→type map. Prompt your generator with cabal-workflow-runner schema (or the committed schema/workflow.schema.json, or Workflow_schema.to_string ()) so it emits conformant workflows by construction — the right kinds, the expr/governor encodings, required fields.
  2. Lint (semantics + safety, pre-run). Lint.check_json then catches what shape alone cannot: ungoverned loops, commits missing a floor gate, dangling output refs.
  3. Validate (the run gate). Validate.workflow is the fail-closed gate the engine requires before any execution.

The Lint library (lib/lint.ml(i), pure, offline, yojson-only) is the feedback channel for a meta-agent that generates its own workflows. With no agent, backend or I/O it is linear for realistic workflows (worst-case superlinear only on pathologically deep branch nesting, since the analyses re-walk both arms of every Branch), so it is cheap to call in a tight generate → lint → fix loop:

open Cabal_workflow_runner

let rec gen ~prompt attempts =
  let raw = run_generator_agent prompt in              (* LLM emits a workflow JSON string *)
  match Lint.check_json ~floor_gates raw with          (* parse-tolerant; never raises *)
  | [] ->                                               (* lint-clean ⇒ guaranteed to validate *)
      Result.bind (Workflow_json.of_string raw) (Validate.workflow ~floor_gates)
  | ds when Lint.has_errors ds && attempts > 0 ->
      let feedback = Yojson.Safe.to_string (Lint.to_json ds) in   (* machine-readable *)
      gen ~prompt:(prompt ^ "\nFix:\n" ^ feedback) (attempts - 1) (* feed back into next prompt *)
  | ds -> (* warnings only / out of attempts: accept *) accept raw ds

Two properties make this work:

  • check_json is parse-tolerant and never raises — malformed JSON → one invalid-json error, a bad shape → invalid-shape. You lint the generator's raw output with no exception handling.
  • lint-clean ⇒ validate. Validate.workflow is defined in terms of Lint.check, so a workflow with no error-severity diagnostics is guaranteed to validate — the gate and the linter share one source of truth and cannot drift.

Diagnostics carry a stable machine code (e.g. ungoverned-loop, commit-missing-floor-gate, dangling-output-ref), an agent/human message, and a JSON-path loc (e.g. steps[3].body[0]). Errors are exactly the floor + parse/shape failures; warnings (dangling-output-ref, missing-output-schema, no-commit, unreachable-after-commit) are legal-but-likely-mistaken shapes that never fail the floor. See SPEC.md §4a for the full code table and the contract.

Contributing

See CONTRIBUTING.md for how to build, test, run the schema↔parser parity check, and the invariants a change must preserve.

This project was built and audited with AI assistance; the per-commit Co-Authored-By trailers disclose where.

License

MIT. Copyright (c) 2026 Epure Team.

Dependencies (11)

  1. mirage-crypto-rng
  2. mirage-crypto-ec >= "2.4.1"
  3. digestif
  4. base64
  5. cmdliner >= "1.3.0"
  6. eio_main >= "1.0"
  7. eio >= "1.0"
  8. yojson
  9. cabal >= "0.3.3" & < "0.4.0"
  10. dune >= "3.13"
  11. ocaml >= "5.3.0"

Dev Dependencies (3)

  1. odoc with-doc
  2. quint-connect with-test & = "0.2.0"
  3. alcotest with-test

Optional Dependencies

None

Used by

None

Conflicts

None

Build status

Results of building cabal_workflow_runner with each compiler on check.ci.ocaml.org, run of against opam-repository 8d8d144. All results for this package.

Each result links to its build log. To keep crawlers from overloading the site, build logs require a GitHub sign-in (see ocurrent/opam-health-check). On your first log, GitHub asks you to “Authorize opam-health-check”, the OCurrent app that runs these checks; it sees only your public profile, not your repositories. The sign-in lasts 30 days.

Version OCaml 4.11 OCaml 4.14 OCaml 5.2 OCaml 5.4 OCaml 5.5
0.23.5 (this version) n/a n/a n/a good good
  • good Package successfully built
  • partial One of the dependencies failed to build
  • bad Package failed to build
  • n/a Package is not available in this environment
  • internal Internal failure