diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9ea26c4f54..660e504b6e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -296,6 +296,10 @@ jobs: - name: Run targeted Windows detached worker regressions id: detached-worker-tests + # Always run after an earlier Windows step fails or the job is + # cancelled, so the report can distinguish a skipped test from missing + # evidence. + if: ${{ always() }} shell: pwsh env: HOME: ${{ runner.temp }}/ooo-detached-worker/home @@ -360,7 +364,12 @@ jobs: passed = len(cases) - failed - skipped lines += [f"Observed: {passed} passed, {failed} failed/error, {skipped} skipped.", "", "| Observation | Result | Detail |", "|---|---|---|"] - invalid = not cases or passed == 0 or failed > 0 + invalid = ( + os.environ["OOO_WORKER_TEST_OUTCOME"] != "success" + or not cases + or passed == 0 + or failed > 0 + ) checks = ( ("Console association", "test_venv_worker_completes_without_allocating_a_console_window"), ("Visible window", "test_venv_worker_completes_without_a_visible_console_window"), @@ -378,6 +387,7 @@ jobs: elif skip is not None: status = "UNSUPPORTED / NOT VERIFIED" detail = skip.get("message") or skip.text or "Observation unavailable." + invalid = True print(f"::warning::{label}: {status}: {detail}") else: status, detail = "PASS", "Legacy positive control and candidate assertions passed." diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 42836879d5..101f9edba4 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -66,6 +66,7 @@ ouroboros [OPTIONS] COMMAND [ARGS]... | `seed` | Generate or inspect seed specifications | | `workflow-ir` | Inspect workflow intermediate representation | | `zcode` | Convenience wrapper for Zcode (bundles `start`, `qa`, `run` with Zcode pre-selected; for global config use `setup --runtime zcode`) | +| `cloud` | Run a workspace-local zero-daemon workflow and export/import portable state bundles | > **Shorthand entry points:** `ooo` and `ouroboros` both launch the main CLI. > `ozo` is a standalone shorthand that launches only the Zcode convenience commands @@ -73,6 +74,29 @@ ouroboros [OPTIONS] COMMAND [ARGS]... --- +## `ouroboros cloud` + +Run a deterministic host-turn workflow in a managed cloud sandbox without a +background daemon, runtime socket, writable HOME/XDG directory, or private Git +authentication. State is stored under `/.ouroboros-cloud/`. + +```bash +ouroboros cloud init --workspace . --seed "Build a report" +ouroboros cloud plan --workspace . 'python -m compileall -q src' 'uv run pytest tests/unit/cloud -q' +ouroboros cloud next --workspace . +ouroboros cloud record-evidence tests passed --workspace . --step 0 +ouroboros cloud verify --workspace . +``` + +`cloud bundle export` creates a deterministic, checksum-manifested tar bundle. +For Git workspaces it also includes an execution patch tied to the recorded +base revision. `cloud bundle import` verifies the manifest and refuses to +apply that patch if local `HEAD` moved or the patch no longer applies. +Imported plans require `ouroboros cloud approve --workspace ` before +`cloud next` can execute their commands. + +--- + ## `ouroboros auto` diff --git a/docs/guides/cloud-runtime.md b/docs/guides/cloud-runtime.md new file mode 100644 index 0000000000..f2f1bf7719 --- /dev/null +++ b/docs/guides/cloud-runtime.md @@ -0,0 +1,83 @@ +# Cloud Sandbox / Zero-Daemon Runtime + +The portable runtime keeps its durable workflow state in +`/.ouroboros-cloud/state.json`. It does not use `HOME`, XDG state, +private GitHub credentials, background daemons, or runtime sockets. + +Environment detection is available through `ouroboros.cloud.detect_environment`. +It recognizes workspaces mounted below `/workspace`, `CODEX_CLOUD`, unavailable HOME/XDG directories, +`GIT_TERMINAL_PROMPT=0`, and explicit daemon/socket restrictions. It evaluates +`XDG_CONFIG_HOME` and `XDG_DATA_HOME` independently, including their HOME-based +defaults. These facts are diagnostic inputs; the portable driver always remains +usable when they are restricted. + +The host-shell driver is deterministic: planned commands run in list order, +once each, from the workspace with `GIT_TERMINAL_PROMPT=0`. Typical use is: + +```console +ooo cloud init --workspace . --seed "Build a report" +ooo cloud plan --workspace . 'python -m compileall -q src' 'uv run pytest tests/unit/cloud -q' +ooo cloud next --workspace . +# If a host turn disconnects while the command is running, inspect its effect +# and acknowledge the durable in-flight record instead of replaying it. +ooo cloud recover 0 --workspace . +ooo cloud record-evidence tests passed --workspace . +ooo cloud verify --workspace . +ooo cloud bundle-export portable.tar.gz --workspace . +ooo cloud bundle-import portable.tar.gz --workspace ./restored +ooo cloud approve --workspace ./restored +``` + +Verification is fail-closed. A valid run has at least one planned step, one +persisted checkpoint, successful return codes, and non-whitespace evidence +covering every planned step. Explicit evidence may target only a completed +step, so a future step cannot be marked observed before its host turn runs. +The most recent 64 verification receipts are retained so repeated host-turn +checks cannot grow the state file without bound. Cloud state mutations and +bundle transfers use a workspace-local file lock, so concurrent host turns +consume each planned step exactly once and an export observes one consistent +state-and-patch snapshot. +Before executing a command, the driver persists an `in_flight` intent. A +disconnect after the command's side effect therefore blocks automatic replay; +the next host turn must inspect the effect and use `cloud recover` to record the +observed result. This gives host turns an explicit at-most-once restart boundary +without pretending that a killed process can know whether its child finished. +Replanning is rejected while that intent exists, so a new plan cannot erase an +unacknowledged side effect. + +Bundles contain the JSON state, the generated bootstrap script, and (when the +workspace is a Git checkout) a binary-safe `execution.patch` relative to the +revision recorded when the run was initialized. The patch includes safe, +non-ignored regular files created during the cloud run. A sorted SHA-256 +manifest covers every payload, and tar/gzip metadata is normalized so repeated +exports are byte-for-byte identical. Import validates every member, checksum, +and the exact generated bootstrap payload before writing; a corrupted +checkpoint cannot replace a good one. The manifest is a checksum rather than +a cryptographic signature, so imported plans are marked unapproved and +require `cloud approve` before execution. + +When a patch is present, import first checks that local `HEAD` still equals the +cloud base revision and runs `git apply --check`. If local `main` advanced or +the patch no longer applies, import fails with a conflict and does not apply +the patch. The state-only legacy bundle form remains readable, but an +execution patch always requires the manifest. +Import also restores the prior patch, checkpoint, and bootstrap targets if a +later target write fails after patch application. State files are capped at +2 MiB and reject non-standard JSON numbers before persistence. + +## Live ChatGPT Work check (2026-11-30) + +Aside used the configured account and profile and opened a brand-new temporary +ChatGPT Work chat. The cloud host returned: + +```text +Linux 3a7e687d67fe 6.18.57 #1 SMP Tue Oct 20 21:56:04 UTC 2026 x86_64 GNU/Linux +{"roundtrip":true} +``` + +No existing/private chat, account settings, billing, or other service was +opened or changed. + +The local restricted-host simulation did complete the equivalent CLI roundtrip +with `env -i`, isolated HOME/XDG directories, `CODEX_CLOUD=1`, and +`GIT_TERMINAL_PROMPT=0`; it ended with `ISOLATED_CLOUD_ROUNDTRIP_OK`. diff --git a/docs/verification/2026-11-30-cloud-runtime-r1.md b/docs/verification/2026-11-30-cloud-runtime-r1.md new file mode 100644 index 0000000000..9550264fc5 --- /dev/null +++ b/docs/verification/2026-11-30-cloud-runtime-r1.md @@ -0,0 +1,488 @@ +# Cloud runtime evolution audit — 2026-11-30 + +## Scope + +Audited `origin/main...HEAD` for cloud-runtime security, state integrity, path +isolation, deterministic bundle recovery, and failure reporting. The audit was +performed in the assigned worktree on branch +`feat/cloud-sandbox-runtime-20261130`; no PR was merged. + +## Findings and fixes + +1. **Forged checkpoint identity could pass verification.** A planned single + `true` step with its persisted checkpoint index changed from `0` to `99` + still passed when return code and evidence were otherwise complete. The + verifier now requires contiguous checkpoint positions and exact command + correspondence with the plan, and records `invalid_checkpoints` in the + receipt. +2. **Evidence accepted an out-of-range step number.** A caller could record + evidence for step `1` when only step `0` existed. The driver now rejects + explicit evidence steps outside the current plan. +3. **Unsafe import targets could cause partial replacement.** Bundle import + validated the state target but could replace state before discovering a + symlinked or non-regular `bootstrap.sh`. Import now validates all state and + bootstrap targets before creating or replacing files; the regression test + confirms the prior checkpoint and outside target remain unchanged. +4. **Malformed local state was reported as a raw filesystem exception.** A + directory at `state.json` reached `read_text()` and raised `IsADirectoryError`. + The store now rejects non-regular state files with a stable `ValueError`. +5. **The Python 3.12 CI fixture was not portable.** The branch's full CI run + exposed a clone commit that depended on runner-global Git identity, and the + environment test depended on permission bits rather than effective access. + The fixture now configures its cloned repository locally, and environment + detection uses `os.access()` for writable HOME/XDG/runtime paths. +6. **Checkpoint continuation metadata was not covered by verification.** A + checkpoint with the correct index and command but a forged `next_step` value + still satisfied the earlier verifier. The verifier now requires each + checkpoint to advertise its contiguous position in the plan. +7. **Imported state accepted malformed execution inputs.** Version strings and + whitespace-only plan commands could be loaded from a hand-edited or legacy + state file. State decoding now accepts only version 1, string seeds, and + non-empty commands, and rejects evidence that targets a nonexistent step. +8. **Git patch export silently dropped generated files.** `git diff` does not + include untracked files, so a cloud-created output disappeared during a + bundle roundtrip. Export now encodes safe, non-ignored regular files as + binary-safe Git creation patches and rejects unsafe or oversized payloads. +9. **Patch import published state before applying the patch.** A failed patch + subprocess could leave the destination checkpoint claiming a result that + was never applied. Import now applies the validated patch before replacing + the portable state, with a fault-injection regression test for the failure + path. +10. **Bootstrap CLI override used shell word splitting.** A crafted + `OUROBOROS_CLOUD_CLI` value could alter the command and its arguments. The + generated helper now expands the override as one quoted executable path. + +## Empirical checks + +- `uv run pytest tests/unit/cloud tests/unit/cli/test_cli_telemetry.py -q` — + **36 passed**. +- `uv run pytest tests/ -k 'cloud' -q` — **41 passed, 8 skipped**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` after the + round-1 changes — **OK**. +- The cloud subset after the round-1 changes — **41 passed, 8 skipped**. +- Existing remote PR run `46303441439` had **38,883 passed, 319 skipped, + 1 xfailed, 2 failed** before this round; both failures were addressed by + the local Git fixture and effective-access changes. A replacement CI run is + required to independently confirm the remote result. +- Aside then completed a fresh temporary ChatGPT Work smoke test and observed + Linux `6.18.57` plus `{"roundtrip":true}` from a cloud-hosted workspace. + The test did not inspect existing/private chats or account settings. The + live result is complementary to, not a replacement for, the deterministic + local test suite. + +## Residual risks + +`CloudDriver.next()` intentionally has no subprocess timeout, so a host-turn +command can occupy its caller indefinitely. Adding a timeout would change the +declared execution contract and remains a separate, explicitly owned follow-up. + +## Round 3 — crash, disconnect, and restart audit + +Round 3 audited the `58797a932dfaa5f64f88616e054c9196595aa899` tree before +changes and concentrated on host-turn interruption boundaries. Three concrete +gaps were reproduced: + +1. A command could perform an external side effect and then lose its caller + before the checkpoint write, causing the next host turn to execute it again. +2. A fresh `CloudDriver` process had no dedicated regression proving that a + completed cursor remains a no-op after restart. +3. A hand-edited or transferred mid-step state had no schema contract for the + interrupted command, so recovery behavior was undefined. + +The fix adds a durable `in_flight` intent before every subprocess launch, +rejects replay with `CloudRecoveryRequired`, adds `cloud recover` for explicit +outcome acknowledgement, validates the intent against `next_step` and the +planned command, and clears it only when the checkpoint is persisted. Replanning +explicitly discards an abandoned intent. Parametrized crash tests cover every +step position in a three-step workflow and assert the side-effect stream remains +exactly `012`. + +The negative verification contract was rechecked: `init`-only, empty-plan, +failed-returncode, missing/empty evidence, whitespace-only evidence, and +interrupted-step states all return `False`; the CLI emits exit code 1 for the +failed and whitespace evidence workflows. A completed workflow in a fresh +driver returns no pending step and does not replay its side effect. + +Round 3 evidence in the working tree: + +- `uv run pytest tests/unit/cloud tests/unit/cli/test_cli_telemetry.py -q` — + **51 passed**. +- `uv run pytest tests/ -k 'cloud' -q` — **56 passed, 8 skipped**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. + +The ChatGPT Work / Aside Linux smoke result in the earlier section is retained +as historical evidence from the prior round. Round 3 did not open a new web +chat or claim a new live result; all Round 3 crash and recovery evidence is +local and deterministic. The external task log was outside the assigned +worktree and was not modified. + +## Round 4 — architecture math and reviewer walkthrough + +Round 4 audited the `a32a16a405c03a6b7f13d138bf2a950bf1bb29b4` tree before +changes. The review used the PR boundary in the description: workspace-local +state, deterministic host turns, fail-closed verification, and portable +bundle transfer. Three additional concrete gaps were reproduced and fixed: + +1. **Evidence could be assigned to a future step.** A caller could record + non-empty evidence for step `1` after planning two steps but before running + either step. The driver now requires an explicitly targeted step to be less + than `next_step`; a regression test proves the future assignment is + rejected. +2. **XDG data detection was incomplete.** When `XDG_CONFIG_HOME` was set, + detection ignored `XDG_DATA_HOME`, and when either variable was absent it + did not consistently evaluate the HOME-based default. Detection now checks + config and data independently and walks a writable HOME ancestor for + missing default directories. A restricted-data-home test covers the + asymmetric case. +3. **Manifest integrity did not authenticate bootstrap semantics.** A bundle + could replace `bootstrap.sh` and update its manifest checksum, causing + import to install arbitrary bootstrap content. Import now accepts only the + exact generated bootstrap payload, with a tampered-payload regression test. + +### Verification math + +For `N` planned steps, verification requires all of the following: `N > 0`, +`len(checkpoints) = N`, `next_step = N`, no in-flight intent, every checkpoint +has index `i`, command `plan[i]`, continuation `i + 1`, and return code `0`, +and the set of completed-step evidence indexes contains every `i` in +`0..N-1`. Evidence strings are trimmed before checking emptiness. Verification +also persists a bounded receipt; the last 64 receipts are retained. + +### Verified versus unverified matrix + +| Area | Evidence | Status and limit | +| --- | --- | --- | +| State durability | Atomic state writes, lock serialization, restart and crash tests | Verified locally; filesystem durability depends on the host filesystem. | +| Verification failure modes | Init-only, empty plan, failed return code, empty/whitespace evidence, forged checkpoints, future evidence | Verified by unit and CLI tests; evidence remains caller-supplied observation. | +| Bundle integrity | Path/member checks, manifest checksums, bootstrap payload check, patch conflict and injected patch failure tests | Verified locally; bundles are not cryptographically signed. | +| Cloud detection | `/workspace`, cloud flags, HOME, both XDG locations, runtime/socket limits | Verified with isolated environment fixtures; provider-specific variables remain advisory. | +| Live ChatGPT Work | Earlier temporary-chat check recorded Linux `6.18.57` and `{"roundtrip":true}` | Historical evidence only; Round 4 did not open a new web chat. | +| Command execution | Ordered `/bin/sh -c` host turns and `GIT_TERMINAL_PROMPT=0` | Verified; no subprocess timeout is promised or implemented. | + +### Reviewer walkthrough + +1. Run `cloud init` and `cloud plan`; inspect `.ouroboros-cloud/state.json`. +2. Run `cloud next` once per planned command. Each turn writes an in-flight + intent before execution and a plan-matched checkpoint after execution. +3. Record evidence with the completed step index. A future index is rejected. +4. Run `cloud verify`; inspect the JSON receipt and require exit code `0`. +5. Export and import a bundle. Import checks the state schema, manifest, + generated bootstrap, Git base, and patch applicability before publishing + the restored state. + +### Round 4 empirical evidence + +- `TMPDIR=/tmp uv run pytest tests/unit/cloud/test_runtime.py -v` — **45 + passed**. +- `TMPDIR=/tmp uv run pytest tests/unit/cloud tests/unit/cli/test_cli_telemetry.py + -q` — **54 passed**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main && uv run + pytest tests/ -k 'cloud' -q` — **59 passed, 8 skipped**. +- `uv run pytest -q` was not completed in Round 4, so no full-suite result is + claimed for that round. + +The separately requested external task log is outside this assigned +worktree, so it was not modified. The repository report is the authoritative +in-worktree record for this round. + +## Round 5 — CI audit, cross-module regression, and clean-diff review + +Round 5 audited the `0b03a6231e54378d2f6dc7c407d384b5b17433c1` tree and its +complete `origin/main...HEAD` diff. The existing PR #3129 remained open and +Draft throughout the audit. Four concrete weaknesses were reproduced or +identified at the runtime and CLI boundary: + +1. **Replanning reused stale evidence.** After a completed plan was replaced + with a new plan, the previous evidence records remained attached. A second + plan could therefore inherit observations from the first plan. Replanning + now clears evidence, and both driver-level and CLI-level tests prove that a + fresh plan cannot verify until new step evidence is recorded. +2. **Replanning reused an obsolete Git patch base.** The first plan's + `git_base_revision` survived later plans, so a bundle exported after a + commit between plans could include unrelated earlier changes. A new plan + now records the current HEAD and branch as its patch base. A Git-backed + regression test proves the revision changes with the plan. +3. **The direct evidence API had an unstable type boundary.** A non-string + evidence name raised `AttributeError` from `.strip()` instead of the + documented validation failure. The driver now rejects non-string names with + `ValueError`, covered by a unit test. +4. **Dangling state-directory symlinks lacked an explicit import regression.** + The existing early symlink guard already rejected them, but the absence of + a test left that protection vulnerable to future refactoring. A regression + test now exercises the dangling-target case before any bundle state can be + written. + +### Round 5 empirical evidence + +- `TMPDIR=/tmp uv run pytest tests/unit/cloud/test_runtime.py -q` — **49 + passed** after the Round 5 fixes. +- `uv run pytest tests/unit/cloud/test_cli.py + tests/unit/cli/test_cli_telemetry.py -q` — **10 passed** after the Round 5 + fixes. +- `TMPDIR=/tmp uv run pytest tests/unit/cloud/test_runtime.py + tests/unit/cloud/test_cli.py tests/unit/cli/test_cli_telemetry.py -q` — **59 + passed** after the Round 5 fixes. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. +- The deterministic cloud acceptance command was rerun after the Round 5 + fixes and recorded **64 passed, 8 skipped**. +- Negative verification remains explicit. `init`-only, empty plan, failed + return code, missing evidence, empty evidence, whitespace-only evidence, + malformed checkpoints, and interrupted execution all return `False`. The + CLI failure cases return exit code `1`. The replan CLI regression also + returns exit code `1` until fresh evidence is recorded. +- The full GitHub Actions workflow was audited from `.github/workflows/lint.yml`, + `.github/workflows/test.yml`, and `.github/workflows/module-size.yml`. The + required local gates cover the same Ruff, MyPy, Python 3.12, and module-size + paths. The remote checks shown before this round were green for the prior + PR head. A fresh remote result is required after the Round 5 push. + +### Round 5 live-environment characterization + +No new ChatGPT Web or Aside session was opened during Round 5. The earlier +temporary-chat observation remains historical evidence only and records Linux +`6.18.57` plus `{"roundtrip":true}`. Round 5 claims local deterministic +verification and CI configuration audit, not a new live browser result. + +### Round 5 residual risk + +`CloudDriver.next()` still has no subprocess timeout. A host-turn command can +occupy its caller indefinitely. This remains an explicitly owned follow-up +because adding cancellation semantics would change the declared execution +contract. + +## Round 6 — real-process journey and failure recovery simulation + +Round 6 audited the complete `origin/main...HEAD` diff and the open Draft PR +#3129 before making changes. Three concrete verification gaps remained: + +1. Existing cloud CLI coverage used `CliRunner` in one Python process, so it + did not prove that a fresh console process can resume state across host + turns or exercise the actual module entry point. +2. Existing restricted-host checks were unit-level observations. No end-to-end + journey combined missing HOME/XDG directories, cloud detection, forced + noninteractive Git, and workspace-local state in separate processes. +3. An interrupted in-flight step raised an unstructured exception from the + CLI, and no console-process regression covered recovery followed by bundle + transfer and verification. + +The fixes add three subprocess journey tests under +`tests/unit/cloud/test_process_journey.py`. They run `python -m ouroboros` +across fresh processes, simulate a disconnect after the durable in-flight +marker, recover the observed result, verify a completed two-step workflow, +export and import its bundle, and confirm the imported state in a new process. +The CLI now emits a JSON `recovery_required` record with exit code `2`, which +lets a host turn route directly to explicit recovery. Separate process tests +also prove that a failed step and a replan without new evidence both fail +closed. + +### Round 6 empirical evidence + +- `uv run pytest tests/unit/cloud/test_process_journey.py -q` — **3 passed**. +- `uv run pytest tests/unit/cli/test_cli_telemetry.py -q` — **3 passed**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK** after the process-journey import fix. +- `uv run mypy src/ouroboros` — **OK**. + +The safe live Aside check used a fresh ChatGPT Work chat and did not inspect +existing conversations or account settings. The managed cloud terminal +returned Linux `6.18.57` and `{'roundtrip': True}` for the requested smoke +test. The deterministic cloud gate recorded **67 passed, 8 skipped** after the +post-change run. The full-suite attempt is reported separately because it +includes unrelated baseline failures outside the cloud selection. + +## Round 7 — P99 tail, backpressure, and resource ceilings + +The adversarial review identified three concrete runtime gaps in the Round 6 +implementation: + +1. Plans, evidence, checkpoints, and captured command output had no explicit + size or count ceiling. A large host turn could grow the JSON checkpoint and + increase every later read/write tail. +2. A host command had no execution deadline. A blocked shell command could hold + the workspace transaction indefinitely and prevent later turns from making + progress. +3. Lock acquisition waited without a queue deadline. Concurrent host turns + could accumulate behind a long step with no bounded failure signal. + +The fixes are local to `ouroboros.cloud`: plans are capped at 256 steps, +commands at 16 KiB, evidence values at 128 KiB, captured stdout/stderr at +64 KiB, and evidence at 1,024 records. Steps default to a 300-second deadline +and record return code 124 when the deadline expires. Output that exceeds the +capture ceiling records return code 125. State lock acquisition defaults to a +30-second bounded wait and raises `CloudStateLockTimeout` when a turn cannot +enter the queue. + +### Round 7 empirical evidence + +- `uv run pytest tests/unit/cloud/ tests/unit/cli/test_cli_telemetry.py -q` — + 66 passed. +- An 8-worker, 32-step concurrent host-turn simulation completed in 266.9 ms; + measured p99 call latency was 266.0 ms, with 6,344 bytes of persisted state + and 32 bytes of command output. The run produced exactly one output byte per + planned step. +- New negative tests cover plan/evidence ceilings, bounded output failure, + timeout failure receipts, and cross-process lock backpressure. +- The existing CLI telemetry allowlist, failed-step verification, empty + evidence verification, process-journey recovery, and bundle roundtrip tests + remain green. + +### Round 7 residual risks + +The default deadline and ceilings are process-local policy values; callers that +need a different host budget must construct `CloudDriver` with explicit limits. +The command remains shell-based by design, so the runtime does not claim to +contain effects produced by a command that launches its own detached children. + +## Round 8 — maintainer-readiness and failure-path audit + +The adversarial review of `origin/main...HEAD` found three additional gaps: + +1. Evidence names had no size limit. A valid single record could inflate the + workspace-local state by megabytes and increase every later state rewrite. +2. Recovery accepted observed output through a separate path from normal + execution. Oversized output could therefore fail late in persistence rather + than receive the same bounded failure receipt as a regular host turn. +3. Bundle export wrote directly to its destination. An archive or filesystem + failure after truncation could destroy a previously usable bundle. + +The runtime now caps evidence names at 256 bytes, applies the normal output +ceiling and return code 125 during recovery, and writes bundles to a temporary +file before atomically replacing the requested destination. New regressions +cover all three cases, including preservation of an existing bundle when +archive creation fails. + +### Round 8 empirical evidence + +- `uv run pytest tests/unit/cloud tests/unit/cli/test_cli_telemetry.py -q` — + **69 passed**. +- `uv run pytest tests/ -k 'cloud' -q` — **74 passed, 8 skipped**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. +- `gh pr checks 3129 --repo Q00/ouroboros` reported all completed checks + successful; the platform-specific runtime and Python 3.12 jobs had not yet + produced a completed result at the time of inspection. +- Safe live Aside verification used a fresh ChatGPT Work chat and reached the + managed cloud terminal. It reported Linux `6.18.57`, clone status `0`, and + virtual-environment status `1`; installation and final verification were not + run because `ensurepip` was unavailable and the image requested + `python3.13-venv`. No live roundtrip pass is claimed. + +## Round 9 — security, tenant isolation, and fault-injection audit + +The adversarial review of `origin/main...HEAD` reproduced four weaknesses +inside the declared cloud-runtime boundary: + +1. **Replanning could erase an unresolved host command.** A state with an + `in_flight` command could be replaced by a new plan, losing the explicit + recovery marker and allowing an external side effect to become + unacknowledged. Replanning now raises `CloudRecoveryRequired` until the + interrupted step is recovered, and the state-preservation regression proves + the old plan and intent remain intact. +2. **Default cloud detection could merge project tenants.** When `/workspace` + existed, an invocation from `/workspace/scratch/` selected the + mount root and therefore shared `.ouroboros-cloud` state across projects. + Detection now uses the current directory unless a workspace or environment + override is explicit, while still recognizing paths below `/workspace` as + cloud mounts. +3. **State input accepted unbounded and non-standard values.** Direct state + loads had no bounded read and evidence accepted IEEE NaN values that are not + standard JSON. State reads and writes now enforce a 2 MiB limit, and JSON + serialization rejects non-finite numbers. +4. **Import rollback stopped before late target failures.** If `git apply` + succeeded and a later state or bootstrap write failed, the repository could + retain the patch while the checkpoint remained old. Import now restores the + patch and both target files on post-apply failure. A fault-injection test + verifies the repository, checkpoint, and bootstrap path return to their + prior state. + +### Round 9 empirical evidence + +- `python3 scripts/check-module-size.py --baseline-ref origin/main` — **OK**. +- The deterministic acceptance command — **78 passed, 8 skipped**. +- `uv run pytest tests/unit/cloud tests/unit/cli/test_cli_telemetry.py -q` — + **73 passed**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. +- A restricted local process journey with isolated HOME/XDG paths, + `CODEX_CLOUD=1`, `CHATGPT_WORK=1`, `OUROBOROS_NO_SOCKETS=1`, and + `GIT_TERMINAL_PROMPT=0` returned `ISOLATED_CLOUD_ROUNDTRIP_OK` with a true + verification receipt. +- A fresh ChatGPT Work chat completed the managed-cloud smoke test. The exact + observed kernel output was `Linux ef5dd49b77b0 6.18.57 #1 SMP Tue Oct 20 + 21:56:04 UTC 2026 x86_64 GNU/Linux`, and the temporary state-file roundtrip + succeeded with `state_exists: True`. +- `uv run pytest tests/ -q -x` reached **267 passed, 18 skipped** before the + first unrelated failure in + `tests/integration/mcp/test_detached_job_worker.py::test_detached_job_survives_accepting_process_exit[None-normal]`, + where the probe process exceeded its 15-second startup/exit wait. The + cloud-selected acceptance suite remained green. + +The working tree was checked for the scratch-root `STATUS.md`, +machine-specific absolute paths, and stale process-state wording. None remain. + +## Round 11 — crash, disconnect, restart, and adversarial property audit + +The adversarial review of `origin/main...HEAD` and the open Draft PR checks +found four concrete gaps at the host-turn boundary: + +1. **Normal byte output was falsely classified as oversized.** The new + streaming runner returns bytes, while the normalizer returns text. Comparing + those values directly made even an empty successful command receive return + code `125`, which caused 17 cloud regressions. The normalizer now checks the + encoded size of the original value and preserves empty output and output at + exactly the configured ceiling. +2. **Crash tests exercised a removed subprocess hook.** The runner moved from + `subprocess.run` to Popen plus reader threads, but interruption tests still + patched the old call and therefore did not prove the durable in-flight + intent. The tests now interrupt the runner seam directly after recording a + side effect and cover a launch-level OSError as well. +3. **Restart coverage stopped after one fresh driver.** A completed step was + proven only across one restart. The regression now creates three fresh + drivers and confirms every subsequent `next()` is a no-op, while the + interrupted path rejects a second recovery acknowledgement and never + replays the side effect. +4. **The most recent PR check had an unrelated Windows timeout failure.** The + completed remote run reported + `test_the_callers_timeout_path_leaves_nothing_behind` in the existing + Windows execution-sandbox suite; it did not touch `ouroboros.cloud`. The + local Windows-targeted selection on this host completed with 58 passed and + 40 skipped. A fresh remote run after this commit is required to distinguish + that pre-existing platform failure from this cloud change. + +### Round 11 empirical evidence + +- `uv run pytest tests/unit/cloud tests/unit/cli/test_cli_telemetry.py -q` — + **75 passed**. +- `python3 scripts/check-module-size.py --baseline-ref origin/main && uv run + pytest tests/ -k 'cloud' -q` — **80 passed, 8 skipped**. +- `uv run ruff format --check src/ tests/` — **OK**. +- `uv run ruff check src/ tests/` — **OK**. +- `uv run mypy src/ouroboros` — **OK**. +- `uv run pytest tests/unit/runtime/test_exec_sandbox.py + tests/unit/runtime/test_exec_sandbox_windows.py -n 0 -q` — **58 passed, + 40 skipped** on the current host. +- The new tests cover empty and exact-ceiling byte output, launch failure with + restart recovery, three repeated fresh-process no-op restarts, and duplicate + recovery acknowledgement rejection. + +The full repository pytest run was started for independent audit coverage. Its +final result is recorded in the PR description and must not be represented as +cloud-suite evidence unless the process completes successfully. diff --git a/llms-full.txt b/llms-full.txt index af2e6dd564..70b870bc6c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -67,6 +67,7 @@ Two command surfaces exist. They are NOT a 1:1 mapping. ouroboros auto Run bounded full-quality ooo auto pipeline. ouroboros cancel Cancel stuck or orphaned executions. ouroboros cleanup Prune leftover auto-session worktrees, branches, locks, and state files. + ouroboros cloud Run a workspace-local zero-daemon cloud workflow. ouroboros codex Manage Ouroboros Codex CLI integration artifacts. ouroboros config Manage Ouroboros configuration. ouroboros detect Generate .ouroboros/mechanical.toml via one AI call. diff --git a/llms.txt b/llms.txt index 3557d84d8b..42902de1bc 100644 --- a/llms.txt +++ b/llms.txt @@ -48,6 +48,7 @@ Every top-level command `ouroboros --help` lists; `ouroboros --help` s - `ouroboros auto`: Run bounded full-quality ooo auto pipeline. - `ouroboros cancel`: Cancel stuck or orphaned executions. - `ouroboros cleanup`: Prune leftover auto-session worktrees, branches, locks, and state files. +- `ouroboros cloud`: Run a workspace-local zero-daemon cloud workflow. - `ouroboros codex`: Manage Ouroboros Codex CLI integration artifacts. - `ouroboros config`: Manage Ouroboros configuration. - `ouroboros detect`: Generate .ouroboros/mechanical.toml via one AI call. diff --git a/src/ouroboros/cli/commands/cloud.py b/src/ouroboros/cli/commands/cloud.py new file mode 100644 index 0000000000..483ed7a122 --- /dev/null +++ b/src/ouroboros/cli/commands/cloud.py @@ -0,0 +1,163 @@ +"""CLI for the portable zero-daemon cloud runtime.""" + +from __future__ import annotations + +from dataclasses import asdict +import json +from pathlib import Path +from typing import Annotated + +import typer + +from ouroboros.cloud.bundle import export_bundle, import_bundle +from ouroboros.cloud.driver import CloudApprovalRequired, CloudDriver, CloudRecoveryRequired +from ouroboros.cloud.environment import detect_environment +from ouroboros.cloud.state import CloudStateLockTimeout + +app = typer.Typer(name="cloud", help="Run a workspace-local zero-daemon cloud workflow.") +record_app = typer.Typer(help="Record portable workflow evidence.") +bundle_app = typer.Typer(help="Export or import a portable workflow bundle.") + + +def _driver(workspace: Path | None) -> CloudDriver: + return CloudDriver(detect_environment(workspace).workspace) + + +@app.command() +def init( + workspace: Annotated[Path | None, typer.Option("--workspace")] = None, seed: str = "" +) -> None: + state = _driver(workspace).init(seed) + typer.echo(json.dumps(state.to_dict(), indent=2, sort_keys=True)) + + +@app.command() +def plan( + steps: Annotated[list[str], typer.Argument()], + workspace: Annotated[Path | None, typer.Option("--workspace")] = None, +) -> None: + state = _driver(workspace).plan(steps) + typer.echo(json.dumps(state.to_dict(), indent=2, sort_keys=True)) + + +@app.command(name="seed") +def seed_plan( + seed: str, workspace: Annotated[Path | None, typer.Option("--workspace")] = None +) -> None: + state = _driver(workspace).init(seed) + typer.echo(json.dumps(state.to_dict(), indent=2, sort_keys=True)) + + +@app.command() +def next(workspace: Annotated[Path | None, typer.Option("--workspace")] = None) -> None: + driver = _driver(workspace) + try: + result = driver.next() + except CloudStateLockTimeout as exc: + typer.echo(json.dumps({"error": "state_lock_timeout", "message": str(exc)})) + raise typer.Exit(code=2) from exc + except CloudRecoveryRequired as exc: + typer.echo( + json.dumps( + { + "error": "recovery_required", + "in_flight": driver.state.in_flight, + "message": str(exc), + }, + sort_keys=True, + ) + ) + raise typer.Exit(code=2) from exc + except CloudApprovalRequired as exc: + typer.echo(json.dumps({"error": "approval_required", "message": str(exc)})) + raise typer.Exit(code=2) from exc + typer.echo("no pending step" if result is None else json.dumps(asdict(result), sort_keys=True)) + + +@app.command() +def recover( + returncode: int, + stdout: str = "", + stderr: str = "", + step: Annotated[int | None, typer.Option("--step")] = None, + workspace: Annotated[Path | None, typer.Option("--workspace")] = None, +) -> None: + """Acknowledge an interrupted step after inspecting its host-side effects.""" + result = _driver(workspace).recover( + returncode=returncode, stdout=stdout, stderr=stderr, step=step + ) + typer.echo(json.dumps(asdict(result), sort_keys=True)) + + +@app.command() +def approve(workspace: Annotated[Path | None, typer.Option("--workspace")] = None) -> None: + """Approve an imported plan for host execution.""" + typer.echo(json.dumps(_driver(workspace).approve().to_dict(), sort_keys=True)) + + +@record_app.command("evidence") +def record_evidence( + name: str, + value: str, + step: Annotated[int | None, typer.Option("--step")] = None, + workspace: Annotated[Path | None, typer.Option("--workspace")] = None, +) -> None: + typer.echo( + json.dumps( + _driver(workspace).record_evidence(name, value, step).to_dict(), + indent=2, + sort_keys=True, + ) + ) + + +@app.command() +def verify(workspace: Annotated[Path | None, typer.Option("--workspace")] = None) -> None: + driver = _driver(workspace) + valid = driver.verify() + typer.echo(json.dumps(driver.state.verification_receipts[-1], sort_keys=True)) + raise typer.Exit(code=0 if valid else 1) + + +@app.command() +def status(workspace: Annotated[Path | None, typer.Option("--workspace")] = None) -> None: + """Print the current portable state and detected host constraints.""" + driver = _driver(workspace) + environment = detect_environment(driver.store.workspace) + typer.echo( + json.dumps( + {"environment": environment.to_dict(), "state": driver.state.to_dict()}, + indent=2, + sort_keys=True, + ) + ) + + +@bundle_app.command("export") +def bundle_export( + destination: Path, workspace: Annotated[Path | None, typer.Option("--workspace")] = None +) -> None: + typer.echo(str(export_bundle(_driver(workspace).store.workspace, destination))) + + +@bundle_app.command("import") +def bundle_import( + bundle: Path, workspace: Annotated[Path | None, typer.Option("--workspace")] = None +) -> None: + typer.echo(str(import_bundle(bundle, _driver(workspace).store.workspace))) + + +# Keep single-command spellings stable for scripts while supporting readable +# ``cloud record evidence`` and ``cloud bundle export`` forms. +app.command(name="record-evidence")(record_evidence) +app.command(name="bundle-export")(bundle_export) +app.command(name="bundle-import")(bundle_import) +app.command(name="next-step")(next) +app.add_typer(record_app, name="record") +app.add_typer(bundle_app, name="bundle") + + +# Long-form spellings read naturally in host-turn instructions. Keep the +# original bundle-* names for compatibility with the first cloud prototype. +app.command(name="export-bundle")(bundle_export) +app.command(name="import-bundle")(bundle_import) diff --git a/src/ouroboros/cli/main.py b/src/ouroboros/cli/main.py index 252c849c68..516ad77a43 100644 --- a/src/ouroboros/cli/main.py +++ b/src/ouroboros/cli/main.py @@ -102,6 +102,7 @@ class _Command(NamedTuple): _Group("gui", f"{_COMMANDS_PACKAGE}.gui"), _Group("service", f"{_COMMANDS_PACKAGE}.service"), _Group("pm", f"{_COMMANDS_PACKAGE}.pm"), + _Group("cloud", f"{_COMMANDS_PACKAGE}.cloud"), _Command( "qa", f"{_COMMANDS_PACKAGE}.qa", diff --git a/src/ouroboros/cloud/__init__.py b/src/ouroboros/cloud/__init__.py new file mode 100644 index 0000000000..68864e723f --- /dev/null +++ b/src/ouroboros/cloud/__init__.py @@ -0,0 +1,21 @@ +"""Portable, workspace-local runtime for restricted cloud sandboxes.""" + +from ouroboros.cloud.bootstrap import bootstrap_bundle +from ouroboros.cloud.bundle import export_bundle, import_bundle +from ouroboros.cloud.driver import CloudApprovalRequired, CloudDriver, CloudRecoveryRequired +from ouroboros.cloud.environment import CloudEnvironment, detect_environment +from ouroboros.cloud.state import CloudState, CloudStateLockTimeout, CloudStateStore + +__all__ = [ + "CloudDriver", + "CloudApprovalRequired", + "CloudRecoveryRequired", + "CloudEnvironment", + "CloudState", + "CloudStateLockTimeout", + "CloudStateStore", + "detect_environment", + "export_bundle", + "import_bundle", + "bootstrap_bundle", +] diff --git a/src/ouroboros/cloud/bootstrap.py b/src/ouroboros/cloud/bootstrap.py new file mode 100644 index 0000000000..df73657d9d --- /dev/null +++ b/src/ouroboros/cloud/bootstrap.py @@ -0,0 +1,15 @@ +"""Bootstrap a portable cloud bundle without auth, sockets, or child daemons.""" + +from __future__ import annotations + +from pathlib import Path + +from ouroboros.cloud.bundle import import_bundle + + +def bootstrap_bundle(bundle: str | Path, workspace: str | Path) -> Path: + """Restore ``bundle`` into ``workspace`` and return its portable state path.""" + return import_bundle(bundle, workspace) + + +__all__ = ["bootstrap_bundle"] diff --git a/src/ouroboros/cloud/bundle.py b/src/ouroboros/cloud/bundle.py new file mode 100644 index 0000000000..014273c4dd --- /dev/null +++ b/src/ouroboros/cloud/bundle.py @@ -0,0 +1,914 @@ +"""Deterministic tar bundles for portable cloud state and Git patches.""" + +from __future__ import annotations + +import base64 +import binascii +from hashlib import sha256 +import io +import json +import os +from pathlib import Path, PureWindowsPath +import stat +import subprocess +import tarfile +import tempfile + +from ouroboros.cloud.state import CloudState, CloudStateStore, _reject_nonstandard_json +from ouroboros.runtime.child_env import build_child_env + +_MAX_MEMBER_SIZE = 2 * 1024 * 1024 +_STATE_NAME = ".ouroboros-cloud/state.json" +_PATCH_NAME = ".ouroboros-cloud/execution.patch" +_MANIFEST_NAME = ".ouroboros-cloud/manifest.json" +_IMPORT_JOURNAL_NAME = ".ouroboros-cloud/import-recovery.json" +_BOOTSTRAP_NAME = "bootstrap.sh" +_MAX_MEMBER_COUNT = 4 + + +def export_bundle(workspace: str | Path, destination: str | Path) -> Path: + """Export a reproducible state bundle, including a Git execution patch. + + The patch is relative to the revision recorded when the cloud run was + initialized. It excludes the portable state directory itself. Every + payload is listed in a manifest so imports can reject corruption before + writing anything to the destination. + """ + store = CloudStateStore(workspace) + with store.lock(): + state = store.initialize() + state_payload = _json_bytes(state.to_dict()) + patch_payload = _git_patch(store.workspace, state) + files = {_STATE_NAME: state_payload} + if patch_payload: + files[_PATCH_NAME] = patch_payload + files[_BOOTSTRAP_NAME] = _bootstrap_payload() + if any(len(payload) > _MAX_MEMBER_SIZE for payload in files.values()): + raise ValueError(f"cloud bundle member exceeds {_MAX_MEMBER_SIZE} bytes") + files[_MANIFEST_NAME] = _json_bytes(_manifest(files, state)) + + destination_path = Path(destination).expanduser().resolve() + if destination_path == store.root or store.root in destination_path.parents: + raise ValueError("cloud bundle destination must be outside the state directory") + destination_path.parent.mkdir(parents=True, exist_ok=True) + _write_deterministic_tar(destination_path, files) + return destination_path + + +def import_bundle(bundle: str | Path, workspace: str | Path) -> Path: + """Validate and restore a bundle, applying its patch only on its base. + + Validation is performed entirely in memory first. A malformed state or + checksum therefore cannot replace a previously good checkpoint. A patch + is applied only when the destination repository's ``HEAD`` exactly equals + the cloud run's recorded base revision; this prevents silently applying a + cloud result to a local ``main`` that moved meanwhile. + """ + destination = Path(workspace).expanduser().resolve() + destination_existed = destination.exists() + target = destination / ".ouroboros-cloud" + target_existed = target.exists() + if target.is_symlink(): + raise ValueError("cloud import directory must not be a symlink") + # Decode and authenticate the archive before creating the destination's + # state directory. An invalid transfer must leave a new workspace absent, + # just as it leaves an existing checkpoint untouched. + files = _read_and_validate_bundle(Path(bundle).expanduser().resolve()) + manifest = _decode_manifest(files.get(_MANIFEST_NAME)) + _verify_manifest(manifest, files) + state = _decode_state(files[_STATE_NAME]) + if files[_BOOTSTRAP_NAME] != _bootstrap_payload(): + raise ValueError("cloud bundle bootstrap payload is not trusted") + patch = files.get(_PATCH_NAME) + state.execution_approved = False + files[_STATE_NAME] = _json_bytes(state.to_dict()) + + if destination.exists() and not destination.is_dir(): + raise ValueError("cloud import workspace must be a directory") + if patch and not destination.exists(): + _check_patch_base(destination, state) + store = CloudStateStore(destination) + try: + with store.lock(): + # Recheck after acquiring the workspace lock in case another process + # created or replaced the target between archive validation and lock. + if target.is_symlink(): + raise ValueError("cloud import directory must not be a symlink") + _recover_import_journal(destination, target) + patch_already_applied = False + if patch: + _check_patch_base(destination, state) + try: + _check_patch(destination, patch) + except ValueError as forward_error: + if _check_patch_applied(destination, patch): + patch_already_applied = True + else: + raise forward_error + + _validate_import_targets(destination) + targets = { + target / "state.json": files[_STATE_NAME], + destination / "bootstrap.sh": files[_BOOTSTRAP_NAME], + } + previous = {path: _existing_file(path) for path in targets} + patch_applied = False + journal_path = destination / _IMPORT_JOURNAL_NAME + try: + if patch and not patch_already_applied: + _write_import_journal(destination, target, patch) + _apply_patch(destination, patch) + patch_applied = True + target.mkdir(parents=True, exist_ok=True) + for path, payload in targets.items(): + _write_regular_file(path, payload) + except BaseException as exc: + if journal_path.is_file() or journal_path.is_symlink(): + try: + _recover_import_journal(destination, target) + except BaseException as rollback_error: + exc.add_note(f"cloud import journal recovery failed: {rollback_error}") + elif patch: + patch_needs_rollback = patch_already_applied or patch_applied + if not patch_needs_rollback: + patch_needs_rollback = _check_patch_applied(destination, patch) + if patch_needs_rollback: + try: + _reverse_patch(destination, patch) + except BaseException as rollback_error: + exc.add_note(f"cloud patch rollback failed: {rollback_error}") + try: + for path, payload in previous.items(): + _restore_file(path, payload) + except BaseException as restore_error: + exc.add_note(f"cloud import target rollback failed: {restore_error}") + raise + # Re-read after the atomic state replacement as a final schema check. + store.load() + if journal_path.exists(): + journal_path.unlink() + _fsync_directory(journal_path.parent) + return target / "state.json" + except BaseException: + _remove_import_scaffold( + destination, + target, + destination_existed=destination_existed, + target_existed=target_existed, + ) + raise + + +def _json_bytes(value: object) -> bytes: + return ( + json.dumps(value, allow_nan=False, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + ).encode("utf-8") + + +def _bootstrap_payload() -> bytes: + return b"""#!/bin/sh +# Portable Ouroboros cloud bundle; no daemon, network, or auth required. +set -eu +workspace=${1:-.} +state="$workspace/.ouroboros-cloud/state.json" +if [ ! -f "$state" ]; then + echo "missing cloud state: $state" >&2 + exit 1 +fi +echo "Ouroboros cloud state: $state" +cli=${OUROBOROS_CLOUD_CLI:-ouroboros} +exec "$cli" cloud verify --workspace "$workspace" +""" + + +def _git_patch(workspace: Path, state: CloudState) -> bytes: + base = state.git_base_revision + if not base: + return b"" + try: + result = subprocess.run( + [ + "git", + "diff", + "--binary", + "--no-ext-diff", + "--end-of-options", + base, + "--", + ".", + ":(exclude).ouroboros-cloud/**", + ], + cwd=workspace, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot capture cloud execution patch: {exc}") from exc + if result.returncode != 0: + raise ValueError("cannot capture cloud execution patch") + untracked = _untracked_patch(workspace, state.git_untracked_paths) + return result.stdout + untracked + + +def _untracked_patch(workspace: Path, baseline_paths: list[str]) -> bytes: + """Encode safe, non-ignored files created by the cloud run as Git patches.""" + try: + listed = subprocess.run( + [ + "git", + "ls-files", + "--others", + "--exclude-standard", + "-z", + "--", + ".", + ":(exclude).ouroboros-cloud", + ":(exclude).ouroboros-cloud/**", + ], + cwd=workspace, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot enumerate cloud execution files: {exc}") from exc + if listed.returncode != 0: + raise ValueError("cannot enumerate cloud execution files") + + patches: list[bytes] = [] + baseline = set(baseline_paths) + paths = sorted( + (os.fsdecode(raw) for raw in listed.stdout.split(b"\0") if raw), + key=lambda path: os.fsencode(path), + ) + for relative in paths: + if relative in baseline: + continue + relative_path = Path(relative) + if relative_path.is_absolute() or ".." in relative_path.parts: + raise ValueError("cannot capture an unsafe untracked cloud path") + if relative_path.parts[:1] == (".ouroboros-cloud",): + continue + candidate = workspace / relative_path + try: + if candidate.is_symlink() or not candidate.is_file(): + raise ValueError("cannot capture an untracked symlink or non-file") + if not candidate.resolve().is_relative_to(workspace): + raise ValueError("cannot capture an untracked path outside the workspace") + result = subprocess.run( + [ + "git", + "diff", + "--no-index", + "--binary", + "--no-ext-diff", + "--", + "/dev/null", + relative, + ], + cwd=workspace, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot capture cloud execution file: {relative}") from exc + if result.returncode not in {0, 1}: + raise ValueError(f"cannot capture cloud execution file: {relative}") + if result.stdout: + patches.append(result.stdout) + return b"".join(patches) + + +def _manifest(files: dict[str, bytes], state: CloudState) -> dict[str, object]: + return { + "format": 2, + "files": { + name: {"sha256": _checksum(payload), "size": len(payload)} + for name, payload in sorted(files.items()) + }, + "git": { + "base_revision": state.git_base_revision, + "branch": state.git_branch, + "patch": _PATCH_NAME if _PATCH_NAME in files else None, + }, + } + + +def _checksum(payload: bytes) -> str: + return sha256(payload).hexdigest() + + +def _write_deterministic_tar(destination: Path, files: dict[str, bytes]) -> None: + fd, temporary = tempfile.mkstemp( + prefix=f"{destination.name}.", suffix=".tmp", dir=destination.parent + ) + try: + with os.fdopen(fd, "wb") as raw: + # Fix gzip's timestamp as well as tar's metadata. This makes two + # exports of the same workspace byte-for-byte identical. + import gzip + + with gzip.GzipFile(fileobj=raw, filename="", mode="wb", mtime=0) as compressed: + with tarfile.open(fileobj=compressed, mode="w") as archive: + for name in sorted(files): + info = tarfile.TarInfo(name) + info.size = len(files[name]) + info.mode = 0o755 if name == _BOOTSTRAP_NAME else 0o644 + info.mtime = 0 + archive.addfile(info, io.BytesIO(files[name])) + raw.flush() + os.fsync(raw.fileno()) + os.replace(temporary, destination) + _fsync_directory(destination.parent) + finally: + Path(temporary).unlink(missing_ok=True) + + +def _read_and_validate_bundle(bundle: Path) -> dict[str, bytes]: + allowed = {_STATE_NAME, _PATCH_NAME, _MANIFEST_NAME, _BOOTSTRAP_NAME} + try: + with tarfile.open(bundle, "r:gz") as archive: + files: dict[str, bytes] = {} + for member_count, member in enumerate(archive, start=1): + if member_count > _MAX_MEMBER_COUNT: + raise ValueError("bundle contains too many members") + if member.name in files: + raise ValueError("bundle contains duplicate members") + if ( + member.name not in allowed + or not member.isfile() + or member.issym() + or member.islnk() + or member.size > _MAX_MEMBER_SIZE + ): + raise ValueError("bundle contains an unsupported or unsafe member") + source = archive.extractfile(member) + if source is None: + raise ValueError("bundle member has no content") + payload = source.read() + if len(payload) > _MAX_MEMBER_SIZE: + raise ValueError(f"bundle member exceeds {_MAX_MEMBER_SIZE} bytes") + files[member.name] = payload + except (tarfile.TarError, OSError) as exc: + raise ValueError(f"cannot read cloud bundle: {exc}") from exc + required = {_STATE_NAME, _BOOTSTRAP_NAME} + if not required <= files.keys(): + raise ValueError("bundle is missing required members") + return files + + +def _decode_state(payload: bytes) -> CloudState: + try: + value = json.loads(payload.decode("utf-8"), parse_constant=_reject_nonstandard_json) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError("cloud checkpoint is corrupted") from exc + if not isinstance(value, dict): + raise ValueError("cloud checkpoint is corrupted") + try: + return CloudState.from_dict(value) + except (TypeError, ValueError) as exc: + raise ValueError("cloud checkpoint is corrupted") from exc + + +def _decode_manifest(payload: bytes | None) -> dict[str, object]: + if payload is None: + # Bundles from the first prototype had no manifest. They remain + # importable, but cannot carry a patch and receive no checksum claim. + return {} + try: + value = json.loads(payload.decode("utf-8"), parse_constant=_reject_nonstandard_json) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError("cloud bundle manifest is corrupted") from exc + if not isinstance(value, dict) or value.get("format") != 2: + raise ValueError("unsupported cloud bundle manifest") + return value + + +def _verify_manifest(manifest: dict[str, object], files: dict[str, bytes]) -> None: + if not manifest: + if _PATCH_NAME in files: + raise ValueError("cloud patch requires a checksum manifest") + return + entries = manifest.get("files") + if not isinstance(entries, dict): + raise ValueError("cloud bundle manifest is corrupted") + expected = set(entries) + actual = set(files) - {_MANIFEST_NAME} + if expected != actual: + raise ValueError("cloud bundle manifest does not match its members") + for name, entry in entries.items(): + if not isinstance(name, str) or not isinstance(entry, dict): + raise ValueError("cloud bundle manifest is corrupted") + checksum = entry.get("sha256") + size = entry.get("size") + if checksum != _checksum(files[name]) or size != len(files[name]): + raise ValueError(f"cloud bundle checksum mismatch: {name}") + + +def _git_head(workspace: Path) -> str | None: + try: + result = subprocess.run( + ["git", "rev-parse", "--verify", "HEAD"], + cwd=workspace, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + text=True, + check=False, + ) + except OSError: + return None + return result.stdout.strip() if result.returncode == 0 else None + + +def _check_patch_base(workspace: Path, state: CloudState) -> None: + current = _git_head(workspace) + if current != state.git_base_revision: + raise ValueError( + "cloud patch conflict: local HEAD moved since the cloud run " + f"(expected {state.git_base_revision}, found {current or 'none'})" + ) + + +def _check_patch(workspace: Path, patch: bytes) -> None: + _check_patch_direction(workspace, patch, reverse=False) + + +def _check_patch_applied(workspace: Path, patch: bytes) -> bool: + """Return whether a previously interrupted import already applied patch.""" + try: + _check_patch_direction(workspace, patch, reverse=True) + except ValueError: + return False + return True + + +def _check_patch_direction(workspace: Path, patch: bytes, *, reverse: bool) -> None: + _validate_patch_payload(patch) + command = ["git", "apply", "--check", "--whitespace=nowarn"] + if reverse: + command.append("--reverse") + command.append("-") + try: + result = subprocess.run( + command, + cwd=workspace, + input=patch, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot validate cloud execution patch: {exc}") from exc + if result.returncode != 0: + detail = result.stderr.decode("utf-8", errors="replace").strip() + raise ValueError(f"cloud patch conflict: {detail or 'git apply --check failed'}") + + +def _validate_patch_payload(patch: bytes) -> None: + """Reject patch operations that can escape the workspace trust boundary.""" + for line in _patch_header_lines(patch): + if line.startswith((b"old mode ", b"new mode ", b"new file mode ")): + if line.rstrip().endswith(b"120000"): + raise ValueError("cloud patch cannot create or modify symbolic links") + continue + metadata = _patch_path_metadata(line) + if metadata is None: + continue + for token in _patch_path_tokens(metadata): + path = _decode_patch_path(token) + if path.startswith(("a/", "b/")): + path = path[2:] + if path in {"/dev/null", "nul", "NUL"}: + continue + windows_path = PureWindowsPath(path) + if ( + Path(path).is_absolute() + or Path(path).drive + or windows_path.drive + or windows_path.root + or ".." in Path(path).parts + or ".." in windows_path.parts + or any(":" in part for part in windows_path.parts) + or any(PureWindowsPath(part).is_reserved() for part in windows_path.parts) + ): + raise ValueError("cloud patch contains an unsafe path") + if windows_path.parts and windows_path.parts[0].casefold() == ".ouroboros-cloud": + raise ValueError( + "cloud patch contains an unsafe path in the internal state directory" + ) + + +def _patch_paths(patch: bytes) -> list[str]: + """Return every workspace path that a validated patch may touch.""" + _validate_patch_payload(patch) + paths: list[str] = [] + for line in _patch_header_lines(patch): + metadata = _patch_path_metadata(line) + if metadata is None: + continue + for token in _patch_path_tokens(metadata): + path = _decode_patch_path(token) + if path.startswith(("a/", "b/")): + path = path[2:] + if path in {"/dev/null", "nul", "NUL"} or path in paths: + continue + paths.append(path) + return paths + + +def _patch_header_lines(patch: bytes) -> tuple[bytes, ...]: + """Return patch header lines outside unified-diff hunks. + + A hunk's added line has one leading ``+``. Consequently, a legitimate + source line beginning with ``++ `` is serialized as ``+++ `` and must not + be mistaken for a file header. Git's ``diff --git`` marker starts each + file section, so the hunk state can be reset without interpreting hunk + body text as metadata. + """ + header_prefixes = ( + b"diff --git ", + b"--- ", + b"+++ ", + b"rename from ", + b"rename to ", + b"copy from ", + b"copy to ", + b"old mode ", + b"new mode ", + b"new file mode ", + ) + in_hunk = False + lines: list[bytes] = [] + for line in patch.splitlines(): + if line.startswith(b"diff --git "): + in_hunk = False + elif line.startswith(b"@@"): + in_hunk = True + if not in_hunk and line.startswith(header_prefixes): + lines.append(line) + return tuple(lines) + + +def _patch_path_metadata(line: bytes) -> bytes | None: + """Return the path portion of a file-path header, if present.""" + for prefix in ( + b"diff --git ", + b"--- ", + b"+++ ", + b"rename from ", + b"rename to ", + b"copy from ", + b"copy to ", + ): + if line.startswith(prefix): + return line[len(prefix) :] + return None + + +def _write_import_journal(workspace: Path, target: Path, patch: bytes) -> None: + """Persist patch pre-images before a multi-file Git apply begins.""" + snapshots: list[dict[str, object]] = [] + created_directories: set[str] = set() + for relative in _patch_paths(patch): + relative_path = Path(relative) + if ( + relative_path.is_absolute() + or ".." in relative_path.parts + or relative_path.parts[:1] == (".ouroboros-cloud",) + ): + raise ValueError("cloud patch contains an unsafe path") + candidate = workspace / relative_path + if candidate.is_symlink(): + raise ValueError("cloud patch target must not be a symbolic link") + if not candidate.resolve(strict=False).is_relative_to(workspace): + raise ValueError("cloud patch target escapes the workspace") + if candidate.exists() and not candidate.is_file(): + raise ValueError("cloud patch target must be a regular file") + if candidate.exists(): + snapshots.append( + { + "path": relative, + "exists": True, + "mode": stat.S_IMODE(candidate.stat().st_mode), + "payload": base64.b64encode(candidate.read_bytes()).decode("ascii"), + } + ) + else: + snapshots.append({"path": relative, "exists": False}) + parent = candidate.parent + while parent != workspace and workspace in parent.parents: + if not parent.exists(): + created_directories.add(str(parent.relative_to(workspace))) + parent = parent.parent + journal = { + "format": 1, + "paths": snapshots, + "created_directories": sorted( + created_directories, key=lambda value: (value.count(os.sep), value), reverse=True + ), + } + _write_regular_file( + target / Path(_IMPORT_JOURNAL_NAME).name, + _json_bytes(journal), + mode=0o600, + ) + + +def _recover_import_journal(workspace: Path, target: Path) -> None: + """Restore a patch pre-image left by an importer that lost its process.""" + journal_path = target / Path(_IMPORT_JOURNAL_NAME).name + if not journal_path.exists() and not journal_path.is_symlink(): + return + if journal_path.is_symlink() or not journal_path.is_file(): + raise ValueError("cloud import recovery journal must be a regular file") + try: + journal = json.loads(journal_path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError("cloud import recovery journal is corrupted") from exc + if not isinstance(journal, dict) or journal.get("format") != 1: + raise ValueError("unsupported cloud import recovery journal") + paths = journal.get("paths") + directories = journal.get("created_directories", []) + if not isinstance(paths, list) or not isinstance(directories, list): + raise ValueError("cloud import recovery journal is corrupted") + for record in paths: + if not isinstance(record, dict): + raise ValueError("cloud import recovery journal is corrupted") + relative = record.get("path") + if not isinstance(relative, str): + raise ValueError("cloud import recovery journal is corrupted") + path = _recovery_path(workspace, relative) + if record.get("exists") is True: + payload = record.get("payload") + mode = record.get("mode") + if not isinstance(payload, str) or not isinstance(mode, int): + raise ValueError("cloud import recovery journal is corrupted") + try: + restored = base64.b64decode(payload, validate=True) + except (binascii.Error, ValueError) as exc: + raise ValueError("cloud import recovery journal is corrupted") from exc + _write_regular_file(path, restored, mode=mode) + elif record.get("exists") is False: + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.exists(): + raise ValueError("cloud import recovery target is not a regular file") + else: + raise ValueError("cloud import recovery journal is corrupted") + for relative in directories: + if not isinstance(relative, str): + raise ValueError("cloud import recovery journal is corrupted") + path = _recovery_path(workspace, relative) + if path.is_symlink(): + raise ValueError("cloud import recovery directory must not be a symbolic link") + try: + path.rmdir() + except FileNotFoundError: + pass + except OSError: + continue + journal_path.unlink() + _fsync_directory(journal_path.parent) + + +def _recovery_path(workspace: Path, relative: str) -> Path: + """Resolve a recovery path without following outside-workspace parents.""" + relative_path = Path(relative) + if ( + relative_path.is_absolute() + or ".." in relative_path.parts + or relative_path.parts[:1] == (".ouroboros-cloud",) + ): + raise ValueError("cloud import recovery journal contains an unsafe path") + path = workspace / relative_path + try: + inside_workspace = path.resolve(strict=False).is_relative_to(workspace) + except (OSError, RuntimeError) as exc: + raise ValueError("cloud import recovery journal contains an unsafe path") from exc + if not inside_workspace: + raise ValueError("cloud import recovery journal contains an unsafe path") + return path + + +def _patch_path_tokens(metadata: bytes) -> tuple[bytes, ...]: + """Split Git path metadata while retaining quoted path escapes.""" + tokens: list[bytes] = [] + index = 0 + while index < len(metadata): + while index < len(metadata) and metadata[index] in b" \t": + index += 1 + if index >= len(metadata): + break + start = index + if metadata[index] == ord('"'): + index += 1 + escaped = False + while index < len(metadata): + char = metadata[index] + index += 1 + if escaped: + escaped = False + elif char == ord("\\"): + escaped = True + elif char == ord('"'): + break + else: + while index < len(metadata) and metadata[index] not in b" \t": + index += 1 + tokens.append(metadata[start:index]) + return tuple(tokens) + + +def _decode_patch_path(token: bytes) -> str: + if not token.startswith(b'"'): + return os.fsdecode(token) + if len(token) < 2 or token[-1] != ord('"'): + return os.fsdecode(token) + decoded = bytearray() + index = 1 + end = len(token) - 1 + escapes = { + ord("a"): b"\a", + ord("b"): b"\b", + ord("f"): b"\f", + ord("n"): b"\n", + ord("r"): b"\r", + ord("t"): b"\t", + ord("v"): b"\v", + ord("\\"): b"\\", + ord('"'): b'"', + } + while index < end: + char = token[index] + index += 1 + if char != ord("\\"): + decoded.append(char) + continue + if index >= end: + return os.fsdecode(token) + escaped = token[index] + index += 1 + if escaped in escapes: + decoded.extend(escapes[escaped]) + continue + if ord("0") <= escaped <= ord("7"): + octal = bytearray((escaped,)) + while len(octal) < 3 and index < end and ord("0") <= token[index] <= ord("7"): + octal.append(token[index]) + index += 1 + decoded.append(int(octal, 8)) + continue + return os.fsdecode(token) + return os.fsdecode(bytes(decoded)) + + +def _apply_patch(workspace: Path, patch: bytes) -> None: + try: + result = subprocess.run( + ["git", "apply", "--whitespace=nowarn", "-"], + cwd=workspace, + input=patch, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot apply cloud execution patch: {exc}") from exc + if result.returncode != 0: + detail = result.stderr.decode("utf-8", errors="replace").strip() + raise ValueError(f"cloud patch conflict: {detail or 'git apply failed'}") + + +def _reverse_patch(workspace: Path, patch: bytes) -> None: + try: + result = subprocess.run( + ["git", "apply", "--reverse", "--whitespace=nowarn", "-"], + cwd=workspace, + input=patch, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot roll back cloud execution patch: {exc}") from exc + if result.returncode != 0: + detail = result.stderr.decode("utf-8", errors="replace").strip() + raise ValueError(f"cannot roll back cloud execution patch: {detail or 'git apply failed'}") + + +def _write_regular_file(path: Path, payload: bytes, *, mode: int | None = None) -> None: + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError("bundle target must be a regular file") + if mode is None: + mode = 0o755 if path.name == _BOOTSTRAP_NAME else 0o600 + fd, temporary = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent) + try: + with open(fd, "wb", closefd=True) as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, mode & 0o777) + Path(temporary).replace(path) + _fsync_directory(path.parent) + finally: + Path(temporary).unlink(missing_ok=True) + + +def _existing_file(path: Path) -> tuple[bytes, int] | None: + if not path.exists(): + return None + return path.read_bytes(), stat.S_IMODE(path.stat().st_mode) + + +def _restore_file(path: Path, snapshot: tuple[bytes, int] | None) -> None: + if snapshot is None: + path.unlink(missing_ok=True) + else: + payload, mode = snapshot + _write_regular_file(path, payload, mode=mode) + + +def _remove_import_scaffold( + destination: Path, + target: Path, + *, + destination_existed: bool, + target_existed: bool, +) -> None: + """Remove only directories created by a failed import when they are empty.""" + if target_existed: + return + try: + (target / "state.json.lock").unlink(missing_ok=True) + target.rmdir() + except OSError: + return + if not destination_existed: + try: + destination.rmdir() + except OSError: + pass + + +def _validate_import_targets(destination: Path) -> None: + """Reject unsafe targets before any state or patch mutation occurs.""" + target = destination / ".ouroboros-cloud" + if target.exists() and (target.is_symlink() or not target.is_dir()): + raise ValueError("bundle cloud state directory must be a regular directory") + for path in (target / "state.json", destination / "bootstrap.sh"): + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError("bundle target must be a regular file") + + +def _force_noninteractive_git(child_env: dict[str, str]) -> None: + child_env["GIT_TERMINAL_PROMPT"] = "0" + + +def _fsync_directory(directory: Path) -> None: + if os.name != "posix": + return + directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + +__all__ = ["export_bundle", "import_bundle"] diff --git a/src/ouroboros/cloud/driver.py b/src/ouroboros/cloud/driver.py new file mode 100644 index 0000000000..c29685ecc6 --- /dev/null +++ b/src/ouroboros/cloud/driver.py @@ -0,0 +1,723 @@ +"""Deterministic host-shell execution over the portable cloud state.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +import json +import os +from pathlib import Path +import signal +import subprocess +import threading +from typing import Any + +from ouroboros.cloud.limits import ( + DEFAULT_LOCK_TIMEOUT_SECONDS, + DEFAULT_STEP_TIMEOUT_SECONDS, + MAX_COMMAND_BYTES, + MAX_EVIDENCE_NAME_BYTES, + MAX_EVIDENCE_RECORDS, + MAX_EVIDENCE_VALUE_BYTES, + MAX_OUTPUT_BYTES, + MAX_PLAN_STEPS, + MAX_RECEIPTS, +) +from ouroboros.cloud.state import CloudState, CloudStateStore +from ouroboros.runtime.child_env import build_child_env + +_MAX_VERIFICATION_RECEIPTS = MAX_RECEIPTS +_TIMEOUT_RETURN_CODE = 124 +_OUTPUT_LIMIT_RETURN_CODE = 125 +_CLOUD_ENV_ALLOWLIST = frozenset( + { + "CI", + "COLORTERM", + "COMSPEC", + "GIT_TERMINAL_PROMPT", + "LANG", + "LC_ALL", + "LC_CTYPE", + "NO_COLOR", + "PATH", + "PATHEXT", + "SystemRoot", + "TERM", + "TEMP", + "TMP", + "TMPDIR", + "TZ", + "WINDIR", + } +) + + +class CloudRecoveryRequired(RuntimeError): + """A host turn ended with a command whose outcome must be acknowledged.""" + + +class CloudApprovalRequired(RuntimeError): + """An imported plan must be explicitly approved before execution.""" + + +@dataclass(frozen=True, slots=True) +class StepResult: + index: int + command: str + returncode: int + stdout: str + stderr: str + + def to_dict(self) -> dict[str, object]: + return { + "index": self.index, + "command": self.command, + "returncode": self.returncode, + "stdout": self.stdout, + "stderr": self.stderr, + } + + +class CloudDriver: + """Stateful facade for init, planning, execution, evidence, and verify.""" + + def __init__( + self, + workspace: str | Path, + *, + step_timeout: float | None = DEFAULT_STEP_TIMEOUT_SECONDS, + lock_timeout: float | None = DEFAULT_LOCK_TIMEOUT_SECONDS, + ) -> None: + if step_timeout is not None and step_timeout <= 0: + raise ValueError("cloud step timeout must be positive or None") + self.store = CloudStateStore(workspace, lock_timeout=lock_timeout) + self.step_timeout = step_timeout + + @property + def state(self) -> CloudState: + with self.store.lock(): + return self.store.load() + + def init(self, seed: str = "") -> CloudState: + with self.store.lock(): + state = self.store.initialize() + self._record_git_baseline(state) + if seed: + state.seed = seed + self.store.save(state) + return state + + def plan(self, steps: list[str]) -> CloudState: + if len(steps) > MAX_PLAN_STEPS: + raise ValueError(f"cloud plan must contain at most {MAX_PLAN_STEPS} steps") + if not all(isinstance(step, str) and step.strip() for step in steps): + raise ValueError("cloud plan steps must be non-empty strings") + if any(len(step.encode("utf-8")) > MAX_COMMAND_BYTES for step in steps): + raise ValueError(f"cloud command exceeds the {MAX_COMMAND_BYTES}-byte resource ceiling") + with self.store.lock(): + state = self.store.initialize() + if state.in_flight is not None: + index = state.in_flight["index"] + raise CloudRecoveryRequired( + f"cloud step {index} has an unresolved execution; " + "inspect its external effects and call cloud recover before replanning" + ) + state.git_base_revision = None + state.git_branch = None + state.git_untracked_paths.clear() + self._record_git_baseline(state) + state.plan = list(steps) + state.next_step = 0 + state.checkpoints.clear() + state.evidence.clear() + state.in_flight = None + state.verification_receipts.clear() + state.execution_approved = True + self.store.save(state) + return state + + def approve(self) -> CloudState: + """Approve an imported plan for host execution.""" + with self.store.lock(): + state = self.store.load() + state.execution_approved = True + self.store.save(state) + return state + + def _record_git_baseline(self, state: CloudState) -> None: + """Remember the immutable revision to which a cloud patch belongs.""" + if state.git_base_revision is not None: + return + try: + revision = subprocess.run( + ["git", "rev-parse", "--verify", "HEAD"], + cwd=self.store.workspace, + capture_output=True, + text=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + if revision.returncode != 0: + return + branch = subprocess.run( + ["git", "branch", "--show-current"], + cwd=self.store.workspace, + capture_output=True, + text=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError: + return + state.git_base_revision = revision.stdout.strip() or None + state.git_branch = branch.stdout.strip() or None + state.git_untracked_paths = _git_untracked_paths(self.store.workspace) + + def next(self, *, env: Mapping[str, str] | None = None) -> StepResult | None: + with self.store.lock(): + state = self.store.load() + if not state.execution_approved: + raise CloudApprovalRequired( + "cloud plan came from an imported bundle; approve it before execution" + ) + if state.in_flight is not None: + index = state.in_flight["index"] + raise CloudRecoveryRequired( + f"cloud step {index} has an unresolved execution; " + "inspect its external effects and call cloud recover" + ) + checkpoint_errors = _checkpoint_errors(state) + if checkpoint_errors: + raise ValueError( + "cloud state has invalid completed checkpoints: " + + ", ".join(str(position) for position in checkpoint_errors) + ) + if state.next_step >= len(state.plan): + return None + index = state.next_step + command = state.plan[index] + state.in_flight = {"index": index, "command": command} + self.store.save(state) + try: + returncode, raw_stdout, raw_stderr, timed_out = _run_host_turn( + command, + cwd=self.store.workspace, + env=_cloud_child_env(self.store.workspace, env), + timeout=self.step_timeout, + ) + returncode, stdout, stderr = _normalize_step_result( + returncode, raw_stdout, raw_stderr + ) + if timed_out: + returncode = _TIMEOUT_RETURN_CODE + stderr = _append_failure( + stderr, + f"cloud step exceeded the {self.step_timeout:g}-second timeout", + ) + except subprocess.TimeoutExpired as exc: + stdout = _bounded_text(_timeout_output(exc.stdout)) + stderr = _bounded_text(_timeout_output(exc.stderr)) + returncode = _TIMEOUT_RETURN_CODE + stderr = _append_failure( + stderr, + f"cloud step exceeded the {self.step_timeout:g}-second timeout", + ) + state.next_step += 1 + state.checkpoints.append( + { + **StepResult(index, command, returncode, stdout, stderr).to_dict(), + "next_step": state.next_step, + } + ) + state.in_flight = None + self.store.save(state) + return StepResult(index, command, returncode, stdout, stderr) + + def recover( + self, + *, + returncode: int, + stdout: str = "", + stderr: str = "", + step: int | None = None, + ) -> StepResult: + """Acknowledge an interrupted step without executing it again. + + The caller supplies the observed result after inspecting the host. This + is deliberately explicit because a disconnected process cannot prove + whether its child finished before the disconnect. + """ + if isinstance(returncode, bool) or not isinstance(returncode, int): + raise ValueError("cloud recovery returncode must be an integer") + if not isinstance(stdout, str) or not isinstance(stderr, str): + raise ValueError("cloud recovery output must be strings") + if step is not None and (isinstance(step, bool) or not isinstance(step, int) or step < 0): + raise ValueError("cloud recovery step must be a non-negative integer") + returncode, stdout, stderr = _normalize_step_result(returncode, stdout, stderr) + with self.store.lock(): + state = self.store.load() + if state.in_flight is None: + if state.checkpoints and step is None: + raise ValueError( + "cloud state has no interrupted step; recovery step identity is " + "required after an earlier checkpoint" + ) + matches = [ + checkpoint + for checkpoint in state.checkpoints + if step is None or checkpoint.get("index") == step + if _checkpoint_matches_recovery( + checkpoint, + returncode=returncode, + stdout=stdout, + stderr=stderr, + ) + ] + if len(matches) > 1: + raise ValueError( + "cloud recovery replay is ambiguous; provide the step identity" + ) + if matches: + checkpoint = matches[0] + return StepResult( + checkpoint["index"], + checkpoint["command"], + checkpoint["returncode"], + checkpoint["stdout"], + checkpoint["stderr"], + ) + raise ValueError("cloud state has no interrupted step to recover") + index = state.in_flight["index"] + command = state.in_flight["command"] + if step is not None and step != index: + raise ValueError(f"cloud recovery step does not match active step {index}") + if step is None and state.checkpoints: + raise ValueError( + "cloud state has no interrupted step; recovery step identity is " + "required after an earlier checkpoint" + ) + if len(state.checkpoints) != index: + raise ValueError( + "cloud state has invalid completed checkpoints: " + f"expected {index}, found {len(state.checkpoints)}" + ) + checkpoint_errors = [ + position for position in _checkpoint_errors(state) if position != index + ] + if checkpoint_errors: + raise ValueError( + "cloud state has invalid completed checkpoints: " + + ", ".join(str(position) for position in checkpoint_errors) + ) + result = StepResult(index, command, returncode, stdout, stderr) + state.next_step = index + 1 + state.checkpoints.append( + {**result.to_dict(), "next_step": state.next_step, "recovered": True} + ) + state.in_flight = None + self.store.save(state) + return result + + def record_evidence(self, name: str, value: Any, step: int | None = None) -> CloudState: + if not isinstance(name, str) or not name.strip(): + raise ValueError("cloud evidence name must not be empty") + if len(name.encode("utf-8")) > MAX_EVIDENCE_NAME_BYTES: + raise ValueError( + f"cloud evidence name exceeds the {MAX_EVIDENCE_NAME_BYTES}-byte resource ceiling" + ) + if step is not None and (isinstance(step, bool) or not isinstance(step, int) or step < 0): + raise ValueError("cloud evidence step must be a non-negative integer") + try: + json_value = _json_value(value) + except (TypeError, ValueError) as exc: + raise ValueError("cloud evidence must be JSON serializable") from exc + with self.store.lock(): + state = self.store.load() + if len(state.evidence) >= MAX_EVIDENCE_RECORDS: + raise ValueError( + f"cloud evidence must contain at most {MAX_EVIDENCE_RECORDS} records" + ) + if ( + len(json.dumps(json_value, ensure_ascii=False).encode("utf-8")) + > MAX_EVIDENCE_VALUE_BYTES + ): + raise ValueError( + f"cloud evidence value exceeds the {MAX_EVIDENCE_VALUE_BYTES}-byte resource ceiling" + ) + if step is not None and step >= len(state.plan): + raise ValueError("cloud evidence step is outside the planned steps") + if step is not None and step >= state.next_step: + raise ValueError("cloud evidence step has not completed") + evidence_step = step + if evidence_step is None and state.next_step > 0: + evidence_step = state.next_step - 1 + record: dict[str, Any] = {"name": name, "value": json_value} + if evidence_step is not None: + record["step"] = evidence_step + state.evidence.append(record) + self.store.save(state) + return state + + def verify(self) -> bool: + with self.store.lock(): + state = self.store.load() + checkpoints_complete = len(state.checkpoints) == len(state.plan) + steps_succeeded = all( + checkpoint.get("returncode") == 0 for checkpoint in state.checkpoints + ) + checkpoint_errors = _checkpoint_errors(state) + required_steps = set(range(len(state.plan))) + evidence_steps = { + item.get("step") + for item in state.evidence + if isinstance(item.get("step"), int) and _has_evidence(item.get("value")) + } + evidence_complete = evidence_steps >= required_steps + complete = ( + bool(state.plan) + and bool(state.checkpoints) + and bool(evidence_steps) + and state.next_step == len(state.plan) + and state.in_flight is None + and checkpoints_complete + and steps_succeeded + and not checkpoint_errors + and evidence_complete + ) + receipt = { + "complete": complete, + "next_step": state.next_step, + "planned_steps": len(state.plan), + "checkpoint_count": len(state.checkpoints), + "evidence_count": len(state.evidence), + "failed_steps": [ + checkpoint.get("index") + for checkpoint in state.checkpoints + if checkpoint.get("returncode") != 0 + ], + "invalid_checkpoints": checkpoint_errors, + "missing_evidence_steps": sorted(required_steps - evidence_steps), + "recovery_required": state.in_flight is not None, + } + state.verification_receipts.append(receipt) + del state.verification_receipts[:-_MAX_VERIFICATION_RECEIPTS] + self.store.save(state) + return complete + + +def _json_value(value: Any) -> Any: + """Return a JSON-safe copy without importing a project serializer.""" + import json + + encoded = json.dumps(value, allow_nan=False) + return json.loads(encoded) + + +def _force_noninteractive_git(child_env: dict[str, str]) -> None: + """Keep cloud host turns from prompting for unavailable Git credentials.""" + child_env["GIT_TERMINAL_PROMPT"] = "0" + + +def _cloud_child_env(workspace: Path, overrides: Mapping[str, str] | None) -> dict[str, str]: + """Build a workspace-local environment for untrusted planned commands.""" + child_env = {key: value for key, value in os.environ.items() if key in _CLOUD_ENV_ALLOWLIST} + if overrides: + child_env.update( + {key: value for key, value in overrides.items() if key in _CLOUD_ENV_ALLOWLIST} + ) + state_root = workspace / ".ouroboros-cloud" + local_dirs = tuple( + state_root / name for name in ("home", "cache", "config", "data", "state", "tmp") + ) + for directory in local_dirs: + directory.mkdir(exist_ok=True) + if directory.is_symlink() or not directory.is_dir(): + raise RuntimeError(f"cloud child directory must be a regular directory: {directory}") + child_env.update( + { + "HOME": str(state_root / "home"), + "XDG_CACHE_HOME": str(state_root / "cache"), + "XDG_CONFIG_HOME": str(state_root / "config"), + "XDG_DATA_HOME": str(state_root / "data"), + "XDG_STATE_HOME": str(state_root / "state"), + "TMPDIR": str(state_root / "tmp"), + "TEMP": str(state_root / "tmp"), + "TMP": str(state_root / "tmp"), + } + ) + return build_child_env( + base_env=child_env, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ) + + +def _has_evidence(value: object) -> bool: + """Return whether a recorded value contains an observable result.""" + if isinstance(value, str): + return bool(value.strip()) + return value is not None and value != [] and value != {} + + +def _bounded_text(value: str | bytes | None) -> str: + if value is None: + return "" + if isinstance(value, bytes): + value = value.decode("utf-8", errors="replace") + encoded = value.encode("utf-8") + if len(encoded) <= MAX_OUTPUT_BYTES: + return value + return encoded[:MAX_OUTPUT_BYTES].decode("utf-8", errors="ignore") + + +def _timeout_output(value: str | bytes | None) -> str: + return _bounded_text(value) + + +def _append_failure(stderr: str, message: str) -> str: + suffix = f"{message}\n" + available = max(0, MAX_OUTPUT_BYTES - len(suffix.encode("utf-8"))) + prefix = stderr.encode("utf-8")[:available].decode("utf-8", errors="ignore") + return prefix + suffix + + +def _normalize_step_result( + returncode: int, stdout: str | bytes | None, stderr: str | bytes | None +) -> tuple[int, str, str]: + """Apply the same bounded-output contract to execution and recovery paths.""" + bounded_stdout = _bounded_text(stdout) + bounded_stderr = _bounded_text(stderr) + if _output_exceeds_limit(stdout) or _output_exceeds_limit(stderr): + bounded_stderr = _append_failure( + bounded_stderr, + f"cloud step output exceeded the {MAX_OUTPUT_BYTES}-byte resource ceiling", + ) + return _OUTPUT_LIMIT_RETURN_CODE, bounded_stdout, bounded_stderr + return returncode, bounded_stdout, bounded_stderr + + +def _output_exceeds_limit(value: str | bytes | None) -> bool: + """Detect truncation without confusing equivalent bytes and text values.""" + if value is None: + return False + if isinstance(value, bytes): + return len(value) > MAX_OUTPUT_BYTES + return len(value.encode("utf-8")) > MAX_OUTPUT_BYTES + + +def _checkpoint_matches_recovery( + checkpoint: dict[str, Any], *, returncode: int, stdout: str, stderr: str +) -> bool: + """Recognize a retry after recovery was durably committed.""" + return ( + checkpoint.get("recovered") is True + and checkpoint.get("returncode") == returncode + and checkpoint.get("stdout") == stdout + and checkpoint.get("stderr") == stderr + ) + + +def _run_host_turn( + command: str, + *, + cwd: Path, + env: Mapping[str, str], + timeout: float | None, +) -> tuple[int, bytes, bytes, bool]: + """Run one host turn with bounded capture and descendant cleanup. + + ``subprocess.run(capture_output=True)`` buffers an untrusted command's + complete output before the cloud limit can truncate it. Dedicated reader + threads retain only one output limit plus one sentinel byte while draining + the pipes, so a noisy command cannot deadlock the child or grow memory + without bound. A new POSIX session lets a timeout terminate descendants + before the checkpoint is committed. + """ + command_argv = _host_turn_argv(command, env) + if os.name == "nt": # pragma: no cover - exercised by the Windows CI job + process = subprocess.Popen( + command_argv, + cwd=cwd, + env=build_child_env( + base_env=env, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=False, + creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), + ) + else: + process = subprocess.Popen( + command_argv, + cwd=cwd, + env=build_child_env( + base_env=env, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=False, + start_new_session=True, + ) + assert process.stdout is not None + assert process.stderr is not None + output: list[bytes] = [b"", b""] + stdout_reader = threading.Thread( + target=_read_bounded_pipe, args=(process.stdout, output, 0), daemon=True + ) + stderr_reader = threading.Thread( + target=_read_bounded_pipe, args=(process.stderr, output, 1), daemon=True + ) + stdout_reader.start() + stderr_reader.start() + timed_out = False + try: + process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + _terminate_host_turn(process) + process.wait() + readers = (stdout_reader, stderr_reader) + if any(reader.is_alive() for reader in readers): + # A detached descendant can retain the inherited pipe after the shell + # exits. Kill the process group before waiting so a host turn cannot + # outlive the command's own deadline while draining its output. + _terminate_host_turn(process) + # A detached descendant can keep a pipe open after the process group has + # exited. Keep the normal drain window short so cleanup cannot outlive a + # host turn just because that descendant ignores the group termination. + for reader in readers: + reader.join(timeout=0.05) + if any(reader.is_alive() for reader in readers): + for stream in (process.stdout, process.stderr): + if stream is not None: + stream.close() + for reader in readers: + reader.join(timeout=0.05) + return process.returncode, output[0], output[1], timed_out + + +def _host_turn_argv(command: str, env: Mapping[str, str]) -> list[str]: + """Select a native shell while keeping command execution deterministic.""" + if os.name == "nt": + return [env.get("COMSPEC") or "cmd.exe", "/d", "/s", "/c", command] + return ["/bin/sh", "-c", command] + + +def _read_bounded_pipe(stream: Any, output: list[bytes], index: int) -> None: + chunks = bytearray() + try: + while True: + chunk = stream.read(8192) + if not chunk: + break + if len(chunks) <= MAX_OUTPUT_BYTES: + chunks.extend(chunk[: MAX_OUTPUT_BYTES + 1 - len(chunks)]) + except (OSError, ValueError): + pass + output[index] = bytes(chunks) + + +def _terminate_host_turn(process: subprocess.Popen[bytes]) -> None: + try: + if os.name == "nt": # pragma: no cover - exercised by the Windows CI job + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(process.pid)], + capture_output=True, + env=build_child_env( + base_env={ + key: value + for key, value in os.environ.items() + if key in _CLOUD_ENV_ALLOWLIST + }, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + else: + os.killpg(process.pid, signal.SIGKILL) + except (OSError, ProcessLookupError): + try: + process.kill() + except ProcessLookupError: + pass + + +def _git_untracked_paths(workspace: Path) -> list[str]: + try: + result = subprocess.run( + [ + "git", + "ls-files", + "--others", + "--exclude-standard", + "-z", + "--", + ".", + ":(exclude).ouroboros-cloud", + ":(exclude).ouroboros-cloud/**", + ], + cwd=workspace, + capture_output=True, + env=build_child_env( + base_env=os.environ, + max_depth=1_000_000, + depth_error_factory=RuntimeError, + post_build=_force_noninteractive_git, + ), + check=False, + ) + except OSError as exc: + raise ValueError(f"cannot record cloud untracked baseline: {exc}") from exc + if result.returncode != 0: + raise ValueError("cannot record cloud untracked baseline") + paths: list[str] = [] + for raw_path in result.stdout.split(b"\0"): + if not raw_path: + continue + try: + paths.append(raw_path.decode("utf-8")) + except UnicodeDecodeError as exc: + raise ValueError("cloud untracked paths must be UTF-8") from exc + return paths + + +def _checkpoint_errors(state: CloudState) -> list[int]: + """Reject forged, duplicated, skipped, or plan-mismatched checkpoints.""" + errors: list[int] = [] + if state.in_flight is not None: + errors.append(state.in_flight["index"]) + if state.next_step != len(state.checkpoints): + errors.append(min(state.next_step, len(state.checkpoints))) + for position, checkpoint in enumerate(state.checkpoints): + index = checkpoint.get("index") + command = checkpoint.get("command") + if ( + index != position + or isinstance(index, bool) + or not isinstance(index, int) + or index < 0 + or index >= len(state.plan) + or command != state.plan[index] + or checkpoint.get("next_step") != position + 1 + ): + errors.append(position) + return sorted(set(errors)) diff --git a/src/ouroboros/cloud/environment.py b/src/ouroboros/cloud/environment.py new file mode 100644 index 0000000000..452c71a274 --- /dev/null +++ b/src/ouroboros/cloud/environment.py @@ -0,0 +1,156 @@ +"""Side-effect-light detection of the capabilities of a cloud host.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import asdict, dataclass +import os +from pathlib import Path +import tempfile + + +def _truthy(value: str | None) -> bool: + return value is not None and value.strip().lower() in {"1", "true", "yes", "on"} + + +def _writable(path: Path) -> bool: + # Detection must not create files in HOME/XDG. Those locations are only + # advisory; portable state is created separately under the workspace. + try: + if path.exists(): + return path.is_dir() and os.access(path, os.W_OK | os.X_OK) + if path.parent == path: + return False + return _writable(path.parent) + except OSError: + return False + + +def _ephemeral(path: Path | None) -> bool: + """Return whether a path is in the host's temporary scratch area.""" + if path is None: + return True + try: + temporary = Path(tempfile.gettempdir()).resolve() + resolved = path.resolve() + return resolved == temporary or resolved.is_relative_to(temporary) + except OSError: + return True + + +@dataclass(frozen=True, slots=True) +class CloudEnvironment: + """Observed runtime constraints, suitable for JSON diagnostics.""" + + workspace: Path + is_cloud: bool + workspace_mount: bool + home_restricted: bool + xdg_restricted: bool + home_ephemeral: bool + xdg_ephemeral: bool + git_noninteractive: bool + daemon_limited: bool + socket_limited: bool + state_root: Path + reasons: tuple[str, ...] = () + + @property + def zero_daemon(self) -> bool: + return self.daemon_limited or self.socket_limited or self.is_cloud + + def to_dict(self) -> dict[str, object]: + result = asdict(self) + result["workspace"] = str(self.workspace) + result["state_root"] = str(self.state_root) + result["reasons"] = list(self.reasons) + result["zero_daemon"] = self.zero_daemon + return result + + +def detect_environment( + workspace: str | Path | None = None, + environ: Mapping[str, str] | None = None, +) -> CloudEnvironment: + """Detect cloud and restricted-host facts without starting a daemon. + + ``workspace`` is preferred, then ``OUROBOROS_WORKSPACE``, and finally the + current directory. A cloud mount is detected from that selected path, + while each project keeps its state in its own workspace directory. All + writes are limited to the eventual workspace state directory. + """ + env = os.environ if environ is None else environ + requested = workspace or env.get("OUROBOROS_WORKSPACE") + if requested: + root = Path(requested).expanduser() + else: + root = Path.cwd() + root = root.resolve() + home_value = env.get("HOME") + home = Path(home_value).expanduser() if home_value else None + xdg_values = ( + env.get("XDG_CONFIG_HOME"), + env.get("XDG_DATA_HOME"), + ) + xdg_paths = tuple(Path(value).expanduser() if value else None for value in xdg_values) + xdg_defaults = (home / ".config" if home else None, home / ".local/share" if home else None) + xdg_paths = tuple( + path if path is not None else default + for path, default in zip(xdg_paths, xdg_defaults, strict=True) + ) + home_ephemeral = _ephemeral(home) + xdg_ephemeral = any(_ephemeral(path) for path in xdg_paths) + home_restricted = home is None or home_ephemeral or not _writable(home) + xdg_restricted = any(path is None or not _writable(path) for path in xdg_paths) or xdg_ephemeral + cloud = ( + _truthy(env.get("CODEX_CLOUD")) + or _truthy(env.get("CHATGPT_WORK")) + or _truthy(env.get("DOT_MANAGED_CLOUD")) + or root == Path("/workspace") + or root.is_relative_to(Path("/workspace")) + ) + git_noninteractive = env.get("GIT_TERMINAL_PROMPT") == "0" + runtime_dir = Path(env.get("XDG_RUNTIME_DIR", "/tmp")).expanduser() + socket_limited = ( + _truthy(env.get("OUROBOROS_NO_SOCKETS")) + or _truthy(env.get("OUROBOROS_SOCKET_LIMITED")) + or runtime_dir is None + or not _writable(runtime_dir) + ) + daemon_limited = ( + cloud + or _truthy(env.get("OUROBOROS_NO_DAEMON")) + or _truthy(env.get("OUROBOROS_DAEMON_LIMITED")) + or socket_limited + ) + reasons: list[str] = [] + if cloud: + reasons.append("cloud workspace or CODEX_CLOUD") + if home_restricted: + reasons.append("HOME unavailable or unwritable") + if home_ephemeral: + reasons.append("HOME is ephemeral") + if xdg_restricted: + reasons.append("XDG directory unavailable or unwritable") + if xdg_ephemeral: + reasons.append("XDG directory is ephemeral") + if git_noninteractive: + reasons.append("GIT_TERMINAL_PROMPT=0") + if daemon_limited: + reasons.append("background daemons disabled") + if socket_limited: + reasons.append("runtime sockets unavailable") + return CloudEnvironment( + workspace=root, + is_cloud=cloud, + workspace_mount=root == Path("/workspace") or root.is_relative_to(Path("/workspace")), + home_restricted=home_restricted, + xdg_restricted=xdg_restricted, + home_ephemeral=home_ephemeral, + xdg_ephemeral=xdg_ephemeral, + git_noninteractive=git_noninteractive, + daemon_limited=daemon_limited, + socket_limited=socket_limited, + state_root=root / ".ouroboros-cloud", + reasons=tuple(reasons), + ) diff --git a/src/ouroboros/cloud/limits.py b/src/ouroboros/cloud/limits.py new file mode 100644 index 0000000000..d6e124bca4 --- /dev/null +++ b/src/ouroboros/cloud/limits.py @@ -0,0 +1,20 @@ +"""Resource ceilings for the portable cloud runtime.""" + +from __future__ import annotations + +# These limits keep a hostile or accidental host turn from turning the +# workspace-local JSON checkpoint into an unbounded queue or memory sink. +MAX_PLAN_STEPS = 256 +MAX_COMMAND_BYTES = 16 * 1024 +MAX_SEED_BYTES = 64 * 1024 +MAX_EVIDENCE_RECORDS = 1_024 +MAX_EVIDENCE_NAME_BYTES = 256 +MAX_EVIDENCE_VALUE_BYTES = 128 * 1024 +MAX_CHECKPOINTS = 256 +MAX_OUTPUT_BYTES = 64 * 1024 +MAX_RECEIPTS = 64 +MAX_STATE_BYTES = 2 * 1024 * 1024 + +DEFAULT_STEP_TIMEOUT_SECONDS = 300.0 +DEFAULT_LOCK_TIMEOUT_SECONDS = 30.0 +LOCK_POLL_INTERVAL_SECONDS = 0.01 diff --git a/src/ouroboros/cloud/state.py b/src/ouroboros/cloud/state.py new file mode 100644 index 0000000000..47e80fc8e6 --- /dev/null +++ b/src/ouroboros/cloud/state.py @@ -0,0 +1,400 @@ +"""Atomic workspace-local state for the portable cloud runtime. + +The state file is deliberately boring JSON. A ChatGPT Work or Codex Cloud +turn can inspect it, edit neither credentials nor a daemon database, and pass +the directory to the next turn or to another machine. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import asdict, dataclass, field +import errno +import json +import os +from pathlib import Path +import re +import sys +import tempfile +import time +from typing import Any, NoReturn + +from ouroboros.cloud.limits import ( + DEFAULT_LOCK_TIMEOUT_SECONDS, + LOCK_POLL_INTERVAL_SECONDS, + MAX_CHECKPOINTS, + MAX_COMMAND_BYTES, + MAX_EVIDENCE_NAME_BYTES, + MAX_EVIDENCE_RECORDS, + MAX_EVIDENCE_VALUE_BYTES, + MAX_OUTPUT_BYTES, + MAX_PLAN_STEPS, + MAX_RECEIPTS, + MAX_SEED_BYTES, + MAX_STATE_BYTES, +) +from ouroboros.core.file_lock import file_lock + +_SUPPORTED_VERSION = 1 +_GIT_REVISION_RE = re.compile(r"[0-9a-fA-F]{40}|[0-9a-fA-F]{64}") + + +class CloudStateLockTimeout(TimeoutError): + """A host turn exceeded the bounded wait for the workspace state lock.""" + + +def _validate_records(value: object, name: str) -> list[dict[str, Any]]: + if not isinstance(value, list) or not all(isinstance(item, dict) for item in value): + raise ValueError(f"cloud {name} must be a list of objects") + return [dict(item) for item in value] + + +@dataclass(slots=True) +class CloudState: + version: int = 1 + seed: str = "" + git_base_revision: str | None = None + git_branch: str | None = None + git_untracked_paths: list[str] = field(default_factory=list) + plan: list[str] = field(default_factory=list) + next_step: int = 0 + evidence: list[dict[str, Any]] = field(default_factory=list) + checkpoints: list[dict[str, Any]] = field(default_factory=list) + # A durable intent written before a host command starts. It prevents a + # disconnect after the command's side effect from silently replaying it. + active_step: dict[str, Any] | None = None + execution_approved: bool = True + verification_receipts: list[dict[str, Any]] = field(default_factory=list) + + @property + def in_flight(self) -> dict[str, Any] | None: + """Compatibility view for state written before ``active_step``.""" + return self.active_step + + @in_flight.setter + def in_flight(self, value: dict[str, Any] | None) -> None: + self.active_step = value + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, value: dict[str, Any]) -> CloudState: + version = value.get("version", _SUPPORTED_VERSION) + if ( + version != _SUPPORTED_VERSION + or isinstance(version, bool) + or not isinstance(version, int) + ): + raise ValueError(f"unsupported cloud state version: {version!r}") + seed = value.get("seed", "") + if not isinstance(seed, str): + raise ValueError("cloud seed must be a string") + _check_text_size(seed, MAX_SEED_BYTES, "cloud seed") + plan = value.get("plan", []) + if not isinstance(plan, list) or len(plan) > MAX_PLAN_STEPS: + raise ValueError(f"cloud plan must contain at most {MAX_PLAN_STEPS} steps") + evidence = value.get("evidence", []) + if not isinstance(plan, list) or not all( + isinstance(item, str) and item.strip() for item in plan + ): + raise ValueError("cloud plan must be a list of non-empty strings") + for command in plan: + _check_text_size(command, MAX_COMMAND_BYTES, "cloud command") + if not isinstance(evidence, list) or not all(isinstance(item, dict) for item in evidence): + raise ValueError("cloud evidence must be a list of objects") + if len(evidence) > MAX_EVIDENCE_RECORDS: + raise ValueError(f"cloud evidence must contain at most {MAX_EVIDENCE_RECORDS} records") + for item in evidence: + name = item.get("name") + if not isinstance(name, str) or not name.strip(): + raise ValueError("cloud evidence names must be non-empty strings") + _check_text_size(name, MAX_EVIDENCE_NAME_BYTES, "cloud evidence name") + step = item.get("step") + if step is not None and ( + isinstance(step, bool) or not isinstance(step, int) or step < 0 + ): + raise ValueError("cloud evidence steps must be non-negative integers") + if step is not None and step >= len(plan): + raise ValueError("cloud evidence step is outside the planned steps") + _check_json_size(item.get("value"), MAX_EVIDENCE_VALUE_BYTES, "cloud evidence value") + next_step = value.get("next_step", 0) + if isinstance(next_step, bool) or not isinstance(next_step, int) or next_step < 0: + raise ValueError("cloud next_step must be a non-negative integer") + if next_step > len(plan): + raise ValueError("cloud next_step cannot exceed the plan length") + checkpoints = _validate_records(value.get("checkpoints", []), "checkpoints") + if len(checkpoints) > MAX_CHECKPOINTS: + raise ValueError(f"cloud checkpoints must contain at most {MAX_CHECKPOINTS} records") + for item in checkpoints: + returncode = item.get("returncode") + if isinstance(returncode, bool) or not isinstance(returncode, int): + raise ValueError("cloud checkpoint returncodes must be integers") + index = item.get("index") + if isinstance(index, bool) or not isinstance(index, int) or index < 0: + raise ValueError("cloud checkpoint indexes must be non-negative integers") + command = item.get("command") + if not isinstance(command, str): + raise ValueError("cloud checkpoint commands must be strings") + _check_text_size(command, MAX_COMMAND_BYTES, "cloud checkpoint command") + checkpoint_step = item.get("next_step") + if ( + isinstance(checkpoint_step, bool) + or not isinstance(checkpoint_step, int) + or checkpoint_step < 0 + ): + raise ValueError("cloud checkpoint next_step must be a non-negative integer") + if not isinstance(item.get("stdout"), str) or not isinstance(item.get("stderr"), str): + raise ValueError("cloud checkpoint output must be strings") + _check_text_size(item["stdout"], MAX_OUTPUT_BYTES, "cloud checkpoint stdout") + _check_text_size(item["stderr"], MAX_OUTPUT_BYTES, "cloud checkpoint stderr") + active_step = value.get("active_step") + legacy_in_flight = value.get("in_flight") + if active_step is None: + active_step = legacy_in_flight + elif legacy_in_flight is not None and active_step != legacy_in_flight: + raise ValueError("cloud active step and in-flight step disagree") + if active_step is not None: + if not isinstance(active_step, dict): + raise ValueError("cloud active step must be an object or null") + active_step_index = active_step.get("index") + if ( + isinstance(active_step_index, bool) + or not isinstance(active_step_index, int) + or active_step_index < 0 + or active_step_index >= len(plan) + ): + raise ValueError("cloud active step and in-flight step index is invalid") + if active_step_index != next_step: + raise ValueError("cloud active step and in-flight step must match next_step") + if active_step.get("command") != plan[active_step_index]: + raise ValueError("cloud active step and in-flight command do not match the plan") + execution_approved = value.get("execution_approved", True) + if not isinstance(execution_approved, bool): + raise ValueError("cloud execution approval must be a boolean") + receipts = _validate_records( + value.get("verification_receipts", []), "verification receipts" + ) + if len(receipts) > MAX_RECEIPTS: + raise ValueError(f"cloud verification receipts must contain at most {MAX_RECEIPTS}") + git_base_revision = _optional_string(value.get("git_base_revision"), "git base revision") + if git_base_revision is not None and not _GIT_REVISION_RE.fullmatch(git_base_revision): + raise ValueError("cloud git base revision must be a full object ID") + git_untracked_paths = value.get("git_untracked_paths", []) + if not isinstance(git_untracked_paths, list) or not all( + isinstance(path, str) and path for path in git_untracked_paths + ): + raise ValueError("cloud untracked paths must be a list of non-empty strings") + for path in git_untracked_paths: + _check_text_size(path, MAX_COMMAND_BYTES, "cloud untracked path") + return cls( + version=version, + seed=seed, + git_base_revision=git_base_revision, + git_branch=_optional_string(value.get("git_branch"), "git branch"), + git_untracked_paths=list(git_untracked_paths), + plan=plan, + next_step=next_step, + evidence=evidence, + checkpoints=checkpoints, + active_step=dict(active_step) if active_step is not None else None, + execution_approved=execution_approved, + verification_receipts=receipts, + ) + + +def _optional_string(value: object, name: str) -> str | None: + if value is None: + return None + if not isinstance(value, str): + raise ValueError(f"cloud {name} must be a string or null") + return value + + +class CloudStateStore: + """Persist a cloud run beneath ``/.ouroboros-cloud``.""" + + filename = "state.json" + + def __init__( + self, + workspace: str | Path, + *, + lock_timeout: float | None = DEFAULT_LOCK_TIMEOUT_SECONDS, + ) -> None: + self.workspace = Path(workspace).expanduser().resolve() + self.root = self.workspace / ".ouroboros-cloud" + self.path = self.root / self.filename + if lock_timeout is not None and lock_timeout < 0: + raise ValueError("cloud lock timeout must be non-negative or None") + self.lock_timeout = lock_timeout + + def _ensure_root(self) -> None: + if self.workspace.exists() and not self.workspace.is_dir(): + raise ValueError(f"cloud workspace is not a directory: {self.workspace}") + self.workspace.mkdir(parents=True, exist_ok=True) + if self.root.is_symlink(): + raise ValueError("cloud state directory must not be a symlink") + self.root.mkdir(parents=True, exist_ok=True) + if not self.root.is_dir(): + raise ValueError(f"cloud state path is not a directory: {self.root}") + if self.path.is_symlink(): + raise ValueError("cloud state file must be a regular file") + if self.path.exists() and not self.path.is_file(): + raise ValueError("cloud state file must be a regular file") + + @contextmanager + def lock(self) -> Iterator[None]: + """Serialize cloud state transactions across host-turn processes.""" + self._ensure_root() + deadline = None if self.lock_timeout is None else time.monotonic() + self.lock_timeout + while True: + lock = file_lock(self.path, blocking=False, stable_parent_authority=True) + try: + lock.__enter__() + except OSError as exc: + if exc.errno not in { + errno.EAGAIN, + errno.EACCES, + errno.EDEADLK, + }: + raise + if deadline is not None and time.monotonic() >= deadline: + raise CloudStateLockTimeout( + f"cloud state lock was busy for {self.lock_timeout:.3f}s" + ) from exc + time.sleep(LOCK_POLL_INTERVAL_SECONDS) + continue + try: + yield + except BaseException: + lock.__exit__(*sys.exc_info()) + raise + else: + lock.__exit__(None, None, None) + return + + def initialize(self) -> CloudState: + self._ensure_root() + if self.path.exists(): + return self.load() + state = CloudState() + self.save(state) + return state + + def load(self) -> CloudState: + self._ensure_root() + try: + with self.path.open("rb") as stream: + payload = stream.read(MAX_STATE_BYTES + 1) + except FileNotFoundError: + return self.initialize() + if len(payload) > MAX_STATE_BYTES: + raise ValueError( + f"cloud state file exceeds the {MAX_STATE_BYTES}-byte resource ceiling" + ) + try: + value = json.loads(payload.decode("utf-8"), parse_constant=_reject_nonstandard_json) + except UnicodeDecodeError as exc: + raise ValueError("cloud state must be UTF-8 JSON") from exc + if not isinstance(value, dict): + raise ValueError("cloud state must be a JSON object") + return CloudState.from_dict(value) + + def save(self, state: CloudState) -> None: + payload = state.to_dict() + # Validate the complete public state shape before replacing a good + # checkpoint. Resource checks alone are insufficient for callers + # that construct or mutate a CloudState directly: without this pass, + # an invalid checkpoint would be written and fail only on the next + # load. + CloudState.from_dict(payload) + self._ensure_root() + try: + encoded = ( + json.dumps(payload, allow_nan=False, ensure_ascii=False, indent=2, sort_keys=True) + + "\n" + ).encode("utf-8") + except (TypeError, ValueError) as exc: + raise ValueError("cloud state contains values that are not JSON serializable") from exc + if len(encoded) > MAX_STATE_BYTES: + raise ValueError(f"cloud state exceeds the {MAX_STATE_BYTES}-byte resource ceiling") + _validate_resource_limits(state) + fd, temporary = tempfile.mkstemp(prefix="state.", suffix=".tmp", dir=self.root) + try: + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump( + payload, + stream, + allow_nan=False, + ensure_ascii=False, + indent=2, + sort_keys=True, + ) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.path) + if os.name == "posix": + directory_fd = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + finally: + try: + Path(temporary).unlink() + except FileNotFoundError: + pass + + +def _check_text_size(value: str, limit: int, name: str) -> None: + if len(value.encode("utf-8")) > limit: + raise ValueError(f"{name} exceeds the {limit}-byte resource ceiling") + + +def _reject_nonstandard_json(value: str) -> NoReturn: + raise ValueError(f"cloud state contains non-standard JSON number: {value}") + + +def _check_json_size(value: object, limit: int, name: str) -> None: + try: + encoded = json.dumps( + value, allow_nan=False, ensure_ascii=False, separators=(",", ":") + ).encode("utf-8") + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be JSON serializable") from exc + if len(encoded) > limit: + raise ValueError(f"{name} exceeds the {limit}-byte resource ceiling") + + +def _validate_resource_limits(state: CloudState) -> None: + """Check growth ceilings without rejecting intentionally forged test state.""" + _check_text_size(state.seed, MAX_SEED_BYTES, "cloud seed") + if len(state.plan) > MAX_PLAN_STEPS: + raise ValueError(f"cloud plan must contain at most {MAX_PLAN_STEPS} steps") + for command in state.plan: + if isinstance(command, str): + _check_text_size(command, MAX_COMMAND_BYTES, "cloud command") + if len(state.evidence) > MAX_EVIDENCE_RECORDS: + raise ValueError(f"cloud evidence must contain at most {MAX_EVIDENCE_RECORDS} records") + for item in state.evidence: + if isinstance(item, dict): + name = item.get("name") + if isinstance(name, str): + _check_text_size(name, MAX_EVIDENCE_NAME_BYTES, "cloud evidence name") + _check_json_size(item.get("value"), MAX_EVIDENCE_VALUE_BYTES, "cloud evidence value") + if len(state.checkpoints) > MAX_CHECKPOINTS: + raise ValueError(f"cloud checkpoints must contain at most {MAX_CHECKPOINTS} records") + for item in state.checkpoints: + if isinstance(item, dict): + command = item.get("command") + if isinstance(command, str): + _check_text_size(command, MAX_COMMAND_BYTES, "cloud checkpoint command") + for key in ("stdout", "stderr"): + value = item.get(key) + if isinstance(value, str): + _check_text_size(value, MAX_OUTPUT_BYTES, f"cloud checkpoint {key}") + if len(state.verification_receipts) > MAX_RECEIPTS: + raise ValueError(f"cloud verification receipts must contain at most {MAX_RECEIPTS}") diff --git a/src/ouroboros/mcp/job_manager.py b/src/ouroboros/mcp/job_manager.py index 35892e520e..5f9b070229 100644 --- a/src/ouroboros/mcp/job_manager.py +++ b/src/ouroboros/mcp/job_manager.py @@ -2480,6 +2480,9 @@ async def cancel_job(self, job_id: str) -> JobSnapshot: ): runner_task.cancel() cancelled_tasks.append(runner_task) + # The owning job task persists the terminal event after runner cancel. + if task is not None and not task.done() and task is not asyncio.current_task(): + cancelled_tasks.append(task) if cancelled_tasks: await asyncio.wait(cancelled_tasks, timeout=5) if ( diff --git a/src/ouroboros/mcp/tools/citation_check.py b/src/ouroboros/mcp/tools/citation_check.py index 2e646af3ad..5597c2f141 100644 --- a/src/ouroboros/mcp/tools/citation_check.py +++ b/src/ouroboros/mcp/tools/citation_check.py @@ -304,14 +304,16 @@ def _default_fetch(url: str, timeout: float) -> bool: with opener.open(request, timeout=remaining): # noqa: S310 return time.monotonic() <= deadline except urllib.error.HTTPError as error: - try: - if method == "HEAD" and error.code in (405, 501): - continue # server refuses HEAD; try the ranged GET once - # A 3xx HTTPError can indicate the redirect cap was exceeded; - # it is not evidence of a reachable final source. - return False - finally: - error.close() + retry_get = method == "HEAD" and error.code in (405, 501) + # Close the rejected response before opening the fallback. Some + # HTTP stacks keep the connection occupied until close() runs, + # which can make the ranged GET fail spuriously under load. + error.close() + if retry_get: + continue # server refuses HEAD; try the ranged GET once + # A 3xx HTTPError can indicate the redirect cap was exceeded; + # it is not evidence of a reachable final source. + return False except Exception: return False return False diff --git a/src/ouroboros/telemetry.py b/src/ouroboros/telemetry.py index d4894d3f91..d9c2369ab3 100644 --- a/src/ouroboros/telemetry.py +++ b/src/ouroboros/telemetry.py @@ -114,6 +114,7 @@ "artifacts", "auto", "cancel", + "cloud", "cleanup", "codex", "config", diff --git a/tests/unit/cloud/__init__.py b/tests/unit/cloud/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/cloud/test_cli.py b/tests/unit/cloud/test_cli.py new file mode 100644 index 0000000000..816fa7f12e --- /dev/null +++ b/tests/unit/cloud/test_cli.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from typer.testing import CliRunner + +from ouroboros.cli.main import app + + +def test_cloud_cli_drives_a_host_turn(tmp_path: Path) -> None: + runner = CliRunner() + workspace = str(tmp_path) + + result = runner.invoke(app, ["cloud", "init", "--workspace", workspace, "--seed", "smoke"]) + assert result.exit_code == 0, result.stdout + assert json.loads(result.stdout)["seed"] == "smoke" + + result = runner.invoke( + app, + ["cloud", "plan", "true", "--workspace", workspace], + ) + assert result.exit_code == 0, result.stdout + + result = runner.invoke(app, ["cloud", "next", "--workspace", workspace]) + assert result.exit_code == 0, result.stdout + assert json.loads(result.stdout)["returncode"] == 0 + + result = runner.invoke( + app, + [ + "cloud", + "record-evidence", + "smoke", + "passed", + "--step", + "0", + "--workspace", + workspace, + ], + ) + assert result.exit_code == 0, result.stdout + + result = runner.invoke(app, ["cloud", "verify", "--workspace", workspace]) + assert result.exit_code == 0, result.stdout + assert json.loads(result.stdout)["complete"] is True + + +def test_cloud_cli_status_is_json(tmp_path: Path) -> None: + result = CliRunner().invoke(app, ["cloud", "status", "--workspace", str(tmp_path)]) + assert result.exit_code == 0, result.stdout + payload = json.loads(result.stdout) + assert payload["state"]["next_step"] == 0 + assert payload["environment"]["state_root"].endswith(".ouroboros-cloud") + + +def test_cloud_cli_verify_rejects_uninitialized_workflow(tmp_path: Path) -> None: + runner = CliRunner() + workspace = str(tmp_path) + + result = runner.invoke(app, ["cloud", "init", "--workspace", workspace]) + assert result.exit_code == 0, result.stdout + + result = runner.invoke(app, ["cloud", "verify", "--workspace", workspace]) + assert result.exit_code == 1, result.stdout + assert json.loads(result.stdout)["complete"] is False + + +def test_cloud_cli_replanning_requires_new_evidence(tmp_path: Path) -> None: + runner = CliRunner() + workspace = str(tmp_path) + + assert runner.invoke(app, ["cloud", "plan", "true", "--workspace", workspace]).exit_code == 0 + assert runner.invoke(app, ["cloud", "next", "--workspace", workspace]).exit_code == 0 + assert ( + runner.invoke( + app, + ["cloud", "record-evidence", "run", "observed", "--workspace", workspace], + ).exit_code + == 0 + ) + assert runner.invoke(app, ["cloud", "verify", "--workspace", workspace]).exit_code == 0 + + assert runner.invoke(app, ["cloud", "plan", "true", "--workspace", workspace]).exit_code == 0 + assert runner.invoke(app, ["cloud", "next", "--workspace", workspace]).exit_code == 0 + result = runner.invoke(app, ["cloud", "verify", "--workspace", workspace]) + + assert result.exit_code == 1, result.stdout + assert json.loads(result.stdout)["missing_evidence_steps"] == [0] + + +def test_cloud_cli_recovers_an_interrupted_step(tmp_path: Path) -> None: + runner = CliRunner() + workspace = str(tmp_path) + state_path = tmp_path / ".ouroboros-cloud" / "state.json" + state_path.parent.mkdir() + state_path.write_text( + json.dumps( + { + "plan": ["true"], + "next_step": 0, + "in_flight": {"index": 0, "command": "true"}, + } + ), + encoding="utf-8", + ) + + result = runner.invoke(app, ["cloud", "recover", "0", "--workspace", workspace]) + assert result.exit_code == 0, result.stdout + assert json.loads(result.stdout)["index"] == 0 + + +def test_cloud_cli_verify_rejects_failed_step(tmp_path: Path) -> None: + runner = CliRunner() + workspace = str(tmp_path) + assert runner.invoke(app, ["cloud", "plan", "false", "--workspace", workspace]).exit_code == 0 + assert runner.invoke(app, ["cloud", "next", "--workspace", workspace]).exit_code == 0 + assert ( + runner.invoke( + app, + ["cloud", "record-evidence", "run", "observed", "--workspace", workspace], + ).exit_code + == 0 + ) + + result = runner.invoke(app, ["cloud", "verify", "--workspace", workspace]) + assert result.exit_code == 1, result.stdout + assert json.loads(result.stdout)["complete"] is False + + +def test_cloud_cli_verify_rejects_whitespace_evidence(tmp_path: Path) -> None: + runner = CliRunner() + workspace = str(tmp_path) + assert runner.invoke(app, ["cloud", "plan", "true", "--workspace", workspace]).exit_code == 0 + assert runner.invoke(app, ["cloud", "next", "--workspace", workspace]).exit_code == 0 + assert ( + runner.invoke( + app, + ["cloud", "record-evidence", "run", " \t ", "--workspace", workspace], + ).exit_code + == 0 + ) + + result = runner.invoke(app, ["cloud", "verify", "--workspace", workspace]) + assert result.exit_code == 1, result.stdout + assert json.loads(result.stdout)["complete"] is False diff --git a/tests/unit/cloud/test_process_journey.py b/tests/unit/cloud/test_process_journey.py new file mode 100644 index 0000000000..bdb1f6db23 --- /dev/null +++ b/tests/unit/cloud/test_process_journey.py @@ -0,0 +1,364 @@ +"""End-to-end cloud journeys across fresh CLI processes.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +import pytest + +REPOSITORY_ROOT = Path(__file__).resolve().parents[3] + + +def _host_env(workspace: Path) -> dict[str, str]: + """Model a cloud host whose HOME and XDG locations do not persist.""" + environment = os.environ.copy() + environment.update( + { + "CHATGPT_WORK": "1", + "CODEX_CLOUD": "1", + "GIT_TERMINAL_PROMPT": "0", + "HOME": str(workspace.parent / "missing-home"), + "OUROBOROS_NO_SOCKETS": "1", + "OUROBOROS_TELEMETRY": "0", + "XDG_CONFIG_HOME": str(workspace.parent / "missing-config"), + "XDG_DATA_HOME": str(workspace.parent / "missing-data"), + "PYTHONPATH": os.pathsep.join( + filter(None, [str(REPOSITORY_ROOT / "src"), environment.get("PYTHONPATH")]) + ), + } + ) + return environment + + +def _run(workspace: Path, *arguments: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "ouroboros", *arguments], + cwd=workspace, + env=_host_env(workspace), + capture_output=True, + text=True, + timeout=30, + check=False, + ) + + +def _json(result: subprocess.CompletedProcess[str]) -> dict[str, object]: + return json.loads(result.stdout) + + +def test_cloud_journey_survives_process_turns_recovery_and_bundle_transfer( + tmp_path: Path, +) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + destination.mkdir() + + result = _run(source, "cloud", "init", "--workspace", str(source), "--seed", "smoke") + assert result.returncode == 0, result.stderr + assert _json(result)["seed"] == "smoke" + + result = _run( + source, + "cloud", + "plan", + 'test "$GIT_TERMINAL_PROMPT" = 0', + "printf second > second.txt", + "--workspace", + str(source), + ) + assert result.returncode == 0, result.stderr + + state_path = source / ".ouroboros-cloud" / "state.json" + state = json.loads(state_path.read_text(encoding="utf-8")) + state["in_flight"] = {"index": 0, "command": state["plan"][0]} + state_path.write_text(json.dumps(state), encoding="utf-8") + + result = _run(source, "cloud", "next", "--workspace", str(source)) + assert result.returncode == 2 + recovery = _json(result) + assert recovery["error"] == "recovery_required" + assert recovery["in_flight"] == {"index": 0, "command": state["plan"][0]} + + result = _run( + source, + "cloud", + "recover", + "0", + "--stdout", + "first turn was observed", + "--stderr", + "", + "--workspace", + str(source), + ) + assert result.returncode == 0, result.stderr + assert _json(result)["index"] == 0 + + result = _run(source, "cloud", "next", "--workspace", str(source)) + assert result.returncode == 0, result.stderr + assert _json(result)["returncode"] == 0 + assert (source / "second.txt").read_text(encoding="utf-8") == "second" + + for step, value in ((0, "first turn was observed"), (1, "second turn was observed")): + result = _run( + source, + "cloud", + "record-evidence", + "smoke", + value, + "--step", + str(step), + "--workspace", + str(source), + ) + assert result.returncode == 0, result.stderr + + result = _run(source, "cloud", "verify", "--workspace", str(source)) + assert result.returncode == 0, result.stderr + assert _json(result)["complete"] is True + + result = _run(source, "cloud", "status", "--workspace", str(source)) + assert result.returncode == 0, result.stderr + status = _json(result) + assert status["environment"]["zero_daemon"] is True + assert status["environment"]["home_restricted"] is True + assert status["environment"]["xdg_restricted"] is True + + bundle = tmp_path / "cloud-run.tar.gz" + result = _run( + source, + "cloud", + "bundle", + "export", + str(bundle), + "--workspace", + str(source), + ) + assert result.returncode == 0, result.stderr + assert bundle.is_file() + + result = _run( + destination, + "cloud", + "bundle", + "import", + str(bundle), + "--workspace", + str(destination), + ) + assert result.returncode == 0, result.stderr + + result = _run(destination, "cloud", "verify", "--workspace", str(destination)) + assert result.returncode == 0, result.stderr + assert _json(result)["complete"] is True + assert (destination / "bootstrap.sh").is_file() + + +def test_cloud_process_verification_fails_for_a_failed_step(tmp_path: Path) -> None: + workspace = tmp_path / "failed" + workspace.mkdir() + + result = _run(workspace, "cloud", "plan", "false", "--workspace", str(workspace)) + assert result.returncode == 0, result.stderr + + result = _run(workspace, "cloud", "next", "--workspace", str(workspace)) + assert result.returncode == 0, result.stderr + assert _json(result)["returncode"] != 0 + + result = _run( + workspace, + "cloud", + "record-evidence", + "observed", + "failure", + "--step", + "0", + "--workspace", + str(workspace), + ) + assert result.returncode == 0, result.stderr + + result = _run(workspace, "cloud", "verify", "--workspace", str(workspace)) + assert result.returncode == 1 + receipt = _json(result) + assert receipt["complete"] is False + assert receipt["failed_steps"] == [0] + + +def test_cloud_process_replanning_requires_new_evidence(tmp_path: Path) -> None: + workspace = tmp_path / "replan" + workspace.mkdir() + + for command in ( + ("cloud", "plan", "true", "--workspace", str(workspace)), + ("cloud", "next", "--workspace", str(workspace)), + ( + "cloud", + "record-evidence", + "run", + "observed", + "--step", + "0", + "--workspace", + str(workspace), + ), + ): + result = _run(workspace, *command) + assert result.returncode == 0, result.stderr + + result = _run(workspace, "cloud", "verify", "--workspace", str(workspace)) + assert result.returncode == 0, result.stderr + + result = _run(workspace, "cloud", "plan", "true", "--workspace", str(workspace)) + assert result.returncode == 0, result.stderr + result = _run(workspace, "cloud", "next", "--workspace", str(workspace)) + assert result.returncode == 0, result.stderr + result = _run(workspace, "cloud", "verify", "--workspace", str(workspace)) + assert result.returncode == 1 + assert _json(result)["missing_evidence_steps"] == [0] + + +@pytest.mark.skipif(os.name == "nt", reason="SIGKILL process-group test requires POSIX") +def test_cloud_process_crash_fails_closed_then_recovers_and_imports( + tmp_path: Path, +) -> None: + source = tmp_path / "source" + sandbox = tmp_path / "sandbox" + destination = tmp_path / "destination" + source.mkdir() + sandbox.mkdir() + destination.mkdir() + + result = _run(source, "cloud", "init", "--workspace", str(source), "--seed", "crash") + assert result.returncode == 0, result.stderr + result = _run( + source, + "cloud", + "plan", + "printf started > crash.started; printf '%s' \"$$\" > crash.pid; sleep 30", + "--workspace", + str(source), + ) + assert result.returncode == 0, result.stderr + + planned_bundle = tmp_path / "planned.tar.gz" + result = _run( + source, + "cloud", + "bundle", + "export", + str(planned_bundle), + "--workspace", + str(source), + ) + assert result.returncode == 0, result.stderr + result = _run( + sandbox, + "cloud", + "bundle", + "import", + str(planned_bundle), + "--workspace", + str(sandbox), + ) + assert result.returncode == 0, result.stderr + result = _run(sandbox, "cloud", "approve", "--workspace", str(sandbox)) + assert result.returncode == 0, result.stderr + + crashed = subprocess.Popen( + [sys.executable, "-m", "ouroboros", "cloud", "next", "--workspace", str(sandbox)], + cwd=sandbox, + env=_host_env(sandbox), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + host_pid: int | None = None + try: + deadline = time.monotonic() + 10 + started = sandbox / "crash.started" + pid_path = sandbox / "crash.pid" + while time.monotonic() < deadline and not pid_path.exists(): + time.sleep(0.02) + assert started.exists() + host_pid = int(pid_path.read_text(encoding="utf-8")) + crashed.send_signal(signal.SIGKILL) + assert crashed.wait(timeout=10) == -signal.SIGKILL + os.killpg(host_pid, signal.SIGKILL) + + state = json.loads( + (sandbox / ".ouroboros-cloud" / "state.json").read_text(encoding="utf-8") + ) + assert state["active_step"] == {"command": state["plan"][0], "index": 0} + + result = _run(sandbox, "cloud", "verify", "--workspace", str(sandbox)) + assert result.returncode == 1 + assert _json(result)["recovery_required"] is True + + result = _run( + sandbox, + "cloud", + "recover", + "137", + "--stdout", + "crash observed", + "--workspace", + str(sandbox), + ) + assert result.returncode == 0, result.stderr + result = _run( + sandbox, + "cloud", + "record-evidence", + "crash", + "recovered", + "--step", + "0", + "--workspace", + str(sandbox), + ) + assert result.returncode == 0, result.stderr + result = _run(sandbox, "cloud", "verify", "--workspace", str(sandbox)) + assert result.returncode == 1 + + recovered_bundle = tmp_path / "recovered.tar.gz" + result = _run( + sandbox, + "cloud", + "bundle", + "export", + str(recovered_bundle), + "--workspace", + str(sandbox), + ) + assert result.returncode == 0, result.stderr + result = _run( + destination, + "cloud", + "bundle", + "import", + str(recovered_bundle), + "--workspace", + str(destination), + ) + assert result.returncode == 0, result.stderr + result = _run(destination, "cloud", "verify", "--workspace", str(destination)) + assert result.returncode == 1 + assert _json(result)["failed_steps"] == [0] + finally: + if crashed.poll() is None: + crashed.kill() + crashed.wait() + if host_pid is not None: + try: + os.killpg(host_pid, signal.SIGKILL) + except ProcessLookupError: + pass + crashed.communicate(timeout=10) diff --git a/tests/unit/cloud/test_round20_audit.py b/tests/unit/cloud/test_round20_audit.py new file mode 100644 index 0000000000..b1ce15c116 --- /dev/null +++ b/tests/unit/cloud/test_round20_audit.py @@ -0,0 +1,128 @@ +"""Round 20 regressions for portable cloud runtime boundary conditions.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +import ouroboros.cloud.bundle as bundle_module +from ouroboros.cloud.bundle import export_bundle, import_bundle +from ouroboros.cloud.driver import CloudDriver +from ouroboros.cloud.limits import MAX_COMMAND_BYTES + + +def test_invalid_bundle_does_not_create_a_new_destination(tmp_path: Path) -> None: + source = tmp_path / "source" + source.mkdir() + export_bundle(source, tmp_path / "valid.tar.gz") + invalid = tmp_path / "invalid.tar.gz" + invalid.write_bytes(b"not a gzip archive") + destination = tmp_path / "new-destination" + + with pytest.raises(ValueError, match="cannot read cloud bundle"): + import_bundle(invalid, destination) + + assert not destination.exists() + + +def test_checkpoint_command_obeys_plan_command_ceiling_on_load(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + payload = driver.state.to_dict() + payload["next_step"] = 1 + payload["checkpoints"] = [ + { + "index": 0, + "command": "x" * (MAX_COMMAND_BYTES + 1), + "returncode": 0, + "stdout": "", + "stderr": "", + "next_step": 1, + } + ] + driver.store.path.write_text(json.dumps(payload), encoding="utf-8") + + with pytest.raises(ValueError, match="cloud checkpoint command"): + driver.store.load() + + +def test_next_rejects_checkpoint_cursor_mismatch_before_side_effect( + tmp_path: Path, +) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["printf x >> repeated.txt"]) + state = driver.state + state.checkpoints = [ + { + "index": 0, + "command": state.plan[0], + "returncode": 0, + "stdout": "", + "stderr": "", + "next_step": 1, + } + ] + state.next_step = 0 + driver.store.save(state) + + with pytest.raises(ValueError, match="invalid completed checkpoints"): + driver.next() + + assert not (tmp_path / "repeated.txt").exists() + + +def test_import_rejects_option_injected_git_base_revision(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + payload = driver.init().to_dict() + payload["git_base_revision"] = "--output=/tmp/escaped.patch" + + with pytest.raises(ValueError, match="full object ID"): + type(driver.state).from_dict(payload) + + +def test_unicode_evidence_uses_utf8_state_size_math(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + assert driver.next() is not None + driver.record_evidence("observation", "한" * 20_000, step=0) + + restored = driver.store.load() + assert restored.evidence[0]["value"] == "한" * 20_000 + assert len(driver.store.path.read_bytes()) < 100_000 + + +@pytest.mark.parametrize( + "path", + [ + b"..\\outside.txt", + b"C:\\outside.txt", + b"\\\\server\\share", + b".ouroboros-cloud\\state.json", + b"CON", + b"foo:bar", + ], +) +def test_patch_paths_reject_windows_escape_forms(path: bytes) -> None: + with pytest.raises(ValueError, match="unsafe path"): + bundle_module._validate_patch_payload(b"diff --git a/" + path + b" b/" + path + b"\n") + + +def test_windows_worker_evidence_runs_after_cancellation_and_fails_closed() -> None: + workflow = (Path(__file__).resolve().parents[3] / ".github/workflows/test.yml").read_text( + encoding="utf-8" + ) + + worker_step = workflow.split( + " - name: Run targeted Windows detached worker regressions", 1 + )[1] + worker_step, report_step = worker_step.split( + " - name: Report detached worker verification scope", 1 + ) + + assert "if: ${{ always() }}" in worker_step + assert "!cancelled()" not in worker_step + assert "OOO_WORKER_TEST_OUTCOME: ${{ steps.detached-worker-tests.outcome }}" in report_step + assert 'os.environ["OOO_WORKER_TEST_OUTCOME"] != "success"' in report_step + assert "NOT VERIFIED: no JUnit report was produced." in report_step diff --git a/tests/unit/cloud/test_runtime.py b/tests/unit/cloud/test_runtime.py new file mode 100644 index 0000000000..d436f699a3 --- /dev/null +++ b/tests/unit/cloud/test_runtime.py @@ -0,0 +1,1470 @@ +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +import io +import json +from pathlib import Path +import random +import stat +import subprocess +import sys +import tarfile +import tempfile +from time import monotonic + +import pytest + +from ouroboros.cloud.bootstrap import bootstrap_bundle +import ouroboros.cloud.bundle as bundle_module +from ouroboros.cloud.bundle import _bootstrap_payload, export_bundle, import_bundle +import ouroboros.cloud.driver as driver_module +from ouroboros.cloud.driver import ( + _MAX_VERIFICATION_RECEIPTS, + CloudApprovalRequired, + CloudDriver, + CloudRecoveryRequired, +) +from ouroboros.cloud.environment import detect_environment +from ouroboros.cloud.limits import ( + DEFAULT_LOCK_TIMEOUT_SECONDS, + MAX_COMMAND_BYTES, + MAX_EVIDENCE_NAME_BYTES, + MAX_EVIDENCE_RECORDS, + MAX_EVIDENCE_VALUE_BYTES, + MAX_OUTPUT_BYTES, + MAX_PLAN_STEPS, + MAX_STATE_BYTES, +) +from ouroboros.cloud.state import CloudState, CloudStateStore + + +def test_detects_cloud_mount_and_restricted_runtime(monkeypatch, tmp_path: Path) -> None: + workspace = tmp_path / "workspace" + workspace.mkdir() + environment = { + "CODEX_CLOUD": "1", + "HOME": str(tmp_path / "missing-home"), + "XDG_CONFIG_HOME": str(tmp_path / "missing-xdg"), + "GIT_TERMINAL_PROMPT": "0", + "OUROBOROS_NO_SOCKETS": "1", + } + monkeypatch.chdir(workspace) + facts = detect_environment(workspace, environment) + assert facts.is_cloud + assert facts.home_restricted + assert facts.xdg_restricted + assert facts.git_noninteractive + assert facts.daemon_limited and facts.socket_limited + assert facts.state_root == workspace / ".ouroboros-cloud" + assert facts.zero_daemon + + +def test_workspace_mount_is_a_cloud_signal(tmp_path: Path) -> None: + facts = detect_environment("/workspace", {"HOME": str(tmp_path / "home")}) + assert facts.is_cloud + assert facts.workspace_mount + assert facts.state_root == Path("/workspace/.ouroboros-cloud") + + +def test_detects_explicit_runtime_limits(tmp_path: Path) -> None: + workspace = tmp_path / "project" + workspace.mkdir() + facts = detect_environment( + workspace, + { + "HOME": str(tmp_path / "home"), + "XDG_CONFIG_HOME": str(tmp_path / "config"), + "OUROBOROS_DAEMON_LIMITED": "yes", + "OUROBOROS_SOCKET_LIMITED": "true", + "GIT_TERMINAL_PROMPT": "0", + }, + ) + assert not facts.is_cloud + assert facts.git_noninteractive + assert facts.daemon_limited and facts.socket_limited + assert facts.home_restricted and facts.xdg_restricted + + +def test_missing_home_and_xdg_are_restricted(tmp_path: Path) -> None: + facts = detect_environment(tmp_path / "project", {"CODEX_CLOUD": "0"}) + assert facts.home_restricted and facts.xdg_restricted + assert facts.home_ephemeral and facts.xdg_ephemeral + assert facts.state_root == (tmp_path / "project").resolve() / ".ouroboros-cloud" + + +def test_restricted_xdg_data_home_is_detected_when_config_home_is_valid( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + home = tmp_path / "home" + config = home / ".config" + config.mkdir(parents=True) + blocked_parent = tmp_path / "not-a-directory" + blocked_parent.write_text("file", encoding="utf-8") + monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path / "host-tmp")) + + facts = detect_environment( + tmp_path / "project", + { + "HOME": str(home), + "XDG_CONFIG_HOME": str(config), + "XDG_DATA_HOME": str(blocked_parent / "data"), + "XDG_RUNTIME_DIR": str(home / ".runtime"), + }, + ) + + assert facts.home_restricted is False + assert facts.xdg_restricted + + +def test_local_host_with_portable_runtime_dir_is_not_marked_limited( + tmp_path: Path, monkeypatch +) -> None: + home = tmp_path / "portable-home" + xdg = home / ".config" + runtime = home / ".runtime" + home.mkdir() + xdg.mkdir() + runtime.mkdir() + host_tmp = tmp_path / "host-tmp" + host_tmp.mkdir() + monkeypatch.setattr(tempfile, "gettempdir", lambda: str(host_tmp)) + facts = detect_environment( + tmp_path / "project", + { + "HOME": str(home), + "XDG_CONFIG_HOME": str(xdg), + "XDG_RUNTIME_DIR": str(runtime), + }, + ) + assert not facts.home_restricted + assert not facts.xdg_restricted + assert not facts.daemon_limited + assert not facts.socket_limited + + +def test_state_persists_without_home_or_xdg(tmp_path: Path, monkeypatch) -> None: + workspace = tmp_path / "project" + workspace.mkdir() + monkeypatch.setenv("HOME", str(tmp_path / "unwritable-home")) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "unwritable-xdg")) + monkeypatch.setenv("GIT_TERMINAL_PROMPT", "0") + driver = CloudDriver(workspace) + driver.init("build a tool") + driver.plan(["printf cloud > result.txt"]) + result = driver.next() + assert result is not None and result.returncode == 0 + assert (workspace / "result.txt").read_text() == "cloud" + restored = CloudStateStore(workspace).load() + assert restored.seed == "build a tool" + assert restored.next_step == 1 + assert restored.checkpoints[0]["returncode"] == 0 + + +def test_git_prompt_cannot_be_reenabled_by_step_environment(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(['test "$GIT_TERMINAL_PROMPT" = 0']) + result = driver.next(env={"GIT_TERMINAL_PROMPT": "1"}) + assert result is not None and result.returncode == 0 + + +def test_host_turn_does_not_inherit_controller_secrets_or_home( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("CLOUD_RUNTIME_TEST_SECRET", "must-not-leak") + driver = CloudDriver(tmp_path) + driver.plan( + [ + 'test -z "${CLOUD_RUNTIME_TEST_SECRET-}"', + f'test "$HOME" = "{tmp_path / ".ouroboros-cloud" / "home"}"', + ] + ) + + first = driver.next(env={"CLOUD_RUNTIME_TEST_SECRET": "explicit-secret"}) + second = driver.next() + + assert first is not None and first.returncode == 0 + assert second is not None and second.returncode == 0 + + +def test_bundle_roundtrip_is_self_contained(tmp_path: Path) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + CloudDriver(source).plan(["true"]) + bundle = export_bundle(source, tmp_path / "run.tar.gz") + assert bundle.exists() + imported = import_bundle(bundle, destination) + assert imported == destination / ".ouroboros-cloud" / "state.json" + assert json.loads(imported.read_text())["plan"] == ["true"] + assert json.loads(imported.read_text())["execution_approved"] is False + CloudDriver(destination).init() + with pytest.raises(CloudApprovalRequired): + CloudDriver(destination).next() + CloudDriver(destination).approve() + assert CloudDriver(destination).next() is not None + assert not list(destination.glob("**/*.sock")) + bootstrapped = bootstrap_bundle(bundle, destination / "bootstrapped") + assert json.loads(bootstrapped.read_text())["plan"] == ["true"] + + +def test_bundle_import_preserves_bootstrap_executable_mode(tmp_path: Path) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + CloudDriver(source).init("safe") + bundle = export_bundle(source, tmp_path / "run.tar.gz") + + import_bundle(bundle, destination) + + assert stat.S_IMODE((destination / "bootstrap.sh").stat().st_mode) == 0o755 + + +def test_bundle_import_rejects_path_traversal(tmp_path: Path) -> None: + bundle = tmp_path / "unsafe.tar.gz" + with tarfile.open(bundle, "w:gz") as archive: + info = tarfile.TarInfo("../outside.txt") + payload = b"unsafe" + info.size = len(payload) + import io + + archive.addfile(info, io.BytesIO(payload)) + try: + import_bundle(bundle, tmp_path / "restored") + except ValueError as exc: + assert "unsupported" in str(exc) + else: + raise AssertionError("unsafe bundle was accepted") + + +def test_bundle_import_rejects_member_flood_before_restoring_workspace(tmp_path: Path) -> None: + bundle = tmp_path / "member-flood.tar.gz" + names = [ + bundle_module._STATE_NAME, + bundle_module._BOOTSTRAP_NAME, + bundle_module._MANIFEST_NAME, + bundle_module._PATCH_NAME, + bundle_module._PATCH_NAME, + ] + with tarfile.open(bundle, "w:gz") as archive: + for name in names: + payload = b"{}\n" + info = tarfile.TarInfo(name) + info.size = len(payload) + archive.addfile(info, io.BytesIO(payload)) + + with pytest.raises(ValueError, match="too many members"): + import_bundle(bundle, tmp_path / "restored") + assert not (tmp_path / "restored").exists() + + +def test_bundle_import_rejects_symlink_target(tmp_path: Path) -> None: + bundle = tmp_path / "state.tar.gz" + source = tmp_path / "source" + source.mkdir() + CloudDriver(source).init("safe") + export_bundle(source, bundle) + + destination = tmp_path / "destination" + destination.mkdir() + outside = tmp_path / "outside.json" + outside.write_text("leave me", encoding="utf-8") + state_dir = destination / ".ouroboros-cloud" + state_dir.mkdir() + (state_dir / "state.json").symlink_to(outside) + + try: + import_bundle(bundle, destination) + except ValueError as exc: + assert "regular file" in str(exc) + else: + raise AssertionError("symlink target was accepted") + assert outside.read_text(encoding="utf-8") == "leave me" + + +def test_bundle_export_is_byte_for_byte_deterministic(tmp_path: Path) -> None: + source = tmp_path / "source" + source.mkdir() + CloudDriver(source).plan(["true"]) + + first = export_bundle(source, tmp_path / "first.tar.gz") + second = export_bundle(source, tmp_path / "second.tar.gz") + + assert first.read_bytes() == second.read_bytes() + + +def test_bundle_export_preserves_an_existing_destination_on_write_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = tmp_path / "source" + CloudDriver(source).init() + destination = tmp_path / "existing.tar.gz" + destination.write_bytes(b"previous bundle") + + def fail_archive(*_args: object, **_kwargs: object) -> object: + raise OSError("simulated archive failure") + + monkeypatch.setattr(bundle_module.tarfile, "open", fail_archive) + with pytest.raises(OSError, match="simulated archive failure"): + export_bundle(source, destination) + + assert destination.read_bytes() == b"previous bundle" + + +def test_bundle_export_rejects_state_directory_destination(tmp_path: Path) -> None: + source = tmp_path / "source" + source.mkdir() + driver = CloudDriver(source) + driver.init("safe") + state_before = driver.store.path.read_bytes() + + with pytest.raises(ValueError, match="outside the state directory"): + export_bundle(source, driver.store.path) + + assert driver.store.path.read_bytes() == state_before + + +def test_patch_import_does_not_create_failed_absent_destination(tmp_path: Path) -> None: + source = tmp_path / "source" + _git_repo(source) + CloudDriver(source).init("patch") + (source / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(source, tmp_path / "patch.tar.gz") + destination = tmp_path / "absent" + + with pytest.raises(ValueError, match="cloud patch conflict"): + import_bundle(bundle, destination) + + assert not destination.exists() + + +def test_corrupt_bundle_does_not_replace_valid_checkpoint(tmp_path: Path) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + destination.mkdir() + CloudDriver(source).init("good") + valid = export_bundle(source, tmp_path / "valid.tar.gz") + import_bundle(valid, destination) + expected = (destination / ".ouroboros-cloud/state.json").read_bytes() + + corrupted = tmp_path / "corrupted.tar.gz" + with tarfile.open(valid, "r:gz") as reader, tarfile.open(corrupted, "w:gz") as writer: + for member in reader.getmembers(): + payload = reader.extractfile(member) + assert payload is not None + data = payload.read() + if member.name == ".ouroboros-cloud/state.json": + data = b'{"checkpoints": [null]}\n' + member.size = len(data) + writer.addfile(member, io.BytesIO(data)) + + with pytest.raises(ValueError, match="checksum mismatch"): + import_bundle(corrupted, destination) + assert (destination / ".ouroboros-cloud/state.json").read_bytes() == expected + + +def _git(cwd: Path, *args: str) -> str: + result = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=True) + return result.stdout.strip() + + +def _git_repo(path: Path) -> None: + path.mkdir() + _git(path, "init", "--quiet") + _git(path, "config", "user.email", "cloud-test@example.invalid") + _git(path, "config", "user.name", "Cloud Test") + (path / "result.txt").write_text("base\n", encoding="utf-8") + _git(path, "add", "result.txt") + _git(path, "commit", "--quiet", "-m", "base") + + +def test_bundle_patch_roundtrip_applies_on_recorded_git_base(tmp_path: Path) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("patch") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "patch.tar.gz") + + import_bundle(bundle, local) + + assert (local / "result.txt").read_text(encoding="utf-8") == "cloud result\n" + + +def test_bundle_patch_import_is_idempotent_after_a_committed_patch(tmp_path: Path) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("patch") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "patch.tar.gz") + + import_bundle(bundle, local) + import_bundle(bundle, local) + + assert (local / "result.txt").read_text(encoding="utf-8") == "cloud result\n" + assert CloudStateStore(local).load().seed == "patch" + + +def test_bundle_import_recovers_when_patch_was_applied_before_a_crash( + tmp_path: Path, +) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("patch") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "patch.tar.gz") + + with tarfile.open(bundle, "r:gz") as archive: + member = archive.extractfile(".ouroboros-cloud/execution.patch") + assert member is not None + bundle_module._apply_patch(local, member.read()) + + import_bundle(bundle, local) + + assert (local / "result.txt").read_text(encoding="utf-8") == "cloud result\n" + assert CloudStateStore(local).load().seed == "patch" + + +def test_replanning_refreshes_the_git_patch_base(tmp_path: Path) -> None: + workspace = tmp_path / "workspace" + _git_repo(workspace) + driver = CloudDriver(workspace) + + first = driver.plan(["true"]) + first_revision = first.git_base_revision + (workspace / "result.txt").write_text("committed between plans\n", encoding="utf-8") + _git(workspace, "add", "result.txt") + _git(workspace, "commit", "--quiet", "-m", "between plans") + + second = driver.plan(["true"]) + + assert first_revision is not None + assert second.git_base_revision == _git(workspace, "rev-parse", "HEAD") + assert second.git_base_revision != first_revision + + +def test_bundle_patch_roundtrip_includes_untracked_files(tmp_path: Path) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + (cloud / "preexisting.txt").write_text("keep local\n", encoding="utf-8") + CloudDriver(cloud).init("new file") + (cloud / "generated.txt").write_text("generated by cloud\n", encoding="utf-8") + + bundle = export_bundle(cloud, tmp_path / "untracked.tar.gz") + import_bundle(bundle, local) + + assert (local / "generated.txt").read_text(encoding="utf-8") == "generated by cloud\n" + assert not (local / "preexisting.txt").exists() + + +def test_bundle_import_rejects_patch_that_would_create_a_symlink(tmp_path: Path) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("symlink") + outside = tmp_path / "outside.txt" + outside.write_text("outside\n", encoding="utf-8") + (cloud / "result.txt").unlink() + (cloud / "result.txt").symlink_to(outside) + + bundle = export_bundle(cloud, tmp_path / "symlink.tar.gz") + + with pytest.raises(ValueError, match="symbolic links"): + import_bundle(bundle, local) + assert (local / "result.txt").is_file() + assert not (local / "result.txt").is_symlink() + assert outside.read_text(encoding="utf-8") == "outside\n" + + +@pytest.mark.parametrize( + "metadata", + [ + b"rename to ", + b"copy to ", + b'diff --git "a/\\056ouroboros-cloud/state.json" "b/\\056ouroboros-cloud/state.json" ', + ], +) +def test_patch_metadata_cannot_target_cloud_state_directory(metadata: bytes) -> None: + with pytest.raises(ValueError, match="internal state directory"): + bundle_module._validate_patch_payload(metadata + b".ouroboros-cloud/state.json\n") + + +def test_patch_hunk_line_resembling_file_header_is_ignored() -> None: + patch = b"""diff --git a/result.txt b/result.txt +index df967b9..f2d5c8f 100644 +--- a/result.txt ++++ b/result.txt +@@ -1 +1,2 @@ + base ++++ /tmp/legal-source-text +""" + + bundle_module._validate_patch_payload(patch) + + assert bundle_module._patch_paths(patch) == ["result.txt"] + + +def test_bundle_import_keeps_checkpoint_when_patch_application_fails( + tmp_path: Path, monkeypatch +) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("new") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "failure.tar.gz") + old_state = CloudDriver(local).init("old").to_dict() + + def fail_patch(*_args, **_kwargs) -> None: + raise ValueError("injected patch failure") + + monkeypatch.setattr(bundle_module, "_apply_patch", fail_patch) + with pytest.raises(ValueError, match="injected patch failure"): + import_bundle(bundle, local) + + assert CloudStateStore(local).load().to_dict() == old_state + + +def test_bundle_import_rolls_back_patch_when_target_write_fails( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("new") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "failure-after-patch.tar.gz") + old_state = CloudDriver(local).init("old").to_dict() + original_write = bundle_module._write_regular_file + + def fail_bootstrap(path: Path, payload: bytes, **kwargs: object) -> None: + if path.name == "bootstrap.sh": + raise ValueError("injected target write failure") + original_write(path, payload, **kwargs) + + monkeypatch.setattr(bundle_module, "_write_regular_file", fail_bootstrap) + with pytest.raises(ValueError, match="injected target write failure"): + import_bundle(bundle, local) + + assert (local / "result.txt").read_text(encoding="utf-8") == "base\n" + assert CloudStateStore(local).load().to_dict() == old_state + assert not (local / "bootstrap.sh").exists() + + +def test_bundle_import_rolls_back_patch_when_apply_raises_after_mutation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("new") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "failure-after-apply.tar.gz") + original_apply = bundle_module._apply_patch + + def apply_then_crash(path: Path, payload: bytes) -> None: + original_apply(path, payload) + raise KeyboardInterrupt + + monkeypatch.setattr(bundle_module, "_apply_patch", apply_then_crash) + with pytest.raises(KeyboardInterrupt): + import_bundle(bundle, local) + + assert (local / "result.txt").read_text(encoding="utf-8") == "base\n" + assert not (local / ".ouroboros-cloud" / "state.json").exists() + assert not (local / "bootstrap.sh").exists() + + +def test_bundle_import_recovers_non_ascii_path_after_target_write_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + filename = "é.txt" + _git_repo(cloud) + (cloud / filename).write_text("base\n", encoding="utf-8") + _git(cloud, "add", filename) + _git(cloud, "commit", "--quiet", "-m", "base") + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + + CloudDriver(cloud).init("non-ascii") + (cloud / filename).write_text("cloud\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "failure-non-ascii.tar.gz") + files = bundle_module._read_and_validate_bundle(bundle) + assert b'"a/\\303\\251.txt"' in files[bundle_module._PATCH_NAME] + + original_write = bundle_module._write_regular_file + + def fail_bootstrap(path: Path, payload: bytes, **kwargs: object) -> None: + if path.name == "bootstrap.sh": + raise ValueError("injected target write failure") + original_write(path, payload, **kwargs) + + monkeypatch.setattr(bundle_module, "_write_regular_file", fail_bootstrap) + with pytest.raises(ValueError, match="injected target write failure"): + import_bundle(bundle, local) + + assert (local / filename).read_text(encoding="utf-8") == "base\n" + assert not (local / "é.txt").exists() + + +def test_bundle_import_recovers_a_stale_patch_journal_before_replay( + tmp_path: Path, +) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + (cloud / "one.txt").write_text("base one\n", encoding="utf-8") + (cloud / "two.txt").write_text("base two\n", encoding="utf-8") + _git(cloud, "add", "one.txt", "two.txt") + _git(cloud, "commit", "--quiet", "-m", "base") + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + + CloudDriver(cloud).init("patch") + (cloud / "one.txt").write_text("cloud one\n", encoding="utf-8") + (cloud / "two.txt").write_text("cloud two\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "stale-journal.tar.gz") + files = bundle_module._read_and_validate_bundle(bundle) + patch = files[bundle_module._PATCH_NAME] + target = local / ".ouroboros-cloud" + target.mkdir() + + bundle_module._write_import_journal(local, target, patch) + bundle_module._apply_patch(local, patch) + (local / "two.txt").unlink() + + import_bundle(bundle, local) + + assert (local / "one.txt").read_text(encoding="utf-8") == "cloud one\n" + assert (local / "two.txt").read_text(encoding="utf-8") == "cloud two\n" + assert not (local / ".ouroboros-cloud" / "import-recovery.json").exists() + + +def test_import_recovery_rejects_symlinked_parent_before_external_delete( + tmp_path: Path, +) -> None: + workspace = tmp_path / "workspace" + target = workspace / ".ouroboros-cloud" + outside = tmp_path / "outside" + workspace.mkdir() + target.mkdir() + outside.mkdir() + outside_file = outside / "result.txt" + outside_file.write_text("preserve\n", encoding="utf-8") + (workspace / "nested").symlink_to(outside, target_is_directory=True) + + journal = { + "format": 1, + "paths": [{"path": "nested/result.txt", "exists": False}], + "created_directories": [], + } + (target / "import-recovery.json").write_bytes(bundle_module._json_bytes(journal)) + + with pytest.raises(ValueError, match="unsafe path"): + bundle_module._recover_import_journal(workspace, target) + + assert outside_file.read_text(encoding="utf-8") == "preserve\n" + assert (target / "import-recovery.json").exists() + + +def test_bundle_import_removes_new_workspace_after_target_write_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = tmp_path / "source" + source.mkdir() + CloudDriver(source).init("safe") + bundle = export_bundle(source, tmp_path / "failure-new-workspace.tar.gz") + destination = tmp_path / "destination" + original_write = bundle_module._write_regular_file + + def fail_bootstrap(path: Path, payload: bytes, **kwargs: object) -> None: + if path.name == "bootstrap.sh": + raise ValueError("injected target write failure") + original_write(path, payload, **kwargs) + + monkeypatch.setattr(bundle_module, "_write_regular_file", fail_bootstrap) + with pytest.raises(ValueError, match="injected target write failure"): + import_bundle(bundle, destination) + + assert not destination.exists() + + +def test_imported_bootstrap_quotes_cli_override() -> None: + payload = _bootstrap_payload().decode("utf-8") + + assert "cli=${OUROBOROS_CLOUD_CLI:-ouroboros}" in payload + assert 'exec "$cli" cloud verify' in payload + + +def test_bundle_patch_rejects_local_branch_that_moved(tmp_path: Path) -> None: + cloud = tmp_path / "cloud" + local = tmp_path / "local" + _git_repo(cloud) + _git(tmp_path, "clone", "--quiet", str(cloud), str(local)) + _git(local, "config", "user.email", "cloud-test@example.invalid") + _git(local, "config", "user.name", "Cloud Test") + CloudDriver(cloud).init("patch") + (cloud / "result.txt").write_text("cloud result\n", encoding="utf-8") + bundle = export_bundle(cloud, tmp_path / "patch.tar.gz") + + (local / "result.txt").write_text("local result\n", encoding="utf-8") + _git(local, "add", "result.txt") + _git(local, "commit", "--quiet", "-m", "local move") + + with pytest.raises(ValueError, match="cloud patch conflict"): + import_bundle(bundle, local) + assert not (local / ".ouroboros-cloud" / "state.json").exists() + + +def test_driver_evidence_and_verify(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + driver.plan(["true"]) + assert driver.next() is not None + driver.record_evidence("tests", "passed") + assert driver.verify() + assert driver.state.verification_receipts[-1]["complete"] is True + + +def test_verify_rejects_init_only_state(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + + assert not driver.verify() + + +def test_replanning_discards_evidence_from_the_previous_plan(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + assert driver.next() is not None + driver.record_evidence("old-plan", "observed") + assert driver.verify() + + driver.plan(["true"]) + assert driver.state.evidence == [] + assert driver.next() is not None + assert not driver.verify() + + +def test_replanning_requires_recovery_before_discarding_in_flight_step(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + state = driver.state + state.in_flight = {"index": 0, "command": "true"} + driver.store.save(state) + + with pytest.raises(CloudRecoveryRequired, match="before replanning"): + driver.plan(["false"]) + + assert driver.state.in_flight == {"index": 0, "command": "true"} + assert driver.state.plan == ["true"] + + +def test_verify_rejects_empty_plan(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan([]) + driver.record_evidence("run", "observed") + + assert not driver.verify() + + +def test_completed_step_is_restart_idempotent(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["printf x >> side-effect.txt"]) + assert driver.next() is not None + + for _ in range(3): + restarted = CloudDriver(tmp_path) + assert restarted.next() is None + assert (tmp_path / "side-effect.txt").read_text(encoding="utf-8") == "x" + + +def test_interrupted_step_is_not_replayed_and_can_be_recovered( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["printf x >> side-effect.txt"]) + + def crash_after_side_effect(*_args: object, **_kwargs: object) -> object: + (tmp_path / "side-effect.txt").write_text("x", encoding="utf-8") + raise KeyboardInterrupt + + monkeypatch.setattr(driver_module, "_run_host_turn", crash_after_side_effect) + with pytest.raises(KeyboardInterrupt): + driver.next() + + restarted = CloudDriver(tmp_path) + assert restarted.state.in_flight == {"index": 0, "command": "printf x >> side-effect.txt"} + with pytest.raises(CloudRecoveryRequired, match="unresolved execution"): + restarted.next() + + recovered = restarted.recover(returncode=0, stdout="observed") + assert recovered.index == 0 + retried = restarted.recover(returncode=0, stdout="observed", step=0) + assert retried == recovered + with pytest.raises(ValueError, match="step identity is required"): + restarted.recover(returncode=0) + restarted.record_evidence("command", "observed") + assert restarted.verify() + assert (tmp_path / "side-effect.txt").read_text(encoding="utf-8") == "x" + + +def test_recovery_does_not_match_an_ordinary_completed_checkpoint(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + driver.next() + + with pytest.raises(ValueError, match="no interrupted step"): + driver.recover(returncode=0) + + +def test_recovery_replay_requires_step_identity_after_progress(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true", "true"]) + for index in range(2): + state = driver.state + state.in_flight = {"index": state.next_step, "command": state.plan[state.next_step]} + driver.store.save(state) + driver.recover( + returncode=0, + stdout="same", + stderr="same", + step=index if index else None, + ) + + with pytest.raises(ValueError, match="step identity is required"): + driver.recover(returncode=0, stdout="same", stderr="same") + + +def test_recovery_rejects_stale_unique_result_after_progress(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true", "false"]) + first = driver.state + first.in_flight = {"index": 0, "command": "true"} + driver.store.save(first) + driver.recover(returncode=0, stdout="first") + + second = driver.state + second.in_flight = {"index": 1, "command": "false"} + driver.store.save(second) + with pytest.raises(ValueError, match="step identity is required"): + driver.recover(returncode=0, stdout="stale") + + recovered = driver.recover(returncode=0, stdout="stale", step=1) + assert recovered.index == 1 + + +def test_recovery_rejects_inconsistent_completed_checkpoints(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true", "true"]) + state = driver.state + state.next_step = 1 + state.in_flight = {"index": 1, "command": "true"} + driver.store.save(state) + + with pytest.raises(ValueError, match="invalid completed checkpoints"): + driver.recover(returncode=0) + + +def test_launch_failure_preserves_recovery_intent_across_restart( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["printf x >> side-effect.txt"]) + + def fail_to_launch(*_args: object, **_kwargs: object) -> object: + raise OSError("host shell unavailable") + + monkeypatch.setattr(driver_module, "_run_host_turn", fail_to_launch) + with pytest.raises(OSError, match="host shell unavailable"): + driver.next() + + restarted = CloudDriver(tmp_path) + assert restarted.state.in_flight == {"index": 0, "command": "printf x >> side-effect.txt"} + restarted.recover(returncode=1, stderr="launch failed") + assert CloudDriver(tmp_path).next() is None + assert not (tmp_path / "side-effect.txt").exists() + + +def test_host_turn_accepts_empty_and_exact_limit_bytes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true", "true"]) + results = iter( + [ + (0, b"", b"", False), + (0, b"x" * MAX_OUTPUT_BYTES, b"", False), + ] + ) + monkeypatch.setattr(driver_module, "_run_host_turn", lambda *_args, **_kwargs: next(results)) + + empty = driver.next() + exact = driver.next() + + assert empty is not None and empty.returncode == 0 + assert exact is not None and exact.returncode == 0 + assert len(exact.stdout.encode("utf-8")) == MAX_OUTPUT_BYTES + + +def test_recovery_applies_the_same_output_ceiling_as_execution(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + state = driver.state + state.in_flight = {"index": 0, "command": "true"} + driver.store.save(state) + + recovered = driver.recover(returncode=0, stdout="x" * (MAX_OUTPUT_BYTES + 1)) + + assert recovered.returncode == 125 + assert len(recovered.stdout.encode("utf-8")) <= MAX_OUTPUT_BYTES + assert "resource ceiling" in recovered.stderr + driver.record_evidence("observed", "recovered", step=0) + assert not driver.verify() + + +@pytest.mark.parametrize("crash_index", [0, 1, 2]) +def test_recovery_preserves_exactly_once_cursor_across_each_step( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, crash_index: int +) -> None: + driver = CloudDriver(tmp_path) + commands = [f"printf {index} >> steps.txt" for index in range(3)] + driver.plan(commands) + for _ in range(crash_index): + assert driver.next() is not None + + def crash_after_side_effect(*_args: object, **_kwargs: object) -> object: + with (tmp_path / "steps.txt").open("a", encoding="utf-8") as stream: + stream.write(str(crash_index)) + raise KeyboardInterrupt + + monkeypatch.setattr(driver_module, "_run_host_turn", crash_after_side_effect) + with pytest.raises(KeyboardInterrupt): + driver.next() + monkeypatch.undo() + + restarted = CloudDriver(tmp_path) + restarted.recover(returncode=0, step=crash_index) + while restarted.next() is not None: + pass + assert (tmp_path / "steps.txt").read_text(encoding="utf-8") == "012" + + +def test_state_rejects_in_flight_step_that_does_not_match_cursor(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + driver.store.path.write_text( + json.dumps( + { + "plan": ["true"], + "next_step": 0, + "in_flight": {"index": 1, "command": "true"}, + } + ), + encoding="utf-8", + ) + + with pytest.raises(ValueError, match="in-flight step index"): + driver.store.load() + + +def test_verify_rejects_whitespace_only_evidence(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + assert driver.next() is not None + driver.record_evidence("command", " \n\t ") + + assert not driver.verify() + + +def test_verify_rejects_empty_required_step_evidence(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + result = driver.next() + assert result is not None and result.returncode == 0 + + assert not driver.verify() + receipt = driver.state.verification_receipts[-1] + assert receipt["missing_evidence_steps"] == [0] + + +def test_verify_rejects_evidence_without_required_step(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + driver.record_evidence("unscoped", "observed", step=None) + result = driver.next() + assert result is not None and result.returncode == 0 + + assert not driver.verify() + assert driver.state.verification_receipts[-1]["missing_evidence_steps"] == [0] + + +def test_verify_rejects_failed_step_even_with_evidence(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["false"]) + result = driver.next() + assert result is not None and result.returncode != 0 + driver.record_evidence("command", "observed failure") + + assert not driver.verify() + receipt = driver.state.verification_receipts[-1] + assert receipt["failed_steps"] == [0] + + +def test_verify_rejects_empty_step_evidence(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + result = driver.next() + assert result is not None and result.returncode == 0 + driver.record_evidence("command", "") + + assert not driver.verify() + assert driver.state.verification_receipts[-1]["missing_evidence_steps"] == [0] + + +def test_verify_rejects_forged_checkpoint_index(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + assert driver.next() is not None + state = driver.state + state.checkpoints[0]["index"] = 99 + driver.store.save(state) + driver.record_evidence("command", "observed", step=0) + + assert not driver.verify() + assert driver.state.verification_receipts[-1]["invalid_checkpoints"] == [0] + + +def test_verify_rejects_forged_checkpoint_next_step(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + assert driver.next() is not None + state = driver.state + state.checkpoints[0]["next_step"] = 99 + driver.store.save(state) + driver.record_evidence("command", "observed", step=0) + + assert not driver.verify() + assert driver.state.verification_receipts[-1]["invalid_checkpoints"] == [0] + + +def test_state_rejects_malformed_version_and_empty_plan_command(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + state_path = driver.store.path + + state_path.write_text(json.dumps({"version": "1"}), encoding="utf-8") + with pytest.raises(ValueError, match="unsupported cloud state version"): + driver.store.load() + + state_path.write_text(json.dumps({"plan": [" "]}), encoding="utf-8") + with pytest.raises(ValueError, match="non-empty strings"): + driver.store.load() + + +def test_state_rejects_non_list_evidence(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + driver.store.path.write_text( + json.dumps({"plan": ["true"], "evidence": {"name": "bad"}}), encoding="utf-8" + ) + + with pytest.raises(ValueError, match="evidence must be a list"): + driver.store.load() + + +def test_record_evidence_rejects_step_outside_plan(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + + with pytest.raises(ValueError, match="outside the planned steps"): + driver.record_evidence("command", "observed", step=1) + + +def test_state_directory_checkpoint_must_be_a_regular_file(tmp_path: Path) -> None: + root = tmp_path / ".ouroboros-cloud" + root.mkdir() + (root / "state.json").mkdir() + + with pytest.raises(ValueError, match="regular file"): + CloudStateStore(tmp_path).load() + + +def test_state_store_does_not_persist_an_invalid_mutated_state(tmp_path: Path) -> None: + store = CloudStateStore(tmp_path) + store.initialize() + state = store.load() + state.plan = [1] # type: ignore[list-item] + + with pytest.raises(ValueError, match="cloud plan"): + store.save(state) + assert store.load().plan == [] + + +def test_state_decoder_fuzz_keeps_malformed_inputs_bounded() -> None: + """Random field corruption must reject cleanly or round-trip stably.""" + randomizer = random.Random(3129) + baseline = { + "version": 1, + "seed": "seed", + "git_base_revision": None, + "git_branch": None, + "git_untracked_paths": [], + "plan": ["true"], + "next_step": 0, + "evidence": [], + "checkpoints": [], + "active_step": None, + "execution_approved": True, + "verification_receipts": [], + } + values: tuple[object, ...] = ( + None, + True, + False, + -1, + 2**80, + "", + "mutated", + [], + ["true"], + {}, + {"nested": [True, None]}, + ) + + for _ in range(256): + candidate = dict(baseline) + candidate[randomizer.choice(tuple(baseline))] = randomizer.choice(values) + try: + restored = CloudState.from_dict(candidate) + except ValueError: + continue + assert restored.to_dict() == candidate + + +def test_bundle_import_rejects_bootstrap_symlink_before_replacing_state( + tmp_path: Path, +) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + destination.mkdir() + CloudDriver(source).init("new") + bundle = export_bundle(source, tmp_path / "run.tar.gz") + + old_state = CloudDriver(destination).init("old") + expected = old_state.to_dict() + outside = tmp_path / "outside.sh" + outside.write_text("leave me", encoding="utf-8") + (destination / "bootstrap.sh").symlink_to(outside) + + with pytest.raises(ValueError, match="regular file"): + import_bundle(bundle, destination) + assert CloudStateStore(destination).load().to_dict() == expected + assert outside.read_text(encoding="utf-8") == "leave me" + + +def test_bundle_import_rejects_dangling_state_directory_symlink( + tmp_path: Path, +) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + destination.mkdir() + CloudDriver(source).init("safe") + bundle = export_bundle(source, tmp_path / "run.tar.gz") + + (destination / ".ouroboros-cloud").symlink_to(tmp_path / "missing-state") + + with pytest.raises(ValueError, match="symlink"): + import_bundle(bundle, destination) + + +def test_bundle_import_rejects_tampered_bootstrap_payload(tmp_path: Path) -> None: + source = tmp_path / "source" + destination = tmp_path / "destination" + source.mkdir() + destination.mkdir() + CloudDriver(source).init("safe") + bundle = export_bundle(source, tmp_path / "run.tar.gz") + + tampered = tmp_path / "tampered.tar.gz" + with tarfile.open(bundle, "r:gz") as reader, tarfile.open(tampered, "w:gz") as writer: + members: dict[str, bytes] = {} + for member in reader.getmembers(): + payload = reader.extractfile(member) + assert payload is not None + members[member.name] = payload.read() + members["bootstrap.sh"] = b"#!/bin/sh\necho tampered\n" + manifest = json.loads(members[".ouroboros-cloud/manifest.json"]) + manifest["files"]["bootstrap.sh"] = { + "sha256": bundle_module._checksum(members["bootstrap.sh"]), + "size": len(members["bootstrap.sh"]), + } + members[".ouroboros-cloud/manifest.json"] = ( + json.dumps(manifest, indent=2, sort_keys=True) + "\n" + ).encode("utf-8") + for name, payload in members.items(): + info = tarfile.TarInfo(name) + info.size = len(payload) + writer.addfile(info, io.BytesIO(payload)) + + with pytest.raises(ValueError, match="bootstrap payload"): + import_bundle(tampered, destination) + assert not (destination / ".ouroboros-cloud" / "state.json").exists() + + +def test_record_evidence_rejects_non_integer_step(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + + try: + driver.record_evidence("command", "observed", step="0") # type: ignore[arg-type] + except ValueError as exc: + assert "non-negative integer" in str(exc) + else: + raise AssertionError("non-integer evidence step was accepted") + + +def test_record_evidence_rejects_non_string_name(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + + with pytest.raises(ValueError, match="name must not be empty"): + driver.record_evidence(None, "observed") # type: ignore[arg-type] + + +def test_record_evidence_rejects_non_standard_json_numbers(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + + with pytest.raises(ValueError, match="JSON serializable"): + driver.record_evidence("nan", float("nan")) + + +def test_state_file_has_a_bounded_read_size(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.init() + driver.store.path.write_bytes(b"{" + b"x" * MAX_STATE_BYTES + b"}") + + with pytest.raises(ValueError, match=f"{MAX_STATE_BYTES}-byte resource ceiling"): + driver.store.load() + + +def test_record_evidence_can_target_a_specific_step(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true", "true"]) + assert driver.next() is not None + assert driver.next() is not None + driver.record_evidence("first", "ok", step=0) + driver.record_evidence("second", "ok", step=1) + + assert driver.verify() + + +def test_record_evidence_name_has_a_resource_ceiling(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + driver.next() + + with pytest.raises(ValueError, match=f"{MAX_EVIDENCE_NAME_BYTES}-byte resource ceiling"): + driver.record_evidence("n" * (MAX_EVIDENCE_NAME_BYTES + 1), "observed", step=0) + + +def test_record_evidence_rejects_uncompleted_step(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true", "true"]) + assert driver.next() is not None + + with pytest.raises(ValueError, match="has not completed"): + driver.record_evidence("future", "observed", step=1) + + +def test_concurrent_next_calls_serialize_the_state_cursor(tmp_path: Path) -> None: + if not Path("/bin/sh").exists(): + pytest.skip("cloud host-turn execution requires /bin/sh") + driver = CloudDriver(tmp_path) + step_count = 24 + driver.plan(["sleep 0.01; printf x >> output.txt"] * step_count) + + def drain() -> list[int]: + worker = CloudDriver(tmp_path) + indexes: list[int] = [] + while True: + result = worker.next() + if result is None: + return indexes + indexes.append(result.index) + + with ThreadPoolExecutor(max_workers=4) as pool: + results = [future.result() for future in (pool.submit(drain) for _ in range(4))] + + indexes = [index for worker_indexes in results for index in worker_indexes] + assert sorted(indexes) == list(range(step_count)) + assert CloudDriver(tmp_path).state.next_step == step_count + assert (tmp_path / "output.txt").read_text(encoding="utf-8") == "x" * step_count + + +def test_verify_retains_bounded_receipt_history(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + assert driver.next() is not None + driver.record_evidence("command", "observed") + + for _ in range(_MAX_VERIFICATION_RECEIPTS + 8): + assert driver.verify() + + state = driver.state + assert len(state.verification_receipts) == _MAX_VERIFICATION_RECEIPTS + + +def test_default_workspace_is_current_directory(tmp_path: Path, monkeypatch) -> None: + monkeypatch.chdir(tmp_path) + facts = detect_environment(environ={"HOME": str(tmp_path)}) + assert facts.workspace == tmp_path + + +def test_plan_and_evidence_have_explicit_resource_ceilings(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + + with pytest.raises(ValueError, match=f"at most {MAX_PLAN_STEPS}"): + driver.plan(["true"] * (MAX_PLAN_STEPS + 1)) + with pytest.raises(ValueError, match=f"{MAX_COMMAND_BYTES}-byte resource ceiling"): + driver.plan(["x" * (MAX_COMMAND_BYTES + 1)]) + + driver.plan(["true"]) + with pytest.raises(ValueError, match=f"{MAX_EVIDENCE_VALUE_BYTES}-byte resource ceiling"): + driver.record_evidence("large", "x" * MAX_EVIDENCE_VALUE_BYTES) + driver.next() + for index in range(MAX_EVIDENCE_RECORDS): + driver.record_evidence(f"evidence-{index}", "ok", step=0) + with pytest.raises(ValueError, match=f"at most {MAX_EVIDENCE_RECORDS}"): + driver.record_evidence("overflow", "ok", step=0) + + +def test_step_output_is_bounded_and_verification_fails(tmp_path: Path, monkeypatch) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + + monkeypatch.setattr( + driver_module, + "_run_host_turn", + lambda *_args, **_kwargs: (0, b"x" * (MAX_OUTPUT_BYTES + 1), b"", False), + ) + result = driver.next() + + assert result is not None + assert result.returncode == 125 + assert len(result.stdout.encode()) <= MAX_OUTPUT_BYTES + assert "resource ceiling" in result.stderr + driver.record_evidence("output", "observed", step=0) + assert not driver.verify() + + +def test_step_timeout_is_recorded_as_a_failed_checkpoint(tmp_path: Path, monkeypatch) -> None: + driver = CloudDriver(tmp_path, step_timeout=0.01) + driver.plan(["sleep 1"]) + + def timed_out(*_args, **_kwargs): + raise subprocess.TimeoutExpired("/bin/sh", 0.01, output="partial", stderr="waiting") + + monkeypatch.setattr(driver_module, "_run_host_turn", timed_out) + result = driver.next() + + assert result is not None + assert result.returncode == 124 + assert "0.01-second timeout" in result.stderr + driver.record_evidence("timeout", "observed", step=0) + assert not driver.verify() + + +def test_windows_host_turn_uses_comspec(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(driver_module.os, "name", "nt") + + assert driver_module._host_turn_argv( + "echo hello", {"COMSPEC": r"C:\\Windows\\System32\\cmd.exe"} + ) == [r"C:\\Windows\\System32\\cmd.exe", "/d", "/s", "/c", "echo hello"] + + +@pytest.mark.skipif( + not Path("/bin/sh").exists(), reason="cloud host-turn execution requires /bin/sh" +) +def test_host_turn_does_not_wait_for_detached_pipe_holders(tmp_path: Path) -> None: + # Leave enough scheduling margin for process creation on loaded CI hosts; + # the assertion below still proves the detached holder is not awaited. + driver = CloudDriver(tmp_path, step_timeout=0.2) + driver.plan(["sleep 0.5 &"]) + + started = monotonic() + result = driver.next() + elapsed = monotonic() - started + + assert result is not None and result.returncode == 0 + assert elapsed < 0.5 + + +def test_cloud_child_environment_rejects_symlinked_local_directory(tmp_path: Path) -> None: + driver = CloudDriver(tmp_path) + driver.plan(["true"]) + outside = tmp_path / "outside" + outside.mkdir() + (tmp_path / ".ouroboros-cloud" / "home").symlink_to(outside, target_is_directory=True) + + with pytest.raises(RuntimeError, match="cloud child directory"): + driver.next() + + +def test_lock_backpressure_has_a_bounded_wait(tmp_path: Path) -> None: + store = CloudStateStore(tmp_path, lock_timeout=0.01) + with store.lock(): + probe = subprocess.run( + [ + sys.executable, + "-c", + ( + "from ouroboros.cloud.state import CloudStateStore\n" + "import sys\n" + "store = CloudStateStore(sys.argv[1], lock_timeout=0.01)\n" + "with store.lock():\n" + " store.load()\n" + ), + str(tmp_path), + ], + capture_output=True, + text=True, + check=False, + ) + assert probe.returncode != 0 + assert "CloudStateLockTimeout" in probe.stderr + assert DEFAULT_LOCK_TIMEOUT_SECONDS > 0 diff --git a/tests/unit/mcp/tools/test_citation_check.py b/tests/unit/mcp/tools/test_citation_check.py index 52f970ba93..068750c1dc 100644 --- a/tests/unit/mcp/tools/test_citation_check.py +++ b/tests/unit/mcp/tools/test_citation_check.py @@ -84,14 +84,26 @@ def test_redirect_limit_closes_unread_response() -> None: def test_rejected_head_is_closed_before_ranged_get(status: int) -> None: error = HTTPError("https://example.test/0", status, "HEAD rejected", {}, None) response = MagicMock() + events: list[str] = [] + + def open_request(request: Request, **_kwargs: object) -> object: + events.append(f"open:{request.get_method()}") + if request.get_method() == "HEAD": + raise error + return response + + def close_error() -> None: + events.append("close") + HTTPError.close(error) + with ( - patch("urllib.request.OpenerDirector.open", side_effect=[error, response]) as open_request, - patch.object(error, "close", wraps=error.close) as close, + patch("urllib.request.OpenerDirector.open", side_effect=open_request) as open_mock, + patch.object(error, "close", side_effect=close_error) as close, ): assert _default_fetch("https://example.test/0", 1.0) is True close.assert_called_once() - assert open_request.call_args_list[1].args[0].get_method() == "GET" - assert open_request.call_args_list[1].args[0].get_header("Range") == "bytes=0-0" + assert events == ["open:HEAD", "close", "open:GET"] + assert open_mock.call_args_list[1].args[0].get_header("Range") == "bytes=0-0" def test_not_found_is_closed_and_not_verified() -> None: