diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dbce981..fb0ae26 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,7 +41,7 @@ jobs: test: name: Test / ${{ matrix.os-name }} / Node ${{ matrix.node-version }} runs-on: ${{ matrix.os }} - timeout-minutes: 15 + timeout-minutes: ${{ matrix.os-name == 'macOS' && 20 || 15 }} strategy: fail-fast: false matrix: diff --git a/README.md b/README.md index 97cb199..5be9b9d 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,19 @@ Repository maintainers and developer-tooling teams use ThreadLoop to govern AI-a verification, review, and human completion. Agents perform work; ThreadLoop owns advancement through the outer software development lifecycle (SDLC). Completion requires current evidence of same-HEAD human approval and the merged PR. -ThreadLoop currently runs a fixed governed PR lifecycle. It's neither an agent harness nor a general-purpose DAG engine. -It doesn't supply a model/tool loop, model routing, or protected-effect permission enforcement. +ThreadLoop supports the fixed governed PR lifecycle and configurable, graph-bound Workflow Runs. A run can hand an +enrolled engineering action to a bounded executor. ThreadLoop checks the returned evidence before it allows a +transition. ## Capability status -| Status | What it covers | -| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Implemented now** | Fixed PR lifecycle, durable SQLite state, current-HEAD proof and signed review checks, bounded post-PR repair, human completion, review artifacts, and verified audit export. | -| **Implemented now** | [Graph-bound Workflow Runs](docs/workflow-runs.md) with durable graph bindings, deterministic decisions, explicit transition application and prepared signed evidence. | -| **Accepted in Controller Contract v0.1** | Workflow Profile and Compiled Graph, Controller Decision and Action Request, Execution Claim and Attempt, executor/GAAP mapping, and controller conformance specifications, published in [threadloop-contracts](https://github.com/nnennandukwe/threadloop-contracts). | -| **Deferred to the controller-runtime milestone** | Dispatch of selected engineering actions and verification of the production controller by the external suite. | -| **Deferred to the Rust migration** | A Rust ThreadLoop replacement, after the contract freeze and separate runtime milestone demonstrate the required behavior. | +| Status | What it covers | +| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Implemented now** | Fixed PR lifecycle, durable SQLite state, current-HEAD proof and signed review checks, bounded post-PR repair, human completion, review artifacts, and verified audit export. | +| **Implemented now** | [Graph-bound Workflow Runs](https://github.com/nnennandukwe/threadloop/blob/1c59b1a4d08732a7dac5e2cdd1f84dd403e6113c/docs/workflow-runs.md) with durable graph bindings, deterministic decisions, explicit transition application and prepared signed evidence. | +| **Accepted in Controller Contract v0.1** | Workflow Profile and Compiled Graph, Controller Decision and Action Request, Execution Claim and Attempt, executor/GAAP mapping, and controller conformance specifications, published in [threadloop-contracts](https://github.com/nnennandukwe/threadloop-contracts). | +| **Implemented now** | Selected engineering actions use the managed GAAP bridge. The caller can import a signed child result, inspect the next decision and request a guarded transition. [Workflow Run commands](https://github.com/nnennandukwe/threadloop/blob/1c59b1a4d08732a7dac5e2cdd1f84dd403e6113c/docs/workflow-runs.md) | +| **Deferred to the Rust migration** | A Rust ThreadLoop replacement, after the contract freeze and separate runtime milestone demonstrate the required behavior. | The optional [GAAP executor bridge](docs/gaap-executor.md) implements explicit host adoption, durable Execution Claims, one bounded process invocation, independent signed receipt verification, and evidence persistence before guard @@ -30,10 +31,10 @@ The contracts and their offline compiler and validators live in mapping helpers also support the optional executor bridge. Existing sessions don't acquire graph bindings or Execution Claims from the accepted specifications. -The [contract freeze #110](https://github.com/nnennandukwe/threadloop/issues/110) is complete. -[RunInvariant PR #4](https://github.com/nnennandukwe/run-invariant/pull/4) merged the external harness for this corpus. -Synthetic subjects exercise that harness; conformance by a real ThreadLoop controller remains unproven. These milestones -don't establish a release or completion of the separate runtime milestone. +RunInvariant launches ThreadLoop’s controller subject against the frozen v0.1 corpus. The readiness report records the +measured revision, case results, rollback checks and the status of the live human completion gate. +[TypeScript baseline](https://github.com/nnennandukwe/threadloop/blob/1c59b1a4d08732a7dac5e2cdd1f84dd403e6113c/docs/pre-rust-readiness.md) +· [Contract freeze](https://github.com/nnennandukwe/threadloop/issues/110) The [architecture guide](docs/architecture.md) explains the four system roles, the YAML-to-canonical-JSON contract, and the relationship between a ThreadLoop Workflow Run and a GAAP Agent Run. It links the normative contracts and separates diff --git a/docs/architecture.md b/docs/architecture.md index 0827d90..ebc03a1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,16 +13,16 @@ contracts and what remains to be implemented. The [glossary](../CONTEXT.md) defi The status applies to the specific capability, not to every use of the same domain term. -| Status | Capability | Evidence or next owner | -| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Implemented now** | Fixed PR lifecycle, SQLite persistence, guarded transitions, current-HEAD proof/review checks, repair accounting, blocking, and human completion. | [Lifecycle reference](lifecycle.md) and [preservation mapping](current-lifecycle-graph-mapping.md). | -| **Implemented now** | Session CLI, read-only next-action inspection, Markdown artifacts, and verified audit exports. | [CLI reference](cli.md) and [audit export](observability.md). | -| **Implemented now** | Deterministic controller selection and durable graph-bound create, inspect, decide and apply operations, including prepared signed evidence. | [Workflow Run commands](workflow-runs.md) and [selection implementation](../src/domain/workflow-controller.ts). | -| **Implemented in threadloop-contracts** | YAML compiler, candidate validators, executor mapping helpers, and internal conformance-corpus checks. | Development tooling in [threadloop-contracts](https://github.com/nnennandukwe/threadloop-contracts), tagged `v0.1.0`. | -| **Accepted in Controller Contract v0.1** | Profile/graph identities, deterministic decisions and action requests, claim/attempt recovery semantics, executor process seam, and external conformance protocol. | Five versioned contract families in the [contract index](#contract-index). | -| **Deferred to the controller-runtime milestone** | Selected-action execution and conformance through the external harness. | [Runtime tracker #168](https://github.com/nnennandukwe/threadloop/issues/168), [conformance handoff](https://github.com/nnennandukwe/threadloop-contracts/blob/v0.1.0/docs/contracts/controller-conformance-v0.1/run-invariant-follow-up.md), and [generated state-machine tests #112](https://github.com/nnennandukwe/threadloop/issues/112). | -| **Implemented in the optional executor bridge** | Host-adopted claims, GAAP process invocation, independently authenticated receipt admission, and persistence before controller reevaluation. | [Executor guide](gaap-executor.md) and [runtime integration #111](https://github.com/nnennandukwe/threadloop/issues/111). | -| **Deferred to the Rust migration** | A Rust replacement of ThreadLoop after the contract freeze and the separate runtime milestone prove the required behavior. | [Contract tracker #110](https://github.com/nnennandukwe/threadloop/issues/110), [storage compatibility #85](https://github.com/nnennandukwe/threadloop/issues/85) and [runtime tracker #168](https://github.com/nnennandukwe/threadloop/issues/168). | +| Status | Capability | Evidence or next owner | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Implemented now** | Fixed PR lifecycle, SQLite persistence, guarded transitions, current-HEAD proof/review checks, repair accounting, blocking, and human completion. | [Lifecycle reference](lifecycle.md) and [preservation mapping](current-lifecycle-graph-mapping.md). | +| **Implemented now** | Session CLI, read-only next-action inspection, Markdown artifacts, and verified audit exports. | [CLI reference](cli.md) and [audit export](observability.md). | +| **Implemented now** | Deterministic controller selection and durable graph-bound create, inspect, decide and apply operations, including prepared signed evidence. | [Workflow Run commands](workflow-runs.md) and [selection implementation](../src/domain/workflow-controller.ts). | +| **Implemented in threadloop-contracts** | YAML compiler, candidate validators, executor mapping helpers, and internal conformance-corpus checks. | Development tooling in [threadloop-contracts](https://github.com/nnennandukwe/threadloop-contracts), tagged `v0.1.0`. | +| **Accepted in Controller Contract v0.1** | Profile/graph identities, deterministic decisions and action requests, claim/attempt recovery semantics, executor process seam, and external conformance protocol. | Five versioned contract families in the [contract index](#contract-index). | +| **Implemented now** | Enrolled engineering actions dispatch through the GAAP bridge. The controller subject exposes graph compilation, decisions and execution scenarios to RunInvariant. | [Managed execution](workflow-runs.md) and [external proof and parity](pre-rust-readiness.md). | +| **Implemented in the optional executor bridge** | Host-adopted claims, GAAP process invocation, independently authenticated receipt admission, and persistence before controller reevaluation. | [Executor guide](gaap-executor.md) and [runtime integration #111](https://github.com/nnennandukwe/threadloop/issues/111). | +| **Deferred to the Rust migration** | A Rust replacement of ThreadLoop after the contract freeze and the separate runtime milestone prove the required behavior. | [Contract tracker #110](https://github.com/nnennandukwe/threadloop/issues/110), [storage compatibility #85](https://github.com/nnennandukwe/threadloop/issues/85) and [runtime tracker #168](https://github.com/nnennandukwe/threadloop/issues/168). | An accepted schema isn't a running service. A valid fixture isn't an admitted receipt, an acquired claim, or a runtime conformance result. Existing CLI `task` and `session` names remain compatibility terms; these contracts don't rename @@ -30,27 +30,24 @@ commands, change SQLite records, or retroactively bind sessions to configurable ## Four roles and their authority -| Role | Responsibility | Authority boundary | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -| **ThreadLoop** | Own the Workflow Run, outer SDLC feedback loop, guarded transitions, evidence freshness, repair rules, and human completion boundary. | Only ThreadLoop applies its lifecycle decisions. Host-adopted claims ship in the optional bridge; configurable runtime execution remains deferred. | -| **GAAP** | Govern one bounded Agent Run, including its model/tool work and protected effects. | Completion of an Agent Run supplies evidence; it can't complete a ThreadLoop Workflow Run. | -| **RunInvariant** | Evaluate implementation-independent decision conformance through fixtures and a process interface. | Conformance output can't dispatch work or advance lifecycle state. | -| **Adapters and delivery infrastructure** | Execute bounded requests, translate provider observations, or deliver scheduler wakes. | Delivery, process success, and adapter output can't invent authorization, recover blocked runs, or approve completion. | +| Role | Responsibility | Authority boundary | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| **ThreadLoop** | Own the Workflow Run, outer SDLC feedback loop, guarded transitions, evidence freshness, repair rules, and human completion boundary. | ThreadLoop applies a current decision on an explicit request. A child admission alone leaves the outer lifecycle version unchanged. | +| **GAAP** | Govern one bounded Agent Run, including its model/tool work and protected effects. | Completion of an Agent Run supplies evidence; it can't complete a ThreadLoop Workflow Run. | +| **RunInvariant** | Evaluate implementation-independent decision conformance through fixtures and a process interface. | Conformance output can't dispatch work or advance lifecycle state. | +| **Adapters and delivery infrastructure** | Execute bounded requests, translate provider observations, or deliver scheduler wakes. | Delivery, process success, and adapter output can't invent authorization, recover blocked runs, or approve completion. | [Governed Agent Autonomy Patterns (GAAP)](https://github.com/nnennandukwe/governed-agent-autonomy-patterns) is an inner execution system. ThreadLoop is the outer lifecycle authority; it's neither an agent harness nor a general-purpose DAG engine. Its graph language has registered SDLC actions, guards, authority requirements, and cycle controls, rather than arbitrary executable nodes or expressions. -[RunInvariant](https://github.com/nnennandukwe/run-invariant) currently provides GAAP decision-conformance -infrastructure. [RunInvariant PR #4](https://github.com/nnennandukwe/run-invariant/pull/4) merged a separate ThreadLoop -controller harness that consumes the pinned conformance corpus, launches one external process per case, and validates -responses. Synthetic subjects exercise the harness; a real ThreadLoop controller hasn't demonstrated conformance. After -the v0.1 freeze the corpus moved, with the rest of the contracts, to -[threadloop-contracts](https://github.com/nnennandukwe/threadloop-contracts); RunInvariant's existing pin to a -ThreadLoop commit stays valid. The -[integration handoff](https://github.com/nnennandukwe/threadloop-contracts/blob/v0.1.0/docs/contracts/controller-conformance-v0.1/run-invariant-follow-up.md) -records the requirements and remaining proof. Merged harness support doesn't establish a release or runtime integration. +RunInvariant owns the corpus and expected results during a proof. It sends each normalized request to a fresh external +subject process. ThreadLoop’s subject calls the compiler, production selector or execution journal. The parent checks +the returned identity and digests against the frozen inputs. The readiness report identifies the measured artifact, all +case results and the scope of the process isolation. +[External harness](https://github.com/nnennandukwe/run-invariant/pull/4) · +[TypeScript readiness report](pre-rust-readiness.md) ## Implemented now: the fixed governed PR lifecycle @@ -91,10 +88,10 @@ execution evidence in separate host-owned state; it never supplies those lifecyc ## Accepted in Controller Contract v0.1: the execution relationship -The following diagram describes accepted responsibilities. The optional [executor bridge](gaap-executor.md) implements -the Action Request through evidence admission and guard reevaluation. The pure controller selects a decision from a -supplied Workflow Run snapshot. The runtime milestone covers persistence of that snapshot and application of the -selected transition. +A Workflow Run retains its compiled graph at creation. The controller selects a decision from a snapshot of its current +facts. An enrolled engineering action creates a request for the managed executor. After the child commits an admission, +ThreadLoop imports it, reevaluates the graph and checks a fresh apply request. The child and outer stores have separate +commit points. [Managed execution and recovery](workflow-runs.md) ```mermaid flowchart TD @@ -234,10 +231,10 @@ original chain. Both formats read an existing snapshot. SQLite and the lifecycle These specifications are **accepted in Controller Contract v0.1** and live in [threadloop-contracts](https://github.com/nnennandukwe/threadloop-contracts), tagged `v0.1.0`, with their validation -tooling. The runtime now selects and applies transitions. Selected-action dispatch and external controller verification -are tracked in [the runtime milestone](https://github.com/nnennandukwe/threadloop/issues/168). ThreadLoop keeps a -vendored copy of the Governed PR profile, and `tests/unit/lifecycle-contract-drift.test.ts` fails if the runtime -lifecycle and that profile drift apart. +tooling. The runtime selects transitions, guards their application and dispatches enrolled actions. The +[TypeScript baseline](pre-rust-readiness.md) records the external verification and outstanding completion evidence. +ThreadLoop keeps a vendored copy of the Governed PR profile, and `tests/unit/lifecycle-contract-drift.test.ts` fails if +the runtime lifecycle and that profile drift apart. | Contract | Schemas and examples | Supporting evidence | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/docs/evidence/issue-172-controller-conformance.json b/docs/evidence/issue-172-controller-conformance.json new file mode 100644 index 0000000..7fd63e1 --- /dev/null +++ b/docs/evidence/issue-172-controller-conformance.json @@ -0,0 +1,718 @@ +{ + "schema": "threadloop.controller-proof/1", + "implementation": { + "revision": "80e091c9f6412195a8444f048add977d648c4115", + "tree": "987ef4aeda6bb371b0c2f476a3dbeae9467d89ec", + "lock_sha256": "70e168ee4e6df299cd1e1b52e3609699f54eff5e892d6c0afcc1ea498194e7c2" + }, + "upstream": { + "harness": { + "revision": "54be0d2240c44ee11b65d5e278a2cb667ee523b4", + "tree": "8315b088107689880adf2e1733d2641247204cc2", + "lock_sha256": "7f9e013f1a612a08ac1724f04c6646459ec755b17835dfc5a9ee355cddc1d8ec" + }, + "contracts": { + "revision": "4ed9a94a2a089b9ae950d93297f7a6b9b939d3a6", + "tree": "e2dda16bd8dc6cda5c26ab45150ae25bb0023782", + "lock_sha256": "33e158199f5a08e4d6613f4a8b7b68117486933ba64fd3af22d8d67ee36f4c86" + }, + "tag_revision": "7dcf432bc75a68b5ee803c6ebb7346b6bb417f83", + "corpus_source_revision": "fde510deca780c7cada8a2e461bd15af0fe4ae88", + "source": { + "repository": "https://github.com/nnennandukwe/threadloop", + "revision": "fde510deca780c7cada8a2e461bd15af0fe4ae88", + "status": "accepted-in-threadloop-pr-128", + "corpus_digest": "11620588c6f4b39353ea9f77e361a50b5cb0dc970410b1ac10aa8bef13efad84", + "schemas": { + "compatibility.schema.json": "0dd444965f6f437c2738c80e9f1973f4933e396aa9e29e6300ee4cfa2bb71cc3", + "execution-scenario.schema.json": "3d32570877088dc29608cdddb09c6804a23d421ba2ea528a19a62a80f75803d9", + "fixture.schema.json": "7965664420b1fcd8c70fb1b4c13a68bb0be84b349653fd914263e9afde5fc9ae", + "manifest.schema.json": "7bb7fa1348f8a4c3e60814678ca6ef6a9d5ee398d603bc56170ba0137b5f6e30", + "request.schema.json": "d1ab90b30435c184fcda6e3081930d676eea1059bf2af6c1f84e1971ccad77d9", + "response.schema.json": "04392f24e64fd73e599aad39c43747336c3e3b01e9e35d8d970b190d1daab67a", + "shared.schema.json": "5d07767b44ccd66e08fa2ff2a1ca2c5d81fd54319924b4a63884ca056e9f1802", + "source.schema.json": "4fbc818d2920d5fa4e1a24f987b4783206009a94103263151f321702ea1b7fc8" + } + }, + "domain_schemas": { + "workflow-graph": { + "compiled-graph.schema.json": "ef4b407ab91d7f25951a350e07524833ca5bc7bbc2e397da121050073465cd61", + "graph-binding.schema.json": "69de7cbe7d84086a8830cd06fb813ce57a1e8a51d6d8e0dc7ee56a089a37bde3", + "workflow-profile.schema.json": "b5897fbeed24588decb16fbfce48144bee5dca3fab98050bb4d1c1ae0880ee56" + }, + "controller": { + "action-request.schema.json": "aa3823530512ed9e294ed963fa1468d9055f2beedf55a5288e2a9709deb8b744", + "controller-decision.schema.json": "72aabc5a8f5552bf2064d67d0349f8b479c0af992d20f99f2c20b9d1458fb41a", + "controller-input.schema.json": "36ef91f4b37d4dabdd3cef7f6dada18f1494361967971f9076bf179cc2a2c953" + }, + "execution": { + "attempt-receipt.schema.json": "5ad06cb999653d53ffb89322507ed403a2145076d74ae0ea0e6fe6b6a51a58d2", + "attempt.schema.json": "3bf679f0779594fcbaa27a62c871f8e742980cb1ceb0e5370079db82b6eaf6ab", + "execution-claim.schema.json": "1cfc65d6df1abd4bd3c9aff993038c31c0bdf16e23603ed1a7203eb9b47bad7d", + "execution-journal.schema.json": "cf1a4af7e92aa9a713fe5d577870c5d4f11dab4f4ef2c1694fe309ca18ae0692", + "execution-operation.schema.json": "47dd2e3e231f6da50537552afda3e7b31fa91789fedc899ffd3889c6e0b60455", + "execution-policy.schema.json": "8f2436fa8acd528ba99bab767a695e9b9e55fd73785f8368f85006a9dfc4b4a6", + "receipt-admission.schema.json": "e0790c9cc8423c7a6a47f0d28da75e1dc5159d5ec29d8037f325cba72bb9ce27", + "recovery-evidence.schema.json": "3eb4a15b53b65a67f423b7c56d0d5d5c7648b4365db2146865285a537c9d2575" + }, + "executor": { + "executor-request.schema.json": "e4a300796e4d155b361d574b2b915e3869bd95d83beb5adf8fdb3ca5cc567176", + "executor-result.schema.json": "e80862cd118d27eab46a4d75efe96d61be25683d98c81b908e0d288e41a03fb3", + "gaap-mapping-policy.schema.json": "27d96515de315c9935b202ba36a31715fc97a4e1630d3c7f89c7def712fa2e52", + "result-observation.schema.json": "9e31a30801e474dcb1d4986f299a0215f3c5be2f406fd810bdc5dd8e940ccec3" + } + } + }, + "contract": { + "protocol": "threadloop.controller-conformance/0.1", + "fixture_schema": "threadloop.conformance-fixture/0.1", + "canonicalization": "threadloop.conformance-json/0.1", + "digest_profile": "threadloop.conformance-sha256/0.1", + "request_schema": "threadloop.conformance-request/0.1", + "response_schema": "threadloop.conformance-response/0.1", + "manifest_schema": "threadloop.conformance-manifest/0.1", + "compatibility_schema": "threadloop.conformance-compatibility/0.1", + "compatibility_digest": "9590ab51c9081ee2c43f67c0ed1b3453588acdda0e63f259827625971643eadf" + }, + "subject": { + "name": "threadloop-controller", + "revision": "80e091c9f6412195a8444f048add977d648c4115", + "version": "0.1.0", + "artifact_digest": "d416ec2bbf6fec50c1408c11acd96014bf7ac24f92e88416d9af1feb34c9cfaf" + }, + "artifact_manifest": [ + { + "bytes": 7350, + "path": "docs/contracts/executor-v0.1/upstream/gaap/agent-run-request.schema.json", + "sha256": "a0e9af9ffc7c0814e3221d44ad8466071a1f5c443eb5527fac9030de5a246618" + }, + { + "bytes": 16600, + "path": "docs/contracts/executor-v0.1/upstream/gaap/terminal-run-receipt.schema.json", + "sha256": "6e0643f34d6ad767eb925f267cd6b8d5d284cfb8a74124885cbb0a2f05540026" + }, + { + "bytes": 1574589, + "path": "scripts/executor-contract/subject.mjs", + "sha256": "127f412645c0a5ce58d025680fd7a5e731a1ab31a3de25a8eced9cce0d886b76" + } + ], + "controls": { + "case_001": { + "request_digest": "7000a6b6db163a53b79742ec2d3302bc776fafe19611d1230a8a12dca5851865", + "response_digest": "34c24e1a7aa0fb2ab30f065754acef7798cd642ebd10cdd848a327cd2b30f9db", + "stdout_sha256": "1ef536bbcef8bf691284793ba03fc3f2024f86a8221acc066c4ca0207722b254", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc" + }, + "case_024": { + "request_digest": "c1d158a4f2c0299a6d0d9e714cae38aa15c8424a4ace255be92e6466751ba56a", + "response_digest": "55122d136c1655e868999e8505ccc53284b069763d548dd0071169c66402dd2d", + "stdout_sha256": "612fc244c32bf5dc13327227407c3c12b81a376fd49f1fe9ab5d947db7c34fe3", + "outcome": "blocked", + "reason": "AMBIGUOUS_REMEDY" + }, + "relabeled": { + "case_id": "case_999", + "request_digest": "b0f36e830ebe4a2c24905acd45efc2529063b5cd66534c0e24d4c4eb5f66c725", + "response_digest": "2688422642a691997e57463703c7f1729430df8c83e38f7449a263c023e36350", + "same_domain_result": true + }, + "wrong_result": "nonconforming", + "wrong_correlation": "protocol_error", + "file_denials": { + "case": "EPERM", + "shared_values": "EPERM", + "golden": "EPERM", + "synthetic_subject": "EPERM", + "build_inputs": "EPERM", + "parent_identity": "EPERM" + }, + "timeout": { + "status": "transport_error", + "timeout_ms": 1500, + "started_case_directories": 1 + }, + "parent_scratch_removed": true + }, + "runner": { + "exit": 0, + "packet_schema": "run-invariant.threadloop-packet/0.1", + "subject_kind": "controller", + "raw_packet_sha256": "4ef21f2663cf9c43b64d5738a245fd60e198ec8781149c6ecc0471259b790917", + "limits": { + "timeout_ms": 10000, + "stdin_bytes": 16777217, + "stdout_bytes": 16777217, + "stderr_bytes": 1048576 + }, + "report_limits": { + "case_result_bytes": 65536, + "total_result_bytes": 2097152, + "diagnostic_bytes": 4096, + "identity_bytes": 16384, + "command_bytes": 65536 + }, + "process_cleanup": "POSIX-process-group-SIGKILL", + "shell": false, + "claim_boundary": { + "proves": "The declared controller subject matched only the passing frozen cases.", + "does_not_prove": [ + "Authenticated artifact identity", + "Runtime integration", + "Persistence or crash recovery", + "Sandbox isolation", + "Production safety", + "Certification, deployment or adoption" + ] + }, + "platform": "26.6", + "architecture": "arm64", + "node_version": "v26.8.2", + "node_sha256": "3fbe98203f8f4a86ce5b0b573a1a30aa4253064c4c2a0299c436d259b68e54b0", + "launcher_sha256": "9ee6a179d2e5a282a12faf25b84ea0a7fa8525f03e3d0a3729b0e4a241da80a9", + "policy_sha256": "3a30da3571ccf0411c77bd7c01abd42c7f02a5501ca6213b8f07fca8af46b50e", + "build_metafile_sha256": "e5adc1326cfae446a79968a4ba5801469eda50c1aee498d64463457d600767ce" + }, + "conformance": { + "passed": 38, + "nonconforming": 0, + "protocol_error": 0, + "transport_error": 0, + "total": 38, + "failed": 0, + "cases": [ + { + "id": "case_001", + "operation": "compile_graph", + "fixture_digest": "c6608a869775dd6f32f99fe387a29efcf415a9dc71aec15f921ccca722a70b58", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "972653336fc62879ed8d9a97dce96b08a17ff2ee9204a5f0aa062c1317d27a09", + "request_digest": "7000a6b6db163a53b79742ec2d3302bc776fafe19611d1230a8a12dca5851865", + "response_digest": "34c24e1a7aa0fb2ab30f065754acef7798cd642ebd10cdd848a327cd2b30f9db", + "stdout_sha256": "1ef536bbcef8bf691284793ba03fc3f2024f86a8221acc066c4ca0207722b254", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "compiled", + "controller_outcome": null + }, + { + "id": "case_002", + "operation": "compile_graph", + "fixture_digest": "a7890e9e3cf34057e581e8cc37911f08f67a2e2a47d6116db2c636478f6f1b9d", + "graph_digest": null, + "status": "passed", + "input_digest": "02da8764491ebde4d55e12625613feb1b55bf47c7fcba16a891225721b157940", + "request_digest": "965e82bdbf1fd9bd5d51d1a129b6f2793fb8ee9cfe534f91f96524a53782ce05", + "response_digest": "a255ccd723928671ff85a7b9d8323087b3726acb418b5d799dd373d9fc015a68", + "stdout_sha256": "e108fe50122e8729fe551982db27f26f365895980d5a364409b85011f174689c", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "invalid", + "controller_outcome": null + }, + { + "id": "case_003", + "operation": "compile_graph", + "fixture_digest": "8e2ff213aee97691c79056ee6d123c0fa55ebf70a5020b7550d00c6632daf191", + "graph_digest": null, + "status": "passed", + "input_digest": "82f2a2894c00ff8d181368b9937b499df152845df749ab79ddbecd2916cd2fb7", + "request_digest": "4253f902a48346d1ef506310d2d5dc8de3545a8298afa29fc2029b89b85e4ac6", + "response_digest": "ddac9cd0b82a5263db7103e25fc78c6eb0cdefa2f3c13dea96ce8ebed73b958d", + "stdout_sha256": "3e9268d0969680c7aace1d12c7ccf83c80cf3f5ab7caa2b5ac15134c3b934573", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "invalid", + "controller_outcome": null + }, + { + "id": "case_004", + "operation": "decide", + "fixture_digest": "00998d5db8454b5ad1a961689ad292b8c89c95b733a82497b3ba68f554919afb", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "4fc69aeb9217ce579feba1482b2a567b17331ce2485aaa2f9837ca8b800f9a8a", + "request_digest": "897264a8363d5be6346bb9c63a97afb441bb75beb3288b657386069d91dafeff", + "response_digest": "7388883d1b46ea83b76827fd8daf591052bbdd1b4c7c7498ba1ee33731882db3", + "stdout_sha256": "b721891fbadf82c8ea8458c5d6314b43824f8a4fdaa1eb695cb6007522c27e5b", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_005", + "operation": "decide", + "fixture_digest": "a858937bb9d4d2aaa2d52a5f5a421221a6c36a5cf18a1552e8a17d8411d3ea96", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "377bb73f16f25573384ea65ffc8bb0d21b4421c6d696b8bd162014ee9880dc2e", + "request_digest": "9f07c890145be099062c5cd6d3438099a7f5f53a53bc11007d3fa5163d2c7d9c", + "response_digest": "f01ba1e73fb8e418b3ff0d88b04404fb407db9aae714beab51def62e1a8c615b", + "stdout_sha256": "7356a38f28c6e607f0cf0cc5fa62841e459c23ecbd4146b0300c4e0687082c04", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_006", + "operation": "decide", + "fixture_digest": "40ffd6d47691dcfde0bbd148e32c349f705789b23938b550dd52b48db64ab182", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "fd3dad363f866460e24add65448dd83566352d6e60364c97bec47f23bc7aa728", + "request_digest": "d6f9603fbbc3e34b8237ed22476f50869575d0f2d10a61343fc8d761d9f40907", + "response_digest": "2cbb3bb6d119b86425cba923b7d817df731cb7b89d4afeb8c3c48d70b9cb9230", + "stdout_sha256": "8f4119063a4291d5d3260bb4706246fc6ce051dfd81ab930f630f3c7afaf01b5", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_007", + "operation": "decide", + "fixture_digest": "01c0763fc3f4ce5b323415437aa2f4c60ead5b477ca78207ac1e4d8ee92e6c85", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "a1f7d0f07f86cd985797dcf59256b70404fbdc1c4845e1f822acf2c9f3242afd", + "request_digest": "7c454b5dfa7bb8a8c8646b2c7148fe1b8f463a86d7e1c11469b8ddf7f44d12c2", + "response_digest": "59ec640949aa09bcadb735da66421561d5531815f91a58a88963c380961d8f03", + "stdout_sha256": "027bf2a1c5595b2bee9b1d5fa94750d47c4526c79ab0312e6c2c7afd914be4c5", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_008", + "operation": "decide", + "fixture_digest": "c5dab871027c8c7c8ed7611d8b48f7d2dd6844cb73333d0fb7c07d86c73d1b69", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "1bb46a569ca1ae967edebdcf9834303bdd781a502fd74f22677f58262ff28e29", + "request_digest": "8f46983ca1d531d5f9aca9808f225b217815c63eee0cae3e22fa05adabd753a0", + "response_digest": "4eec9e01dafb051686eb4c92389dec28e6461c8c52ac8a24a87482e33f3c018e", + "stdout_sha256": "066eb808c03d73ade57c677c56368667b2458e8fb52b622197b806e8023e74ce", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "transition_available" + }, + { + "id": "case_009", + "operation": "decide", + "fixture_digest": "6a2d3a5b45525f81119426525d26f6456748d7b78efad94414e43d48826074c9", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "dc17d19fd2b7ffca47bcee1402d1adef1206b09b48a4a626d9f8e505c65e597c", + "request_digest": "f5153e500d7af900d908634f1406b7f182a8056d9ab265e26e2964d399e5d733", + "response_digest": "26e8178e5ea48bd614d2fde615ae5be615b15f9700b87751da865a3bf85010ef", + "stdout_sha256": "1dc52ba7ff45c6f9ea977be53c0e24691bab7c618edaf5636d97cc1a2daa78e0", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "human_action_required" + }, + { + "id": "case_010", + "operation": "decide", + "fixture_digest": "1362d53007d03b80c939c30e28d027b6c71fff4b8aa100df6ead3a13416e7e53", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "c1054a22f131a233040a9cfcb35b237030d1bc4cb0f4fba2085826e10c1b09a6", + "request_digest": "5c8924e8654fb037bef82a6ed370e82a5736ee1724b6790d03b56d94369699bc", + "response_digest": "cc299403bff11275843c37127805e617d3ec2ba360ca697dfb4e7260778385b4", + "stdout_sha256": "fef3f84832d1b58c8bef8a6d58c040035e6619869d7e01f7a92494b63fdc1538", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "human_action_required" + }, + { + "id": "case_011", + "operation": "decide", + "fixture_digest": "e79ef14cc4552e7e81a87b8150f1e71d0b1c48e664e2c33f31406b9cb8130445", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "818a1e935ecb1bd973a2b9ff1bbbe0b03405b086cbfa02dc2cc8fec5c1775c07", + "request_digest": "0cc40481052f7156d0889a9effeee934bef56a74226db9496bbca1ae4058d6a1", + "response_digest": "9b413c44225f5ee730f8dae8426e87766093da5f5a4086b3972384dea8d391c5", + "stdout_sha256": "d735814ab0edaae3d1feff971a6e413bfac3a03d1d7e2f122ee7d2f649241f0e", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "transition_available" + }, + { + "id": "case_012", + "operation": "decide", + "fixture_digest": "1ec6b78173fd36a11a5e14b43086c25a13e0be52a3d8c011f3173ee2767ffaba", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "2ce0dd060ab7e789c6c43a515556d32dd3c022e515298ef15541fe8c4688bfdd", + "request_digest": "9ec43551d428ce6de7886119b6cf7ce12ff24725ce68759d308dda9e68f79e46", + "response_digest": "8460ec6dd8ef65697f4c61f05ec82f464bfeb528fdb7e0333f949f867cfbb26d", + "stdout_sha256": "3f727a3e9d44b2ee9f76b11f6e2de11a13654588391896b244e460f86c6dc4ac", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "terminal" + }, + { + "id": "case_013", + "operation": "decide", + "fixture_digest": "5cd480a6662947c6c77c4e09edecc329b39ebbeec4341ced3ae023797259cfd5", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "5248ad02fdf843ccd2cfe89b8a3ba657665af54de55aab2b0efa1ae1708e766a", + "request_digest": "2cf09e51654cef8be69d9260f6096769c515e11f764755b6fbd57c656fb27db4", + "response_digest": "02ab3e90b8c007a3a45f0b94b6cafcb17979b79b985c9bed5ae17dbd7eff256f", + "stdout_sha256": "fc2de40e1927b427061e4f953c3c5a6b5b7e26118e64a6a8ecb6f8a5ba19fc3c", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "blocked" + }, + { + "id": "case_014", + "operation": "decide", + "fixture_digest": "f1563be9d9219e7cd8ffa0f2cd55b3c522aeabfd2419109d32df8eb6eefaefb3", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "3ebd341855e49c77e016b4242145f879f53662d3e4155307f7ddff3e280b56c3", + "request_digest": "138467745c0048872fe3f7d56d7cb9d4b9093413dfbff47b1b4a1e6a65512f01", + "response_digest": "144e03b9da234696dc6c792ef9bf3e89e7f400d19f87a84e00cd66e88508dc47", + "stdout_sha256": "d998fa7df2c24f32cd65d4c71f7ada1b494feb831029c677b1d06b66e6fdc179", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "blocked" + }, + { + "id": "case_015", + "operation": "decide", + "fixture_digest": "8ffbed4e5de5c50a00f8f9677dd79e1ff88666cb58b3d7bc12852d806b22fbdb", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "8ac09d295ee0a6fb3270d8904b664c10d93994ff14343d744da11cf967c52638", + "request_digest": "aa2b454ca7d43beccc0210b7f48e1b3284575f17e62c1f72db335bd9587c9313", + "response_digest": "18a11c48243fd8dcbbba1c3b3e545fe87a073e5c3d7edbb5838bf81e195a5443", + "stdout_sha256": "b0293e23eb1db3d337404c118112ebe002f65dfbf86b45a7f94698de0f630989", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "waiting" + }, + { + "id": "case_016", + "operation": "decide", + "fixture_digest": "d002ed8260d9a138f082a9f7dc7b7929bf9ea90ea2dd12b80b3cd0ee3d224f41", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "eaa3055cfd5ef19f60c65c9a59c514f86a1968a63aa68d557ea498a84e6b7b7e", + "request_digest": "fb83856c7e63b48c8ba05a22ff8c29af5938049ae1962544fad63c2e40c79ebb", + "response_digest": "d4916f35050435e9ede2eff0caad9a0f2115861f0986c90d8940dbc302ef80cf", + "stdout_sha256": "9ff9528ab892753baa041877b9e236944890b6646c564cafdde467e32f319098", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "blocked" + }, + { + "id": "case_017", + "operation": "decide", + "fixture_digest": "90fd7119e8b9b8800e2963ca231f43cb290fa89a2bf2233a7ae67b7fa4ea5c0a", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "2b818114b8c3792a1fc872f0a50a4c891e250d240b683e9a60eb79fa75d016aa", + "request_digest": "1869bf84e91c208db7d04f04f1994a4b7f659e955b26c3f9d29fb440f3eba2d6", + "response_digest": "878d02e01936f7fcbafb78d8afcce0490b128121aab09b3263b244354223f270", + "stdout_sha256": "e9e308f7dc459a8efe92c43ecff89b467bcaff1d7a4a6d29bf43dc93f3646625", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "blocked" + }, + { + "id": "case_018", + "operation": "decide", + "fixture_digest": "4fd485c6ce2c738beb2baf6be9f8094cb59b95e52fe283432dcc704d3fd0ff03", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "42e8b4aabb04af175d6844d538b2c89fb660b2e88b7318aa67da577e9bd57cd8", + "request_digest": "6b8e7453bb8efd17709acdd303708c0c8e6735788c962a62d4600333e1a1ef88", + "response_digest": "fd4f907c9902f01e4b77fa71d5e771abb83e975c34e38d17726156f9ad53b77a", + "stdout_sha256": "81ef796ce9293f8945fc690d5bfb648a11517c39a26034eed2e45b141779b441", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "human_action_required" + }, + { + "id": "case_019", + "operation": "decide", + "fixture_digest": "b933dcefab8924f239b9970ca775bdf4b4af8c9e2873ff5b4dd144217112ce3a", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "ab5483361f102a88496335518e1a69fb2d63c63882120ec3dda5e4d6a6f4f0a1", + "request_digest": "614de5d5100d781a2ef8bcb35fa8180b665b3d7ff4c4aa4c707dc5d8e1a0bb91", + "response_digest": "10364a9a6174a065c1b3ece1304571b3ab6c492f2c2fba5b48587427aeb5730d", + "stdout_sha256": "f4ed0279064fa3e5759cd0d06619b38ae92d81393726b0896c7d8f899ddf8a7f", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "human_action_required" + }, + { + "id": "case_020", + "operation": "decide", + "fixture_digest": "4fbd9eed9c20ee5cc2ff20ba4d74164f7898698964521956ed958cd7a180e024", + "graph_digest": "17065977d0b16f024cc3c48387d4156cedcc6b2f36b681bee3e002fe09713dee", + "status": "passed", + "input_digest": "c5d7ebd2c7a8c99ac0a29e21a0f32f20fff7fef606b8c9ca757bacb07fdda6e9", + "request_digest": "5963a020df760e3108380cd6d20e8326abff95d73a103c81dece342f0a48bf49", + "response_digest": "4c710d57779ac49c46ff9947304247644002a0015884eab5b7bc1c8dbf1faec4", + "stdout_sha256": "5fd39a30fbf0fe4793020b7efc5d4a7d1e33c30f7e2181c0ad578570b27a6d40", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "human_action_required" + }, + { + "id": "case_021", + "operation": "decide", + "fixture_digest": "8ac335cbaf8ae4bf18e9bc762deeef1cb2c6f51e96a694cc87089d9dcb3e1c36", + "graph_digest": "17065977d0b16f024cc3c48387d4156cedcc6b2f36b681bee3e002fe09713dee", + "status": "passed", + "input_digest": "2c55df3ffad427a48e202b842715db54df08c8173ac944209035253d2cfd6974", + "request_digest": "888fa632044121f1d286551922bf6d259d8f8ba8206fd0d6347ff200f117275b", + "response_digest": "11f8160ae16ba2acf835474bf4cf8f89863332c74e62a34e5c125b38bf788286", + "stdout_sha256": "7e47981aafce1e9ed2ee746be85c7e5c8e1574f671341ec4774adbc27478fab1", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_022", + "operation": "decide", + "fixture_digest": "f960f59dea819f02f45ac0248e35d75f03ee68f36bcadde2c90da80579e227bc", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "b4572d424ec68cd132a1df3b6068ec1b96781d8e17c43cb83eb7f63475b2a606", + "request_digest": "4067b5b73b908840c87cb86a40554d07f51f8ecdeaae33ad9fb1b82202115885", + "response_digest": "c5f7e5226f2e7f3c3c4d0f4337e96238e10cec870e0986ca999af79ee9e260c7", + "stdout_sha256": "231d62d8e0c2c5a5548741522c252a75ef76d3db8a4101f227d242599621ca48", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_023", + "operation": "decide", + "fixture_digest": "ab7362a1f0fe06f56f0c60718c7c5aa73a4fdeb91459b1078b887552734b923f", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "365e6bbbf0aa447c2b6ebdb1d19062263d7635f022c500fe18faaea6c380cc35", + "request_digest": "5e1f192a0430e9580c989b73b1fdd928e7f460e1176e40bf6af68f098446f414", + "response_digest": "70d8feb328881ffa0ee0dc208d5a252939d7cf8aa0fd607c751ee1f0c2ea843a", + "stdout_sha256": "9be8a183752a706b02d3f5b8b4a80ba8f6fce4cd854660029ad077f4295190be", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_024", + "operation": "decide", + "fixture_digest": "ba2b8efc62b30ecb521c995fe3ee0f7f1119c2d3dd7c94aed60ea4351b9ed509", + "graph_digest": "0e98cc6221b5573d603cdde5bb2804ed15148ba8ad5d30e14e72511d931b45db", + "status": "passed", + "input_digest": "aa8b8253c6e57c596cd3f26ac5525899e8b3f098bcc2f03a27c80ae0379be87f", + "request_digest": "c1d158a4f2c0299a6d0d9e714cae38aa15c8424a4ace255be92e6466751ba56a", + "response_digest": "55122d136c1655e868999e8505ccc53284b069763d548dd0071169c66402dd2d", + "stdout_sha256": "612fc244c32bf5dc13327227407c3c12b81a376fd49f1fe9ab5d947db7c34fe3", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "blocked" + }, + { + "id": "case_025", + "operation": "decide", + "fixture_digest": "55d536a986bfbc4f41c2bafd22a229d5d296f956e25029a26ceef8df1691a233", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "1f5d343fea49a7703f7eed579c79e706b4d369c2a7d53b223f872d4f1448c8c0", + "request_digest": "618085dd5d6765e36d044d3f16af09421ea387382e52565b27598f40b240a870", + "response_digest": "5972e26cfecec243fe75e2ecc18852d7b85622d6b045aa6654e924952c43bdd8", + "stdout_sha256": "dff6eaef9a20fc8bdb4a331962d2c678b32e4fbef848f25407d1b1c230238614", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_026", + "operation": "decide", + "fixture_digest": "d921a6a79609c68c57118d3db622aab8085c42b076404a16402650dbebe85ee9", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "c03df0a67c2b56be784825a7475a935516d5cc159f5bc22952eb23fcfd35ad40", + "request_digest": "737ca08772e809bc2f92902b0d237049dbf15b5bf22354f7de2896e82ba37f5c", + "response_digest": "350824e474e046e2b7fbfe960cd6d0a3821bb7d411e9e8a41d25603fab373f53", + "stdout_sha256": "39a74a2378f607ab4bb38cdd98a379443a2e4c7038ba879451d9825b098898d4", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_027", + "operation": "decide", + "fixture_digest": "37d2225ce49567b4e5e1f34d97cdc4a5c068ad8e34582a02d0c5ca0f449e8eaa", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "b3a27114e40213bef35ad1fd56294a146de950d5817b8c59106a3d8fe8b15d12", + "request_digest": "eee03957a791423e6199e04b048de3d775a03aec651c74712c814ef1d2983044", + "response_digest": "f092ebeca8530de00f87a56830684e79a98716d3b8aa1563781988287fe8a249", + "stdout_sha256": "8f54e1c41f196c993892f0a3eb5275ec285e571d6ad9c2c3920777fe5e8206af", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_028", + "operation": "execution_scenario", + "fixture_digest": "c755278847864eee235592f177904d8342dab31c02fb358a5d6cc66ca0f90583", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "3990c2edb6410696ff93f9bf44a3a9da27c51cb1e91a2c94a53a1fdbfc7a09f5", + "request_digest": "04ec81151a8bdb77de2f825df57c6ed5b24008249a0834921e4b6d8edc876a62", + "response_digest": "8ac13da3e7ff371ceb6486a549d789ecf5518de52bdef103dfc593b3a694b20a", + "stdout_sha256": "72d3040caca24d80b8603088a8ac0a8e33d956b16ace913cc7f6672b54ffe9da", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_029", + "operation": "execution_scenario", + "fixture_digest": "d0aac580a617b44f9b12fe8913a198f2012c9a683488bf3a00368a80988acbf1", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "179d5351cc698d53ab3b2e322239ec574ac8f26a8ce1c1f30c82843a89cccaee", + "request_digest": "582b3266691519d754fc543db57809b3f5a5cdc7e0aeb29fdcb1447569376722", + "response_digest": "8e8468a47749333b13c15af7a3e0a311bbb940e3de95f9cec36ad8871cd1fe48", + "stdout_sha256": "854c9da7b4bdb712be4172f35286d4bb4635b245d33712badbb7c9269e244519", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_030", + "operation": "execution_scenario", + "fixture_digest": "89094e226e3a2f923219d15a441ab622c8a197856c7bd1188f7a29e48243d7be", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "a606173f56d1904c423262b75d45822f1d307025e301c981a439a3b6e58bef58", + "request_digest": "eba6fcf0219a58b78548345ff03a7ee38260670b877c6f705e91bac3a82ae175", + "response_digest": "d58b4161e30458675f817227fb308a576c270316fcfedb195ab15e462679d918", + "stdout_sha256": "3d36ef77d07347173b7152df8dc9945919bd9b78fc6a288b67ce54fdc75bb88e", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_031", + "operation": "execution_scenario", + "fixture_digest": "041bbee057417b18227d4e2de735ecb85cb2c0348aa97d036ffe8b218b74d8a8", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "5d92521e67019af62bd5d9fee75e1d893f459ff6c41bd83d5aa7d8eb9b5013d4", + "request_digest": "ca0427876befb680bd42006f7bd1a2392e3443ebdae4ce6bd1cfb1b3fdad4589", + "response_digest": "bba441014fb24a7ba8e630fdf82172c1f0f4d2afcd8bd541e92a95de40d4f6aa", + "stdout_sha256": "8be1fd0995c2967b2b3830456bc55e060a0a999cca235de0c7ce59ccc89f3410", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_032", + "operation": "execution_scenario", + "fixture_digest": "3ecb25d10a8e50f1ce7cb1493f7f8bc1e5f71a72543b0912f92275d7775ea94c", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "23f923ea3dd7040ef44192f60eaacfc92438c8adaf38b1ad32d9d6dd9c3b0503", + "request_digest": "b5a50abdf1ec74cafd22977fd15f5e6fe33c22216ab1e24be8e26b924f01d187", + "response_digest": "90a83147f21bd73dec36dedd047e33eb6067fdf047abe2d53caca236db620510", + "stdout_sha256": "6fe4856586beb3c61696842bf68b0c3150819eeba74df683823ba882dea0905a", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_033", + "operation": "execution_scenario", + "fixture_digest": "696346c478b1a9ffb8407dba2650a54318b30484bbd65886aa310ee9764f3c60", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "7f3a6e85ec1eb3a6427009b32f086c33137c451b669d4094d533d7e7ef0a5ad1", + "request_digest": "cc492c785323c2d241a9ab45e18d754c29cd088861bf3ffd3d506f0d06a18c4a", + "response_digest": "5fa18ce4cc35bbf5d82590d712d77aadaa8471eb033be7f9cff6cd9e738b97a7", + "stdout_sha256": "b636a0089082e6268d9411e0be738c7804b9adca3f81f99039cff5393292e3c8", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_034", + "operation": "execution_scenario", + "fixture_digest": "6990d436e906b7dd874cb7dd6dfa40f7b704dd077d62766e4901eab6d13eb9b0", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "0973db062cbcdffa8b1b65f8c03bb9fdbcc13baf97d548156756131666c9ae74", + "request_digest": "383bcf09828dda676442d535b27648230fa076bdabdb7eb4e62948a0eefa731c", + "response_digest": "36052b407e60fb9bd7c1a02c4a7469465f5b6b109cb42de96af33ef95c42a325", + "stdout_sha256": "78e8e2cfc43f8ddb44fdf3e4e07a348816fc4dbeb188626dfa138aa0d3b8728a", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_035", + "operation": "execution_scenario", + "fixture_digest": "c3c6c1af30038d371c55e0459d5ea138827a5e80ca3d4c9e719d4139e4223c4e", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "87dd301051c315223a5530ff34e86824ee919665109ee712b460a89a1bcf9986", + "request_digest": "e41d1a40d27b3fb255163cbaace21a1fafa0958834df01de0e3c5f8933abb07f", + "response_digest": "64faefd11c054458f62dc3ece2c7615bc7d5f7fcecd3b44e064ccd237ee298a4", + "stdout_sha256": "527405d364ea5f8b04448991cef95c7adf95c978c38c4df089295881e0155f0c", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_036", + "operation": "decide", + "fixture_digest": "6a2cfdf998368cd892e46647189404e2aeae5f833391e7f996e8a63b884f0318", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "a8ea7aa8630e97ea6543aef4dce4e3a03ee64e52acb1626b05ee553d9253bb5a", + "request_digest": "87754121a9ac9b9cecd465604768703ed9ed66f9a9aa2134cc33e88853454697", + "response_digest": "230a96f3941459062ad60f8ea233002b21699c1ada7155e4bd8ec2c2f800d81d", + "stdout_sha256": "a25a47dc184319654850c2197eb887883c5476b5fc10e6528651323b06b83027", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "decision", + "controller_outcome": "engineering_action_required" + }, + { + "id": "case_037", + "operation": "execution_scenario", + "fixture_digest": "d611f08feb74485285457194d080c52d7be5678c5e33bd99cc1f8aaa008f1f46", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "5e19ed1338af86c4be657d0863f49aabcf47653c817d5bf1d9fc29d6b30f42d8", + "request_digest": "b3511f470f7d940f9645ea9c75cffb1dcd8f1083738dc37d643d4c16defe68bd", + "response_digest": "5a2a1fc7786fc4a03fd4013cdc863f0a018e3effcbca565203d500745dcb7ea3", + "stdout_sha256": "b4e4fcd68e8c3c82635c04539637ca7cc53b7b30fbc192bf24aad5dc0ee86829", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + }, + { + "id": "case_038", + "operation": "execution_scenario", + "fixture_digest": "6fd1e621e8ca0d0ce7328ba655055b8df4585782807c9c61ae00b34042d221bc", + "graph_digest": "7df5f3b655e61bc872f83de08c6ce7b0c0c714de15256ada7b13127264bcd2dc", + "status": "passed", + "input_digest": "b9b9e03c1894936cf9d5ccc02648300833aa2fbb3bc4bd94cba443dfac5d54ae", + "request_digest": "2390f2f0e8c823429d94069e43c751117123de2faba45c7b9f56f392e7b064fe", + "response_digest": "2d343c22f0305d4375c5df8ee14f7a91ca1bd76ba8bf79d2b8526a997a9ec320", + "stdout_sha256": "0ab378e95b6fff1cf6122b1717f9d6c7ec7f66777a8a4aec91946573080e96c7", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "result_status": "execution", + "controller_outcome": null + } + ] + } +} diff --git a/docs/evidence/issue-172-installed-cli.json b/docs/evidence/issue-172-installed-cli.json new file mode 100644 index 0000000..900feea --- /dev/null +++ b/docs/evidence/issue-172-installed-cli.json @@ -0,0 +1,651 @@ +{ + "source": { + "revision": "80e091c9f6412195a8444f048add977d648c4115", + "tree": "987ef4aeda6bb371b0c2f476a3dbeae9467d89ec", + "lock_blob": "b35af44702d348558f848767c6eae50a40b7ca18", + "node": "v26.8.2", + "npm": "11.19.1", + "tarball": "threadloop-0.1.0.tgz", + "sha256": "36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51", + "cli_sha256": "610e586afd19fd85e0b2adade639b88a98213a039cb980772f72a65ded4cdc22", + "integrity": "sha512-thLVEkgwnuv9EMxiNyy9Ddm2Z+mGuirfETwpkGV/7kXXomgZQ134Mq5IuJnwNyNNPyB3TtqwsgfHqAljpMLAxA==", + "bundled_dependencies": 55 + }, + "packages": { + "candidate": { + "revision": "80e091c9f6412195a8444f048add977d648c4115", + "tree": "987ef4aeda6bb371b0c2f476a3dbeae9467d89ec", + "lock_blob": "b35af44702d348558f848767c6eae50a40b7ca18", + "node": "v26.8.2", + "npm": "11.19.1", + "tarball": "threadloop-0.1.0.tgz", + "sha256": "36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51", + "cli_sha256": "610e586afd19fd85e0b2adade639b88a98213a039cb980772f72a65ded4cdc22", + "integrity": "sha512-thLVEkgwnuv9EMxiNyy9Ddm2Z+mGuirfETwpkGV/7kXXomgZQ134Mq5IuJnwNyNNPyB3TtqwsgfHqAljpMLAxA==", + "bundled_dependencies": 55 + }, + "rollback": { + "revision": "31388a07566350dfeddc30578d43b8926d5b4e22", + "tree": "17124dd8949059d40c25807e297659817f2c5b11", + "lock_blob": "b35af44702d348558f848767c6eae50a40b7ca18", + "node": "v26.8.2", + "npm": "11.19.1", + "sha256": "c8c96f8229ee141bfe31b1509440e548aa2fb64b089bd6f44b41016e7e0fe078", + "cli_sha256": "0859b3f5c9a0cac969bbe0c744ade31080d81910d53ae04970ea654d3ce94571", + "integrity": "sha512-lpV4S8nRXKjCYr5Qarg7x95EY1bBDXsVmC5NrTyvYxFM1iLjY2MiNU9zWOWejexEAJo3HXjJkDa8x/ueNmLpqg==", + "tarball": "threadloop-0.1.0.tgz", + "bundled_dependencies": 55 + }, + "pre_adoption": { + "revision": "7c54c2bb8055f00736e3b5f6631e9aecbe0fd212", + "tree": "41cc922588c519f3cd2ad24d4487c4af37f4ccb0", + "lock_blob": "b35af44702d348558f848767c6eae50a40b7ca18", + "node": "v26.8.2", + "npm": "11.19.1", + "sha256": "4370cea4a5d7be5e283fcafc09fdce07e37168929db8a1e21448614e79f51bc1", + "cli_sha256": "4310265f970cf273ebbb29cf2e28f5882c0cbeeab88c64b044a26fca3aa700c5", + "integrity": "sha512-aJV8OK9jgZBo8Og/lMkc2opnMG30fh5TuBK92kj4mTw8FP38Gpdj8r0vZ+Ah85romgz1TPWGZbIw9nx/jgXrSA==", + "tarball": "threadloop-0.1.0.tgz", + "bundled_dependencies": 55 + } + }, + "versions": { + "candidate": "0.1.0", + "rollback": "0.1.0" + }, + "declared_errors": { + "750ae36b6b7b6ea34081a8c90236d8c95f71b086": [ + "SESSION_NOT_FOUND", + "SESSION_REQUIRED", + "SESSION_AMBIGUOUS", + "THREADLOOP_NOT_INITIALIZED", + "INVALID_ARGUMENT", + "BASE_REF_NOT_FOUND", + "NOT_GIT_REPOSITORY", + "STATE_CORRUPTED", + "RECONCILE_TARGET_REQUIRED" + ], + "80e091c9f6412195a8444f048add977d648c4115": [ + "SESSION_NOT_FOUND", + "WORKFLOW_RUN_NOT_FOUND", + "WORKFLOW_RUNTIME_UNSUPPORTED", + "SESSION_REQUIRED", + "SESSION_AMBIGUOUS", + "THREADLOOP_NOT_INITIALIZED", + "INVALID_ARGUMENT", + "BASE_REF_NOT_FOUND", + "NOT_GIT_REPOSITORY", + "STATE_CORRUPTED", + "SESSION_SCHEMA_MIGRATION_REQUIRED", + "STATE_VERSION_CONFLICT", + "IDEMPOTENCY_CONFLICT", + "TRANSITION_NOT_ALLOWED", + "TRANSITION_GUARD_FAILED", + "STATE_BUSY", + "EXECUTOR_REJECTED", + "REPOSITORY_OBSERVATION_FAILED", + "RECONCILE_TARGET_REQUIRED", + "PROOF_PLAN_MISSING", + "PROOF_PLAN_CORRUPTED", + "GATE_NOT_DECLARED", + "GATE_NOT_RUNNABLE", + "GATE_PREFLIGHT_DIRTY", + "RECEIPT_NOT_RECORDED", + "SIGNED_RECEIPT_INVALID", + "SIGNED_RECEIPT_SIGNATURE_INVALID", + "SIGNED_RECEIPT_TRANSPARENCY_MISSING", + "SIGNED_RECEIPT_IDENTITY_MISMATCH", + "SIGNED_RECEIPT_ARTIFACT_MISMATCH", + "SIGNED_RECEIPT_HEAD_MISMATCH", + "SIGNED_RECEIPT_RESULT_REJECTED", + "SIGNED_RECEIPT_SETUP_FAILED", + "SIGNED_RECEIPT_CONFLICT", + "SIGNED_RECEIPT_VERIFICATION_UNAVAILABLE", + "AUDIT_UNAVAILABLE", + "AUDIT_EMPTY", + "AUDIT_VERIFICATION_FAILED", + "AUDIT_EXPORT_CONFLICT", + "AUDIT_EXPORT_FAILED", + "AUDIT_CORPUS_INVALID" + ] + }, + "failure_envelopes": [ + { + "operation": ["start"], + "code": "INVALID_ARGUMENT", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["capture"], + "code": "INVALID_ARGUMENT", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["status"], + "code": "INVALID_ARGUMENT", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["finish"], + "code": "INVALID_ARGUMENT", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "finish"], + "code": "INVALID_ARGUMENT", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["daemon", "run"], + "code": "INVALID_ARGUMENT", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "list"], + "code": "NOT_GIT_REPOSITORY", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "list"], + "code": "THREADLOOP_NOT_INITIALIZED", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "status"], + "code": "SESSION_REQUIRED", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "status"], + "code": "SESSION_NOT_FOUND", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "start"], + "code": "BASE_REF_NOT_FOUND", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "reconcile"], + "code": "RECONCILE_TARGET_REQUIRED", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["artifact", "generate"], + "code": "SESSION_AMBIGUOUS", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["workflow", "create"], + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["workflow", "inspect"], + "code": "WORKFLOW_RUN_NOT_FOUND", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["workflow", "inspect"], + "code": "WORKFLOW_RUN_NOT_FOUND", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "list"], + "code": "STATE_CORRUPTED", + "exit": 1, + "stream": "stderr" + }, + { + "operation": ["session", "list"], + "code": "STATE_CORRUPTED", + "exit": 1, + "stream": "stderr" + } + ], + "protocol": { + "default_version": 4, + "4": { + "json_sha256": "e5943879bfaf27696f0c791adca0d5510e6e49d5660edfa9beb75931c846ed90", + "text_sha256": "5ac51f9c27359b9f27e717adec58d4b85c3e78e4b721957ed534f2d9a7e40fcf", + "commands": { + "init": "threadloop init - Initialize ThreadLoop in the current Git repo", + "artifact generate": "threadloop artifact generate [kind] [--session ] [--json] - Generate a Markdown artifact from task, notes, and Git context", + "session start": "threadloop session start [--goal <goal>] [--constraint <constraint...>] [--base <ref>] [--issue <ref>] [--actor <actor>] [--goal-edit] [--run-config <file>] [--json] - Start a task-scoped session", + "session list": "threadloop session list [--json] - List sessions in the current workspace", + "session status": "threadloop session status --session <id> [--json] - Show status for an explicit session", + "session capture": "threadloop session capture <kind> [text] --session <id> [--because <reason>] [--actor <actor>] [--edit] [--json] - Capture a structured checkpoint entry for an explicit session", + "session heartbeat": "threadloop session heartbeat --session <id> [--source <source>] [--json] - Refresh mechanical session metadata without creating a semantic entry", + "session transition": "threadloop session transition <target-state> --session <id> --expected-state-version <version> --idempotency-key <key> --actor <actor> --input <json-object> [--json] - Apply an idempotent, guarded lifecycle transition", + "session next": "threadloop session next --session <id> [--json] - Inspect the deterministic next lifecycle candidate without mutating state", + "session gate run": "threadloop session gate run <gate-id> --session <id> [--json] - Run one declared local gate and append an immutable receipt", + "session gate import": "threadloop session gate import <package-path> --session <id> [--json] - Verify and append one signed GitHub Actions gate receipt", + "session review import": "threadloop session review import <package-path> --session <id> [--json] - Verify and append one signed GitHub review snapshot", + "session reconcile": "threadloop session reconcile (--session <id> | --all) [--json] - Refresh Git-derived metadata for a session without creating semantic entries", + "executor register": "threadloop executor register --state <directory> --binding <file> --config <file> [--json] - Adopt a fresh host-controlled action and signer policy", + "executor run": "threadloop executor run --state <directory> [--json] - Launch the registered Attempt once and admit verified evidence", + "executor inspect": "threadloop executor inspect --state <directory> [--json] - Independently verify retained executor state without launching", + "executor admit": "threadloop executor admit <observation-id> --state <directory> [--json] - Recheck retained output after an admission failure without launching", + "executor evaluate": "threadloop executor evaluate --state <directory> [--json] - Re-evaluate lifecycle guards after evidence admission", + "audit show": "threadloop audit show --session <id> [--json] - Show hash-linked audit events for a session", + "audit verify": "threadloop audit verify --session <id> [--root <sha256>] [--json] - Verify a session audit chain and optional retained root", + "audit export": "threadloop audit export --session <id> --output <path> [--json] - Verify and atomically create a JSONL audit export", + "audit corpus": "threadloop audit corpus (--session <ids...> | --all) --output <path> [--format <format>] [--json] - Export a verified corpus with one outcome per session", + "audit verify-export": "threadloop audit verify-export --input <path> [--root <sha256>] [--json] - Verify retained corpus bytes without a repository or database", + "protocol": "threadloop protocol [--json] - Print the agent integration protocol" + }, + "contractVersions": { + "protocol": 4, + "proofPlan": 4, + "sessionNext": 4, + "signedReviewReceipt": 1, + "auditEvent": 1, + "handoff": 3 + }, + "capabilities": [] + }, + "5": { + "json_sha256": "1ad7fcc02c57024a9263560d591650d178cad2ade2aa712a789de97ff2c181ce", + "text_sha256": "ed62d07a04364d61ed5356d285c79e15abeaa81b5d27e191024754c0a4fdadaa", + "commands": { + "init": "threadloop init - Initialize ThreadLoop in the current Git repo", + "artifact generate": "threadloop artifact generate [kind] [--session <id>] [--json] - Generate a Markdown artifact from task, notes, and Git context", + "session start": "threadloop session start <title> [--goal <goal>] [--constraint <constraint...>] [--base <ref>] [--issue <ref>] [--actor <actor>] [--goal-edit] [--run-config <file>] [--json] - Start a task-scoped session", + "session list": "threadloop session list [--json] - List sessions in the current workspace", + "session status": "threadloop session status --session <id> [--json] - Show status for an explicit session", + "session capture": "threadloop session capture <kind> [text] --session <id> [--because <reason>] [--actor <actor>] [--edit] [--json] - Capture a structured checkpoint entry for an explicit session", + "session heartbeat": "threadloop session heartbeat --session <id> [--source <source>] [--json] - Refresh mechanical session metadata without creating a semantic entry", + "session transition": "threadloop session transition <target-state> --session <id> --expected-state-version <version> --idempotency-key <key> --actor <actor> --input <json-object> [--json] - Apply an idempotent, guarded lifecycle transition", + "session next": "threadloop session next --session <id> [--json] - Inspect the deterministic next lifecycle candidate without mutating state", + "session gate run": "threadloop session gate run <gate-id> --session <id> [--json] - Run one declared local gate and append an immutable receipt", + "session gate import": "threadloop session gate import <package-path> --session <id> [--json] - Verify and append one signed GitHub Actions gate receipt", + "session review import": "threadloop session review import <package-path> --session <id> [--json] - Verify and append one signed GitHub review snapshot", + "session reconcile": "threadloop session reconcile (--session <id> | --all) [--json] - Refresh Git-derived metadata for a session without creating semantic entries", + "executor register": "threadloop executor register --state <directory> --binding <file> --config <file> [--json] - Adopt a fresh host-controlled action and signer policy", + "executor run": "threadloop executor run --state <directory> [--json] - Launch the registered Attempt once and admit verified evidence", + "executor inspect": "threadloop executor inspect --state <directory> [--json] - Independently verify retained executor state without launching", + "executor admit": "threadloop executor admit <observation-id> --state <directory> [--json] - Recheck retained output after an admission failure without launching", + "executor evaluate": "threadloop executor evaluate --state <directory> [--json] - Re-evaluate lifecycle guards after evidence admission", + "audit show": "threadloop audit show --session <id> [--json] - Show hash-linked audit events for a session", + "audit verify": "threadloop audit verify --session <id> [--root <sha256>] [--json] - Verify a session audit chain and optional retained root", + "audit export": "threadloop audit export --session <id> --output <path> [--json] - Verify and atomically create a JSONL audit export", + "audit corpus": "threadloop audit corpus (--session <ids...> | --all) --output <path> [--format <format>] [--json] - Export a verified corpus with one outcome per session", + "audit verify-export": "threadloop audit verify-export --input <path> [--root <sha256>] [--json] - Verify retained corpus bytes without a repository or database", + "workflow create": "threadloop workflow create <run-id> --profile <yaml> --setup <json> [--json] - Create a run bound to one compiled graph and setup", + "workflow inspect": "threadloop workflow inspect <run-id> [--json] - Read the verified graph binding and current state", + "workflow decide": "threadloop workflow decide <run-id> [--json] - Select the next outcome from verified run facts", + "workflow apply": "threadloop workflow apply <run-id> --decision <file> --idempotency-key <key> [--json] - Apply a fresh selected transition once", + "workflow execute": "threadloop workflow execute <run-id> --decision <file> [--json] - Execute a selected engineering action through the enrolled GAAP bridge", + "workflow expire-claim": "threadloop workflow expire-claim <run> --attempt <id> --expected-state-version <n> [--json] - Record an overdue claim for its enrolled Attempt", + "workflow evidence collect": "threadloop workflow evidence collect <kind> --run <run-id> [--gate <id>] [--operation <id>] --expected-state-version <n> --idempotency-key <key> [--json] - Collect local gate or pre-PR review evidence from the enrolled producer", + "workflow evidence prepare": "threadloop workflow evidence prepare <kind> --run <run-id> [--gate <id>] [--pr <n>] [--instruction <file>] --expected-state-version <n> --idempotency-key <key> [--json] - Bind a sensor observation to the current run", + "workflow evidence import": "threadloop workflow evidence import <kind> --run <run-id> --source <file> --expected-state-version <n> [--json] - Verify and retain a prepared sensor package", + "protocol": "threadloop protocol [--contract <version>] [--json] - Print the agent integration protocol" + }, + "contractVersions": { + "protocol": 5, + "proofPlan": 4, + "sessionNext": 4, + "signedReviewReceipt": 1, + "auditEvent": 1, + "handoff": 3, + "workflowRun": 1 + }, + "capabilities": ["workflow_runs_v1", "workflow_gaap_execution_v1", "workflow_claim_expiry_v1"] + } + }, + "help": { + "threadloop": "Usage: threadloop [options] [command]\n\nTask-first, repo-local session memory that generates review-ready artifacts\n\nOptions:\n -V, --version output the version number\n -h, --help display help for command\n\nCommands:\n init Initialize ThreadLoop in the current Git repo\n artifact Generate artifacts from session context\n session Manage explicit ThreadLoop sessions\n executor Run the frozen GAAP reference process bridge\n audit Inspect and export the authoritative audit ledger\n workflow Manage graph-bound Workflow Runs\n protocol [options] Print the agent integration protocol\n help [command] display help for command\n", + "init": "Usage: threadloop init [options]\n\nInitialize ThreadLoop in the current Git repo\n\nOptions:\n -h, --help display help for command\n", + "artifact generate": "Usage: threadloop artifact generate [options] [kind]\n\nGenerate a Markdown artifact from task, notes, and Git context\n\nArguments:\n kind artifact kind (default: \"change-brief\")\n\nOptions:\n --session <id> session id to target\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session start": "Usage: threadloop session start [options] <title>\n\nStart a task-scoped session\n\nArguments:\n title task title\n\nOptions:\n --goal <goal> goal for the task\n --constraint <constraint...> constraints that matter for this task\n --base <ref> base Git ref used for comparisons; defaults to\n main when available\n --issue <ref> issue reference for branch and PR traceability\n --actor <actor> entry actor for the initial intent record\n (default: \"cli\")\n --goal-edit open $EDITOR for the goal text\n --run-config <file> caller configuration and snapshot file paths for\n immutable audit attribution\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session list": "Usage: threadloop session list [options]\n\nList sessions in the current workspace\n\nOptions:\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session status": "Usage: threadloop session status [options]\n\nShow status for an explicit session\n\nOptions:\n --session <id> session id to target\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session capture": "Usage: threadloop session capture [options] <kind> [text]\n\nCapture a structured checkpoint entry for an explicit session\n\nArguments:\n kind entry kind\n text entry text\n\nOptions:\n --session <id> session id to target\n --because <reason> optional reasoning or context\n --actor <actor> entry actor for the captured note (default: \"cli\")\n --edit open $EDITOR for longer text\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session heartbeat": "Usage: threadloop session heartbeat [options]\n\nRefresh mechanical session metadata without creating a semantic entry\n\nOptions:\n --session <id> session id to target\n --source <source> heartbeat source\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session transition": "Usage: threadloop session transition [options] <target-state>\n\nApply an idempotent, guarded lifecycle transition\n\nArguments:\n target-state target lifecycle state\n\nOptions:\n --session <id> session id to target\n --expected-state-version <version> optimistic lifecycle state version\n --idempotency-key <key> idempotency key for this canonical request\n --actor <actor> transition actor\n --input <json-object> structured transition input, including\n proof_plan or pre_pr_review when required\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session next": "Usage: threadloop session next [options]\n\nInspect the deterministic next lifecycle candidate without mutating state\n\nOptions:\n --session <id> session id to inspect\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session gate run": "Usage: threadloop session gate run [options] <gate-id>\n\nRun one declared local gate and append an immutable receipt\n\nArguments:\n gate-id declared proof-plan gate id\n\nOptions:\n --session <id> session id to target\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session gate import": "Usage: threadloop session gate import [options] <package-path>\n\nVerify and append one signed GitHub Actions gate receipt\n\nArguments:\n package-path path to a signed receipt package\n\nOptions:\n --session <id> session id to target\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session review import": "Usage: threadloop session review import [options] <package-path>\n\nVerify and append one signed GitHub review snapshot\n\nArguments:\n package-path path to a signed review package\n\nOptions:\n --session <id> session id to target\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "session reconcile": "Usage: threadloop session reconcile [options]\n\nRefresh Git-derived metadata for a session without creating semantic entries\n\nOptions:\n --session <id> session id to reconcile\n -a, --all reconcile all active sessions\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "executor register": "Usage: threadloop executor register [options]\n\nAdopt a fresh host-controlled action and signer policy\n\nOptions:\n --state <directory> new state directory outside the subject\n --binding <file> host-adopted frozen controller binding JSON\n --config <file> explicit process and verification configuration JSON\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "executor run": "Usage: threadloop executor run [options]\n\nLaunch the registered Attempt once and admit verified evidence\n\nOptions:\n --state <directory> registered executor state directory\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "executor inspect": "Usage: threadloop executor inspect [options]\n\nIndependently verify retained executor state without launching\n\nOptions:\n --state <directory> executor state directory\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "executor admit": "Usage: threadloop executor admit [options] <observation-id>\n\nRecheck retained output after an admission failure without launching\n\nArguments:\n observation-id retained successful transport observation\n\nOptions:\n --state <directory> executor state directory\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "executor evaluate": "Usage: threadloop executor evaluate [options]\n\nRe-evaluate lifecycle guards after evidence admission\n\nOptions:\n --state <directory> executor state directory\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "audit show": "Usage: threadloop audit show [options]\n\nShow hash-linked audit events for a session\n\nOptions:\n --session <id> session id to inspect\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "audit verify": "Usage: threadloop audit verify [options]\n\nVerify a session audit chain and optional retained root\n\nOptions:\n --session <id> session id to verify\n --root <sha256> previously retained audit root\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "audit export": "Usage: threadloop audit export [options]\n\nVerify and atomically create a JSONL audit export\n\nOptions:\n --session <id> session id to export\n --output <path> new output path; existing files are never overwritten\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "audit corpus": "Usage: threadloop audit corpus [options]\n\nExport a verified corpus with one outcome per session\n\nOptions:\n --format <format> native corpus, viewer logs or verifiable logs (choices:\n \"native\", \"otel\", \"otel-verifiable\", default: \"native\")\n --session <ids...> explicit session ids to include\n --all include every session in the current repository\n --output <path> new output path; existing files are never overwritten\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "audit verify-export": "Usage: threadloop audit verify-export [options]\n\nVerify retained corpus bytes without a repository or database\n\nOptions:\n --input <path> retained corpus file\n --root <sha256> previously retained whole-file corpus root\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow create": "Usage: threadloop workflow create [options] <run-id>\n\nCreate a run bound to one compiled graph and setup\n\nOptions:\n --profile <yaml> workflow profile file\n --setup <json> workflow setup file\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow inspect": "Usage: threadloop workflow inspect [options] <run-id>\n\nRead the verified graph binding and current state\n\nOptions:\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow decide": "Usage: threadloop workflow decide [options] <run-id>\n\nSelect the next outcome from verified run facts\n\nOptions:\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow apply": "Usage: threadloop workflow apply [options] <run-id>\n\nApply a fresh selected transition once\n\nOptions:\n --decision <file> saved workflow decide JSON response\n --idempotency-key <key> stable key for this request\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow execute": "Usage: threadloop workflow execute [options] <run-id>\n\nExecute a selected engineering action through the enrolled GAAP bridge\n\nOptions:\n --decision <file> saved workflow decide JSON response\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow expire-claim": "Usage: threadloop workflow expire-claim [options] <run>\n\nRecord an overdue claim for its enrolled Attempt\n\nOptions:\n --attempt <id> enrolled Attempt ID from workflow inspect\n --expected-state-version <n> expected lifecycle version\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow evidence collect": "Usage: threadloop workflow evidence collect [options] <kind>\n\nCollect local gate or pre-PR review evidence from the enrolled producer\n\nOptions:\n --run <run-id> workflow run ID\n --gate <id> adopted local proof gate\n --operation <id> Qodo review operation UUID\n --expected-state-version <n> expected lifecycle version\n --idempotency-key <key> stable collection key\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow evidence prepare": "Usage: threadloop workflow evidence prepare [options] <kind>\n\nBind a sensor observation to the current run\n\nOptions:\n --run <run-id> workflow run ID\n --gate <id> declared gate ID\n --pr <n> positive pull request number\n --instruction <file> explicit human instruction file\n --expected-state-version <n> expected lifecycle version\n --idempotency-key <key> stable preparation key\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "workflow evidence import": "Usage: threadloop workflow evidence import [options] <kind>\n\nVerify and retain a prepared sensor package\n\nOptions:\n --run <run-id> workflow run ID\n --source <file> signed sensor package or GAAP correlation file\n --expected-state-version <n> expected lifecycle version\n --json Output machine-readable JSON\n -h, --help display help for command\n", + "protocol": "Usage: threadloop protocol [options]\n\nPrint the agent integration protocol\n\nOptions:\n --contract <version> protocol version to print (choices: \"4\", \"5\")\n --json Output machine-readable JSON\n -h, --help display help for command\n" + }, + "no_arguments": { + "exit": 1, + "stderr": "Usage: threadloop [options] [command]\n\nTask-first, repo-local session memory that generates review-ready artifacts\n\nOptions:\n -V, --version output the version number\n -h, --help display help for command\n\nCommands:\n init Initialize ThreadLoop in the current Git repo\n artifact Generate artifacts from session context\n session Manage explicit ThreadLoop sessions\n executor Run the frozen GAAP reference process bridge\n audit Inspect and export the authoritative audit ledger\n workflow Manage graph-bound Workflow Runs\n protocol [options] Print the agent integration protocol\n help [command] display help for command\n" + }, + "runner_sha256": { + "80e091c9f6412195a8444f048add977d648c4115": "fd9fabf1ad27f4b91d1b369b9283200045a1ca54e54d38da014d4f29972cc0dc", + "31388a07566350dfeddc30578d43b8926d5b4e22": "fd9fabf1ad27f4b91d1b369b9283200045a1ca54e54d38da014d4f29972cc0dc", + "7c54c2bb8055f00736e3b5f6631e9aecbe0fd212": "f0294d8c2abb5b8dcb6d9b8564eb6076a72a26614323acf0dc1ed4479e190a81" + }, + "per_runtime": { + "v22.22.2": { + "node": "v22.22.2", + "host": "macOS-26.6-arm64-arm-64bit", + "race": { + "winner": "parity-right", + "loser": "STATE_VERSION_CONFLICT", + "replay_sha256": "75df7b8f7c2bc7bbb362566d55c39bac49938b05018999dbe7aa6d9e7be1dfba" + }, + "rollback_proof": { + "pre_upgrade": { + "session status": "64542b79793a6d335201cf597fd10e60ea3d20755cdc48068a26b1e7505c3b0d", + "session next": "ce445f2a896e6b181bd7763d91240f56bcc4fc521b8baa723665014e1625f6f1", + "audit show": "50cf4c260e43decf37c214b6ed6f87eeee6d5afeaed183985a23bd30f19faad3", + "audit verify": "1532d5b4599a1dd28073986c6f5923e5dcf557b8c4d6b679341f6e9435c604f4", + "audit export": "bb11d9f9ed1417415727ccafcafec265bfb08756373c2604b9195aaf3737a87a" + }, + "post_upgrade": { + "session status": "416f37da0839d59b446cc4bf679dc7a36556e1e53f4e7b65c6783d8fe499c298", + "session next": "839d2642825c580423edda59293666a43267391276970664547128c891ef6687", + "audit show": "917de81b2c44194919261f8e9907395d6c8f25e8d57a07c0623c2a8b8326b127", + "audit verify": "1b97529dd7bcbd5ed686a973884575598595dbb7173881b0f14d4ce43e8f0839", + "audit export": "13df5a624863a10c77dc2a53a03ca4f44e59e66a250e80745f2da5938cb869d6" + }, + "restored": { + "session status": "64542b79793a6d335201cf597fd10e60ea3d20755cdc48068a26b1e7505c3b0d", + "session next": "ce445f2a896e6b181bd7763d91240f56bcc4fc521b8baa723665014e1625f6f1", + "audit show": "50cf4c260e43decf37c214b6ed6f87eeee6d5afeaed183985a23bd30f19faad3", + "audit verify": "1532d5b4599a1dd28073986c6f5923e5dcf557b8c4d6b679341f6e9435c604f4", + "audit export": "bb11d9f9ed1417415727ccafcafec265bfb08756373c2604b9195aaf3737a87a" + }, + "pre_files": { + "state.db": "c61517a4dc45484aba885319e73c12437874242903f588ea196600423767b2b7", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "post_files": { + "state.db": "25b6ddc7333e75c1d09004b443934ea56666ab8296a083cd0a3a7d120275b8aa", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "restored_files": { + "state.db": "c61517a4dc45484aba885319e73c12437874242903f588ea196600423767b2b7", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "post_upgrade_session_absent": true, + "post_upgrade_workflow_absent": true + }, + "artifacts": { + ".change-brief": "cf31c8191bb237d44bc9a2252a7dbf3b00c6a5e03baa8b49e3694175a2ad3517", + ".handoff": "622be4b346834c9d3f13586b8e2f61f05ddd26aa07b074e18f978ac16cacccd6", + ".pr-summary": "f95ce67695800b91c8809c20ff34470ad9b423788735decf7b278ba220822872" + }, + "workflow": { + "graph_digest": "22fb31abcf828c86c0c299eed82bc0d196285a62a9875bfd96fa3d5580202234", + "initial": "intake", + "final": "prepared", + "final_version": 1, + "exact_replay_preserved": true + }, + "pre_adoption": { + "original_reads": { + "session status": "3747f123c5fc8ef1fb0a6832f8dad0ae861a56e8bf4d6fb4ccf81a7113cf592a", + "session next": "80766a64edf99f6fafb87456be96568a21b9624097b47fff8230348fccce61c9", + "audit show": "1d8db6268072a7fda66e17c2d3bf0d6a64b84b7e2a3cf3dcfa138af8267f5b34", + "audit verify": "ed4ad6e0d1660d38117219e116b9b0cf61af172af4fa30a81f5d00cdfb0b8e98", + "audit export": "d286e0e520119763589cb1c9039400da4466412a537d687833061951327cdf5b" + }, + "candidate_reads": { + "session status": "3747f123c5fc8ef1fb0a6832f8dad0ae861a56e8bf4d6fb4ccf81a7113cf592a", + "session next": "206a3765190a7e2fad13727df7a939957ec52574d3e3d627a098352bec3b0ffb", + "audit show": "1d8db6268072a7fda66e17c2d3bf0d6a64b84b7e2a3cf3dcfa138af8267f5b34", + "audit verify": "ed4ad6e0d1660d38117219e116b9b0cf61af172af4fa30a81f5d00cdfb0b8e98", + "audit export": "d286e0e520119763589cb1c9039400da4466412a537d687833061951327cdf5b" + }, + "database": { + "state.db": "bbdc24c1753f3f2a0f3494b0aec7b2e83cb7020d910d9b182357b6382b75dce1" + }, + "catalog_and_workflow_tables_absent": true, + "capabilities": ["session_next_v1"], + "next_other_fields_identical": true + }, + "storage": { + "generation": 8, + "future_generation_refused_without_writes": { + "state.db": "f183e522dd15966d25bb84099e6ca820e50612a8d7b3c3d2a3999599eb977b5f" + }, + "legacy_json_sha256": "8dcc406d6ab111da1c212e64a25d8a393c80ab0cdbeb942e72fdf82e24a234ce", + "legacy_task_imported": false, + "generation_one_ddl_revision": "750ae36b6b7b6ea34081a8c90236d8c95f71b086", + "generation_one_ddl_sha256": "80908d1e0f6ba7a7b4376497c1888bf795aa5d946e68aa12e20b5d41f0f82b5f", + "rejected_read_preserved_files": { + "state.db": "4501776c51cd7e09cfcb730e7f109484c6164533a500960b8d40a4ed96480690" + } + }, + "raw_packet_sha256": "fabb72a6b7bfc8ca149fac23b4b82b0e094b2a3f32551cbda916102da2bc1758" + }, + "v24.20.0": { + "node": "v24.20.0", + "host": "macOS-26.6-arm64-arm-64bit", + "race": { + "winner": "parity-right", + "loser": "STATE_VERSION_CONFLICT", + "replay_sha256": "9031744bdf2e000cb1147af30ea3ddab0ebf0ccbfa2f7809c573035d5b57a810" + }, + "rollback_proof": { + "pre_upgrade": { + "session status": "e41bb10660bbfd18567f1010fcddc260ac902407a46d35607eabdcf3baf50d38", + "session next": "2523c91c9f61a94b10e2fb7b73a4a466a2ac8092e42c16d0682bd9eb498ea926", + "audit show": "1f27cfed14c609253e1ccdd656f3cce5165eb9f425c353578fb947292b9c97b1", + "audit verify": "44eec6b38aa1f40915ebd750089a1a986b549f4bd04caef4c666cbca25215bbd", + "audit export": "82fb8c4de91bafa970a17e9107e1a1f5404464eda55bef90eba4d6333903b262" + }, + "post_upgrade": { + "session status": "faf121a62faa9a806a599644ebd94e34e5e9fc11e4a7ec284b1f3f0534d2ccf6", + "session next": "a09c0bf39acf2265871030854db56e0023887eb2dde203507776a7f97f980e1e", + "audit show": "9360f2224196d97a788f1afe0e6c353fdea98e8041da836500cff69edf6565e1", + "audit verify": "8aa9914b5c15f3b0273b75d80180ec8b890d09e60a5772b931baf4f901ce0e5c", + "audit export": "6e7b432bb09a7b054725ff19f1df1bf60167a86950d522d974216452a39ca924" + }, + "restored": { + "session status": "e41bb10660bbfd18567f1010fcddc260ac902407a46d35607eabdcf3baf50d38", + "session next": "2523c91c9f61a94b10e2fb7b73a4a466a2ac8092e42c16d0682bd9eb498ea926", + "audit show": "1f27cfed14c609253e1ccdd656f3cce5165eb9f425c353578fb947292b9c97b1", + "audit verify": "44eec6b38aa1f40915ebd750089a1a986b549f4bd04caef4c666cbca25215bbd", + "audit export": "82fb8c4de91bafa970a17e9107e1a1f5404464eda55bef90eba4d6333903b262" + }, + "pre_files": { + "state.db": "61a32143bf7ffd2093deea60ae6c176b27e5d2e948ec0143a4cf9c20f9b4e1db", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "post_files": { + "state.db": "d008271e6a7184e1bb417f7cf7275705492dc9ec0b82cbfe98d8bdb43e748d08", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "restored_files": { + "state.db": "61a32143bf7ffd2093deea60ae6c176b27e5d2e948ec0143a4cf9c20f9b4e1db", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "post_upgrade_session_absent": true, + "post_upgrade_workflow_absent": true + }, + "artifacts": { + ".change-brief": "dcb7993a9747f451da571fe75250cbef4b692910e0644e4a2dd6e3a9b561bcc2", + ".handoff": "8c2ec54ae4aa2183a21b694fbd004e0c694887711a2ec90902a78a12f182b147", + ".pr-summary": "af17475b427e613aa6c9593ac91a524c6d08c0feaf9669087aceff54f9eb5f1d" + }, + "workflow": { + "graph_digest": "22fb31abcf828c86c0c299eed82bc0d196285a62a9875bfd96fa3d5580202234", + "initial": "intake", + "final": "prepared", + "final_version": 1, + "exact_replay_preserved": true + }, + "pre_adoption": { + "original_reads": { + "session status": "085445fa77ee85a5df53813aa802e28c6997c73f24305e9387921b8a88d7a251", + "session next": "509ea15ca894f8aee312dc4e11525dd7df4243e595a0450377dfa6ad83c5920b", + "audit show": "89761466258e59291e1175a9e2ac8e92d60c0bfd79fd465f06f17e7a558e2596", + "audit verify": "e30818a7f38982c7fe95020198ae9aad09c0453e6d30e608de5dfadf48186c3b", + "audit export": "a2a8011d83d873778a6d4fab6c46bdbe2854a768520dc0e6299351920d17daef" + }, + "candidate_reads": { + "session status": "085445fa77ee85a5df53813aa802e28c6997c73f24305e9387921b8a88d7a251", + "session next": "a64e19360f2dd648b32527b0493d6da3b644456b043ec2c26997f50b582a3897", + "audit show": "89761466258e59291e1175a9e2ac8e92d60c0bfd79fd465f06f17e7a558e2596", + "audit verify": "e30818a7f38982c7fe95020198ae9aad09c0453e6d30e608de5dfadf48186c3b", + "audit export": "a2a8011d83d873778a6d4fab6c46bdbe2854a768520dc0e6299351920d17daef" + }, + "database": { + "state.db": "b096e336cd6652365ff3e8d1780334be0563ebf03a60524c73df74d98424ae64" + }, + "catalog_and_workflow_tables_absent": true, + "capabilities": ["session_next_v1"], + "next_other_fields_identical": true + }, + "storage": { + "generation": 8, + "future_generation_refused_without_writes": { + "state.db": "f183e522dd15966d25bb84099e6ca820e50612a8d7b3c3d2a3999599eb977b5f" + }, + "legacy_json_sha256": "8c3fa07dc9c3eb0f1e1ee9dfafc93113e1bc43f5a05bf5dfda5f7da4f5819479", + "legacy_task_imported": false, + "generation_one_ddl_revision": "750ae36b6b7b6ea34081a8c90236d8c95f71b086", + "generation_one_ddl_sha256": "80908d1e0f6ba7a7b4376497c1888bf795aa5d946e68aa12e20b5d41f0f82b5f", + "rejected_read_preserved_files": { + "state.db": "4501776c51cd7e09cfcb730e7f109484c6164533a500960b8d40a4ed96480690" + } + }, + "raw_packet_sha256": "ec76f978136b6486305cfa52ad0defb899b341157d768b57647b094d5d1ac9dc" + }, + "v26.8.2": { + "node": "v26.8.2", + "host": "macOS-26.6-arm64-arm-64bit", + "race": { + "winner": "parity-left", + "loser": "STATE_VERSION_CONFLICT", + "replay_sha256": "eedda2aae521b9e6117beeacab84d7f1fd2fbbad47a4fd40b7a384547e1ff763" + }, + "rollback_proof": { + "pre_upgrade": { + "session status": "bbaa3535650748b505a06606bcdb594be7747abee5d46a39a5446a8134eeb68d", + "session next": "61edfbcb785cb9018cab0bba4d0ed0ccfcb169dd3f5aeb126981262b3a0d4ed7", + "audit show": "0264f1495c61667b761f85ae2673f440a90e367f3552462e6aa2ae78faa269ae", + "audit verify": "66e9e9a2694c49201c364cdd05f2f51c8f933eed8e3a615e839d76a4c9c53927", + "audit export": "7c9335f5a43ae2fb05b5241882c64c5ab425c8625cd7696b662b31e6cba0c70f" + }, + "post_upgrade": { + "session status": "29aa71bc7339a8b71f40a643f43ce7c2695b7b015cb541adaf8f8c24e0660ed2", + "session next": "397317ee2df6c8e867eb479e1256bc7e99d7725e5dfdfea0581d9dff3f79fbb4", + "audit show": "250a4db59e80fc0520b4920bd5b2c61989e6d3dad089052434ba03cb57c9ba6c", + "audit verify": "a8ffdbd9ed277e874e412f8bb6352b7046442527320c1b5aa89d61ecc30c2f2a", + "audit export": "498978f066bad990c92cbbef05b0a32bc3cdb3a3cf1f6745339b825a7ae77048" + }, + "restored": { + "session status": "bbaa3535650748b505a06606bcdb594be7747abee5d46a39a5446a8134eeb68d", + "session next": "61edfbcb785cb9018cab0bba4d0ed0ccfcb169dd3f5aeb126981262b3a0d4ed7", + "audit show": "0264f1495c61667b761f85ae2673f440a90e367f3552462e6aa2ae78faa269ae", + "audit verify": "66e9e9a2694c49201c364cdd05f2f51c8f933eed8e3a615e839d76a4c9c53927", + "audit export": "7c9335f5a43ae2fb05b5241882c64c5ab425c8625cd7696b662b31e6cba0c70f" + }, + "pre_files": { + "state.db": "7f16a40de06507eec944175de718a84b6eb4b214246e222659d2fdd5a31db5b3", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "post_files": { + "state.db": "199ff0d5ea19c268638c652d52df6c1913b3a4533513fbedde6fcfe4b4f330b6", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "restored_files": { + "state.db": "7f16a40de06507eec944175de718a84b6eb4b214246e222659d2fdd5a31db5b3", + "state.db-shm": "fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb", + "state.db-wal": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "post_upgrade_session_absent": true, + "post_upgrade_workflow_absent": true + }, + "artifacts": { + ".change-brief": "e4bf2312a3afbbc76e3ed9871b72b40512560358d36d9f7c798aa59c13bc8286", + ".handoff": "f6343637addb357ad42bf05078abe54e92dacadde3afa7c3e7008bc25c251b36", + ".pr-summary": "c22658a9ccb4754a47ad29df6a576a86a4998ee57a131d206cce3b0d69ceefb2" + }, + "workflow": { + "graph_digest": "22fb31abcf828c86c0c299eed82bc0d196285a62a9875bfd96fa3d5580202234", + "initial": "intake", + "final": "prepared", + "final_version": 1, + "exact_replay_preserved": true + }, + "pre_adoption": { + "original_reads": { + "session status": "c733835fc0dc627182ac3c38ff6c47005bf0267f0c220f805a2a2e05e32fc8eb", + "session next": "c9ce58c3d3f917be049d60a215147d026aec53915a7754b2ca9544206385b7c3", + "audit show": "6aa20d36038ddf35c21b5afbc8478a285627c6478546820a6c070d496bb67293", + "audit verify": "5a475ebd99e7ce36831249087d608b152c92f7d1f48b82647237e4b26c9fcc19", + "audit export": "30a7bd0b44ea417173d1d028f883eb88b38d5e47e421cb333daa147e665d2996" + }, + "candidate_reads": { + "session status": "c733835fc0dc627182ac3c38ff6c47005bf0267f0c220f805a2a2e05e32fc8eb", + "session next": "6c614492432fc36e1287d6fe2c195956e21a9b196167dbc14319d00a9e567bab", + "audit show": "6aa20d36038ddf35c21b5afbc8478a285627c6478546820a6c070d496bb67293", + "audit verify": "5a475ebd99e7ce36831249087d608b152c92f7d1f48b82647237e4b26c9fcc19", + "audit export": "30a7bd0b44ea417173d1d028f883eb88b38d5e47e421cb333daa147e665d2996" + }, + "database": { + "state.db": "4a35f5921c8f0d683a8546eab247dc3f99defe6da1cdbf2932bd632c69602039" + }, + "catalog_and_workflow_tables_absent": true, + "capabilities": ["session_next_v1"], + "next_other_fields_identical": true + }, + "storage": { + "generation": 8, + "future_generation_refused_without_writes": { + "state.db": "f183e522dd15966d25bb84099e6ca820e50612a8d7b3c3d2a3999599eb977b5f" + }, + "legacy_json_sha256": "6a8dbb06330467840594e1e629522cb5300d19cca293a679fe04d32bfd52dba1", + "legacy_task_imported": false, + "generation_one_ddl_revision": "750ae36b6b7b6ea34081a8c90236d8c95f71b086", + "generation_one_ddl_sha256": "80908d1e0f6ba7a7b4376497c1888bf795aa5d946e68aa12e20b5d41f0f82b5f", + "rejected_read_preserved_files": { + "state.db": "4501776c51cd7e09cfcb730e7f109484c6164533a500960b8d40a4ed96480690" + } + }, + "raw_packet_sha256": "8e453e1519329d1a1c55f698e3be5626126daa8c6c819e33345d83c1b3e9da76" + } + } +} diff --git a/docs/evidence/issue-172-managed-rollback.json b/docs/evidence/issue-172-managed-rollback.json new file mode 100644 index 0000000..fc9bff9 --- /dev/null +++ b/docs/evidence/issue-172-managed-rollback.json @@ -0,0 +1,621 @@ +{ + "source": { + "revision": "80e091c9f6412195a8444f048add977d648c4115", + "tree": "987ef4aeda6bb371b0c2f476a3dbeae9467d89ec", + "lock_blob": "b35af44702d348558f848767c6eae50a40b7ca18", + "node": "v26.8.2", + "npm": "11.19.1", + "tarball": "threadloop-0.1.0.tgz", + "sha256": "36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51", + "cli_sha256": "610e586afd19fd85e0b2adade639b88a98213a039cb980772f72a65ded4cdc22", + "integrity": "sha512-thLVEkgwnuv9EMxiNyy9Ddm2Z+mGuirfETwpkGV/7kXXomgZQ134Mq5IuJnwNyNNPyB3TtqwsgfHqAljpMLAxA==", + "bundled_dependencies": 55 + }, + "previous": { + "bundled_dependencies": 55, + "cli_sha256": "0859b3f5c9a0cac969bbe0c744ade31080d81910d53ae04970ea654d3ce94571", + "integrity": "sha512-lpV4S8nRXKjCYr5Qarg7x95EY1bBDXsVmC5NrTyvYxFM1iLjY2MiNU9zWOWejexEAJo3HXjJkDa8x/ueNmLpqg==", + "lock_blob": "b35af44702d348558f848767c6eae50a40b7ca18", + "node": "v26.8.2", + "npm": "11.19.1", + "revision": "31388a07566350dfeddc30578d43b8926d5b4e22", + "sha256": "c8c96f8229ee141bfe31b1509440e548aa2fb64b089bd6f44b41016e7e0fe078", + "tarball": "threadloop-0.1.0.tgz", + "tree": "17124dd8949059d40c25807e297659817f2c5b11" + }, + "previous_merge": "bdf68cc2d3ad915d085aecff47c9181f65fb5205", + "fixture_files": { + "scripts/pre-rust/rollback-fixture.ts": "a34dbaca9a61349b6323df7eeb2e9fd03de8c1f11ccbcaa8924d2d0195573765", + "tests/fixtures/gaap-producer.ts": "f310f27fa745b146c5749f73b184ea831ed274335f681b42b9a5a2717cc47a09", + "tests/fixtures/gaap.ts": "05dc08e35462704821d1d1d2340313ce7736f1a724b1664eb53e176a203e9886", + "tests/fixtures/workflow/execution-cut.mjs": "7e3d35d78c4ed13c87ae788b93df94fccce031fa617ec8347f2ff1d517cb7b41", + "tests/helpers/workflow-execution.ts": "da55d08c335221cb94a6116868e1cf72eb857b236ab25712bf7bc148f9f617ba" + }, + "driver_sha256": "b7f13ed4027e7bf8c15717a2d9f89bd25dd619689a90806badfa3ade2c612ddc", + "limit_per_backup_bytes": 67108864, + "mode": "quiescent two-store backup and restore", + "per_runtime": { + "v22.22.2": { + "raw_packet_sha256": "e412f2f019cab3eb2674dc1bd0d1c97c39fc6ff4dec48500c83eb7382b66f726", + "sqlite": "3.51.0", + "cases": [ + { + "accepted": [], + "blobs": [], + "case": "held", + "child_revision": 2, + "child_root_digest": "31ffb24a3949bf6f94ec395263fcf96564b61ca59b6e191a1160bb916bc71079", + "effect_file_sha256": "a0cb50ef664c14794b50531c2ed4c9d9e57aabde1e1ecb22d0c1d9f8df06fefa", + "execution_revision_before": 3, + "execution_revision_recovered": 3, + "file_hashes_before": { + ".threadloop/state/state.db": "d0b9bb2a4868292d5a43c34e552ac3739d071f667094a2b68cdeb99c17b19275", + ".threadloop/state/workflow-execution-500cab78fe7973234eb282234629ca74/executor.sqlite": "bd743fe4b23619424bf180053e42a7f9fc06213354fe80281135c28f7de11528" + }, + "file_hashes_restored": { + ".threadloop/state/state.db": "d0b9bb2a4868292d5a43c34e552ac3739d071f667094a2b68cdeb99c17b19275", + ".threadloop/state/workflow-execution-500cab78fe7973234eb282234629ca74/executor.sqlite": "bd743fe4b23619424bf180053e42a7f9fc06213354fe80281135c28f7de11528" + }, + "import_events_after_backup": 0, + "import_events_after_recovery": 0, + "import_events_restored": 0, + "initial_observation": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "execution_outstanding" + }, + "invocations_after_recovery": 1, + "launches": 1, + "legacy_version_after_backup": 1, + "legacy_version_restored": 0, + "observations": [ + { + "envelope_sha256": null, + "id": 1, + "status": "exit_failed", + "stderr_sha256": "8e9475953db5168b536053519c61cedbb4bfec8add48d4ff1425080f4b0de981", + "stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + ], + "old_managed_refusals": { + "apply": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "child_inspect": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "child_run": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "decide": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "inspect": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "prepare": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "reused_create": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + } + }, + "outer_state_version": 3, + "physical_subject_head": "9d5d5907f9673f75f8905a8aa9e801a9c0c3c8c6", + "recovery_disposition": "execution_outstanding", + "replay_disposition": "execution_outstanding", + "snapshot_bytes": 798250 + }, + { + "accepted": [ + { + "admission_digest": "49c2efa2461c266cb4ede7db5df28dccbb7e39fc9bab9885a054b6ba51d62361", + "envelope_sha256": "bf755ba836a3801b684e9e47efce12070ab33bf6f5bfe77e114cc6ecabc16663", + "observation": 1, + "predicate_sha256": "c15e8f62dccf2476b27ce4d1af858f4ab0cdcc8d95044e1b2c32f9c2f9e7a3eb", + "result_sha256": "64b17a1083ac18ee53bffc3c2f12f55f4a982423cb08e6bedc9db5b074ae4a4d", + "signature_count": 1, + "source_digest": "098be226e4fcd6c4443587946a013aed24af4c20de94214984e4b3cb0a305082", + "source_id": "threadloop_attempt_5428763f129dc2d713a3b15648f3d12677910e84408c3e538fe3ea5c248e4844" + } + ], + "blobs": [ + { + "bytes": 21, + "id": "sha256:0c5d8c89ef623535e4f3df8b5879e5256b52d5a54adc9c602c418391eacb21b1", + "sha256": "0c5d8c89ef623535e4f3df8b5879e5256b52d5a54adc9c602c418391eacb21b1" + }, + { + "bytes": 33, + "id": "sha256:6ccd87ea7aa30b553ada852e153b2fce021e7a53caaf18a27a3a54ac0e38fe4d", + "sha256": "6ccd87ea7aa30b553ada852e153b2fce021e7a53caaf18a27a3a54ac0e38fe4d" + }, + { + "bytes": 159, + "id": "sha256:ec49d61914a4e032e0444dafa9e0567db757ec7094b67aae09f874ded1fb57cd", + "sha256": "ec49d61914a4e032e0444dafa9e0567db757ec7094b67aae09f874ded1fb57cd" + } + ], + "case": "admitted", + "child_revision": 3, + "child_root_digest": "ecaa45761663f65184193ff0de57900657a5165788a2d892bb2fcf092ab1e9e4", + "effect_file_sha256": null, + "execution_revision_before": 2, + "execution_revision_recovered": 3, + "file_hashes_before": { + ".threadloop/state/state.db": "05c985d7fd183f663c5cbb5c377a9c96b58a1a8e64d03d8944d49e8583d9aee7", + ".threadloop/state/workflow-execution-65f9a12f6a72e8d77b6fe07438c2fcd5/executor.sqlite": "d92119881a58987b9af8e2a67235ac5ce295cecee471eec0fafe10e87fb225e5" + }, + "file_hashes_restored": { + ".threadloop/state/state.db": "05c985d7fd183f663c5cbb5c377a9c96b58a1a8e64d03d8944d49e8583d9aee7", + ".threadloop/state/workflow-execution-65f9a12f6a72e8d77b6fe07438c2fcd5/executor.sqlite": "d92119881a58987b9af8e2a67235ac5ce295cecee471eec0fafe10e87fb225e5" + }, + "import_events_after_backup": 1, + "import_events_after_recovery": 1, + "import_events_restored": 0, + "initial_observation": { + "observed_boundary": "managed-cut=admit", + "signal": "SIGKILL" + }, + "invocations_after_recovery": 1, + "launches": 1, + "legacy_version_after_backup": 1, + "legacy_version_restored": 0, + "observations": [ + { + "envelope_sha256": "bf755ba836a3801b684e9e47efce12070ab33bf6f5bfe77e114cc6ecabc16663", + "id": 1, + "status": "ok", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stdout_sha256": "3b9cf9d1103525d61836d9c434f4492a25c323a7cfbc9637fd30af8fb0a01254" + } + ], + "old_managed_refusals": { + "apply": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "child_inspect": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "child_run": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "decide": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "inspect": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "prepare": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "reused_create": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + } + }, + "outer_state_version": 3, + "physical_subject_head": "7e3a2fc767c807e85d9ea7e32033258dbc53d859", + "recovery_disposition": "imported", + "replay_disposition": "imported", + "snapshot_bytes": 788875 + } + ] + }, + "v24.20.0": { + "raw_packet_sha256": "97aa50c2a88be3249804fb379dc6440121ced62a0cde036a78017f077763d0e1", + "sqlite": "3.51.0", + "cases": [ + { + "accepted": [], + "blobs": [], + "case": "held", + "child_revision": 2, + "child_root_digest": "d5ca0890b1465b683f57e665deb5af41567499071da3ff091c808ec220b8964a", + "effect_file_sha256": "a0cb50ef664c14794b50531c2ed4c9d9e57aabde1e1ecb22d0c1d9f8df06fefa", + "execution_revision_before": 3, + "execution_revision_recovered": 3, + "file_hashes_before": { + ".threadloop/state/state.db": "491840af7cc0a6ef3df376778f4e97b5115d3d95e6b343812fdbb7bce5eefd0a", + ".threadloop/state/workflow-execution-8a20b0e242554314e437294ee355a6f1/executor.sqlite": "b4a3b78d4eb5f3e8ee83f972486cba6beb13944d7612c7dca08a5a77cadfad7f" + }, + "file_hashes_restored": { + ".threadloop/state/state.db": "491840af7cc0a6ef3df376778f4e97b5115d3d95e6b343812fdbb7bce5eefd0a", + ".threadloop/state/workflow-execution-8a20b0e242554314e437294ee355a6f1/executor.sqlite": "b4a3b78d4eb5f3e8ee83f972486cba6beb13944d7612c7dca08a5a77cadfad7f" + }, + "import_events_after_backup": 0, + "import_events_after_recovery": 0, + "import_events_restored": 0, + "initial_observation": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "execution_outstanding" + }, + "invocations_after_recovery": 1, + "launches": 1, + "legacy_version_after_backup": 1, + "legacy_version_restored": 0, + "observations": [ + { + "envelope_sha256": null, + "id": 1, + "status": "exit_failed", + "stderr_sha256": "8e9475953db5168b536053519c61cedbb4bfec8add48d4ff1425080f4b0de981", + "stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + ], + "old_managed_refusals": { + "apply": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "child_inspect": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "child_run": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "decide": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "inspect": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "prepare": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "reused_create": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + } + }, + "outer_state_version": 3, + "physical_subject_head": "28b5665365f792a3899eff8402f3808d8d6e4414", + "recovery_disposition": "execution_outstanding", + "replay_disposition": "execution_outstanding", + "snapshot_bytes": 798233 + }, + { + "accepted": [ + { + "admission_digest": "5853154e7acbaa3b59af9c7f2dcf24d8b8637b7260c27a2dd389ac16043bfa2d", + "envelope_sha256": "d6fd679d9eea7383b1ff208c0dde5df0c4168bbc0b3a7fcab3111b7dc8a631eb", + "observation": 1, + "predicate_sha256": "cab9038c3648dabd6943e88f6c0645bcc330d5e472bab96c06165a19f757d824", + "result_sha256": "f71bf442bf0386b3e198a956f84879b3baff5f5b3175264b7c1f2cade9f52c04", + "signature_count": 1, + "source_digest": "c31781a48ddbdadafea58845a6836c62171377ce7314f0f1537465421731883a", + "source_id": "threadloop_attempt_1a4e652a5db5c371f10dfc39c2d9ea77138d7245cf46fe1f8882fe0b70c9f58f" + } + ], + "blobs": [ + { + "bytes": 21, + "id": "sha256:0c5d8c89ef623535e4f3df8b5879e5256b52d5a54adc9c602c418391eacb21b1", + "sha256": "0c5d8c89ef623535e4f3df8b5879e5256b52d5a54adc9c602c418391eacb21b1" + }, + { + "bytes": 33, + "id": "sha256:6ccd87ea7aa30b553ada852e153b2fce021e7a53caaf18a27a3a54ac0e38fe4d", + "sha256": "6ccd87ea7aa30b553ada852e153b2fce021e7a53caaf18a27a3a54ac0e38fe4d" + }, + { + "bytes": 159, + "id": "sha256:ec49d61914a4e032e0444dafa9e0567db757ec7094b67aae09f874ded1fb57cd", + "sha256": "ec49d61914a4e032e0444dafa9e0567db757ec7094b67aae09f874ded1fb57cd" + } + ], + "case": "admitted", + "child_revision": 3, + "child_root_digest": "7b9f9a4ba77b4c7f66e6a0ca563dfa1162eb5b839fb5df400513907d277deba4", + "effect_file_sha256": null, + "execution_revision_before": 2, + "execution_revision_recovered": 3, + "file_hashes_before": { + ".threadloop/state/state.db": "04f6f984268e9c934e79b7d7a6ead94eec2219d67cb365ec74108db4c56d9c81", + ".threadloop/state/workflow-execution-c6be86cb73dea37b1d3bfcf698c82f8e/executor.sqlite": "f1712cbd0dbb985f88a48efdc296d4a6c4c949e1db34fa4277e3105080ad2e15" + }, + "file_hashes_restored": { + ".threadloop/state/state.db": "04f6f984268e9c934e79b7d7a6ead94eec2219d67cb365ec74108db4c56d9c81", + ".threadloop/state/workflow-execution-c6be86cb73dea37b1d3bfcf698c82f8e/executor.sqlite": "f1712cbd0dbb985f88a48efdc296d4a6c4c949e1db34fa4277e3105080ad2e15" + }, + "import_events_after_backup": 1, + "import_events_after_recovery": 1, + "import_events_restored": 0, + "initial_observation": { + "observed_boundary": "managed-cut=admit", + "signal": "SIGKILL" + }, + "invocations_after_recovery": 1, + "launches": 1, + "legacy_version_after_backup": 1, + "legacy_version_restored": 0, + "observations": [ + { + "envelope_sha256": "d6fd679d9eea7383b1ff208c0dde5df0c4168bbc0b3a7fcab3111b7dc8a631eb", + "id": 1, + "status": "ok", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stdout_sha256": "43b72c8753a24b704bf474baef3b2555dc1c59ba75b414e7e24c0a785235af49" + } + ], + "old_managed_refusals": { + "apply": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "child_inspect": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "child_run": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "decide": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "inspect": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "prepare": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "reused_create": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + } + }, + "outer_state_version": 3, + "physical_subject_head": "07171b63393b7418ee2aea28519e6e052f1c26b9", + "recovery_disposition": "imported", + "replay_disposition": "imported", + "snapshot_bytes": 788858 + } + ] + }, + "v26.8.2": { + "raw_packet_sha256": "ef6bdd2b0f48ed6188565c48c1d886596d191c7def568a600acc0b2e9fd24e11", + "sqlite": "3.51.0", + "cases": [ + { + "accepted": [], + "blobs": [], + "case": "held", + "child_revision": 2, + "child_root_digest": "46561bc239e4cb212cdcf46a5577aa175c0fc61ddebb7569179a56455516676e", + "effect_file_sha256": "a0cb50ef664c14794b50531c2ed4c9d9e57aabde1e1ecb22d0c1d9f8df06fefa", + "execution_revision_before": 3, + "execution_revision_recovered": 3, + "file_hashes_before": { + ".threadloop/state/state.db": "57d9ce239569268790db87ca221cd370f3203779f8961fb6cc78922ccdcec74f", + ".threadloop/state/workflow-execution-1190da3b473e81f20eee371fbb640d78/executor.sqlite": "e8380cfc79778f77375d29aed6ee8a5f7dfdc53f226f4504da1f42ae29732acf" + }, + "file_hashes_restored": { + ".threadloop/state/state.db": "57d9ce239569268790db87ca221cd370f3203779f8961fb6cc78922ccdcec74f", + ".threadloop/state/workflow-execution-1190da3b473e81f20eee371fbb640d78/executor.sqlite": "e8380cfc79778f77375d29aed6ee8a5f7dfdc53f226f4504da1f42ae29732acf" + }, + "import_events_after_backup": 0, + "import_events_after_recovery": 0, + "import_events_restored": 0, + "initial_observation": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "execution_outstanding" + }, + "invocations_after_recovery": 1, + "launches": 1, + "legacy_version_after_backup": 1, + "legacy_version_restored": 0, + "observations": [ + { + "envelope_sha256": null, + "id": 1, + "status": "exit_failed", + "stderr_sha256": "8e9475953db5168b536053519c61cedbb4bfec8add48d4ff1425080f4b0de981", + "stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + ], + "old_managed_refusals": { + "apply": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "child_inspect": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "child_run": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "decide": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "inspect": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "prepare": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "reused_create": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + } + }, + "outer_state_version": 3, + "physical_subject_head": "9604d74bd02bc2eb74fb253b0f8a26814fd96a60", + "recovery_disposition": "execution_outstanding", + "replay_disposition": "execution_outstanding", + "snapshot_bytes": 798218 + }, + { + "accepted": [ + { + "admission_digest": "e5d61f3e63d5bb6a2648e66bcc3bdf615c4700c4a0fefcc666635ca4c7262e44", + "envelope_sha256": "eeb64d6b2e675c5d81bda03a5345c1bbfa58cba085619470cc7916b6928f3ab1", + "observation": 1, + "predicate_sha256": "6e557d664aebcc47292599a50808deb4776e6c4ee8b98e4cff9c32e6435780e4", + "result_sha256": "35e49567066d9822c3ebe8f2db914cf7e76f0ca850af575f59f4bfc9655023d8", + "signature_count": 1, + "source_digest": "f2fe4966cf0542e7f6cc52e667df097f5dfa1b8c3152a6d187cb7213471f9709", + "source_id": "threadloop_attempt_fb4105e371c23c5181d55ba4f0d1f5664783415a325608b6fb8c13e02450b8f9" + } + ], + "blobs": [ + { + "bytes": 21, + "id": "sha256:0c5d8c89ef623535e4f3df8b5879e5256b52d5a54adc9c602c418391eacb21b1", + "sha256": "0c5d8c89ef623535e4f3df8b5879e5256b52d5a54adc9c602c418391eacb21b1" + }, + { + "bytes": 33, + "id": "sha256:6ccd87ea7aa30b553ada852e153b2fce021e7a53caaf18a27a3a54ac0e38fe4d", + "sha256": "6ccd87ea7aa30b553ada852e153b2fce021e7a53caaf18a27a3a54ac0e38fe4d" + }, + { + "bytes": 159, + "id": "sha256:ec49d61914a4e032e0444dafa9e0567db757ec7094b67aae09f874ded1fb57cd", + "sha256": "ec49d61914a4e032e0444dafa9e0567db757ec7094b67aae09f874ded1fb57cd" + } + ], + "case": "admitted", + "child_revision": 3, + "child_root_digest": "7338054f2d86e639c8cf6007bc0854641c076c4c460bfa9a6d0d1de17bd51148", + "effect_file_sha256": null, + "execution_revision_before": 2, + "execution_revision_recovered": 3, + "file_hashes_before": { + ".threadloop/state/state.db": "3374de8eb8ab6c0a56c340a9eee6cf28ffe8577ba0b923ab7419e46a966ff451", + ".threadloop/state/workflow-execution-77fc4c8250df0fafbe894752661a4647/executor.sqlite": "53f958f90bd38d5bff937a08ecab4d3fea8b04301d80d6493db9de34bf61c3a5" + }, + "file_hashes_restored": { + ".threadloop/state/state.db": "3374de8eb8ab6c0a56c340a9eee6cf28ffe8577ba0b923ab7419e46a966ff451", + ".threadloop/state/workflow-execution-77fc4c8250df0fafbe894752661a4647/executor.sqlite": "53f958f90bd38d5bff937a08ecab4d3fea8b04301d80d6493db9de34bf61c3a5" + }, + "import_events_after_backup": 1, + "import_events_after_recovery": 1, + "import_events_restored": 0, + "initial_observation": { + "observed_boundary": "managed-cut=admit", + "signal": "SIGKILL" + }, + "invocations_after_recovery": 1, + "launches": 1, + "legacy_version_after_backup": 1, + "legacy_version_restored": 0, + "observations": [ + { + "envelope_sha256": "eeb64d6b2e675c5d81bda03a5345c1bbfa58cba085619470cc7916b6928f3ab1", + "id": 1, + "status": "ok", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stdout_sha256": "5741f342d4c86e77c94d3bfff7d1a53a60fa4afcedadcfc80592d37cd816d899" + } + ], + "old_managed_refusals": { + "apply": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "child_inspect": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "child_run": { + "code": "EXECUTOR_REJECTED", + "exit": 1, + "reason": "state.version" + }, + "decide": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "inspect": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "prepare": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + }, + "reused_create": { + "code": "WORKFLOW_RUNTIME_UNSUPPORTED", + "exit": 1, + "reason": "unsupported_workflow_setup" + } + }, + "outer_state_version": 3, + "physical_subject_head": "69a80cc2fdbb90e1aa0c6307233d20380705152a", + "recovery_disposition": "imported", + "replay_disposition": "imported", + "snapshot_bytes": 788843 + } + ] + } + } +} diff --git a/docs/evidence/issue-172-native-execution.json b/docs/evidence/issue-172-native-execution.json new file mode 100644 index 0000000..989bd0d --- /dev/null +++ b/docs/evidence/issue-172-native-execution.json @@ -0,0 +1,130 @@ +{ + "implementation": { + "revision": "80e091c9f6412195a8444f048add977d648c4115", + "tree": "987ef4aeda6bb371b0c2f476a3dbeae9467d89ec", + "lock_sha256": "70e168ee4e6df299cd1e1b52e3609699f54eff5e892d6c0afcc1ea498194e7c2" + }, + "gaap_commit": "0a82687d6070081e0a5cb613698f0724dc6f00cb", + "binaries": { + "goose_sha256": "sha256:4b8258c24adad9e07957d1dddfc7d965b97883dce2eff64af7e3d3c005655d81", + "implementation_digest": "sha256:42305ab1ebed503c68ce6796fe1a9f6a727ca4442809b76c7daa261f124054db", + "attestor_digest": "sha256:d1ee3ef7e8e40d147d7aec1ff34c1a0af3b11b0618a39a2517f35fd5af10f257" + }, + "os": "macOS-26.6-arm64-arm-64bit", + "source_inputs": { + "file_count": 296, + "digest": "4428f2fb639e6b0c8ff9dbdfe90981e166372813ddc696a368ef21f79bf7c4fb" + }, + "installed_package": { + "package_sha256": "36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51", + "cli_sha256": "610e586afd19fd85e0b2adade639b88a98213a039cb980772f72a65ded4cdc22" + }, + "provider": "deterministic local provider", + "signing": "public fixture key", + "cases": [ + { + "goose_sha256": "sha256:4b8258c24adad9e07957d1dddfc7d965b97883dce2eff64af7e3d3c005655d81", + "goose_version": "1.54.0", + "implementation_digest": "sha256:42305ab1ebed503c68ce6796fe1a9f6a727ca4442809b76c7daa261f124054db", + "attestor_digest": "sha256:d1ee3ef7e8e40d147d7aec1ff34c1a0af3b11b0618a39a2517f35fd5af10f257", + "controller_request_digest": "319ed123fb1611e1f6f38d42a92ac000d92a47d84add2e55562c1c2d460dc30c", + "executor_request_digest": "f46403f5f3ec2a2af9fd1418bbbc16e62ba8ed4c640fdefe587886fac587be93", + "claim": { + "id": "0e94f108-b0e3-4852-a2c6-9268ec4235b3", + "version": 1 + }, + "attempt_id": "8a587440-8b89-47ce-becf-b4560e34594b", + "attempt_status": "succeeded", + "admission_digest": "27d12a9c57b34615b3964f4c0d35c2d2a246090647415c52806271d9a94b4ded", + "launch_count": 1, + "source_id": "threadloop_attempt_e64101e1baa22be733034e28062001a1ddd294fa20c7e92e32a916eff3590f88", + "provider_requests": 5, + "provider_transcript_sha256": "881121e831020101b6a8dfa8a2ca270867f8783815dee51d183afc50b535a663", + "provenance_sha256": "67de0b2276e82ae7d154358219273aa3664a8ce3f054b35c1dbbea3bbf199c08", + "package_sha256": "36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51", + "source_inputs_sha256": "4428f2fb639e6b0c8ff9dbdfe90981e166372813ddc696a368ef21f79bf7c4fb", + "final_state": "verifying", + "final_version": 4, + "subject_commit": "7897c380886b00c4510def0f8b28869811da3829", + "envelope_sha256": "585ec6c34b29f3ff612178a0509b578f8b77ff9235a8bcb9a1710340dafd1982", + "signed_predicate_sha256": "a3b7458c9001c840af98d7986105a9024db50c3ce1198e8738be1d3cce7ecb91", + "key_id": "gaap-goose-public-fixture-only", + "kind": "managed", + "case": "allow" + }, + { + "goose_sha256": "sha256:4b8258c24adad9e07957d1dddfc7d965b97883dce2eff64af7e3d3c005655d81", + "goose_version": "1.54.0", + "implementation_digest": "sha256:42305ab1ebed503c68ce6796fe1a9f6a727ca4442809b76c7daa261f124054db", + "attestor_digest": "sha256:d1ee3ef7e8e40d147d7aec1ff34c1a0af3b11b0618a39a2517f35fd5af10f257", + "controller_request_digest": "ec5b409e2dbce3c2337129c717a9321e4e0aef4fd46fa4f11c8ca0b4318159f7", + "executor_request_digest": "8824b54e6ec4f911628714982a19a46ff21dba88895e7696cbab3f6b00edc331", + "claim": { + "id": "0c534839-ad3b-4c8f-84ed-d47128f9b51f", + "version": 1 + }, + "attempt_id": "263b048c-bcaa-4a31-aa86-06123f1ca975", + "attempt_status": "unknown_outcome", + "admission_digest": "d0ed209cefb78b0d12d95c59e430d2cda17c55465f0133afd702765a75506488", + "launch_count": 1, + "source_id": "threadloop_attempt_c62f85f78e5204825f29a43aaa60aae22582a7caf6cc45a51aa7e36b6787fb5a", + "provider_requests": 5, + "provider_transcript_sha256": "90482252b55b6ee2aabc0e644ea5576ebf3adf36501e75e69486d74d2c3941ff", + "provenance_sha256": "e1b458f53c0101848d8d02a7b7a15dec9072ecc9baa34d1ed8555a2187685106", + "package_sha256": "36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51", + "source_inputs_sha256": "4428f2fb639e6b0c8ff9dbdfe90981e166372813ddc696a368ef21f79bf7c4fb", + "final_state": "implementing", + "final_version": 3, + "subject_commit": "4388142f60db37f4a59c4f4e5b7e3814f88aa42c", + "envelope_sha256": "cfae68186f3ca794c4cf76c45b10bd285e01ba8f1a52cf814487c1209ffbaed3", + "signed_predicate_sha256": "1dd55cf3c8dcb713ed56ba0cb4bd28f687495af7bfcde811baa288d5baed4307", + "key_id": "gaap-goose-public-fixture-only", + "kind": "managed", + "case": "bad_patch" + }, + { + "provider_requests": 5, + "signer": "gaap-goose-public-fixture-only", + "provenance_sha256": "d908a783609a918bdc4412ae6d511b03e1f725272c634235bbe305a54bfc71da", + "inspection_sha256": "bfbc3b195d805fff83858a95aa47bca1690a168d5264d508526cfc61b536f432", + "transcript_sha256": "a573a5b3547592cf3186638c4cc08eb5ed59853e2a2ddfb7b408d852afe181ae", + "result_sha256": "9df083cbcc0d1bd498f321e6a5762fbee8bac976c463fbe036a0af13e84036cd", + "envelope_sha256": "ee00dc558d075f99fbc2b9c8aa0fa2490dd740936679e0bab2f0ef673d86a5e2", + "admission_digest": "7265e88fc094898d23c9ccebd2e4621a2e060ea935a97d4c04f90ab2d55f69f7", + "state": "implementing", + "state_version": 2, + "launches": 1, + "admissions": 1, + "request_status": "satisfied", + "attempt_status": "succeeded", + "execution_status": "idle", + "attempt_id": "6e2f7365-7406-468c-80bb-90317258030b", + "signed_predicate_sha256": "e17ad9188b6aa165b3c9d383a6361673ade788e385cdeb39557c619a9263a5c3", + "key_id": "gaap-goose-public-fixture-only", + "kind": "standalone", + "case": "allow" + }, + { + "provider_requests": 5, + "signer": "gaap-goose-public-fixture-only", + "provenance_sha256": "6a909df59f6261451e0f77d24cbbd7c9707081239ba2c76fd8036136bcdec420", + "inspection_sha256": "c811727a8470eb3d5a5addca621ba8afa9905edcd804c3bfd6122343a941a455", + "transcript_sha256": "d7a8b0bdc972e9076059f60dceb08f8ad5203eb579f7a7c1c891c0e640299b16", + "result_sha256": "e0db2f3a0ca7c0524fc1293a300df70625cab5bae784409d95ddc040616ac5cc", + "envelope_sha256": "5416b178e67be82ca26b3015ce69db521d127ee36bd7e234d32f810609891091", + "admission_digest": "6966820dcdf2aa1b39439afac329d17fd56e4658f00ec3654d7ce9599acc41fa", + "state": "implementing", + "state_version": 2, + "launches": 1, + "admissions": 1, + "request_status": "open", + "attempt_status": "unknown_outcome", + "execution_status": "reconciliation_required", + "attempt_id": "47573497-fa59-4666-ada8-24e26f13da5b", + "signed_predicate_sha256": "795b778b5de28c7308b8576d0ace7a03d655a34cc07d9d9a6c94e52eaa24e008", + "key_id": "gaap-goose-public-fixture-only", + "kind": "standalone", + "case": "bad_patch" + } + ] +} diff --git a/docs/plans/issue-172-controller-conformance-and-parity.md b/docs/plans/issue-172-controller-conformance-and-parity.md new file mode 100644 index 0000000..c8aba66 --- /dev/null +++ b/docs/plans/issue-172-controller-conformance-and-parity.md @@ -0,0 +1,413 @@ +# Issue 172 Controller Conformance and Pre-Rust Parity Build Plan + +## Summary + +Prove the TypeScript controller through an independent process, show recovery from interrupted execution, and measure +what a later Rust implementation must preserve. Deliver the subject, reproducible proof and readiness report in one +ThreadLoop PR. The separate live proof needs an authorized fixture PR and an independent person's decision. The Rust +replacement belongs to M003. [Issue #172](https://github.com/nnennandukwe/threadloop/issues/172) · +[Program #168](https://github.com/nnennandukwe/threadloop/issues/168) · +[Runtime gate #110](https://github.com/nnennandukwe/threadloop/issues/110) · +[Storage #85](https://github.com/nnennandukwe/threadloop/issues/85) · +[M003](https://github.com/nnennandukwe/threadloop/milestone/3) + +| Predecessor | Inspected evidence | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| #85 storage | PR #173 merged as `8014d80acc8b6209560f2d6df5c9cf450544c4f2`. [PR](https://github.com/nnennandukwe/threadloop/pull/173) · [CI](https://github.com/nnennandukwe/threadloop/actions/runs/44950980593) · [Security](https://github.com/nnennandukwe/threadloop/actions/runs/44950980567) | +| #169 selector | PR #174 merged as `0694d0c50143aa4dd2799586456aa5a18008514f`. [PR](https://github.com/nnennandukwe/threadloop/pull/174) · [CI](https://github.com/nnennandukwe/threadloop/actions/runs/44956272381) · [Security](https://github.com/nnennandukwe/threadloop/actions/runs/44956272369) | +| #170 Workflow Runs | PR #176 merged as `bdf68cc2d3ad915d085aecff47c9181f65fb5205`. Its tree matches reviewed `31388a07566350dfeddc30578d43b8926d5b4e22`. [PR](https://github.com/nnennandukwe/threadloop/pull/176) · [CI](https://github.com/nnennandukwe/threadloop/actions/runs/44961637392) · [Security](https://github.com/nnennandukwe/threadloop/actions/runs/44961637374) | +| #171 managed execution | PR #177 merged as `50b3aa61f92bbc1e03b3177683e16aa199a3dd7b`. Its tree `493ec2647f40b295a123ded829592a20c551a4be` matches reviewed commit `ca713573e1ffc0c60ad4be34c58638804c65a4c9`. Hosted Qodo run 2091862 completed at that commit. All 8 required jobs passed. [PR reviews](https://github.com/nnennandukwe/threadloop/pull/177/files) · [Reviewed source](https://github.com/nnennandukwe/threadloop/tree/ca713573e1ffc0c60ad4be34c58638804c65a4c9) · [Merged base](https://github.com/nnennandukwe/threadloop/commit/50b3aa61f92bbc1e03b3177683e16aa199a3dd7b) · [PR CI](https://github.com/nnennandukwe/threadloop/actions/runs/44988350617) · [PR Security](https://github.com/nnennandukwe/threadloop/actions/runs/44988350578) · [Main CI](https://github.com/nnennandukwe/threadloop/actions/runs/45016894891) · [Main Security](https://github.com/nnennandukwe/threadloop/actions/runs/45016894836) · [Expiry commit points](https://github.com/nnennandukwe/threadloop/blob/ca713573e1ffc0c60ad4be34c58638804c65a4c9/docs/plans/issue-171-managed-workflow-execution.md#expire-an-overdue-managed-claim) · [CLI refusal tests](https://github.com/nnennandukwe/threadloop/blob/ca713573e1ffc0c60ad4be34c58638804c65a4c9/tests/integration/workflow-execution.test.ts) · [Qodo response parser](https://github.com/nnennandukwe/threadloop/blob/ca713573e1ffc0c60ad4be34c58638804c65a4c9/src/services/workflow-collection.ts) · [Provider response fixture](https://github.com/nnennandukwe/threadloop/blob/ca713573e1ffc0c60ad4be34c58638804c65a4c9/tests/integration/workflow-collection.test.ts) · [Local review object formats](https://github.com/nnennandukwe/threadloop/blob/ca713573e1ffc0c60ad4be34c58638804c65a4c9/docs/plans/issue-171-managed-workflow-execution.md#collect-local-reviews-in-sha-256-git-repositories) | + +At `ca713573e1ffc0c60ad4be34c58638804c65a4c9`, local auto-depth review operation `d2d40a8b-1768-4aa1-82de-7d276a8f0cb2` +completed in incremental mode with complete reported coverage. Qodo lists recommendation `0800154c` as dismissed. The +exact-head review lists recommendation `1a56a90a` as pending. Two Qodo CLI responses for the same missing operation +contained the same U+2014 delimiter and different trace IDs. Rule 576985 permits clearly marked protocol data. Comments +above the parser and its integration fixture identify that delimiter. The parser matches the measured prefix and the +fixture preserves the full provider message. The Qodo triage receipt for `0800154c` records reason `intentional` and +reports pending downstream synchronization. Qodo skipped spec-agent. The native check passed 940 tests in 75 files, +including build and package smoke. The controller suite passed 65 tests. The dependency audit reported zero +vulnerabilities. On Node 22.22.2, 24.20.0, 26.8.2, installed clients passed 129 cross-version calls and 6 signed-fixture +cases. Both managed native cases used the measured tarball, SHA-256 +`580e41c90245af236df32d908ea4387996a8261f02f6dbf5ea5da380f8c087bb`. The first two-worker run found zero +invocation-counter entries at the observation interruption. The isolated case and the full one-worker rerun passed on +the same commit. The first run didn't retain the child's transport status. On Node 26.8.2, the host check accepted two +environment configurations and refused six unsupported configurations. An older run kept its recorded state after +dispatch refused its unsupported setting. The signed producer launched once, admitted one result and returned it on +replay. Host proof SHA-256 `74fc0364ebdf81a7d188c0e40240288485cc395dbf55bd5e3d6d7f78a86d235d`. Managed hosts accepted an +empty argument list. Both native controls used two measured file arguments. Creation refused three unsupported argument +forms. An operator could still inspect an older run whose arguments prevented execution. That run recorded zero +execution reservations. Five refused operator commands preserved the child and outer database heads. The eligible expiry +replayed with the same result. Expiry packet SHA-256 `56eb411b8e67d818ba72c57b9e77cf88437b1b51539cb690a6a09c625dea3164`. +The packaged CLI admitted one fixture review for a real SHA-256 Git repository and replayed it after reopening. +Independent object hashes matched the accepted base, head and tree. Substituting any one of them left the receipt count +at one and the run at implementing/v3. The fixture used a local status reader with GitHub sensors disabled. Git object +proof SHA-256 `4e777606b30b36dbe07d15b24d1da5c2391b6c23ae8172da63284a6e16325026`. Hosted Qodo run 2091688 at `9b71c05` +listed interpreter finding `e6ee99a6` as pending. Run 2091862 at `ca71357` lists it as implemented. + +## Skills To Use + +| Stage | Skills and work | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Plan and contracts | Use software-build-plan, qodo-get-rules and qodo-codebase-wisdom to check the actual base and applicable rules. Apply producer/consumer coordination and exhaustive enum handling to the subject and its packet. | +| Implementation | Use tdd and failure-path-testing for public process, reducer, importer and CLI behavior. Use transaction-proof and sqlite-concurrency-hardening for the shared root reader/writer, independent connections and commit cuts. Use workflow-invariants for witness freshness and human authority, and cli-interactive-parity for the installed surface. | +| Delivery | Use qodo-review and qodo-review-resolver on the complete intended change. Use voice-canon and verify_language.py for the plan, report, PR and evidence summaries. | + +Qodo returned ten scoped rules for the external protocol and journal changes. Rules 1060877 and 1060865 require +coordinated producer and consumer validation and exhaustive handling of the frozen result types. Rules 1060879, 1060863, +1060853, 1060851, 1060843, 1060842 and 1060888 apply if a shared field, parameter, alias or configuration name changes. +The A2UI message rule has no applicable message type here. Existing dependency pins and established names carry forward. +Qodo Codebase located request construction and response checking in RunInvariant and root reads, writes and commit +markers in ThreadLoop. The lookup omitted resolved commit IDs. Direct Git reads at the pins below verified those entry +points. +[External checker](https://github.com/nnennandukwe/run-invariant/blob/54be0d2240c44ee11b65d5e278a2cb667ee523b4/src/threadloop/runner.js) +· +[SQLite owner](https://github.com/nnennandukwe/threadloop/blob/50b3aa61f92bbc1e03b3177683e16aa199a3dd7b/src/adapters/fs/gaap-state.ts) + +## Scope + +Deliver a production-backed external controller subject, all 38 frozen cases, independent SQLite and native failure +proof, the governed completion result, and parity and rollback measurements. Use the accepted graph, ordinary storage +generation, execution and evidence contracts. Preserve the legacy CLI, runner, audit/export bytes, historical graph +bindings and independently owned GAAP, RunInvariant and contracts checkouts. The separately authorized GAAP roadmap owns +GAAP source changes. This build uses the current TypeScript package, existing processes, SQLite and CI. + +## Package Layout / File-to-Task Mapping + +| Owner | Change or call | +| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scripts/controller-conformance/` | Small subject, build entry and parent-side proof launcher. Ship a reproducible revision-bound artifact via the source checkout. Build with `node scripts/controller-conformance/build.mjs --output NEW_DIRECTORY`. The runner launches `node BUILD/runtime/scripts/executor-contract/subject.mjs conformance`. Sibling identity, manifest and build metadata stay with the parent. Existing CLI contracts keep their own entry points. | +| `src/domain/workflow-controller.ts` and public contracts exports | Route normalized graph input to `compileWorkflowProfile(JSON.stringify(input))`, decision input to `selectWorkflowDecision(input)`, and execution inputs to the public execution reducers used by ThreadLoop. | +| `src/adapters/fs/gaap-state.ts` and its SQLite root storage | Extract the canonical single-row read/write already used by the executor. Share those functions with the case store. Preserve GAAP's root schema, owner checks, commit-generation readback and signature/blob transaction. | +| `src/services/gaap-executor.ts`, `workflow-evaluation.ts`, `workflow-execution.ts` and workflow stores | Exercise the actual launch, signed admission, pure reevaluation and deliberate apply in native and persistence tests. A subject case uses its own frozen authority inputs. | +| Existing controller, managed execution and store integration tests, `scripts/prove-gaap-goose.{py,ts}`, `scripts/smoke-pack.mjs` | Extend the smallest missing boundary test. Reuse the existing native fixed and `--workflow-run` modes. Package comparisons use physical installs. | +| `docs/pre-rust-readiness.md`, `docs/architecture.md`, `docs/plans/issue-172-controller-conformance-and-parity.md` | Track the plan, findings, requirement-to-evidence index and measured status. Track the small proof drivers or their equivalent in `scripts/` after review so reproduction works from a clean checkout. | + +## Dependencies And Settings + +Retain the existing locked Node/TypeScript/npm/SQLite stack. Support Node 22.22.2+, 24.15.0+ in their respective majors, +and Node 26+. Verify each actual runtime and package. Use a fresh bounded directory for each proof and reclaim only its +fixtures. Recheck available disk before installs or native output. Preserve existing caches and worktrees. + +| Input | Pinned identity | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Contracts | `v0.1.0` commit `7dcf432bc75a68b5ee803c6ebb7346b6bb417f83`, installed commit `4ed9a94a2a089b9ae950d93297f7a6b9b939d3a6`, common `docs/contracts` tree `ab807daea6e0c81786f92b82fdaad1e50db6418c`. | +| RunInvariant | `54be0d2240c44ee11b65d5e278a2cb667ee523b4`. Its `threadloop/pin.json` SHA-256 is `96f21b9265d2045d3e9273d4b53ba24a208a7cd00cff0a2dee9636447b27179f`. Corpus source is ThreadLoop `fde510deca780c7cada8a2e461bd15af0fe4ae88`. | +| Corpus and compatibility | Corpus digest `11620588c6f4b39353ea9f77e361a50b5cb0dc970410b1ac10aa8bef13efad84`. Compatibility digest `9590ab51c9081ee2c43f67c0ed1b3453588acdda0e63f259827625971643eadf`. Verify all eight conformance schemas by name and hash and all 18 domain schemas in the descriptor. Retain inventory, input and fixture digests in the parent packet. | +| Native binaries | The #171 managed cases used GAAP `0a82687d6070081e0a5cb613698f0724dc6f00cb` and Goose 1.54.0. The host, attestor and Goose SHA-256 values were `sha256:42305ab1ebed503c68ce6796fe1a9f6a727ca4442809b76c7daa261f124054db`, `sha256:d1ee3ef7e8e40d147d7aec1ff34c1a0af3b11b0618a39a2517f35fd5af10f257` and `sha256:4b8258c24adad9e07957d1dddfc7d965b97883dce2eff64af7e3d3c005655d81`. Recheck the actual binaries and transcript for each applicable native case. | + +## Canonical Contracts + +### Process and authority + +One process reads one bounded canonical UTF-8 JSON request through EOF and emits one canonical response on stdout. +Operational diagnostics use stderr. The protocol is `threadloop.controller-conformance/0.1`, with the frozen request, +response, fixture, canonicalization and digest profiles. Reuse `parseExecutorMessage` and `canonicalExecutorJson` from +the public executor codec, enforce the published closed schemas, recompute `input_digest` and `request_digest`, and +return the request digest, independently measured subject identity, result and recomputed response digest. Malformed +framing, unknown versions, duplicate keys, unexpected fields, mismatched identities or digests fail before dispatch. +Valid transport with an invalid domain document yields its ordered `{code,path,identifier}` diagnostics. The pinned +transport permits 10 seconds, 16 MiB plus one byte on each of stdin and stdout, and 1 MiB on stderr. +[Frozen process contract](https://github.com/nnennandukwe/threadloop-contracts/tree/v0.1.0/docs/contracts/controller-conformance-v0.1) + +The parent checks the corpus manifest and expanded input, launches the subject, validates nested identities and compares +the machine result. The subject sees operation and domain input. Case ID and corpus ID serve envelope correlation only. +Retain selection order, including the generally applicable completion-witness ordering in 011 and exhaustive +`AMBIGUOUS_REMEDY` in 024. The harness handles blocked-reason prose and enclosing decision digest according to its +frozen comparison. Preserve the frozen outcomes if an implementation discrepancy appears. + +Bundle the subject and embedded wire schemas using a clean exact revision and matching lockfile. The runtime artifact +consists of the ESM bundle and two published GAAP upstream schemas, `agent-run-request.schema.json` and +`terminal-run-receipt.schema.json`, at the module-relative paths used by the codec. Compute each file's hash and length. +Sort by relative path, then hash the UTF-8 canonical JSON array of `{bytes,path,sha256}` entries without a trailing +newline. The operator's identity JSON names subject, version, revision and `artifact_digest`. The subject measures its +own explicit runtime list. Record Node, launcher, sandbox policy and build-input manifest separately. Embed the +published execution-scenario wire schema in the bundle. Dispatch only the operation and domain input. Changing a valid +case label must preserve the domain result. If bundling exposes another runtime file, identify it, measure it and review +the closure before execution. + +PR #179's first hosted review identified two installations outside Git's clean-tree check. A local rebuild could use the +same installed packages as the submitted build, and the parent could load the harness's existing dependencies. The +independent proof must stage the exact source revisions, install their lockfiles into fresh directories and use that +harness for inventory, execution and controls. The pinned contracts Git package needs its generated distribution. Build +it from the exact contracts checkout with the contracts lockfile and its tracked build script. Use that output in the +isolated ThreadLoop install. Compare the submitted runtime to the independently built artifact before scoring. Record +all three source revisions, lock identities and the contracts build step. Test this through the proof command with an +inert difference in a disposable installation. +[Hosted finding](https://github.com/nnennandukwe/threadloop/pull/179#discussion_r4658087972) + +Use the tested macOS isolated launcher with a fresh per-case scratch directory, explicit runtime reads, restricted +environment, closed inherited file descriptors, confined writes and disabled network. The parent retains the checkouts, +fixtures, shared values, golden vectors, synthetic subject, operator identity and output packet. Recheck the three +runtime files, a kernel-denied read for the fixtures and the five-file negative control after building the final +artifact. Inspect the actual bundler inputs and run controls against existing denied files. At the #170 preflight, four +isolated transport calls compiled graph `22fb31abcf828c86c0c299eed82bc0d196285a62a9875bfd96fa3d5580202234`, selected an +engineering action, returned `AMBIGUOUS_REMEDY`, and reopened a replayed registration. The kernel denied five forbidden +reads. The three-file artifact digest was `ec5902d1c871f206e4ddcd90bc8d8048e2406e381523ae108a92ee8814fe7258`. Full wire +validation, production persistence and the 38-case final artifact still need measurement. + +### Frozen case inventory + +Each numbered entry is a `case_NNN` from the pinned manifest. This inventory belongs in the plan and parent-side report. +The adapter must remain independent of it. + +| Operation | Cases | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Graph compilation (3) | 001 governed PR identity, 002 unreachable terminal, 003 uncontrolled cycle. | +| Decision (25) | 004 required action, 005 refresh stale evidence, 006 independent proof, 007 review evidence, 008 available transition, 009 human approval, 010 human merge, 011 completion, 012 terminal, 013 stale observation, 014 unsupported capability, 015 waiting, 016 expired claim, 017 unknown execution, 018 setup handoff, 019 repair-budget handoff, 020 human release handoff, 021 publication, 022 admitted repair, 023 commit repaired work, 024 equivalent remedies, 025 mutation after verification, 026 higher-sequence expired proof, 027 reversed receipt arrival, 036 completed Agent Run still needs outer proof and approval. | +| Execution scenario (10) | 028 exact redelivery, 029 competing executor A first, 030 B first, 031 running-claim expiry, 032 late receipt after replacement, 033 unadmitted GAAP report, 034 independent success admission, 035 request identity conflict, 037 same-revision acquisition A first, 038 B first. | + +### Opt-in live governed completion + +Use the dedicated small shipping-quote fixture in `nnennandukwe/threadloop`. The Unit 5 delivery tree exceeds the +physical GAAP profile. The measured #171 base contains 434 tracked paths. GAAP checks the full checkout and index within +64 descendants, eight levels and 8,192 bytes per file. Keep code, file modes, caller and test inputs in the measured +fixture. Keep both databases, dependencies and proof outputs outside it. + +Submit the prepared route decision inside the owning chat before any new public action. It requests authorization for a +reviewed caller enablement PR from `proof/issue-172-evidence-caller` if needed, the dedicated base +`proof/issue-172-parity-base`, feature `proof/issue-172-shipping-quote`, one fixture PR into that base, one scoped full +Qodo review and bounded signed observations. Identify the author, willing independent GitHub User and their node ID, +dispatcher and merger. The reviewer decides after the actual PR and head exist. A route approval can't supply their +review. Preserve both refs through collection. The operator will retain the approval or refusal with the exact proposed +refs and budget. [Issue #172](https://github.com/nnennandukwe/threadloop/issues/172) + +The proposed fixed caller installs at `.github/workflows/issue-172-evidence.yml`, 2,753 bytes, SHA-256 +`06d652b423560f20ec4aa91b56e362a9785611a2220e663428f470583cc1e50c`, Git blob `b3f7d34e735db4455eb7b455ed059df8ebbcc7a8`. +Confirm the reviewed default-branch installation and identical base and feature bytes. Its gate and review sensors both +pin `bdf68cc2d3ad915d085aecff47c9181f65fb5205`. Bind both build-signer URIs to those paths and SHA, the GitHub Actions +OIDC issuer and the exact feature-ref caller certificate. Use run `session_wf_issue172_shipping`, gate `shipping_quote`, +command `["python3","-B","-m","unittest","-v","test_shipping"]`, working directory `.` and 30,000 ms timeout. Private +actionlint 1.7.12 accepted the caller. Verify the eight independent quote examples and preserve the test/caller bytes +while committing only the intended changes to `shipping.py`, `terminal.txt` and `mcp.txt`. Before enablement, present +the complete caller bytes with the recorded SHA-256. +[Reviewed reusable workflows](https://github.com/nnennandukwe/threadloop/tree/bdf68cc2d3ad915d085aecff47c9181f65fb5205/.github/workflows) + +Bind the real repository, proof base, approved reviewer, setup/2 enrollment, local and independent gate, immutable proof +plan, GAAP host, Qodo reader and `host_producers` declarations. Record actual feature head H, tree, content digest, +effect, claim/Attempt and signed child admission. Collect the fresh local gate and full Qodo review at the enrolled +base, H and tree. Before each dispatch prepare a specific signed observation on the current run and compare its session +ID, prepared receipt ID, plan digest, subject H and gate or PR target to the caller inputs. + +The budget allows one gate and up to three review dispatches, eight standard jobs, 570 configured runner-minutes total, +zero new spend. Count failed and uncertain dispatches. Check an uncertain run before retrying. Use one preparation/key +per observation and retain signed packages before expiry. Verify trust, subject, policy, timing and receipts at import. +Present the actual PR URL, H, current gates, findings and authority to the reviewer in this chat. An eligible GitHub +User must approve H. The authorized merger checks the same H and merges into the proof base. After signed observation of +that merge and `merged_at`, decide, explicitly apply completion, and reopen the run. Changed H, expired evidence, budget +exhaustion or a declined review leaves the live row pending. Preserve head H for post-merge collection. + +## TDD And BDD Implementation Strategy + +1. Start with a failing public request/response test. Compile an independently authored alternate graph. Mutate its + opaque case ID and reseal the envelope. Check that only the correlation changes. Add one decision at a time, + including the tie, human handoff and terminal cases. +2. Reproduce the execution boundary with one registration. Persist it, reopen, replay it and inspect the row + independently. Add a real rejected operation, then an identity conflict, receipt fencing and a racing stale proposal. + Drive production reducer behavior from normalized input. +3. Run the external suite once the subject handles all three operations. Check that an isolated deliberately wrong + result is rejected by the parent. Keep mutation controls and oracle files outside the production build. +4. Run the four native paths, persisted interruption checks and installed rollback. Record the same request, Attempt, + source and lifecycle head from independently reopened stores. Execute authorized live stages as their prerequisites + become available. + +## Component Design + +`execution_scenario` has exactly `initial`, `steps`, `admitted_digests` and `projection_snapshot`. Use the unique +supplied digests as a read-only case authority. Preserve step ordering and each original actor, ID, time, context, +expected revision and expected digest. Call `createExecutionJournal` for creation, `applyExecutionOperation` for each +step and `projectExecution` after reopening for final projection. The reducers replay and authenticate the prior data. +Stop on validation diagnostics. Map successful results to the published step fields and projection fields, including +rejected receipts, identity conflicts and all controller execution fields. The ordinary GAAP helper generates IDs and +grants admissions after its own checks. The managed evaluator admits a projection from a physical observation. Both stay +on the production host side. +[Host operations](https://github.com/nnennandukwe/threadloop/blob/50b3aa61f92bbc1e03b3177683e16aa199a3dd7b/src/services/gaap-executor.ts) +· +[Frozen reducers](https://github.com/nnennandukwe/threadloop-contracts/blob/4ed9a94a2a089b9ae950d93297f7a6b9b939d3a6/scripts/execution-contract/model.ts) + +Use `readSealedRoot(db): { value: unknown; digest: string }` and `writeSealedRoot(db, value, expectedRowDigest?): void` +inside each owner's synchronous SQLite transaction. The shared read verifies the bytes, row hash and canonical encoding. +A conditional write must update exactly one row. On the host, keep v1/v2 validation, managed owner, root revision fence, +commit marker and blob/receipt/journal admission in the original transaction. The subject creates a private case +database and never dispatches a process. After creation, open a fresh connection per step, use `BEGIN IMMEDIATE`, and +check the returned model `expected_execution_digest` against the loaded journal. The SQLite compare-and-swap uses the +digest of the whole stored row. A model-proposed rejected or conflicting append is durable. Exact replay writes no new +root, event or marker. Return each result after commit. Reopen the final journal for projection under the same case +authority. Create the first row with INSERT. Update the existing row only when its stored digest matches the one read. +Verify that a stale row digest prevents the update using a second connection. The model must still process a stale +operation revision because it records that refusal as an event. Preserve the separate admission sets and operation IDs +for both prescribed arrival orders. + +## Failure And Recovery Rules + +| Fault or invalid input | Required observation | +| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Unauthorized initial, step or projection input | Missing exact digest yields the model diagnostic and no unauthorized append. A duplicate admission set fails input validation. For a replay at the next prefix, require its new prefix-specific admission. Removing it yields `UNTRUSTED_EXECUTION_INPUT`. Restoring it returns the original result without a write. | +| Storage corruption, stale selection or competing writers | Verify SQLite row hash independently. Resealing the storage row around a changed inner digest still yields `EXECUTION_DIGEST_MISMATCH`. Race two connections against the original domain revision. Where the losing operation is admitted at the winning prefix, expect one grant and one recorded conflict/rejection with the frozen code. | +| Interrupt at the journal commit boundary | Before commit, reopening gives the original root. After commit before response, read back the durable append and require authorized replay. Compare bytes, revision and count. Reclaim only the case directory owned by this trial. | +| Child or outer response loss | Check snapshots at enrollment, start, physical effect, transport observation, signed admission and outer import. A durable start can precede process creation. Compare independent invocation count with claim, Attempt and outer version. Unknown effects remain held. A committed child admission can be imported without executing again. | +| Missing fresh proof, approval or merge | Return the guarded refusal or human handoff. Preserve lifecycle state and authenticated evidence. An operator can collect the next eligible proof or prepare a fresh observation within the approved scope. | + +## Commit Plan + +1. Commit the verified canonical Unit 5 plan before production edits. +2. Commit bounded framing, production dispatch, shared row storage and source-driven red/green tests in coherent slices. +3. Commit reproducible proof tooling and the report, with the complete requirement-to-evidence index and accurate live + status. Keep external artifact measurements traceable to the code SHA that ran. + +## Branch And PR Flow + +Use the verified #171 merge as the Unit 5 base in its own issue branch and worktree. Keep all other checkouts, branches +and checkpoints intact. Run repository instructions and host-native checks on the full diff. Qodo Local Review is +eligible given a pushed reviewable base and established access. Pin that merge-base, supply plan, decisions, evidence +and recent work, use fast checkpoints and auto depth for the final complete committed diff. An eligible review service +failure records an outstanding gate. Reproduce and fix supported findings, then re-review the new head. Obtain specific +authorization for any stored dismissal. + +Open one PR linked to #172 and #168. Require a completed structured hosted review on the current PR SHA, required CI and +Security, and a final head/tree check before merging with the reviewed SHA. Verify the merged tree and main CI +afterward. Use a non-closing link to #172 while mandatory live proof is pending. The fixture PR has its own destination, +review and same-head merge. The implementation PR may deliver independently verified work while the live acceptance +remains open. + +## Test Plan + +At `06c086d`, both macOS jobs passed the tests and build before the 15-minute job limit interrupted their packaged +install checks. A second attempt passed on Node 22 and reached the limit on Node 22.22.2. Allow 20 minutes for each +macOS test job and retain 15 minutes on Ubuntu. Validate the workflow with actionlint and require all four platform jobs +to finish their tests, build and packaged install at the reviewed revision. +[CI attempts](https://github.com/nnennandukwe/threadloop/actions/runs/45214202711) + +**Native and external checks.** Use fresh disposable clones of the pinned dependencies. Install their locked packages +and run upstream checks there, then supply those clean clones to the read-only external proof. Set `CONTRACTS` and +`HARNESS` to their absolute paths and `EVIDENCE` to a fresh directory outside the clean ThreadLoop checkout. The parent +invokes RunInvariant, supplies the measured identity, starts each subject in its own scratch directory and retains the +raw and public packets. The measured launcher requires macOS Seatbelt. Its parent has separate deadlines for inventory, +the complete suite and negative controls. After a parent timeout, the launcher reaps its case process before the driver +removes scratch. The proof uses a private npm cache for public registry reads while installing the three locks. An +operator running the proof needs network access to those public dependencies and space for the disposable installs. The +three installs and rebuild fit on a 512 MiB temporary volume on the measured macOS arm64 host. + +```bash +npm ci +npm run test:controller +npm run test:controller:deep +VITEST_MAX_WORKERS=2 npm run check +python3 -B -m unittest discover -s tests/proof -v +npm run security:dependencies +git diff --check origin/main...HEAD + +(cd "$CONTRACTS" && npm ci && npm run spec:conformance:check && npm run check) +(cd "$HARNESS" && npm ci && npm test && THREADLOOP_CHECKOUT="$CONTRACTS" npm run test:threadloop) +npm run build:controller-subject -- --output "$EVIDENCE/build" +python3 -B scripts/controller-conformance/prove.py --harness "$HARNESS" --contracts "$CONTRACTS" \ + --build "$EVIDENCE/build" --output "$EVIDENCE/controller.json" --raw-output "$EVIDENCE/raw.json" +``` + +Require exit 0 and packet schema `run-invariant.threadloop-packet/0.1` with `subject_kind: controller`. Check +`conformance.total` and `conformance.passed` equal 38 and `failed`, `nonconforming`, `protocol_error` and +`transport_error` equal zero. Match each row in `conformance.cases` to its frozen ID and operation, and retain the +verified input, request and response digests. Compare the packet’s `source`, `contract` and `subject` with the pinned +corpus, schema and measured artifact. Retain `runner.command`, `runner.limits`, `runner.report_limits` and +`claim_boundary` alongside the packet. Record the runner checkout revision and process exit status separately. +[Packet fields](https://github.com/nnennandukwe/run-invariant/blob/54be0d2240c44ee11b65d5e278a2cb667ee523b4/src/threadloop/runner.js) +· +[Process exit status](https://github.com/nnennandukwe/run-invariant/blob/54be0d2240c44ee11b65d5e278a2cb667ee523b4/src/threadloop/cli.js). +Exercise separate restart/CAS and profile-binding tests through production service and CLI paths. The serial corpus +doesn't race SQLite writers. Verify that the parent reclaims the per-case directory after a timed-out child is killed. +Publish the runner's counts and one row for each of the 38 case IDs with operation, status and measured digests. For +case 024, bind the observed reason to the runner row by matching the original request and response digests and stdout +hash. Keep the raw packet's SHA-256, exit code and measured launcher limits. Omit host paths and unbounded output from +the public packet. + +**Four native controls.** Each run gets a fresh output directory. Use the locked GAAP host/attestor, Goose 1.54.0 and +the deterministic local provider. + +```bash +export PYTHONDONTWRITEBYTECODE=1 +npm run prove:gaap:goose -- --gaap "$GAAP" --goose "$GOOSE" --case allow --output "$EVIDENCE/fixed-allow" +npm run prove:gaap:goose -- --gaap "$GAAP" --goose "$GOOSE" --case bad_patch --output "$EVIDENCE/fixed-bad" +npm run prove:gaap:goose -- --gaap "$GAAP" --goose "$GOOSE" --workflow-run --case allow --output "$EVIDENCE/managed-allow" +npm run prove:gaap:goose -- --gaap "$GAAP" --goose "$GOOSE" --workflow-run --case bad_patch --output "$EVIDENCE/managed-bad" +``` + +Fixed allow and bad-patch must preserve the legacy outer state at implementing/v2 with signed admission in each case. +Allow projects idle. The admitted unknown outcome requires reconciliation. Managed allow must record a selected request, +one launch and signed admission, then a scoped commit, explicit apply to verifying/v4 and passing local proof at that +commit. Managed bad-patch must record the admitted unknown outcome and refuse advancement at implementing/v3. Check +process, transcript, physical workspace, child and outer records independently. The #171 managed allow and bad-patch +provenance SHA-256 values are `ddc8d71f28d8431bce72bd0de46572fba11ca702d078d17c66075d0eb9dcfc1d` and +`06383e8b219448bd4cb9ffcee97d63acf99c5589f4c25553a6226b8f446fc287`. The fixed allow and bad-patch provenance SHA-256 +values are `fa969d1079b1d4648f0f1782aa303d554973ac63bf2bc9759f77cff396bc5f3a` and +`ac21568e1a6cf97cd5857d568fc2d3e5be6ba51a19a0b859ab000db483e7a440`. The locally deterministic cases use fixture trust +and don't supply live human evidence. + +**Installed package identity.** PR #179's second hosted review found that each package and its adjacent provenance file +could agree on changed bytes. Both public comparison commands must verify every supplied archive against a build from +the named Git objects before executing the CLI. Include the candidate, v1 Workflow Run and pre-adoption packages. Read +their build inputs from the trusted checkout with its matching npm installation. Verify that a harmless archive change, +with matching caller-supplied hashes, fails before use. Repeat the final archive comparison with independently +installed, lockfile-verified dependencies. Check that the installed README's new documentation links open from a package +installation. [Hosted review](https://github.com/nnennandukwe/threadloop/pull/179/files) + +The managed backup covers the physical executor output tree alongside the outer and child databases. Compare the +relative output paths and bytes before copying, in the backup and after restoration. A missing, changed or extra file +must fail the comparison even when SQLite still reports the same heads and admitted blobs. + +**Parity and rollback.** Measure a fresh exact-head TypeScript package and its runtime files, locked dependency blob, OS +and Node. Reconcile each of M003's original 15 command names and generation-1 expectations at +`750ae36b6b7b6ea34081a8c90236d8c95f71b086` with the actual installed interface. Nine names remained at #170. Default v4 +then listed 24 commands and opt-in v5 listed 30. Measure the complete #172 CLI, including setup/2 execution and +collection. Check aliases, removed commands, flags/help, text/JSON, error/exit behavior, implicit or ambiguous session +targets, multiple active sessions, captured/editor content, Git filtering, artifact formats, snapshots, reconcile, +daemon disposition, storage and concurrent writes. Preserve the reviewed runner hashes and protocol v4 text/JSON bytes. +Retest v5 discovery, v1/v2 coexistence and predecessor refusals on Node 22/24/26. + +Reuse the reviewed #170 rollback tarball `c8c96f8229ee141bfe31b1509440e548aa2fb64b089bd6f44b41016e7e0fe078` and +pre-adoption package `4370cea4a5d7be5e283fcafc09fdce07e37168929db8a1e21448614e79f51bc1`. The historical single-database +packet `3db08ed2a23e9063be041036adf3833dd27e2e06658232f794176e1144d5afbd` compared the old reader to upgraded state, +restored the quiescent backup and reproduced export SHA-256 +`8e2a2160fd9ddc471d35e3491199a36880655c1a81a3ed44e57b298ae871a722`. Check generation 7 explicit init, generation 8 +additive features and future-generation refusal. Compare database and artifact/export digests as well as logical state. +Account for read-side WAL/SHM files and for all newer writes lost by restoring an older snapshot. + +Rerun the two-database rollback from independent quiescent checkpoints and matching source paths. Leave the physical +subject and invocation counter outside the backup. At reviewed head `ca713573e1ffc0c60ad4be34c58638804c65a4c9`, the +held-effect backup was 822,020 bytes. Restored execution stayed at revision 3. The committed child-admission backup was +812,625 bytes. Recovery imported one signed receipt and three blobs at outer execution revision 2→3. Each case recorded +one physical invocation and lifecycle version 3. Both restored pairs reproduced their original file hashes. The #170 +client refused five managed workflow probes and both child operations and still read a legacy v1 run. Rollback packet +SHA-256 `4e1f947a71858c92d8baf904ef2ccb6d78527d511711c6ff211289c8cb9f8642`. For Unit 5 use a new exact-SHA package, +integrity/quick checks, completed WAL checkpoints, a 64 MiB cap per backup, an independent reader, and before/after +evidence for both cuts. + +**Evidence for the readiness report.** Review and track the parent-side isolation launcher, installed-package comparator +and quiescent rollback driver in the ThreadLoop change. Each driver must accept explicit inputs and reproduce its +measurements from a clean commit. Keep the corpus and parent-side comparisons outside the controller artifact. Record +each M003 command and storage disposition, the proposed live route, its authorization status and the fixed caller’s +measured bytes in the readiness report. Include the 38 sanitized case rows, pins, artifact manifest, parity and rollback +results and native proof digests in the report or a linked CI artifact with its retention and SHA-256. Keep signed +originals in authorized evidence storage and expose the fields needed to verify them. Link reviewed drivers, public +results and durable artifact locations from the tracked evidence index. + +For every #110/#85/#168/M003 requirement record expected behavior, observed result, status, source commit/tree, +OS/runtime, package or artifact hash, reproducible command, and durable evidence location. Compare review and merge +trees. A report commit changes its own head. Rerun the external suite, rollback and relevant package/native checks at +the final reviewed SHA. Link that final packet and post-merge result from #172 and the tracker. Preserve historical +receipts and exact pins. + +## Definition Of Done + +Close #172 and #168 only when all prerequisite units have merged-tree and post-merge proof, the real subject passes all +38 cases, the four native and persistence paths hold, installed parity and both rollback paths are measured, and the +live Workflow Run reaches its guarded completion after current proof, review, eligible same-head human approval and +signed merge observation. Refresh M003's TypeScript baseline and label its Rust migration, cross-language differential, +performance, release packaging, artifact provenance and RC soak as future work. A passed simulated case can't fill a +pending live row. + +## Assumptions And Defaults + +Proceed with local, read-only dependency and CI work using existing entitlements. Obtain the operator’s decision on +fixture refs, caller enablement, fixture PR, Qodo submission and dispatch budget before starting those live steps. If +the user or eligible reviewer hasn't supplied a necessary decision, finish the independent conformance, native, recovery +and parity work. Publish the accurate pending status, preserve the run and evidence, and leave the prerequisite Goal +open. diff --git a/docs/pre-rust-readiness.md b/docs/pre-rust-readiness.md new file mode 100644 index 0000000..1a9aa60 --- /dev/null +++ b/docs/pre-rust-readiness.md @@ -0,0 +1,130 @@ +# ThreadLoop’s TypeScript baseline before Rust + +ThreadLoop can bind a Workflow Run to a compiled graph, select its next action and guard the transition that follows. +Managed engineering actions use the GAAP process bridge. A signed child result and a Workflow Run transition have +separate commit points. The live completion proof still needs an independent person's approval and a signed merge +observation at the same reviewed commit. [Runtime issue #172](https://github.com/nnennandukwe/threadloop/issues/172) · +[Program tracker](https://github.com/nnennandukwe/threadloop/issues/168) + +ThreadLoop commit `80e091c9f6412195a8444f048add977d648c4115`, tree `987ef4aeda6bb371b0c2f476a3dbeae9467d89ec`, produced +the measurements below on macOS arm64. Its bundled tarball has SHA-256 +`36f1a69c52e0ae4cc4c4fb7e03c207f30c6391efec12f123581b896df5c6fa51`. The later evidence and review commits can be +verified from the linked implementation issue. +[Measured source](https://github.com/nnennandukwe/threadloop/tree/80e091c9f6412195a8444f048add977d648c4115) · +[Implementation issue](https://github.com/nnennandukwe/threadloop/issues/172) + +At this revision, `npm run check` passed all 952 tests in 77 files, built the CLI and verified the packaged install. The +dependency audit reported zero vulnerabilities. All nine Python proof tests passed. The separate controller suite passed +65 tests. The unit 5 plan links each earlier delivery to its reviewed head, matching merge tree and both post-merge +checks. [Predecessor verification](plans/issue-172-controller-conformance-and-parity.md#summary) + +## Requirements and evidence + +| Requirement | Observed behavior | Delivery | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Additive storage, #85 | Ordinary gate results use a domain-seeded catalog at storage generation 8. The first compatible write adopts the old layout. Read-only operations leave historical receipt and export bytes intact. Generation 7 requires explicit initialization. Independent SQLite readers and raw inserts check the write guards. | [Storage PR and reviewed plan](https://github.com/nnennandukwe/threadloop/pull/173) · [Main CI](https://github.com/nnennandukwe/threadloop/actions/runs/44950980593) | +| Deterministic selection, #110 | The selector derives each of the six outcomes from the canonical input, including ties, outstanding obligations and human handoffs. | [Selector PR](https://github.com/nnennandukwe/threadloop/pull/174) · [Main CI](https://github.com/nnennandukwe/threadloop/actions/runs/44956272381) | +| Durable graph binding and authority, #110 | Create commits the binding and first run version. Decide reads current facts. Apply rechecks evidence and the expected version. Separate processes exercise replay, conflict, interruption and restart. | [Durable runs PR](https://github.com/nnennandukwe/threadloop/pull/176) · [Process tests](../tests/integration/workflow-store-process.test.ts) · [Main CI](https://github.com/nnennandukwe/threadloop/actions/runs/44961637392) | +| Bounded external execution, #110 | A selected engineering action produces a claim and Attempt, then one bounded launch. Signed admission commits to the child store. The outer run imports the evidence and reevaluates before a deliberate apply. An uncertain effect holds for reconciliation. | [Selected execution PR](https://github.com/nnennandukwe/threadloop/pull/177) · [Managed process tests](../tests/integration/workflow-execution.test.ts) · [Main CI](https://github.com/nnennandukwe/threadloop/actions/runs/45016894891) | +| Independent conformance, #110 | The production subject passed all 38 cases. The parent independently matched each case with its request, response and output digests. Six forbidden file reads returned a kernel denial. | [38 case results and controls](evidence/issue-172-controller-conformance.json) | +| Governed completion, #110 | The public fixture route still needs authorization, a willing independent reviewer and the actual review and merge at the subject head. The human handoff remains open. | [Completion criteria](https://github.com/nnennandukwe/threadloop/issues/172) | +| Rust parity and rollback, M003 | Three installed Node runtimes agreed on all 33 v5 commands and both v4 outputs. Both old readers reproduced the supported audit history. Quiescent restore and recovery preserved one physical invocation in each managed case. | [Installed CLI](evidence/issue-172-installed-cli.json) · [Restored databases](evidence/issue-172-managed-rollback.json) | + +The contracts freeze records the authority model. RunInvariant checks the external subject. ThreadLoop owns runtime +writes. The #86 run identity and #88 read-only audit exports retain their original meaning. +[Authority ADR](adr/0001-sdlc-graph-authority-model.md) · +[Run identity](https://github.com/nnennandukwe/threadloop/issues/86) · +[Audit exports](https://github.com/nnennandukwe/threadloop/issues/88) + +## External controller and native execution + +The original measurement below used the installed dependencies in the clean implementation and harness checkouts. Git +verified tracked source and lockfiles. The first proof driver reused those installations for its rebuild and harness +execution. The PR tracks the follow-up measurement against independently installed dependencies. +[Review and follow-up evidence](https://github.com/nnennandukwe/threadloop/pull/179) + +RunInvariant `54be0d2240c44ee11b65d5e278a2cb667ee523b4` ran the frozen corpus against the three-file runtime with +artifact digest `d416ec2bbf6fec50c1408c11acd96014bf7ac24f92e88416d9af1feb34c9cfaf`. All three graph compilations, 25 +decisions and ten execution scenarios passed. Case 024 returned `blocked` with `AMBIGUOUS_REMEDY`. The parent reproduced +its response hash, changed the case label and obtained the same domain result. The controls detected a wrong answer, a +mismatched response and a timeout. The parent ran +`python3 launch.py CASE_ROOT NODE SUBJECT REQUEST_SCHEMA RECEIPT_SCHEMA conformance` for each case, with a ten-second +deadline. The packet records the exact byte limits, schema hashes, case rows and isolation checks. +[External results](evidence/issue-172-controller-conformance.json) · +[Reproduction commands](plans/issue-172-controller-conformance-and-parity.md#test-plan) + +The serial corpus checks behavior visible over the process protocol. Separate SQLite tests race independent writers, +reopen committed state, kill a worker before and after commit, and recheck authority before replay. The generated deep +suite covered 512 controller histories and 48 process histories. The pinned contracts suite passed 404 tests and its +installed smoke test. RunInvariant passed 95 native tests and 59 ThreadLoop integration tests. +[Commit-cut and writer tests](../tests/integration/controller-execution-scenario.test.ts) · +[Generated histories](../scripts/controller-generated/deep.ts) + +Goose 1.54.0 and GAAP `0a82687d6070081e0a5cb613698f0724dc6f00cb` ran the shipping fixture through the real native +binaries using a deterministic local provider and public fixture signing key. All four cases launched once and produced +one independently verified signed admission. +[Native receipts and package hashes](evidence/issue-172-native-execution.json) + +| Run | Allowed change | Bad patch | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| Managed Workflow Run | The Attempt succeeded. A scoped commit and explicit apply moved the run to `verifying`, version 4. The declared local gate passed at that commit. | The signed outcome recorded an uncertain effect. Apply refused and the run stayed at `implementing`, version 3. | +| Standalone bridge | The child projected idle. The fixed session stayed at `implementing`, version 2. | The child required reconciliation. The fixed session stayed at `implementing`, version 2. | + +The proposed live proof needs the operator to authorize dedicated proof refs, its fixture PR, a default-branch evidence +caller and a willing independent GitHub reviewer. The caller proposal has SHA-256 +`06d652b423560f20ec4aa91b56e362a9785611a2220e663428f470583cc1e50c`. The proposal caps signed collection at four +dispatches with zero additional spend. Completion requires the actual reviewer’s decision and a signed observation of +the merge at that approved head. [Live acceptance](https://github.com/nnennandukwe/threadloop/issues/172) + +## Installed command and storage baseline + +The original package comparison checked archive bytes against their accompanying provenance files and exercised the +installed commands. Those checks needed an independent source build to establish that each supplied archive came from +its claimed Git revision. PR #179 records the revised archive check and its results. +[Package verification](https://github.com/nnennandukwe/threadloop/pull/179) + +The Rust milestone originally pinned 15 commands and storage generation 1 at `750ae36`. Its description says ten error +codes. The source declares nine. The installed comparison exercises all nine through current error paths and records the +current declared set. Successful JSON commands write to stdout. JSON failures write an error envelope to stderr and +exit 1. An empty invocation emits usage on stderr and exits 1. +[Historical CLI](https://github.com/nnennandukwe/threadloop/blob/750ae36b6b7b6ea34081a8c90236d8c95f71b086/src/cli-program.ts) +· +[Historical error codes](https://github.com/nnennandukwe/threadloop/blob/750ae36b6b7b6ea34081a8c90236d8c95f71b086/src/contracts/errors.ts) + +| Original commands | Behavior a replacement needs to preserve | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `init`, `protocol` | `init` initializes local storage and reports text. Default and explicit v4 have identical JSON and text bytes. Clients can negotiate v5 to discover the workflow commands. | +| `session start`, `session list`, `session status`, `session capture` | Two active sessions can coexist. Status and capture require a session ID. Changed-file snapshots honor the base ref and exclude ThreadLoop metadata. Editor input appears in the stored goal or requested entry. | +| `session heartbeat`, `session reconcile`, `artifact generate` | Reconcile requires a session or `--all`. The three Markdown formats retain their content. An implicit artifact target works with one active session and fails on two. | +| `start`, `capture`, `status`, `finish`, `session finish`, `daemon run` | All six return `INVALID_ARGUMENT`. The supported session commands and guarded transitions own those operations. `daemon` remains a recorded heartbeat source. | + +Current initialization preserves an old JSON file without importing its tasks. The installed reader refuses a +generation-1 SQLite file built from the original bootstrap SQL. On an actual pre-adoption generation-8 store, status, +next and audit export preserve the database and historical audit bytes. The next-action response reports its validated +storage capability. The tested generation-9 store survives both read and initialization refusals. + +The installed packages on Node 22.22.2, 24.20.0 and 26.8.2 returned identical help and protocol descriptions. Default v4 +lists 24 commands. Opt-in v5 lists 33 and advertises `workflow_runs_v1`, `workflow_gaap_execution_v1` and +`workflow_claim_expiry_v1`. The runtime declares 41 error codes. The recorded runner skill retains its reviewed SHA-256 +`fd9fabf1ad27f4b91d1b369b9283200045a1ca54e54d38da014d4f29972cc0dc`. The packet contains the complete help text, protocol +digests and runner revisions. [Installed CLI measurements](evidence/issue-172-installed-cli.json) + +## Rollback boundary + +Restore from a quiescent backup taken with both databases checkpointed. Preserve the enrolled subject and its physical +effects. The predecessor can read a v1 run in the same database and refuses operations on a v2 enrollment. Restoring an +earlier snapshot discards later writes. The proof records those writes and checks the restored hashes before recovery. +[Installed comparison and managed rollback](../scripts/pre-rust/README.md) + +Across all three Node versions, restoring a held physical effect kept outer execution revision 3 at revision 3. +Restoring a committed child admission reimported one signed receipt and three blobs, moving outer execution revision 2 +to 3. Both cuts left the Workflow Run at lifecycle version 3. Every restored database matched its recorded file hash and +the producer counter stayed at one. The Node 26 single-store backup also reproduced its database and audit export hashes +with each reader. [Paired rollback results](evidence/issue-172-managed-rollback.json) · +[Single-store comparison](evidence/issue-172-installed-cli.json) + +## What still belongs to Rust + +The Rust implementation, TypeScript-versus-Rust comparisons, platform binaries, installers, performance measurements, +release attestation and release-candidate soak belong to M003. This TypeScript baseline supplies inputs to that work. +[Rust planning milestone](https://github.com/nnennandukwe/threadloop/milestone/3) diff --git a/knip.json b/knip.json index 9bd9b86..564eff3 100644 --- a/knip.json +++ b/knip.json @@ -9,6 +9,8 @@ "entry": [ "scripts/prove-gaap-goose.ts", "scripts/smoke-managed-workflow.ts", + "scripts/pre-rust/rollback-fixture.ts", + "scripts/controller-conformance/subject.ts", "tests/fixtures/gaap-native-producer.ts", "scripts/controller-generated/*.ts" ] diff --git a/package.json b/package.json index 6471b0f..395cc58 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "sensor:github-review:collect": "tsx scripts/collect-github-review-snapshot.ts", "sensor:github-review:sign": "tsx scripts/sign-github-review-receipt.ts", "prove:gaap:goose": "python3 scripts/prove-gaap-goose.py", + "build:controller-subject": "node scripts/controller-conformance/build.mjs", "test:controller": "vitest run tests/unit/controller-generated.test.ts tests/unit/controller-generated-mutants.test.ts tests/integration/controller-generated-process.test.ts tests/integration/controller-history-replay.test.ts", "test:controller:deep": "tsx scripts/controller-generated/deep.ts", "test:controller:replay": "tsx scripts/controller-generated/replay.ts" diff --git a/scripts/controller-conformance/artifact.ts b/scripts/controller-conformance/artifact.ts new file mode 100644 index 0000000..7149d16 --- /dev/null +++ b/scripts/controller-conformance/artifact.ts @@ -0,0 +1,20 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +export const subjectPath = 'scripts/executor-contract/subject.mjs'; +const schemaRoot = 'docs/contracts/executor-v0.1/upstream/gaap'; +export const schemaPaths = [ + schemaRoot + '/agent-run-request.schema.json', + schemaRoot + '/terminal-run-receipt.schema.json', +]; + +export function measureSubject(runtime: string, version: string, revision: string) { + const manifest = [...schemaPaths, subjectPath].sort().map((path) => { + const content = readFileSync(join(runtime, path)); + return { bytes: content.length, path, sha256: createHash('sha256').update(content).digest('hex') }; + }); + // The record keys above are in canonical UTF-16 order. + const artifact_digest = createHash('sha256').update(JSON.stringify(manifest)).digest('hex'); + return { manifest, identity: { name: 'threadloop-controller', version, revision, artifact_digest } }; +} diff --git a/scripts/controller-conformance/build.mjs b/scripts/controller-conformance/build.mjs new file mode 100644 index 0000000..17cb4dc --- /dev/null +++ b/scripts/controller-conformance/build.mjs @@ -0,0 +1,75 @@ +import { execFileSync } from 'node:child_process'; +import { copyFileSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build as bundle } from 'tsup'; +import { measureSubject, schemaPaths, subjectPath } from './artifact.ts'; + +const repo = fileURLToPath(new URL('../../', import.meta.url)); +const require = createRequire(import.meta.url); +function revision(destination) { + const git = (args) => execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim(); + const head = git(['rev-parse', 'HEAD']); + const outputPath = relative(repo, destination); + const paths = ['.']; + if (outputPath && !isAbsolute(outputPath) && outputPath !== '..' && !outputPath.startsWith('..' + sep)) { + paths.push(':(exclude,literal)' + outputPath.split(sep).join('/')); + } + return git(['status', '--porcelain', '--untracked-files=normal', '--', ...paths]) ? head + '-dirty' : head; +} +async function build(destination) { + const version = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf8')).version; + const source = revision(destination); + const runtime = join(destination, 'runtime'); + mkdirSync(destination); + try { + for (const path of schemaPaths) { + const installed = require.resolve('threadloop-contracts/assets/' + path.slice('docs/contracts/'.length)); + mkdirSync(dirname(join(runtime, path)), { recursive: true }); + copyFileSync(installed, join(runtime, path)); + } + const bundleDirectory = dirname(join(runtime, subjectPath)); + await bundle({ + entry: ['scripts/controller-conformance/subject.ts'], + bundle: true, + platform: 'node', + format: ['esm'], + target: 'node22', + metafile: true, + noExternal: [/.*/], + splitting: false, + config: false, + silent: true, + outDir: bundleDirectory, + outExtension: () => ({ js: '.mjs' }), + banner: { js: "const require = (await import('node:module')).createRequire(import.meta.url);" }, + define: { + THREADLOOP_SUBJECT_REVISION: JSON.stringify(source), + THREADLOOP_SUBJECT_VERSION: JSON.stringify(version), + }, + }); + renameSync(join(bundleDirectory, 'metafile-esm.json'), join(destination, 'build-metafile.json')); + if (revision(destination) !== source) + throw new Error('The source revision changed during the build. Repeat from a stable checkout.'); + const { manifest, identity } = measureSubject(runtime, version, source); + const writeJson = (name, value) => + writeFileSync(join(destination, name), JSON.stringify(value, null, 2) + '\n', { flag: 'wx' }); + writeJson('manifest.json', manifest); + writeJson('identity.json', identity); + } catch (error) { + rmSync(destination, { recursive: true, force: true }); + throw error; + } +} +try { + const [flag, directory, ...rest] = process.argv.slice(2); + if (flag !== '--output' || !directory || rest.length) + throw new Error('Usage: node scripts/controller-conformance/build.mjs --output <fresh-directory>'); + const destination = resolve(directory); + process.chdir(repo); + await build(destination); +} catch (error) { + process.stderr.write(error.message + '\n'); + process.exitCode = 1; +} diff --git a/scripts/controller-conformance/check-controls.cjs b/scripts/controller-conformance/check-controls.cjs new file mode 100644 index 0000000..9d0773a --- /dev/null +++ b/scripts/controller-conformance/check-controls.cjs @@ -0,0 +1,126 @@ +// RunInvariant stays in the parent. Each child gets its own restricted launcher. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +async function main() { + const settings = JSON.parse(fs.readFileSync(0, 'utf8')); + const { harness, contracts, command, control, identity, canaries, controlRoot } = settings; + const { canonical, digest, sha256 } = require(path.join(harness, 'src/threadloop/codec')); + const { buildRequest, loadCorpus, profiles, responseSchema } = require(path.join(harness, 'src/threadloop/corpus')); + const { runCase, validateResponse } = require(path.join(harness, 'src/threadloop/runner')); + const { defaults, invoke } = require(path.join(harness, 'src/threadloop/process')); + const corpus = loadCorpus(contracts); + const inventory = corpus.fixtures.map((fixture, index) => { + const entry = corpus.manifest.manifest.entries[index]; + const envelope = buildRequest(corpus, fixture); + return { + id: entry.id, + operation: entry.operation, + fixture_digest: entry.fixture_digest, + input_digest: entry.input_digest, + request_digest: envelope.request_digest, + graph_digest: + fixture.input.binding?.graph_digest ?? fixture.input.projection_snapshot?.binding?.graph_digest ?? null, + }; + }); + if (settings.inventoryOnly) return inventory; + const byId = (id) => { + const fixture = corpus.fixtures.find((item) => item.id === id); + assert.ok(fixture, id); + return fixture; + }; + const baseline = buildRequest(corpus, byId('case_024')); + const call = async (envelope) => { + const { stdout } = await invoke(command, Buffer.from(canonical(envelope)), defaults); + const reply = validateResponse(corpus, envelope, stdout, identity); + return { reply, stdout_sha256: sha256(stdout) }; + }; + const original = await call(baseline); + const decision = original.reply.response.result.decision.decision; + assert.equal(decision.outcome, 'blocked'); + assert.deepEqual( + decision.reasons.map((reason) => reason.code), + ['AMBIGUOUS_REMEDY'], + ); + const relabeled = structuredClone(baseline); + relabeled.request.case_id = 'case_999'; + relabeled.request_digest = digest(relabeled.request); + corpus.validate('request', relabeled); + assert.notEqual(relabeled.request_digest, baseline.request_digest); + const second = await call(relabeled); + assert.deepEqual(second.reply.response.result, original.reply.response.result); + + const fixture = byId('case_001'); + const request = buildRequest(corpus, fixture); + const compiled = await call(request); + assert.equal(compiled.reply.response.result.status, 'compiled'); + const invalid = { status: 'invalid', diagnostics: [{ code: 'CONTROL', identifier: null, path: '$' }] }; + async function substituted(correlation) { + const response = { + ...profiles, + schema: responseSchema, + request_digest: correlation, + subject: identity, + result: invalid, + }; + const wire = canonical({ response, response_digest: digest(response) }); + return runCase(corpus, fixture, [...control, 'reply', wire], identity, defaults); + } + const mismatch = await substituted(request.request_digest); + assert.equal(mismatch.status, 'nonconforming'); + const unrelated = await substituted(digest('independent correlation')); + assert.equal(unrelated.status, 'protocol_error'); + assert.match(unrelated.diagnostic, /Request correlation/); + + Object.values(canaries).forEach((file) => assert.ok(fs.statSync(file).isFile())); + const reads = await invoke([...control, 'read', ...Object.values(canaries)], Buffer.alloc(0), defaults); + const denied = JSON.parse(reads.stdout); + assert.equal(denied.length, Object.keys(canaries).length); + assert.ok(denied.every((code) => code === 'EPERM' || code === 'EACCES')); + assert.deepEqual(fs.readdirSync(controlRoot), []); + const timeoutMs = 1500; + const expired = await runCase(corpus, fixture, [...control, 'timeout'], identity, { + ...defaults, + timeout_ms: timeoutMs, + }); + assert.equal(expired.status, 'transport_error'); + assert.match(expired.diagnostic, /^TIMEOUT:/); + const leftovers = fs.readdirSync(controlRoot); + assert.equal(leftovers.length, 1); + assert.equal(fs.readFileSync(path.join(controlRoot, leftovers[0], 'started'), 'utf8'), 'timeout control'); + return { + inventory, + controls: { + case_001: { + request_digest: request.request_digest, + response_digest: compiled.reply.response_digest, + stdout_sha256: compiled.stdout_sha256, + graph_digest: compiled.reply.response.result.compiled_graph.graph_digest, + }, + case_024: { + request_digest: baseline.request_digest, + response_digest: original.reply.response_digest, + stdout_sha256: original.stdout_sha256, + outcome: decision.outcome, + reason: decision.reasons[0].code, + }, + relabeled: { + case_id: relabeled.request.case_id, + request_digest: relabeled.request_digest, + response_digest: second.reply.response_digest, + same_domain_result: true, + }, + wrong_result: mismatch.status, + wrong_correlation: unrelated.status, + file_denials: Object.fromEntries(Object.keys(canaries).map((name, index) => [name, denied[index]])), + timeout: { status: expired.status, timeout_ms: timeoutMs, started_case_directories: leftovers.length }, + }, + }; +} +main() + .then((output) => process.stdout.write(JSON.stringify(output))) + .catch((error) => { + process.stderr.write(error.message + '\n'); + process.exitCode = 1; + }); diff --git a/scripts/controller-conformance/execution-scenario.ts b/scripts/controller-conformance/execution-scenario.ts new file mode 100644 index 0000000..d1ae967 --- /dev/null +++ b/scripts/controller-conformance/execution-scenario.ts @@ -0,0 +1,91 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { z } from 'zod'; +import { createExecutionJournal } from 'threadloop-contracts/execution'; +import type { OperationResult } from 'threadloop-contracts/execution'; +import schema from 'threadloop-contracts/assets/controller-conformance-v0.1/schemas/execution-scenario.schema.json' with { type: 'json' }; +import { ScenarioJournal } from './scenario-journal.js'; + +interface Scenario { + initial: { context: unknown; request: unknown; policy: unknown }; + steps: { context: unknown; operation: unknown }[]; + admitted_digests: string[]; + projection_snapshot: unknown; +} +type Diagnostic = { code: string; path: string; identifier: string | null }; +const scenarioSchema = z.fromJSONSchema(schema as z.core.JSONSchema.JSONSchema) as z.ZodType<Scenario>; +function invalid(diagnostics: Diagnostic[]) { + return { + status: 'invalid' as const, + diagnostics: diagnostics.map(({ code, path, identifier }) => ({ code, path, identifier })), + }; +} + +export function runExecutionScenario(input: unknown) { + const parsed = scenarioSchema.safeParse(input); + if (!parsed.success) + return invalid( + parsed.error.issues.map((issue) => ({ + code: 'SCHEMA_INVALID', + path: + '$' + issue.path.map((part) => (typeof part === 'number' ? '[' + part + ']' : '.' + String(part))).join(''), + identifier: null, + })), + ); + const { initial, steps, admitted_digests, projection_snapshot } = parsed.data; + const admitted = new Set(admitted_digests); + if (admitted.size !== admitted_digests.length) + return invalid([{ code: 'DUPLICATE_ADMISSION', path: '$', identifier: null }]); + const authority = { isAdmitted: (digest: string) => admitted.has(digest) }; + const created = createExecutionJournal(initial.context, initial.request, initial.policy, authority); + if (!created.ok) return invalid(created.diagnostics); + const directory = mkdtempSync(path.join(tmpdir(), 'threadloop-scenario-')); + try { + const journal = new ScenarioJournal(path.join(directory, 'journal.sqlite'), authority); + journal.initialize(created.value); + const results: (Omit<OperationResult, 'recovery'> & { replayed: boolean })[] = []; + for (const step of steps) { + const applied = journal.apply(step.context, step.operation); + if (!applied.ok) return invalid(applied.diagnostics); + const { disposition, code, revision, claim, attempt_id } = applied.value.result; + results.push({ disposition, code, revision, claim, attempt_id, replayed: applied.value.replayed }); + } + const final = journal.project(projection_snapshot); + if (!final.ok) return invalid(final.diagnostics); + const { projection, controller } = final.value; + return { + status: 'execution' as const, + steps: results, + projection: { + revision: projection.revision, + request_status: projection.request_status, + claims: projection.claims.map(({ id, version, status, attempt_id }) => ({ id, version, status, attempt_id })), + attempts: projection.attempts.map(({ id, claim, status, effect, receipt_id }) => ({ + id, + claim, + status, + effect, + receipt_id, + })), + receipts: projection.receipts.map(({ envelope, result }) => ({ + id: envelope.receipt.id, + receipt_digest: envelope.receipt_digest, + code: result.code, + })), + conflicts: projection.conflicts.map( + ({ namespace, identity, original_digest, incoming_digest, resolved_by }) => ({ + namespace, + identity, + original_digest, + incoming_digest, + resolved_by, + }), + ), + controller, + }, + }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/scripts/controller-conformance/launch.py b/scripts/controller-conformance/launch.py new file mode 100644 index 0000000..f2e9ec8 --- /dev/null +++ b/scripts/controller-conformance/launch.py @@ -0,0 +1,61 @@ +"""Launch one controller process under macOS Seatbelt with private case files.""" + +import os +import subprocess +import sys +import tempfile +from pathlib import Path + + +def run_with_parent(command, directory, parent): + """Reap the sandboxed child if its RunInvariant parent exits during a case.""" + if parent <= 1 or os.getppid() != parent: + raise SystemExit("The case parent exited before launch.") + child = subprocess.Popen(command, cwd=directory, env={"TZ": "UTC", "LC_ALL": "C", "TMPDIR": directory}) + try: + while os.getppid() == parent: + try: + return child.wait(timeout=0.1) + except subprocess.TimeoutExpired: + continue + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=2) + return child.returncode + + +def main(arguments): + """Run the measured Node entry with fresh scratch and pass its exit status to RunInvariant.""" + if sys.platform != "darwin" or not os.access("/usr/bin/sandbox-exec", os.X_OK): + raise SystemExit("Controller isolation requires macOS and /usr/bin/sandbox-exec.") + if len(arguments) < 5: + raise SystemExit("Usage: launch.py CASE_ROOT NODE ENTRY REQUEST_SCHEMA RECEIPT_SCHEMA [ARG ...]") + import fcntl + + parent = os.getppid() + root, node, entry, request, receipt = (Path(value).resolve(strict=True) for value in arguments[:5]) + descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + # The parent can await this directory lock before removing a stopped case's files. + fcntl.flock(descriptor, fcntl.LOCK_SH) + with tempfile.TemporaryDirectory(prefix="case-", dir=root) as directory: + parameters = { + "NODE": node, + "ARTIFACT": entry, + "SCRATCH": directory, + "REQUEST_SCHEMA": request, + "RECEIPT_SCHEMA": receipt, + } + command = ["/usr/bin/sandbox-exec"] + for key, value in parameters.items(): + command.extend(["-D", f"{key}={value}"]) + command.extend(["-f", Path(__file__).with_name("subject.sb"), node, entry, *arguments[5:]]) + status = run_with_parent(command, directory, parent) + return status if status >= 0 else 128 - status + finally: + os.close(descriptor) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/controller-conformance/operations.ts b/scripts/controller-conformance/operations.ts new file mode 100644 index 0000000..a8bc04e --- /dev/null +++ b/scripts/controller-conformance/operations.ts @@ -0,0 +1,26 @@ +import { compileWorkflowProfile, type Diagnostic } from 'threadloop-contracts/workflow'; +import { selectWorkflowDecision } from '../../src/domain/workflow-controller.js'; +import { runExecutionScenario } from './execution-scenario.js'; + +export type Operation = 'compile_graph' | 'decide' | 'execution_scenario'; + +function invalid(diagnostics: Diagnostic[]) { + return { + status: 'invalid', + diagnostics: diagnostics.map(({ code, path, identifier }) => ({ code, path, identifier })), + }; +} +export function runControllerOperation(operation: Operation, input: unknown) { + switch (operation) { + case 'compile_graph': { + const compiled = compileWorkflowProfile(JSON.stringify(input)); + return compiled.ok ? { status: 'compiled', compiled_graph: compiled.value } : invalid(compiled.diagnostics); + } + case 'decide': { + const decision = selectWorkflowDecision(input); + return decision.ok ? { status: 'decision', decision: decision.value } : invalid(decision.diagnostics); + } + case 'execution_scenario': + return runExecutionScenario(input); + } +} diff --git a/scripts/controller-conformance/prove.py b/scripts/controller-conformance/prove.py new file mode 100644 index 0000000..4e630f0 --- /dev/null +++ b/scripts/controller-conformance/prove.py @@ -0,0 +1,682 @@ +"""Run the frozen external suite against an isolated controller built from a clean ThreadLoop commit.""" + +import argparse +import hashlib +import json +import os +import platform +import re +import shutil +import subprocess +import sys +import tempfile +import time +from collections import Counter +from pathlib import Path + + +SCRIPTS = Path(__file__).resolve().parent +REPO = SCRIPTS.parents[1] +HARNESS = "54be0d2240c44ee11b65d5e278a2cb667ee523b4" +CONTRACTS = "4ed9a94a2a089b9ae950d93297f7a6b9b939d3a6" +FREEZE = "7dcf432bc75a68b5ee803c6ebb7346b6bb417f83" +CORPUS_SOURCE = "fde510deca780c7cada8a2e461bd15af0fe4ae88" +CORPUS = "11620588c6f4b39353ea9f77e361a50b5cb0dc970410b1ac10aa8bef13efad84" +COMPATIBILITY = "9590ab51c9081ee2c43f67c0ed1b3453588acdda0e63f259827625971643eadf" +CORPUS_DIR = Path("docs/contracts/controller-conformance-v0.1") +GAAP_DIR = Path("docs/contracts/executor-v0.1/upstream/gaap") +SCHEMAS = [GAAP_DIR / name for name in ("agent-run-request.schema.json", "terminal-run-receipt.schema.json")] +SUBJECT = Path("scripts/executor-contract/subject.mjs") +CONTROL = REPO / "tests/fixtures/controller-conformance/control.mjs" +STATUSES = ("passed", "nonconforming", "protocol_error", "transport_error") +OUTCOMES = { + "transition_available", + "engineering_action_required", + "human_action_required", + "waiting", + "blocked", + "terminal", +} +CONTRACT = { + "protocol": "threadloop.controller-conformance/0.1", + "fixture_schema": "threadloop.conformance-fixture/0.1", + "canonicalization": "threadloop.conformance-json/0.1", + "digest_profile": "threadloop.conformance-sha256/0.1", + "request_schema": "threadloop.conformance-request/0.1", + "response_schema": "threadloop.conformance-response/0.1", + "manifest_schema": "threadloop.conformance-manifest/0.1", + "compatibility_schema": "threadloop.conformance-compatibility/0.1", + "compatibility_digest": COMPATIBILITY, +} +LIMITS = { + "timeout_ms": 10000, + "stdin_bytes": 16 * 1024 * 1024 + 1, + "stdout_bytes": 16 * 1024 * 1024 + 1, + "stderr_bytes": 1024 * 1024, +} +PARENT_SETUP_SECONDS = 30 +GIT_SECONDS = 60 +BUILD_SECONDS = 180 +INSTALL_SECONDS = 300 +INSTALL_FLAGS = ["--ignore-scripts", "--include=dev", "--include=optional", "--no-audit", "--no-fund"] +# RunInvariant allows one second for each process group to close its inherited pipes. +SECONDS_PER_CASE_WITH_CLEANUP = LIMITS["timeout_ms"] // 1000 + 1 +HARNESS_PARENT_SECONDS = PARENT_SETUP_SECONDS + 38 * SECONDS_PER_CASE_WITH_CLEANUP +CONTROL_PARENT_SECONDS = PARENT_SETUP_SECONDS + 7 * SECONDS_PER_CASE_WITH_CLEANUP + + +def require(condition, message): + """Refuse inconsistent inputs before publishing an evidence claim.""" + if not condition: + raise ValueError(message) + + +def digest(data): + """Hash the supplied bytes without adding framing.""" + return hashlib.sha256(data).hexdigest() + + +def file_hash(path): + """Hash a file in bounded chunks, including a host Node executable.""" + result = hashlib.sha256() + with path.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + result.update(block) + return result.hexdigest() + + +def canonical(value): + """Encode the ASCII manifest entries in the frozen compact property order.""" + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + + +def read_json(path): + """Read a JSON file from the parent process.""" + return json.loads(path.read_bytes()) + + +def git(repo, *arguments): + """Read a value from the requested Git checkout.""" + return subprocess.check_output(["git", "-C", repo, *arguments], text=True, timeout=GIT_SECONDS).strip() + + +def checkout(repo, revision): + """Verify the revision and clean working tree, and record its dependency lock.""" + require( + git(repo, "rev-parse", "HEAD") == revision and not git(repo, "status", "--porcelain"), + f"Use a clean checkout at {revision}: {repo}", + ) + return { + "revision": revision, + "tree": git(repo, "rev-parse", "HEAD^{tree}"), + "lock_sha256": file_hash(repo / "package-lock.json"), + } + + +def proof_environment(scratch): + """Give the proof tools a private home and npm cache for public, noninteractive package reads.""" + tools = [shutil.which(name) for name in ("node", "npm", "git")] + require(all(tools), "Install Node.js, npm and Git before running the proof.") + tool_dirs = [str(Path(tool).parent) for tool in tools] + env = { + "HOME": str(scratch), + "TMPDIR": str(scratch), + "PATH": os.pathsep.join(dict.fromkeys([*tool_dirs, *os.defpath.split(os.pathsep)])), + "LC_ALL": "C", + "TZ": "UTC", + "NODE_OPTIONS": "--no-global-search-paths", + "npm_config_cache": str(scratch / "npm-cache"), + "npm_config_userconfig": str(scratch / "user.npmrc"), + "npm_config_globalconfig": str(scratch / "global.npmrc"), + "npm_config_update_notifier": "false", + "npm_config_fetch_retries": "1", + "GIT_TERMINAL_PROMPT": "0", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ALLOW_PROTOCOL": "file:https", + "GIT_CONFIG_COUNT": "2", + "GIT_CONFIG_KEY_0": "url.https://github.com/.insteadOf", + "GIT_CONFIG_VALUE_0": "ssh://git@github.com/", + "GIT_CONFIG_KEY_1": "url.https://github.com/.insteadOf", + "GIT_CONFIG_VALUE_1": "git@github.com:", + } + if os.environ.get("npm_config_offline") == "true": + env["npm_config_offline"] = "true" + return env + + +def stage_locked_checkout(source, revision, destination): + """Install the committed lockfile in a fresh local clone without running package lifecycle scripts.""" + expected = checkout(source, revision) + env = proof_environment(destination.parent) + require(not destination.exists(), "Choose a fresh checkout destination.") + subprocess.run( + ["git", "clone", "--quiet", "--local", "--shared", "--no-checkout", "--", source, destination], + env=env, + check=True, + timeout=GIT_SECONDS, + ) + subprocess.run( + ["git", "-c", "core.hooksPath=" + os.devnull, "checkout", "--quiet", "--detach", revision], + cwd=destination, + env=env, + check=True, + timeout=GIT_SECONDS, + ) + subprocess.run( + ["npm", "ci", *INSTALL_FLAGS], + cwd=destination, + env=env, + check=True, + timeout=INSTALL_SECONDS, + ) + require(checkout(destination, revision) == expected, "The staged source or lockfile changed.") + return destination + + +def build_contracts_dependency(node, implementation, contracts, env): + """Verify the Git dependency's installed metadata and build its exports with its own locked compiler.""" + package = implementation / "node_modules/threadloop-contracts" + metadata = {"LICENSE", "README.md", "package.json"} + require( + package.is_dir() + and not package.is_symlink() + and {p.name for p in package.iterdir()} - {"node_modules"} == metadata, + "The fresh contracts install must contain only the pinned package metadata and its dependencies.", + ) + for name in sorted(metadata): + item = package / name + require( + item.is_file() + and not item.is_symlink() + and git(contracts, "hash-object", "--no-filters", str(item)) + == git(contracts, "rev-parse", CONTRACTS + ":" + name), + "The installed contracts package differs from its pinned Git source: " + name, + ) + subprocess.run( + [node, contracts / "scripts/build-package.mjs"], + cwd=contracts, + env=env, + check=True, + timeout=BUILD_SECONDS, + ) + # package.json maps ./assets/* to ./dist/docs/contracts/* alongside the generated JavaScript. + # npm owns the nested dependency versions in the ThreadLoop install. + (contracts / "dist").rename(package / "dist") + + +def pinned_inputs(harness, contracts): + """Verify the harness pins, the frozen source, executable corpus assets and schema inventories.""" + harness_info = checkout(harness, HARNESS) + contracts_info = checkout(contracts, CONTRACTS) + require( + git(contracts, "rev-parse", "v0.1.0^{}") == FREEZE, + "Restore the v0.1.0 contracts tag.", + ) + require( + read_json(REPO / "package-lock.json")["packages"]["node_modules/threadloop-contracts"][ + "resolved" + ].endswith("#" + CONTRACTS), + "The installed contracts must use the documented immutable pin.", + ) + pin = read_json(harness / "threadloop/pin.json") + require( + pin["revision"] == CORPUS_SOURCE and pin["corpus_digest"] == CORPUS, + "The harness corpus pin changed.", + ) + + def corpus_blobs(repo, revision): + """List the Git object identities of the frozen executable data and canonical vectors.""" + lines = git(repo, "ls-tree", "-r", revision, "--", str(CORPUS_DIR)).splitlines() + return [line for line in lines if line.endswith((".json", ".canonical"))] + + source_files = corpus_blobs(REPO, CORPUS_SOURCE) + require( + len(source_files) == 52 + and source_files == corpus_blobs(contracts, CONTRACTS) == corpus_blobs(contracts, FREEZE), + "The frozen JSON and canonical vectors differ between repositories or the release tag.", + ) + home = contracts / CORPUS_DIR + require( + len(pin["schemas"]) == 8 + and all(file_hash(home / "schemas" / name) == sha for name, sha in pin["schemas"].items()), + "A frozen conformance schema differs from the harness pin.", + ) + descriptor = read_json(home / "compatibility.json") + require( + digest(canonical(descriptor)) == COMPATIBILITY, + "Compatibility descriptor digest differs.", + ) + domain = { + row["name"]: {item["path"]: item["sha256"] for item in row["schemas"]} + for row in descriptor["contracts"] + } + require(sum(map(len, domain.values())) == 18, "Expected 18 pinned domain schemas.") + for family, schemas in domain.items(): + for name, sha in schemas.items(): + require( + file_hash(contracts / "docs/contracts" / (family + "-v0.1") / "schemas" / name) == sha, + "Domain schema differs: " + name, + ) + return { + "harness": harness_info, + "contracts": contracts_info, + "tag_revision": FREEZE, + "corpus_source_revision": CORPUS_SOURCE, + "source": pin, + "domain_schemas": domain, + } + + +def measure_build(build, contracts, head): + """Check the three runtime files against the declared closure and the upstream schemas.""" + runtime = build / "runtime" + entries = list(runtime.rglob("*")) + require( + runtime.is_dir() and not runtime.is_symlink() and all(not entry.is_symlink() for entry in entries), + "A staged runtime contains a symbolic link.", + ) + files = sorted(entry.relative_to(runtime) for entry in entries if not entry.is_dir()) + require( + files == sorted([SUBJECT, *SCHEMAS]) and all((runtime / path).is_file() for path in files), + "The readable runtime must contain the bundle and two regular schema files.", + ) + manifest = [ + { + "bytes": (runtime / path).stat().st_size, + "path": path.as_posix(), + "sha256": file_hash(runtime / path), + } + for path in files + ] + require( + manifest == read_json(build / "manifest.json"), + "Runtime bytes differ from their manifest.", + ) + for path in SCHEMAS: + require( + file_hash(runtime / path) == file_hash(contracts / path), + "An upstream schema changed during staging.", + ) + identity = { + "name": "threadloop-controller", + "revision": head, + "version": read_json(REPO / "package.json")["version"], + "artifact_digest": digest(canonical(manifest)), + } + require( + identity == read_json(build / "identity.json"), + "The controller identity differs from its source or runtime files.", + ) + meta = read_json(build / "build-metafile.json") + wire_names = { + "request.schema.json", + "response.schema.json", + "execution-scenario.schema.json", + } + for name in meta["inputs"]: + parts = Path(name).parts + require( + not ({"fixtures", "vectors", "tests", "test"} & set(parts)) + and "golden" not in parts + and (("docs" not in parts) or (Path(name).name in wire_names and "schemas" in parts)), + "The controller build includes an input outside its public runtime contracts: " + name, + ) + return identity, manifest + + +def public_cases(packet, inventory): + """Keep identities, machine outcomes and digests. Raw diagnostics and expected payloads stay with the parent.""" + cases = packet["cases"] + require(len(inventory) == len(cases) == 38, "The complete external suite has 38 cases.") + require( + Counter(row["operation"] for row in inventory) + == {"compile_graph": 3, "decide": 25, "execution_scenario": 10}, + "The frozen operation inventory differs.", + ) + published = [] + for index, (entry, result) in enumerate(zip(inventory, cases), 1): + require( + entry["id"] == f"case_{index:03d}" + and all( + entry[key] == result[key] for key in ("id", "operation", "input_digest", "request_digest") + ), + "Unbound result row.", + ) + status = result["status"] + require(status in STATUSES, "Unknown harness status.") + row = {key: entry[key] for key in ("id", "operation", "fixture_digest", "graph_digest")} + row["status"] = status + for field in ( + "input_digest", + "request_digest", + "response_digest", + "stdout_sha256", + "stderr_sha256", + ): + value = result[field] + require( + (value is None and status in ("protocol_error", "transport_error")) + or (isinstance(value, str) and re.fullmatch("[0-9a-f]{64}", value)), + "Malformed case digest.", + ) + row[field] = value + if "result_status" in result: + require( + result["result_status"] in ("compiled", "invalid", "decision", "execution"), + "Unknown result type.", + ) + row["result_status"] = result["result_status"] + outcome = result["controller_outcome"] + require(outcome is None or outcome in OUTCOMES, "Unknown controller outcome.") + row["controller_outcome"] = outcome + published.append(row) + counts = {status: sum(row["status"] == status for row in published) for status in STATUSES} + counts.update(total=len(published), failed=len(published) - counts["passed"]) + require( + all(count == packet[key] for key, count in counts.items()), + "Harness counts differ from the public rows.", + ) + return {**counts, "cases": published} + + +def await_case_teardown(roots, label): + """Wait for interrupted launchers to reap their sandboxed subjects and release their case directories.""" + import fcntl + + deadline = time.monotonic() + 3 + for root in roots: + descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + while True: + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + raise ValueError(f"{label} timed out and a case launcher still owns its scratch.") + time.sleep(0.02) + finally: + os.close(descriptor) + + +def bounded_parent(label, command, *, seconds, cwd, case_roots=(), data=None, env=None): + """Bound the Node parent separately from the frozen harness's own per-case process deadlines.""" + try: + return subprocess.run(command, input=data, capture_output=True, cwd=cwd, env=env, timeout=seconds) + except subprocess.TimeoutExpired as error: + # subprocess.run has killed and reaped its direct child. Each detached launcher observes reparenting. + await_case_teardown(case_roots, label) + raise ValueError(f"{label} exceeded its {seconds:g}-second deadline.") from error + + +def external_checks(node, arguments, case_roots=(), *, scripts=None, env=None): + """Read pinned harness metadata or run its independent negative controls in a separate parent process.""" + inventory = arguments.get("inventoryOnly", False) + result = bounded_parent( + "conformance inventory" if inventory else "conformance controls", + [node, (scripts or SCRIPTS) / "check-controls.cjs"], + cwd=scripts or SCRIPTS, + env=env, + seconds=PARENT_SETUP_SECONDS if inventory else CONTROL_PARENT_SECONDS, + case_roots=case_roots, + data=json.dumps(arguments).encode(), + ) + require( + result.returncode == 0, + "RunInvariant control failed: " + result.stderr.decode(errors="replace")[-400:], + ) + return json.loads(result.stdout) + + +def write_new(path, data): + """Make completed output visible at a fresh path with an exclusive link.""" + with tempfile.NamedTemporaryFile(dir=path.parent) as stage: + stage.write(data) + stage.flush() + os.link(stage.name, path) + + +def measure(args): + """Run the pinned CLI, project its raw packet, verify the control results and remove case-owned scratch.""" + require( + sys.platform == "darwin" and os.access("/usr/bin/sandbox-exec", os.X_OK), + "This proof requires macOS with /usr/bin/sandbox-exec. Run it on a supported macOS host.", + ) + require( + not args.output.exists() + and ( + not args.raw_output + or (args.raw_output.resolve() != args.output.resolve() and not args.raw_output.exists()) + ), + "Choose fresh, distinct output files.", + ) + harness, contracts, build = ( + args.harness.resolve(strict=True), + args.contracts.resolve(strict=True), + args.build.resolve(strict=True), + ) + node = Path(shutil.which("node") or "node").resolve(strict=True) + head = git(REPO, "rev-parse", "HEAD") + tree = checkout(REPO, head) + upstream = pinned_inputs(harness, contracts) + identity, manifest = measure_build(build, contracts, head) + node_hash = file_hash(node) + with tempfile.TemporaryDirectory(prefix="threadloop-controller-proof-") as directory: + scratch = Path(directory).resolve() + env = proof_environment(scratch) + implementation = stage_locked_checkout(REPO, head, scratch / "threadloop") + staged_contracts = stage_locked_checkout(contracts, CONTRACTS, scratch / "contracts") + build_contracts_dependency(node, implementation, staged_contracts, env) + scripts = implementation / "scripts/controller-conformance" + rebuilt = scratch / "build" + subprocess.run( + [node, scripts / "build.mjs", "--output", rebuilt], + cwd=implementation, + env=env, + check=True, + timeout=BUILD_SECONDS, + ) + require( + measure_build(rebuilt, contracts, head) == (identity, manifest), + "The submitted controller differs from the lockfile-based rebuild. Run npm ci and rebuild it.", + ) + original_inputs = read_json(build / "build-metafile.json")["inputs"] + require( + original_inputs == read_json(rebuilt / "build-metafile.json")["inputs"], + "The clean rebuild used a different input closure.", + ) + staged_harness = stage_locked_checkout(harness, HARNESS, scratch / "harness") + runtime = rebuilt / "runtime" + cases = scratch / "cases" + cases.mkdir() + controls_root = scratch / "controls" + controls_root.mkdir() + launcher = [ + sys.executable, + str(scripts / "launch.py"), + str(cases), + str(node), + str(runtime / SUBJECT), + *(str(runtime / path) for path in SCHEMAS), + ] + command = launcher + ["conformance"] + control = launcher.copy() + control[2], control[4] = str(controls_root), str(implementation / CONTROL.relative_to(REPO)) + settings = { + "harness": str(staged_harness), + "contracts": str(staged_contracts), + "identity": identity, + "command": command, + "control": control, + "controlRoot": str(controls_root), + } + inventory = external_checks(node, {**settings, "inventoryOnly": True}, scripts=scripts, env=env) + run = bounded_parent( + "RunInvariant harness", + [ + node, + staged_harness / "bin/run-invariant.js", + "threadloop", + "--checkout", + staged_contracts, + "--subject", + rebuilt / "identity.json", + "--subject-kind", + "controller", + "--json", + "--", + *command, + ], + cwd=scratch, + env=env, + seconds=HARNESS_PARENT_SECONDS, + case_roots=(cases,), + ) + require( + run.returncode in (0, 1), + "RunInvariant configuration failed: " + run.stderr.decode(errors="replace")[-400:], + ) + raw = json.loads(run.stdout) + if args.raw_output: + write_new(args.raw_output, run.stdout) + require( + raw["subject"] == identity + and raw["source"] == upstream["source"] + and raw["subject_kind"] == "controller" + and raw["schema"] == "run-invariant.threadloop-packet/0.1", + "Unexpected runner or subject identity.", + ) + require( + raw["contract"] == CONTRACT + and raw["runner"]["command"] == command + and raw["runner"]["limits"] == LIMITS, + "RunInvariant reported a different compatibility descriptor or process.", + ) + results = public_cases(raw["conformance"], inventory) + require( + run.returncode == int(results["failed"] > 0), + "RunInvariant exit status differs from its results.", + ) + proof = {"status": "suite_failed"} + if not results["failed"]: + private_files = { + "case": staged_contracts / CORPUS_DIR / "fixtures/case_024.json", + "shared_values": staged_contracts / CORPUS_DIR / "shared.json", + "golden": staged_contracts / CORPUS_DIR / "vectors/golden.json", + "synthetic_subject": staged_harness / "test/fixtures/threadloop-subject.js", + "build_inputs": rebuilt / "build-metafile.json", + "parent_identity": rebuilt / "identity.json", + } + settings["canaries"] = {name: str(path) for name, path in private_files.items()} + proof = external_checks(node, settings, (cases, controls_root), scripts=scripts, env=env)[ + "controls" + ] + for index in (0, 23): + row = results["cases"][index] + repeated = proof[row["id"]] + require( + all( + repeated[key] == row[key] + for key in ("request_digest", "response_digest", "stdout_sha256") + ), + "The repeated response differs from RunInvariant's row: " + row["id"], + ) + results["cases"][0]["graph_digest"] = proof["case_001"]["graph_digest"] + require( + measure_build(rebuilt, contracts, head) == (identity, manifest), + "The measured runtime changed.", + ) + require( + checkout(implementation, head) == tree + and checkout(staged_harness, HARNESS) == upstream["harness"] + and checkout(staged_contracts, CONTRACTS) == upstream["contracts"], + "A staged checkout or its lockfile changed during the proof.", + ) + node_version = subprocess.check_output( + [node, "--version"], env=env, text=True, timeout=PARENT_SETUP_SECONDS + ).strip() + npm_version = subprocess.check_output( + ["npm", "--version"], env=env, text=True, timeout=PARENT_SETUP_SECONDS + ).strip() + if not results["failed"]: + require(not any(cases.iterdir()), "A completed case retained scratch.") + require(not scratch.exists(), "The parent retained case scratch after the suite.") + proof["parent_scratch_removed"] = True + require( + checkout(REPO, head) == tree + and checkout(harness, HARNESS) == upstream["harness"] + and checkout(contracts, CONTRACTS) == upstream["contracts"] + and file_hash(node) == node_hash, + "A proof input changed.", + ) + report = { + "schema": "threadloop.controller-proof/1", + "implementation": tree, + "upstream": upstream, + "contract": raw["contract"], + "subject": identity, + "artifact_manifest": manifest, + "controls": proof, + "runner": { + "exit": run.returncode, + "packet_schema": raw["schema"], + "subject_kind": raw["subject_kind"], + "raw_packet_sha256": digest(run.stdout), + "limits": raw["runner"]["limits"], + "dependency_install": { + "install_method": "npm ci " + " ".join(INSTALL_FLAGS), + "npm_version": npm_version, + "sources": ["implementation", "upstream.contracts", "upstream.harness"], + "contracts_build": "node scripts/build-package.mjs", + }, + "parent_deadlines_seconds": { + "install_per_checkout": INSTALL_SECONDS, + "git": GIT_SECONDS, + "build": BUILD_SECONDS, + "node_version": PARENT_SETUP_SECONDS, + "inventory": PARENT_SETUP_SECONDS, + "harness": HARNESS_PARENT_SECONDS, + "controls": CONTROL_PARENT_SECONDS, + }, + "report_limits": raw["runner"]["report_limits"], + "process_cleanup": raw["runner"]["process_cleanup"], + "shell": raw["runner"]["shell"], + "claim_boundary": raw["claim_boundary"], + "platform": platform.mac_ver()[0], + "architecture": platform.machine(), + "node_version": node_version, + "node_sha256": node_hash, + "launcher_sha256": file_hash(SCRIPTS / "launch.py"), + "policy_sha256": file_hash(SCRIPTS / "subject.sb"), + "build_metafile_sha256": file_hash(build / "build-metafile.json"), + }, + "conformance": results, + } + write_new(args.output, (json.dumps(report, indent=2) + "\n").encode()) + print(f"{results['passed']}/{results['total']} passed. Packet SHA-256 {file_hash(args.output)}") + return run.returncode + + +def main(): + """Parse explicit local inputs. All published results come from the measured invocation.""" + parser = argparse.ArgumentParser( + description=__doc__ + " Isolation requires macOS with /usr/bin/sandbox-exec." + ) + for option in ("harness", "contracts", "build", "output"): + parser.add_argument("--" + option, required=True, type=Path) + parser.add_argument( + "--raw-output", + type=Path, + help="Optional new private file for the original RunInvariant packet, including local paths.", + ) + args = parser.parse_args() + try: + return measure(args) + except (ValueError, KeyError, OSError, subprocess.SubprocessError) as error: + print(f"Controller proof failed: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/controller-conformance/scenario-journal.ts b/scripts/controller-conformance/scenario-journal.ts new file mode 100644 index 0000000..2ecf58c --- /dev/null +++ b/scripts/controller-conformance/scenario-journal.ts @@ -0,0 +1,54 @@ +import { pathToFileURL } from 'node:url'; +import { applyExecutionOperation, projectExecution } from 'threadloop-contracts/execution'; +import type { ExecutionAuthority, ExecutionJournal } from 'threadloop-contracts/execution'; +import { isPlainObject } from '../../src/domain/canonical-json.js'; +import { DatabaseSync } from '../../src/adapters/fs/sqlite-driver.js'; +import { readSealedRoot, sealedRootTable, writeSealedRoot } from '../../src/adapters/fs/sealed-root.js'; + +/** One private scenario journal. Each method opens its own connection. */ +export class ScenarioJournal { + constructor( + private readonly filename: string, + private readonly authority: ExecutionAuthority, + ) {} + private write<T>(creating: boolean, operation: (database: DatabaseSync) => T): T { + const file = pathToFileURL(this.filename); + file.searchParams.set('mode', creating ? 'rwc' : 'rw'); + const database = new DatabaseSync(file.href); + try { + database.exec('PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL'); + database.exec('BEGIN IMMEDIATE'); + const result = operation(database); + database.exec('COMMIT'); + return result; + } finally { + database.close(); + } + } + initialize(journal: ExecutionJournal): void { + this.write(true, (database) => { + database.exec(sealedRootTable); + writeSealedRoot(database, journal); + }); + } + apply(context: unknown, operation: unknown) { + return this.write(false, (database) => { + const row = readSealedRoot(database); + const applied = applyExecutionOperation(row.value, context, operation, this.authority); + if (!applied.ok) return applied; + if (!isPlainObject(row.value) || row.value.execution_digest !== applied.value.expected_execution_digest) + throw new Error('Execution proposal differs from the retained predecessor.'); + if (!applied.value.replayed) writeSealedRoot(database, applied.value.journal, row.digest); + return applied; + }); + } + project(snapshot: unknown) { + const database = new DatabaseSync(this.filename, { readOnly: true }); + try { + database.exec('PRAGMA busy_timeout=5000'); + return projectExecution(readSealedRoot(database).value, snapshot, this.authority); + } finally { + database.close(); + } + } +} diff --git a/scripts/controller-conformance/subject.sb b/scripts/controller-conformance/subject.sb new file mode 100644 index 0000000..58aad32 --- /dev/null +++ b/scripts/controller-conformance/subject.sb @@ -0,0 +1,18 @@ +(version 1) +(allow default) +(deny file-read* file-write* network* process-fork process-exec) +(import "dyld-support.sb") +(allow process-exec (literal (param "NODE"))) +(allow file-read-data file-read-metadata file-map-executable + (literal (param "NODE")) + (literal (param "ARTIFACT")) + (literal (param "REQUEST_SCHEMA")) + (literal (param "RECEIPT_SCHEMA")) + (subpath "/System/Library") + (subpath "/usr/lib") + (literal "/dev/null") + (literal "/dev/random") + (literal "/dev/urandom")) +(allow file-read-metadata (literal "/") (literal "/private") (literal "/private/tmp")) +(allow file-read* file-write* (subpath (param "SCRATCH"))) +(allow file-read-metadata (path-ancestors (param "ARTIFACT")) (path-ancestors (param "SCRATCH")) (path-ancestors (param "NODE"))) diff --git a/scripts/controller-conformance/subject.ts b/scripts/controller-conformance/subject.ts new file mode 100644 index 0000000..a326f6a --- /dev/null +++ b/scripts/controller-conformance/subject.ts @@ -0,0 +1,85 @@ +import { fileURLToPath } from 'node:url'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import { canonicalExecutorJson, parseExecutorMessage } from 'threadloop-contracts/executor'; +import requestSchema from 'threadloop-contracts/assets/controller-conformance-v0.1/schemas/request.schema.json' with { type: 'json' }; +import responseSchema from 'threadloop-contracts/assets/controller-conformance-v0.1/schemas/response.schema.json' with { type: 'json' }; +import { z } from 'zod'; +import { sha256 } from '../../src/adapters/crypto/sha256.js'; +import { measureSubject } from './artifact.js'; +import { runControllerOperation, type Operation } from './operations.js'; + +declare const THREADLOOP_SUBJECT_VERSION: string; +declare const THREADLOOP_SUBJECT_REVISION: string; +interface Request { + request: { + protocol: string; + schema: string; + fixture_schema: string; + canonicalization: string; + digest_profile: string; + corpus_digest: string; + case_id: string; + operation: Operation; + input: unknown; + input_digest: string; + }; + request_digest: string; +} +const validator = new Ajv2020({ strict: true, strictTypes: false }); +const dateTime = z.iso.datetime({ precision: 3 }); +validator.addFormat('date-time', { type: 'string', validate: (value: string) => dateTime.safeParse(value).success }); +const validRequest = validator.compile<Request>(requestSchema); +const validResponse = validator.compile(responseSchema); +const maxFramedBytes = 16 * 1024 * 1024 + 1; + +async function readRequest() { + const chunks: Buffer[] = []; + let length = 0; + for await (const bytes of process.stdin as AsyncIterable<Buffer>) { + length += bytes.length; + if (length > maxFramedBytes) throw new Error('Request exceeds the frozen message byte limit.'); + chunks.push(bytes); + } + const parsed = parseExecutorMessage(Buffer.concat(chunks, length)); + if (!parsed.ok) throw new Error('Invalid conformance request framing: ' + parsed.diagnostics[0]?.code); + if (!validRequest(parsed.value)) throw new Error('Invalid conformance request envelope.'); + return parsed.value; +} +function canonical(value: unknown) { + const result = canonicalExecutorJson(value); + if (!result.ok) throw new Error('Value exceeds the frozen canonical JSON contract: ' + result.diagnostics[0]?.code); + return result.value; +} +async function main() { + if (process.argv.length !== 3 || process.argv[2] !== 'conformance') throw new Error('Use the conformance command.'); + const { request, request_digest } = await readRequest(); + if (sha256(canonical(request.input)) !== request.input_digest || sha256(canonical(request)) !== request_digest) + throw new Error('The input or request digest differs from its canonical bytes.'); + const { identity } = measureSubject( + fileURLToPath(new URL('../../', import.meta.url)), + THREADLOOP_SUBJECT_VERSION, + THREADLOOP_SUBJECT_REVISION, + ); + const result = runControllerOperation(request.operation, request.input); + const response = { + protocol: request.protocol, + fixture_schema: request.fixture_schema, + canonicalization: request.canonicalization, + digest_profile: request.digest_profile, + schema: 'threadloop.conformance-response/0.1', + request_digest, + subject: identity, + result, + }; + // Domain records can share bindings in memory. Each occurrence becomes a separate JSON value on the wire. + const wireResponse: unknown = JSON.parse(JSON.stringify(response)); + const envelope = { response: wireResponse, response_digest: sha256(canonical(wireResponse)) }; + if (!validResponse(envelope)) throw new Error('The controller result failed the frozen response schema.'); + process.stdout.write(canonical(envelope) + '\n'); +} +try { + await main(); +} catch (error) { + process.stderr.write((error instanceof Error ? error.message.slice(0, 512) : 'Conformance operation failed.') + '\n'); + process.exitCode = 1; +} diff --git a/scripts/pre-rust/README.md b/scripts/pre-rust/README.md new file mode 100644 index 0000000..9f61b26 --- /dev/null +++ b/scripts/pre-rust/README.md @@ -0,0 +1,59 @@ +# Reproduce the TypeScript baseline + +These commands build local tarballs, install them offline and exercise the installed commands in disposable Git +repositories. Use a clone with full Git history and its matching `npm ci` installation. The package version is `0.1.0` +across these revisions. Git and SHA-256 identify the builds. + +Each comparison uses the named Git revisions and the checkout's installed build tools to rebuild the requested archives +offline. It checks every supplied archive and its CLI against those builds before installing any of them. The dependency +installation in the checkout is a trusted input. An adjacent provenance file alone can't authenticate an archive. Use +the recorded Node and npm build versions to reproduce the exact tarball bytes. + +## CLI and storage + +Choose a new evidence directory outside the checkout. Each script refuses an existing output. The historic inputs share +the candidate's dependency lock at the measured revision. Use an isolated checkout with the matching lock when that +changes. + +```sh +REPO=$(git rev-parse --show-toplevel) +REV=$(git rev-parse HEAD) +EVIDENCE=$(mktemp -d) +RUNS_V1=31388a07566350dfeddc30578d43b8926d5b4e22 +PRE_ADOPTION=7c54c2bb8055f00736e3b5f6631e9aecbe0fd212 +python3 -B scripts/pre-rust/pack.py "$REPO" "$REV" "$EVIDENCE/current" +python3 -B scripts/pre-rust/pack.py "$REPO" "$RUNS_V1" "$EVIDENCE/runs-v1" +python3 -B scripts/pre-rust/pack.py "$REPO" "$PRE_ADOPTION" "$EVIDENCE/old-storage" +python3 -B scripts/pre-rust/installed_parity.py "$REPO" "$REV" "$EVIDENCE/current" \ + "$EVIDENCE/runs-v1" "$EVIDENCE/old-storage" "$EVIDENCE/installed-parity.json" +python3 -B scripts/pre-rust/managed_rollback.py "$REPO" "$REV" "$EVIDENCE/current" \ + "$EVIDENCE/runs-v1" "$EVIDENCE/managed-rollback.json" +``` + +Run the last two commands with each supported Node major first on `PATH` and a separate JSON output for each run. The +measured hosts and versions appear in the [readiness report](../../docs/pre-rust-readiness.md). The scripts require +Python 3.9+, Git, npm and a POSIX shell environment for the editor fixture. + +The CLI comparison records each declared command's installed help, default and negotiated protocol bytes, representative +error envelopes, Git snapshots, the three Markdown artifacts and a race between two CLI processes. The storage check +reads a store created by the pre-adoption CLI. A separate rollback check changes a v1 Workflow Run checkout with the +current CLI and reopens its offline backup with both packages. It checks audit exports, the state database and read-side +WAL or SHM files separately. WAL is SQLite's write-ahead log. SHM is its shared-memory index. + +## Restoring managed execution + +Keep the controlling repository, its immutable graph and its enrolled `executor.sqlite` together. Quiesce writers and +verify both databases before copying them. The managed proof runs a full checkpoint, compares file hashes and keeps the +external subject and an invocation counter outside the backup. It compares the retained executor output paths and file +bytes before and after restoration. It restores only fixtures it created, at their original paths. + +1. In the lost-response case, the producer changed the subject and stopped before it reported the effect. Both the + restored CLI and a repeated delivery hold the Attempt for reconciliation. The independent counter records one + invocation. +2. In the admitted case, the child committed a signed receipt before outer reporting stopped. The restored CLI imports + that receipt and the caller can replay the same result. The child retains one invocation. The Workflow Run stays at + the same lifecycle version. + +Restoring a backup discards writes committed afterward. The proof records the discarded legacy transition and any later +outer import. The old CLI can still inspect a supported v1 run in the same database. Its managed-run and child +operations refuse the newer data. diff --git a/scripts/pre-rust/installed_parity.py b/scripts/pre-rust/installed_parity.py new file mode 100644 index 0000000..2ddbf24 --- /dev/null +++ b/scripts/pre-rust/installed_parity.py @@ -0,0 +1,482 @@ +#!/usr/bin/env python3 +"""Compare three installed ThreadLoop revisions in disposable Git repositories.""" + +from concurrent.futures import ThreadPoolExecutor +from contextlib import closing +from hashlib import sha256 +from pathlib import Path +from tempfile import TemporaryDirectory +import argparse +import json +import platform +import re +from proof_package import PRE_RUNS, RUNS_V1, install_packages, offline_environment, write_report +import shutil +import sqlite3 +import subprocess + +args = argparse.ArgumentParser(description=__doc__) +args.add_argument("checkout", type=Path, help="checkout containing the source revisions") +args.add_argument("revision", help="full SHA of the candidate package") +args.add_argument("candidate", type=Path, help="directory from pack.py") +args.add_argument("rollback", type=Path, help="directory from pack.py") +args.add_argument("pre_adoption", type=Path, help="package from the original program baseline") +args.add_argument("new_report", type=Path) +opt = args.parse_args() +if not __debug__: + args.error("This proof requires active assertions. Run Python without -O.") +if opt.new_report.exists(): + args.error("Supply a fresh output filename.") +report = { + "host": platform.platform(), + "packages": {}, + "protocol": {}, + "help": {}, + "failure_envelopes": [], + "reader_sidecars": {}, +} +original = "750ae36b6b7b6ea34081a8c90236d8c95f71b086" + + +def digest(value): + """Return the SHA-256 hex digest of the supplied bytes.""" + return sha256(value).hexdigest() + + +def raw(*args, cwd=None): + """Run a command in the proof environment and return its stdout bytes on success.""" + return subprocess.check_output(args, cwd=cwd, env=env, stderr=subprocess.PIPE, timeout=60) + + +def git_object(revision, name): + """Read the exact bytes of a tracked path at the specified revision.""" + return raw("git", "-C", opt.checkout.resolve(), "show", revision + ":" + name) + + +def run(binary, cwd, *args): + """Capture an installed CLI command's exit status, stdout and stderr within 45 seconds.""" + return subprocess.run([binary, *args], cwd=cwd, env=env, capture_output=True, timeout=45) + + +def ok(binary, cwd, *args): + """Return the CLI's stdout after checking for a zero exit status and empty stderr.""" + out = run(binary, cwd, *args) + assert out.returncode == 0 and not out.stderr, (args, out.returncode, out.stderr[:900]) + return out.stdout + + +def data(binary, cwd, *args): + """Request JSON output and return the data from a successful CLI response.""" + val = json.loads(ok(binary, cwd, *args, "--json")) + assert val["ok"] is True + return val["data"] + + +def rejected(binary, cwd, args, code): + """Check the CLI's error code, output stream and exit status, then record the refusal.""" + out = run(binary, cwd, *args, "--json") + assert out.returncode == 1 and not out.stdout, (args, out.returncode, out.stdout[:400]) + value = json.loads(out.stderr) + assert value["ok"] is False and value["error"]["code"] == code, (args, code, value) + report["failure_envelopes"].append( + {"operation": args[:2], "code": code, "exit": out.returncode, "stream": "stderr"} + ) + + +def git_repo(name): + """Create a disposable Git repository on main with one committed README.""" + path = temp / name + path.mkdir() + raw("git", "init", "-qb", "main", path) + for key, value in [ + ("user.name", "Parity Test"), + ("user.email", "parity@example.invalid"), + ("commit.gpgsign", "false"), + ]: + raw("git", "config", key, value, cwd=path) + (path / "README.md").write_text("# Parity\n") + raw("git", "add", "README.md", cwd=path) + raw("git", "commit", "-qm", "Initial subject", cwd=path) + return path + + +def dbfile(repo): + """Return the path to the session database inside the fixture repository.""" + return repo / ".threadloop/state/state.db" + + +def fingerprints(repo): + """Hash the state database and every state.db sidecar present in its directory.""" + db = dbfile(repo) + return {p.name: digest(p.read_bytes()) for p in db.parent.glob("state.db*") if p.is_file()} + + +def committed_files(files): + """Omit shared-memory indexes and empty write-ahead logs when comparing database fingerprints.""" + return { + k: v + for k, v in files.items() + if not k.endswith("-shm") and not (k.endswith("-wal") and v == digest(b"")) + } + + +def reads(binary, repo, session, label): + """Hash session and audit output and verify the reads preserve committed database bytes.""" + before = fingerprints(repo) + args = ["--session", session, "--json"] + checks = { + " ".join(cmd): digest(ok(binary, repo, *cmd, *args)) + for cmd in [("session", "status"), ("session", "next"), ("audit", "show"), ("audit", "verify")] + } + export = temp / (label + ".jsonl") + data(binary, repo, "audit", "export", "--session", session, "--output", str(export)) + checks["audit export"] = digest(export.read_bytes()) + after = fingerprints(repo) + assert committed_files(after) == committed_files(before), (label, before, after) + report["reader_sidecars"][label] = {"before": before, "after": after} + return checks + + +def fresh_protocol(binary, version): + """Hash both protocol outputs and collect the advertised commands, versions and capabilities.""" + view = ["--contract", version] if version else [] + enc = ok(binary, temp, "protocol", *view, "--json") + plain = ok(binary, temp, "protocol", *view) + info = json.loads(enc)["data"] + return { + "json_sha256": digest(enc), + "text_sha256": digest(plain), + "commands": info["commands"], + "contractVersions": info["contractVersions"], + "capabilities": info.get("capabilities", []), + } + + +with TemporaryDirectory(prefix="threadloop-parity-") as owned: + temp = Path(owned).resolve() + env = { + **offline_environment(temp), + "TMPDIR": str(temp), + "NODE_NO_WARNINGS": "1", + "NO_COLOR": "1", + "GIT_CEILING_DIRECTORIES": str(temp.parent), + "TZ": "UTC", + } + + report["node"] = raw("node", "--version").decode().strip() + packages = install_packages( + opt.checkout.resolve(), + { + "candidate": (opt.candidate.resolve(), opt.revision), + "rollback": (opt.rollback.resolve(), RUNS_V1), + "pre_adoption": (opt.pre_adoption.resolve(), PRE_RUNS), + }, + temp, + env, + ) + report["packages"] = {label: record for label, (_, record) in packages.items()} + candidate = packages["candidate"][0] + old = packages["rollback"][0] + historic = packages["pre_adoption"][0] + report["versions"] = { + name: ok(binary, temp, "--version").decode().strip() + for name, binary in [("candidate", candidate), ("rollback", old)] + } + for version in ["", "4", "5"]: + report["protocol"][version or "default"] = fresh_protocol(candidate, version) + assert report["protocol"]["default"] == report["protocol"]["4"] + assert ( + report["protocol"]["4"]["json_sha256"] + == "e5943879bfaf27696f0c791adca0d5510e6e49d5660edfa9beb75931c846ed90" + ) + assert ( + report["protocol"]["4"]["text_sha256"] + == "5ac51f9c27359b9f27e717adec58d4b85c3e78e4b721957ed534f2d9a7e40fcf" + ) + report["rollback_default"] = fresh_protocol(old, "") + assert report["rollback_default"]["json_sha256"] == report["protocol"]["4"]["json_sha256"] + assert report["rollback_default"]["text_sha256"] == report["protocol"]["4"]["text_sha256"] + for name in ["", *report["protocol"]["5"]["commands"]]: + report["help"][name or "threadloop"] = ok(candidate, temp, *name.split(), "--help").decode() + missing = run(candidate, temp) + assert missing.returncode == 1 and not missing.stdout and b"Usage:" in missing.stderr + report["no_args"] = {"exit": 1, "stderr": missing.stderr.decode()} + for name in ["start", "capture", "status", "finish", "session finish", "daemon run"]: + rejected(candidate, temp, name.split(), "INVALID_ARGUMENT") + rejected(candidate, temp, ["session", "list"], "NOT_GIT_REPOSITORY") + repo = git_repo("workspace") + rejected(candidate, repo, ["session", "list"], "THREADLOOP_NOT_INITIALIZED") + ok(old, repo, "init") + raw("git", "checkout", "-qb", "feature/parity", cwd=repo) + (repo / "feature.ts").write_text("export const feature = 1;\n") + raw("git", "add", "feature.ts", cwd=repo) + raw("git", "commit", "-qm", "Exercise base-aware scope", cwd=repo) + session = data( + old, repo, "session", "start", "Parity session", "--goal", "Verify rollback", "--base", "main" + )["session_id"] + pre = reads(old, repo, session, "pre-old") + pre_db = fingerprints(repo) + saved = temp / "pre-upgrade" + shutil.copytree(repo / ".threadloop", saved) + assert reads(candidate, repo, session, "pre-current") == pre + rejected(candidate, repo, ["session", "status"], "SESSION_REQUIRED") + rejected(candidate, repo, ["session", "status", "--session", "absent"], "SESSION_NOT_FOUND") + rejected( + candidate, repo, ["session", "start", "test", "--goal", "x", "--base", "absent"], "BASE_REF_NOT_FOUND" + ) + rejected(candidate, repo, ["session", "reconcile"], "RECONCILE_TARGET_REQUIRED") + editor = temp / "fixture-editor" + editor.write_text("#!/bin/sh\nprintf '%s\\n' 'Inspect the parity marker' > \"$1\"\n") + editor.chmod(0o700) + env["EDITOR"] = str(editor) + data(candidate, repo, "session", "capture", "reviewer_guidance", "--session", session, "--edit") + for cmd in [ + ("heartbeat", "--source", "daemon", "--session", session), + ("reconcile", "--session", session), + ("reconcile", "--all"), + ]: + data(candidate, repo, "session", *cmd) + status = data(candidate, repo, "session", "status", "--session", session) + assert "feature.ts" in status["repo_snapshot"]["changedFiles"], status["repo_snapshot"] + assert status["session"]["last_heartbeat_source"] == "daemon", status["session"] + for kind in ["change-brief", "pr-summary", "handoff"]: + data(candidate, repo, "artifact", "generate", kind) + artifacts = {p.suffixes[-2]: p.read_text() for p in (repo / ".threadloop/artifacts").glob("*.md")} + assert len(artifacts) == 3 and "Inspect the parity marker" in artifacts[".pr-summary"] + assert "feature.ts" in artifacts[".change-brief"] and ".threadloop/" not in artifacts[".change-brief"] + report["artifacts"] = {k: digest(text.encode()) for k, text in artifacts.items()} + second_start = data(candidate, repo, "session", "start", "Second session", "--goal-edit") + second = second_start["session_id"] + assert second_start["task"]["goal"] == "Inspect the parity marker" + rejected(candidate, repo, ["artifact", "generate"], "SESSION_AMBIGUOUS") + assert len(data(candidate, repo, "session", "list")["sessions"]) == 2 and second != session + + def frame(key): + """Build the framed-transition arguments for a version-zero session using the supplied replay key.""" + return [ + "session", + "transition", + "framed", + "--session", + session, + "--expected-state-version", + "0", + "--idempotency-key", + key, + "--actor", + "agent", + "--input", + "{}", + "--json", + ] + + keys = ["parity-left", "parity-right"] + with ThreadPoolExecutor(max_workers=2) as racers: + result = list(racers.map(lambda key: run(candidate, repo, *frame(key)), keys)) + assert sorted(x.returncode for x in result) == [0, 1], [(x.returncode, x.stderr[:400]) for x in result] + winner = next(i for i, x in enumerate(result) if x.returncode == 0) + assert json.loads(result[1 - winner].stderr)["error"]["code"] == "STATE_VERSION_CONFLICT" + assert ok(candidate, repo, *frame(keys[winner])) == result[winner].stdout + report["race"] = { + "winner": keys[winner], + "loser": "STATE_VERSION_CONFLICT", + "replay_sha256": digest(result[winner].stdout), + } + + revision = report["packages"]["candidate"]["revision"] + subject = git_repo("subject") + profile = temp / "quote.yaml" + profile.write_bytes(git_object(revision, "tests/fixtures/workflow/quote.yaml")) + setup = temp / "setup.json" + setup.write_text( + json.dumps( + dict( + schema_version="threadloop.workflow-setup/1", + subject_workspace=str(subject), + repository_id="fixture-repository", + policy=dict( + id="fixture-policy", + proof_binding_transition_id=None, + local_gate_ids=[], + independent_gate_ids=[], + publication_destination=None, + ), + proof_plan=None, + trusted_sources=None, + allowed_change_paths=[], + ) + ) + ) + graph = data( + candidate, repo, "workflow", "create", "quote", "--profile", str(profile), "--setup", str(setup) + ) + unsupported = temp / "future.json" + unsupported.write_text(json.dumps({"schema_version": "threadloop.workflow-setup/999"})) + rejected( + candidate, + repo, + ["workflow", "create", "future", "--profile", str(profile), "--setup", str(unsupported)], + "WORKFLOW_RUNTIME_UNSUPPORTED", + ) + rejected(candidate, repo, ["workflow", "inspect", "future"], "WORKFLOW_RUN_NOT_FOUND") + profile.write_text("schema_version: invalid\n") + assert data(candidate, repo, "workflow", "inspect", "quote") == graph + observed = ok(candidate, repo, "workflow", "decide", "quote", "--json") + decision = temp / "decision.json" + decision.write_bytes(observed) + apply = ["workflow", "apply", "quote", "--decision", str(decision), "--idempotency-key", "parity-apply"] + data(candidate, repo, *apply) + reopened = data(candidate, repo, "workflow", "inspect", "quote") + data(candidate, repo, *apply) + assert reopened["state"] == "prepared" and reopened["state_version"] == 1 + assert data(candidate, repo, "workflow", "inspect", "quote") == reopened + report["workflow"] = { + "graph_digest": graph["graph_digest"], + "initial": graph["state"], + "final": reopened["state"], + "final_version": reopened["state_version"], + "exact_replay_preserved": True, + } + assert data(old, repo, "workflow", "inspect", "quote") == reopened + report["rollback_workflow_v1"] = "read identical state" + post = reads(candidate, repo, session, "post-current") + assert post == reads(old, repo, session, "post-old") and post["audit export"] != pre["audit export"] + post_db = fingerprints(repo) + (repo / ".threadloop").rename(temp / "post-upgrade") + shutil.copytree(saved, repo / ".threadloop") + assert fingerprints(repo) == pre_db + assert ( + pre + == reads(old, repo, session, "restored-old") + == reads(candidate, repo, session, "restored-current") + ) + assert len(data(old, repo, "session", "list")["sessions"]) == 1 + rejected(candidate, repo, ["workflow", "inspect", "quote"], "WORKFLOW_RUN_NOT_FOUND") + report["rollback_proof"] = dict( + pre_upgrade=pre, + post_upgrade=post, + restored=pre, + pre_files=pre_db, + post_files=post_db, + restored_files=fingerprints(repo), + post_upgrade_session_absent=True, + post_upgrade_workflow_absent=True, + ) + + jsonrepo = git_repo("legacy-json") + legacyfile = jsonrepo / ".threadloop/state/state.json" + legacyfile.parent.mkdir(parents=True) + historical = { + "id": "legacy-task", + "title": "Legacy sentinel", + "goal": "Verify JSON migration", + "constraints": [], + "repoRoot": str(jsonrepo), + "status": "active", + "createdAt": "2020-01-01T00:00:00.000Z", + } + legacyfile.write_text( + json.dumps({"tasks": [historical], "sessions": [], "entries": [], "artifacts": [], "active": None}) + ) + json_hash = digest(legacyfile.read_bytes()) + ok(candidate, jsonrepo, "init") + with closing(sqlite3.connect(dbfile(jsonrepo))) as db: + assert db.execute("SELECT count(*) FROM tasks WHERE id=?", ("legacy-task",)).fetchone()[0] == 0 + assert db.execute("SELECT value FROM metadata WHERE key='schema_version'").fetchone()[0] == "8" + assert json_hash == digest(legacyfile.read_bytes()) + one = git_repo("schema-one") + target = one / ".threadloop" + (target / "state").mkdir(parents=True) + shutil.copy(jsonrepo / ".threadloop/config.json", target / "config.json") + old_store = git_object(original, "src/adapters/fs/sqlite-store.ts").decode() + ddl = ( + old_store.split("function bootstrapDatabase(db: DatabaseSync) {", 1)[1] + .split("db.exec(\x60", 1)[1] + .split("\x60);", 1)[0] + ) + assert "CREATE TABLE IF NOT EXISTS repo_snapshots" in ddl + with closing(sqlite3.connect(dbfile(one))) as db: + db.executescript(ddl) + db.execute("INSERT INTO metadata (key,value) VALUES ('schema_version','1')") + db.commit() + bad_before = fingerprints(one) + rejected(candidate, one, ["session", "list"], "STATE_CORRUPTED") + assert committed_files(bad_before) == committed_files(fingerprints(one)) + # A future generation must also survive an attempted initialization. + future = git_repo("future-generation") + future_db = dbfile(future) + future_db.parent.mkdir(parents=True) + shutil.copy(jsonrepo / ".threadloop/config.json", future / ".threadloop/config.json") + with closing(sqlite3.connect(future_db)) as db: + db.execute("CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)") + db.execute("INSERT INTO metadata VALUES ('schema_version','9')") + db.commit() + future_before = fingerprints(future) + rejected(candidate, future, ["session", "list"], "STATE_CORRUPTED") + assert future_before == fingerprints(future) + init = run(candidate, future, "init") + assert init.returncode == 1 and b"Unsupported ThreadLoop schema version: 9" in init.stderr + assert future_before == fingerprints(future) + report["storage"] = dict( + generation=8, + future_generation_refused_without_writes=future_before, + legacy_json_sha256=json_hash, + legacy_task_imported=False, + generation_one_ddl_revision=original, + generation_one_ddl_sha256=digest(ddl.encode()), + rejected_read_preserved_files=bad_before, + ) + untouched = git_repo("pre-adoption") + hist_session = data( + historic, untouched, "session", "start", "Historical receipts", "--goal", "Retain the audit root" + )["session_id"] + before = reads(historic, untouched, hist_session, "old-shape-original") + old_bytes = committed_files(fingerprints(untouched)) + after = reads(candidate, untouched, hist_session, "old-shape-candidate") + assert before["audit export"] == after["audit export"] and old_bytes == committed_files( + fingerprints(untouched) + ) + with closing(sqlite3.connect("file:" + str(dbfile(untouched)) + "?mode=ro", uri=True)) as conn: + assert ( + conn.execute( + "SELECT count(*) FROM sqlite_schema WHERE name IN ('gate_result_catalog','workflow_events')" + ).fetchone()[0] + == 0 + ) + lifecycle = data(candidate, untouched, "session", "next", "--session", hist_session)["lifecycle"] + assert lifecycle["storage_schema_version"] == 8 and "session_next_v1" in lifecycle["storage_capabilities"] + original_next = data(historic, untouched, "session", "next", "--session", hist_session) + current_next = data(candidate, untouched, "session", "next", "--session", hist_session) + current_next["lifecycle"].pop("storage_capabilities") + assert original_next == current_next + report["pre_adoption"] = dict( + original_reads=before, + candidate_reads=after, + database=old_bytes, + catalog_and_workflow_tables_absent=True, + capabilities=lifecycle["storage_capabilities"], + next_other_fields_identical=True, + ) + report["declared_error_codes"] = { + revision: re.findall( + r"'([A-Z_]+)'", + git_object(revision, "src/contracts/errors.ts").decode().split("] as const;", 1)[0], + ) + for revision in [original, report["packages"]["candidate"]["revision"]] + } + assert set(report["declared_error_codes"][original]) <= { + row["code"] for row in report["failure_envelopes"] + } + report["runner_sha256"] = { + revision: digest(git_object(revision, ".agents/skills/threadloop-runner/SKILL.md")) + for revision in [ + report["packages"]["candidate"]["revision"], + report["packages"]["rollback"]["revision"], + "7c54c2bb8055f00736e3b5f6631e9aecbe0fd212", + ] + } + +write_report(opt.new_report, report) +print( + f"{len(report['help']) - 1} command help entries verified. Rollback restored the original database and audit export." +) diff --git a/scripts/pre-rust/managed_rollback.py b/scripts/pre-rust/managed_rollback.py new file mode 100644 index 0000000..1410a55 --- /dev/null +++ b/scripts/pre-rust/managed_rollback.py @@ -0,0 +1,668 @@ +#!/usr/bin/env python3 +"""Verify two managed Workflow Run snapshots with the installed candidate and #170 CLIs.""" + +import argparse +import base64 +import json +import os +from pathlib import Path +import re +import shutil +import signal +import sqlite3 +import stat +import subprocess +import tempfile + +from hashlib import sha256 +from proof_package import RUNS_V1, file_hash, install_packages, require, offline_environment, write_report + +OLD_MERGE = "bdf68cc2d3ad915d085aecff47c9181f65fb5205" +RUN = "session_wf_rollback" +LEGACY = "session_wf_previous_reader" +CASE_LIMIT = 64 * 1024 * 1024 + + +def sha(data): + """Return the SHA-256 hex digest of the supplied bytes.""" + return sha256(data).hexdigest() + + +def run(args, cwd, env, timeout=65): + """Run the command within its time limit and capture the exit status and both output streams.""" + return subprocess.run( + [os.fspath(arg) for arg in args], cwd=cwd, env=env, capture_output=True, timeout=timeout + ) + + +def success(args, cwd, env): + """Return stdout on success or report the failed command with its trailing stderr.""" + proc = run(args, cwd, env) + require(proc.returncode == 0, f"{args[0]} {args[1:3]} exited {proc.returncode}: {proc.stderr[-1600:]!r}") + return proc.stdout + + +def cli(binary, cwd, env, args): + """Request JSON from the installed CLI and check the successful response envelope.""" + output = json.loads(success([binary, *args, "--json"], cwd, env)) + require(output["ok"] is True, f"Unsuccessful result for {args[:2]}") + return output + + +def refuse(binary, cwd, env, args, code, reason=None): + """Verify the refusal on stderr and return its exit status, error code and reason.""" + proc = run([binary, *args, "--json"], cwd, env) + require( + proc.returncode == 1 and not proc.stdout.strip(), + f"Expected refusal for {args[:2]}: {proc.returncode}", + ) + error = json.loads(proc.stderr)["error"] + require(error["code"] == code and (reason is None or error["details"]["reason"] == reason), repr(error)) + return {"exit": proc.returncode, "code": error["code"], "reason": error.get("details", {}).get("reason")} + + +def git(checkout, env, *args): + """Run Git against the requested checkout and return its trimmed output.""" + return success(["git", "-C", checkout, *args], checkout, env).decode().strip() + + +def checkpoint(control): + """Check both databases, truncate their write-ahead logs and return their paths.""" + outer = control / ".threadloop/state/state.db" + children = list((control / ".threadloop/state").glob("workflow-execution-*/executor.sqlite")) + require(outer.is_file() and len(children) == 1, "Expected one outer and one child database") + names = [outer, children[0]] + for name in names: + with sqlite3.connect(name, isolation_level=None) as db: + require( + db.execute("PRAGMA quick_check").fetchall() == [("ok",)], f"Invalid database at {name.name}" + ) + require( + db.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()[0] == 0, + "A writer still holds the backup", + ) + db.close() + wal = Path(str(name) + "-wal") + require(not wal.exists() or wal.stat().st_size == 0, "Checkpoint left uncopied WAL frames") + return names + + +def offline(dbfile): + """Open an immutable, read-only SQLite connection with named columns.""" + db = sqlite3.connect(dbfile.as_uri() + "?mode=ro&immutable=1", uri=True) + db.row_factory = sqlite3.Row + return db + + +def retained_outputs(root): + """Measure regular files and directories under a quiescent child outputs directory.""" + paths = {} + total_bytes = 0 + + def visit(name, parent_fd, relative, depth): + """Read one entry relative to its open parent without following links.""" + nonlocal total_bytes + require( + len(paths) < 4096 and depth <= 64, "Retained outputs exceed the fixture's entry or depth limit" + ) + info = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if stat.S_ISDIR(info.st_mode): + paths[relative] = {"kind": "directory"} + directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent_fd) + try: + with os.scandir(directory) as entries: + for entry in entries: + child_path = entry.name if relative == "." else f"{relative}/{entry.name}" + visit(entry.name, directory, child_path, depth + 1) + finally: + os.close(directory) + else: + require( + relative != "." and stat.S_ISREG(info.st_mode), + f"Unsupported retained output kind at {relative}", + ) + total_bytes += info.st_size + require(total_bytes < CASE_LIMIT, "Retained outputs exceed the fixture's byte limit") + flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK + with os.fdopen(os.open(name, flags, dir_fd=parent_fd), "rb") as handle: + require( + stat.S_ISREG(os.fstat(handle.fileno()).st_mode), + f"Unsupported retained output kind at {relative}", + ) + contents = handle.read(info.st_size + 1) + require( + len(contents) == info.st_size, f"Retained output changed during measurement at {relative}" + ) + paths[relative] = {"kind": "file", "bytes": len(contents), "sha256": sha(contents)} + + visit(root, None, ".", 0) + summary = { + "entries": len(paths), + "files": sum(entry["kind"] == "file" for entry in paths.values()), + "bytes": total_bytes, + "sha256": sha(json.dumps(paths, sort_keys=True, separators=(",", ":")).encode()), + } + return paths, summary + + +def receipt_state(control): + """Verify the checkpointed database pair and measure retained child files, receipts and blobs.""" + outer, child = checkpoint(control) + with offline(outer) as db: + head = dict( + db.execute( + "SELECT state,version,revision,ordinal,digest FROM workflow_heads WHERE run_id=?", (RUN,) + ).fetchone() + ) + execution = dict( + db.execute( + "SELECT revision,digest,active_reservation FROM workflow_execution_heads WHERE run_id=?", + (RUN,), + ).fetchone() + ) + counts = dict( + db.execute( + "SELECT kind,count(*) FROM workflow_execution_events WHERE run_id=? GROUP BY kind", (RUN,) + ) + ) + legacy_version = db.execute( + "SELECT version FROM workflow_heads WHERE run_id=?", (LEGACY,) + ).fetchone()[0] + outer_integrity = len(db.execute("PRAGMA foreign_key_check").fetchall()) + db.close() + with offline(child) as db: + body, retained_hash = db.execute("SELECT body,digest FROM root").fetchone() + require(sha(body.encode()) == retained_hash, "Child root bytes differ from its digest") + root = json.loads(body) + launches = [ + dict(row) for row in db.execute("SELECT attempt,request_digest,output_directory FROM launch") + ] + observed = [ + { + "id": row["id"], + "status": row["status"], + "stdout_sha256": sha(row["stdout"]), + "stderr_sha256": sha(row["stderr"]), + "envelope_sha256": sha(row["envelope"]) if row["envelope"] else None, + } + for row in db.execute("SELECT id,status,stdout,stderr,envelope FROM observation ORDER BY id") + ] + receipts = [] + for row in db.execute("SELECT * FROM accepted ORDER BY source_id"): + signed = json.loads(row["envelope"]) + require( + base64.b64decode(signed["payload"], validate=True) == row["predicate"], + "Signed payload differs from the accepted bytes", + ) + admission = json.loads(row["admission"]) + receipts.append( + { + "source_id": row["source_id"], + "source_digest": row["source_digest"], + "observation": row["observation_id"], + "envelope_sha256": sha(row["envelope"]), + "predicate_sha256": sha(row["predicate"]), + "admission_digest": admission["admission_digest"], + "result_sha256": sha(row["result"].encode()), + "signature_count": len(signed["signatures"]), + } + ) + blobs = [ + {"id": row["digest"], "bytes": len(row["bytes"]), "sha256": sha(row["bytes"])} + for row in db.execute("SELECT digest,bytes FROM blob ORDER BY digest") + ] + require(all(row["id"] == "sha256:" + row["sha256"] for row in blobs), "Child blob digest mismatch") + generation = db.execute("PRAGMA user_version").fetchone()[0] + db.close() + require( + outer_integrity == 0 and generation == 2 and root["owner"]["workflow_run_id"] == RUN, + "Wrong managed database pair", + ) + output_paths, outputs = retained_outputs(child.parent / "outputs") + return { + "files": {str(p.relative_to(control)): file_hash(p) for p in [outer, child]}, + "outer": head, + "execution": execution, + "legacy_version": legacy_version, + "counts": counts, + "child": { + "generation": generation, + "revision": root["revision"], + "root_sha256": retained_hash, + "owner": root["owner"], + "launches": launches, + "observations": observed, + "output_paths": output_paths, + "outputs": outputs, + "accepted": receipts, + "blobs": blobs, + }, + } + + +def old_reads(previous, root, env, profile, child_relative): + """Check the prior CLI's managed-run and child refusals, then read the supported legacy run.""" + # The saved v1 proposal projection keeps the old parser's shape and reaches its store reader. + operations = { + "inspect": ["workflow", "inspect", RUN], + "decide": ["workflow", "decide", RUN], + "apply": [ + "workflow", + "apply", + RUN, + "--decision", + "previous-decision.json", + "--idempotency-key", + "old-apply", + ], + "prepare": [ + "workflow", + "evidence", + "prepare", + "signed-gate", + "--run", + RUN, + "--gate", + "check", + "--expected-state-version", + "3", + "--idempotency-key", + "old-prepare", + ], + "reused_create": ["workflow", "create", RUN, "--profile", profile, "--setup", "legacy.json"], + } + results = { + key: refuse(previous, root, env, args, "WORKFLOW_RUNTIME_UNSUPPORTED") + for key, args in operations.items() + } + for operation in ["inspect", "run"]: + results["child_" + operation] = refuse( + previous, + root, + env, + ["executor", operation, "--state", root / child_relative], + "EXECUTOR_REJECTED", + "state.version", + ) + legacy = cli(previous, root, env, ["workflow", "inspect", LEGACY])["data"] + require( + legacy["workflow_run_id"] == LEGACY and legacy["state_version"] == 0, + "Previous supported run is unreadable", + ) + return {"managed_refusals": results, "legacy_view": legacy} + + +def counter(log): + """Read the producer's invocation IDs in order, returning an empty list if the log is absent.""" + return log.read_text().splitlines() if log.exists() else [] + + +def measure_subject(subject, env): + """Read the physical checkout's HEAD, Git status and effect-file digest for comparison after recovery.""" + effect = subject / "source.txt" + return { + "head": git(subject, env, "rev-parse", "HEAD"), + "status": git(subject, env, "status", "--porcelain=v1", "-uall"), + "effect_file_sha256": file_hash(effect) if effect.is_file() else None, + } + + +def proof_case(case, current, previous, source, scratch, env): + """Restore a held or admitted execution snapshot and check its receipts, lifecycle and invocation count.""" + counter_dir = scratch / ("counter-" + case) + counter_dir.mkdir() + mode = "effect_response_lost" if case == "held" else "success" + config = json.loads( + success( + ["node", "--import", "tsx", "scripts/pre-rust/rollback-fixture.ts", mode, counter_dir], + source, + env, + ) + ) + control, subject, profile = Path(config["control"]), Path(config["subject"]), config["profile"] + require( + all(d.resolve().is_relative_to(scratch / "fixtures") for d in [control, subject]), + "Fixture escaped scratch", + ) + legacy_subject = scratch / ("legacy-subject-" + case) + shutil.copytree(subject, legacy_subject, symlinks=True) + legacy_setup = json.loads((control / "legacy.json").read_text()) + legacy_setup["subject_workspace"] = str(legacy_subject) + (control / "legacy.json").write_text(json.dumps(legacy_setup)) + success(["git", "init", "-qb", "main"], control, env) + success([current, "init"], control, env) + for run_id, setup in [(LEGACY, "legacy.json"), (RUN, "setup.json")]: + cli(current, control, env, ["workflow", "create", run_id, "--profile", profile, "--setup", setup]) + + def saved(id, filename): + """Save the run's decision envelope in the control checkout and return it to the caller.""" + result = cli(current, control, env, ["workflow", "decide", id]) + (control / filename).write_text(json.dumps(result)) + return result + + for edge in ["frame", "bind_plan", "begin_implementation"]: + saved(RUN, "edge.json") + applied = cli( + current, + control, + env, + ["workflow", "apply", RUN, "--decision", "edge.json", "--idempotency-key", edge], + )["data"] + require(applied["transition_id"] == edge, "Expected governed graph progression") + proposal = saved(RUN, "engineering.json") + require( + proposal["data"]["controller_decision"]["decision"]["outcome"] == "engineering_action_required", + "Expected engineering action", + ) + prior = json.loads(json.dumps(proposal)) + for key in ["execution_digest", "execution_revision"]: + del prior["data"]["expectation"][key] + (control / "previous-decision.json").write_text(json.dumps(prior)) + execute = ["workflow", "execute", RUN, "--decision", "engineering.json"] + if case == "held": + initial = refuse(current, control, env, execute, "EXECUTOR_REJECTED", "execution_outstanding") + else: + result = run( + [ + "node", + "--import", + source / "tests/fixtures/workflow/execution-cut.mjs", + current, + *execute, + "--json", + ], + control, + {**env, "THREADLOOP_TEST_EXECUTION_CUT": "admit"}, + ) + require( + result.returncode == -signal.SIGKILL and b"managed-cut=admit" in result.stderr, + "Missing child admission cut", + ) + initial = {"signal": "SIGKILL", "observed_boundary": "managed-cut=admit"} + info = cli(current, control, env, ["workflow", "inspect", RUN])["data"] + receipt = info["execution"] + require( + receipt["disposition"] == ("started" if case == "held" else "admitted") + and info["state_version"] == 3, + "Unexpected initial outer state", + ) + (control / "correlation.json").write_text(json.dumps(receipt["correlation"])) + recover = [ + "workflow", + "evidence", + "import", + "gaap", + "--run", + RUN, + "--source", + "correlation.json", + "--expected-state-version", + "3", + ] + log = counter_dir / "invocations.log" + initial_count = counter(log) + require( + initial_count == [receipt["correlation"]["attempt_id"]], + "Expected exactly one independently counted invocation", + ) + observed_subject = measure_subject(subject, env) + require( + case != "held" + or observed_subject["effect_file_sha256"] == sha(b"effect occurred before response loss\n"), + "Missing physical held effect", + ) + before = receipt_state(control) + child_relative = Path(next(p for p in before["files"] if p.endswith("executor.sqlite"))).parent + facts = before["child"] + require( + len(facts["launches"]) == 1 + and facts["launches"][0]["attempt"] == initial_count[0] + and facts["launches"][0]["request_digest"] == receipt["correlation"]["executor_request_digest"] + and before["execution"]["active_reservation"] == facts["owner"]["reservation_id"] + and not before["counts"].get("import"), + "Invalid initial correlated state", + ) + require(len(facts["accepted"]) == int(case == "admitted"), "Unexpected signed receipt count") + # The enrolled launch retains its original absolute path when the control checkout is copied. + attempt_output = Path(facts["launches"][0]["output_directory"]) + require( + attempt_output.parent == control / child_relative / "outputs", + "Launch points outside the child outputs", + ) + paths = facts["output_paths"] + if case == "held": + marker = b"synthetic producer reached its effect" + require( + paths.get(f"{attempt_output.name}/effect-observation.txt") + == {"kind": "file", "bytes": len(marker), "sha256": sha(marker)}, + "Missing the held Attempt's physical effect observation", + ) + else: + require( + bool(facts["blobs"]) + and facts["accepted"][0]["signature_count"] > 0 + and facts["observations"][0]["envelope_sha256"] == facts["accepted"][0]["envelope_sha256"], + "Missing admitted signed bytes", + ) + envelope = paths.get(f"{attempt_output.name}/envelope.json", {}) + require( + envelope.get("sha256") == facts["accepted"][0]["envelope_sha256"] + and all( + paths.get(f"{attempt_output.name}/blobs/{blob['sha256']}") + == {"kind": "file", "bytes": blob["bytes"], "sha256": blob["sha256"]} + for blob in facts["blobs"] + ), + "Physical Attempt outputs differ from the admitted envelope or blobs", + ) + old_live = old_reads(previous, control, env, profile, child_relative) + require(receipt_state(control) == before, "Old reader or writer changed the live pair") + total = sum(p.stat().st_size for p in control.rglob("*") if p.is_file()) + require(total < CASE_LIMIT, "Fixture exceeds its physical snapshot limit") + backup = scratch / ("backup-" + case) + shutil.copytree(control, backup, symlinks=True) + require(receipt_state(backup) == before, "Copied snapshot differs from live files") + old_backup = old_reads(previous, backup, env, profile, child_relative) + require( + old_backup == old_live and receipt_state(backup) == before, "Previous binary changed the backup pair" + ) + + # Advance the live copy after backup. The operator can see exactly which durable facts restoration discards. + saved(LEGACY, "legacy-edge.json") + cli( + current, + control, + env, + ["workflow", "apply", LEGACY, "--decision", "legacy-edge.json", "--idempotency-key", "after-backup"], + ) + + def recover_admitted(): + """Import the retained receipt and verify its admission, Attempt and unchanged run version.""" + first = cli(current, control, env, recover)["data"] + require( + first["disposition"] == "imported" + and first["state_version"] == 3 + and first["attempt_status"] == "succeeded" + and first["source_digest"] == facts["accepted"][0]["source_digest"] + and first["admission_digest"] == facts["accepted"][0]["admission_digest"], + "Import changed the accepted receipt", + ) + return first + + live_import = recover_admitted() if case == "admitted" else None + later = receipt_state(control) + require( + later["legacy_version"] == 1 and later["counts"].get("import", 0) == int(case == "admitted"), + "Expected post-backup writes", + ) + require(later["child"]["outputs"] == facts["outputs"], "Post-backup operations changed child outputs") + # Only temporary paths created by this driver can reach the restore operation. + require( + control.parent == Path(env["TMPDIR"]) and backup.parent == scratch and backup != control, + "Invalid restoration ownership", + ) + control.rename(scratch / ("retired-" + case)) + shutil.copytree(backup, control, symlinks=True) + restored = receipt_state(control) + require( + restored == before and measure_subject(subject, env) == observed_subject, + "Restored files or external physical effect changed", + ) + restored_info = cli(current, control, env, ["workflow", "inspect", RUN])["data"] + require(restored_info == info, "Reopened installed inspector differs from the snapshot") + verified_child = cli(current, control, env, ["executor", "inspect", "--state", control / child_relative])[ + "data" + ] + require( + verified_child["launch_count"] == 1 and verified_child["revision"] == facts["revision"], + "Verified child belongs to another generation", + ) + require(receipt_state(control) == restored, "Installed inspectors changed the restored snapshot") + if case == "held": + recovered = refuse(current, control, env, recover, "EXECUTOR_REJECTED", "execution_outstanding") + replay = refuse(current, control, env, execute, "EXECUTOR_REJECTED", "execution_outstanding") + else: + recovered = recover_admitted() + replay = cli(current, control, env, execute)["data"] + require( + recovered == live_import == replay and cli(current, control, env, recover)["data"] == replay, + "Committed import replay mismatch", + ) + after = receipt_state(control) + require( + after["outer"] == before["outer"] + and after["child"] == before["child"] + and after["legacy_version"] == 0 + and after["counts"].get("import", 0) == int(case == "admitted") + and counter(log) == initial_count + and measure_subject(subject, env) == observed_subject, + "Recovery repeated a child effect or mutated lifecycle state", + ) + return { + "case": case, + "initial_observation": initial, + "snapshot_bytes": total, + "file_hashes_before": before["files"], + "file_hashes_restored": restored["files"], + "outputs_before": facts["outputs"], + "outputs_restored": restored["child"]["outputs"], + "outer_state_version": info["state_version"], + "child_root_digest": facts["root_sha256"], + "child_revision": facts["revision"], + "execution_revision_before": before["execution"]["revision"], + "execution_revision_recovered": after["execution"]["revision"], + "launches": len(facts["launches"]), + "invocations_after_recovery": len(counter(log)), + "physical_subject_head": observed_subject["head"], + "effect_file_sha256": observed_subject["effect_file_sha256"], + "accepted": facts["accepted"], + "blobs": facts["blobs"], + "observations": facts["observations"], + "old_managed_refusals": old_backup["managed_refusals"], + "legacy_version_after_backup": later["legacy_version"], + "legacy_version_restored": restored["legacy_version"], + "import_events_after_backup": later["counts"].get("import", 0), + "import_events_restored": restored["counts"].get("import", 0), + "import_events_after_recovery": after["counts"].get("import", 0), + "recovery_disposition": recovered.get("disposition", recovered.get("reason")), + "replay_disposition": replay.get("disposition", replay.get("reason")), + } + + +def main(): + """Install both revisions, run both rollback cases and write their evidence to a fresh report.""" + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("checkout", type=Path) + p.add_argument("revision") + p.add_argument("candidate_package", type=Path) + p.add_argument("prior_package", type=Path) + p.add_argument("new_report", type=Path) + args = p.parse_args() + require(re.fullmatch("[0-9a-f]{40}", args.revision) is not None, "Expected a full candidate commit SHA") + checkout = args.checkout.resolve() + report = args.new_report.resolve() + require(not report.exists(), "Choose a fresh report filename") + with tempfile.TemporaryDirectory(prefix="threadloop-managed-rollback-") as directory: + scratch = Path(directory).resolve() + fixtures = scratch / "fixtures" + fixtures.mkdir() + env = { + **offline_environment(scratch), + "TMPDIR": str(fixtures), + "TMP": str(fixtures), + "TEMP": str(fixtures), + } + require( + git(checkout, env, "rev-parse", RUNS_V1 + "^{tree}") + == git(checkout, env, "rev-parse", OLD_MERGE + "^{tree}"), + "Reviewed #170 tree differs from its merge", + ) + source = scratch / "source" + source.mkdir() + arc = scratch / "fixtures.tar" + success( + [ + "git", + "archive", + "--format=tar", + "-o", + arc, + args.revision, + "src", + "tests", + "scripts", + "package.json", + "package-lock.json", + "tsconfig.build.json", + "tsconfig.json", + ], + checkout, + env, + ) + success(["tar", "-xf", arc, "-C", source], scratch, env) + arc.unlink() + require( + file_hash(source / "package-lock.json") == file_hash(checkout / "package-lock.json"), + "Installed fixture dependency lock differs from the candidate", + ) + (source / "node_modules").symlink_to(checkout / "node_modules", target_is_directory=True) + packages = install_packages( + checkout, + { + "current": (args.candidate_package.resolve(), args.revision), + "previous": (args.prior_package.resolve(), RUNS_V1), + }, + scratch, + env, + ) + current, csource = packages["current"] + previous, psource = packages["previous"] + cases = [proof_case(case, current, previous, source, scratch, env) for case in ["held", "admitted"]] + packet = { + "format": "threadloop.managed-rollback-proof/1", + "driver_sha256": file_hash(Path(__file__).resolve()), + "node": success(["node", "--version"], scratch, env).decode().strip(), + "sqlite": sqlite3.sqlite_version, + "current": csource, + "old": psource, + "old_merge": OLD_MERGE, + "process_fixture": "local fixture producer with fixture signing", + "fixture_source": { + p: file_hash(source / p) + for p in [ + "scripts/pre-rust/rollback-fixture.ts", + "tests/helpers/workflow-execution.ts", + "tests/fixtures/workflow/execution-cut.mjs", + "tests/fixtures/gaap-producer.ts", + "tests/fixtures/gaap.ts", + ] + }, + "cases": cases, + } + require(not scratch.exists(), "Temporary proof files remain") + packet["scratch_removed"] = True + write_report(report, packet, sort_keys=True) + print(f"{report.name} SHA-256 {file_hash(report)}") + + +if __name__ == "__main__": + main() diff --git a/scripts/pre-rust/pack.py b/scripts/pre-rust/pack.py new file mode 100644 index 0000000..37ea8c0 --- /dev/null +++ b/scripts/pre-rust/pack.py @@ -0,0 +1,14 @@ +"""Build a committed ThreadLoop revision offline from its matching installed lockfile.""" + +import argparse +from pathlib import Path +from proof_package import build_revision_package as pack + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("checkout", type=Path) + parser.add_argument("revision", help="full commit SHA to package") + parser.add_argument("new_directory", type=Path) + args = parser.parse_args() + pack(args.checkout.resolve(), args.revision, args.new_directory.resolve()) diff --git a/scripts/pre-rust/proof_package.py b/scripts/pre-rust/proof_package.py new file mode 100644 index 0000000..45ab77f --- /dev/null +++ b/scripts/pre-rust/proof_package.py @@ -0,0 +1,221 @@ +"""Verify and install revision-specific ThreadLoop packages in a disposable proof directory.""" + +from hashlib import sha256 +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + +PRE_RUNS = "7c54c2bb8055f00736e3b5f6631e9aecbe0fd212" +RUNS_V1 = "31388a07566350dfeddc30578d43b8926d5b4e22" + + +def require(condition, message): + """Raise ValueError with the supplied explanation when a proof check fails.""" + if not condition: + raise ValueError(message) + + +def file_hash(path): + """Read the file in chunks and return its SHA-256 hex digest.""" + digest = sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(128 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def git_environment(): + """Select the named Git objects in the requested checkout, ignoring local replacement refs.""" + return { + **{key: value for key, value in os.environ.items() if not key.startswith("GIT_")}, + "GIT_NO_REPLACE_OBJECTS": "1", + } + + +def git(checkout, *args): + """Run Git in the specified checkout and return its trimmed output on success.""" + return subprocess.check_output( + ["git", "-C", checkout, *args], env=git_environment(), text=True, timeout=60 + ).strip() + + +def source_identity(checkout, revision): + """Verify the full commit ID and return its tree ID and package-lock.json blob ID.""" + require(re.fullmatch("[0-9a-f]{40}", revision), "Supply a full commit SHA") + require(git(checkout, "rev-parse", "--verify", revision + "^{commit}") == revision, "Expected a commit") + return { + "revision": revision, + "tree": git(checkout, "rev-parse", revision + "^{tree}"), + "lock_blob": git(checkout, "rev-parse", revision + ":package-lock.json"), + } + + +def offline_environment(scratch): + """Create empty Git templates and configure offline npm installs with a scratch-local cache.""" + # Isolate disposable Git commits from the invoking checkout and its hooks or signing identity. + templates = scratch / "empty-git-templates" + templates.mkdir() + return { + **git_environment(), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_TEMPLATE_DIR": str(templates), + "GIT_TERMINAL_PROMPT": "0", + "npm_config_offline": "true", + "npm_config_userconfig": os.devnull, + "npm_config_cache": str(scratch / "npm-cache"), + "npm_config_update_notifier": "false", + "npm_config_audit": "false", + "npm_config_fund": "false", + "HUSKY": "0", + "TSX_DISABLE_CACHE": "1", + } + + +def write_report(path, record, sort_keys=False): + """Publish the complete JSON document once, preserving any existing output.""" + encoded = json.dumps(record, indent=2, sort_keys=sort_keys).encode() + b"\n" + with tempfile.NamedTemporaryFile(dir=path.parent) as staged: + staged.write(encoded) + staged.flush() + os.link(staged.name, path) + + +def build_revision_package(checkout, revision, output): + """Build Git's committed bytes offline with the operator's trusted, matching npm ci toolchain.""" + record = source_identity(checkout, revision) + require( + git(checkout, "hash-object", "package-lock.json") == record["lock_blob"], + "Install the dependencies from this revision's lockfile using npm ci", + ) + require((checkout / "node_modules/.bin/tsup").is_file(), "Run npm ci in the checkout") + require(not output.exists(), "Choose a fresh package directory.") + with tempfile.TemporaryDirectory(prefix="threadloop-pack-") as temporary: + scratch = Path(temporary).resolve() + source = scratch / "source" + source.mkdir() + env = offline_environment(scratch) + archive = scratch / "source.tar" + subprocess.run( + ["git", "-C", checkout, "archive", "-o", archive, revision], env=env, check=True, timeout=120 + ) + subprocess.run(["tar", "-xf", archive, "-C", source], check=True, timeout=120) + archive.unlink() + # npm pack omits directory symlinks when bundling the CLI's dependencies. + shutil.copytree(checkout / "node_modules", source / "node_modules", symlinks=True) + subprocess.run(["npm", "run", "build"], cwd=source, env=env, check=True, timeout=180) + # npm 10 may run prepare during pack. CI skips Git hook setup in this source archive. + # Background script output keeps the package listing valid JSON across npm versions. + (entry,) = json.loads( + subprocess.check_output( + [ + "npm", + "pack", + "--offline", + "--ignore-scripts", + "--foreground-scripts=false", + "--json", + "--pack-destination", + scratch, + ], + cwd=source, + env={**env, "CI": "true"}, + timeout=120, + ) + ) + tarball = scratch / entry["filename"] + record.update( + node=subprocess.check_output(["node", "--version"], env=env, text=True, timeout=30).strip(), + npm=subprocess.check_output(["npm", "--version"], env=env, text=True, timeout=30).strip(), + tarball=entry["filename"], + sha256=file_hash(tarball), + cli_sha256=file_hash(source / "dist/cli.js"), + integrity=entry["integrity"], + bundled_dependencies=len(entry["bundled"]), + ) + output.mkdir(mode=0o700) + destination = output / record["tarball"] + try: + shutil.copyfile(tarball, destination) + # Readers require the complete provenance file before this package can be used. + write_report(output / "provenance.json", record) + except BaseException: + if not (output / "provenance.json").exists(): + destination.unlink(missing_ok=True) + output.rmdir() + raise + return record + + +def install_packages(checkout, packages, scratch, env): + """Authenticate all supplied archives against Git rebuilds before installing any package. + + The operator supplies a trusted npm ci toolchain matching the source lock. One private + rebuild per revision measures all package bytes. Its Node and npm versions describe + this independent measurement. The install uses the privately retained rebuild. + """ + installed = {} + with tempfile.TemporaryDirectory(dir=scratch, prefix="verified-packages-") as directory: + rebuilt = {} + for supplied, revision in packages.values(): + if revision not in rebuilt: + output = Path(directory) / str(len(rebuilt)) + record = build_revision_package(checkout, revision, output) + rebuilt[revision] = (record, output / record["tarball"]) + expected, reference_archive = rebuilt[revision] + claimed = json.loads((supplied / "provenance.json").read_bytes()) + fields = ( + "revision", + "tree", + "lock_blob", + "tarball", + "sha256", + "cli_sha256", + "integrity", + "bundled_dependencies", + ) + require( + isinstance(claimed, dict) and all(claimed.get(k) == expected[k] for k in fields), + "Package provenance differs from the independent Git rebuild.", + ) + archive = (supplied / expected["tarball"]).resolve(strict=True) + require( + archive.parent == supplied.resolve() + and archive.is_file() + and archive.stat().st_size == reference_archive.stat().st_size + and file_hash(archive) == expected["sha256"], + "Package archive differs from the independent Git rebuild.", + ) + + for role, (_, revision) in packages.items(): + record, archive = rebuilt[revision] + prefix = scratch / role + prefix.mkdir() + subprocess.run( + [ + "npm", + "install", + "--offline", + "--ignore-scripts", + "--no-package-lock", + "--no-save", + "--prefix", + prefix, + archive, + ], + cwd=prefix, + env=env, + check=True, + timeout=120, + stdout=subprocess.DEVNULL, + ) + cli = (prefix / "node_modules/.bin/threadloop").resolve(strict=True) + require( + cli.is_relative_to(prefix) and file_hash(cli) == record["cli_sha256"], "Installed CLI differs" + ) + installed[role] = (cli, record) + return installed diff --git a/scripts/pre-rust/rollback-fixture.ts b/scripts/pre-rust/rollback-fixture.ts new file mode 100644 index 0000000..3713c46 --- /dev/null +++ b/scripts/pre-rust/rollback-fixture.ts @@ -0,0 +1,20 @@ +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { managedWorkflowFixture } from '../../tests/helpers/workflow-execution.js'; +import { governedProfile } from '../../tests/helpers/workflow-run.js'; + +const [mode, counterDirectory] = process.argv.slice(2); +if ((mode !== 'success' && mode !== 'effect_response_lost') || !counterDirectory) { + throw new Error('Supply a rollback case and an invocation counter directory.'); +} + +const { control, subject, setup, host } = await managedWorkflowFixture(mode); +host.environment.TEST_GAAP_COUNTER_DIRECTORY = counterDirectory; +const { gaap, ...legacy } = setup; +if (gaap.host !== 'host.json') throw new Error('The rollback fixture enrolled a different host.'); +await writeFile(path.join(control, gaap.host), JSON.stringify(host)); +await writeFile( + path.join(control, 'legacy.json'), + JSON.stringify({ ...legacy, schema_version: 'threadloop.workflow-setup/1' }), +); +process.stdout.write(JSON.stringify({ control, subject, profile: governedProfile })); diff --git a/src/adapters/fs/gaap-state.ts b/src/adapters/fs/gaap-state.ts index e6f0655..2e66c92 100644 --- a/src/adapters/fs/gaap-state.ts +++ b/src/adapters/fs/gaap-state.ts @@ -2,6 +2,7 @@ import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, unlin import path from 'node:path'; import { randomUUID } from 'node:crypto'; import { DatabaseSync } from './sqlite-driver.js'; +import { readSealedRoot, writeSealedRoot, sealedRootTable } from './sealed-root.js'; import { requireGaapDirectory } from './gaap-files.js'; import { canonicalJson } from '../../domain/canonical-json.js'; import { sha256 } from '../crypto/sha256.js'; @@ -129,14 +130,14 @@ export class GaapState { database.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; BEGIN IMMEDIATE'); database.exec(` PRAGMA user_version=${root.schema_version === 'threadloop.gaap-state/2' ? 2 : 1}; - CREATE TABLE root (id INTEGER PRIMARY KEY CHECK(id=1), body TEXT NOT NULL, digest TEXT NOT NULL); + ${sealedRootTable}; CREATE TABLE launch (attempt TEXT PRIMARY KEY, request_digest TEXT NOT NULL, output_directory TEXT NOT NULL); CREATE TABLE observation (id INTEGER PRIMARY KEY, status TEXT NOT NULL, stdout BLOB NOT NULL, stderr BLOB NOT NULL, envelope BLOB, metadata TEXT NOT NULL); CREATE TABLE accepted (source_id TEXT PRIMARY KEY, source_digest TEXT NOT NULL, envelope BLOB NOT NULL, predicate BLOB NOT NULL, result TEXT NOT NULL, admission TEXT NOT NULL, observation_id INTEGER NOT NULL); CREATE TABLE blob (digest TEXT PRIMARY KEY, bytes BLOB NOT NULL); CREATE TABLE evaluation (id INTEGER PRIMARY KEY, body TEXT NOT NULL); `); - this.writeRoot(database, root); + writeSealedRoot(database, root); this.writeGeneration(database, generation); this.fault('register.before_commit'); commitAttempted = true; @@ -187,16 +188,14 @@ export class GaapState { 'Executor state requires a host-owned directory without group or other write permission.', ); } - private readRoot(database: DatabaseSync, owner?: ManagedGaapOwner, publicInspection = false): GaapRoot { - const row = database.prepare('SELECT body,digest FROM root WHERE id=1').get(); - if (!row || typeof row.body !== 'string' || sha256(row.body) !== row.digest) - throw new GaapEvidenceError('state.integrity', 'Executor root is missing or differs from its retained identity.'); - const root = JSON.parse(row.body) as GaapRoot; + private readRoot(database: DatabaseSync, owner?: ManagedGaapOwner, publicInspection = false) { + const { value, digest } = readSealedRoot(database); + const root = value as GaapRoot; if ( + !root || !['threadloop.gaap-state/1', 'threadloop.gaap-state/2'].includes(root.schema_version) || !Number.isSafeInteger(root.revision) || - root.revision < 0 || - canonicalJson(root) !== row.body + root.revision < 0 ) throw new GaapEvidenceError('state.integrity', 'Executor root has an unsupported or noncanonical shape.'); const managed = root.schema_version === 'threadloop.gaap-state/2'; @@ -222,11 +221,7 @@ export class GaapState { } if (!managed && owner) throw new GaapEvidenceError('state.owner', 'A standalone executor has no owning Workflow Run.'); - return root; - } - private writeRoot(database: DatabaseSync, root: GaapRoot) { - const bytes = canonicalJson(root); - database.prepare('INSERT OR REPLACE INTO root VALUES (1,?,?)').run(bytes, sha256(bytes)); + return { root, digest }; } private writeGeneration(database: DatabaseSync, generation: string): void { // Additive metadata also supports state-1 databases created before this marker existed. @@ -241,7 +236,7 @@ export class GaapState { const database = this.open(); try { const marker = database.prepare('SELECT token FROM commit_generation WHERE id=1').get(); - return marker?.token === generation && canonicalJson(this.readRoot(database, owner)) === expectedRoot; + return marker?.token === generation && canonicalJson(this.readRoot(database, owner).root) === expectedRoot; } finally { database.close(); } @@ -249,7 +244,7 @@ export class GaapState { read(owner?: ManagedGaapOwner): GaapRoot { const database = this.open(); try { - return this.readRoot(database, owner); + return this.readRoot(database, owner).root; } finally { database.close(); } @@ -325,10 +320,10 @@ export class GaapState { let outcome: { ok: true; value: T } | { ok: false; error: unknown }; try { database.exec('PRAGMA synchronous=FULL; BEGIN IMMEDIATE'); - const root = this.readRoot(database, owner); + const { root, digest } = this.readRoot(database, owner); const value = operation(root, database); root.revision += 1; - this.writeRoot(database, root); + writeSealedRoot(database, root, digest); this.writeGeneration(database, generation); proposedRoot = canonicalJson(root); this.fault('state.before_commit'); @@ -376,7 +371,7 @@ export class GaapState { const database = this.open(); try { database.exec('BEGIN'); - const root = this.readRoot(database, owner, publicInspection); + const { root } = this.readRoot(database, owner, publicInspection); const launches = database.prepare('SELECT * FROM launch').all(); const observations = database.prepare('SELECT * FROM observation ORDER BY id').all(); const accepted = database.prepare('SELECT * FROM accepted').all(); diff --git a/src/adapters/fs/sealed-root.ts b/src/adapters/fs/sealed-root.ts new file mode 100644 index 0000000..f640971 --- /dev/null +++ b/src/adapters/fs/sealed-root.ts @@ -0,0 +1,36 @@ +import { sha256 } from '../crypto/sha256.js'; +import { canonicalJson } from '../../domain/canonical-json.js'; +import { GaapEvidenceError } from '../../domain/gaap-json.js'; +import type { DatabaseSync } from './sqlite-driver.js'; + +export const sealedRootTable = + 'CREATE TABLE root (id INTEGER PRIMARY KEY CHECK(id=1), body TEXT NOT NULL, digest TEXT NOT NULL)'; + +export function readSealedRoot(database: DatabaseSync): { value: unknown; digest: string } { + const row = database.prepare('SELECT body,digest FROM root WHERE id=1').get(); + if (!row || typeof row.body !== 'string' || typeof row.digest !== 'string' || sha256(row.body) !== row.digest) + throw new GaapEvidenceError('state.integrity', 'Executor root is missing or differs from its retained identity.'); + let value: unknown; + try { + value = JSON.parse(row.body); + } catch { + throw new GaapEvidenceError('state.integrity', 'Executor root must contain canonical JSON.'); + } + if (canonicalJson(value) !== row.body) + throw new GaapEvidenceError('state.integrity', 'Executor root must contain canonical JSON.'); + return { value, digest: row.digest }; +} + +export function writeSealedRoot(database: DatabaseSync, value: unknown, expectedRowDigest?: string): void { + const body = canonicalJson(value); + const digest = sha256(body); + if (expectedRowDigest === undefined) { + database.prepare('INSERT INTO root (id,body,digest) VALUES (1,?,?)').run(body, digest); + return; + } + const result = database + .prepare('UPDATE root SET body=?,digest=? WHERE id=1 AND digest=?') + .run(body, digest, expectedRowDigest); + if (result.changes !== 1) + throw new GaapEvidenceError('state.fenced', 'The retained executor root changed before the journal could commit.'); +} diff --git a/tests/fixtures/controller-conformance/control.mjs b/tests/fixtures/controller-conformance/control.mjs new file mode 100644 index 0000000..7f3f73f --- /dev/null +++ b/tests/fixtures/controller-conformance/control.mjs @@ -0,0 +1,24 @@ +// Independent process controls for the harness. The controller bundle excludes this file. +import fs from 'node:fs'; + +const [operation, ...values] = process.argv.slice(2); +if (operation === 'read') { + const denied = values.map((file) => { + try { + const descriptor = fs.openSync(file, 'r'); + fs.closeSync(descriptor); + return 'readable'; + } catch (error) { + return error.code; + } + }); + process.stdout.write(JSON.stringify(denied)); +} else if (operation === 'timeout') { + fs.writeFileSync('started', 'timeout control'); + setInterval(() => {}, 60_000); +} else if (operation === 'reply') { + fs.readFileSync(0); + process.stdout.write(values[0]); +} else { + throw new Error('Unknown independent harness control'); +} diff --git a/tests/fixtures/controller-execution-writer.mjs b/tests/fixtures/controller-execution-writer.mjs new file mode 100644 index 0000000..82eef93 --- /dev/null +++ b/tests/fixtures/controller-execution-writer.mjs @@ -0,0 +1,17 @@ +// Each process receives one admitted test operation and competes for the actual SQLite writer lock. +import { readFileSync, writeSync } from 'node:fs'; +import { DatabaseSync } from 'node:sqlite'; +import { ScenarioJournal } from '../../scripts/controller-conformance/scenario-journal.ts'; + +const { filename, step, admissions } = JSON.parse(readFileSync(0, 'utf8')); +const digests = new Set(admissions); +const exec = DatabaseSync.prototype.exec; +DatabaseSync.prototype.exec = function (sql) { + if (sql === 'BEGIN IMMEDIATE') writeSync(2, 'scenario-writer-at-begin\n'); + return exec.call(this, sql); +}; +const journal = new ScenarioJournal(filename, { isAdmitted: (digest) => digests.has(digest) }); +const result = journal.apply(step.context, step.operation); +process.stdout.write( + JSON.stringify(result.ok ? { result: result.value.result, replayed: result.value.replayed } : result), +); diff --git a/tests/fixtures/workflow/execution-cut.mjs b/tests/fixtures/workflow/execution-cut.mjs index fe6ebfd..c2b6198 100644 --- a/tests/fixtures/workflow/execution-cut.mjs +++ b/tests/fixtures/workflow/execution-cut.mjs @@ -8,7 +8,7 @@ DatabaseSync.prototype.prepare = function (sql) { const statement = prepare.call(this, sql); const childPhase = /^INSERT INTO (launch|observation|accepted)\b/.exec(sql)?.[1]; const outer = sql.startsWith('INSERT INTO workflow_execution_events('); - const expiry = point === 'expire' && sql.startsWith('INSERT OR REPLACE INTO root '); + const expiry = point === 'expire' && sql.startsWith('UPDATE root SET '); if (!childPhase && !outer && !expiry) return statement; const run = statement.run.bind(statement); statement.run = (...args) => { diff --git a/tests/integration/controller-conformance-process.test.ts b/tests/integration/controller-conformance-process.test.ts new file mode 100644 index 0000000..df6a9fb --- /dev/null +++ b/tests/integration/controller-conformance-process.test.ts @@ -0,0 +1,315 @@ +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { z } from 'zod'; +import { canonicalJson } from '../../src/domain/canonical-json.js'; +import { sha256 } from '../../src/adapters/crypto/sha256.js'; + +const root = import.meta.dirname + '/../..'; +const versions = { + protocol: 'threadloop.controller-conformance/0.1', + fixture_schema: 'threadloop.conformance-fixture/0.1', + canonicalization: 'threadloop.conformance-json/0.1', + digest_profile: 'threadloop.conformance-sha256/0.1', +}; +const profile = { + schema_version: '0.1', + profile: { id: 'folio', revision: 1 }, + initial_state: 'drafted', + states: [ + { id: 'drafted', kind: 'active' }, + { id: 'checked', kind: 'active' }, + { id: 'issued', kind: 'terminal' }, + ], + transitions: [ + { id: 'check_folio', from: 'drafted', to: 'checked', priority: 0, guard_refs: [], authority: ['threadloop'] }, + { + id: 'issue_folio', + from: 'checked', + to: 'issued', + guard_refs: ['approval', 'publication'], + authority: ['threadloop', 'human'], + }, + ], + guards: [ + { + id: 'approval', + capability: 'human_approval', + parameters: { scope: 'current_subject' }, + required_actions: ['authorize'], + }, + { id: 'publication', capability: 'completion_observed', parameters: { kind: 'publication' } }, + ], + required_actions: [{ id: 'authorize', capability: 'approve_change', authority: 'human', parameters: {} }], +}; +const graphDigest = '24c18e7fb1b5dbaa0ffb1e2d7fe9e68c32dff2660effe54dff3b72f68c66799a'; +const identitySchema = z.strictObject({ + name: z.string(), + version: z.string(), + revision: z.string(), + artifact_digest: z.string(), +}); +const envelopeSchema = z.strictObject({ + response: z.strictObject({ + protocol: z.literal(versions.protocol), + fixture_schema: z.literal(versions.fixture_schema), + canonicalization: z.literal(versions.canonicalization), + digest_profile: z.literal(versions.digest_profile), + schema: z.literal('threadloop.conformance-response/0.1'), + request_digest: z.string(), + subject: identitySchema, + result: z.record(z.string(), z.unknown()), + }), + response_digest: z.string(), +}); + +function request( + operation: string, + input: unknown, + case_id = 'case_900', + corpus_digest = sha256('independent graph examples'), +) { + const payload = { + ...versions, + schema: 'threadloop.conformance-request/0.1', + operation, + case_id, + corpus_digest, + input, + input_digest: sha256(canonicalJson(input)), + }; + return { request: payload, request_digest: sha256(canonicalJson(payload)) }; +} + +function snapshot(compiled: unknown, digest = graphDigest) { + const subject = { kind: 'repository', repository_id: 'folio', revision: 'r1', content_digest: sha256('folio r1') }; + const rules = { + selection: 'threadloop.remedies/0.1', + proof_plan: null, + proof_binding_transition_id: null, + repository_binding: { branch: 'folio', baseline: subject }, + publication_destination: null, + local_gate_ids: [], + independent_gate_ids: [], + evidence_policies: [], + authorities: ['threadloop', 'human'].map((type) => ({ type, identity: { id: type, digest: sha256(type) } })), + }; + return { + schema_version: '0.1', + compiled_graph: compiled, + binding: { + workflow_run_id: 'folio-run', + graph_schema_version: '0.1', + graph_digest: digest, + source_state: 'drafted', + state_version: 1, + subject, + }, + observation: { + id: 'workspace', + subject, + state_version: 1, + status: 'verified', + valid_until: null, + repository: { branch: 'folio', clean: true, change_scope: 'within_plan', basis: subject, relationship: 'equal' }, + }, + history: { + status: 'verified', + digest: sha256('history'), + proof_plan_bound: false, + phase: null, + budget_counts: [], + prior_state: null, + implementation_basis: subject, + repair_admission: null, + }, + policy: { id: 'folio', rules, digest: sha256(canonicalJson(rules)) }, + available_capabilities: [{ actor: 'human', capability: 'approve_change' }], + receipts: [], + invalidated_claims: [], + execution: { status: 'idle' }, + existing_requests: [], + evaluation_time: '2026-01-01T00:00:00.000Z', + }; +} + +describe('external controller process', () => { + let scratch: string; + let output: string; + let bundle: string; + let identity: z.infer<typeof identitySchema>; + beforeAll(() => { + scratch = mkdtempSync(join(tmpdir(), 'threadloop-controller-')); + output = join(scratch, 'build'); + execFileSync(process.execPath, ['scripts/controller-conformance/build.mjs', '--output', output], { + cwd: root, + timeout: 25000, + }); + bundle = join(output, 'runtime/scripts/executor-contract/subject.mjs'); + identity = identitySchema.parse(JSON.parse(readFileSync(join(output, 'identity.json'), 'utf8'))); + renameSync(join(output, 'identity.json'), join(scratch, 'operator-identity.json')); + }); + afterAll(() => { + if (scratch) rmSync(scratch, { recursive: true, force: true }); + }); + function invoke(input: string, verb = 'conformance') { + return spawnSync(process.execPath, [bundle, verb], { + input, + cwd: scratch, + encoding: 'utf8', + timeout: 10000, + maxBuffer: 17 * 1024 * 1024, + }); + } + function exchange(message: ReturnType<typeof request>, framing = '') { + const processResult = invoke(canonicalJson(message) + framing); + expect(processResult.status, processResult.stderr).toBe(0); + const body = envelopeSchema.parse(JSON.parse(processResult.stdout)); + expect(processResult.stdout).toBe(canonicalJson(body) + '\n'); + expect(body.response_digest).toBe(sha256(canonicalJson(body.response))); + expect(body.response.subject).toEqual(identity); + expect(body.response.request_digest).toBe(message.request_digest); + return body.response.result; + } + it('compiles the supplied graph and binds the response to independently measured runtime bytes', () => { + const result = exchange(request('compile_graph', profile), '\n'); + expect(result).toMatchObject({ + status: 'compiled', + compiled_graph: { graph_digest: graphDigest, graph: { initial_state: 'drafted', profile: { id: 'folio' } } }, + }); + const relabeled = request('compile_graph', profile, 'case_901'); + expect(relabeled.request_digest).not.toBe(request('compile_graph', profile).request_digest); + expect(exchange(relabeled)).toEqual(result); + const reordered = exchange( + request( + 'compile_graph', + { ...profile, states: [...profile.states].reverse(), transitions: [...profile.transitions].reverse() }, + 'case_901', + sha256('another graph corpus'), + ), + ); + expect(reordered).toEqual(result); + const files = [ + 'docs/contracts/executor-v0.1/upstream/gaap/agent-run-request.schema.json', + 'docs/contracts/executor-v0.1/upstream/gaap/terminal-run-receipt.schema.json', + 'scripts/executor-contract/subject.mjs', + ]; + const manifest = files.map((path) => { + const bytes = readFileSync(join(output, 'runtime', path)); + return { bytes: bytes.length, path, sha256: sha256(bytes) }; + }); + expect(JSON.parse(readFileSync(join(output, 'manifest.json'), 'utf8'))).toEqual(manifest); + expect(identity.artifact_digest).toBe(sha256(canonicalJson(manifest))); + expect(identity.name).toBe('threadloop-controller'); + const commit = identity.revision.replace(/-dirty$/, ''); + expect(commit).toMatch(/^[a-f0-9]+$/); + expect([40, 64]).toContain(commit.length); + execFileSync('git', ['cat-file', '-e', commit + '^{commit}'], { cwd: root }); + }); + it('preserves the ordered machine diagnostics of a domain-invalid graph', () => { + const graph = { ...profile, initial_state: 'issued' }; + expect(exchange(request('compile_graph', graph))).toEqual({ + status: 'invalid', + diagnostics: [ + { code: 'INVALID_INITIAL_STATE', path: '$.initial_state', identifier: 'issued' }, + { code: 'UNREACHABLE_STATE', path: '$.states[0]', identifier: 'drafted' }, + { code: 'UNREACHABLE_STATE', path: '$.states[1]', identifier: 'checked' }, + ], + }); + }); + it('selects from the supplied run, including a terminal state and a mismatched binding', () => { + const compiled = exchange(request('compile_graph', profile)).compiled_graph; + const input = snapshot(compiled); + const decision = exchange(request('decide', input)); + expect(decision).toMatchObject({ + status: 'decision', + decision: { decision: { outcome: 'transition_available', transition_id: 'check_folio' } }, + }); + expect( + exchange(request('decide', { ...input, binding: { ...input.binding, source_state: 'issued' } })), + ).toMatchObject({ status: 'decision', decision: { decision: { outcome: 'terminal', terminal_state: 'issued' } } }); + expect( + exchange(request('decide', { ...input, binding: { ...input.binding, graph_digest: '0'.repeat(64) } })), + ).toEqual({ + status: 'invalid', + diagnostics: [{ code: 'BINDING_MISMATCH', path: '$.graph_digest', identifier: 'folio' }], + }); + }); + it('requests a human handoff for one applicable restoration and blocks equivalent restorations', () => { + for (const actions of [['restore_folio'], ['restore_folio', 'restore_checked_folio']]) { + const profileWithRestoration = { + ...profile, + guards: [ + ...profile.guards, + { + id: 'on_branch', + capability: 'repository', + parameters: { condition: 'clean_plan_branch' }, + required_actions: actions, + }, + ], + transitions: profile.transitions.map((edge) => + edge.id === 'check_folio' ? { ...edge, guard_refs: ['on_branch'], authority: ['threadloop', 'human'] } : edge, + ), + required_actions: [ + ...profile.required_actions, + ...actions.map((id) => ({ id, capability: 'restore_repository', authority: 'human', parameters: {} })), + ], + }; + const compiled = exchange(request('compile_graph', profileWithRestoration)).compiled_graph; + const { graph_digest } = z.object({ graph_digest: z.string() }).parse(compiled); + const input = snapshot(compiled, graph_digest); + input.observation.repository.branch = 'different-branch'; + input.available_capabilities.push({ actor: 'human', capability: 'restore_repository' }); + const decision = exchange(request('decide', input)); + const expected = + actions.length === 1 + ? { + outcome: 'human_action_required', + action_request: { request: { action_id: 'restore_folio', capability: 'restore_repository' } }, + } + : { outcome: 'blocked', reasons: [{ code: 'AMBIGUOUS_REMEDY' }] }; + expect(decision).toMatchObject({ status: 'decision', decision: { decision: expected } }); + } + }); + it('uses lexical ordering for integer-looking object keys in wire digests', () => { + const message = request('compile_graph', { '10': true, '2': false }); + const literal = '{"10":true,"2":false}'; + const payload = { ...message.request, input_digest: sha256(literal) }; + const content = canonicalJson(payload).replace('{"2":false,"10":true}', literal); + const requestDigest = sha256(content); + const result = invoke('{"request":' + content + ',"request_digest":' + JSON.stringify(requestDigest) + '}'); + expect(result.status, result.stderr).toBe(0); + const response = envelopeSchema.parse(JSON.parse(result.stdout)); + expect(response.response.request_digest).toBe(requestDigest); + expect(response.response.result.status).toBe('invalid'); + }); + it('rejects malformed framing and mismatched digests before emitting a response', () => { + const message = request('compile_graph', profile); + const invalidInput = { ...message.request, input_digest: '0'.repeat(64) }; + const unknownVersion = { ...message.request, protocol: 'threadloop.controller-conformance/2' }; + const wire = canonicalJson(message); + for (const [input, reason] of [ + [wire + '\n\n', 'request framing'], + [wire.replace('"case_id":', '"case_id":"case_900","case_id":'), 'request framing'], + [canonicalJson({ ...message, request_digest: '0'.repeat(64) }), 'request digest'], + [ + canonicalJson({ request: invalidInput, request_digest: sha256(canonicalJson(invalidInput)) }), + 'input or request digest', + ], + [ + canonicalJson({ request: unknownVersion, request_digest: sha256(canonicalJson(unknownVersion)) }), + 'request envelope', + ], + [canonicalJson({ ...message, extra: 1 }), 'request envelope'], + ['x'.repeat(16 * 1024 * 1024 + 2), 'message byte limit'], + ] as const) { + const refused = invoke(input); + expect(refused.status, refused.stderr).toBe(1); + expect(refused.stdout).toBe(''); + expect(refused.stderr).toContain(reason); + } + }); +}); diff --git a/tests/integration/controller-execution-scenario.test.ts b/tests/integration/controller-execution-scenario.test.ts new file mode 100644 index 0000000..c548c93 --- /dev/null +++ b/tests/integration/controller-execution-scenario.test.ts @@ -0,0 +1,360 @@ +import { expect, it, afterEach } from 'vitest'; +import { execFile } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { DatabaseSync } from '../../src/adapters/fs/sqlite-driver.js'; +import { ScenarioJournal } from '../../scripts/controller-conformance/scenario-journal.js'; +import { readSealedRoot, writeSealedRoot } from '../../src/adapters/fs/sealed-root.js'; +import { cleanupTemporaryState, makeTempDir } from '../helpers/session.js'; + +import { + createExecutionJournal, + applyExecutionOperation, + executionAdmissionDigest, + requestReference, +} from 'threadloop-contracts/execution'; +import type { + ExecutionContext, + ExecutionOperation, + ExecutionPolicy, + ExecutionJournal, +} from 'threadloop-contracts/execution'; +import { publicSnapshot } from '../generated/controller/adapter.js'; +import { selectWorkflowDecision } from '../../src/domain/workflow-controller.js'; +import { canonicalJson } from '../../src/domain/canonical-json.js'; +import { sha256 } from '../../src/adapters/crypto/sha256.js'; +import { runExecutionScenario } from '../../scripts/controller-conformance/execution-scenario.js'; + +afterEach(cleanupTemporaryState); + +async function fixture() { + const snapshot = await publicSnapshot(); + const selected = selectWorkflowDecision(snapshot); + if (!selected.ok || selected.value.decision.outcome !== 'engineering_action_required') + throw new Error('Fixture requires an engineering action.'); + const request = selected.value.decision.action_request; + const rules: ExecutionPolicy['rules'] = { + request: requestReference(request), + workflow_policy: { id: snapshot.policy.id, digest: snapshot.policy.digest }, + retry_safety: 'reconciliation_required', + max_attempts: 2, + }; + const policy = { id: 'scenario_policy', rules, digest: sha256(canonicalJson(rules)) }; + const identity = snapshot.policy.rules.authorities.find((item) => item.type === 'threadloop')!.identity; + const context: ExecutionContext = { + snapshot, + actor: { kind: 'threadloop', identity }, + recovery_evidence: [], + receipt_admissions: [], + }; + const initial = { context, request, policy }; + const admissions = new Set([executionAdmissionDigest({ kind: 'create', ...initial })]); + const authority = { isAdmitted: (digest: string) => admissions.has(digest) }; + const created = createExecutionJournal(context, request, policy, authority); + if (!created.ok) throw new Error(JSON.stringify(created.diagnostics)); + const genesis = created.value; + const operation: ExecutionOperation = { + schema_version: '0.1', + id: 'register_once', + actor: context.actor, + request: rules.request, + binding: request.request.binding, + execution_policy: { id: policy.id, digest: policy.digest }, + expected_revision: 0, + expected_execution_digest: genesis.execution_digest, + command: { kind: 'register_request', request }, + }; + const register = { context, operation }; + function authorizeStep(journal: ExecutionJournal, step: typeof register) { + admissions.add( + executionAdmissionDigest({ kind: 'operation', execution_digest: journal.execution_digest, ...step }), + ); + } + authorizeStep(genesis, register); + const registered = applyExecutionOperation(genesis, context, operation, authority); + if (!registered.ok) throw new Error(JSON.stringify(registered.diagnostics)); + return { + initial, + register, + genesis, + registered: registered.value.journal, + admissions, + authority, + authorizeStep, + snapshot, + }; +} + +it('requires an admission at the retained prefix before returning a registered operation on replay', async () => { + const { initial, register, registered, admissions, authorizeStep, snapshot } = await fixture(); + const run = () => + runExecutionScenario({ + initial, + steps: [register, register], + projection_snapshot: snapshot, + admitted_digests: [...admissions], + }); + expect(run()).toEqual({ + status: 'invalid', + diagnostics: [{ code: 'UNTRUSTED_EXECUTION_INPUT', path: '$', identifier: null }], + }); + authorizeStep(registered, register); + admissions.add( + executionAdmissionDigest({ kind: 'projection', execution_digest: registered.execution_digest, snapshot }), + ); + const result = { + disposition: 'applied', + code: 'REQUEST_ALREADY_REGISTERED', + revision: 1, + claim: null, + attempt_id: null, + }; + expect(run()).toMatchObject({ + status: 'execution', + steps: [ + { ...result, replayed: false }, + { ...result, replayed: true }, + ], + projection: { revision: 1, request_status: 'open', claims: [], attempts: [], receipts: [], conflicts: [] }, + }); +}); + +type Step = { context: ExecutionContext; operation: ExecutionOperation }; + +async function storedFixture() { + const facts = await fixture(); + const filename = path.join(await makeTempDir(), 'case.sqlite'); + const store = new ScenarioJournal(filename, facts.authority); + store.initialize(facts.genesis); + return { ...facts, filename, store }; +} + +function readRow(filename: string) { + const db = new DatabaseSync(filename, { readOnly: true }); + try { + return readSealedRoot(db); + } finally { + db.close(); + } +} + +function writer(filename: string, step: Step, admissions: Set<string>, cut?: string) { + const args = ['--import', 'tsx']; + if (cut) args.push('--import', fileURLToPath(new URL('../fixtures/workflow/sqlite-cut.mjs', import.meta.url))); + args.push(fileURLToPath(new URL('../fixtures/controller-execution-writer.mjs', import.meta.url))); + const child = execFile(process.execPath, args, { + timeout: 15_000, + env: { ...process.env, NODE_NO_WARNINGS: '1', ...(cut ? { THREADLOOP_TEST_SQLITE_CUT: cut } : {}) }, + }); + const stderr: string[] = []; + const stdout: string[] = []; + child.stdout!.on('data', (data: string) => stdout.push(data)); + const atLock = new Promise<void>((resolve, reject) => { + child.stderr!.on('data', (data: string) => { + stderr.push(data); + if (stderr.join('').includes('scenario-writer-at-begin')) resolve(); + }); + child.on('error', reject); + child.once('close', () => reject(new Error('Writer exited before reaching BEGIN IMMEDIATE: ' + stderr.join('')))); + }); + const exit = new Promise<{ code: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string }>( + (resolve, reject) => { + child.once('error', reject); + child.once('close', (code, signal) => + resolve({ code, signal, stdout: stdout.join(''), stderr: stderr.join('') }), + ); + }, + ); + child.stdin!.end(JSON.stringify({ filename, step, admissions: [...admissions] })); + return { atLock, exit }; +} + +it('refuses a journal with a mismatched storage digest without changing its retained bytes', async () => { + const { filename, store, register, genesis, admissions, snapshot } = await storedFixture(); + admissions.add( + executionAdmissionDigest({ kind: 'projection', execution_digest: genesis.execution_digest, snapshot }), + ); + expect(store.project(snapshot)).toMatchObject({ ok: true, value: { projection: { revision: 0 } } }); + + const observer = new DatabaseSync(filename); + try { + const row = observer.prepare('SELECT CAST(body AS BLOB) AS body,digest FROM root WHERE id=1'); + const original = row.get()!; + const otherDigest = sha256('different fixture journal'); + expect(original.digest).not.toBe(otherDigest); + expect(observer.prepare('UPDATE root SET digest=? WHERE id=1').run(otherDigest).changes).toBe(1); + const dataVersion = observer.prepare('PRAGMA data_version'); + const before = dataVersion.get(); + + expect(() => store.project(snapshot)).toThrowError(expect.objectContaining({ code: 'state.integrity' })); + expect(() => store.apply(register.context, register.operation)).toThrowError( + expect.objectContaining({ code: 'state.integrity' }), + ); + + expect(row.get()).toEqual({ body: original.body, digest: otherDigest }); + expect(dataVersion.get()).toEqual(before); + } finally { + observer.close(); + } +}); + +it('preserves the committed row on stale storage CAS and refuses an inner journal whose outer seal is valid', async () => { + const { filename, store, genesis, register, registered, snapshot } = await storedFixture(); + const initial = readRow(filename); + expect(store.apply(register.context, register.operation)).toMatchObject({ ok: true, value: { replayed: false } }); + const committed = readRow(filename); + expect(committed.value).toEqual(registered); + const stale = new DatabaseSync(filename); + try { + expect(() => writeSealedRoot(stale, genesis, initial.digest)).toThrow(/retained executor root changed/i); + expect(readRow(filename)).toEqual(committed); + const damaged = { ...registered, execution_digest: '0'.repeat(64) }; + const body = canonicalJson(damaged); + stale.prepare('UPDATE root SET body=?,digest=? WHERE id=1').run(body, sha256(body)); + expect(readRow(filename).value).toEqual(damaged); + expect(store.project(snapshot)).toMatchObject({ ok: false, diagnostics: [{ code: 'EXECUTION_DIGEST_MISMATCH' }] }); + expect(store.apply(register.context, register.operation)).toMatchObject({ + ok: false, + diagnostics: [{ code: 'EXECUTION_DIGEST_MISMATCH' }], + }); + expect(readRow(filename).value).toEqual(damaged); + } finally { + stale.close(); + } +}); + +it.each(['before commit', 'after commit'] as const)( + 'recovers an interrupted registration %s using the retained prefix', + async (cut) => { + const { filename, store, register, admissions, registered, authorizeStep } = await storedFixture(); + const prior = readRow(filename); + const process = writer(filename, register, admissions, cut); + await process.atLock; + const killed = await process.exit; + expect(killed).toMatchObject({ signal: 'SIGKILL', stdout: '' }); + expect(killed.stderr).toContain('workflow-cut=' + cut); + if (cut === 'before commit') { + expect(readRow(filename)).toEqual(prior); + expect(store.apply(register.context, register.operation)).toMatchObject({ + ok: true, + value: { replayed: false, result: { revision: 1 } }, + }); + } + const committed = readRow(filename); + expect(committed.value).toEqual(registered); + expect(store.apply(register.context, register.operation)).toMatchObject({ + ok: false, + diagnostics: [{ code: 'UNTRUSTED_EXECUTION_INPUT' }], + }); + authorizeStep(registered, register); + expect(store.apply(register.context, register.operation)).toMatchObject({ + ok: true, + value: { replayed: true, result: { revision: 1 } }, + }); + expect(readRow(filename)).toEqual(committed); + }, +); + +it('records one grant and one admitted version conflict from two processes competing for the same journal revision', async () => { + const { filename, store, register, initial, genesis, snapshot, admissions, authority, authorizeStep } = + await storedFixture(); + if (!snapshot.evaluation_time) throw new Error('The test snapshot requires a fixed host clock.'); + const validUntil = new Date(Date.parse(snapshot.evaluation_time) + 30_000).toISOString(); + const contender = (name: string): Step => { + const executor = { id: 'worker_' + name, incarnation: 'process_' + name }; + const actor: ExecutionContext['actor'] = { kind: 'executor', executor }; + return { + context: { ...initial.context, actor }, + operation: { + ...register.operation, + id: 'acquire_' + name, + actor, + command: { + kind: 'acquire', + executor, + claim_id: 'claim_' + name, + attempt_id: 'attempt_' + name, + valid_until: validUntil, + }, + }, + }; + }; + const steps = [contender('left'), contender('right')] as const; + // Admit both actual arrival orders. Each proposal still carries revision zero. + for (const [first, second] of [ + [steps[0], steps[1]], + [steps[1], steps[0]], + ] as const) { + authorizeStep(genesis, first); + const proposal = applyExecutionOperation(genesis, first.context, first.operation, authority); + if (!proposal.ok) throw new Error(JSON.stringify(proposal.diagnostics)); + authorizeStep(proposal.value.journal, second); + } + const owner = new DatabaseSync(filename); + const start: ReturnType<typeof writer>[] = []; + try { + owner.exec('BEGIN IMMEDIATE'); + for (const step of steps) start.push(writer(filename, step, admissions)); + await Promise.all(start.map((proc) => proc.atLock)); + expect(readRow(filename).value).toEqual(genesis); + owner.exec('COMMIT'); + } finally { + owner.close(); + } + const exits = await Promise.all(start.map((proc) => proc.exit)); + const reports = exits + .map((result) => { + expect(result.code, result.stderr).toBe(0); + return JSON.parse(result.stdout) as { + result: { code: string; revision: number; disposition: string; claim: { id: string } | null }; + }; + }) + .sort((a, b) => a.result.revision - b.result.revision); + expect(reports).toMatchObject([ + { replayed: false, result: { revision: 1, code: 'CLAIM_ACQUIRED', disposition: 'applied' } }, + { + replayed: false, + result: { revision: 2, code: 'EXECUTION_VERSION_CONFLICT', disposition: 'rejected', claim: null }, + }, + ]); + const row = readRow(filename); + const final = row.value as ExecutionJournal; + expect(final.execution.entries).toHaveLength(2); + admissions.add(executionAdmissionDigest({ kind: 'projection', execution_digest: final.execution_digest, snapshot })); + expect(store.project(snapshot)).toMatchObject({ + ok: true, + value: { + projection: { revision: 2, claims: [{ id: reports[0]!.result.claim!.id }], attempts: [{ status: 'pending' }] }, + }, + }); + for (const step of steps) { + authorizeStep(final, step); + expect(store.apply(step.context, step.operation)).toMatchObject({ ok: true, value: { replayed: true } }); + } + expect(readRow(filename)).toEqual(row); +}); + +it('refuses a different final snapshot without an independent admission and rejects duplicate authority digests', async () => { + const { initial, register, registered, admissions, snapshot } = await fixture(); + admissions.add( + executionAdmissionDigest({ kind: 'projection', execution_digest: registered.execution_digest, snapshot }), + ); + const input = { + initial, + steps: [register], + projection_snapshot: { ...snapshot, evaluation_time: '2026-09-10T10:00:01.000Z' }, + admitted_digests: [...admissions], + }; + expect(runExecutionScenario(input)).toMatchObject({ + status: 'invalid', + diagnostics: [{ code: 'UNTRUSTED_EXECUTION_INPUT' }], + }); + expect(runExecutionScenario({ ...input, admitted_digests: [...admissions, ...admissions] })).toEqual({ + status: 'invalid', + diagnostics: [{ code: 'DUPLICATE_ADMISSION', path: '$', identifier: null }], + }); + expect(runExecutionScenario({ ...input, steps: Array(257).fill(register) })).toEqual({ + status: 'invalid', + diagnostics: [{ code: 'SCHEMA_INVALID', path: '$.steps', identifier: null }], + }); +}); diff --git a/tests/proof/test_controller_conformance.py b/tests/proof/test_controller_conformance.py new file mode 100644 index 0000000..807b4ef --- /dev/null +++ b/tests/proof/test_controller_conformance.py @@ -0,0 +1,256 @@ +"""Exercise the same process launcher used by the external controller harness.""" + +import json +import importlib.util +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest.mock import patch + + +SCRIPTS = Path(__file__).resolve().parents[2] / "scripts/controller-conformance" +SPEC = importlib.util.spec_from_file_location("conformance_proof", SCRIPTS / "prove.py") +PROOF = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PROOF) + + +class LockedDependencyTest(unittest.TestCase): + """Verify the dependency bytes available to the controller build and the harness.""" + + def test_staged_resolution_ignores_same_version_change_in_ambient_install(self): + """Read the locked metadata from a fresh checkout while preserving the caller's local edit.""" + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + source = root / "source" + package = root / "data-package" + source.mkdir() + package.mkdir() + manifest = {"name": "proof-data", "version": "1.0.0", "description": "locked metadata"} + (package / "package.json").write_text(json.dumps(manifest)) + (source / ".gitignore").write_text("node_modules/\n") + (source / ".npmrc").write_text("offline=true\naudit=false\nfund=false\nupdate-notifier=false\n") + (source / "package.json").write_text( + json.dumps( + { + "name": "proof-fixture", + "version": "1.0.0", + "dependencies": {"proof-data": "file:proof-data-1.0.0.tgz"}, + } + ) + ) + env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + env.update( + GIT_CONFIG_GLOBAL=os.devnull, + GIT_CONFIG_NOSYSTEM="1", + npm_config_cache=str(root / "cache"), + npm_config_offline="true", + npm_config_userconfig=os.devnull, + npm_config_update_notifier="false", + npm_config_audit="false", + ) + with patch.dict(os.environ, env, clear=True): + + def command(cwd, *argv): + """Run a fixture command and return its trimmed stdout on success.""" + return subprocess.run( + argv, cwd=cwd, capture_output=True, text=True, check=True, timeout=60 + ).stdout.strip() + + command(package, "npm", "pack", "--offline", "--ignore-scripts", "--pack-destination", source) + command(source, "npm", "install", "--offline", "--ignore-scripts") + command(source, "git", "init", "-q") + command(source, "git", "add", ".") + command( + source, + "git", + "-c", + "user.name=Proof Fixture", + "-c", + "user.email=proof@example.invalid", + "commit", + "--no-gpg-sign", + "-qm", + "Pin the data package", + ) + revision = command(source, "git", "rev-parse", "HEAD") + original_checkout = PROOF.checkout(source, revision) + ambient_file = source / "node_modules/proof-data/package.json" + self.assertEqual(json.loads(ambient_file.read_bytes()), manifest) + ambient_file.write_text(json.dumps({**manifest, "description": "local metadata"})) + self.assertEqual(PROOF.checkout(source, revision), original_checkout) + read_metadata = ("node", "-p", "require('proof-data/package.json').description") + self.assertEqual(command(source, *read_metadata), "local metadata") + + staged = PROOF.stage_locked_checkout(source, revision, root / "staged") + + self.assertEqual(command(staged, "git", "rev-parse", "HEAD"), revision) + self.assertEqual( + (staged / "package-lock.json").read_bytes(), (source / "package-lock.json").read_bytes() + ) + self.assertEqual(command(staged, *read_metadata), "locked metadata") + self.assertEqual(command(source, *read_metadata), "local metadata") + + +class PublicPacketTest(unittest.TestCase): + """Check what a researcher can recover from a public packet when the subject fails.""" + + def test_failed_rows_exclude_oracle_payloads_transport_diagnostics_and_operator_paths(self): + """Keep all 38 cases and their identities while publishing only the named fields.""" + inventory = [] + results = [] + for index, operation in enumerate( + ["compile_graph"] * 3 + ["decide"] * 25 + ["execution_scenario"] * 10, 1 + ): + binding = { + "id": f"case_{index:03d}", + "operation": operation, + "input_digest": "1" * 64, + "request_digest": "2" * 64, + } + inventory.append( + { + **binding, + "fixture_digest": "3" * 64, + "graph_digest": None, + "source_path": "/private/canary", + } + ) + results.append( + { + **binding, + "response_digest": "4" * 64, + "stdout_sha256": "5" * 64, + "stderr_sha256": "6" * 64, + "status": "passed", + } + ) + for row, state in zip(results, ["nonconforming", "protocol_error", "transport_error"]): + row.update( + status=state, + actual={"console": "/private/canary"}, + expected={"value": "/private/canary"}, + diagnostic="transport read /private/canary", + ) + packet = { + "cases": results, + "passed": 35, + "failed": 3, + "protocol_error": 1, + "transport_error": 1, + "nonconforming": 1, + "total": 38, + } + sanitized = PROOF.public_cases(packet, inventory) + self.assertEqual(len(sanitized["cases"]), 38) + self.assertEqual(sanitized["nonconforming"], 1) + self.assertEqual(sanitized["cases"][0]["fixture_digest"], "3" * 64) + self.assertNotIn("/private/canary", json.dumps(sanitized)) + results[0]["request_digest"] = "a" * 64 + with self.assertRaisesRegex(ValueError, "Unbound"): + PROOF.public_cases(packet, inventory) + + +class ControllerIsolationTest(unittest.TestCase): + """Check the operating-system boundary without supplying any fixture answers.""" + + @unittest.skipUnless(sys.platform == "darwin", "The measured launcher uses macOS Seatbelt.") + def test_stalled_control_parent_releases_its_detached_case(self): + """Bound a stalled Node parent and confirm its independently grouped subject stops writing.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + cases = root / "cases" + cases.mkdir() + probe = root / "probe.cjs" + probe.write_text( + "const fs = require('node:fs');" + "fs.writeFileSync('subject-pid', String(process.pid));" + "setInterval(() => fs.appendFileSync('ticks', '.'), 50).unref();" + "setTimeout(() => {}, 2400);" + ) + controller = root / "check-controls.cjs" + controller.write_text( + "const fs = require('node:fs');" + "const {command, root, controlRoot} = JSON.parse(fs.readFileSync(0));" + "fs.writeFileSync(root + '/parent-pid', String(process.pid));" + "const child = require('node:child_process').spawn(command[0], command.slice(1), " + "{detached: true, stdio: 'ignore'});" + "child.unref();" + "const copyPid = setInterval(() => {" + "for (const caseDir of fs.readdirSync(controlRoot)) {" + "const base = controlRoot + '/' + caseDir;" + "if (fs.existsSync(base + '/ticks')) {" + "fs.copyFileSync(base + '/subject-pid', root + '/subject-pid'); clearInterval(copyPid);" + "Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2500);" + "}}}, 20); copyPid.unref();" + "setTimeout(() => process.stdout.write('{}'), 3300);" + ) + node = str(Path(shutil.which("node")).resolve()) + command = [ + sys.executable, + str(SCRIPTS / "launch.py"), + str(cases), + node, + str(probe), + str(probe), + str(probe), + ] + started = time.monotonic() + with ( + patch.object(PROOF, "SCRIPTS", root), + patch.object(PROOF, "CONTROL_PARENT_SECONDS", 1.5), + ): + with self.assertRaisesRegex(ValueError, "conformance controls.*deadline"): + PROOF.external_checks( + node, {"command": command, "root": str(root), "controlRoot": str(cases)}, (cases,) + ) + self.assertLess(time.monotonic() - started, 10) + parent_pid = int((root / "parent-pid").read_text()) + subject_pid = int((root / "subject-pid").read_text()) + self.assertEqual(list(cases.iterdir()), []) + for pid in (parent_pid, subject_pid): + with self.assertRaises(ProcessLookupError): + os.kill(pid, 0) + self.assertFalse(root.exists()) + + @unittest.skipUnless(sys.platform == "darwin", "The measured launcher uses macOS Seatbelt.") + def test_private_scratch_and_denied_parent_canary(self): + """A child can write its case output and receives a kernel denial for an existing parent file.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + cases = root / "cases" + cases.mkdir() + canary = root / "private-canary" + canary.write_text("parent-owned") + probe = root / "probe.cjs" + probe.write_text( + "const fs = require('node:fs');" + "fs.writeFileSync('output', 'case-owned');" + "try { fs.readFileSync(process.argv[2]); process.exitCode=1; }" + "catch (error) { console.log(JSON.stringify([error.code, fs.readFileSync('output','utf8')])); }" + ) + node = Path(shutil.which("node")).resolve() + result = subprocess.run( + [ + sys.executable, + SCRIPTS / "launch.py", + cases, + node, + probe, + probe, + probe, + canary, + ], + capture_output=True, + check=True, + text=True, + timeout=10, + ) + denial, value = json.loads(result.stdout) + self.assertIn(denial, {"EPERM", "EACCES"}) + self.assertEqual(value, "case-owned") + self.assertEqual(list(cases.iterdir()), []) diff --git a/tests/proof/test_managed_rollback_outputs.py b/tests/proof/test_managed_rollback_outputs.py new file mode 100644 index 0000000..bf47c97 --- /dev/null +++ b/tests/proof/test_managed_rollback_outputs.py @@ -0,0 +1,144 @@ +"""Check which retained child output files participate in the managed rollback proof.""" + +from contextlib import closing +import hashlib +import importlib +import json +import os +from pathlib import Path +import shutil +import sqlite3 +import subprocess +import sys +import tempfile +import unittest + + +SCRIPTS = Path(__file__).resolve().parents[2] / "scripts/pre-rust" +CHILD = Path(".threadloop/state/workflow-execution-fixture") +ARTIFACT = CHILD / "outputs/attempt-fixture/blobs/evidence" +DATABASES = [Path(".threadloop/state/state.db"), CHILD / "executor.sqlite"] + + +class RestoredChildOutputsTest(unittest.TestCase): + """Exercise the snapshot reader that compares the live, copied and restored control trees.""" + + def setUp(self): + """Create the SQLite tables read by the proof and one nested child output.""" + sys.path.insert(0, str(SCRIPTS)) + self.addCleanup(sys.path.remove, str(SCRIPTS)) + self.proof = importlib.import_module("managed_rollback") + work = tempfile.TemporaryDirectory() + self.addCleanup(work.cleanup) + self.scratch = Path(work.name).resolve() + self.live = self.scratch / "live" + (self.live / ARTIFACT).parent.mkdir(parents=True) + (self.live / ARTIFACT).write_bytes(b"retained child evidence\n") + with closing(sqlite3.connect(self.live / DATABASES[0])) as db: + db.executescript(""" + CREATE TABLE workflow_heads(run_id, state, version, revision, ordinal, digest); + CREATE TABLE workflow_execution_heads(run_id, revision, digest, active_reservation); + CREATE TABLE workflow_execution_events(run_id, kind); + """) + db.executemany( + "INSERT INTO workflow_heads VALUES (?, 'implementing', 3, 1, 0, 'head')", + [(self.proof.RUN,), (self.proof.LEGACY,)], + ) + db.execute( + "INSERT INTO workflow_execution_heads VALUES (?, 2, 'execution', 'reservation')", + (self.proof.RUN,), + ) + db.commit() + with closing(sqlite3.connect(self.live / DATABASES[1])) as db: + db.executescript(""" + PRAGMA user_version = 2; + CREATE TABLE root(body, digest); + CREATE TABLE launch(attempt, request_digest, output_directory); + CREATE TABLE observation(id, status, stdout, stderr, envelope); + CREATE TABLE accepted(source_id); + CREATE TABLE blob(digest, bytes); + """) + output_directory = (self.live / ARTIFACT).parents[1] + db.execute( + "INSERT INTO launch VALUES (?, ?, ?)", ("attempt-fixture", "request", str(output_directory)) + ) + body = json.dumps({"owner": {"workflow_run_id": self.proof.RUN}, "revision": 2}) + db.execute("INSERT INTO root VALUES (?, ?)", (body, hashlib.sha256(body.encode()).hexdigest())) + db.commit() + + def test_output_changes_break_the_restored_state_match_with_identical_databases(self): + """Detect changed, removed and additional output files during the same comparison as restore.""" + baseline = self.proof.receipt_state(self.live) + for difference in ("changed", "missing", "extra", "renamed", "extra-empty-directory"): + with self.subTest(difference=difference): + restored = shutil.copytree(self.live, self.scratch / difference) + self.assertEqual(self.proof.receipt_state(restored), baseline) + artifact = restored / ARTIFACT + if difference == "changed": + artifact.write_bytes(b"R" + artifact.read_bytes()[1:]) + elif difference == "missing": + artifact.unlink() + elif difference == "extra": + artifact.with_name("extra").write_bytes(artifact.read_bytes()) + elif difference == "renamed": + artifact.rename(artifact.with_name("renamed")) + else: + artifact.with_name("empty").mkdir() + current = self.proof.receipt_state(restored) + for db in DATABASES: + self.assertEqual((restored / db).read_bytes(), (self.live / db).read_bytes()) + self.assertNotEqual(current, baseline) + if difference in ("changed", "renamed"): + actual, expected = current["child"]["outputs"], baseline["child"]["outputs"] + self.assertEqual(actual["files"], expected["files"]) + self.assertEqual(actual["bytes"], expected["bytes"]) + self.assertNotEqual(actual["sha256"], expected["sha256"]) + + @unittest.skipUnless(hasattr(os, "mkfifo"), "The rollback file verifier uses POSIX paths.") + def test_refuses_output_links_and_special_files_before_reading_them(self): + """A link or named pipe must fail promptly, including a link at the output root.""" + outside = self.scratch / "outside" + outside.mkdir() + canary = outside / "canary" + canary.write_bytes(b"External fixture file\n") + original = canary.stat() + # A mistaken open on the pipe has a five-second deadline in the child test process. + for kind in ("file-link", "directory-link", "root-link", "fifo"): + with self.subTest(kind=kind): + restored = shutil.copytree(self.live, self.scratch / kind) + outputs = restored / CHILD / "outputs" + item = (restored / ARTIFACT).with_name("extra") + if kind == "fifo": + os.mkfifo(item) + elif kind == "root-link": + outputs.rename(self.scratch / "original-outputs") + outputs.symlink_to(outside, target_is_directory=True) + else: + item.symlink_to( + canary if kind == "file-link" else outside, + target_is_directory=kind == "directory-link", + ) + check = subprocess.run( + [ + sys.executable, + "-B", + "-c", + "import sys\nfrom pathlib import Path\nfrom managed_rollback import receipt_state\n" + "try: receipt_state(Path(sys.argv[1]))\n" + "except ValueError as error: sys.exit(str(error))", + restored, + ], + cwd=SCRIPTS, + capture_output=True, + text=True, + timeout=5, + ) + self.assertEqual(check.returncode, 1) + self.assertIn("Unsupported retained output kind at ", check.stderr) + self.assertEqual(canary.stat().st_mtime_ns, original.st_mtime_ns) + self.assertEqual(canary.read_bytes(), b"External fixture file\n") + self.assertEqual(list(outside.iterdir()), [canary]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/proof/test_pre_rust_packages.py b/tests/proof/test_pre_rust_packages.py new file mode 100644 index 0000000..23e6683 --- /dev/null +++ b/tests/proof/test_pre_rust_packages.py @@ -0,0 +1,163 @@ +"""Verify the complete npm archives used by the installed parity and rollback proofs.""" + +import hashlib +import importlib +import json +from pathlib import Path +import subprocess +import sys +import tarfile +import tempfile +import unittest + +SCRIPTS = Path(__file__).resolve().parents[2] / "scripts/pre-rust" + + +class PackageTrustTest(unittest.TestCase): + """Exercise the offline proof packer and installer with two real Git revisions.""" + + def setUp(self): + """Create a Git project whose build can add a harmless README note during packaging.""" + sys.path.insert(0, str(SCRIPTS)) + self.addCleanup(sys.path.remove, str(SCRIPTS)) + self.proof = importlib.import_module("proof_package") + work = tempfile.TemporaryDirectory() + self.addCleanup(work.cleanup) + self.root = Path(work.name).resolve() + self.project = self.root / "project" + self.project.mkdir() + self.env = { + **self.proof.offline_environment(self.root), + "GIT_AUTHOR_NAME": "Package Fixture", + "GIT_AUTHOR_EMAIL": "fixture@example.invalid", + "GIT_COMMITTER_NAME": "Package Fixture", + "GIT_COMMITTER_EMAIL": "fixture@example.invalid", + } + (self.project / ".gitignore").write_text("node_modules/\ndist/\n") + (self.project / "package.json").write_text( + json.dumps( + { + "name": "threadloop", + "version": "0.1.0", + "files": ["dist"], + "bin": {"threadloop": "dist/cli.js"}, + "scripts": {"build": "tsup"}, + "devDependencies": {"fixture-builder": "file:builder"}, + } + ) + ) + self.cli = b"#!/usr/bin/env node\nconsole.log('Installed package fixture');\n" + (self.project / "cli.js").write_bytes(self.cli) + builder = self.project / "builder" + builder.mkdir() + (builder / "package.json").write_text( + json.dumps( + { + "name": "fixture-builder", + "version": "1.0.0", + "bin": {"tsup": "build.cjs"}, + } + ) + ) + executable = builder / "build.cjs" + executable.write_text( + "#!/usr/bin/env node\n" + "const fs = require('node:fs');\n" + "fs.mkdirSync('dist', { recursive: true });\n" + "fs.copyFileSync('cli.js', 'dist/cli.js');\n" + "if (process.env.THREADLOOP_FIXTURE_README === '1') {\n" + " fs.appendFileSync('README.md', 'Alternate packaging note.\\n');\n" + "}\n" + ) + executable.chmod(0o755) + self.run_command("npm", "install", "--offline", "--ignore-scripts") + self.run_command("git", "init", "--quiet") + self.revisions = {} + for role in ("previous", "candidate"): + (self.project / "README.md").write_text(f"{role} fixture release\n") + self.run_command("git", "add", ".") + self.run_command("git", "commit", "--quiet", "-m", role) + self.revisions[role] = self.run_command("git", "rev-parse", "HEAD").strip() + + def run_command(self, *argv, env=None): + """Run a real package or Git command in the isolated fixture project.""" + return subprocess.run( + argv, + cwd=self.project, + env=env or self.env, + capture_output=True, + text=True, + check=True, + timeout=60, + ).stdout + + def pack(self, role, readme_note): + """Run the public pack command and read the archive and its own measured provenance.""" + directory = self.root / (role + ("-note" if readme_note else "-original")) + self.run_command( + sys.executable, + "-B", + SCRIPTS / "pack.py", + self.project, + self.revisions[role], + directory, + env={**self.env, "THREADLOOP_FIXTURE_README": "1" if readme_note else "0"}, + ) + record = json.loads((directory / "provenance.json").read_bytes()) + archive = directory / record["tarball"] + self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), record["sha256"]) + with tarfile.open(archive, "r:gz") as contents: + files = {entry.name: contents.extractfile(entry).read() for entry in contents if entry.isfile()} + return directory, record, files + + def test_candidate_and_previous_packages_require_the_source_built_archive(self): + """Verify both complete archives before either package can reach the installed proof.""" + packages = {} + repacked = {} + digests = {} + for role in ("candidate", "previous"): + revision = self.revisions[role] + original, trusted, first_files = self.pack(role, False) + changed, alternate, second_files = self.pack(role, True) + self.assertEqual(trusted["revision"], revision) + self.assertEqual(alternate["revision"], revision) + self.assertEqual(trusted["tree"], alternate["tree"]) + self.assertEqual(trusted["lock_blob"], alternate["lock_blob"]) + self.assertNotEqual(trusted["sha256"], alternate["sha256"]) + self.assertEqual(trusted["cli_sha256"], alternate["cli_sha256"]) + self.assertEqual(first_files["package/dist/cli.js"], self.cli) + self.assertEqual( + second_files.pop("package/README.md"), + first_files.pop("package/README.md") + b"Alternate packaging note.\n", + ) + self.assertEqual(first_files, second_files) + packages[role] = original, revision + repacked[role] = changed, revision + digests[role] = trusted["sha256"] + + for differing_role in packages: + with self.subTest(differing_role=differing_role): + scratch = self.root / ("refused-" + differing_role) + scratch.mkdir() + with self.assertRaisesRegex(ValueError, "(?i)(archive|tarball|package)"): + self.proof.install_packages( + self.project, + {**packages, differing_role: repacked[differing_role]}, + scratch, + self.env, + ) + for role in packages: + self.assertFalse((scratch / role).exists()) + + scratch = self.root / "accepted" + scratch.mkdir() + installed = self.proof.install_packages(self.project, packages, scratch, self.env) + for role in packages: + cli, record = installed[role] + self.assertEqual(record["sha256"], digests[role]) + self.assertEqual((cli.parents[1] / "README.md").read_text(), f"{role} fixture release\n") + self.assertEqual(self.run_command("node", cli), "Installed package fixture\n") + + +if __name__ == "__main__": + unittest.main()