package cabal_workflow_runner

All checked builds pass
  1. Overview
  2. Docs

doc/CHANGELOG.html

Changelog

Unreleased

v0.23.5

  • Preserve Dune's default C compiler flags when building the secure filesystem stubs, including position-independent code required by shared libraries.
  • Make the write retry loop unambiguous to compilers that warn about misleading indentation.

v0.23.4

Built against Cabal 0.3.3 (the v2 build recipe pins its revision 5f4655ee, tree 7e687e3d); requires Cabal >= 0.3.3. No CWR runtime change; a new observation CLI test ("Pi multi-turn usage is summed") pins the summed usage and cost in call.finished (it fails against Cabal 0.3.2).

  • Pi usage and cost cover the whole run. Cabal 0.3.2 and earlier reported the usage of the last Pi provider response only, so a multi-turn Pi call under-counted its tokens and cost.cost_usd, often by a large factor for agentic runs with many tool turns. Cabal 0.3.3 sums usage over every response of the run (assistant and tool-result message_end, compaction_end, and Pi 1.3.0 cache-warm usage entries). For the Pi backend, the usage counters and cost.cost_usd of call.finished now grow roughly with the number of turns of the call. Hosts that budget or sum spend from these rows will see totals step up on upgrade; caps calibrated on 0.23.3 figures were calibrated on under-counted values.
  • Failed, timed-out and cancelled Pi calls include the cut response. When the Pi stream stops inside a response (timeout, signal, cancellation), the last non-zero in-flight usage of that response is added to the partial usage (usage.usage_basis = "partial") and cost.
  • call.finished usage of Pi rows has always been labelled scope = "invocation"; rows written by 0.23.3 and earlier carried the last response only. From 0.23.4 the label is accurate.
  • Other backends are unchanged.

v0.23.3

Built against Cabal 0.3.2 (the v2 build recipe pins its revision); requires Cabal >= 0.3.2.

  • Usage and cost of failed and timed-out calls are kept. Cabal 0.3.2 parses usage from the stdout a call printed before it exited nonzero, was signalled or timed out. call.finished now carries those counters and cost.cost_usd on failed and timeout outcomes, with usage.usage_basis = "partial" (previously unknown, with null counters). Codex usage stays restricted to Cabal's validated terminal observation. Hosts that sum spend from the sidecar should include these rows.
  • Calls stopped by a deadline keep their evidence. With --deadline or a controlled candidate deadline_at, Cabal's task timeout is set to the time left, and the host guard around the call used to cancel it at that same instant, before Cabal could return. The guard now fires 5 s past the deadline. For the backends that honour Cabal's task timeout (read-only claude-code, codex and pi; mutable codex, opencode and pi), Cabal stops the provider and returns its Timeout result first, so the timeout row of call.finished carries the session id, partial usage, cost, provider_lifecycle and a provider-timeout diagnostic (previously all null, classified host-failure), and the step still ends as candidate deadline expired. Limits:

    • YAML adapters (the built-in mutable claude-code, gemini and copilot, and ~/.cabal/adapters overrides) apply their own timeout_seconds instead of the deadline. For them the guard is still the only stop at the deadline: the call now ends up to 5 s after the deadline and records no evidence.
    • Cabal's timer starts when the provider is spawned. Work before the spawn (backend availability, pi --version) delays it; past 2.5 s of such work the guard fires first.
    • A step may now end up to 5 s after its deadline. A controller that sets a candidate deadline_at should leave at least 5 s before its own control deadline for agent.record.
    • A Cabal Timeout counts as a deadline expiry only when the deadline has passed. An adapter timeout that fires earlier (a YAML timeout_seconds shorter than the time left) is still an ordinary, retryable failure. Cabal 0.3.2 also bounds the stdin prompt by the task timeout.
  • failure_diagnostic.stderr_bytes / stderr_sha256 describe the exact stderr bytes. Cabal 0.3.1 read stderr by lines and appended a newline to the last unterminated line; 0.3.2 captures stderr verbatim, so the count and digest of an unterminated stderr differ by that byte.
  • Channel observation boundary (residual of MR !15). Closes the known limitations listed under v0.23.0:

    • Every channel writer and channel-observe share one 128 MiB ceiling on canonical state bytes. A write whose resulting state exceeds it fails with channel state exceeds canonical byte ceiling before any state is replaced, so a channel can no longer grow past what observation can read. The previous reader limit was 64 MiB. A publish must also leave 8 KiB per unacknowledged message free (one receive and one acknowledge receipt), so consumers can drain a full channel as long as each receipt stays under 4 KiB (operation ids, principal, alias and recipient are not length bounded; much longer ones can still stall an acknowledge until the next publish evicts acknowledged messages); when a new message does not fit, publish evicts acknowledged messages, oldest first, even below max_retained_messages. Renewals are not reserved: a renew refused at the ceiling lets the lease expire, and redelivery archives the superseded receipts. A state already larger than 128 MiB (possible only with a pre-release writer and very large bounds) is now refused by every writer and by channel-observe.
    • Store-open failures are classified in C from errno into invalid authority, busy (only EWOULDBLOCK on the store lock) or I/O, instead of matching localized error text. A failed ownership, mode or link-count check is always invalid authority. Writers wait only on a busy lock; other open failures are reported at once.
    • CWR_OBSERVE_TEST_NOTIFY_FD / CWR_OBSERVE_TEST_WAIT_FD are removed from the CLI. Tests inject the post-snapshot pause through Channel_observation_command.run ~after_snapshot.
    • Archived receipts and archive nodes are prepared and the candidate state is validated (including the byte ceiling) before any archive object is published. The channel-observe output and error codes are unchanged.

v0.23.2

Built against Cabal 0.3.1 (the v2 build recipe pins its revision).

  • Pi lifecycle metadata in the observation sidecar. For Pi calls, call.finished gains provider_lifecycle: Cabal's cabal.pi-lifecycle@1 reduction of Pi's compaction, auto-retry and summarization-retry events (counts, at most 64 events with line number, anchor timestamp, closed reason/source, attempts, delays, token counts before/after compaction, success/aborted/willRetry flags, closed error class, error byte length and SHA-256, final stopReason, truncated_output). Error excerpts are never stored: error_excerpt is always null. Other backends write null. schema_version stays 1 (additive field).
  • Truncated output is its own failure class. A Pi answer cut at the output token limit (final stopReason = "length", or Pi 1.3.0's print-mode truncation exit) fails the step with Pi terminal error: truncated-output and the sidecar classification provider-truncated-output, instead of a success with unparseable JSON or provider-exit/provider-failure.
  • Pi MCP isolation. Read-only and mutable Pi steps probe pi --version and pass --no-mcp to Pi >= 1.0.4 (and when the version is unknown), so an audited repository's MCP configuration cannot add servers or tools. Pi 0.99.0 to 1.0.3 (MCP without --no-mcp) are refused before the task starts. Pi 0.85.1 runs unchanged.
  • Read-only Pi steps now apply Cabal's Pi_cli.normalize_terminal_result, as mutable Pi steps already did: a provider error reported with exit 0 fails with Cabal's redacted category instead of "no parseable structured JSON".

v0.23.1

Supersedes v0.23.0 for package admission. v0.23.0's source and runtime are unchanged here apart from the resume-id check below; no v2 package was ever published for v0.23.0.

  • Reproducible build tool in v2 packages. The private build now runs every recipe step with the workspace bind-mounted at the fixed root /var/tmp/cwr-v2-build, in a private user and mount namespace under the caller's uid (recipe cwr-build-recipe@3, authority recipe label cwr-exact-private-build@3; the authority format stays cwr-build-authority@2). In v0.23.0 the private dune embedded the workspace path, so build.tool_sha256 differed between two honest builds and an independent verifier could not reproduce the build authority. The authority still binds the exact bytes of the dune that ran; that hash is now reproducible. The builder needs unprivileged user namespaces and an empty /var/tmp/cwr-v2-build owned by the builder (created if missing). The private-build recipe, packager and verifier change, so a new verifier identity applies. The verifier now pins the whole recipe, not only its Cabal source. Host-side probes and the final verifier run with a minimal environment, and the mount point is refused if group- or other-writable.
  • Resume ids made only of dots, or starting with -, are rejected. CWR_RESUME_SESSION_ID of ., .., any run of dots, or a value starting with - now fails as an unsafe identifier instead of reaching pi --session; dots inside an id remain valid.

v0.23.0

This release puts the runtime that production ran from the 0.22 line (bb0fe5f, built against Cabal development commit fa527c7b) on a tagged release built against tagged Cabal 0.3.0, and makes Pi session retention work on it. It requires Cabal >= 0.3.0 & < 0.4.0.

  • Pi session retention. CWR_RETAIN_SESSION=1 sets Cabal's retain_session on agent calls. A fresh Pi call then receives neither --no-session nor --session, and Pi persists its session JSONL under its standard session location in the HOME the host provides. Unset, empty or 0 keeps --no-session. A resume (CWR_RESUME_STEP_ID + CWR_RESUME_SESSION_ID) still passes --session <id>. The 0.22 production build passed --no-session on every fresh Pi call, so no transcript was written; tagged v0.22.0 (Cabal 0.2.0) passed no session flag at all. capabilities declares agent_session_retention (version 1, backend pi, binding CWR_RETAIN_SESSION). Retained transcripts contain full prompts and responses, unlike CWR telemetry. Without --no-session, Pi derives its session directory name from the working directory, so very long worktree paths can exceed NAME_MAX; hosts that retain sessions should use short working-directory paths.
  • Session environment is checked before the run. An invalid CWR_RETAIN_SESSION, a partial CWR_RESUME_* pair or an unsafe resume id makes run exit 1 with a session: message before any step executes.
  • Authenticated channel observation. channel-observe reports aggregate counts and backpressure age for one operator-bound channel root without running the workflow or writing channel state, ledgers or receipts.
  • File-backed run context. run --ctx-file PATH reads the run context from a regular file; it is mutually exclusive with --ctx.
  • Workflow deadline on agent calls. run --deadline EPOCH_SECONDS bounds every agent call, not only governed loops. Timeouts derive from Unix epoch deadlines; the previous subtraction from Eio's monotonic clock could turn a bounded call into an effectively unbounded one.
  • Host-controlled session resume. CWR_RESUME_STEP_ID and CWR_RESUME_SESSION_ID (both required, bounded identifier) resume a retained backend session for one step.
  • Capability declaration. capabilities prints the closed cwr-capabilities@1 set: agent_session_resume, context_file (run --ctx-file, exclusive with --ctx), channel_observation (channel-observe with required --channel, --channel-root, --now) and agent_session_retention.
  • Provider failures are preserved. A failed agent call's structured error now carries Cabal's failure reason (including Pi's redacted provider category), timeout or cancellation instead of a generic message. The success field is unchanged. These reasons now reach traces and ledgers.
  • Concurrent channel writers wait. Every channel store transaction (publish, receive, renew, acknowledge) retries a held store lock for about 10 seconds instead of failing at once. The wait blocks the process, not only the waiting fiber.
  • Verified v2 packages. scripts/package-v2.sh and scripts/verify-package-v2.sh produce and recheck a deterministic package with cwr-build-receipt@2 and cwr-package-verification@1. Directory inventories use a fresh descriptor each time, so a receipt created between two inventories is no longer missed on btrfs (package file set changed).

Known limitations of the channel observation code, which is the production 0.22 round. A later draft round (MR !15) addresses them but was never reviewed to completion and is not included:

  • Writers have no state-size ceiling while observation reads at most 64 MiB, so a channel within its declared bounds can grow past the point where channel-observe can read it.
  • The CLI honours CWR_OBSERVE_TEST_NOTIFY_FD and CWR_OBSERVE_TEST_WAIT_FD, a test synchronization hook that can delay or prefix observation output. Hosts must not set them.
  • Store-open failures are classified from error text, and every lock failure counts as busy, which also drives the writer wait above.

v0.22.0

  • Added exclusive fifo, mailbox, and priority delivery modes to durable channels. Omitting mode preserves the v0.21.0 FIFO format, message identities, and authenticated state. A stored channel rejects reopening under another mode.
  • Mailbox sends require a nonempty recipient; receives select messages addressed to the operator-bound principal. Priority sends require an integer from 0 to 9; receives select the highest eligible priority, then publication order. Active leases are never preempted, and expired messages become eligible again.
  • Mode and send metadata are bound to message identities, request digests, receipts, and durable state. Invalid combinations fail closed. Bounded Quint checks and executable OCaml trace conformance cover routing, ordering, lease expiry, and fencing. The mailbox principal remains an operator-supplied routing value, not a new credential; strict priority can starve low-priority messages.

v0.21.0

  • Added durable typed channels with generation-fenced publish, receive, renew, and acknowledge operations, replay and Repair & Continue integration, bounded authenticated receipt history, a multiprocess proof, and Quint safety plus OCaml conformance checks.

v0.20.0

  • Added an owner-private, exact-byte workflow registry (registry-add, registry-inspect) and digest-pinned recursive workflow composition. The new Workflow_source/Workflow_resolver APIs preserve the existing closed Types.workflow and Workflow_json interfaces. All workflow-input commands now use one resolver-aware loader; resolution is offline, bounded, namespace-safe, and emits deterministic redacted cwr-resolution-receipt@1 evidence. A disposable verified raw-object cache never replaces registry authority. The unresolved schema is available through source-schema and schema/workflow-source.schema.json. Nondefault workflow/registry inputs use inherited descriptors, registry inspection reads a separate bounded metadata object only, registry publication accepts workflow bytes only from stdin or an inherited FD, and CLI resolution receipts can be retained through CWR_RESOLUTION_RECEIPT_FD and fail closed if that configured channel fails.
  • Run steps now accept explicit "observe": [] to execute without a filesystem snapshot. Omitting observe remains backward-compatible and observes the whole working directory. Process results and run receipts remain recorded.

v0.19.3

Deterministic workflow graphs. cabal-workflow-runner graph WORKFLOW.json validates a workflow and renders its planned control flow as standalone SVG, Mermaid, or a versioned cwr-workflow-graph@1 JSON IR. The renderer covers every CWR step kind, performs no execution, and deliberately makes no claim about observed execution or reachability. Its SVG presents decisions, parallel lanes, joins, loop return arcs, gate consequences and bounded tool identities as an automaton-style control-flow diagram.

v0.19.2

Validated Codex usage telemetry. Read-only and mutable Codex calls now retain complete, non-negative terminal input, output, cache-read, and cache-write token counters supplied by Cabal 0.2.x. Ambiguous, duplicated, or malformed terminal usage remains explicitly unknown without discarding an otherwise valid structured agent result. Telemetry records the stable backend identifier rather than a display name.

Partial telemetry remains partial for other providers. Claude, OpenCode, Pi, and future non-Codex backends continue to preserve independently observed token fields when another counter is absent. Missing counters are not rewritten as zero, and prompts or raw provider output are never copied into the observation sidecar.

This release requires cabal >= 0.2.0 & < 0.3.0, whose validated Codex parser and Pi compatibility surface were exercised by the full CWR suite before release.

v0.19.1

Writable Codex dispatch uses the native Cabal adapter. CWR now registers Codex_cli after Cabal's descriptor loader, deliberately replacing the generic YAML fallback. Mutable Codex steps therefore retain their requested model, native closed JSON schema, Cabal timeout, and workspace-write sandbox. The private provider-observation sidecar records failed calls with a closed failure classification plus exit code and exact byte-count/SHA-256 pairs for captured stdout and stderr. It never persists either stream, the prompt, or exception prose.

Deadline governor. {"kind":"deadline"} stops a governed loop once an operator-supplied wall-clock instant has passed. The instant is a runtime value (Engine.run ~deadline, with ~now as an injectable clock seam), never a workflow field — a workflow declaring Deadline under a runtime that supplies none never fires it, the same posture as Budget against a constant budget stub. Each check records a deadline_read bool verdict and replay re-feeds the recorded verdict instead of consulting the clock, so a run recorded after its deadline passed still replays byte-identically (replay deliberately takes no deadline). The JS compiler refuses the governor: a JS target has no engine-recorded clock reading, so any emitted approximation would be a governor that looks present and behaves differently. It does not bound a step's duration — governors are checked between iterations, so one long agent step can overrun the deadline arbitrarily; it bounds how many further iterations start. test/test_cwr.ml covers both polarities (reached / not reached), the no-runtime-deadline case, clock-free replay including a tampered verdict rejected as Replay_mismatch, the compiler refusal, and the JSON round-trip with an instant in the file rejected.

proof-carrying-change example workflow. A first assembly of cwr with arch-index: gates an agent-authored code change on arch-index's change-impact and architecture-fitness-function verdicts (arch-impact/arch-rules --format json) via five floor gates (g-computed/g-sound/g-no-new-findings/g-rules-pass/g-independent), a governed correction loop, and an independent reviewer agent that is additive to the tooled gates, never a substitute for them. See examples/proof-carrying-change.workflow.json and docs/proof-carrying-change.md. test/test_pcc.ml covers the nominal path, a persistent-findings governor stop, arch-impact's sound-refusal path, an un-⊤-marked index, reviewer rejection, a missing approval token, a float rejected on structured Run stdout, and ledger replay of a Blocked outcome.

Round-1 review fix. g-computed originally gated on outputs.impact.parsed.computed, which is true on every path that prints a JSON object — including a --fail-on-new-findings sound refusal, since arch-impact prints its object before running the refusal check. A refused run reached the reviewer/Commit past four "passing" gates, undetected because the test meant to catch it (T3) stubbed a computed:false root that the real tool cannot produce. Fixed: g-computed now reads outputs.impact.parsed.verdict == "pass", which covers "fail" and "refused" alike. T3 rewritten to arch-impact's real refusal shape (confirmed red against the old predicate, green after the fix); T2 updated to the gate it now actually hits; a new T2b exercises g-no-new-findings as the belt-and-braces check it always was meant to be, on a synthetic inconsistent stub the real tool cannot produce; a new structural test mutates the workflow file to remove each of the five floor gates in turn and confirms Validate.workflow fails for every one, naming the gate — replacing an unverified doc claim with an automated check.

Round-2 review fix (BLOCKER + 2 MAJOR + minors). An independent blind-context adversarial review found the floor gates read outputs.impact/outputs.rules — the loop's LAST in-loop iteration, bound BEFORE that same iteration's fixer step made its final edit. The gates certified a tree state one edit older than what actually got committed; neither reviewer (reads only the gates' own trusted dossier) nor pcc-preflight (dune test) closed the gap. Fixed by adding a post-loop re-verification pass — reindex-final/impact-final/ rules-final, run once after the loop exits regardless of which governor stopped it — and pointing every floor gate and reviewer's input at its outputs instead. New regression test T-late-regression (in-loop clean, fixer declares done anyway, post-loop dirty) confirmed red (Committed, the bug) against the pre-fix gate wiring and green (Blocked) after; T-converge-iter-3 covers genuine multi-iteration convergence with per-call-varying stubs.

Same review found author/fixer were prompted to read run-context values (ctx.task, outputs.impact/outputs.rules) they never actually received: cwr's only context channel into a prompt is structured input, which requires read_only:true — a write-access agent can never declare it. Fixed via the engine's other channel: brief, a file path re-read fresh on every Agent invocation. author's brief is .pcc/task.md (operator-supplied, replacing the broken --ctx claim); fixer's is .pcc/dossier.md, written every loop iteration by a new dossier Run step (pcc-dossier, a fourth pcc-* convention binary) from the same arch-impact/arch-rules --format md the JSON steps just ran, against the same tree.

Also: arch-rules invocations now pin --on-unknown fail --on-possible fail --on-vacuous fail --on-not-computed fail explicitly — arch-index's own defaults (--on-unknown warn in particular) are argued for human PRs, not adversarial agent gating, and left unpinned this gate's real strictness lived in another repo's unversioned runtime defaults. Dead pcc-baseline step removed (nothing ever consumed its output — arch-impact's own new_findings was already diff-scoped). docs/proof-carrying-change.md gained a threat-model section for read_only:false agents (mitigable via unused executable_digest, host responsibility, and structural limits, honestly separated) and three new test scenarios (T-rules-fail, T-preflight-fails, plus the two above) exercising floor gates and failure paths the first cut never touched.

v0.19.0

Run-start approval ledger identity. run --ledger now initializes its ledger before execution. When --approve is supplied, a singleton approval_supplied header binds a domain-separated SHA-256 token digest to the actual workflow digest, attestation session, and canonical run-context digest. Early Blocked/Aborted runs retain this evidence; approval-less runs cannot claim it. Replay validates placement and every binding, including equality with any Commit token digest, while remaining compatible with legacy ledgers. The raw approval token is never persisted, and replay explicitly provides consistency validation rather than token reauthentication.

A requested ledger is opened once without following symlinks, locked before truncation, required to be an unaliased regular file, and held at mode 0600 through prefix and terminal writes. The prefix is flushed before execution. Initialization failures prevent effects; terminal persistence or pathname identity failures refuse a successful CLI result and explicitly warn that effects may already have occurred.

New Commit events use sha256("cwr.approval-token/v2\\0" || raw_token) as well. Replay remains compatible with legacy header-free ledgers containing the prior 32-hex Commit digest because no new approval header claims v2 binding there.

Digest-pinned Run executables. A run step may declare executable_digest (sha256:<hex>). CWR resolves the bare command through the operator's PATH, opens it with O_NOFOLLOW, requires a single-link regular executable, hashes the exact descriptor bytes, and fails before dispatch on a pin mismatch. The verified bytes execute from a private read/execute-only snapshot rather than by reopening the mutable origin path.

The resolved absolute path and digest are bound into outputs.<id>.executable, the Run_executed trace/ledger entry, and replay validation. Legacy Runs that omit the field retain their existing backend and serialization behavior. The native-to-JavaScript compiler refuses pinned Runs because that target cannot preserve the verified-execution contract. Parser/schema parity and a CLI self-test cover pin mismatch, origin replacement, identity recording, and snapshot execution.

v0.18.1

Commit preflight linearization lock. An optional preflight.lock_file, relative to the preflight working directory, lets CWR hold the same BSD flock(2) used by campaign writers from before input selection through process execution, receipt validation, and adjacent Committed_step emission. CWR opens/creates the lock by descriptor traversal with O_NOFOLLOW, requires a single-link regular file, fails immediately when busy, and rechecks the live device/inode before Commit.

While holding the lock, CWR injects the reserved canonical input cwr.commit_lock={path,held:true,device,inode} (digit-string identity) and binds it into the input digest, preflight receipt, trace, and replay. User selectors cannot collide with that namespace. Symlink, hardlink, traversal, busy-lock, removal, and inode-replacement cases fail closed without Commit. The successful validated receipt is the Commit linearization point and authorizes its immutable target/evidence digest, not later mutable worktree bytes.

v0.18.0

Engine-owned decision receipts and approval-time preflight. A read-only Agent may now select guaranteed predecessor context with input. CWR sends a restricted-canonical projection in an engine envelope and records request/result receipts under receipts.<id>, binding the session dispatch, concrete backend capability, role, read_only=true, declared selector paths, input/output digests, success, and exact structured output. Attest may select those receipts; lint rejects mutable or parallel structured Agents and unsafe receipt producers. Replay reconstructs every binding and rejects receipt or predecessor tampering.

Commit has an optional structured preflight using the Run command/input/schema vocabulary. It executes only after a runtime approval token, through the runtime allowlist, and immediately before commitment. Nonzero exit, truncation, invalid JSON/schema, unsafe command path, missing input, or absent allowlist authority blocks the Commit. The engine records a canonical preflight receipt and binds it and its digest into the adjacent Commit trace entry; replay validates it without executing. Legacy Agent and Commit workflows retain their prior encoding and behavior.

v0.17.1

v0.17 review closure. Read-only Agent dispatch no longer trusts cabal registry capability metadata or bundled/project/global YAML adapters. It resolves only the available handwritten Claude_code and Codex_cli command builders, whose actual argv blocks Claude Bash/Edit/Write and selects Codex's read-only sandbox. Unknown or unsafe explicit agent_type values fail without fallback or dispatch. The direct audited path also avoids target-directory project-config writes.

Structured Runs now reject truncated stdout before parsing, including replay, and lint/validation reject any Run using input or stdout_schema beneath Parallel. Fake-PATH CLI tests pin exact argv, defeat a project YAML ID spoof, and verify zero target mutation; focused Cabal command-builder suites remain green.

v0.17

Structured Run I/O. run steps may select dotted context paths with input; CWR sends their restricted-canonical JSON projection to the child on stdin and records a SHA-256 input digest. Optional stdout_schema requires stdout to be a restricted-canonical JSON object satisfying the existing schema vocabulary and binds it as outputs.<id>.parsed. The digest and parsed object are ledger-bound and replay-verified without executing the command. Parser, schema, lint, runner/backend, compiler refusal, documentation, and regression tests were updated; Runs omitting both fields retain their prior behavior.

v0.16

Read-only attestation producer enforcement. An attest step may select an outputs.<id> value produced by an Agent only when every Agent producer with that ID is declared read_only. Lint and validation reject drift statically. At runtime, read-only Agent dispatch selects only backends whose cabal Backend_registry descriptor declares read_only_support; an explicitly selected unsafe backend fails before dispatch and the default selector filters to declared read-only backends.

v0.15

Authenticated native output export. Added the attest step and canonical Ed25519 envelopes binding workflow digest/identity, step, selected context values, replay domain, and operator session nonce. Live execution writes atomically under a checked artifact root; missing configuration and unsafe/symlink paths block. Replay is effect-free and requires a pinned public-key identity plus the expected nonce, so tampered ledger entries and cross-session reuse fail authentication.

Private seeds enter the CLI only through --attestation-key-fd: exactly 32 bytes are read and the descriptor is closed before backend construction. Backend.t is unchanged, so Agent, Run, and Shell adapters never receive signer material. Added public-key export, schema/parser/lint/compiler/ledger integration, focused tests, and an end-to-end CLI security selftest; the existing 110 tests remain green.

Adversarial follow-up hardened the boundary with recursive duplicate-key rejection, restricted canonical signed JSON, signed occurrence counters, global ID/output uniqueness, Parallel rejection, compiler refusal, operator-pinned workflow digests and required-attestation paths, secure descriptor-relative reads/writes, concurrent-swap tests, explicit post-rename published-uncertain, and a cross-language Node Ed25519 verifier. The final closure removed replacement entirely, requires immutable {occurrence} paths in repeatable control flow, fixes trusted relative . roots, pins every Node-verifier binding independently, and aligns UTF-8 ordering/JS-safe integer vectors. The focused attestation suite now contains 20 tests (130 total), including controlled engine, replay, CLI, and standalone-verifier rejection of unsafe numeric selections.

v0.14

Faithful CWR→JS compiler. to-claude-workflow now emits runnable Claude Workflow JavaScript instead of stubs: an Expr.t → JS translator so gate/branch emit real conditions, loop-governor → JS termination (counter, budget, fixpoint), the mandatory export const meta = {...} header, agent-option forwarding (output_schema, read_only, on_failure), and compilation of shell/evidence steps plus protocol/brief/ agent_type agent fields. (commit and run keep their documented approximations + notes; direction is CWR→JS only, no reverse parser.)

Compiler safety — "silent-invalid-output" class closed. Every parser-accepted workflow now either compiles to JS that node --check accepts, or fails closed with a clear Compile_error (CLI exits non-zero) — never exit-0 JS that node rejects. Three fixes: js_comment_safe neutralizes all four JS line terminators (LF, CR, U+2028, U+2029), applied centrally in emit_comment so no workflow string (name, version, shell/evidence fields, run/parallel comments) can split a // comment and leak its tail as code; foreach's over ctx key is emitted via js_ident instead of raw into the live pipeline(...) call; and a per-JS-scope variable-binding tracker fails closed when two step ids collide on the same JS variable name in one scope (since js_ident is lossy), including collisions with the implicit export const meta and the item foreach parameter. Sibling scopes may legally reuse a name.

Per-step agent model override. An Agent step gains an optional model field (e.g. "claude-fable-5") that overrides the backend's global CWR_MODEL for that step only; a blank value or an absent field falls back to the backend default. Threaded through the parser/serializer (added to the agent closed known-key set), the JSON schema (schema↔parser parity + no-drift hold), the backend run_agent interface, the cabal backend, the engine (live + replay; model does not enter the trace, so replay stays byte-identical), and the CWR→JS compiler (emitted as a model: "..." agent() option). CLI --version → 0.14.0.

v0.11

Soft-fail agent steps (on_failure). An Agent step gains an optional on_failure field: "abort" (default, unchanged — a success = false run fails closed → Aborted) or "continue" — a soft failure that records the failed Agent_ran, binds its output, and lets the walk continue. This is for continuous loops where one iteration's agent failure must not kill the whole run; the failed agent's output is still bound under outputs.<id>, so any predicate reading it is fail-closed (a missing field is false). replay reproduces a soft-failed step byte-identically (no Blocked_at, no Aborted). CLI --version → 0.11.0.

Safety (enforced, not assumed): the validator rejects on_failure = "continue" in any workflow that contains a Commit (the soft-fail-with-commit error) — soft-fail is permitted only in commit-free workflows. This is required because the commit-floor invariant tracks gate IDs, not whether a gate's predicate consumes the soft-failed agent's output; a trivially-true floor gate could otherwise let a commit fire past a soft-failed agent. With no Commit reachable, "continue" changes only whether a failed agent aborts the walk. Default behaviour is unchanged; a workflow that omits on_failure parses, validates, lints, and serialises exactly as before (the field is emitted only when "continue"). Schema (workflow.schema.json) updated; schema↔parser parity holds; new engine tests cover soft-fail + replay (F3) and the soft-fail-with-commit rejection.

v0.10

An on-disk ledger + replay-from-file: a run's recorded trace can now be persisted to disk and replayed byte-identically in a later process. Replay is no longer in-memory-only. The persistence boundary is a pure, yojson-only module; Engine.replay is unchanged (it already took a trace). CLI --version → 0.10.0.

Integrity caveat (be honest with auditors): replay attests the trace is internally consistent with the workflow and the recorded agent/run outputs — every structural tamper (corrupt/truncated/reordered/trailing line, cross-workflow trace, or a verdict inconsistent with its inputs) fails closed — but it does not authenticate those outputs or the commit token. A ledger is an unauthenticated, attacker-editable file: a forged ledger can replay to Committed. For tamper-evidence, sign/MAC the ledger out of band. (Found by adversarial review; documented rather than over-claimed as "re-auditable".)

Added

  • lib/ledger.ml(i) — pure, yojson-only persistence boundary.

    • to_ndjson : Types.trace -> string serialises a trace to newline-delimited JSON: one tagged ("kind") object per trace_entry, in order, each newline-terminated. Every variant is covered — Agent_ran, Gate_evaluated, Branch_taken, Loop_iter, Budget_read, Fixpoint_progress, Loop_stopped, Run_executed (incl. the FULL run_result: exit/stdout/stderr/truncated and each file's path/change/size/digest), Committed_step, Blocked_at.
    • of_ndjson : string -> (Types.trace, string) result is the fail-closed inverse: any malformed line (bad JSON, unknown/missing kind, missing/ill-typed field) ⇒ Error, never raises; blank lines (a trailing newline) are ignored. Round-trip: of_ndjson (to_ndjson t) = Ok t for every trace.
  • CLI. run gains --ledger <path>: after a successful run the recorded trace is written as NDJSON to <path>. New subcommand replay <workflow.json> --ledger <path> [--floor <g>]…: loads + Validate.workflows the workflow, reads the ledger, Ledger.of_ndjsons it (clear error on corrupt), and Engine.replay ~traces it — printing the replayed outcome and exiting 0 on success, non-zero on a corrupt ledger, a validation error, or a Replay_mismatch (incl. a workflow/ledger mismatch). Replay never dispatches an agent or executes a command (no backend consulted), exactly like the in-memory replay.

Determinism / scope

  • Persisted byte-identical replay. Because the serialisation round-trips ALL trace entries faithfully and Engine.replay re-feeds the recorded results (re-evaluating only the total DSL and asserting each recorded verdict), replay <wf> --ledger <file> reproduces the original outcome in a separate process. A workflow/ledger mismatch, a corrupt line, or a trailing extra entry all fail closed (the existing trailing-entry guard now reached via the file path) rather than silently "succeeding".
  • lib/ stays yojson-only. The ledger is the on-disk encoding, not an effect; reading/writing the file lives in bin/.
  • No schema / parity impact. The ledger is runtime output, not workflow input — the workflow schema is unchanged and scripts/parity_check.py stays at 0 divergences.

Tests

  • Round-trip over a trace exercising every entry variant (incl. a Run_executed with file changes and Loop/Budget/Fixpoint entries): of_ndjson (to_ndjson t) = Ok t.
  • End-to-end persist → replay-from-file: a stub-backend run is written to a temp file, read back via a fresh of_ndjson, and Engine.replayed to the identical outcome — with marker counters proving replay called neither run_agent nor run_command.
  • Corrupt/tampered ledger: a malformed (and an unknown-kind) line ⇒ of_ndjson Error; a ledger with a trailing extra entry decodes but ⇒ Engine.replay Replay_mismatch.

v0.9

A new run step: an orchestrator-executed, observable shell command, designed so a side-effecting step lives in a replayable engine without breaking determinism and without pulling process execution into the yojson-only library. CLI --version → 0.9.0.

Added

  • Run { id; cmd; working_dir; timeout_ms; observe } step. cmd is a non-empty argv executed without a shell (no implicit sh -c). working_dir is required, relative, and rejected at parse if absolute or containing a .. component (the effect scope + snapshot root). timeout_ms is an optional bounded int; observe is an optional list of relative paths to snapshot (default: the whole working_dir).
  • Injected run effect — cabal stays out of lib/. Backend.t gains run_command : id:… -> argv:string list -> working_dir:… -> timeout_ms:int option -> observe:string list option -> run_result, where run_result = { exit; stdout; stderr; truncated; files } and file_change = { path; change : Created|Modified|Deleted; size; digest }. The library defines these types and calls the injected function; bin/runner.ml (wired in bin/backend_cabal.ml) implements it via Cabal.Backend_process.run_process (no shell) plus a before/after directory snapshot (path → digest + size) diffed into a file_change list. digest is an MD5 content digest (Digest) for change-detection / observability — NOT a cryptographic integrity guarantee. stdout/stderr are size-capped at 64 KiB with a truncated flag. The result is bound under outputs.<id> as JSON, so the DSL can read outputs.mk.exit, exists(outputs.mk.files), etc. lib/ still depends on yojson only.
  • Operator allowlist (runtime-only, fail-closed). Engine.run gains ?run_allowlist:string list (default []). A run step executes only if Filename.basename (List.hd cmd) is in the allowlist or the allowlist contains "*"; otherwise the step is Blocked (run command "<bin>" not permitted (allowlist)). With [], no run step ever executes (off/fail-closed); "*" allows all. CLI --allow-run BIN (repeatable) populates it. It is operator-only and runtime-only — a workflow file can never grant itself the allowlist.
  • Determinism / replay. A live run executes the command exactly once, records the full result as a new trace entry Run_executed { id; result }, and binds it. Engine.replay consumes the recorded Run_executed, re-binds it, and NEVER re-executes (no run_command call; the allowlist is not consulted on replay since nothing runs) — so rm runs once and replay is byte-identical + side-effect-free, mirroring the Agent_ran replay arm. The allowlist-Blocked case records/replays as Blocked_at + terminal Blocked, like the gate/commit Fail arms. Trailing-trace-entry rejection still holds for run-bearing traces.
  • Validator / schema / parser. working_dir absolute or .. ⇒ reject; empty cmd ⇒ reject (parser-level). The JSON Schema gains a closed run step variant (cmd an array minItems:1 of strings, working_dir a required string carrying a pattern that rejects absolute / ..-segment paths to keep the schema↔parser iff, timeout_ms a bounded int, observe an array of strings). schema/workflow.schema.json regenerated (no-drift test green); the parser↔schema kinds test now includes run; the behavioral parity test and scripts/parity_check.py gained run cases (parity still 0 divergences).
  • Lint. Every run step emits an informational run-step-executes-commands warning, and a known-destructive binary (rm, rmdir, mv, dd, mkfs, shred, truncate, the :(){ fork-bomb idiom) emits a louder run-step-destructive-command warning. Both are warnings (best-effort, not a security control — the allowlist is the trust boundary), so has_errors stays false.
  • Example. examples/run-demo.workflow.json — a run of mkdir -p (observing the created dir) followed by a gate on eq(outputs.mk.exit, 0), ending Completed_no_commit. Validates and lints clean-of-errors (the run-step-executes-commands warning is expected).

Review fixes (pre-release, adversarial review of the run step)

  • Correct, honestly-labeled digest. Replaced the broken hand-rolled SHA-256 (failed every known-answer vector — an operator-precedence bug) with OCaml stdlib Digest (MD5): Digest.to_hex (Digest.string content). The file_change field is renamed sha256 → digest (runtime output under outputs.<id>.files[].digest; no schema/parity impact). Documented as an MD5 content digest for change-detection / observability — not a cryptographic integrity guarantee. A known-answer test pins MD5("abc") = 900150983cd24fb0d6963f7d28e17f72.
  • Closed the allowlist bypass. cmd[0] must be a bare command name resolved via PATH: any cmd[0] containing a / (absolute/relative path) is Blocked before the allowlist match (engine-level, fail-closed, recorded/replayable), so --allow-run mkdir + ["/attacker/mkdir"] no longer execs the attacker binary.
  • The run effect can never crash the engine. bin/runner.ml wraps the whole effect in try … with: spawn failure ⇒ exit 127, output-buffer overflow ⇒ exit 125 + truncated, timeout ⇒ exit 124 — always a recorded run_result, never an uncaught exception (preserving "exactly one recorded result, replayable").
  • Honest doc warnings. Allowlisting a wrapper (sh/bash/env/xargs/find/ interpreters) effectively allows arbitrary commands — keep the allowlist to leaf tools; and a symlinked working_dir is followed (cwd = resolved target).

Honest scope (not overclaimed)

working_dir bounds the cwd and the snapshot scope but does NOT sandbox the command from touching absolute paths named in its args. The allowlist is the trust control (operator opt-in; [] = off/fail-closed, "*" = all); full isolation (container/chroot) is out of scope for this MVP.

Tests

  • run mkdir-like (stub returns exit 0 + a Created file) ⇒ outputs.mk.exit = 0, files has the created entry, and a following gate eq(outputs.mk.exit, 0) passes.
  • Allowlist enforcement: a non-allowlisted binary ⇒ Blocked with run_command not called; the binary listed (by basename) ⇒ runs; ["*"] ⇒ runs.
  • Replay never re-executes: a stub increments a counter per call; after a live run (counter = 1), Engine.replay reproduces the identical outcome AND the counter does not increment; trailing-entry rejection still holds.
  • File diff: a first run returns Created and a second returns Deleted; both observed in their respective outputs.<id>.files.
  • working_dir with .. / absolute and an empty cmd ⇒ parse Error.
  • The run-demo example validates + lints clean-of-errors; a destructive rm run emits run-step-destructive-command while has_errors stays false.
  • Review-fix tests: MD5 digest known-answer; path-bearing cmd[0] (absolute/relative) ⇒ Blocked with run_command not called while a bare allowlisted name runs; a failed run effect is recorded (engine never crashes).
  • 45 → 55 tests; all prior invariants preserved.

Preserved invariants

  • Loop ceiling (termination guarantee); gate-Fail-blocks; runtime token digest-only; floor reachability; determinism / byte-identical replay; Expr.eval totality; lint-clean ⇒ validate; schema↔parser parity / no-drift (scripts/parity_check.py 0 divergences); lib/ depends on yojson only — process execution lives in bin/.

v0.8.1

Tooling / open-source-readiness changes only — no runtime behaviour change, so the CLI --version stays 0.8.0.

Tooling

  • CI (GitHub Actions). .github/workflows/ci.yml reproduces the documented build on ubuntu-latest: ocaml/setup-ocaml@v3 (OCaml 5.3), pins the public cabal (opam pin add -n cabal …), opam install . --deps-only --with-test, then dune build + dune runtest. A second job runs the schema↔parser parity check (setup-python → pip install jsonschema → dune build → python3 scripts/parity_check.py).
  • Standalone test binary. The four example/schema fixture loads in test/test_cwr.ml previously used cwd-relative ../examples/… / ../schema/… paths that only resolved under the dune test sandbox, so dune exec test/test_cwr.exe from the repo root spuriously failed. A project_path helper now resolves fixtures via DUNE_SOURCEROOT (set by dune for dune exec/dune test), falling back to the legacy ../ form. Both dune test and dune exec test/test_cwr.exe pass (45 tests).
  • CONTRIBUTING.md added: build/test recipe (cabal pin), the parity-check workflow, the lib/-stays-yojson-only rule, the schema↔parser parity contract, and the safety-floor invariants a change must preserve.
  • README.md gained a prominent "Status: early / experimental (v0.x)" note surfacing the MVP boundaries (in-memory replay, JSON-only format, no Spawn, the small-model live-dispatch validation) and a one-line AI-assistance disclosure.
  • Renamed a test fixture token from super-secret-approval to test-approval-token (cosmetic; tests stay green).

v0.8

A corrective release addressing five findings from an external review. Two engine safety fixes (fail-closed on a failed agent; replay rejects trailing trace garbage), two analysis fixes (Exists over a present object; branch-dependent dangling-ref detection), and one CLI honesty fix (a real consumable budget). CLI --version → 0.8.0.

Fixed

  • F1 (High) — a failed agent step now FAILS CLOSED. Previously Engine.run's Agent branch fell through | _ -> st on success = false, binding the backend's {"error":…} output and CONTINUING; a later always-true gate + token could then Commit despite the failure. A success = false agent run now aborts the walk (Aborted, emitting Blocked_at), mirroring the schema-mismatch arm. The symmetric change is made in Engine.replay (it consumes the recorded Blocked_at and reproduces the Aborted), so run and replay agree on the trace shape [Agent_ran{success=false}; Blocked_at; …Aborted].
  • F2 (Medium) — Exists treats a present object/array as present. value_of_json flattens `Assoc _ to Null (fine for comparisons), so {"exists":"outputs.a.obj"} was false even when obj was a present object. Expr now resolves Exists over the RAW JSON (new resolve_raw): a present object/array/scalar ⇒ true; an explicit JSON null or a missing path ⇒ false. Comparison operators keep value-based resolve (semantics unchanged); Expr.eval stays total.
  • F3 (Medium) — lint catches branch-dependent dangling output refs. Lint's Branch case previously UNIONED both arms' produced outputs, so a reference AFTER the branch to an output produced in only ONE arm was not flagged. The guaranteed-available produced set after a Branch is now the INTERSECTION of the two arms' sets (an output is guaranteed only if BOTH arms produce it), mirroring the floor's branch=intersection discipline. Field-level merge: an id survives only if in both arms; its fields are the field-set intersection when both declare a schema, else None. Intra-arm behaviour is unchanged. The examples remain lint-clean (0 diagnostics).
  • F4 (Medium) — replay rejects trailing extra trace entries. Engine.replay consumed from the pending trace but never asserted it was empty when the walk finished, so a trace = valid-prefix ++ garbage replayed "successfully". It now raises Replay_mismatch "trailing trace entries after workflow completed" if any entries remain. (Replay_mismatch is now exposed in engine.mli.)
  • F5 (Low/Med) — CWR_BUDGET is a real consumable cap. bin/backend_cabal.ml's budget () returned the env value on EVERY call, so CWR_BUDGET=10 read 10 forever and the Budget governor never fired. budget is now a per-make (per-run, shared across all loops = a total run budget) mutable counter initialised from CWR_BUDGET (default 1_000_000) that decrements and returns the remaining. Documented off-by-one: with CWR_BUDGET=N the counter starts at N, readings are N−1…0, and the Budget governor stops on the Nth check, so the run performs at most N budget-governed loop iterations total. Determinism is unaffected (every Budget_read is recorded; replay re-feeds recorded values and never calls budget).

Tests

  • F1: a workflow whose first agent stub returns success = false (then an always-true gate + commit + token) ⇒ Engine.run yields Aborted (NOT Committed), no Committed_step in the trace, and Engine.replay ~trace reproduces the same Aborted.
  • F2: Exists ["outputs";"a";"obj"] ⇒ true over a present object, false over an explicit null, false over a missing path, true over a present scalar and a present array.
  • F3: a gate after a branch referencing outputs.x.v with x produced only in the then arm ⇒ dangling-output-ref Warning; a reference to an output produced in BOTH arms ⇒ no warning.
  • F4: a real recorded trace with one extra dummy entry appended ⇒ Replay_mismatch; the unmodified trace still replays fine.
  • F5: the engine-level decrementing-budget test pins the exact iteration count (the CLI constant→decrement change is verified by reading).

Docs

  • SPEC.md / README.md: the Agent step / engine §3 note the fail-closed-on-failed-agent behaviour; the CWR_BUDGET description states the honest consumable-budget semantics and the off-by-one. Lint's branch comment now documents the intersection discipline.

Preserved invariants

  • Loop ceiling (termination guarantee); gate-Fail-blocks; runtime token digest-only; floor reachability; determinism / byte-identical replay; lib/ depends on yojson only; Expr.eval totality; lint-clean ⇒ validate; schema↔parser parity / no-drift (scripts/parity_check.py still 0 divergences).

v0.7.1

Final parity fix from a confirming external audit (94/95 cases agreed; this closes the last one).

  • Integer-valued floats. JSON Schema's "type":"integer" matches any number with zero fractional part, so {"n": 5.0} is schema-valid — but the parser's req_bounded_int accepted only `Int, rejecting `Float. The schema cannot cleanly forbid 5.0, so the parser now accepts an integer-valued float in [1, max_int] (and rejects a fractional one), restoring the "parser accepts iff structurally schema-valid" iff. Safe direction either way (the bug was over-rejection, never under-acceptance).
  • scripts/parity_check.py — a reproducible, real-validator-driven parity check (jsonschema Draft 2020-12 vs the parser over a 30-case battery; exits non-zero on any divergence). Addresses the prior weakness that the in-suite behavioral test's expected verdicts were hand-authored.
  • Added integer-valued-float cases to test_schema_parser_behavioral_parity.

v0.7

A corrective release addressing a third re-audit finding: the published JSON Schema and the parser still disagreed on 7 of 54 enumerated inputs, verified against the Draft 2020-12 validator. The divergences were value-bound mismatches and an expr _-escape mismatch. This release closes them definitively and states the governing principle that makes the agreement testable.

Governing principle (now stated in SPEC and made true): Workflow_json.of_string accepts a workflow iff that workflow is structurally valid per schema/workflow.schema.json. Every structural constraint the schema expresses is enforced by the parser, and vice-versa. Semantic floor checks (gate reachability, ungoverned-loop, etc.) remain Lint/Validate's job and are deliberately not encoded in the schema.

Fixed

  • max_iters.n and fixpoint.window bounds now agree on both sides. The parser enforces 1 ≤ v ≤ max_int at parse (new req_bounded_int): a value < 1 is rejected with a clear message (field "n" must be >= 1 (got 0)); a literal > max_int is yielded by yojson as `Intlit and rejected. Previously the parser accepted n = -5 / n = 0 that the schema rejected. The schema's bounded_int maximum was raised from 1073741823 (2³⁰−1) to 4611686018427387903 (OCaml max_int on 64-bit), so a large-but-valid literal like 1073741824 is now schema-valid AND parser-accepted (previously schema-rejected); a literal beyond max_int remains invalid on both sides.
  • Empty governors is now a parse-level shape error. The schema declares the loop governors array minItems:1; the parser now requires a non-empty list (new req_nonempty_list), so it no longer accepts an empty governors array the schema rejects. (The richer ungoverned-loop semantic diagnostic still lives in Lint/Validate.)
  • Expr operator objects are now strictly closed on the schema side too. Expr objects are single-operator: the parser requires exactly one key and rejects any extra key, including a leading-underscore one ({"lit":true,"_x":1} → rejected). The schema's expr branches previously carried the ^_ patternProperty (inherited from the shared closed-object builder) and therefore accepted {"lit":true,"_x":1}. Expr branches now use a distinct strictly-closed builder (additionalProperties:false, no ^_), so the schema rejects it too. Workflow / step / governor objects keep the ^_ escape hatch (the parser allows _ there).
  • The committed schema/workflow.schema.json is regenerated from the lib value (the no-drift test enforces byte-equality; the schema CLI output byte-equals the file).

Tests

  • New behavioral parity test (test_schema_parser_behavioral_parity) enumerates a battery of candidate workflow JSON strings (mirroring the audit's 54-case methodology) — unknown vs _-prefixed keys per object kind, max_iters.n / fixpoint.window ∈ {−5, 0, 1, 2, 1073741824, >max_int}, empty vs single governors, expr objects with 0/1/2 keys and an _-key, and type confusions — and asserts, per case, that the parser accepts iff the case is structurally schema-valid (the expected verdict is hard-coded to mirror the schema). This drives the parser over the battery, which the prior structural-only parity test never did; it fails on pre-fix code (catching the 7 divergences) and passes after. The structural parity test was adapted: expr branches are now asserted strictly closed (no ^_).

Docs

  • SPEC.md / README.md state the governing principle, correct the over-claim that expr objects took _ metadata, document the max_int bound and the minItems:1 governors rule, and note output_schema is the one intentionally-open map.

v0.6

A corrective release addressing a re-audit finding: the published JSON Schema and the parser disagreed on unknown keys. v0.5 made the schema reject extra keys on step/governor/agent objects (additionalProperties:false), but the parser still silently accepted them — so the schema rejected workflows the runner happily executed, voiding the "schema == what runs" contract.

Fixed

  • The parser now rejects unknown keys (closed objects), with a _-prefixed metadata escape hatch. Workflow_json now rejects, fail-closed, any key that is neither a known key for the object nor prefixed with an underscore _, on the top-level workflow object, each step (agent/gate/branch/ loop/commit), and each governor (max_iters/budget/fixpoint). The error names the key and the object (e.g. unknown key "junk" in agent step). Keys beginning with _ (e.g. _doc, _note) are ignored metadata and allowed — the documented escape hatch the examples use. This mirrors the discipline expr_of_json already enforced ("expression object must have exactly one operator key"). output_schema is unchanged: it is intentionally an open field→type map.
  • The schema regained agreement with the parser. Every closed object (workflow, the 5 steps, the 3 governors, the 13 expr branches) now carries patternProperties: {"^_": {}} alongside additionalProperties:false, so the schema accepts exactly the _-prefixed metadata the parser accepts and rejects exactly the unknown keys the parser rejects. The committed schema/workflow.schema.json is regenerated (the no-drift test enforces equality; the schema CLI output byte-equals the committed file).

Docs

  • Schema↔parser conformance wording corrected in SPEC.md / README.md to the now-accurate statement: the parser and the published schema agree — every workflow / step / governor / expr object is closed (unknown keys rejected by BOTH) except keys prefixed with _ (ignored metadata); integers are bounded; a schema-valid workflow parses, and a parser-accepted workflow is schema-valid. The prior sentence that conflated the expr case with step/governor and claimed the schema "does not accept what the parser rejects" while the parser was still lenient has been replaced. Workflow_json.mli documents the closed-object rule and the _ escape hatch.

Other

  • CLI --version → 0.6.0.
  • New tests (behavioral parity guards the v0.5 suite lacked):

    • Parser strictness, per object type: a table asserting the parser of_string ⇒ Error on an unknown non-underscore key for EACH of the top-level workflow object, agent/gate/branch/loop/commit steps, and max_iters/budget/fixpoint governors.
    • Underscore metadata accepted: a workflow with a top-level _doc and a step _note (and a governor _why) parses OK.
    • Schema/parser parity (structural cross-check, no JSON-Schema-validator dependency): each closed object def in the schema carries both additionalProperties:false and a ^_ patternProperty, AND the set of declared properties names for each step/governor/workflow object EQUALS the parser's hard-coded known-key set.
    • The examples (bounty.workflow.json, smoke.workflow.json — the latter has a top-level _doc) still parse, validate, and lint clean. All v0.5 tests remain green (39 tests total).

Preserved invariants

  • Runtime token on every Commit (hashed for the trace, never stored raw).
  • Floor gates guaranteed-evaluated and must PASS on every path to a commit; a false gate blocks.
  • Engine loop ceiling (termination guarantee); determinism / byte-identical replay.
  • Expr.eval totality; lint-clean ⇒ validate.
  • lib/ depends on yojson only — cabal stays confined to bin/.

v0.5

A corrective release addressing findings from an external audit. Four fixes: two correctness/safety blockers in the engine, one schema soundness gap, and a round of doc honesty.

Fixed

  • Loop termination is now an engine guarantee, not a backend/agent promise (BLOCKER). Previously a Budget-only loop could run forever (the shipped cabal backend returns budget () as a constant, so Budget never fired), and a Fixpoint-only loop never terminated if the agent always reported progress. Engine.run / Engine.replay now take ?max_loop_iters (default 10_000) and every loop always stops once it has executed that many iterations — recording Loop_stopped { reason = "ceiling" } — regardless of governors, until, budget, or agent behaviour. Budget / Fixpoint / until are now documented as early-stop heuristics under the ceiling, and Max_iters as an explicit lower bound. The validator still requires ≥1 governor (intent), but the termination guarantee is the ceiling. The ceiling is a constant, so replay reproduces it byte-identically.
  • A failing Gate now BLOCKS the run. A Gate whose predicate evaluates false terminates the walk as Blocked (naming the gate id) instead of recording Fail and continuing. The floor now means "floor gates must pass on every path to a commit." A Gate that evaluates true records Pass and continues, unchanged.
  • examples/bounty.workflow.json restructured. It previously gated g-independent on outputs.final-review.verdict, produced later inside the branch — which both warned (dangling-output-ref) and, under the new gate semantics, would have blocked. The independent review (final-review) and the draft-poc output schema now run before the floor gates, so every gate references only outputs produced before it. The example is now lint-clean (zero diagnostics, no warnings) and reaches commit when the gate predicates hold.
  • JSON Schema no longer accepts what the parser rejects (major). Every expr operator object and every step/governor object is now closed (additionalProperties:false) — matching the parser's exactly-one-operator/kind requirement, so {"path":"x","junk":2} is schema-invalid. The integer governor fields (max_iters.n, fixpoint.window) carry minimum:1 and maximum:1073741823 (2³⁰−1, inside OCaml's safe int range), so a literal too large for the parser to read as an int is schema-invalid too. The committed schema/workflow.schema.json is regenerated (the no-drift test enforces equality); the schema test now asserts the closed objects and the integer bounds structurally (still no JSON-Schema validator dependency).

Docs

  • Loop wording reframed across SPEC.md / README.md / the Engine and Types interfaces: every loop is hard-bounded by the engine ceiling; governors and until are early-stop heuristics; no loop can run unboundedly regardless of the backend's budget or the agent's progress reports.
  • Floor wording updated: floor gates must pass (not merely be present) on every path to a commit; a false gate blocks.
  • Schema↔parser conformance wording made accurate (it now rejects the two divergences above).
  • Lint performance claim made honest: no longer "instant / free"; now "pure, offline, no agent/IO; linear for realistic workflows, worst-case superlinear on pathologically deep branch nesting."
  • extract_json (bin/backend_cabal.ml) docstring notes it is best-effort, not balanced-bracket-aware, and fails closed on ambiguous input (valid-JSON-then-prose-with-braces may be rejected — the safe direction). The disclosed cross-branch dangling-output-ref limitation note is kept.

Other

  • CLI --version → 0.5.0.
  • New tests: a Budget-only loop with a constant budget stops at the ceiling (~max_loop_iters:5, reason "ceiling"); a Fixpoint-only loop whose agent always reports progressed:true also stops at the ceiling; a false floor gate yields Blocked; the bounty example lints with zero diagnostics; the smoke example still reaches Committed; the schema's expr/step/governor objects are closed and its integer fields are bounded, and the parser rejects the junk-key / out-of-range-integer divergences. The decrements-to-zero Budget early-stop and Fixpoint early-stop tests are retained.

Preserved invariants

  • Abstract Validate.Validated.t; Engine.run/replay require it.
  • Commit needs a runtime token (hashed for the trace, never stored raw).
  • Floor gates guaranteed on every path to a commit.
  • lib/ depends on yojson only — cabal stays confined to bin/.

v0.4

A machine-readable JSON Schema of the workflow format, so a meta-agent can constrain its generator to produce conformant workflows by construction — the first of three layers: schema (shape at generation) → lint (semantics/safety pre-run) → validate (the run gate). Library-first.

Added

  • Workflow_schema (lib/workflow_schema.ml(i)) — a pure, yojson-only module exposing the canonical JSON Schema (draft 2020-12) of a workflow as a library value (schema : Yojson.Safe.t, to_string : unit -> string). It uses $defs + $ref for the recursive expr, governor, step and output_schema parts, and is derived from Workflow_json (the actual parser) so it describes exactly what the parser accepts (every step kind, the single-operator expr encoding, the governor kinds, the output_schema type tags). Unknown object keys (the _doc convention) are tolerated, matching the parser's leniency.
  • schema/workflow.schema.json — the committed, pretty-printed artifact a generator/embedder is pointed at. Generated from the library value (like cabal's generate_opam_files); a no-drift test asserts it byte-matches Workflow_schema.to_string ().
  • CLI schema — cabal-workflow-runner schema prints Workflow_schema.to_string () to stdout (exit 0). A thin wrapper.
  • Tests: schema is valid JSON with $schema + $defs(expr, governor, step); no drift (committed file == lib value, byte-for-byte); parser ↔ schema kinds agree (the schema's enumerated step kinds equal {agent, gate, branch, loop, commit} and the parser rejects an unknown kind). No JSON-Schema validator dependency was added.

Docs

  • A "Constrain your generator with the schema" note in the meta-agent sections of README.md and SPEC.md (the three layers: schema → lint → validate).
  • Fixed a v0.2.1 doc gap: README.md now documents CWR_BACKEND, CWR_MODEL and CWR_BUDGET in a "Live run against a backend" subsection, referencing examples/smoke.workflow.json (verified live to Committed).
  • SPEC.md §5: "workflow JSON Schema" moved from planned → done; remaining follow-ups (on-disk ledger + replay CLI, YAML/MD front-end, Spawn/subworkflow step) kept.

Preserved invariants

  • lib/ depends on yojson only — cabal stays confined to bin/.
  • Abstract Validate.Validated.t; Engine.run/replay require it.
  • Commit needs a runtime token; floor gates guaranteed on every path to a commit.

v0.3

A Lint library designed to be embedded by a meta-agent that builds its own workflows dynamically. Library-first: lib/lint.mli is the deliverable; the CLI lint subcommand is a thin convenience.

Added

  • Lint (lib/lint.ml(i)) — a pure, offline, yojson-only linter.

    • check ?floor_gates wf runs ALL floor + semantic checks over a typed workflow and collects every diagnostic in one pass (never first-error-only).
    • check_json ?floor_gates raw is the meta-agent entry point: it lints a generator's RAW string output. Parse-tolerant — malformed JSON becomes a single invalid-json error and a shape error becomes invalid-shape; it never raises.
    • diagnostics carry a STABLE machine code, a human/agent message, and a JSON-path loc (e.g. steps[3].body[0]). diagnostic_to_json / to_json serialise them ({"diagnostics":[..]}) for feeding back into a generator prompt. has_errors distinguishes floor failures from advisory warnings.
    • Error codes (floor + parse/shape, make a workflow unrunnable): invalid-json, invalid-shape, ungoverned-loop, unbounded-max-iters, bad-fixpoint-window, commit-missing-floor-gate.
    • Warning codes (legal + runnable, but a generator likely erred): dangling-output-ref, missing-output-schema, no-commit, unreachable-after-commit.
  • CLI lint <file> [--floor <g>]... [--json] — reads the file, calls Lint.check_json, prints a human table by default or Lint.to_json with --json. Exits non-zero iff there is an error-severity diagnostic (warnings alone exit 0).
  • Docs: a "Meta-agent: building workflows dynamically" section in SPEC.md and README.md (the generate → lint → fix embedding loop, the stable diagnostic-code table, and the lint-clean ⇒ validate contract).

Changed

  • Validate.workflow is now defined in terms of Lint.check. It computes diagnostics and returns Ok validated iff not (has_errors ds), else Error rendered from the error diagnostics. The gate and the linter therefore share ONE source of truth and cannot drift: a workflow with no error-severity diagnostics is guaranteed to validate. The signature (?floor_gates -> Types.workflow -> (Validated.t, string) result) and all existing behaviour are unchanged.

Preserved invariants

  • Abstract Validate.Validated.t; Engine.run/replay require it.
  • Commit needs a runtime token (hashed for the trace, never stored raw).
  • Floor gates guaranteed on every path to a commit.
  • lib/ depends on yojson only — cabal stays confined to bin/.

v0.2.1

First live end-to-end run against a real agent (validated on Claude Haiku).

Fixed / Added

  • The cabal backend now populates the registry via Adapter_loader.register_all before any lookup. Previously the registry was empty at runtime, so run always fell through to "no cabal backend available" and fail-closed — the live dispatch path was never actually functional.
  • Backend + model selection via CWR_BACKEND (backend id, e.g. claude-code) and CWR_MODEL (e.g. haiku), so a run can target a small/cheap/fast model.
  • Robust structured-output extraction. Small models often wrap JSON in prose or a fenced code block; structured_output now tolerates that (direct parse → strip fence → extract first {/[ … last }/]) instead of failing closed on "JSON plus noise". A live smoke run reproduced the brittleness (the first call failed strict parse) and this fix resolves it.
  • examples/smoke.workflow.json — a dumb end-to-end workflow exercising the whole tool (structured output + schema, a gate expression, a governed loop with fixpoint, a branch on structured output, a token-gated commit). Verified live: Committed with a hashed runtime token.

v0.2

Structured, data-driven workflows — without losing determinism or the safety floor.

Added

  • Structured agent output + run context. Agent carries an optional output_schema (a minimal required-field spec over String | Int | Number | Bool | Enum | Any). backend.run_agent now returns bool * Yojson.Safe.t. Each agent's output is bound into a run context under outputs.<id>; the current loop iteration index is exposed at loop.iter. On a successful run the output is validated against output_schema fail-closed — a mismatch yields Aborted "schema mismatch: <field>" (no silent pass, no retry).
  • Total predicate DSL (Expr). Path, Lit, Eq/Ne/Lt/Le/Gt/Ge, In, And/Or/Not, Exists. Expr.eval ~ctx : t -> bool is total: a missing path, a type mismatch, or an incomparable comparison yields false — it never raises and never diverges. No recursion/iteration constructs. JSON encoding in Workflow_json.
  • Governed (possibly-unbounded) loops. Loop { body; until; governors } replaces the fixed-cap loop. Governors: Max_iters n (n ≥ 1), Budget (stop once backend.budget () <= 0), Fixpoint { window; progress } (stop after window consecutive non-progress iterations). A loop may have no Max_iters — unbounded but governed; what is forbidden is an empty governors list.

Changed

  • Gates / branches / loops are now PURE DSL. Gate { id; when_ }, Branch { when_; then_; else_ }, Loop carry Expr.t predicates evaluated by the engine over the run context. eval_gate is removed from the backend entirely — including the old always-Pass CLI placeholder.
  • Backend is now { run_agent : ... -> bool * Yojson.Safe.t; budget : unit -> int }.
  • Validator (fail-closed): governors = [] ⇒ Error "loop is ungoverned"; Max_iters n with n < 1 ⇒ Error; Fixpoint window < 1 ⇒ Error. The floor-gate guarantee (every commit preceded by all floor gates on every path; branch = intersection; loop-body gates do not count) and the runtime token are unchanged.
  • Determinism / replay. The trace records, in order, everything a stop/branch decision reads — each agent's structured JSON, each Budget reading, each Fixpoint progress verdict, each until/gate/branch verdict, and loop iteration counts. A governed loop's bound is purely a function of these recorded inputs, so Engine.replay reproduces the outcome and trace byte-identically even for an unbounded loop.
  • CLI (bin/backend_cabal.ml): run_agent forces structured output (cabal Structured_report, parsing raw_json, fall back to JSON in agent_text; fail closed otherwise); budget defaults to 1,000,000 or reads CWR_BUDGET.

Preserved invariants

  • Abstract Validate.Validated.t; Engine.run/replay require it.
  • Commit needs a runtime token (hashed for the trace, never stored raw).
  • Floor gates guaranteed on every path to a commit.
  • lib/ depends on yojson only — cabal stays confined to bin/.

v0.1

Initial release: deterministic engine, fail-closed validator, bounded loops, context-free gates evaluated by the backend, runtime-token commits, JSON loader.