Install
dune-project
Dependency
Authors
Maintainers
Sources
sha256=846019b2ad922fcc94cd2bba6021b400c6784fcaebfac3bfcfc1461cd39b1ec9
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-resultmessage_end,compaction_end, and Pi 1.3.0 cache-warm usage entries). For the Pi backend, the usage counters andcost.cost_usdofcall.finishednow 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.finishedusage of Pi rows has always been labelledscope = "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.finishednow carries those counters andcost.cost_usdonfailedandtimeoutoutcomes, withusage.usage_basis = "partial"(previouslyunknown, 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
--deadlineor a controlled candidatedeadline_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 itsTimeoutresult first, so thetimeoutrow ofcall.finishedcarries the session id, partial usage, cost,provider_lifecycleand aprovider-timeoutdiagnostic (previously all null, classifiedhost-failure), and the step still ends ascandidate deadline expired. Limits:- YAML adapters (the built-in mutable claude-code, gemini and copilot, and
~/.cabal/adaptersoverrides) apply their owntimeout_secondsinstead 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_atshould leave at least 5 s before its own control deadline foragent.record. - A Cabal
Timeoutcounts as a deadline expiry only when the deadline has passed. An adapter timeout that fires earlier (a YAMLtimeout_secondsshorter than the time left) is still an ordinary, retryable failure. Cabal 0.3.2 also bounds the stdin prompt by the task timeout.
- YAML adapters (the built-in mutable claude-code, gemini and copilot, and
failure_diagnostic.stderr_bytes/stderr_sha256describe 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-observeshare one 128 MiB ceiling on canonical state bytes. A write whose resulting state exceeds it fails withchannel state exceeds canonical byte ceilingbefore 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 belowmax_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 bychannel-observe. - Store-open failures are classified in C from
errnointo invalid authority, busy (onlyEWOULDBLOCKon 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_FDare removed from the CLI. Tests inject the post-snapshot pause throughChannel_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-observeoutput and error codes are unchanged.
- Every channel writer and
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.finishedgainsprovider_lifecycle: Cabal'scabal.pi-lifecycle@1reduction 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, finalstopReason,truncated_output). Error excerpts are never stored:error_excerptis alwaysnull. Other backends writenull.schema_versionstays 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 withPi terminal error: truncated-outputand the sidecar classificationprovider-truncated-output, instead of a success with unparseable JSON orprovider-exit/provider-failure. - Pi MCP isolation. Read-only and mutable Pi steps probe
pi --versionand pass--no-mcpto 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 (recipecwr-build-recipe@3, authority recipe labelcwr-exact-private-build@3; the authority format stayscwr-build-authority@2). In v0.23.0 the privateduneembedded the workspace path, sobuild.tool_sha256differed between two honest builds and an independent verifier could not reproduce the build authority. The authority still binds the exact bytes of thedunethat ran; that hash is now reproducible. The builder needs unprivileged user namespaces and an empty/var/tmp/cwr-v2-buildowned 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_IDof.,.., any run of dots, or a value starting with-now fails as an unsafe identifier instead of reachingpi --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=1sets Cabal'sretain_sessionon agent calls. A fresh Pi call then receives neither--no-sessionnor--session, and Pi persists its session JSONL under its standard session location in theHOMEthe host provides. Unset, empty or0keeps--no-session. A resume (CWR_RESUME_STEP_ID+CWR_RESUME_SESSION_ID) still passes--session <id>. The 0.22 production build passed--no-sessionon every fresh Pi call, so no transcript was written; tagged v0.22.0 (Cabal 0.2.0) passed no session flag at all.capabilitiesdeclaresagent_session_retention(version 1, backendpi, bindingCWR_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 exceedNAME_MAX; hosts that retain sessions should use short working-directory paths. - Session environment is checked before the run. An invalid
CWR_RETAIN_SESSION, a partialCWR_RESUME_*pair or an unsafe resume id makesrunexit 1 with asession:message before any step executes. - Authenticated channel observation.
channel-observereports 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 PATHreads the run context from a regular file; it is mutually exclusive with--ctx. - Workflow deadline on agent calls.
run --deadline EPOCH_SECONDSbounds 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_IDandCWR_RESUME_SESSION_ID(both required, bounded identifier) resume a retained backend session for one step. - Capability declaration.
capabilitiesprints the closedcwr-capabilities@1set:agent_session_resume,context_file(run --ctx-file, exclusive with--ctx),channel_observation(channel-observewith required--channel,--channel-root,--now) andagent_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
successfield 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.shandscripts/verify-package-v2.shproduce and recheck a deterministic package withcwr-build-receipt@2andcwr-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-observecan read it. - The CLI honours
CWR_OBSERVE_TEST_NOTIFY_FDandCWR_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, andprioritydelivery modes to durable channels. Omittingmodepreserves 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 newWorkflow_source/Workflow_resolverAPIs preserve the existing closedTypes.workflowandWorkflow_jsoninterfaces. All workflow-input commands now use one resolver-aware loader; resolution is offline, bounded, namespace-safe, and emits deterministic redactedcwr-resolution-receipt@1evidence. A disposable verified raw-object cache never replaces registry authority. The unresolved schema is available throughsource-schemaandschema/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 throughCWR_RESOLUTION_RECEIPT_FDand fail closed if that configured channel fails. - Run steps now accept explicit
"observe": []to execute without a filesystem snapshot. Omittingobserveremains 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 -> stringserialises a trace to newline-delimited JSON: one tagged ("kind") object pertrace_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 FULLrun_result: exit/stdout/stderr/truncated and each file's path/change/size/digest),Committed_step,Blocked_at.of_ndjson : string -> (Types.trace, string) resultis the fail-closed inverse: any malformed line (bad JSON, unknown/missingkind, missing/ill-typed field) ⇒Error, never raises; blank lines (a trailing newline) are ignored. Round-trip:of_ndjson (to_ndjson t) = Ok tfor every trace.
- CLI.
rungains--ledger <path>: after a successful run the recorded trace is written as NDJSON to<path>. New subcommandreplay <workflow.json> --ledger <path> [--floor <g>]…: loads +Validate.workflows the workflow, reads the ledger,Ledger.of_ndjsons it (clear error on corrupt), andEngine.replay ~traces it — printing the replayed outcome and exiting0on success, non-zero on a corrupt ledger, a validation error, or aReplay_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.replayre-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 inbin/.- No schema / parity impact. The ledger is runtime output, not workflow input — the workflow schema is unchanged and
scripts/parity_check.pystays at 0 divergences.
Tests
- Round-trip over a trace exercising every entry variant (incl. a
Run_executedwith file changes andLoop/Budget/Fixpointentries):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, andEngine.replayed to the identical outcome — with marker counters proving replay called neitherrun_agentnorrun_command. - Corrupt/tampered ledger: a malformed (and an unknown-
kind) line ⇒of_ndjsonError; a ledger with a trailing extra entry decodes but ⇒Engine.replayReplay_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.cmdis a non-empty argv executed without a shell (no implicitsh -c).working_diris required, relative, and rejected at parse if absolute or containing a..component (the effect scope + snapshot root).timeout_msis an optional bounded int;observeis an optional list of relative paths to snapshot (default: the wholeworking_dir).- Injected run effect — cabal stays out of
lib/.Backend.tgainsrun_command : id:… -> argv:string list -> working_dir:… -> timeout_ms:int option -> observe:string list option -> run_result, whererun_result = { exit; stdout; stderr; truncated; files }andfile_change = { path; change : Created|Modified|Deleted; size; digest }. The library defines these types and calls the injected function;bin/runner.ml(wired inbin/backend_cabal.ml) implements it viaCabal.Backend_process.run_process(no shell) plus a before/after directory snapshot (path → digest + size) diffed into afile_change list.digestis an MD5 content digest (Digest) for change-detection / observability — NOT a cryptographic integrity guarantee.stdout/stderrare size-capped at 64 KiB with atruncatedflag. The result is bound underoutputs.<id>as JSON, so the DSL can readoutputs.mk.exit,exists(outputs.mk.files), etc.lib/still depends on yojson only. - Operator allowlist (runtime-only, fail-closed).
Engine.rungains?run_allowlist:string list(default[]). Arunstep executes only ifFilename.basename (List.hd cmd)is in the allowlist or the allowlist contains"*"; otherwise the step isBlocked(run command "<bin>" not permitted (allowlist)). With[], norunstep 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.replayconsumes the recordedRun_executed, re-binds it, and NEVER re-executes (norun_commandcall; the allowlist is not consulted on replay since nothing runs) — sormruns once and replay is byte-identical + side-effect-free, mirroring theAgent_ranreplay arm. The allowlist-Blockedcase records/replays asBlocked_at+ terminalBlocked, like the gate/commitFailarms. Trailing-trace-entry rejection still holds for run-bearing traces. - Validator / schema / parser.
working_dirabsolute or..⇒ reject; emptycmd⇒ reject (parser-level). The JSON Schema gains a closedrunstep variant (cmdan arrayminItems:1of strings,working_dira required string carrying a pattern that rejects absolute /..-segment paths to keep the schema↔parser iff,timeout_msa bounded int,observean array of strings).schema/workflow.schema.jsonregenerated (no-drift test green); the parser↔schema kinds test now includesrun; the behavioral parity test andscripts/parity_check.pygainedruncases (parity still 0 divergences). - Lint. Every
runstep emits an informationalrun-step-executes-commandswarning, and a known-destructive binary (rm,rmdir,mv,dd,mkfs,shred,truncate, the:(){fork-bomb idiom) emits a louderrun-step-destructive-commandwarning. Both are warnings (best-effort, not a security control — the allowlist is the trust boundary), sohas_errorsstays false. - Example.
examples/run-demo.workflow.json— arunofmkdir -p(observing the created dir) followed by agateoneq(outputs.mk.exit, 0), endingCompleted_no_commit. Validates and lints clean-of-errors (therun-step-executes-commandswarning 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). Thefile_changefield is renamedsha256→digest(runtime output underoutputs.<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 pinsMD5("abc") = 900150983cd24fb0d6963f7d28e17f72. - Closed the allowlist bypass.
cmd[0]must be a bare command name resolved viaPATH: anycmd[0]containing a/(absolute/relative path) isBlockedbefore 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.mlwraps the whole effect intry … with: spawn failure ⇒ exit127, output-buffer overflow ⇒ exit125+truncated, timeout ⇒ exit124— always a recordedrun_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 symlinkedworking_diris 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
runmkdir-like (stub returns exit 0 + aCreatedfile) ⇒outputs.mk.exit = 0,fileshas the created entry, and a followinggate eq(outputs.mk.exit, 0)passes.- Allowlist enforcement: a non-allowlisted binary ⇒
Blockedwithrun_commandnot 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.replayreproduces the identical outcome AND the counter does not increment; trailing-entry rejection still holds. - File diff: a first run returns
Createdand a second returnsDeleted; both observed in their respectiveoutputs.<id>.files. working_dirwith../ absolute and an emptycmd⇒ parseError.- The
run-demoexample validates + lints clean-of-errors; a destructivermrun emitsrun-step-destructive-commandwhilehas_errorsstays false. - Review-fix tests: MD5 digest known-answer; path-bearing
cmd[0](absolute/relative) ⇒Blockedwithrun_commandnot 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.evaltotality; lint-clean ⇒ validate; schema↔parser parity / no-drift (scripts/parity_check.py0 divergences);lib/depends on yojson only — process execution lives inbin/.
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.ymlreproduces the documented build onubuntu-latest:ocaml/setup-ocaml@v3(OCaml 5.3), pins the public cabal (opam pin add -n cabal …),opam install . --deps-only --with-test, thendune 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.mlpreviously used cwd-relative../examples/…/../schema/…paths that only resolved under thedune testsandbox, sodune exec test/test_cwr.exefrom the repo root spuriously failed. Aproject_pathhelper now resolves fixtures viaDUNE_SOURCEROOT(set by dune fordune exec/dune test), falling back to the legacy../form. Bothdune testanddune exec test/test_cwr.exepass (45 tests). CONTRIBUTING.mdadded: build/test recipe (cabal pin), the parity-check workflow, thelib/-stays-yojson-only rule, the schema↔parser parity contract, and the safety-floor invariants a change must preserve.README.mdgained a prominent "Status: early / experimental (v0.x)" note surfacing the MVP boundaries (in-memory replay, JSON-only format, noSpawn, the small-model live-dispatch validation) and a one-line AI-assistance disclosure.- Renamed a test fixture token from
super-secret-approvaltotest-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'sAgentbranch fell through| _ -> stonsuccess = false, binding the backend's{"error":…}output and CONTINUING; a later always-true gate + token could thenCommitdespite the failure. Asuccess = falseagent run now aborts the walk (Aborted, emittingBlocked_at), mirroring the schema-mismatch arm. The symmetric change is made inEngine.replay(it consumes the recordedBlocked_atand reproduces theAborted), so run and replay agree on the trace shape[Agent_ran{success=false}; Blocked_at; …Aborted]. - F2 (Medium) —
Existstreats a present object/array as present.value_of_jsonflattens`Assoc _toNull(fine for comparisons), so{"exists":"outputs.a.obj"}was false even whenobjwas a present object.Exprnow resolvesExistsover the RAW JSON (newresolve_raw): a present object/array/scalar ⇒ true; an explicit JSONnullor a missing path ⇒ false. Comparison operators keep value-basedresolve(semantics unchanged);Expr.evalstays total. - F3 (Medium) — lint catches branch-dependent dangling output refs.
Lint'sBranchcase 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 aBranchis 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: anidsurvives only if in both arms; its fields are the field-set intersection when both declare a schema, elseNone. Intra-arm behaviour is unchanged. The examples remain lint-clean (0 diagnostics). - F4 (Medium) — replay rejects trailing extra trace entries.
Engine.replayconsumed from the pending trace but never asserted it was empty when the walk finished, so a trace = valid-prefix ++ garbage replayed "successfully". It now raisesReplay_mismatch "trailing trace entries after workflow completed"if any entries remain. (Replay_mismatchis now exposed inengine.mli.) - F5 (Low/Med) —
CWR_BUDGETis a real consumable cap.bin/backend_cabal.ml'sbudget ()returned the env value on EVERY call, soCWR_BUDGET=10read10forever and theBudgetgovernor never fired.budgetis now a per-make(per-run, shared across all loops = a total run budget) mutable counter initialised fromCWR_BUDGET(default 1_000_000) that decrements and returns the remaining. Documented off-by-one: withCWR_BUDGET=Nthe counter starts at N, readings are N−1…0, and theBudgetgovernor stops on the Nth check, so the run performs at most N budget-governed loop iterations total. Determinism is unaffected (everyBudget_readis recorded; replay re-feeds recorded values and never callsbudget).
Tests
- F1: a workflow whose first agent stub returns
success = false(then an always-true gate + commit + token) ⇒Engine.runyieldsAborted(NOTCommitted), noCommitted_stepin the trace, andEngine.replay ~tracereproduces the sameAborted. - F2:
Exists ["outputs";"a";"obj"]⇒ true over a present object, false over an explicitnull, false over a missing path, true over a present scalar and a present array. - F3: a gate after a branch referencing
outputs.x.vwithxproduced only in thethenarm ⇒dangling-output-refWarning; 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: theAgentstep / engine §3 note the fail-closed-on-failed-agent behaviour; theCWR_BUDGETdescription 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.evaltotality; lint-clean ⇒ validate; schema↔parser parity / no-drift (scripts/parity_check.pystill 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'sreq_bounded_intaccepted only`Int, rejecting`Float. The schema cannot cleanly forbid5.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.nandfixpoint.windowbounds now agree on both sides. The parser enforces1 ≤ v ≤ max_intat parse (newreq_bounded_int): a value< 1is rejected with a clear message (field "n" must be >= 1 (got 0)); a literal> max_intis yielded by yojson as`Intlitand rejected. Previously the parser acceptedn = -5/n = 0that the schema rejected. The schema'sbounded_intmaximumwas raised from1073741823(2³⁰−1) to4611686018427387903(OCamlmax_inton 64-bit), so a large-but-valid literal like1073741824is now schema-valid AND parser-accepted (previously schema-rejected); a literal beyondmax_intremains invalid on both sides.- Empty
governorsis now a parse-level shape error. The schema declares the loopgovernorsarrayminItems:1; the parser now requires a non-empty list (newreq_nonempty_list), so it no longer accepts an emptygovernorsarray the schema rejects. (The richerungoverned-loopsemantic diagnostic still lives inLint/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.jsonis regenerated from the lib value (the no-drift test enforces byte-equality; theschemaCLI 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 singlegovernors, 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.mdstate the governing principle, correct the over-claim that expr objects took_metadata, document themax_intbound and theminItems:1governors rule, and noteoutput_schemais 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_jsonnow 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 disciplineexpr_of_jsonalready enforced ("expression object must have exactly one operator key").output_schemais 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: {"^_": {}}alongsideadditionalProperties:false, so the schema accepts exactly the_-prefixed metadata the parser accepts and rejects exactly the unknown keys the parser rejects. The committedschema/workflow.schema.jsonis regenerated (the no-drift test enforces equality; theschemaCLI output byte-equals the committed file).
Docs
- Schema↔parser conformance wording corrected in
SPEC.md/README.mdto 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.mlidocuments 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 ⇒ Erroron an unknown non-underscore key for EACH of the top-level workflow object,agent/gate/branch/loop/commitsteps, andmax_iters/budget/fixpointgovernors. - Underscore metadata accepted: a workflow with a top-level
_docand 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:falseand a^_patternProperty, AND the set of declaredpropertiesnames 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).
- Parser strictness, per object type: a table asserting the parser
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.evaltotality; lint-clean ⇒ validate.lib/depends on yojson only — cabal stays confined tobin/.
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 returnsbudget ()as a constant, soBudgetnever fired), and aFixpoint-only loop never terminated if the agent always reported progress.Engine.run/Engine.replaynow take?max_loop_iters(default10_000) and every loop always stops once it has executed that many iterations — recordingLoop_stopped { reason = "ceiling" }— regardless of governors,until, budget, or agent behaviour.Budget/Fixpoint/untilare now documented as early-stop heuristics under the ceiling, andMax_itersas 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
Gatenow BLOCKS the run. AGatewhose predicate evaluates false terminates the walk asBlocked(naming the gate id) instead of recordingFailand continuing. The floor now means "floor gates must pass on every path to a commit." AGatethat evaluates true recordsPassand continues, unchanged. examples/bounty.workflow.jsonrestructured. It previously gatedg-independentonoutputs.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 thedraft-pocoutput 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 reachescommitwhen 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/kindrequirement, so{"path":"x","junk":2}is schema-invalid. The integer governor fields (max_iters.n,fixpoint.window) carryminimum:1andmaximum:1073741823(2³⁰−1, inside OCaml's safeintrange), so a literal too large for the parser to read as anintis schema-invalid too. The committedschema/workflow.schema.jsonis 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/ theEngineandTypesinterfaces: every loop is hard-bounded by the engine ceiling; governors anduntilare 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).
Lintperformance 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-branchdangling-output-reflimitation 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"); aFixpoint-only loop whose agent always reportsprogressed:truealso stops at the ceiling; a false floor gate yieldsBlocked; the bounty example lints with zero diagnostics; the smoke example still reachesCommitted; 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-zeroBudgetearly-stop andFixpointearly-stop tests are retained.
Preserved invariants
- Abstract
Validate.Validated.t;Engine.run/replayrequire it. Commitneeds 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 tobin/.
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+$reffor the recursiveexpr,governor,stepandoutput_schemaparts, and is derived fromWorkflow_json(the actual parser) so it describes exactly what the parser accepts (every stepkind, the single-operator expr encoding, the governor kinds, theoutput_schematype tags). Unknown object keys (the_docconvention) 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'sgenerate_opam_files); a no-drift test asserts it byte-matchesWorkflow_schema.to_string ().- CLI
schema—cabal-workflow-runner schemaprintsWorkflow_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 stepkinds 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.mdandSPEC.md(the three layers: schema → lint → validate). - Fixed a v0.2.1 doc gap:
README.mdnow documentsCWR_BACKEND,CWR_MODELandCWR_BUDGETin a "Live run against a backend" subsection, referencingexamples/smoke.workflow.json(verified live toCommitted). SPEC.md§5: "workflow JSON Schema" moved from planned → done; remaining follow-ups (on-disk ledger +replayCLI, YAML/MD front-end,Spawn/subworkflow step) kept.
Preserved invariants
lib/depends on yojson only — cabal stays confined tobin/.- Abstract
Validate.Validated.t;Engine.run/replayrequire it. Commitneeds 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 wfruns ALL floor + semantic checks over a typed workflow and collects every diagnostic in one pass (never first-error-only).check_json ?floor_gates rawis the meta-agent entry point: it lints a generator's RAW string output. Parse-tolerant — malformed JSON becomes a singleinvalid-jsonerror and a shape error becomesinvalid-shape; it never raises.diagnostics carry a STABLE machinecode, a human/agentmessage, and a JSON-pathloc(e.g.steps[3].body[0]).diagnostic_to_json/to_jsonserialise them ({"diagnostics":[..]}) for feeding back into a generator prompt.has_errorsdistinguishes 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, callsLint.check_json, prints a human table by default orLint.to_jsonwith--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.mdandREADME.md(the generate → lint → fix embedding loop, the stable diagnostic-code table, and the lint-clean ⇒ validate contract).
Changed
Validate.workflowis now defined in terms ofLint.check. It computes diagnostics and returnsOk validatediffnot (has_errors ds), elseErrorrendered 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/replayrequire it. Commitneeds 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 tobin/.
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_allbefore any lookup. Previously the registry was empty at runtime, sorunalways 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) andCWR_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_outputnow 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 withfixpoint, a branch on structured output, a token-gated commit). Verified live:Committedwith a hashed runtime token.
v0.2
Structured, data-driven workflows — without losing determinism or the safety floor.
Added
- Structured agent output + run context.
Agentcarries an optionaloutput_schema(a minimal required-field spec overString | Int | Number | Bool | Enum | Any).backend.run_agentnow returnsbool * Yojson.Safe.t. Each agent's output is bound into a run context underoutputs.<id>; the current loop iteration index is exposed atloop.iter. On a successful run the output is validated againstoutput_schemafail-closed — a mismatch yieldsAborted "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 -> boolis total: a missing path, a type mismatch, or an incomparable comparison yieldsfalse— it never raises and never diverges. No recursion/iteration constructs. JSON encoding inWorkflow_json. - Governed (possibly-unbounded) loops.
Loop { body; until; governors }replaces the fixed-cap loop. Governors:Max_iters n(n ≥ 1),Budget(stop oncebackend.budget () <= 0),Fixpoint { window; progress }(stop afterwindowconsecutive non-progress iterations). A loop may have noMax_iters— unbounded but governed; what is forbidden is an emptygovernorslist.
Changed
- Gates / branches / loops are now PURE DSL.
Gate { id; when_ },Branch { when_; then_; else_ },LoopcarryExpr.tpredicates evaluated by the engine over the run context.eval_gateis removed from the backend entirely — including the old always-PassCLI placeholder. - Backend is now
{ run_agent : ... -> bool * Yojson.Safe.t; budget : unit -> int }. - Validator (fail-closed):
governors = []⇒Error "loop is ungoverned";Max_iters nwithn < 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
Budgetreading, eachFixpointprogress verdict, eachuntil/gate/branch verdict, and loop iteration counts. A governed loop's bound is purely a function of these recorded inputs, soEngine.replayreproduces the outcome and trace byte-identically even for an unbounded loop. - CLI (
bin/backend_cabal.ml):run_agentforces structured output (cabalStructured_report, parsingraw_json, fall back to JSON inagent_text; fail closed otherwise);budgetdefaults to 1,000,000 or readsCWR_BUDGET.
Preserved invariants
- Abstract
Validate.Validated.t;Engine.run/replayrequire it. Commitneeds 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 tobin/.
v0.1
Initial release: deterministic engine, fail-closed validator, bounded loops, context-free gates evaluated by the backend, runtime-token commits, JSON loader.