From 0fea8efea22aac0d4f06e4f5005893b4b5406d63 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 03:16:22 +0900 Subject: [PATCH 01/41] feat: add VM personal-agent runtime adapter --- README.md | 1 + STATUS.md | 15 + docs/getting-started.md | 3 +- docs/runtime-guides/grok-bot.md | 78 ++ docs/runtime-guides/grok.md | 4 + docs/runtime-guides/host.md | 5 + docs/runtime-guides/personal-agent-host.md | 156 +++ docs/runtime-guides/vm-personal-agent.md | 60 ++ docs/verification/grok-bot-host-adapter.md | 57 ++ docs/verification/grok-bot-public-surface.md | 71 ++ src/ouroboros/integrations/__init__.py | 84 ++ .../integrations/personal_agent_host.py | 943 ++++++++++++++++++ .../integrations/vm_agent_profile.py | 88 ++ .../integrations/vm_agent_runtime.py | 856 ++++++++++++++++ .../host/test_personal_agent_host.py | 278 ++++++ .../integrations/test_personal_agent_host.py | 131 +++ .../integrations/test_vm_agent_runtime.py | 395 ++++++++ 17 files changed, 3224 insertions(+), 1 deletion(-) create mode 100644 STATUS.md create mode 100644 docs/runtime-guides/grok-bot.md create mode 100644 docs/runtime-guides/personal-agent-host.md create mode 100644 docs/runtime-guides/vm-personal-agent.md create mode 100644 docs/verification/grok-bot-host-adapter.md create mode 100644 docs/verification/grok-bot-public-surface.md create mode 100644 src/ouroboros/integrations/__init__.py create mode 100644 src/ouroboros/integrations/personal_agent_host.py create mode 100644 src/ouroboros/integrations/vm_agent_profile.py create mode 100644 src/ouroboros/integrations/vm_agent_runtime.py create mode 100644 tests/integration/host/test_personal_agent_host.py create mode 100644 tests/unit/integrations/test_personal_agent_host.py create mode 100644 tests/unit/integrations/test_vm_agent_runtime.py diff --git a/README.md b/README.md index ae16d75271..5658e6102c 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,7 @@ agent host. The full command list is in [GJC](./docs/runtime-guides/gjc.md) · [Antigravity CLI](./docs/runtime-guides/antigravity.md) · [Grok Build CLI](./docs/runtime-guides/grok.md) · +[Grok Bot host](./docs/runtime-guides/grok-bot.md) · [DeepSeek Harness](./docs/guides/deepseek-harness.md) The installer connects the ones you have; the console's **Connect** page diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 0000000000..d3a863b26a --- /dev/null +++ b/STATUS.md @@ -0,0 +1,15 @@ +# Ouroboros + +## 🗺️ 단계 / 로드맵 +- [x] 1단계: 기준 호스트 어댑터와 검증 자료 확인 +- [x] 2단계: VM Personal-Agent Runtime과 Grokbot VM 프로필 구현 +- [x] 3단계: 단위 테스트와 보안·복구 시나리오 검증 +- [ ] 👉 4단계: 전체 게이트 확인과 초안 PR 갱신 (현재 위치) + +## 🛑 블로커 +- 블로커: 없음 + +## 🤖 AI 실행 맥락 +- 마지막 커밋: 9c3c9dfb (VM personal-agent runtime adapter) +- 지금 손댄 파일: STATUS.md, Draft PR 메타데이터 +- 다음 할 일: Draft PR 생성 후 CI와 전체 pytest 결과를 기록하고 live Grokbot 미검증 범위를 유지 diff --git a/docs/getting-started.md b/docs/getting-started.md index ab9ae92c69..3e34b2a41f 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -636,6 +636,7 @@ For backend-specific configuration: - [Pi CLI runtime guide](runtime-guides/pi.md) - [OMP CLI runtime guide](runtime-guides/omp.md) - [Pi JSON mode documentation](https://pi.dev/docs/latest/json) +- [Personal-agent host adapter](runtime-guides/personal-agent-host.md) · [Grok Bot host](runtime-guides/grok-bot.md) ### Every supported host @@ -653,7 +654,7 @@ DeepSeek works in both directions: as the LLM backend for the interview, Seed and QA pipeline, and as a host through the installable `dsh-ouroboros` plugin. See the [DeepSeek Harness guide](guides/deepseek-harness.md). -The other runtime guides: [Hermes](runtime-guides/hermes.md) · [Gemini CLI](runtime-guides/gemini.md) · [Zcode](runtime-guides/zcode.md) · [Goose](runtime-guides/goose.md) · [GJC](runtime-guides/gjc.md) · [Antigravity CLI](runtime-guides/antigravity.md) · [Grok Build CLI](runtime-guides/grok.md) · [GitHub Copilot ACP](runtime-guides/copilot-acp.md) · [Megacode harness](runtime-guides/megacode.md) · [Host-driven execution](runtime-guides/host.md) +The other runtime guides: [Hermes](runtime-guides/hermes.md) · [Gemini CLI](runtime-guides/gemini.md) · [Zcode](runtime-guides/zcode.md) · [Goose](runtime-guides/goose.md) · [GJC](runtime-guides/gjc.md) · [Antigravity CLI](runtime-guides/antigravity.md) · [Grok Build CLI](runtime-guides/grok.md) · [Grok Bot host](runtime-guides/grok-bot.md) · [Personal-agent host adapter](runtime-guides/personal-agent-host.md) · [GitHub Copilot ACP](runtime-guides/copilot-acp.md) · [Megacode harness](runtime-guides/megacode.md) · [Host-driven execution](runtime-guides/host.md) --- diff --git a/docs/runtime-guides/grok-bot.md b/docs/runtime-guides/grok-bot.md new file mode 100644 index 0000000000..05c4c14caf --- /dev/null +++ b/docs/runtime-guides/grok-bot.md @@ -0,0 +1,78 @@ +# Grok Bot host (public MCP contract) + +This is separate from the [Grok Build CLI runtime](grok.md). The CLI runtime +starts a local `grok -p` subprocess and is selected with `--runtime grok`. +Grok Bot is a personal-agent host: it may call a public MCP connector and may +run work on its own cloud computer. For the latter, Ouroboros uses +`--runtime host` and the reusable +[personal-agent host adapter](personal-agent-host.md). + +## Confirmed public surface + +As checked on 2026-11-28, the official documentation says: + +- Bots use a persistent cloud computer with a browser, command line, and + filesystem; files, sign-ins, and command-line credentials are shared by Bots + on the account. See [Use the computer and apps](https://docs.x.ai/grok-bot/computer-and-apps). +- A custom MCP server can be added by URL or by a command that runs on the Bot + computer. The desktop connector UI supports Remote HTTPS and Command types. + See the same [computer and apps guide](https://docs.x.ai/grok-bot/computer-and-apps). +- A custom MCP connector can be entered at `grok.com/connectors`; the official + connector guide says the server URL must be reachable over the public + internet and may require tunneling and authentication. See + [Connectors](https://docs.x.ai/grok/connectors). +- Business/Enterprise teams may require an administrator to provision the + connector. See [Connector Management](https://docs.x.ai/grok/connector-management). +- Desktop command execution is user-controlled and normally asks for approval; + Grok Bot's own work runs on its cloud computer. See [the FAQ](https://docs.x.ai/grok-bot/faq). + +These facts are enough to define a public-MCP integration boundary. They do +not define a stable external API that lets this repository submit a message to +a particular user's Bot or receive a Bot callback. No such private API is +implemented or implied here. + +## Candidate deployment shapes + +### Remote HTTPS custom connector + +Run `ouroboros mcp serve --runtime host --transport streamable-http` behind an +authenticated HTTPS endpoint and register that endpoint as a custom MCP +connector. The endpoint and its workspace must be designed so the worker path +returned by Ouroboros is accessible to the host. A local-only URL is not +enough for the cloud Bot; follow the official tunneling and authentication +requirements. + +### Command custom connector + +The official UI documents a command connector that runs on the Bot computer. +That could co-locate the MCP server and its workspace, but the exact command +environment, Python/`uv` availability, long-running process behavior, auth +headers, and lifecycle semantics were not available for an unauthenticated +end-to-end test. Treat this as an operator experiment, not a repository +guarantee. The adapter does not install or wrap a `grok` executable. + +## Explicit user flow + +Configure the host-side skill or instruction to call the adapter only for a +message beginning with `/ouroboros` (or the documented `ooo auto` alias). The +adapter then calls `ouroboros_start_auto`; it does not inspect or intercept +ordinary Bot messages. The host must pump `ouroboros_job_wait`, execute each +announced worker using its native capability, submit the result, and return the +receipt's Seed/execution/evaluation/verification evidence to the user. + +The fake-host integration test proves this complete contract without claiming +that it is a live Grok Bot connection: + +```bash +uv run pytest -q tests/unit/integrations/test_personal_agent_host.py \ + tests/integration/host/test_personal_agent_host.py +``` + +## Not verified + +No authenticated Grok Bot account, connector, or public callback endpoint was +available in the development session. The computer/browser inventory exposed +only the Codex MCP Apps and in-app browser surfaces, so no live Bot message or +connector mutation was attempted. The repository therefore reports this +adapter as a tested public-contract/fake-host path, not as a completed +platform E2E connection. diff --git a/docs/runtime-guides/grok.md b/docs/runtime-guides/grok.md index 3682a439ea..d25fc4f0bb 100644 --- a/docs/runtime-guides/grok.md +++ b/docs/runtime-guides/grok.md @@ -1,5 +1,9 @@ # Grok Build CLI Runtime +This guide is for the local Grok Build CLI subprocess runtime. It is **not** +the Grok Bot personal-agent host. For the latter, see the [Grok Bot host +guide](grok-bot.md) and the reusable [personal-agent host contract](personal-agent-host.md). + Run Ouroboros workflows on top of the locally installed xAI **Grok Build** CLI (the `grok` binary). diff --git a/docs/runtime-guides/host.md b/docs/runtime-guides/host.md index 66ff085b7c..5a369bf509 100644 --- a/docs/runtime-guides/host.md +++ b/docs/runtime-guides/host.md @@ -1,5 +1,10 @@ # Host-driven execution runtime +For a personal-agent host (including the currently unverified Grok Bot public +MCP surface), see the reusable [personal-agent host adapter](personal-agent-host.md) +and its [Grok Bot evidence](grok-bot.md). This guide remains the lower-level +generic `host` runtime contract. + The `host` agent runtime delegates execution to the calling MCP host instead of spawning an external CLI. It is intended for hosts such as DeepSeek Harness that can spawn their own subagents but do not expose an installable execution diff --git a/docs/runtime-guides/personal-agent-host.md b/docs/runtime-guides/personal-agent-host.md new file mode 100644 index 0000000000..8978b0b988 --- /dev/null +++ b/docs/runtime-guides/personal-agent-host.md @@ -0,0 +1,156 @@ +# Personal-agent host adapter + +This guide describes the optional host contract for a personal agent such as +Grok Bot. It is a host-facing access layer over Ouroboros's existing MCP +tools; it is not another agent runtime and it does not replace the local Grok +Build CLI runtime. + +The implementation is in +[`ouroboros.integrations.personal_agent_host`](../../src/ouroboros/integrations/personal_agent_host.py). +It is deliberately platform-neutral so another personal agent or a cloud host +can implement the same contract without importing a private platform SDK. + +## Boundary and explicit invocation + +The adapter claims only messages that begin with an exact explicit prefix: + +```text +/ouroboros +ooo auto +``` + +To resume a persisted Auto session: + +```text +/ouroboros resume +ooo auto --resume +``` + +Every other message returns `None` from `start()` and causes no MCP call. +Consequently ordinary conversation, memory, search, mail, calendar, booking, +and scheduled work do not enter Ouroboros automatically. The host must also +keep the adapter behind its own explicit user-command or skill boundary. + +## What is reused + +An explicit request follows the existing job-tracked path: + +```text +personal-agent message + -> ouroboros_start_auto + -> interview / intent refinement / Seed generation + -> existing execution and server-side evaluation/verification + -> ouroboros_job_wait + -> pending_host_dispatches (when runtime=host) + -> host runs the supplied worker prompt in the supplied workspace + -> ouroboros_submit_fanout_results + -> ouroboros_job_wait / ouroboros_job_result +``` + +The minimum negotiated tool set is: + +| Tool | Responsibility | +| --- | --- | +| `ouroboros_start_auto` | Create or resume the durable Auto session and job | +| `ouroboros_job_wait` | Poll state and receive one-shot host dispatch announcements | +| `ouroboros_submit_fanout_results` | Return the worker result through the existing correlation and validation guards | +| `ouroboros_job_result` | Fetch the terminal result and verification evidence | + +`PersonalAgentHostAdapter.negotiate()` checks this set before a host claims +support. `MCPToolTransport` accepts either an Ouroboros MCP adapter, an MCP SDK +client wrapper, or an async callable, so the optional integration does not add +an MCP SDK dependency to the base package. + +## Host-side lifecycle + +The smallest host implementation is equivalent to: + +```python +from ouroboros.integrations import GrokBotHostAdapter, MCPToolTransport + +adapter = GrokBotHostAdapter(MCPToolTransport(mcp_client)) +receipt = await adapter.start( + message, + host_session_id=host_conversation_id, + cwd=host_workspace, +) +if receipt is not None: + while not receipt.is_terminal: + receipt = await adapter.wait(receipt) + for dispatch in receipt.pending_host_dispatches: + # The host's native worker/subagent executes this exact prompt in + # dispatch.working_directory, then returns its final output. + worker_output = await run_native_worker( + dispatch.prompt, + cwd=dispatch.working_directory, + ) + receipt = await adapter.submit_dispatch(receipt, dispatch, worker_output) + receipt = await adapter.result(receipt) + show_to_user(receipt.to_dict()) +``` + +The example is an adapter contract, not a new local CLI or a claim about a +Grok Bot extension API. A host that cannot spawn a worker must submit +`undispatched=True`; it must not invent output. A stale, malformed, or +correlation-mismatched dispatch is rejected and must not be replayed. + +The receipt records the host name, request ID, host session ID, Auto session ID, +job ID, cursor, current state, pending dispatch identity, Seed, execution, +evaluation, verification, failure, recovery, and a resume call. Unknown server +fields remain in `state` for forward compatibility. + +## Runtime and execution location + +For this adapter the MCP server must select the existing host-driven runtime: + +```bash +export OUROBOROS_MCP_AUTH_TOKEN='set-this-outside-the-repository' +ouroboros mcp serve --runtime host \ + --transport streamable-http \ + --host 0.0.0.0 \ + --port 8080 \ + --allowed-host ouroboros.example.com \ + --allow-remote \ + --workspace-root /path/to/allowed/workspace +``` + +Use a secret manager or environment injection for the token; never put a real +token in a seed, source file, shell transcript, or Git commit. Restrict +`--workspace-root` to the smallest allowed project tree. The network MCP +server's authenticated process owns the live host-dispatch waiter. The worker +must be able to access the exact `working_directory` returned in +`pending_host_dispatches`; an HTTP connection alone does not synchronize two +unrelated filesystems. + +The existing host runtime intentionally rejects direct terminal +`ouroboros run`, direct `ouroboros_execute_seed`, and Evolve/Ralph jobs that do +not carry a session scope. Use the job-tracked MCP path above. A host that needs +Ralph/evolution must select an executable runtime for that stage until the +existing session-scope limitation is removed. + +## Recovery and failure handling + +- Persist `auto_session_id`, `job_id`, and the latest `cursor` after every + response. +- Resume with `ouroboros_start_auto` and `{"resume": ""}`; + do not start a new goal when recovering an existing session. +- Poll `ouroboros_job_wait` after a transport or host restart. Persisted Auto + and fan-out records survive, but the in-process live waiter belongs to the + serving MCP process. +- A lost or expired dispatch results in a fresh dispatch ID on retry. Never + replay a prior `dispatch_id` after it is reported stale. +- Preserve terminal `failure` and `recovery` fields and show verification + evidence from the receipt. A worker failure is not a successful empty result. + +## Grok Bot deployment status + +The official Grok Bot documentation currently describes a persistent cloud +computer with command line/filesystem access and a custom MCP connector that +discovers tools from a reachable server. It also documents a command-based +custom connector. Those public surfaces make the MCP contract a plausible +integration boundary, but this repository does not assume an undocumented Bot +callback, private message API, or hidden filesystem mount. + +See [the Grok Bot-specific evidence and setup notes](grok-bot.md) and the +[public-surface verification record](../verification/grok-bot-public-surface.md) +for the exact confirmed and unconfirmed conditions. diff --git a/docs/runtime-guides/vm-personal-agent.md b/docs/runtime-guides/vm-personal-agent.md new file mode 100644 index 0000000000..0faa4f21df --- /dev/null +++ b/docs/runtime-guides/vm-personal-agent.md @@ -0,0 +1,60 @@ +# VM personal-agent runtime + +`VMPersonalAgentRuntime` is the reusable worker bridge for a personal agent +that owns a Linux VM, container, or command sandbox. It is independent of the +agent's model provider and supports two public transport shapes: + +- `CommandVMTransport` for an async shell or command runner; +- `MCPVMTransport` for a public MCP command/turn tool. + +The runtime maps an approved host workspace to the VM workspace, persists a +structured receipt for each `session_id` and `dispatch_id`, and records output, +exit status, execution IDs, and artifact hashes. `JsonVMReceiptStore` can be +placed under the project’s `.ouroboros` state directory so a host restart can +find the previous receipt. + +Host dispatches may identify their working directory in either approved host +path notation or approved VM path notation. Both forms are canonicalized and +remain subject to the same workspace and symlink-escape checks. + +```python +from ouroboros.integrations import ( + CommandVMTransport, + JsonVMReceiptStore, + VMPersonalAgentRuntime, + VMWorkspaceMapper, +) + +runtime = VMPersonalAgentRuntime( + CommandVMTransport(vm_command_client), + workspace=VMWorkspaceMapper("/srv/project", "/cloud/workspace"), + receipt_store=JsonVMReceiptStore("/srv/project/.ouroboros/vm-receipts"), +) +receipt = await runtime.execute_command( + "pytest -q", + dispatch_id=dispatch.dispatch_id, + session_id=dispatch.session_id, + host_workspace=dispatch.working_directory, +) +``` + +## Safety and recovery rules + +Only paths below the configured host root or VM root are accepted. Artifact +collection rejects path traversal and records metadata rather than copying +unknown files into the host process. + +The first request writes a `running` receipt before the transport is called. +If the transport returns an execution ID and the connection drops, a later +`resume_dispatch()` calls the transport’s resume operation. A completed +receipt is returned directly, and a receipt without a resumable execution ID +becomes `recovery_required`; the original command is never silently replayed. +Timeouts and transport disconnects remain visible in the receipt for the host +to report or recover. + +## Grok Bot profile + +`GROK_BOT_VM_PROFILE` describes the documented Grok Bot cloud-computer shell +and custom MCP connector surfaces. It is a profile, not a private xAI API +client, and `live_account_verified` remains `False` until a real account and +connector are tested by an operator. See the [Grok Bot guide](grok-bot.md). diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md new file mode 100644 index 0000000000..c057dc973c --- /dev/null +++ b/docs/verification/grok-bot-host-adapter.md @@ -0,0 +1,57 @@ +# Grok Bot host adapter verification log + +Date: 2026-11-29 (Asia/Seoul) + +This record covers the reusable personal-agent host contract implemented in +`ouroboros.integrations.personal_agent_host`. It deliberately distinguishes +the fake-host proof from a live Grok Bot connection. + +## Automated checks + +| Command | Result | +| --- | --- | +| `uv run ruff format src/ tests/` | Pass; 1,945 files unchanged | +| `uv run ruff check src/ tests/ --fix` | Pass | +| `uv run mypy src/ouroboros` | Pass; 816 source files | +| `uv run pytest -q tests/unit/integrations/test_personal_agent_host.py tests/integration/host/test_personal_agent_host.py` | Pass; 18 tests | +| `uv run --group mcp-test pytest -q tests/unit/docs/test_repo_paths.py::test_maintained_docs_name_only_existing_repository_paths tests/unit/test_dependencies_configured.py::test_mcp_serve_documentation_names_runtime_and_public_claude_aliases tests/unit/integrations/test_personal_agent_host.py tests/integration/host/test_personal_agent_host.py` | Pass; 20 tests | + +The fake-host integration covers ordinary-message rejection, explicit start, +resume, job polling, one-shot host dispatch, correlated result submission, +terminal Seed/execution/evaluation/verification evidence, and an +undispatched-worker failure with recovery metadata. + +## Existing-suite result + +The first plain `uv run pytest` attempt stopped during collection because the +environment did not have the repository's optional `mcp` package. The suite +was then run with its declared test group: + +```text +uv run --group mcp-test pytest -n 4 --dist loadgroup +``` + +That run collected 39,083 tests and produced 38,126 passed, 954 skipped, 1 +expected failure, and 10 failures in 15:52. Two failures were documentation +contracts caused by the new guide and historical-path command; both were +fixed and the 20-test post-fix command above passed. The remaining eight +failures are outside this change and reproduce in a serial, targeted run: + +- two Python 3.14 cancellation/shielded-future assertions in + `tests/unit/boundary/test_base_regression.py`; +- two SQLite VM-step thresholds in + `tests/unit/dashboard_web/test_reader_readonly_uri.py`; +- the real Ralph chaining test waiting on an external Claude CLI/provider; +- two Copilot Anthropic model-id mapping assertions; +- the `PYTHONPLATLIBDIR` poison expectation in the skill-artifact test. + +No source or test files for those existing areas were changed. + +## Live platform check + +No authenticated Grok Bot account, connector, or Bot callback surface was +available in the development environment. The computer-use inventory exposed +only Codex MCP Apps and the in-app browser. No connector was mutated, no +message was sent, and no credential or external process was started. The +official public-surface evidence and the precise unverified conditions are in +[`grok-bot-public-surface.md`](grok-bot-public-surface.md). diff --git a/docs/verification/grok-bot-public-surface.md b/docs/verification/grok-bot-public-surface.md new file mode 100644 index 0000000000..0dadbe48e3 --- /dev/null +++ b/docs/verification/grok-bot-public-surface.md @@ -0,0 +1,71 @@ +# Grok Bot public-surface verification record + +Date: 2026-11-28 (Asia/Seoul) + +## Official sources checked + +| Source | Confirmed fact used by the implementation | +| --- | --- | +| [Use the computer and apps](https://docs.x.ai/grok-bot/computer-and-apps) | Persistent cloud computer; command line/filesystem; custom MCP server by URL or command; shared Bot account computer | +| [Connectors](https://docs.x.ai/grok/connectors) | Custom MCP connector; server URL and authentication; public reachability/tunneling requirement | +| [Connector Management](https://docs.x.ai/grok/connector-management) | Business/Enterprise admin provisioning and custom MCP URL flow | +| [Grok Bot FAQ](https://docs.x.ai/grok-bot/faq) | Cloud execution versus user-approved desktop execution; shared files/logins; background work | +| [xAI Tool Usage Details](https://docs.x.ai/developers/tools/tool-usage-details) | xAI API server-side MCP tool calls are a separate API surface, not evidence of a Grok Bot callback API | + +The docs support treating MCP as the public boundary. They do not document an +external request/callback API for sending a message to a named personal Bot +from this repository. That absence is recorded as an unverified condition, +not converted into an assumption. + +## Repository evidence + +The existing implementation was inspected before adding the adapter: + +- `src/ouroboros/orchestrator/grok_cli_runtime.py` is the Grok Build CLI + subprocess runtime (`grok -p`, streaming JSON, permission flags). It remains + untouched and is not used by the personal-agent adapter. +- `src/ouroboros/orchestrator/runtime_factory.py` already selects the generic + `host` backend. +- `src/ouroboros/orchestrator/host_dispatch.py` already provides durable + fan-out correlation, one-shot dispatch announcements, deadlines, stale + dispatch poisoning, and the server-side verification seam. +- `docs/runtime-guides/host.md` documents the existing + `start_execute_seed → job_wait → submit_fanout_results → verification` + lifecycle and its Evolve/Ralph limitation. +- `src/ouroboros/mcp/host_context.py` intentionally keeps host identity and + capability negotiation generic. The new adapter does not invent a Grok + client identity in that core module. + +Relevant history was checked with: + +```bash +git log --all --oneline -- src/ouroboros/orchestrator/grok_cli_runtime.py +git log --all --oneline -- src/ouroboros/orchestrator/host_dispatch.py +git log --all --oneline -- ':(glob)**/*openclaw*' +git log --all --oneline -S'ChatGPT Host' -- . +git log --all --oneline -S'chatgpt' -- . +``` + +The Grok CLI runtime was introduced by `9461dc5d`; host-driven execution by +`419df835`. The historical OpenClaw channel scaffold (`312aa16`) was removed +by `94d1e1fa` after the architecture moved toward native MCP/skill routing. +The ChatGPT search produced no matching current/history record in this +checkout, so no removed private bridge was reconstructed. + +## Live-access result + +No authenticated Grok Bot surface was available for a safe read-only or +end-to-end test. The available computer-use inventory contained no Grok Bot +application or authenticated Grok tab; only Codex MCP Apps and the in-app +browser were present. No connector was added, no message was sent, and no +credential or external process was started on the user's behalf. + +## Implemented proof instead + +The fake host transport in +`tests/integration/host/test_personal_agent_host.py` exercises the public +contract end to end: ordinary-message rejection, explicit `start_auto`, job +polling, pending dispatch extraction, correlated result submission, terminal +Seed/execution/evaluation/verification evidence, resume identity, and a +host-worker failure/recovery path. It is intentionally not labeled as a live +Grok test. diff --git a/src/ouroboros/integrations/__init__.py b/src/ouroboros/integrations/__init__.py new file mode 100644 index 0000000000..1535f502cf --- /dev/null +++ b/src/ouroboros/integrations/__init__.py @@ -0,0 +1,84 @@ +"""Optional integrations that sit outside the Ouroboros execution core. + +Integrations in this package adapt a host's public tool surface to existing +Ouroboros contracts. They must not make a platform SDK or a private host API +an installation-time dependency. +""" + +from ouroboros.integrations.personal_agent_host import ( + GROK_BOT_HOST_NAME, + HOST_ADAPTER_PROTOCOL, + REQUIRED_HOST_TOOLS, + GrokBotHostAdapter, + HostAdapterError, + HostCapabilityNegotiation, + HostExecutionReceipt, + HostInvocation, + HostSubmissionError, + HostToolResponse, + HostToolTransport, + MCPToolTransport, + PendingHostDispatch, + PersonalAgentHostAdapter, + normalize_tool_response, + parse_explicit_invocation, +) +from ouroboros.integrations.vm_agent_profile import ( + GROK_BOT_VM_PROFILE, + GrokBotVMProfile, + VMPersonalAgentProfile, +) +from ouroboros.integrations.vm_agent_runtime import ( + CommandVMTransport, + JsonVMReceiptStore, + MCPVMTransport, + MemoryVMReceiptStore, + VMArtifact, + VMCommandTransport, + VMExecutionReceipt, + VMExecutionRequest, + VMMCPTransport, + VMPathError, + VMPersonalAgentRuntime, + VMRuntimeError, + VMTransportDisconnected, + VMTransportError, + VMWorkspaceMapper, +) + +__all__ = [ + "GROK_BOT_HOST_NAME", + "HOST_ADAPTER_PROTOCOL", + "REQUIRED_HOST_TOOLS", + "GrokBotHostAdapter", + "HostAdapterError", + "HostCapabilityNegotiation", + "HostExecutionReceipt", + "HostInvocation", + "HostSubmissionError", + "HostToolResponse", + "HostToolTransport", + "MCPToolTransport", + "PendingHostDispatch", + "PersonalAgentHostAdapter", + "normalize_tool_response", + "parse_explicit_invocation", + "GROK_BOT_VM_PROFILE", + "GrokBotVMProfile", + "VMPersonalAgentProfile", + "CommandVMTransport", + "JsonVMReceiptStore", + "MCPVMTransport", + "MemoryVMReceiptStore", + "VMArtifact", + "VMCommandTransport", + "VMExecutionReceipt", + "VMExecutionRequest", + "VMMCPTransport", + "VMPersonalAgentRuntime", + "VMPathError", + "VMRuntimeError", + "VMTransportDisconnected", + "VMTransportError", + "VMWorkspaceMapper", +] diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py new file mode 100644 index 0000000000..55ad2095f8 --- /dev/null +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -0,0 +1,943 @@ +"""Explicit personal-agent host contract for Ouroboros. + +This module is a deliberately small adapter at the edge of the system. It +does not implement an agent loop, a provider client, or a platform-specific +callback API. A personal-agent host supplies a callable MCP tool transport; +the adapter then translates one *explicit* invocation into Ouroboros's +existing ``start_auto``/job lifecycle and host-driven dispatch contract. + +The Grok Build CLI runtime is intentionally not used here. That runtime owns +a local ``grok`` subprocess. This adapter instead assumes that the calling +host can reach the public Ouroboros MCP tools and, when the selected runtime is +``host``, can execute the worker described by ``pending_host_dispatches``. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, field, replace +import shlex +from typing import Any, Protocol +from uuid import uuid4 + +from ouroboros.integrations.vm_agent_profile import ( + GROK_BOT_VM_PROFILE, + GrokBotVMProfile, +) + +HOST_ADAPTER_PROTOCOL = "ouroboros.personal-agent-host/v1" +GROK_BOT_HOST_NAME = "grok_bot" + +START_AUTO_TOOL = "ouroboros_start_auto" +JOB_WAIT_TOOL = "ouroboros_job_wait" +JOB_RESULT_TOOL = "ouroboros_job_result" +CANCEL_JOB_TOOL = "ouroboros_cancel_job" +SUBMIT_FANOUT_TOOL = "ouroboros_submit_fanout_results" + +REQUIRED_HOST_TOOLS: tuple[str, ...] = ( + START_AUTO_TOOL, + JOB_WAIT_TOOL, + JOB_RESULT_TOOL, + SUBMIT_FANOUT_TOOL, +) + +_DEFAULT_INVOCATION_PREFIXES: tuple[str, ...] = ("/ouroboros", "ooo auto") +_RESUME_WORDS = frozenset({"resume", "--resume"}) + + +class HostToolTransport(Protocol): + """Minimal public seam a host integration must provide. + + The returned value may be an Ouroboros ``MCPToolResult``, an MCP SDK + result, or a JSON-like wire mapping. Normalization happens at this + boundary so host adapters do not depend on a particular MCP SDK version. + """ + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any: + """Call one public Ouroboros MCP tool.""" + + +class HostAdapterError(RuntimeError): + """A host invocation or Ouroboros lifecycle response failed closed.""" + + def __init__( + self, + message: str, + *, + tool_name: str | None = None, + response: HostToolResponse | None = None, + ) -> None: + super().__init__(message) + self.tool_name = tool_name + self.response = response + + +class HostSubmissionError(HostAdapterError): + """A host dispatch result was rejected or became stale.""" + + +@dataclass(frozen=True, slots=True) +class HostToolResponse: + """SDK-neutral snapshot of one MCP tool response.""" + + tool_name: str + is_error: bool = False + text: str = "" + meta: Mapping[str, Any] = field(default_factory=dict) + structured_content: Any = None + raw: Any = field(default=None, repr=False, compare=False) + + @property + def payload(self) -> dict[str, Any]: + """Return the machine-readable response payload. + + MCP ``meta`` is the compatibility surface used by Ouroboros's older + clients; ``structuredContent`` is authoritative when both carry the + same key. Keeping both in the merge preserves the current server + contract while allowing newer hosts to use structured content. + """ + payload = dict(self.meta) + if isinstance(self.structured_content, Mapping): + payload.update(self.structured_content) + elif self.structured_content is not None: + payload.setdefault("structured_content", self.structured_content) + return payload + + +@dataclass(frozen=True, slots=True) +class HostInvocation: + """A parsed, explicitly authorized host request.""" + + request_id: str + host_session_id: str | None + raw_message: str + command_prefix: str + goal: str | None = None + resume_auto_session_id: str | None = None + explicit: bool = True + + @property + def is_resume(self) -> bool: + """Whether this invocation resumes a persisted auto session.""" + return self.resume_auto_session_id is not None + + def to_dict(self) -> dict[str, Any]: + """Return a JSON-safe request record suitable for host logs.""" + return { + "request_id": self.request_id, + "host_session_id": self.host_session_id, + "raw_message": self.raw_message, + "command_prefix": self.command_prefix, + "goal": self.goal, + "resume_auto_session_id": self.resume_auto_session_id, + "explicit": self.explicit, + } + + +@dataclass(frozen=True, slots=True) +class PendingHostDispatch: + """A single actionable worker request emitted by ``job_wait``.""" + + dispatch_id: str + fanout_id: str + session_id: str + result_correlation_key: str + submit_tool: str + prompt: str + working_directory: str | None + actionable: bool + raw: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False) + + def to_dict(self) -> dict[str, Any]: + """Return the exact host work handoff plus normalized convenience fields.""" + return { + "dispatch_id": self.dispatch_id, + "fanout_id": self.fanout_id, + "session_id": self.session_id, + "result_correlation_key": self.result_correlation_key, + "submit_tool": self.submit_tool, + "prompt": self.prompt, + "working_directory": self.working_directory, + "actionable": self.actionable, + "raw": _json_copy(self.raw), + } + + +@dataclass(frozen=True, slots=True) +class HostCapabilityNegotiation: + """Result of checking whether a host can consume this adapter contract.""" + + protocol: str + checked: bool + supported: bool + required_tools: tuple[str, ...] + missing_tools: tuple[str, ...] + explicit_invocation_only: bool = True + runtime_backend: str = "host" + resume_supported: bool = True + host_dispatch_supported: bool = True + + def to_dict(self) -> dict[str, Any]: + """Return a wire-safe negotiation result.""" + return { + "protocol": self.protocol, + "checked": self.checked, + "supported": self.supported, + "required_tools": list(self.required_tools), + "missing_tools": list(self.missing_tools), + "explicit_invocation_only": self.explicit_invocation_only, + "runtime_backend": self.runtime_backend, + "resume_supported": self.resume_supported, + "host_dispatch_supported": self.host_dispatch_supported, + } + + +@dataclass(frozen=True, slots=True) +class HostExecutionReceipt: + """Correlated lifecycle state returned to a personal-agent host. + + The evidence fields are intentionally additive views over the raw MCP + payload. Unknown fields are retained in ``state`` so a newer Ouroboros + server can add evaluation or verification evidence without breaking an + older host adapter. + """ + + host_name: str + invocation: HostInvocation + auto_session_id: str + job_id: str + status: str + cursor: int = 0 + is_terminal: bool = False + result_available: bool = False + links: Mapping[str, Any] = field(default_factory=dict) + pending_host_dispatches: tuple[PendingHostDispatch, ...] = () + seed: Mapping[str, Any] = field(default_factory=dict) + execution: Mapping[str, Any] = field(default_factory=dict) + evaluation: Mapping[str, Any] = field(default_factory=dict) + verification: Mapping[str, Any] = field(default_factory=dict) + failure: Mapping[str, Any] = field(default_factory=dict) + recovery: Mapping[str, Any] = field(default_factory=dict) + state: Mapping[str, Any] = field(default_factory=dict) + last_submission: Mapping[str, Any] = field(default_factory=dict) + start_response: HostToolResponse | None = field(default=None, repr=False, compare=False) + last_response: HostToolResponse | None = field(default=None, repr=False, compare=False) + result_response: HostToolResponse | None = field(default=None, repr=False, compare=False) + + @property + def resume_arguments(self) -> dict[str, str]: + """Return the exact arguments needed to resume this auto session.""" + return {"resume": self.auto_session_id} + + def to_dict(self) -> dict[str, Any]: + """Return a complete host-facing, JSON-safe receipt.""" + return { + "protocol": HOST_ADAPTER_PROTOCOL, + "host": self.host_name, + "request": self.invocation.to_dict(), + "auto_session_id": self.auto_session_id, + "job_id": self.job_id, + "status": self.status, + "cursor": self.cursor, + "is_terminal": self.is_terminal, + "result_available": self.result_available, + "links": _json_copy(self.links), + "pending_host_dispatches": [ + dispatch.to_dict() for dispatch in self.pending_host_dispatches + ], + "seed": _json_copy(self.seed), + "execution": _json_copy(self.execution), + "evaluation": _json_copy(self.evaluation), + "verification": _json_copy(self.verification), + "failure": _json_copy(self.failure), + "recovery": _json_copy(self.recovery), + "state": _json_copy(self.state), + "last_submission": _json_copy(self.last_submission), + "resume": { + "tool": START_AUTO_TOOL, + "arguments": self.resume_arguments, + }, + } + + +@dataclass(slots=True) +class MCPToolTransport: + """Adapt an MCP server/client object or callable to ``HostToolTransport``.""" + + target: Any + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any: + """Call ``target.call_tool`` without importing an optional MCP SDK.""" + caller = getattr(self.target, "call_tool", self.target) + if not callable(caller): + raise TypeError("MCPToolTransport target must expose callable call_tool") + return await caller(name, arguments) + + +def _json_copy(value: Any) -> Any: + """Detach a JSON-like value without requiring every host to use a model class.""" + if isinstance(value, Mapping): + return {str(key): _json_copy(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_copy(item) for item in value] + return value + + +def _model_mapping(value: Any) -> dict[str, Any] | None: + if isinstance(value, Mapping): + return dict(value) + model_dump = getattr(value, "model_dump", None) + if callable(model_dump): + try: + dumped = model_dump(by_alias=True, mode="json", exclude_none=False) + except TypeError: + dumped = model_dump() + return dict(dumped) if isinstance(dumped, Mapping) else None + return None + + +def _unwrap_result(value: Any) -> Any: + """Unwrap Ouroboros's ``Result`` without importing the core type.""" + if hasattr(value, "is_err") and hasattr(value, "value"): + if bool(value.is_err): + error = getattr(value, "error", "MCP tool call failed") + raise HostAdapterError(str(error)) + return value.value + return value + + +def normalize_tool_response(tool_name: str, value: Any) -> HostToolResponse: + """Normalize common MCP SDK, Ouroboros, and wire response shapes.""" + value = _unwrap_result(value) + if isinstance(value, HostToolResponse): + return value + + # Avoid importing the optional MCP package; the internal result exposes + # the same attributes as the SDK mapping boundary. + meta = _model_mapping(getattr(value, "meta", None)) or {} + structured = getattr(value, "structured_content", None) + if structured is None: + structured = getattr(value, "structuredContent", None) + is_error = bool(getattr(value, "is_error", getattr(value, "isError", False))) + content = getattr(value, "content", None) + raw_mapping = _model_mapping(value) + if raw_mapping is not None: + meta = _model_mapping(raw_mapping.get("meta")) or meta + if structured is None: + structured = raw_mapping.get("structuredContent", raw_mapping.get("structured_content")) + is_error = bool(raw_mapping.get("isError", raw_mapping.get("is_error", is_error))) + content = raw_mapping.get("content", content) + envelope_keys = { + "content", + "isError", + "is_error", + "meta", + "structuredContent", + "structured_content", + } + direct_payload = { + key: item for key, item in raw_mapping.items() if key not in envelope_keys + } + if not meta and structured is None and content is None and direct_payload: + # A tiny fake or a host-side shim may return the structured payload + # directly. Accept that shape at the edge, while all production + # MCP calls still use the standard envelope. + structured = direct_payload + + text = _content_text(content) + if not text and isinstance(value, str): + text = value + return HostToolResponse( + tool_name=tool_name, + is_error=is_error, + text=text, + meta=meta, + structured_content=structured, + raw=value, + ) + + +def _content_text(content: Any) -> str: + if isinstance(content, str): + return content + if not isinstance(content, Sequence) or isinstance(content, (str, bytes, bytearray)): + return "" + values: list[str] = [] + for item in content: + mapping = _model_mapping(item) + if mapping is None: + continue + text = mapping.get("text") + if isinstance(text, str) and text: + values.append(text) + return "\n".join(values) + + +def _new_request_id() -> str: + return f"hostreq_{uuid4().hex}" + + +def _normalized_session_id(value: str | None) -> str | None: + if value is None: + return None + normalized = value.strip() + return normalized or None + + +def parse_explicit_invocation( + message: str, + *, + host_session_id: str | None = None, + prefixes: Iterable[str] = _DEFAULT_INVOCATION_PREFIXES, + request_id: str | None = None, +) -> HostInvocation | None: + """Parse a command only when it starts with an exact supported prefix. + + Ordinary messages return ``None`` and are never sent to an Ouroboros + tool. Supported forms are ``/ouroboros `` and ``ooo auto ``; + resume forms are ``/ouroboros resume `` and + ``ooo auto --resume ``. Prefix matching is + case-insensitive, while the goal is preserved verbatim. + """ + if not isinstance(message, str): + raise HostAdapterError("host message must be a string") + stripped = message.strip() + if not stripped: + return None + + normalized_prefixes = tuple( + prefix.strip() for prefix in prefixes if isinstance(prefix, str) and prefix.strip() + ) + for prefix in sorted(normalized_prefixes, key=len, reverse=True): + prefix_folded = prefix.casefold() + stripped_folded = stripped.casefold() + if ( + stripped_folded != prefix_folded + and not stripped_folded.startswith(f"{prefix_folded} ") + and not ( + len(stripped) > len(prefix) + and stripped_folded.startswith(prefix_folded) + and stripped[len(prefix)].isspace() + ) + ): + continue + + remainder = stripped[len(prefix) :].strip() + if not remainder: + raise HostAdapterError(f"{prefix} requires a goal or an auto session id to resume") + resume_id = _parse_resume_id(remainder) + if resume_id is not None: + return HostInvocation( + request_id=request_id or _new_request_id(), + host_session_id=_normalized_session_id(host_session_id), + raw_message=message, + command_prefix=prefix, + resume_auto_session_id=resume_id, + ) + return HostInvocation( + request_id=request_id or _new_request_id(), + host_session_id=_normalized_session_id(host_session_id), + raw_message=message, + command_prefix=prefix, + goal=remainder, + ) + return None + + +def _parse_resume_id(remainder: str) -> str | None: + try: + tokens = shlex.split(remainder) + except ValueError as exc: + raise HostAdapterError(f"invalid explicit Ouroboros invocation: {exc}") from exc + if not tokens: + return None + first = tokens[0].casefold() + if first not in _RESUME_WORDS and not first.startswith("--resume="): + return None + if first.startswith("--resume="): + if len(tokens) != 1: + raise HostAdapterError("resume accepts exactly one auto_session_id") + candidate = tokens[0].split("=", 1)[1].strip() + else: + if len(tokens) != 2: + raise HostAdapterError("resume accepts exactly one auto_session_id") + candidate = tokens[1].strip() + if not candidate: + raise HostAdapterError("resume requires a non-empty auto_session_id") + return candidate + + +class PersonalAgentHostAdapter: + """Translate explicit personal-agent requests into existing MCP calls.""" + + def __init__( + self, + transport: HostToolTransport | Callable[[str, dict[str, Any]], Awaitable[Any]], + *, + host_name: str = "personal_agent", + invocation_prefixes: Iterable[str] = _DEFAULT_INVOCATION_PREFIXES, + expected_runtime_backend: str | None = "host", + ) -> None: + self.transport = transport + self.host_name = host_name + self.invocation_prefixes = tuple(invocation_prefixes) + self.expected_runtime_backend = expected_runtime_backend + + @property + def required_tools(self) -> tuple[str, ...]: + """Return the minimum public MCP surface for this adapter.""" + return REQUIRED_HOST_TOOLS + + def negotiate( + self, + advertised_tools: Iterable[str] | None, + ) -> HostCapabilityNegotiation: + """Check a host's negotiated tool list without making a tool call.""" + if advertised_tools is None: + return HostCapabilityNegotiation( + protocol=HOST_ADAPTER_PROTOCOL, + checked=False, + supported=False, + required_tools=REQUIRED_HOST_TOOLS, + missing_tools=(), + ) + available = {str(name) for name in advertised_tools} + missing = tuple(name for name in REQUIRED_HOST_TOOLS if name not in available) + return HostCapabilityNegotiation( + protocol=HOST_ADAPTER_PROTOCOL, + checked=True, + supported=not missing, + required_tools=REQUIRED_HOST_TOOLS, + missing_tools=missing, + ) + + def parse(self, message: str, *, host_session_id: str | None = None) -> HostInvocation | None: + """Parse a host message without invoking Ouroboros.""" + return parse_explicit_invocation( + message, + host_session_id=host_session_id, + prefixes=self.invocation_prefixes, + ) + + async def start( + self, + message: str, + *, + host_session_id: str | None = None, + cwd: str | None = None, + ) -> HostExecutionReceipt | None: + """Start a request, returning ``None`` for ordinary host messages.""" + invocation = self.parse(message, host_session_id=host_session_id) + if invocation is None: + return None + arguments: dict[str, Any] + if invocation.is_resume: + arguments = {"resume": invocation.resume_auto_session_id} + else: + arguments = {"goal": invocation.goal} + if cwd is not None: + normalized_cwd = cwd.strip() + if not normalized_cwd: + raise HostAdapterError("cwd must not be empty") + arguments["cwd"] = normalized_cwd + + response = await self._call(START_AUTO_TOOL, arguments) + payload = response.payload + runtime_backend = payload.get("runtime_backend") + if ( + self.expected_runtime_backend is not None + and runtime_backend != self.expected_runtime_backend + ): + raise HostAdapterError( + "Ouroboros start_auto did not negotiate the expected host runtime " + f"(expected={self.expected_runtime_backend!r}, received={runtime_backend!r})", + tool_name=START_AUTO_TOOL, + response=response, + ) + auto_session_id = _required_text(payload, "auto_session_id", START_AUTO_TOOL) + job_id = _required_text(payload, "job_id", START_AUTO_TOOL) + return _receipt_from_payload( + host_name=self.host_name, + invocation=invocation, + auto_session_id=auto_session_id, + job_id=job_id, + payload=payload, + response=response, + start_response=response, + ) + + async def wait( + self, + receipt: HostExecutionReceipt, + *, + timeout_seconds: int = 5, + wait_for: str = "attention_or_ac_change", + ) -> HostExecutionReceipt: + """Poll a job and expose actionable host dispatches exactly as issued. + + The server caps this long-poll at five seconds. Using that cap by + default keeps a host loop from busy-spinning while still allowing a + caller to request an immediate snapshot with ``timeout_seconds=0``. + """ + if timeout_seconds < 0: + raise HostAdapterError("timeout_seconds must be non-negative") + response = await self._call( + JOB_WAIT_TOOL, + { + "job_id": receipt.job_id, + "cursor": receipt.cursor, + "timeout_seconds": timeout_seconds, + "view": "summary", + "stream": "linked", + "wait_for": wait_for, + }, + ) + payload = response.payload + pending = _pending_dispatches(payload.get("pending_host_dispatches"), JOB_WAIT_TOOL) + return _updated_receipt(receipt, payload, response, pending=pending) + + async def submit_dispatch( + self, + receipt: HostExecutionReceipt, + dispatch: PendingHostDispatch, + content: str | Mapping[str, Any] | None = None, + *, + undispatched: bool = False, + ) -> HostExecutionReceipt: + """Submit one host worker result through Ouroboros's fail-closed seam.""" + if not any( + item.dispatch_id == dispatch.dispatch_id for item in receipt.pending_host_dispatches + ): + raise HostSubmissionError( + f"dispatch {dispatch.dispatch_id} is not pending for job {receipt.job_id}" + ) + if not dispatch.actionable: + raise HostSubmissionError(f"dispatch {dispatch.dispatch_id} is informational only") + if not dispatch.session_id: + raise HostSubmissionError("host dispatch has no session binding") + if dispatch.submit_tool != SUBMIT_FANOUT_TOOL: + raise HostSubmissionError( + f"host dispatch advertised an unsupported submission tool {dispatch.submit_tool!r}" + ) + if undispatched: + result_entry: dict[str, Any] = {"key": "result", "undispatched": True} + else: + _validate_host_content(content) + result_entry = {"key": "result", "content": _json_copy(content)} + response = await self._call( + dispatch.submit_tool or SUBMIT_FANOUT_TOOL, + { + "fanout_id": dispatch.fanout_id, + "session_id": dispatch.session_id, + "correlation_key": dispatch.result_correlation_key, + "results": [result_entry], + }, + ) + payload = response.payload + if payload.get("status") != "complete": + raise HostSubmissionError( + f"Ouroboros rejected host dispatch {dispatch.dispatch_id}: " + f"{payload.get('status', 'unknown')}", + tool_name=dispatch.submit_tool, + response=response, + ) + remaining = tuple( + item + for item in receipt.pending_host_dispatches + if item.dispatch_id != dispatch.dispatch_id + ) + return replace(receipt, pending_host_dispatches=remaining, last_submission=payload) + + async def result(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Fetch and preserve terminal Seed/execution/evaluation evidence.""" + response = await self._call(JOB_RESULT_TOOL, {"job_id": receipt.job_id}) + payload = response.payload + pending = _pending_dispatches(payload.get("pending_host_dispatches"), JOB_RESULT_TOOL) + return _updated_receipt( + receipt, + payload, + response, + pending=pending, + result_response=response, + ) + + async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Request cancellation while retaining the correlated receipt.""" + response = await self._call(CANCEL_JOB_TOOL, {"job_id": receipt.job_id}) + return _updated_receipt(receipt, response.payload, response, pending=()) + + async def _call(self, tool_name: str, arguments: dict[str, Any]) -> HostToolResponse: + caller = getattr(self.transport, "call_tool", self.transport) + if not callable(caller): + raise HostAdapterError("host transport must expose callable call_tool") + try: + raw = await caller(tool_name, arguments) + response = normalize_tool_response(tool_name, raw) + except HostAdapterError as exc: + if exc.tool_name is None: + exc.tool_name = tool_name + raise + except Exception as exc: + raise HostAdapterError(f"host tool call failed: {exc}", tool_name=tool_name) from exc + if response.is_error: + detail = response.text or response.payload.get("error") or "tool returned an error" + raise HostAdapterError(str(detail), tool_name=tool_name, response=response) + return response + + +class GrokBotHostAdapter(PersonalAgentHostAdapter): + """Explicit-command profile for a Grok Bot MCP host. + + This class only names the host and fixes the invocation vocabulary. It + does not claim a private xAI Bot API, install a local ``grok`` binary, or + bypass the public MCP connector/security boundary. + """ + + def __init__( + self, + transport: HostToolTransport | Callable[[str, dict[str, Any]], Awaitable[Any]], + *, + invocation_prefixes: Iterable[str] = _DEFAULT_INVOCATION_PREFIXES, + vm_profile: GrokBotVMProfile = GROK_BOT_VM_PROFILE, + ) -> None: + super().__init__( + transport, + host_name=GROK_BOT_HOST_NAME, + invocation_prefixes=invocation_prefixes, + expected_runtime_backend="host", + ) + self.vm_profile = vm_profile + + def create_vm_runtime( + self, + transport: Any, + *, + host_workspace: str, + receipt_store: Any = None, + default_timeout_seconds: float = 300.0, + ) -> Any: + """Create the reusable VM worker configured for this Grok profile.""" + return self.vm_profile.create_runtime( + transport, + host_workspace=host_workspace, + receipt_store=receipt_store, + default_timeout_seconds=default_timeout_seconds, + ) + + +def _required_text(payload: Mapping[str, Any], key: str, tool_name: str) -> str: + value = payload.get(key) + if not isinstance(value, str) or not value.strip(): + raise HostAdapterError( + f"{tool_name} response is missing required {key}", + tool_name=tool_name, + ) + return value.strip() + + +def _pending_dispatches(value: Any, tool_name: str) -> tuple[PendingHostDispatch, ...]: + if value is None: + return () + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + raise HostAdapterError( + "pending_host_dispatches must be a list", + tool_name=tool_name, + ) + parsed: list[PendingHostDispatch] = [] + for raw_value in value: + raw = _model_mapping(raw_value) + if raw is None: + raise HostAdapterError("pending host dispatch must be an object", tool_name=tool_name) + worker_values = raw.get("subagents") + if ( + not isinstance(worker_values, Sequence) + or isinstance(worker_values, (str, bytes, bytearray)) + or not worker_values + ): + raise HostAdapterError( + "pending host dispatch is missing subagents[0]", + tool_name=tool_name, + ) + worker = _model_mapping(worker_values[0]) + if worker is None: + raise HostAdapterError("pending host worker must be an object", tool_name=tool_name) + context = _model_mapping(worker.get("context")) or {} + parsed.append( + PendingHostDispatch( + dispatch_id=_required_text(raw, "dispatch_id", tool_name), + fanout_id=_required_text(raw, "fanout_id", tool_name), + session_id=_required_text(raw, "session_id", tool_name), + result_correlation_key=_required_text(raw, "result_correlation_key", tool_name), + submit_tool=_required_text(raw, "submit_tool", tool_name), + prompt=_required_text(worker, "prompt", tool_name), + working_directory=( + str(context["working_directory"]) + if context.get("working_directory") is not None + else None + ), + actionable=raw.get("actionable") is True, + raw=raw, + ) + ) + return tuple(parsed) + + +def _receipt_from_payload( + *, + host_name: str, + invocation: HostInvocation, + auto_session_id: str, + job_id: str, + payload: Mapping[str, Any], + response: HostToolResponse, + start_response: HostToolResponse, +) -> HostExecutionReceipt: + state = dict(payload) + return HostExecutionReceipt( + host_name=host_name, + invocation=invocation, + auto_session_id=auto_session_id, + job_id=job_id, + status=str(payload.get("status") or "queued"), + cursor=_non_negative_cursor(payload.get("cursor")), + is_terminal=bool(payload.get("is_terminal", False)), + result_available=bool(payload.get("result_available", False)), + links=_mapping_value(payload.get("links")), + seed=_named_evidence(state, "seed", "seed_state", "seed_result"), + execution=_named_evidence(state, "execution", "execution_state", "execution_result"), + evaluation=_named_evidence( + state, "evaluation", "evaluation_state", "evaluation_result", "qa" + ), + verification=_named_evidence( + state, "verification", "verification_state", "verification_result", "verdict" + ), + failure=_named_evidence(state, "failure", "failure_state", "error"), + recovery=_named_evidence(state, "recovery", "recovery_action", "next_step"), + state=state, + start_response=start_response, + last_response=response, + ) + + +def _updated_receipt( + receipt: HostExecutionReceipt, + payload: Mapping[str, Any], + response: HostToolResponse, + *, + pending: tuple[PendingHostDispatch, ...], + result_response: HostToolResponse | None = None, +) -> HostExecutionReceipt: + state = dict(payload) + return replace( + receipt, + status=str(payload.get("status") or receipt.status), + cursor=_non_negative_cursor(payload.get("cursor", receipt.cursor)), + is_terminal=bool( + payload.get( + "is_terminal", + receipt.is_terminal + or str(payload.get("status", "")).lower() + in {"completed", "complete", "failed", "cancelled", "canceled", "interrupted"}, + ) + ), + result_available=bool(payload.get("result_available", receipt.result_available)), + links=_mapping_value(payload.get("links")) or receipt.links, + pending_host_dispatches=pending, + seed=_named_evidence(state, "seed", "seed_state", "seed_result") or receipt.seed, + execution=_named_evidence(state, "execution", "execution_state", "execution_result") + or receipt.execution, + evaluation=_named_evidence( + state, "evaluation", "evaluation_state", "evaluation_result", "qa" + ) + or receipt.evaluation, + verification=_named_evidence( + state, "verification", "verification_state", "verification_result", "verdict" + ) + or receipt.verification, + failure=_named_evidence(state, "failure", "failure_state", "error") or receipt.failure, + recovery=_named_evidence(state, "recovery", "recovery_action", "next_step") + or receipt.recovery, + state=state, + last_response=response, + result_response=result_response or receipt.result_response, + ) + + +def _mapping_value(value: Any) -> Mapping[str, Any]: + return _model_mapping(value) or {} + + +def _non_negative_cursor(value: Any) -> int: + try: + cursor = int(value) + except (TypeError, ValueError): + return 0 + return max(cursor, 0) + + +def _named_evidence(payload: Mapping[str, Any], *names: str) -> Mapping[str, Any]: + """Find a named evidence object in the current response without flattening it.""" + wanted = set(names) + queue: list[tuple[Any, int]] = [(payload, 0)] + while queue: + current, depth = queue.pop(0) + if depth > 3 or not isinstance(current, Mapping): + continue + for key, value in current.items(): + if key in wanted: + mapped = _model_mapping(value) + if mapped is not None: + return mapped + if value is not None: + return {"value": _json_copy(value)} + if isinstance(value, Mapping): + queue.append((value, depth + 1)) + return {} + + +def _validate_host_content(content: Any) -> None: + if isinstance(content, str): + if content.strip(): + return + raise HostSubmissionError("host execution content must not be empty") + if not isinstance(content, Mapping) or not content: + raise HostSubmissionError("host execution content must be a non-empty string or object") + success = content.get("success") + if "success" in content and not isinstance(success, bool): + raise HostSubmissionError("host execution content.success must be a boolean") + if success is False: + return + substantive = any( + key != "success" + and value is not None + and (not isinstance(value, str) or bool(value.strip())) + and (not isinstance(value, (Mapping, list, tuple)) or bool(value)) + for key, value in content.items() + ) + if not substantive: + raise HostSubmissionError("successful host execution content needs substantive output") + + +__all__ = [ + "CANCEL_JOB_TOOL", + "GROK_BOT_HOST_NAME", + "HOST_ADAPTER_PROTOCOL", + "JOB_RESULT_TOOL", + "JOB_WAIT_TOOL", + "HostAdapterError", + "HostCapabilityNegotiation", + "HostExecutionReceipt", + "HostInvocation", + "HostSubmissionError", + "HostToolResponse", + "HostToolTransport", + "MCPToolTransport", + "PendingHostDispatch", + "PersonalAgentHostAdapter", + "GrokBotHostAdapter", + "REQUIRED_HOST_TOOLS", + "START_AUTO_TOOL", + "SUBMIT_FANOUT_TOOL", + "normalize_tool_response", + "parse_explicit_invocation", +] diff --git a/src/ouroboros/integrations/vm_agent_profile.py b/src/ouroboros/integrations/vm_agent_profile.py new file mode 100644 index 0000000000..9a1d0f27e4 --- /dev/null +++ b/src/ouroboros/integrations/vm_agent_profile.py @@ -0,0 +1,88 @@ +"""Profiles for personal agents that provide a VM and a public tool surface.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +@dataclass(frozen=True, slots=True) +class VMPersonalAgentProfile: + """Description of a VM-backed personal-agent integration. + + A profile describes an integration boundary. It does not contain a + provider client or imply that a live account has been connected. + """ + + profile_name: str = "vm_personal_agent" + host_name: str = "personal_agent" + vm_root: str = "/workspace" + transport_modes: tuple[str, ...] = ("command", "mcp") + invocation_prefixes: tuple[str, ...] = ("/ouroboros", "ooo auto") + public_surface: str = "vm_shell_or_custom_mcp" + live_account_verified: bool = False + + def to_dict(self) -> dict[str, Any]: + """Return a serializable capability profile.""" + return { + "profile_name": self.profile_name, + "host_name": self.host_name, + "vm_root": self.vm_root, + "transport_modes": list(self.transport_modes), + "invocation_prefixes": list(self.invocation_prefixes), + "public_surface": self.public_surface, + "live_account_verified": self.live_account_verified, + } + + def create_runtime( + self, + transport: Any, + *, + host_workspace: str | Path, + receipt_store: Any = None, + default_timeout_seconds: float = 300.0, + ) -> Any: + """Build the reusable VM runtime for this profile. + + The import stays local so importing a profile never imports optional + transport implementations or creates a filesystem state directory. + """ + from ouroboros.integrations.vm_agent_runtime import ( + VMPersonalAgentRuntime, + VMWorkspaceMapper, + ) + + return VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(host_workspace, self.vm_root), + receipt_store=receipt_store, + default_timeout_seconds=default_timeout_seconds, + ) + + +@dataclass(frozen=True, slots=True) +class GrokBotVMProfile(VMPersonalAgentProfile): + """Public-surface profile for a Grok Bot cloud-computer VM. + + The profile intentionally describes the documented VM shell/custom MCP + boundary. It does not claim a private Grok Bot callback API or a paid + account connection. + """ + + profile_name: str = "grok_bot_vm" + host_name: str = "grok_bot" + vm_root: str = "/workspace" + transport_modes: tuple[str, ...] = ("command", "mcp") + invocation_prefixes: tuple[str, ...] = ("/ouroboros", "ooo auto") + public_surface: str = "grok_bot_cloud_computer_shell_or_custom_mcp" + live_account_verified: bool = False + + +GROK_BOT_VM_PROFILE = GrokBotVMProfile() + +__all__ = [ + "GROK_BOT_VM_PROFILE", + "GrokBotVMProfile", + "VMPersonalAgentProfile", +] diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py new file mode 100644 index 0000000000..547835ccb0 --- /dev/null +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -0,0 +1,856 @@ +"""Safe, resumable execution bridge for VM-providing personal agents. + +The bridge is deliberately independent from any one personal-agent product. +It accepts either a command transport or a public MCP transport, maps only +approved workspace paths, and persists one receipt per dispatch correlation +key. A receipt in ``running`` or ``disconnected`` state is never replayed by +calling the original command again; it can only be resumed through a +transport execution identifier. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field, replace +from datetime import UTC, datetime +import hashlib +import inspect +import json +import os +from pathlib import Path, PurePosixPath +import tempfile +from typing import Any, Protocol + + +class VMRuntimeError(RuntimeError): + """Base error for the VM runtime bridge.""" + + +class VMPathError(VMRuntimeError): + """A host or VM path is outside the configured workspace.""" + + +class VMTransportError(VMRuntimeError): + """A VM transport rejected a request or returned an invalid response.""" + + +class VMTransportDisconnected(VMTransportError): + """The host connection dropped while a remote execution was in flight.""" + + def __init__(self, message: str, *, execution_id: str | None = None) -> None: + super().__init__(message) + self.execution_id = execution_id + + +@dataclass(frozen=True, slots=True) +class VMWorkspaceMapper: + """Map paths between one approved host root and one VM root.""" + + host_root: Path + vm_root: PurePosixPath + + def __init__(self, host_root: str | Path, vm_root: str) -> None: + host = Path(host_root).expanduser().resolve() + vm = PurePosixPath(vm_root) + if not vm.is_absolute(): + raise VMPathError("vm_root must be an absolute POSIX path") + object.__setattr__(self, "host_root", host) + object.__setattr__(self, "vm_root", vm) + + def map_host_path(self, path: str | Path) -> str: + """Map an approved host path to its VM path, rejecting escapes.""" + resolved = self._resolve_host_path(path) + relative = resolved.relative_to(self.host_root) + return str(self.vm_root / PurePosixPath(relative.as_posix())) + + def map_vm_path(self, path: str) -> Path: + """Map an approved VM path back to a host path, rejecting escapes.""" + candidate = PurePosixPath(path) + try: + relative = candidate.relative_to(self.vm_root) + except ValueError as exc: + raise VMPathError(f"VM path escapes approved workspace: {path}") from exc + resolved = (self.host_root / Path(*relative.parts)).resolve(strict=False) + try: + resolved.relative_to(self.host_root) + except ValueError as exc: + raise VMPathError(f"VM path escapes approved workspace: {path}") from exc + return resolved + + def resolve_dispatch_workspace(self, path: str | Path) -> Path: + """Resolve a dispatch cwd supplied in host or VM path notation.""" + candidate = Path(path).expanduser() + if not candidate.is_absolute(): + return self._resolve_host_path(candidate) + + resolved_host = candidate.resolve(strict=False) + if resolved_host.is_relative_to(self.host_root): + return resolved_host + + vm_candidate = PurePosixPath(str(path)) + if vm_candidate.is_relative_to(self.vm_root): + return self.map_vm_path(str(path)) + raise VMPathError(f"dispatch workspace escapes approved workspace: {path!s}") + + def host_relative(self, path: str | Path) -> str: + """Return a stable workspace-relative path for an artifact receipt.""" + return self._resolve_host_path(path).relative_to(self.host_root).as_posix() + + def _resolve_host_path(self, path: str | Path) -> Path: + candidate = Path(path).expanduser() + if not candidate.is_absolute(): + candidate = self.host_root / candidate + resolved = candidate.resolve(strict=False) + try: + resolved.relative_to(self.host_root) + except ValueError as exc: + raise VMPathError(f"host path escapes approved workspace: {path!s}") from exc + return resolved + + +@dataclass(frozen=True, slots=True) +class VMExecutionRequest: + """One idempotent command or personal-agent turn.""" + + dispatch_id: str + session_id: str + command: str + host_workspace: str | None = None + vm_workspace: str | None = None + timeout_seconds: float = 300.0 + idempotency_key: str | None = None + artifact_paths: tuple[str, ...] = () + + def __post_init__(self) -> None: + if not self.dispatch_id.strip() or not self.session_id.strip(): + raise VMRuntimeError("dispatch_id and session_id are required") + if not self.command.strip(): + raise VMRuntimeError("command or personal-agent turn must not be empty") + if self.timeout_seconds <= 0: + raise VMRuntimeError("timeout_seconds must be positive") + + @property + def correlation_key(self) -> str: + """Return the durable key shared by retries and host restarts.""" + return self.idempotency_key or f"{self.session_id}:{self.dispatch_id}" + + def with_vm_workspace(self, vm_workspace: str) -> VMExecutionRequest: + """Return the transport-facing request with its mapped VM cwd.""" + return replace(self, vm_workspace=vm_workspace) + + +@dataclass(frozen=True, slots=True) +class VMArtifact: + """Metadata for an artifact collected from the approved workspace.""" + + relative_path: str + vm_path: str + exists: bool + size: int = 0 + sha256: str | None = None + + def to_dict(self) -> dict[str, Any]: + return { + "relative_path": self.relative_path, + "vm_path": self.vm_path, + "exists": self.exists, + "size": self.size, + "sha256": self.sha256, + } + + +_TERMINAL_STATUSES = frozenset({"completed", "failed"}) + + +@dataclass(frozen=True, slots=True) +class VMExecutionReceipt: + """Durable structured evidence for a VM execution.""" + + dispatch_id: str + session_id: str + idempotency_key: str + status: str + command: str + host_workspace: str + vm_workspace: str + timeout_seconds: float + execution_id: str | None = None + exit_code: int | None = None + stdout: str = "" + stderr: str = "" + artifacts: tuple[VMArtifact, ...] = () + error: str | None = None + recovery_required: bool = False + started_at: str = "" + finished_at: str | None = None + raw: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False) + + @property + def is_terminal(self) -> bool: + return self.status in _TERMINAL_STATUSES + + def to_dict(self) -> dict[str, Any]: + return { + "dispatch_id": self.dispatch_id, + "session_id": self.session_id, + "idempotency_key": self.idempotency_key, + "status": self.status, + "command": self.command, + "host_workspace": self.host_workspace, + "vm_workspace": self.vm_workspace, + "timeout_seconds": self.timeout_seconds, + "execution_id": self.execution_id, + "exit_code": self.exit_code, + "stdout": self.stdout, + "stderr": self.stderr, + "artifacts": [artifact.to_dict() for artifact in self.artifacts], + "error": self.error, + "recovery_required": self.recovery_required, + "started_at": self.started_at, + "finished_at": self.finished_at, + "raw": _json_value(self.raw), + } + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: + artifacts: list[VMArtifact] = [] + raw_artifacts = value.get("artifacts", ()) + if isinstance(raw_artifacts, Iterable) and not isinstance(raw_artifacts, (str, bytes)): + for item in raw_artifacts: + if isinstance(item, Mapping): + artifacts.append( + VMArtifact( + relative_path=str(item.get("relative_path", "")), + vm_path=str(item.get("vm_path", "")), + exists=bool(item.get("exists", False)), + size=int(item.get("size", 0)), + sha256=( + str(item["sha256"]) if item.get("sha256") is not None else None + ), + ) + ) + return cls( + dispatch_id=str(value["dispatch_id"]), + session_id=str(value["session_id"]), + idempotency_key=str(value["idempotency_key"]), + status=str(value["status"]), + command=str(value.get("command", "")), + host_workspace=str(value.get("host_workspace", "")), + vm_workspace=str(value.get("vm_workspace", "")), + timeout_seconds=float(value.get("timeout_seconds", 300.0)), + execution_id=(str(value["execution_id"]) if value.get("execution_id") else None), + exit_code=(int(value["exit_code"]) if value.get("exit_code") is not None else None), + stdout=str(value.get("stdout", "")), + stderr=str(value.get("stderr", "")), + artifacts=tuple(artifacts), + error=(str(value["error"]) if value.get("error") is not None else None), + recovery_required=bool(value.get("recovery_required", False)), + started_at=str(value.get("started_at", "")), + finished_at=(str(value["finished_at"]) if value.get("finished_at") else None), + raw=_mapping(value.get("raw")), + ) + + +class VMReceiptStore(Protocol): + """Minimal persistence seam used by the runtime.""" + + def get(self, key: str) -> VMExecutionReceipt | None: + """Read one receipt.""" + + def put(self, receipt: VMExecutionReceipt) -> None: + """Atomically persist one receipt.""" + + def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: + """Find a receipt after a process restart.""" + + +class MemoryVMReceiptStore: + """Small deterministic store useful for embedding and tests.""" + + def __init__(self) -> None: + self._receipts: dict[str, VMExecutionReceipt] = {} + + def get(self, key: str) -> VMExecutionReceipt | None: + return self._receipts.get(key) + + def put(self, receipt: VMExecutionReceipt) -> None: + self._receipts[receipt.idempotency_key] = receipt + + def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: + for receipt in self._receipts.values(): + if receipt.dispatch_id == dispatch_id and ( + session_id is None or receipt.session_id == session_id + ): + return receipt + return None + + +class JsonVMReceiptStore: + """Atomic JSON receipt store that survives host process restarts.""" + + def __init__(self, directory: str | Path) -> None: + self.directory = Path(directory).expanduser().resolve() + self.directory.mkdir(parents=True, exist_ok=True) + + def _path(self, key: str) -> Path: + digest = hashlib.sha256(key.encode("utf-8")).hexdigest() + return self.directory / f"{digest}.json" + + def get(self, key: str) -> VMExecutionReceipt | None: + path = self._path(key) + try: + return VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) + except FileNotFoundError: + return None + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise VMRuntimeError(f"corrupt VM receipt for {key!r}") from exc + + def put(self, receipt: VMExecutionReceipt) -> None: + path = self._path(receipt.idempotency_key) + fd, temporary = tempfile.mkstemp(prefix=".receipt-", suffix=".tmp", dir=self.directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: + for path in self.directory.glob("*.json"): + try: + receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError): + continue + if receipt.dispatch_id == dispatch_id and ( + session_id is None or receipt.session_id == session_id + ): + return receipt + return None + + +class VMTransport(Protocol): + """Transport-neutral command/turn execution surface.""" + + async def execute(self, request: VMExecutionRequest) -> Any: + """Start or complete one idempotent VM operation.""" + + +class ResumableVMTransport(VMTransport, Protocol): + """Optional transport extension for reconnecting to a running operation.""" + + async def resume(self, request: VMExecutionRequest, execution_id: str) -> Any: + """Resume an execution already accepted by the VM.""" + + +@dataclass(slots=True) +class CommandVMTransport: + """Adapt an async VM shell/command callable to ``VMTransport``.""" + + target: Any + + async def execute(self, request: VMExecutionRequest) -> Any: + caller = getattr(self.target, "execute_command", None) + if caller is None: + caller = getattr(self.target, "run_command", None) + if caller is None and callable(self.target): + caller = self.target + if not callable(caller): + raise VMTransportError("command transport needs execute_command or run_command") + return await _await_if_needed( + caller( + request.command, + cwd=request.vm_workspace, + timeout_seconds=request.timeout_seconds, + idempotency_key=request.correlation_key, + ) + ) + + async def resume(self, request: VMExecutionRequest, execution_id: str) -> Any: + caller = getattr(self.target, "resume_execution", None) + if not callable(caller): + raise VMTransportError("command transport cannot resume execution") + return await _await_if_needed( + caller( + execution_id, + cwd=request.vm_workspace, + timeout_seconds=request.timeout_seconds, + idempotency_key=request.correlation_key, + ) + ) + + +VMCommandTransport = CommandVMTransport + + +@dataclass(slots=True) +class MCPVMTransport: + """Adapt a public MCP command/turn tool to ``VMTransport``.""" + + target: Any + execute_tool: str = "vm.execute" + resume_tool: str = "vm.resume" + + async def execute(self, request: VMExecutionRequest) -> Any: + return await self._call( + self.execute_tool, + { + "operation": "execute", + "command": request.command, + "cwd": request.vm_workspace, + "timeout_seconds": request.timeout_seconds, + "idempotency_key": request.correlation_key, + "dispatch_id": request.dispatch_id, + "session_id": request.session_id, + "artifact_paths": list(request.artifact_paths), + }, + ) + + async def resume(self, request: VMExecutionRequest, execution_id: str) -> Any: + return await self._call( + self.resume_tool, + { + "operation": "resume", + "execution_id": execution_id, + "cwd": request.vm_workspace, + "timeout_seconds": request.timeout_seconds, + "idempotency_key": request.correlation_key, + "dispatch_id": request.dispatch_id, + "session_id": request.session_id, + }, + ) + + async def _call(self, name: str, arguments: dict[str, Any]) -> Any: + caller = getattr(self.target, "call_tool", self.target) + if not callable(caller): + raise VMTransportError("MCP transport needs call_tool or an async callable") + try: + raw = await _await_if_needed(caller(name, arguments)) + except (ConnectionError, BrokenPipeError, EOFError) as exc: + raise VMTransportDisconnected(str(exc)) from exc + payload = _payload(raw) + if _is_error(raw, payload): + raise VMTransportError(str(payload.get("error") or "VM MCP tool returned an error")) + return payload + + +VMMCPTransport = MCPVMTransport + + +class VMPersonalAgentRuntime: + """Execute host dispatches in a VM with durable idempotent receipts.""" + + def __init__( + self, + transport: VMTransport, + *, + workspace: VMWorkspaceMapper, + receipt_store: VMReceiptStore | None = None, + default_timeout_seconds: float = 300.0, + ) -> None: + if default_timeout_seconds <= 0: + raise VMRuntimeError("default_timeout_seconds must be positive") + self.transport = transport + self.workspace = workspace + self.receipt_store = receipt_store or MemoryVMReceiptStore() + self.default_timeout_seconds = default_timeout_seconds + self._locks: dict[str, asyncio.Lock] = {} + + async def execute_command( + self, + command: str, + *, + dispatch_id: str, + session_id: str, + host_workspace: str | Path | None = None, + timeout_seconds: float | None = None, + artifact_paths: Iterable[str] = (), + idempotency_key: str | None = None, + ) -> VMExecutionReceipt: + """Execute one command, or return the durable receipt for its retry.""" + request = VMExecutionRequest( + dispatch_id=dispatch_id, + session_id=session_id, + command=command, + host_workspace=str(host_workspace) if host_workspace is not None else None, + timeout_seconds=( + self.default_timeout_seconds if timeout_seconds is None else timeout_seconds + ), + artifact_paths=tuple(artifact_paths), + idempotency_key=idempotency_key, + ) + return await self._execute_request(request) + + async def execute_dispatch( + self, + dispatch: Any, + *, + command: str | None = None, + timeout_seconds: float | None = None, + artifact_paths: Iterable[str] = (), + ) -> VMExecutionReceipt: + """Execute a normalized ``PendingHostDispatch`` or equivalent mapping.""" + values = _object_mapping(dispatch) + dispatch_id = _required_text(values, "dispatch_id") + session_id = _required_text(values, "session_id") + selected_command = ( + command or _optional_text(values, "command") or _optional_text(values, "prompt") + ) + if selected_command is None: + raise VMRuntimeError("host dispatch has no command or prompt") + working_directory = values.get("working_directory") + if working_directory is None or ( + isinstance(working_directory, str) and not working_directory.strip() + ): + host_workspace = None + elif isinstance(working_directory, (str, Path)): + host_workspace = str(self.workspace.resolve_dispatch_workspace(working_directory)) + else: + raise VMRuntimeError("host dispatch working_directory must be a path string") + return await self.execute_command( + selected_command, + dispatch_id=dispatch_id, + session_id=session_id, + host_workspace=host_workspace, + timeout_seconds=timeout_seconds, + artifact_paths=artifact_paths, + ) + + async def resume_dispatch( + self, + dispatch_id: str, + *, + session_id: str | None = None, + ) -> VMExecutionReceipt: + """Resume a persisted operation without replaying its original command.""" + receipt = self.receipt_store.find(dispatch_id, session_id) + if receipt is None: + raise VMRuntimeError(f"no persisted VM receipt for dispatch {dispatch_id}") + request = VMExecutionRequest( + dispatch_id=receipt.dispatch_id, + session_id=receipt.session_id, + command=receipt.command, + host_workspace=receipt.host_workspace, + vm_workspace=receipt.vm_workspace, + timeout_seconds=receipt.timeout_seconds, + idempotency_key=receipt.idempotency_key, + ) + lock = self._locks.setdefault(request.correlation_key, asyncio.Lock()) + async with lock: + current = self.receipt_store.get(request.correlation_key) or receipt + self._validate_receipt_match(current, request) + if current.is_terminal: + return current + return await self._resume_or_recover(current, request) + + def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: + """Collect metadata only for files within the approved workspace.""" + artifacts: list[VMArtifact] = [] + for path in paths: + if not isinstance(path, str) or not path.strip(): + raise VMPathError("artifact paths must be non-empty strings") + if PurePosixPath(path).is_absolute() and not path.startswith( + str(self.workspace.vm_root) + ): + raise VMPathError(f"artifact path escapes VM workspace: {path}") + host_path = ( + self.workspace.map_vm_path(path) + if PurePosixPath(path).is_absolute() + else self.workspace.host_root / path + ) + relative = self.workspace.host_relative(host_path) + vm_path = self.workspace.map_host_path(host_path) + if not host_path.exists(): + artifacts.append(VMArtifact(relative, vm_path, False)) + continue + if not host_path.is_file(): + raise VMPathError(f"artifact path is not a regular file: {path}") + digest = hashlib.sha256(host_path.read_bytes()).hexdigest() + artifacts.append(VMArtifact(relative, vm_path, True, host_path.stat().st_size, digest)) + return tuple(artifacts) + + async def _execute_request(self, request: VMExecutionRequest) -> VMExecutionReceipt: + key = request.correlation_key + lock = self._locks.setdefault(key, asyncio.Lock()) + async with lock: + existing = self.receipt_store.get(key) + if existing is not None: + self._validate_receipt_match(existing, request) + if existing.is_terminal: + return existing + return await self._resume_or_recover(existing, request) + + transport_request = self._prepare_request(request) + started = _now() + running = VMExecutionReceipt( + dispatch_id=request.dispatch_id, + session_id=request.session_id, + idempotency_key=key, + status="running", + command=request.command, + host_workspace=str(self.workspace.host_root), + vm_workspace=transport_request.vm_workspace or str(self.workspace.vm_root), + timeout_seconds=request.timeout_seconds, + started_at=started, + ) + self.receipt_store.put(running) + return await self._call_and_store(running, transport_request, resume=False) + + @staticmethod + def _validate_receipt_match(receipt: VMExecutionReceipt, request: VMExecutionRequest) -> None: + """Reject accidental correlation-key reuse before touching the VM.""" + if ( + receipt.dispatch_id != request.dispatch_id + or receipt.session_id != request.session_id + or receipt.command != request.command + ): + raise VMRuntimeError( + "idempotency key already belongs to a different VM request; refusing replay" + ) + + async def _resume_or_recover( + self, + receipt: VMExecutionReceipt, + request: VMExecutionRequest, + ) -> VMExecutionReceipt: + if receipt.execution_id is None: + return self._store_recovery( + receipt, + "The VM accepted no resumable execution id; refusing to replay the command.", + ) + resume = getattr(self.transport, "resume", None) + if not callable(resume): + return self._store_recovery( + receipt, + "The VM transport cannot resume the accepted execution id; refusing replay.", + ) + return await self._call_and_store(receipt, request, resume=True) + + async def _call_and_store( + self, + receipt: VMExecutionReceipt, + request: VMExecutionRequest, + *, + resume: bool, + ) -> VMExecutionReceipt: + try: + operation = ( + self.transport.resume(request, receipt.execution_id or "") + if resume + else self.transport.execute(request) + ) + raw = await asyncio.wait_for(operation, timeout=request.timeout_seconds) + except TimeoutError: + updated = replace( + receipt, + status="timed_out", + error="VM execution exceeded its timeout", + recovery_required=receipt.execution_id is not None, + finished_at=_now(), + ) + self.receipt_store.put(updated) + return updated + except VMTransportDisconnected as exc: + updated = replace( + receipt, + status="disconnected", + execution_id=exc.execution_id or receipt.execution_id, + error=str(exc), + recovery_required=True, + ) + self.receipt_store.put(updated) + return updated + except (ConnectionError, BrokenPipeError, EOFError) as exc: + updated = replace( + receipt, status="disconnected", error=str(exc), recovery_required=True + ) + self.receipt_store.put(updated) + return updated + except Exception as exc: # transport errors are evidence in the receipt + updated = replace(receipt, status="failed", error=str(exc), finished_at=_now()) + self.receipt_store.put(updated) + return updated + + updated = self._receipt_from_response(receipt, request, raw) + self.receipt_store.put(updated) + return updated + + def _prepare_request(self, request: VMExecutionRequest) -> VMExecutionRequest: + host_workspace = request.host_workspace or str(self.workspace.host_root) + vm_workspace = self.workspace.map_host_path(host_workspace) + for artifact in request.artifact_paths: + candidate = PurePosixPath(artifact) + if candidate.is_absolute() and ( + candidate == self.workspace.vm_root or self.workspace.vm_root in candidate.parents + ): + self.workspace.map_vm_path(artifact) + else: + self.workspace.map_host_path(artifact) + return request.with_vm_workspace(vm_workspace) + + def _receipt_from_response( + self, + receipt: VMExecutionReceipt, + request: VMExecutionRequest, + raw: Any, + ) -> VMExecutionReceipt: + payload = _payload(raw) + execution_id = _optional_text(payload, "execution_id") or receipt.execution_id + status = _optional_text(payload, "status") + if status is None: + status = "completed" if _optional_int(payload, "exit_code", 0) == 0 else "failed" + if status in {"queued", "running", "accepted"}: + status = "running" + exit_code = _optional_int(payload, "exit_code", None) + artifacts = self.collect_artifacts(_artifact_paths(payload, request.artifact_paths)) + return replace( + receipt, + status=status, + execution_id=execution_id, + exit_code=exit_code, + stdout=_optional_text(payload, "stdout") or _optional_text(payload, "output") or "", + stderr=_optional_text(payload, "stderr") or "", + artifacts=artifacts, + error=_optional_text(payload, "error"), + recovery_required=status in {"running", "disconnected", "accepted", "queued"}, + finished_at=None if status == "running" else _now(), + raw=payload, + ) + + def _store_recovery(self, receipt: VMExecutionReceipt, error: str) -> VMExecutionReceipt: + updated = replace(receipt, status="recovery_required", error=error, recovery_required=True) + self.receipt_store.put(updated) + return updated + + +async def _await_if_needed(value: Any) -> Any: + if inspect.isawaitable(value): + return await value + return value + + +def _now() -> str: + return datetime.now(UTC).isoformat() + + +def _mapping(value: Any) -> Mapping[str, Any]: + if isinstance(value, Mapping): + return value + model_dump = getattr(value, "model_dump", None) + if callable(model_dump): + dumped = model_dump(by_alias=True, mode="json", exclude_none=False) + if isinstance(dumped, Mapping): + return dumped + return {} + + +def _payload(value: Any) -> dict[str, Any]: + mapping = dict(_mapping(value)) + if not mapping: + structured = getattr(value, "structured_content", None) + if structured is None: + structured = getattr(value, "structuredContent", None) + mapping = { + "structured_content": structured, + "meta": getattr(value, "meta", None), + "is_error": getattr(value, "is_error", getattr(value, "isError", False)), + } + structured = mapping.get("structuredContent", mapping.get("structured_content")) + meta = mapping.get("meta") + payload = { + str(key): item + for key, item in mapping.items() + if key + not in {"content", "isError", "is_error", "meta", "structuredContent", "structured_content"} + } + if isinstance(meta, Mapping): + payload.update(meta) + if isinstance(structured, Mapping): + payload.update(structured) + return payload + + +def _is_error(raw: Any, payload: Mapping[str, Any]) -> bool: + mapping = _mapping(raw) + if mapping: + return bool( + mapping.get("isError", mapping.get("is_error", payload.get("error") is not None)) + ) + return bool(getattr(raw, "is_error", getattr(raw, "isError", payload.get("error") is not None))) + + +def _object_mapping(value: Any) -> dict[str, Any]: + if isinstance(value, Mapping): + return dict(value) + result: dict[str, Any] = {} + for name in ("dispatch_id", "session_id", "working_directory", "prompt", "command"): + if hasattr(value, name): + result[name] = getattr(value, name) + return result + + +def _required_text(values: Mapping[str, Any], key: str) -> str: + value = values.get(key) + if not isinstance(value, str) or not value.strip(): + raise VMRuntimeError(f"VM dispatch is missing {key}") + return value.strip() + + +def _optional_text(values: Mapping[str, Any], key: str) -> str | None: + value = values.get(key) + return value.strip() if isinstance(value, str) and value.strip() else None + + +def _optional_int(values: Mapping[str, Any], key: str, default: int | None) -> int | None: + value = values.get(key, default) + try: + return int(value) if value is not None else None + except (TypeError, ValueError): + return default + + +def _artifact_paths(payload: Mapping[str, Any], requested: Iterable[str]) -> tuple[str, ...]: + paths = list(requested) + remote = payload.get("artifacts") + if isinstance(remote, Iterable) and not isinstance(remote, (str, bytes, Mapping)): + for item in remote: + if isinstance(item, str): + paths.append(item) + elif isinstance(item, Mapping) and isinstance(item.get("path"), str): + paths.append(item["path"]) + return tuple(dict.fromkeys(paths)) + + +def _json_value(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _json_value(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_value(item) for item in value] + if isinstance(value, (str, int, float, bool)) or value is None: + return value + return str(value) + + +__all__ = [ + "CommandVMTransport", + "JsonVMReceiptStore", + "MCPVMTransport", + "MemoryVMReceiptStore", + "ResumableVMTransport", + "VMArtifact", + "VMCommandTransport", + "VMExecutionReceipt", + "VMExecutionRequest", + "VMMCPTransport", + "VMPersonalAgentRuntime", + "VMPathError", + "VMReceiptStore", + "VMRuntimeError", + "VMTransport", + "VMTransportDisconnected", + "VMTransportError", + "VMWorkspaceMapper", +] diff --git a/tests/integration/host/test_personal_agent_host.py b/tests/integration/host/test_personal_agent_host.py new file mode 100644 index 0000000000..43fec22351 --- /dev/null +++ b/tests/integration/host/test_personal_agent_host.py @@ -0,0 +1,278 @@ +"""Fake-host integration for the explicit personal-agent MCP contract.""" + +from __future__ import annotations + +from copy import deepcopy +from typing import Any + +import pytest + +from ouroboros.integrations.personal_agent_host import ( + GrokBotHostAdapter, + HostSubmissionError, +) + + +def _response(meta: dict[str, Any], *, text: str = "ok") -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": False, + "meta": deepcopy(meta), + } + + +def _pending() -> dict[str, Any]: + return { + "dispatch_id": "fanout_dispatch_1", + "fanout_id": "fanout_dispatch_1", + "host_action": "spawn_subagents", + "dispatch_mode": "host_driven", + "result_correlation_key": "result", + "submit_tool": "ouroboros_submit_fanout_results", + "session_id": "auto_session_1", + "actionable": True, + "subagents": [ + { + "prompt": "WORKING DIRECTORY (mandatory): do the Seed work", + "context": { + "kind": "host_execution", + "working_directory": "/grok/cloud/workspace", + "session_id": "auto_session_1", + }, + } + ], + } + + +class FakeHostTransport: + """Deterministic stand-in for a host's MCP client and worker loop.""" + + def __init__(self) -> None: + self.calls: list[tuple[str, dict[str, Any]]] = [] + self.submitted = False + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + self.calls.append((name, deepcopy(arguments))) + if name == "ouroboros_start_auto": + return _response( + { + "job_id": "job_1", + "auto_session_id": "auto_session_1", + "session_id": "auto_session_1", + "status": "queued", + "runtime_backend": "host", + "cursor": 0, + "is_terminal": False, + "result_available": False, + }, + text="Started background auto session.", + ) + if name == "ouroboros_job_wait": + if not self.submitted: + return _response( + { + "job_id": "job_1", + "status": "running", + "cursor": 1, + "is_terminal": False, + "result_available": False, + "links": {"session_id": "auto_session_1"}, + "pending_host_dispatches": [_pending()], + }, + text="A host worker is required.", + ) + return _response( + { + "job_id": "job_1", + "status": "completed", + "cursor": 2, + "is_terminal": True, + "result_available": True, + "links": { + "session_id": "auto_session_1", + "execution_id": "execution_1", + }, + "seed": {"id": "seed_1", "path": ".ouroboros/seeds/seed_1.yaml"}, + "execution": {"id": "execution_1", "status": "completed"}, + "evaluation": {"status": "passed", "criteria": 3}, + "verification": {"status": "passed", "evidence": ["pytest"]}, + }, + text="Verified.", + ) + if name == "ouroboros_submit_fanout_results": + assert arguments["fanout_id"] == "fanout_dispatch_1" + assert arguments["session_id"] == "auto_session_1" + assert arguments["correlation_key"] == "result" + assert arguments["results"] == [ + {"key": "result", "content": {"final_message": "worker finished"}} + ] + self.submitted = True + return _response( + { + "status": "complete", + "fanout_id": "fanout_dispatch_1", + "kind": "host_execution", + }, + text="Result delivered.", + ) + if name == "ouroboros_job_result": + return _response( + { + "job_id": "job_1", + "status": "completed", + "cursor": 2, + "is_terminal": True, + "result_available": True, + "links": { + "session_id": "auto_session_1", + "execution_id": "execution_1", + }, + "result_payload": { + "seed": {"id": "seed_1"}, + "execution": {"id": "execution_1", "status": "completed"}, + "evaluation": {"status": "passed"}, + "verification": {"status": "passed", "commands": ["pytest"]}, + }, + }, + text="Final verified result.", + ) + raise AssertionError(f"unexpected tool call: {name}") + + +@pytest.mark.integration +@pytest.mark.asyncio +async def test_grok_profile_round_trips_explicit_request_and_verification() -> None: + fake_host = FakeHostTransport() + adapter = GrokBotHostAdapter(fake_host) + + # The host must not let ordinary conversation reach the mutating tool. + assert await adapter.start("Can you search my notes?", host_session_id="grok-1") is None + assert fake_host.calls == [] + + receipt = await adapter.start( + "/ouroboros build the requested feature and verify every acceptance criterion", + host_session_id="grok-1", + cwd="/grok/cloud/workspace", + ) + assert receipt is not None + assert receipt.host_name == "grok_bot" + assert receipt.invocation.explicit is True + assert receipt.invocation.host_session_id == "grok-1" + assert receipt.to_dict()["request"]["request_id"].startswith("hostreq_") + assert receipt.auto_session_id == "auto_session_1" + assert receipt.job_id == "job_1" + assert fake_host.calls[0] == ( + "ouroboros_start_auto", + { + "goal": "build the requested feature and verify every acceptance criterion", + "cwd": "/grok/cloud/workspace", + }, + ) + + waiting = await adapter.wait(receipt) + assert fake_host.calls[1][1]["timeout_seconds"] == 5 + assert len(waiting.pending_host_dispatches) == 1 + dispatch = waiting.pending_host_dispatches[0] + assert dispatch.prompt.startswith("WORKING DIRECTORY") + assert dispatch.working_directory == "/grok/cloud/workspace" + + submitted = await adapter.submit_dispatch( + waiting, + dispatch, + {"final_message": "worker finished"}, + ) + assert submitted.last_submission["status"] == "complete" + + completed = await adapter.wait(submitted) + assert completed.is_terminal is True + assert completed.verification["status"] == "passed" + + final = await adapter.result(completed) + assert final.result_response is not None + assert final.seed["id"] == "seed_1" + assert final.execution["status"] == "completed" + assert final.evaluation["status"] == "passed" + assert final.verification["commands"] == ["pytest"] + assert final.to_dict()["resume"] == { + "tool": "ouroboros_start_auto", + "arguments": {"resume": "auto_session_1"}, + } + + +@pytest.mark.integration +@pytest.mark.asyncio +async def test_resume_uses_the_persisted_auto_session_without_new_goal() -> None: + fake_host = FakeHostTransport() + adapter = GrokBotHostAdapter(fake_host) + + receipt = await adapter.start("/ouroboros resume auto_session_1", host_session_id="grok-2") + + assert receipt is not None + assert receipt.invocation.is_resume + assert fake_host.calls[0] == ( + "ouroboros_start_auto", + {"resume": "auto_session_1"}, + ) + + +class FailureHostTransport(FakeHostTransport): + async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + if name == "ouroboros_job_wait" and self.submitted: + self.calls.append((name, deepcopy(arguments))) + return _response( + { + "job_id": "job_1", + "status": "failed", + "cursor": 3, + "is_terminal": True, + "result_available": True, + "failure": {"reason_code": "host_worker_failed"}, + "recovery": { + "next_step": "resume auto_session_1", + "action": "retry the failed dispatch", + }, + }, + text="Host worker failed.", + ) + if name == "ouroboros_submit_fanout_results": + self.calls.append((name, deepcopy(arguments))) + self.submitted = True + assert arguments["results"] == [{"key": "result", "undispatched": True}] + return _response({"status": "complete", "fanout_id": "fanout_dispatch_1"}) + return await super().call_tool(name, arguments) + + +@pytest.mark.integration +@pytest.mark.asyncio +async def test_undispatched_worker_failure_keeps_recovery_evidence() -> None: + fake_host = FailureHostTransport() + adapter = GrokBotHostAdapter(fake_host) + receipt = await adapter.start("/ouroboros make the change", host_session_id="grok-3") + assert receipt is not None + waiting = await adapter.wait(receipt) + submitted = await adapter.submit_dispatch( + waiting, + waiting.pending_host_dispatches[0], + undispatched=True, + ) + + failed = await adapter.wait(submitted) + assert failed.status == "failed" + assert failed.failure["reason_code"] == "host_worker_failed" + assert failed.recovery["next_step"] == "resume auto_session_1" + + +@pytest.mark.asyncio +async def test_invalid_content_does_not_call_submit_tool() -> None: + fake_host = FakeHostTransport() + adapter = GrokBotHostAdapter(fake_host) + receipt = await adapter.start("/ouroboros make the change") + assert receipt is not None + waiting = await adapter.wait(receipt) + dispatch = waiting.pending_host_dispatches[0] + call_count = len(fake_host.calls) + + with pytest.raises(HostSubmissionError): + await adapter.submit_dispatch(waiting, dispatch, {}) + + assert len(fake_host.calls) == call_count diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py new file mode 100644 index 0000000000..f179bc566e --- /dev/null +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -0,0 +1,131 @@ +"""Unit tests for the platform-neutral personal-agent host contract.""" + +from __future__ import annotations + +import pytest + +from ouroboros.integrations.personal_agent_host import ( + HostAdapterError, + MCPToolTransport, + PersonalAgentHostAdapter, + normalize_tool_response, + parse_explicit_invocation, +) + + +def test_ordinary_messages_are_not_claimed() -> None: + assert parse_explicit_invocation("please remember this for later") is None + assert parse_explicit_invocation("a sentence containing /ouroboros midway") is None + + +def test_explicit_goal_preserves_the_full_user_payload() -> None: + invocation = parse_explicit_invocation( + " /ouroboros refactor the payment boundary\nwhile preserving recovery ", + host_session_id="grok-session-7", + ) + + assert invocation is not None + assert invocation.explicit is True + assert invocation.goal == "refactor the payment boundary\nwhile preserving recovery" + assert invocation.host_session_id == "grok-session-7" + assert invocation.resume_auto_session_id is None + assert invocation.request_id.startswith("hostreq_") + + +@pytest.mark.parametrize( + ("message", "expected"), + [ + ("/ouroboros resume auto_123", "auto_123"), + ("ooo auto --resume auto_456", "auto_456"), + ("/ouroboros --resume=auto_789", "auto_789"), + ], +) +def test_resume_forms_are_explicit_and_structured(message: str, expected: str) -> None: + invocation = parse_explicit_invocation(message) + + assert invocation is not None + assert invocation.goal is None + assert invocation.resume_auto_session_id == expected + assert invocation.is_resume + + +@pytest.mark.parametrize( + "message", + [ + "/ouroboros", + "/ouroboros resume", + "/ouroboros resume one two", + "ooo auto --resume=", + ], +) +def test_malformed_explicit_invocations_fail_closed(message: str) -> None: + with pytest.raises(HostAdapterError): + parse_explicit_invocation(message) + + +def test_negotiation_reports_missing_public_tools() -> None: + adapter = PersonalAgentHostAdapter(lambda _name, _arguments: None) + + result = adapter.negotiate(["ouroboros_start_auto", "ouroboros_job_wait"]) + + assert result.checked is True + assert result.supported is False + assert result.missing_tools == ( + "ouroboros_job_result", + "ouroboros_submit_fanout_results", + ) + assert result.explicit_invocation_only is True + assert result.runtime_backend == "host" + + +def test_unknown_tool_inventory_does_not_claim_support() -> None: + adapter = PersonalAgentHostAdapter(lambda _name, _arguments: None) + + result = adapter.negotiate(None) + + assert result.checked is False + assert result.supported is False + assert result.missing_tools == () + + +def test_wire_response_normalization_preserves_structured_content() -> None: + response = normalize_tool_response( + "ouroboros_start_auto", + { + "content": [{"type": "text", "text": "started"}], + "isError": False, + "meta": {"status": "queued"}, + "structuredContent": {"job_id": "job_1"}, + }, + ) + + assert response.text == "started" + assert response.payload == {"status": "queued", "job_id": "job_1"} + + +@pytest.mark.asyncio +async def test_mcp_transport_wraps_an_async_tool_object() -> None: + class Target: + async def call_tool(self, name: str, arguments: dict[str, object]) -> dict[str, object]: + return {"name": name, "arguments": arguments} + + response = await MCPToolTransport(Target()).call_tool("tool", {"value": 1}) + + assert response == {"name": "tool", "arguments": {"value": 1}} + + +@pytest.mark.asyncio +async def test_adapter_rejects_a_non_host_runtime_before_claiming_execution() -> None: + async def call_tool(_name: str, _arguments: dict[str, object]) -> dict[str, object]: + return { + "meta": { + "job_id": "job_1", + "auto_session_id": "auto_1", + "runtime_backend": "grok", + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + + with pytest.raises(HostAdapterError, match="expected host runtime"): + await adapter.start("/ouroboros do work") diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py new file mode 100644 index 0000000000..1f41a6c566 --- /dev/null +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -0,0 +1,395 @@ +"""Unit coverage for the VM personal-agent runtime bridge.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import pytest + +from ouroboros.integrations import ( + GROK_BOT_VM_PROFILE, + CommandVMTransport, + GrokBotHostAdapter, + JsonVMReceiptStore, + MCPVMTransport, + VMPathError, + VMPersonalAgentRuntime, + VMRuntimeError, + VMTransportDisconnected, + VMWorkspaceMapper, +) + + +class RecordingCommand: + def __init__(self) -> None: + self.calls: list[dict[str, Any]] = [] + + async def execute_command(self, command: str, **kwargs: Any) -> dict[str, Any]: + self.calls.append({"command": command, **kwargs}) + return {"status": "completed", "exit_code": 0, "stdout": "ok"} + + +class RecordingMCP: + def __init__(self) -> None: + self.calls: list[tuple[str, dict[str, Any]]] = [] + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + self.calls.append((name, arguments)) + return {"structuredContent": {"status": "completed", "exit_code": 0}} + + +def test_grok_profile_is_explicitly_unverified_and_public_surface_only() -> None: + assert GROK_BOT_VM_PROFILE.host_name == "grok_bot" + assert GROK_BOT_VM_PROFILE.live_account_verified is False + assert "custom_mcp" in GROK_BOT_VM_PROFILE.public_surface + assert "/ouroboros" in GROK_BOT_VM_PROFILE.invocation_prefixes + + +def test_grok_host_exposes_the_vm_profile() -> None: + adapter = GrokBotHostAdapter(lambda _name, _arguments: None) + assert adapter.vm_profile == GROK_BOT_VM_PROFILE + + +def test_workspace_mapping_rejects_host_and_vm_path_escapes(tmp_path: Path) -> None: + mapper = VMWorkspaceMapper(tmp_path, "/cloud/workspace") + + assert mapper.map_host_path("src/main.py") == "/cloud/workspace/src/main.py" + assert mapper.map_vm_path("/cloud/workspace/src/main.py") == tmp_path / "src/main.py" + + with pytest.raises(VMPathError, match="escapes"): + mapper.map_host_path(tmp_path.parent / "outside.txt") + with pytest.raises(VMPathError, match="escapes"): + mapper.map_vm_path("/cloud/other/secret.txt") + with pytest.raises(VMPathError, match="escapes"): + mapper.map_vm_path("/cloud/workspace/../secret.txt") + + +def test_workspace_mapping_resolves_symlink_escapes(tmp_path: Path) -> None: + outside = tmp_path.parent / "outside-vm-workspace.txt" + outside.write_text("secret", encoding="utf-8") + link = tmp_path / "link" + link.symlink_to(outside) + mapper = VMWorkspaceMapper(tmp_path, "/workspace") + + with pytest.raises(VMPathError, match="escapes"): + mapper.map_host_path("link") + + +def test_artifact_collection_is_workspace_scoped(tmp_path: Path) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + runtime = VMPersonalAgentRuntime( + RecordingCommand(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipts = runtime.collect_artifacts(["result.json"]) + + assert receipts[0].relative_path == "result.json" + assert receipts[0].vm_path == "/workspace/result.json" + assert receipts[0].size > 0 + with pytest.raises(VMPathError): + runtime.collect_artifacts(["../secret.txt"]) + + +def test_artifact_collection_rejects_symlink_escape(tmp_path: Path) -> None: + outside = tmp_path.parent / "outside-artifact.txt" + outside.write_text("secret", encoding="utf-8") + (tmp_path / "link.txt").symlink_to(outside) + runtime = VMPersonalAgentRuntime( + RecordingCommand(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + with pytest.raises(VMPathError, match="escapes"): + runtime.collect_artifacts(["link.txt"]) + + +@pytest.mark.asyncio +async def test_command_transport_maps_cwd_and_idempotency_key(tmp_path: Path) -> None: + target = RecordingCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/vm/workspace"), + ) + + receipt = await runtime.execute_command( + "pytest -q", + dispatch_id="dispatch-1", + session_id="session-1", + host_workspace=tmp_path, + ) + + assert receipt.status == "completed" + assert target.calls == [ + { + "command": "pytest -q", + "cwd": "/vm/workspace", + "timeout_seconds": 300.0, + "idempotency_key": "session-1:dispatch-1", + } + ] + + +@pytest.mark.asyncio +async def test_vm_artifact_paths_are_validated_and_collected(tmp_path: Path) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + runtime = VMPersonalAgentRuntime( + CommandVMTransport(RecordingCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command( + "pytest -q", + dispatch_id="artifact-dispatch", + session_id="artifact-session", + artifact_paths=("/workspace/result.json",), + ) + + assert receipt.artifacts[0].relative_path == "result.json" + assert receipt.artifacts[0].sha256 is not None + + +@pytest.mark.asyncio +async def test_zero_timeout_is_rejected_instead_of_using_the_default(tmp_path: Path) -> None: + runtime = VMPersonalAgentRuntime( + RecordingCommand(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + with pytest.raises(VMRuntimeError, match="timeout_seconds must be positive"): + await runtime.execute_command( + "pytest -q", + dispatch_id="timeout-dispatch", + session_id="timeout-session", + timeout_seconds=0, + ) + + +@pytest.mark.asyncio +async def test_mcp_transport_uses_a_generic_public_command_surface(tmp_path: Path) -> None: + target = RecordingMCP() + runtime = VMPersonalAgentRuntime( + MCPVMTransport(target, execute_tool="agent.command"), + workspace=VMWorkspaceMapper(tmp_path, "/cloud/workspace"), + ) + + receipt = await runtime.execute_command( + "python -V", + dispatch_id="dispatch-2", + session_id="session-2", + ) + + assert receipt.status == "completed" + name, arguments = target.calls[0] + assert name == "agent.command" + assert arguments["cwd"] == "/cloud/workspace" + assert arguments["idempotency_key"] == "session-2:dispatch-2" + + +@pytest.mark.asyncio +async def test_completed_dispatch_is_idempotent_and_never_runs_twice(tmp_path: Path) -> None: + target = RecordingCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + first = await runtime.execute_command("echo one", dispatch_id="d", session_id="s") + second = await runtime.execute_command("echo one", dispatch_id="d", session_id="s") + + assert first == second + assert len(target.calls) == 1 + + +@pytest.mark.asyncio +async def test_concurrent_same_key_calls_execute_once(tmp_path: Path) -> None: + class DelayedCommand(RecordingCommand): + async def execute_command(self, command: str, **kwargs: Any) -> dict[str, Any]: + await asyncio.sleep(0.01) + return await super().execute_command(command, **kwargs) + + target = DelayedCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipts = await asyncio.gather( + *(runtime.execute_command("echo once", dispatch_id="d", session_id="s") for _ in range(20)) + ) + + assert {receipt.status for receipt in receipts} == {"completed"} + assert len(target.calls) == 1 + + +@pytest.mark.asyncio +async def test_idempotency_key_cannot_be_reused_for_a_different_command(tmp_path: Path) -> None: + target = RecordingCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + await runtime.execute_command("echo one", dispatch_id="d", session_id="s") + + with pytest.raises(VMRuntimeError, match="different VM request"): + await runtime.execute_command("echo two", dispatch_id="d", session_id="s") + + assert len(target.calls) == 1 + + +class DisconnectingTransport: + def __init__(self) -> None: + self.execute_calls = 0 + self.resume_calls = 0 + + async def execute(self, _request: Any) -> Any: + self.execute_calls += 1 + raise VMTransportDisconnected("MCP connection dropped", execution_id="remote-1") + + async def resume(self, _request: Any, execution_id: str) -> Any: + self.resume_calls += 1 + assert execution_id == "remote-1" + return {"status": "completed", "exit_code": 0, "stdout": "resumed"} + + +@pytest.mark.asyncio +async def test_disconnect_then_new_runtime_resumes_without_duplicate_execution( + tmp_path: Path, +) -> None: + transport = DisconnectingTransport() + store = JsonVMReceiptStore(tmp_path / "receipts") + workspace = VMWorkspaceMapper(tmp_path, "/workspace") + first_runtime = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + + disconnected = await first_runtime.execute_command( + "make verify", dispatch_id="d", session_id="s" + ) + assert disconnected.status == "disconnected" + assert disconnected.execution_id == "remote-1" + + restarted = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + resumed = await restarted.resume_dispatch("d", session_id="s") + + assert resumed.status == "completed" + assert resumed.stdout == "resumed" + assert transport.execute_calls == 1 + assert transport.resume_calls == 1 + + +def test_corrupt_json_receipt_fails_closed(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + receipt_path = store._path("session:dispatch") + receipt_path.write_text("not json", encoding="utf-8") + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt"): + store.get("session:dispatch") + + +class RunningTransport: + def __init__(self) -> None: + self.execute_calls = 0 + self.resume_calls = 0 + + async def execute(self, _request: Any) -> Any: + self.execute_calls += 1 + return {"status": "running", "execution_id": "remote-2"} + + async def resume(self, _request: Any, execution_id: str) -> Any: + self.resume_calls += 1 + assert execution_id == "remote-2" + return {"status": "completed", "exit_code": 0} + + +@pytest.mark.asyncio +async def test_retry_of_running_receipt_calls_resume_instead_of_execute(tmp_path: Path) -> None: + transport = RunningTransport() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + running = await runtime.execute_command("long task", dispatch_id="d", session_id="s") + completed = await runtime.execute_command("long task", dispatch_id="d", session_id="s") + + assert running.status == "running" + assert completed.status == "completed" + assert transport.execute_calls == 1 + assert transport.resume_calls == 1 + + +@pytest.mark.asyncio +async def test_timeout_without_execution_id_is_recovery_required_and_not_replayed( + tmp_path: Path, +) -> None: + class HangingTransport: + async def execute(self, _request: Any) -> Any: + await asyncio.sleep(1) + return {"status": "completed"} + + runtime = VMPersonalAgentRuntime( + HangingTransport(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + timed_out = await runtime.execute_command( + "slow", + dispatch_id="d", + session_id="s", + timeout_seconds=0.01, + ) + recovered = await runtime.execute_command( + "slow", + dispatch_id="d", + session_id="s", + timeout_seconds=0.01, + ) + + assert timed_out.status == "timed_out" + assert recovered.status == "recovery_required" + assert "refusing to replay" in (recovered.error or "") + + +@pytest.mark.asyncio +async def test_dispatch_object_uses_prompt_and_rejects_unapproved_working_directory( + tmp_path: Path, +) -> None: + target = RecordingCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + result = await runtime.execute_dispatch( + { + "dispatch_id": "d", + "session_id": "s", + "prompt": "run the verification command", + "working_directory": str(tmp_path), + } + ) + assert result.status == "completed" + + vm_result = await runtime.execute_dispatch( + { + "dispatch_id": "vm-cwd", + "session_id": "s", + "prompt": "run from the VM workspace", + "working_directory": "/workspace", + } + ) + assert vm_result.status == "completed" + + with pytest.raises(VMPathError): + await runtime.execute_dispatch( + { + "dispatch_id": "escape", + "session_id": "s", + "prompt": "do not run", + "working_directory": str(tmp_path.parent), + } + ) From 55ca946107d713c6465ef2322be4524e44b23013 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 04:43:11 +0900 Subject: [PATCH 02/41] chore: update runtime adapter task status --- STATUS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/STATUS.md b/STATUS.md index d3a863b26a..af330d6ea0 100644 --- a/STATUS.md +++ b/STATUS.md @@ -10,6 +10,6 @@ - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: 9c3c9dfb (VM personal-agent runtime adapter) +- 마지막 커밋: 0fea8efe (VM personal-agent runtime adapter) - 지금 손댄 파일: STATUS.md, Draft PR 메타데이터 -- 다음 할 일: Draft PR 생성 후 CI와 전체 pytest 결과를 기록하고 live Grokbot 미검증 범위를 유지 +- 다음 할 일: 전체 pytest 종료를 확인하고 Draft PR을 생성한 뒤 PR URL·커밋·게이트 결과를 수령 기록에 남김 From 060966dc3d34eb09ceaf1d3ce938c2f9b2ceea3c Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 05:20:58 +0900 Subject: [PATCH 03/41] chore: finalize runtime adapter task status --- STATUS.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/STATUS.md b/STATUS.md index af330d6ea0..6a7e91309c 100644 --- a/STATUS.md +++ b/STATUS.md @@ -4,12 +4,12 @@ - [x] 1단계: 기준 호스트 어댑터와 검증 자료 확인 - [x] 2단계: VM Personal-Agent Runtime과 Grokbot VM 프로필 구현 - [x] 3단계: 단위 테스트와 보안·복구 시나리오 검증 -- [ ] 👉 4단계: 전체 게이트 확인과 초안 PR 갱신 (현재 위치) +- [x] 4단계: 전체 게이트 확인과 초안 PR 갱신 ## 🛑 블로커 - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: 0fea8efe (VM personal-agent runtime adapter) -- 지금 손댄 파일: STATUS.md, Draft PR 메타데이터 -- 다음 할 일: 전체 pytest 종료를 확인하고 Draft PR을 생성한 뒤 PR URL·커밋·게이트 결과를 수령 기록에 남김 +- 마지막 커밋: 55ca9461 (runtime adapter task status) +- 지금 손댄 파일: STATUS.md, Draft PR #3130 메타데이터 +- 다음 할 일: 최종 커밋을 푸시하고 PR URL·커밋·게이트 결과를 수령 기록에 남김 From 0b8542ec91d9325b8e2349f5a8b9c40054284c17 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 05:59:18 +0900 Subject: [PATCH 04/41] test(integrations): add adversarial concurrency and fault-injection tests for VM host --- src/ouroboros/integrations/__init__.py | 4 + .../integrations/personal_agent_host.py | 150 ++++++++++++++--- .../integrations/vm_agent_runtime.py | 155 +++++++++++++++++- .../host/test_personal_agent_host.py | 69 ++++++++ .../integrations/test_personal_agent_host.py | 9 + .../integrations/test_vm_agent_runtime.py | 92 +++++++++++ 6 files changed, 445 insertions(+), 34 deletions(-) diff --git a/src/ouroboros/integrations/__init__.py b/src/ouroboros/integrations/__init__.py index 1535f502cf..46465e9eec 100644 --- a/src/ouroboros/integrations/__init__.py +++ b/src/ouroboros/integrations/__init__.py @@ -29,6 +29,7 @@ VMPersonalAgentProfile, ) from ouroboros.integrations.vm_agent_runtime import ( + CancellableVMTransport, CommandVMTransport, JsonVMReceiptStore, MCPVMTransport, @@ -43,6 +44,7 @@ VMRuntimeError, VMTransportDisconnected, VMTransportError, + VMTransportTimeout, VMWorkspaceMapper, ) @@ -67,6 +69,7 @@ "GrokBotVMProfile", "VMPersonalAgentProfile", "CommandVMTransport", + "CancellableVMTransport", "JsonVMReceiptStore", "MCPVMTransport", "MemoryVMReceiptStore", @@ -79,6 +82,7 @@ "VMPathError", "VMRuntimeError", "VMTransportDisconnected", + "VMTransportTimeout", "VMTransportError", "VMWorkspaceMapper", ] diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 55ad2095f8..126f70e1ce 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -14,8 +14,10 @@ from __future__ import annotations +import asyncio from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace +import json import shlex from typing import Any, Protocol from uuid import uuid4 @@ -41,6 +43,27 @@ SUBMIT_FANOUT_TOOL, ) +_HOST_RESPONSE_KEYS = frozenset( + { + "auto_session_id", + "cursor", + "evaluation", + "failure", + "fanout_id", + "is_terminal", + "job_id", + "links", + "pending_host_dispatches", + "recovery", + "result_available", + "result_payload", + "runtime_backend", + "seed", + "status", + "verification", + } +) + _DEFAULT_INVOCATION_PREFIXES: tuple[str, ...] = ("/ouroboros", "ooo auto") _RESUME_WORDS = frozenset({"resume", "--resume"}) @@ -311,6 +334,18 @@ def normalize_tool_response(tool_name: str, value: Any) -> HostToolResponse: value = _unwrap_result(value) if isinstance(value, HostToolResponse): return value + if isinstance(value, (str, bytes, bytearray)): + try: + value = json.loads(value) + except (TypeError, ValueError, json.JSONDecodeError) as exc: + raise HostAdapterError( + "MCP response contained invalid JSON", tool_name=tool_name + ) from exc + if not isinstance(value, Mapping): + raise HostAdapterError( + "MCP JSON response must be an object", + tool_name=tool_name, + ) # Avoid importing the optional MCP package; the internal result exposes # the same attributes as the SDK mapping boundary. @@ -344,9 +379,23 @@ def normalize_tool_response(tool_name: str, value: Any) -> HostToolResponse: # MCP calls still use the standard envelope. structured = direct_payload + if structured is not None and not isinstance(structured, Mapping): + raise HostAdapterError( + "MCP structured content must be an object", + tool_name=tool_name, + ) + text = _content_text(content) if not text and isinstance(value, str): text = value + payload_keys = set(meta) + if isinstance(structured, Mapping): + payload_keys.update(structured) + if not is_error and not payload_keys.intersection(_HOST_RESPONSE_KEYS): + raise HostAdapterError( + "MCP response did not contain a recognized Ouroboros payload", + tool_name=tool_name, + ) return HostToolResponse( tool_name=tool_name, is_error=is_error, @@ -377,6 +426,23 @@ def _new_request_id() -> str: return f"hostreq_{uuid4().hex}" +def _start_key( + invocation: HostInvocation, + cwd: str | None, +) -> tuple[str | None, str, str, str]: + action = ( + f"resume:{invocation.resume_auto_session_id}" + if invocation.is_resume + else f"goal:{invocation.goal}" + ) + return ( + invocation.host_session_id, + invocation.command_prefix.casefold(), + action, + cwd or "", + ) + + def _normalized_session_id(value: str | None) -> str | None: if value is None: return None @@ -482,6 +548,8 @@ def __init__( self.host_name = host_name self.invocation_prefixes = tuple(invocation_prefixes) self.expected_runtime_backend = expected_runtime_backend + self._start_locks: dict[tuple[str | None, str, str, str], asyncio.Lock] = {} + self._start_receipts: dict[tuple[str | None, str, str, str], HostExecutionReceipt] = {} @property def required_tools(self) -> tuple[str, ...]: @@ -535,36 +603,45 @@ async def start( arguments = {"resume": invocation.resume_auto_session_id} else: arguments = {"goal": invocation.goal} + normalized_cwd: str | None = None if cwd is not None: normalized_cwd = cwd.strip() if not normalized_cwd: raise HostAdapterError("cwd must not be empty") arguments["cwd"] = normalized_cwd - response = await self._call(START_AUTO_TOOL, arguments) - payload = response.payload - runtime_backend = payload.get("runtime_backend") - if ( - self.expected_runtime_backend is not None - and runtime_backend != self.expected_runtime_backend - ): - raise HostAdapterError( - "Ouroboros start_auto did not negotiate the expected host runtime " - f"(expected={self.expected_runtime_backend!r}, received={runtime_backend!r})", - tool_name=START_AUTO_TOOL, + key = _start_key(invocation, normalized_cwd) + lock = self._start_locks.setdefault(key, asyncio.Lock()) + async with lock: + cached = self._start_receipts.get(key) + if cached is not None: + return cached + response = await self._call(START_AUTO_TOOL, arguments) + payload = response.payload + runtime_backend = payload.get("runtime_backend") + if ( + self.expected_runtime_backend is not None + and runtime_backend != self.expected_runtime_backend + ): + raise HostAdapterError( + "Ouroboros start_auto did not negotiate the expected host runtime " + f"(expected={self.expected_runtime_backend!r}, received={runtime_backend!r})", + tool_name=START_AUTO_TOOL, + response=response, + ) + auto_session_id = _required_text(payload, "auto_session_id", START_AUTO_TOOL) + job_id = _required_text(payload, "job_id", START_AUTO_TOOL) + receipt = _receipt_from_payload( + host_name=self.host_name, + invocation=invocation, + auto_session_id=auto_session_id, + job_id=job_id, + payload=payload, response=response, + start_response=response, ) - auto_session_id = _required_text(payload, "auto_session_id", START_AUTO_TOOL) - job_id = _required_text(payload, "job_id", START_AUTO_TOOL) - return _receipt_from_payload( - host_name=self.host_name, - invocation=invocation, - auto_session_id=auto_session_id, - job_id=job_id, - payload=payload, - response=response, - start_response=response, - ) + self._start_receipts[key] = receipt + return receipt async def wait( self, @@ -605,12 +682,22 @@ async def submit_dispatch( undispatched: bool = False, ) -> HostExecutionReceipt: """Submit one host worker result through Ouroboros's fail-closed seam.""" - if not any( - item.dispatch_id == dispatch.dispatch_id for item in receipt.pending_host_dispatches - ): + current = next( + ( + item + for item in receipt.pending_host_dispatches + if item.dispatch_id == dispatch.dispatch_id + ), + None, + ) + if current is None: raise HostSubmissionError( f"dispatch {dispatch.dispatch_id} is not pending for job {receipt.job_id}" ) + if not _same_dispatch_claim(current, dispatch): + raise HostSubmissionError( + f"dispatch {dispatch.dispatch_id} has a stale correlation token" + ) if not dispatch.actionable: raise HostSubmissionError(f"dispatch {dispatch.dispatch_id} is informational only") if not dispatch.session_id: @@ -918,6 +1005,19 @@ def _validate_host_content(content: Any) -> None: raise HostSubmissionError("successful host execution content needs substantive output") +def _same_dispatch_claim(left: PendingHostDispatch, right: PendingHostDispatch) -> bool: + return ( + left.dispatch_id == right.dispatch_id + and left.fanout_id == right.fanout_id + and left.session_id == right.session_id + and left.result_correlation_key == right.result_correlation_key + and left.submit_tool == right.submit_tool + and left.prompt == right.prompt + and left.working_directory == right.working_directory + and left.actionable == right.actionable + ) + + __all__ = [ "CANCEL_JOB_TOOL", "GROK_BOT_HOST_NAME", diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 547835ccb0..1b0901c0fd 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -43,6 +43,14 @@ def __init__(self, message: str, *, execution_id: str | None = None) -> None: self.execution_id = execution_id +class VMTransportTimeout(VMTransportError): + """The VM accepted an operation but did not finish before the timeout.""" + + def __init__(self, message: str, *, execution_id: str | None = None) -> None: + super().__init__(message) + self.execution_id = execution_id + + @dataclass(frozen=True, slots=True) class VMWorkspaceMapper: """Map paths between one approved host root and one VM root.""" @@ -178,6 +186,7 @@ class VMExecutionReceipt: execution_id: str | None = None exit_code: int | None = None stdout: str = "" + stdout_truncated: bool = False stderr: str = "" artifacts: tuple[VMArtifact, ...] = () error: str | None = None @@ -203,6 +212,7 @@ def to_dict(self) -> dict[str, Any]: "execution_id": self.execution_id, "exit_code": self.exit_code, "stdout": self.stdout, + "stdout_truncated": self.stdout_truncated, "stderr": self.stderr, "artifacts": [artifact.to_dict() for artifact in self.artifacts], "error": self.error, @@ -242,6 +252,7 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: execution_id=(str(value["execution_id"]) if value.get("execution_id") else None), exit_code=(int(value["exit_code"]) if value.get("exit_code") is not None else None), stdout=str(value.get("stdout", "")), + stdout_truncated=bool(value.get("stdout_truncated", False)), stderr=str(value.get("stderr", "")), artifacts=tuple(artifacts), error=(str(value["error"]) if value.get("error") is not None else None), @@ -346,6 +357,13 @@ async def resume(self, request: VMExecutionRequest, execution_id: str) -> Any: """Resume an execution already accepted by the VM.""" +class CancellableVMTransport(VMTransport, Protocol): + """Optional transport extension for cleaning up timed-out executions.""" + + async def cancel(self, request: VMExecutionRequest, execution_id: str) -> Any: + """Cancel or terminate an execution already accepted by the VM.""" + + @dataclass(slots=True) class CommandVMTransport: """Adapt an async VM shell/command callable to ``VMTransport``.""" @@ -382,6 +400,21 @@ async def resume(self, request: VMExecutionRequest, execution_id: str) -> Any: ) ) + async def cancel(self, request: VMExecutionRequest, execution_id: str) -> Any: + caller = getattr(self.target, "cancel_execution", None) + if caller is None: + caller = getattr(self.target, "terminate_execution", None) + if not callable(caller): + raise VMTransportError("command transport cannot cancel execution") + return await _await_if_needed( + caller( + execution_id, + cwd=request.vm_workspace, + timeout_seconds=request.timeout_seconds, + idempotency_key=request.correlation_key, + ) + ) + VMCommandTransport = CommandVMTransport @@ -393,6 +426,7 @@ class MCPVMTransport: target: Any execute_tool: str = "vm.execute" resume_tool: str = "vm.resume" + cancel_tool: str = "vm.cancel" async def execute(self, request: VMExecutionRequest) -> Any: return await self._call( @@ -423,6 +457,20 @@ async def resume(self, request: VMExecutionRequest, execution_id: str) -> Any: }, ) + async def cancel(self, request: VMExecutionRequest, execution_id: str) -> Any: + return await self._call( + self.cancel_tool, + { + "operation": "cancel", + "execution_id": execution_id, + "cwd": request.vm_workspace, + "timeout_seconds": request.timeout_seconds, + "idempotency_key": request.correlation_key, + "dispatch_id": request.dispatch_id, + "session_id": request.session_id, + }, + ) + async def _call(self, name: str, arguments: dict[str, Any]) -> Any: caller = getattr(self.target, "call_tool", self.target) if not callable(caller): @@ -450,13 +498,17 @@ def __init__( workspace: VMWorkspaceMapper, receipt_store: VMReceiptStore | None = None, default_timeout_seconds: float = 300.0, + max_output_chars: int = 64 * 1024, ) -> None: if default_timeout_seconds <= 0: raise VMRuntimeError("default_timeout_seconds must be positive") + if max_output_chars <= 0: + raise VMRuntimeError("max_output_chars must be positive") self.transport = transport self.workspace = workspace self.receipt_store = receipt_store or MemoryVMReceiptStore() self.default_timeout_seconds = default_timeout_seconds + self.max_output_chars = max_output_chars self._locks: dict[str, asyncio.Lock] = {} async def execute_command( @@ -643,16 +695,20 @@ async def _call_and_store( else self.transport.execute(request) ) raw = await asyncio.wait_for(operation, timeout=request.timeout_seconds) + except VMTransportTimeout as exc: + return await self._store_timeout( + receipt, + request, + execution_id=exc.execution_id or receipt.execution_id, + detail=str(exc), + ) except TimeoutError: - updated = replace( + return await self._store_timeout( receipt, - status="timed_out", - error="VM execution exceeded its timeout", - recovery_required=receipt.execution_id is not None, - finished_at=_now(), + request, + execution_id=receipt.execution_id, + detail="VM execution exceeded its timeout", ) - self.receipt_store.put(updated) - return updated except VMTransportDisconnected as exc: updated = replace( receipt, @@ -678,6 +734,38 @@ async def _call_and_store( self.receipt_store.put(updated) return updated + async def _store_timeout( + self, + receipt: VMExecutionReceipt, + request: VMExecutionRequest, + *, + execution_id: str | None, + detail: str, + ) -> VMExecutionReceipt: + cleanup_error: str | None = None + if execution_id is not None: + cancel = getattr(self.transport, "cancel", None) + if callable(cancel): + try: + await asyncio.wait_for( + _await_if_needed(cancel(request, execution_id)), + timeout=1.0, + ) + except Exception as exc: # cleanup evidence belongs in the receipt + cleanup_error = f"; VM cleanup failed: {exc}" + else: + cleanup_error = "; VM transport has no cancellation hook" + updated = replace( + receipt, + status="timed_out", + execution_id=execution_id, + error=f"{detail}{cleanup_error or ''}", + recovery_required=execution_id is not None, + finished_at=_now(), + ) + self.receipt_store.put(updated) + return updated + def _prepare_request(self, request: VMExecutionRequest) -> VMExecutionRequest: host_workspace = request.host_workspace or str(self.workspace.host_root) vm_workspace = self.workspace.map_host_path(host_workspace) @@ -706,18 +794,28 @@ def _receipt_from_response( status = "running" exit_code = _optional_int(payload, "exit_code", None) artifacts = self.collect_artifacts(_artifact_paths(payload, request.artifact_paths)) + stdout, stdout_truncated = _truncate_text( + _optional_text(payload, "stdout") or _optional_text(payload, "output") or "", + self.max_output_chars, + ) + raw_payload = dict(payload) + if "stdout" in raw_payload: + raw_payload["stdout"] = stdout + if "output" in raw_payload: + raw_payload["output"] = stdout return replace( receipt, status=status, execution_id=execution_id, exit_code=exit_code, - stdout=_optional_text(payload, "stdout") or _optional_text(payload, "output") or "", + stdout=stdout, + stdout_truncated=stdout_truncated, stderr=_optional_text(payload, "stderr") or "", artifacts=artifacts, error=_optional_text(payload, "error"), recovery_required=status in {"running", "disconnected", "accepted", "queued"}, finished_at=None if status == "running" else _now(), - raw=payload, + raw=raw_payload, ) def _store_recovery(self, receipt: VMExecutionReceipt, error: str) -> VMExecutionReceipt: @@ -748,6 +846,14 @@ def _mapping(value: Any) -> Mapping[str, Any]: def _payload(value: Any) -> dict[str, Any]: + if isinstance(value, (str, bytes, bytearray)): + try: + decoded = json.loads(value) + except (TypeError, ValueError, json.JSONDecodeError) as exc: + raise VMTransportError("VM transport returned invalid JSON") from exc + if not isinstance(decoded, Mapping): + raise VMTransportError("VM JSON payload must be an object") + value = decoded mapping = dict(_mapping(value)) if not mapping: structured = getattr(value, "structured_content", None) @@ -760,6 +866,10 @@ def _payload(value: Any) -> dict[str, Any]: } structured = mapping.get("structuredContent", mapping.get("structured_content")) meta = mapping.get("meta") + if structured is not None and not isinstance(structured, Mapping): + raise VMTransportError("VM structured content must be an object") + if meta is not None and not isinstance(meta, Mapping): + raise VMTransportError("VM metadata must be an object") payload = { str(key): item for key, item in mapping.items() @@ -770,6 +880,22 @@ def _payload(value: Any) -> dict[str, Any]: payload.update(meta) if isinstance(structured, Mapping): payload.update(structured) + if not payload: + raise VMTransportError("VM transport returned an empty or malformed payload") + if not any( + key in payload + for key in ( + "status", + "exit_code", + "execution_id", + "stdout", + "stderr", + "output", + "artifacts", + "error", + ) + ): + raise VMTransportError("VM transport returned an unrecognized payload") return payload @@ -824,6 +950,15 @@ def _artifact_paths(payload: Mapping[str, Any], requested: Iterable[str]) -> tup return tuple(dict.fromkeys(paths)) +def _truncate_text(value: str, limit: int) -> tuple[str, bool]: + if len(value) <= limit: + return value, False + marker = "\n...[stdout truncated]" + if limit <= len(marker): + return marker[:limit], True + return value[: limit - len(marker)] + marker, True + + def _json_value(value: Any) -> Any: if isinstance(value, Mapping): return {str(key): _json_value(item) for key, item in value.items()} @@ -840,6 +975,7 @@ def _json_value(value: Any) -> Any: "MCPVMTransport", "MemoryVMReceiptStore", "ResumableVMTransport", + "CancellableVMTransport", "VMArtifact", "VMCommandTransport", "VMExecutionReceipt", @@ -851,6 +987,7 @@ def _json_value(value: Any) -> Any: "VMRuntimeError", "VMTransport", "VMTransportDisconnected", + "VMTransportTimeout", "VMTransportError", "VMWorkspaceMapper", ] diff --git a/tests/integration/host/test_personal_agent_host.py b/tests/integration/host/test_personal_agent_host.py index 43fec22351..1b31aa486c 100644 --- a/tests/integration/host/test_personal_agent_host.py +++ b/tests/integration/host/test_personal_agent_host.py @@ -2,12 +2,14 @@ from __future__ import annotations +import asyncio from copy import deepcopy from typing import Any import pytest from ouroboros.integrations.personal_agent_host import ( + START_AUTO_TOOL, GrokBotHostAdapter, HostSubmissionError, ) @@ -139,6 +141,21 @@ async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any raise AssertionError(f"unexpected tool call: {name}") +class DelayedStartHostTransport(FakeHostTransport): + def __init__(self) -> None: + super().__init__() + self.start_entered = asyncio.Event() + self.release_start = asyncio.Event() + self.start_calls = 0 + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + if name == START_AUTO_TOOL: + self.start_calls += 1 + self.start_entered.set() + await self.release_start.wait() + return await super().call_tool(name, arguments) + + @pytest.mark.integration @pytest.mark.asyncio async def test_grok_profile_round_trips_explicit_request_and_verification() -> None: @@ -215,6 +232,30 @@ async def test_resume_uses_the_persisted_auto_session_without_new_goal() -> None ) +@pytest.mark.integration +@pytest.mark.asyncio +async def test_concurrent_duplicate_ouroboros_triggers_share_one_start_receipt() -> None: + fake_host = DelayedStartHostTransport() + adapter = GrokBotHostAdapter(fake_host) + + first_task = asyncio.create_task( + adapter.start("/ouroboros run the verification", host_session_id="grok-duplicate") + ) + await fake_host.start_entered.wait() + second_task = asyncio.create_task( + adapter.start("/ouroboros run the verification", host_session_id="grok-duplicate") + ) + await asyncio.sleep(0) + fake_host.release_start.set() + + first, second = await asyncio.gather(first_task, second_task) + + assert first is not None + assert second == first + assert fake_host.start_calls == 1 + assert [name for name, _ in fake_host.calls] == [START_AUTO_TOOL] + + class FailureHostTransport(FakeHostTransport): async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: if name == "ouroboros_job_wait" and self.submitted: @@ -276,3 +317,31 @@ async def test_invalid_content_does_not_call_submit_tool() -> None: await adapter.submit_dispatch(waiting, dispatch, {}) assert len(fake_host.calls) == call_count + + +@pytest.mark.integration +@pytest.mark.asyncio +async def test_stale_dispatch_correlation_token_is_rejected() -> None: + fake_host = FakeHostTransport() + adapter = GrokBotHostAdapter(fake_host) + receipt = await adapter.start("/ouroboros make the change") + assert receipt is not None + waiting = await adapter.wait(receipt) + dispatch = waiting.pending_host_dispatches[0] + stale_dispatch = dispatch.__class__( + dispatch_id=dispatch.dispatch_id, + fanout_id=dispatch.fanout_id, + session_id=dispatch.session_id, + result_correlation_key="stale-token", + submit_tool=dispatch.submit_tool, + prompt=dispatch.prompt, + working_directory=dispatch.working_directory, + actionable=dispatch.actionable, + raw=dispatch.raw, + ) + call_count = len(fake_host.calls) + + with pytest.raises(HostSubmissionError, match="stale correlation token"): + await adapter.submit_dispatch(waiting, stale_dispatch, {"final_message": "late"}) + + assert len(fake_host.calls) == call_count diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index f179bc566e..4bf228558d 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -103,6 +103,15 @@ def test_wire_response_normalization_preserves_structured_content() -> None: assert response.payload == {"status": "queued", "job_id": "job_1"} +@pytest.mark.parametrize( + "payload", + ["{malformed", "[]", {"structuredContent": ["not an object"]}, {"unknown": True}], +) +def test_malformed_mcp_payloads_fail_closed(payload: object) -> None: + with pytest.raises(HostAdapterError): + normalize_tool_response("ouroboros_job_wait", payload) + + @pytest.mark.asyncio async def test_mcp_transport_wraps_an_async_tool_object() -> None: class Target: diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 1f41a6c566..fd0016d3ab 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -14,10 +14,12 @@ GrokBotHostAdapter, JsonVMReceiptStore, MCPVMTransport, + VMExecutionRequest, VMPathError, VMPersonalAgentRuntime, VMRuntimeError, VMTransportDisconnected, + VMTransportError, VMWorkspaceMapper, ) @@ -190,6 +192,50 @@ async def test_mcp_transport_uses_a_generic_public_command_surface(tmp_path: Pat assert arguments["idempotency_key"] == "session-2:dispatch-2" +@pytest.mark.asyncio +@pytest.mark.parametrize( + "payload", + ["{malformed", "[]", {"structuredContent": ["not an object"]}, {"unknown": True}], +) +async def test_mcp_transport_rejects_malformed_payloads( + payload: object, + tmp_path: Path, +) -> None: + class MalformedMCP: + async def call_tool(self, _name: str, _arguments: dict[str, Any]) -> object: + return payload + + request = VMExecutionRequest( + dispatch_id="malformed", + session_id="session", + command="echo test", + vm_workspace="/workspace", + ) + + with pytest.raises(VMTransportError): + await MCPVMTransport(MalformedMCP()).execute(request) + + +@pytest.mark.asyncio +async def test_oversized_stdout_is_truncated_and_receipt_raw_is_bounded(tmp_path: Path) -> None: + class VerboseCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0, "stdout": "x" * 100} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(VerboseCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_output_chars=32, + ) + + receipt = await runtime.execute_command("verbose", dispatch_id="verbose", session_id="s") + + assert len(receipt.stdout) == 32 + assert receipt.stdout_truncated is True + assert receipt.stdout.endswith("stdout truncated]") + assert receipt.raw["stdout"] == receipt.stdout + + @pytest.mark.asyncio async def test_completed_dispatch_is_idempotent_and_never_runs_twice(tmp_path: Path) -> None: target = RecordingCommand() @@ -354,6 +400,52 @@ async def execute(self, _request: Any) -> Any: assert "refusing to replay" in (recovered.error or "") +@pytest.mark.asyncio +async def test_partial_timeout_cancels_the_remote_execution_before_receipt_is_stored( + tmp_path: Path, +) -> None: + class ZombieTransport: + def __init__(self) -> None: + self.execute_calls = 0 + self.resume_calls = 0 + self.cancelled: list[str] = [] + + async def execute(self, _request: Any) -> Any: + self.execute_calls += 1 + return {"status": "running", "execution_id": "remote-zombie"} + + async def resume(self, _request: Any, execution_id: str) -> Any: + self.resume_calls += 1 + assert execution_id == "remote-zombie" + await asyncio.sleep(1) + return {"status": "completed", "exit_code": 0} + + async def cancel(self, _request: Any, execution_id: str) -> Any: + self.cancelled.append(execution_id) + return {"status": "cancelled", "execution_id": execution_id} + + transport = ZombieTransport() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + running = await runtime.execute_command("long task", dispatch_id="zombie", session_id="s") + timed_out = await runtime.execute_command( + "long task", + dispatch_id="zombie", + session_id="s", + timeout_seconds=0.01, + ) + + assert running.status == "running" + assert timed_out.status == "timed_out" + assert timed_out.recovery_required is True + assert transport.execute_calls == 1 + assert transport.resume_calls == 1 + assert transport.cancelled == ["remote-zombie"] + + @pytest.mark.asyncio async def test_dispatch_object_uses_prompt_and_rejects_unapproved_working_directory( tmp_path: Path, From 7252c48f7f68de6c5ada7a8ee4d58fd11fb330be Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 06:56:40 +0900 Subject: [PATCH 05/41] fix(integrations): harden VM runtime audit boundaries --- STATUS.md | 6 +- docs/verification/grok-bot-host-adapter.md | 80 ++++++ .../integrations/vm_agent_runtime.py | 269 ++++++++++++++---- .../integrations/test_vm_agent_runtime.py | 220 +++++++++++++- 4 files changed, 510 insertions(+), 65 deletions(-) diff --git a/STATUS.md b/STATUS.md index 6a7e91309c..4a0f8e5d80 100644 --- a/STATUS.md +++ b/STATUS.md @@ -10,6 +10,6 @@ - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: 55ca9461 (runtime adapter task status) -- 지금 손댄 파일: STATUS.md, Draft PR #3130 메타데이터 -- 다음 할 일: 최종 커밋을 푸시하고 PR URL·커밋·게이트 결과를 수령 기록에 남김 +- 마지막 커밋: 0b8542ec (adversarial runtime tests; current fixes uncommitted) +- 지금 손댄 파일: vm_agent_runtime.py, test_vm_agent_runtime.py, verification report +- 다음 할 일: required gates 재확인 후 커밋·푸시하고 Draft PR #3130 메타데이터 갱신 diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index c057dc973c..1b9096426e 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -55,3 +55,83 @@ only Codex MCP Apps and the in-app browser. No connector was mutated, no message was sent, and no credential or external process was started. The official public-surface evidence and the precise unverified conditions are in [`grok-bot-public-surface.md`](grok-bot-public-surface.md). + +## Adversarial runtime audit + +Date: 2026-11-30 (Asia/Seoul) + +This round inspected the complete `origin/main...HEAD` diff and exercised the +focused integration tests, path mapping, receipt persistence, disconnect +recovery, malformed transport responses, output bounds, and module-size gate. +The open Draft PR checks were also inspected. At the start of the round, the +repository checks were green for Ruff, MyPy, Bridge TypeScript, module size, +boundary, envelope, and Claude SDK, while the Python 3.12 and Windows sandbox +jobs were still pending. + +The audit found and fixed these concrete contract risks. + +- `resolve_dispatch_workspace()` evaluated the host `Path` before checking the + POSIX VM root. On a Windows host, `PureWindowsPath("/workspace").is_absolute()` + is false, so a VM cwd could be interpreted as a host-relative path. The + mapper now checks POSIX VM containment first, with a simulated Windows-host + regression test. +- Requested artifact paths were validated once as host paths and later treated + as VM paths during collection. An approved absolute host artifact could pass + request preparation and fail during receipt creation. Both stages now use + `resolve_artifact_path()` and the regression suite covers absolute host and + VM paths. +- NUL bytes reached `Path.resolve()` and leaked a raw `ValueError`. All host, + VM, dispatch, and artifact path entry points now raise `VMPathError`. +- `VMExecutionReceipt` did not persist `artifact_paths`, so a restarted + runtime could resume the command without recollecting the requested files. + The field is now serialized and restored, and the JSON restart test verifies + artifact collection after resume. +- Receipt lookup returned the first matching dispatch when multiple sessions + shared a dispatch ID. Memory and JSON stores now fail closed with + `VMRuntimeError` for ambiguous matches. +- A persisted receipt's VM cwd was trusted during resume. Resume now maps the + stored VM cwd back through the approved workspace before invoking a + transport, and a tampered receipt regression test proves that an outside VM + path is rejected before transport calls. +- `stderr` was unbounded even though `stdout` was capped, and artifact hashing + loaded each complete file into memory. stderr is now capped in both the + receipt and raw payload, while hashing streams 1 MiB chunks. +- Separate runtime instances sharing one JSON receipt directory could both + observe a missing receipt and start the same VM command. The JSON store now + claims a new receipt with an atomic hard-link operation; a second runtime + sees the running receipt and enters recovery without replaying the command. +- A command transport response containing only `error` was previously inferred + as a successful zero-exit response. Error-bearing and explicit `error` + statuses now produce terminal failed receipts, and the regression test + proves the error is retained. +- A VM root containing `..` could serialize an escaping VM cwd even though + host-side mapping later rejected some paths. VM-root configuration now fails + closed at construction, and output-limit type validation rejects malformed + runtime configuration before execution. + +The initial focused run passed 56 tests. The new unit coverage passes 38 tests, +and the full focused command passes 70 tests after the fixes. The direct +initial reproductions were a raw `ValueError` for `map_host_path("bad\\x00name")` +and 100 stored stderr characters with `max_output_chars=16`. After the fixes, +the same probes return `VMPathError` and 16 stored stderr characters. + +Commands run for this round: + +```text +uv run pytest tests/unit/integrations/ tests/integration/host/ -q +uv run ruff format --check src/ouroboros/integrations tests/unit/integrations tests/integration/host +uv run ruff check src/ouroboros/integrations tests/unit/integrations tests/integration/host +uv run mypy src/ouroboros +python3 scripts/check-module-size.py --baseline-ref origin/main +``` + +The live paid Grok Bot account and provider-side VM remain unverified. The +runtime evidence in this entry uses deterministic fake command and MCP +transports. + +The repository-wide `uv run pytest` attempt under local Python 3.14 reached +9,739 passed, 119 skipped, and 1 xfailed before it was stopped after three +unrelated failures: two existing cleanup tests in +`tests/unit/boundary/test_base_regression.py` and one output-contract test in +`tests/unit/cli/test_run_successors.py`. The touched integration/runtime +tests and all required repository gates passed independently. diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 1b0901c0fd..25c867f778 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -17,6 +17,7 @@ import hashlib import inspect import json +import math import os from pathlib import Path, PurePosixPath import tempfile @@ -51,6 +52,19 @@ def __init__(self, message: str, *, execution_id: str | None = None) -> None: self.execution_id = execution_id +def _path_text(value: str | os.PathLike[str], label: str) -> str: + """Return a path string while converting invalid path input to VMPathError.""" + try: + text = os.fspath(value) + except TypeError as exc: + raise VMPathError(f"{label} must be a path string") from exc + if not isinstance(text, str): + raise VMPathError(f"{label} must be a text path") + if "\x00" in text: + raise VMPathError(f"{label} must not contain NUL bytes") + return text + + @dataclass(frozen=True, slots=True) class VMWorkspaceMapper: """Map paths between one approved host root and one VM root.""" @@ -59,10 +73,17 @@ class VMWorkspaceMapper: vm_root: PurePosixPath def __init__(self, host_root: str | Path, vm_root: str) -> None: - host = Path(host_root).expanduser().resolve() - vm = PurePosixPath(vm_root) + host_text = _path_text(host_root, "host_root") + vm_text = _path_text(vm_root, "vm_root") + try: + host = Path(host_text).expanduser().resolve() + vm = PurePosixPath(vm_text) + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError("workspace paths must be valid paths") from exc if not vm.is_absolute(): raise VMPathError("vm_root must be an absolute POSIX path") + if ".." in vm.parts: + raise VMPathError("vm_root must not contain parent traversal") object.__setattr__(self, "host_root", host) object.__setattr__(self, "vm_root", vm) @@ -74,7 +95,11 @@ def map_host_path(self, path: str | Path) -> str: def map_vm_path(self, path: str) -> Path: """Map an approved VM path back to a host path, rejecting escapes.""" - candidate = PurePosixPath(path) + text = _path_text(path, "VM path") + try: + candidate = PurePosixPath(text) + except (OSError, ValueError) as exc: + raise VMPathError(f"VM path is invalid: {path}") from exc try: relative = candidate.relative_to(self.vm_root) except ValueError as exc: @@ -88,28 +113,46 @@ def map_vm_path(self, path: str) -> Path: def resolve_dispatch_workspace(self, path: str | Path) -> Path: """Resolve a dispatch cwd supplied in host or VM path notation.""" - candidate = Path(path).expanduser() + text = _path_text(path, "dispatch workspace") + vm_candidate = PurePosixPath(text) + if vm_candidate.is_relative_to(self.vm_root): + return self.map_vm_path(text) + try: + candidate = Path(text).expanduser() + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError(f"dispatch workspace is invalid: {path!s}") from exc if not candidate.is_absolute(): return self._resolve_host_path(candidate) - resolved_host = candidate.resolve(strict=False) + try: + resolved_host = candidate.resolve(strict=False) + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError(f"dispatch workspace is invalid: {path!s}") from exc if resolved_host.is_relative_to(self.host_root): return resolved_host - - vm_candidate = PurePosixPath(str(path)) - if vm_candidate.is_relative_to(self.vm_root): - return self.map_vm_path(str(path)) raise VMPathError(f"dispatch workspace escapes approved workspace: {path!s}") def host_relative(self, path: str | Path) -> str: """Return a stable workspace-relative path for an artifact receipt.""" return self._resolve_host_path(path).relative_to(self.host_root).as_posix() + def resolve_artifact_path(self, path: str | Path) -> Path: + """Resolve a host or VM artifact path using one containment rule.""" + text = _path_text(path, "artifact path") + vm_candidate = PurePosixPath(text) + if vm_candidate.is_absolute() and vm_candidate.is_relative_to(self.vm_root): + return self.map_vm_path(text) + return self._resolve_host_path(text) + def _resolve_host_path(self, path: str | Path) -> Path: - candidate = Path(path).expanduser() - if not candidate.is_absolute(): - candidate = self.host_root / candidate - resolved = candidate.resolve(strict=False) + text = _path_text(path, "host path") + try: + candidate = Path(text).expanduser() + if not candidate.is_absolute(): + candidate = self.host_root / candidate + resolved = candidate.resolve(strict=False) + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError(f"host path is invalid: {path!s}") from exc try: resolved.relative_to(self.host_root) except ValueError as exc: @@ -131,10 +174,21 @@ class VMExecutionRequest: artifact_paths: tuple[str, ...] = () def __post_init__(self) -> None: - if not self.dispatch_id.strip() or not self.session_id.strip(): - raise VMRuntimeError("dispatch_id and session_id are required") - if not self.command.strip(): - raise VMRuntimeError("command or personal-agent turn must not be empty") + for name, value in ( + ("dispatch_id", self.dispatch_id), + ("session_id", self.session_id), + ("command", self.command), + ): + if not isinstance(value, str) or not value.strip(): + raise VMRuntimeError(f"{name} must be non-empty text") + if "\x00" in value: + raise VMRuntimeError(f"{name} must not contain NUL bytes") + if self.idempotency_key is not None and not isinstance(self.idempotency_key, str): + raise VMRuntimeError("idempotency_key must be text") + if not isinstance(self.timeout_seconds, (int, float)) or not math.isfinite( + self.timeout_seconds + ): + raise VMRuntimeError("timeout_seconds must be finite") if self.timeout_seconds <= 0: raise VMRuntimeError("timeout_seconds must be positive") @@ -188,7 +242,9 @@ class VMExecutionReceipt: stdout: str = "" stdout_truncated: bool = False stderr: str = "" + stderr_truncated: bool = False artifacts: tuple[VMArtifact, ...] = () + artifact_paths: tuple[str, ...] = () error: str | None = None recovery_required: bool = False started_at: str = "" @@ -214,7 +270,9 @@ def to_dict(self) -> dict[str, Any]: "stdout": self.stdout, "stdout_truncated": self.stdout_truncated, "stderr": self.stderr, + "stderr_truncated": self.stderr_truncated, "artifacts": [artifact.to_dict() for artifact in self.artifacts], + "artifact_paths": list(self.artifact_paths), "error": self.error, "recovery_required": self.recovery_required, "started_at": self.started_at, @@ -240,6 +298,13 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: ), ) ) + raw_artifact_paths = value.get("artifact_paths", ()) + artifact_paths = ( + tuple(item for item in raw_artifact_paths if isinstance(item, str)) + if isinstance(raw_artifact_paths, Iterable) + and not isinstance(raw_artifact_paths, (str, bytes)) + else () + ) return cls( dispatch_id=str(value["dispatch_id"]), session_id=str(value["session_id"]), @@ -254,7 +319,9 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: stdout=str(value.get("stdout", "")), stdout_truncated=bool(value.get("stdout_truncated", False)), stderr=str(value.get("stderr", "")), + stderr_truncated=bool(value.get("stderr_truncated", False)), artifacts=tuple(artifacts), + artifact_paths=artifact_paths, error=(str(value["error"]) if value.get("error") is not None else None), recovery_required=bool(value.get("recovery_required", False)), started_at=str(value.get("started_at", "")), @@ -272,6 +339,9 @@ def get(self, key: str) -> VMExecutionReceipt | None: def put(self, receipt: VMExecutionReceipt) -> None: """Atomically persist one receipt.""" + def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: + """Claim a new receipt, returning the existing receipt when raced.""" + def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: """Find a receipt after a process restart.""" @@ -288,14 +358,24 @@ def get(self, key: str) -> VMExecutionReceipt | None: def put(self, receipt: VMExecutionReceipt) -> None: self._receipts[receipt.idempotency_key] = receipt - def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: - for receipt in self._receipts.values(): - if receipt.dispatch_id == dispatch_id and ( - session_id is None or receipt.session_id == session_id - ): - return receipt + def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: + existing = self._receipts.get(receipt.idempotency_key) + if existing is not None: + return existing + self._receipts[receipt.idempotency_key] = receipt return None + def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: + matches = [ + receipt + for receipt in self._receipts.values() + if receipt.dispatch_id == dispatch_id + and (session_id is None or receipt.session_id == session_id) + ] + if len(matches) > 1: + raise VMRuntimeError(f"ambiguous VM receipt for dispatch {dispatch_id!r}") + return matches[0] if matches else None + class JsonVMReceiptStore: """Atomic JSON receipt store that survives host process restarts.""" @@ -330,7 +410,26 @@ def put(self, receipt: VMExecutionReceipt) -> None: if os.path.exists(temporary): os.unlink(temporary) + def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: + """Create a receipt without allowing concurrent runtimes to overwrite a claim.""" + path = self._path(receipt.idempotency_key) + fd, temporary = tempfile.mkstemp(prefix=".receipt-", suffix=".tmp", dir=self.directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + try: + os.link(temporary, path) + except FileExistsError: + return self.get(receipt.idempotency_key) + return None + finally: + if os.path.exists(temporary): + os.unlink(temporary) + def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: + matches: list[VMExecutionReceipt] = [] for path in self.directory.glob("*.json"): try: receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) @@ -339,8 +438,10 @@ def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionRe if receipt.dispatch_id == dispatch_id and ( session_id is None or receipt.session_id == session_id ): - return receipt - return None + matches.append(receipt) + if len(matches) > 1: + raise VMRuntimeError(f"ambiguous VM receipt for dispatch {dispatch_id!r}") + return matches[0] if matches else None class VMTransport(Protocol): @@ -500,10 +601,18 @@ def __init__( default_timeout_seconds: float = 300.0, max_output_chars: int = 64 * 1024, ) -> None: + if not isinstance(default_timeout_seconds, (int, float)) or not math.isfinite( + default_timeout_seconds + ): + raise VMRuntimeError("default_timeout_seconds must be finite") if default_timeout_seconds <= 0: raise VMRuntimeError("default_timeout_seconds must be positive") - if max_output_chars <= 0: - raise VMRuntimeError("max_output_chars must be positive") + if ( + not isinstance(max_output_chars, int) + or isinstance(max_output_chars, bool) + or max_output_chars <= 0 + ): + raise VMRuntimeError("max_output_chars must be a positive integer") self.transport = transport self.workspace = workspace self.receipt_store = receipt_store or MemoryVMReceiptStore() @@ -581,15 +690,17 @@ async def resume_dispatch( receipt = self.receipt_store.find(dispatch_id, session_id) if receipt is None: raise VMRuntimeError(f"no persisted VM receipt for dispatch {dispatch_id}") - request = VMExecutionRequest( + approved_host_workspace = self.workspace.map_vm_path(receipt.vm_workspace) + persisted_request = VMExecutionRequest( dispatch_id=receipt.dispatch_id, session_id=receipt.session_id, command=receipt.command, - host_workspace=receipt.host_workspace, - vm_workspace=receipt.vm_workspace, + host_workspace=str(approved_host_workspace), timeout_seconds=receipt.timeout_seconds, idempotency_key=receipt.idempotency_key, + artifact_paths=receipt.artifact_paths, ) + request = self._prepare_request(persisted_request) lock = self._locks.setdefault(request.correlation_key, asyncio.Lock()) async with lock: current = self.receipt_store.get(request.correlation_key) or receipt @@ -604,15 +715,7 @@ def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: for path in paths: if not isinstance(path, str) or not path.strip(): raise VMPathError("artifact paths must be non-empty strings") - if PurePosixPath(path).is_absolute() and not path.startswith( - str(self.workspace.vm_root) - ): - raise VMPathError(f"artifact path escapes VM workspace: {path}") - host_path = ( - self.workspace.map_vm_path(path) - if PurePosixPath(path).is_absolute() - else self.workspace.host_root / path - ) + host_path = self.workspace.resolve_artifact_path(path) relative = self.workspace.host_relative(host_path) vm_path = self.workspace.map_host_path(host_path) if not host_path.exists(): @@ -620,22 +723,25 @@ def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: continue if not host_path.is_file(): raise VMPathError(f"artifact path is not a regular file: {path}") - digest = hashlib.sha256(host_path.read_bytes()).hexdigest() - artifacts.append(VMArtifact(relative, vm_path, True, host_path.stat().st_size, digest)) + try: + size, digest = _hash_file(host_path) + except OSError as exc: + raise VMPathError(f"artifact path cannot be read: {path}") from exc + artifacts.append(VMArtifact(relative, vm_path, True, size, digest)) return tuple(artifacts) async def _execute_request(self, request: VMExecutionRequest) -> VMExecutionReceipt: key = request.correlation_key lock = self._locks.setdefault(key, asyncio.Lock()) async with lock: + transport_request = self._prepare_request(request) existing = self.receipt_store.get(key) if existing is not None: - self._validate_receipt_match(existing, request) + self._validate_receipt_match(existing, transport_request) if existing.is_terminal: return existing - return await self._resume_or_recover(existing, request) + return await self._resume_or_recover(existing, transport_request) - transport_request = self._prepare_request(request) started = _now() running = VMExecutionReceipt( dispatch_id=request.dispatch_id, @@ -643,14 +749,28 @@ async def _execute_request(self, request: VMExecutionRequest) -> VMExecutionRece idempotency_key=key, status="running", command=request.command, - host_workspace=str(self.workspace.host_root), + host_workspace=transport_request.host_workspace or str(self.workspace.host_root), vm_workspace=transport_request.vm_workspace or str(self.workspace.vm_root), timeout_seconds=request.timeout_seconds, + artifact_paths=request.artifact_paths, started_at=started, ) - self.receipt_store.put(running) + claim = getattr(self.receipt_store, "put_if_absent", None) + existing_after_claim = ( + claim(running) if callable(claim) else self._put_without_claim(running) + ) + if existing_after_claim is not None: + self._validate_receipt_match(existing_after_claim, transport_request) + if existing_after_claim.is_terminal: + return existing_after_claim + return await self._resume_or_recover(existing_after_claim, transport_request) return await self._call_and_store(running, transport_request, resume=False) + def _put_without_claim(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: + """Keep compatibility with third-party stores predating atomic claims.""" + self.receipt_store.put(receipt) + return None + @staticmethod def _validate_receipt_match(receipt: VMExecutionReceipt, request: VMExecutionRequest) -> None: """Reject accidental correlation-key reuse before touching the VM.""" @@ -658,6 +778,8 @@ def _validate_receipt_match(receipt: VMExecutionReceipt, request: VMExecutionReq receipt.dispatch_id != request.dispatch_id or receipt.session_id != request.session_id or receipt.command != request.command + or receipt.vm_workspace != request.vm_workspace + or receipt.artifact_paths != request.artifact_paths ): raise VMRuntimeError( "idempotency key already belongs to a different VM request; refusing replay" @@ -768,16 +890,15 @@ async def _store_timeout( def _prepare_request(self, request: VMExecutionRequest) -> VMExecutionRequest: host_workspace = request.host_workspace or str(self.workspace.host_root) - vm_workspace = self.workspace.map_host_path(host_workspace) + resolved_workspace = self.workspace._resolve_host_path(host_workspace) + vm_workspace = self.workspace.map_host_path(resolved_workspace) for artifact in request.artifact_paths: - candidate = PurePosixPath(artifact) - if candidate.is_absolute() and ( - candidate == self.workspace.vm_root or self.workspace.vm_root in candidate.parents - ): - self.workspace.map_vm_path(artifact) - else: - self.workspace.map_host_path(artifact) - return request.with_vm_workspace(vm_workspace) + self.workspace.resolve_artifact_path(artifact) + return replace( + request, + host_workspace=str(resolved_workspace), + vm_workspace=vm_workspace, + ) def _receipt_from_response( self, @@ -788,12 +909,20 @@ def _receipt_from_response( payload = _payload(raw) execution_id = _optional_text(payload, "execution_id") or receipt.execution_id status = _optional_text(payload, "status") + response_error = _optional_text(payload, "error") if status is None: - status = "completed" if _optional_int(payload, "exit_code", 0) == 0 else "failed" + status = ( + "failed" + if response_error is not None or _optional_int(payload, "exit_code", 0) != 0 + else "completed" + ) + elif status == "error" or status == "completed" and response_error is not None: + status = "failed" if status in {"queued", "running", "accepted"}: status = "running" exit_code = _optional_int(payload, "exit_code", None) - artifacts = self.collect_artifacts(_artifact_paths(payload, request.artifact_paths)) + artifact_paths = _artifact_paths(payload, request.artifact_paths) + artifacts = self.collect_artifacts(artifact_paths) stdout, stdout_truncated = _truncate_text( _optional_text(payload, "stdout") or _optional_text(payload, "output") or "", self.max_output_chars, @@ -803,6 +932,11 @@ def _receipt_from_response( raw_payload["stdout"] = stdout if "output" in raw_payload: raw_payload["output"] = stdout + stderr, stderr_truncated = _truncate_text( + _optional_text(payload, "stderr") or "", self.max_output_chars, label="stderr" + ) + if "stderr" in raw_payload: + raw_payload["stderr"] = stderr return replace( receipt, status=status, @@ -810,9 +944,11 @@ def _receipt_from_response( exit_code=exit_code, stdout=stdout, stdout_truncated=stdout_truncated, - stderr=_optional_text(payload, "stderr") or "", + stderr=stderr, + stderr_truncated=stderr_truncated, artifacts=artifacts, - error=_optional_text(payload, "error"), + artifact_paths=artifact_paths, + error=response_error, recovery_required=status in {"running", "disconnected", "accepted", "queued"}, finished_at=None if status == "running" else _now(), raw=raw_payload, @@ -950,10 +1086,21 @@ def _artifact_paths(payload: Mapping[str, Any], requested: Iterable[str]) -> tup return tuple(dict.fromkeys(paths)) -def _truncate_text(value: str, limit: int) -> tuple[str, bool]: +def _hash_file(path: Path) -> tuple[int, str]: + digest = hashlib.sha256() + size = 0 + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + with os.fdopen(os.open(path, flags), "rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + size += len(chunk) + digest.update(chunk) + return size, digest.hexdigest() + + +def _truncate_text(value: str, limit: int, *, label: str = "stdout") -> tuple[str, bool]: if len(value) <= limit: return value, False - marker = "\n...[stdout truncated]" + marker = f"\n...[{label} truncated]" if limit <= len(marker): return marker[:limit], True return value[: limit - len(marker)] + marker, True diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index fd0016d3ab..7e70a9f29a 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -3,7 +3,8 @@ from __future__ import annotations import asyncio -from pathlib import Path +import json +from pathlib import Path, PureWindowsPath from typing import Any import pytest @@ -14,6 +15,7 @@ GrokBotHostAdapter, JsonVMReceiptStore, MCPVMTransport, + MemoryVMReceiptStore, VMExecutionRequest, VMPathError, VMPersonalAgentRuntime, @@ -67,6 +69,9 @@ def test_workspace_mapping_rejects_host_and_vm_path_escapes(tmp_path: Path) -> N with pytest.raises(VMPathError, match="escapes"): mapper.map_vm_path("/cloud/workspace/../secret.txt") + with pytest.raises(VMPathError, match="parent traversal"): + VMWorkspaceMapper(tmp_path, "/cloud/workspace/../unsafe") + def test_workspace_mapping_resolves_symlink_escapes(tmp_path: Path) -> None: outside = tmp_path.parent / "outside-vm-workspace.txt" @@ -109,6 +114,37 @@ def test_artifact_collection_rejects_symlink_escape(tmp_path: Path) -> None: runtime.collect_artifacts(["link.txt"]) +def test_dispatch_workspace_checks_posix_vm_root_before_windows_host_absolute_check( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + import ouroboros.integrations.vm_agent_runtime as runtime_module + + mapper = VMWorkspaceMapper(tmp_path, "/workspace") + monkeypatch.setattr(runtime_module, "Path", PureWindowsPath) + + assert mapper.resolve_dispatch_workspace("/workspace/src") == tmp_path / "src" + + +@pytest.mark.parametrize("operation", ["host", "vm", "dispatch", "artifact"]) +def test_nul_bytes_are_rejected_as_vm_path_errors( + operation: str, + tmp_path: Path, +) -> None: + mapper = VMWorkspaceMapper(tmp_path, "/workspace") + runtime = VMPersonalAgentRuntime(RecordingCommand(), workspace=mapper) + + with pytest.raises(VMPathError): + if operation == "host": + mapper.map_host_path("bad\x00name") + elif operation == "vm": + mapper.map_vm_path("/workspace/bad\x00name") + elif operation == "dispatch": + mapper.resolve_dispatch_workspace("/workspace/bad\x00name") + else: + runtime.collect_artifacts(["bad\x00name"]) + + @pytest.mark.asyncio async def test_command_transport_maps_cwd_and_idempotency_key(tmp_path: Path) -> None: target = RecordingCommand() @@ -155,6 +191,28 @@ async def test_vm_artifact_paths_are_validated_and_collected(tmp_path: Path) -> assert receipt.artifacts[0].sha256 is not None +@pytest.mark.asyncio +async def test_host_artifact_path_is_normalized_consistently_before_and_after_dispatch( + tmp_path: Path, +) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + runtime = VMPersonalAgentRuntime( + CommandVMTransport(RecordingCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command( + "pytest -q", + dispatch_id="host-artifact", + session_id="session", + artifact_paths=(str(artifact),), + ) + + assert receipt.artifact_paths == (str(artifact),) + assert receipt.artifacts[0].relative_path == "result.json" + + @pytest.mark.asyncio async def test_zero_timeout_is_rejected_instead_of_using_the_default(tmp_path: Path) -> None: runtime = VMPersonalAgentRuntime( @@ -236,6 +294,55 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] assert receipt.raw["stdout"] == receipt.stdout +@pytest.mark.asyncio +async def test_oversized_stderr_is_truncated_and_receipt_raw_is_bounded(tmp_path: Path) -> None: + class VerboseCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0, "stderr": "x" * 100} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(VerboseCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_output_chars=32, + ) + + receipt = await runtime.execute_command("verbose", dispatch_id="stderr", session_id="s") + + assert len(receipt.stderr) == 32 + assert receipt.stderr_truncated is True + assert receipt.stderr.endswith("stderr truncated]") + assert receipt.raw["stderr"] == receipt.stderr + + +@pytest.mark.asyncio +async def test_command_error_payload_is_failed_instead_of_defaulting_to_success( + tmp_path: Path, +) -> None: + class RejectingCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"error": "permission denied"} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(RejectingCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("private command", dispatch_id="error", session_id="s") + + assert receipt.status == "failed" + assert receipt.is_terminal is True + assert receipt.error == "permission denied" + + +def test_invalid_output_limit_is_rejected_as_runtime_input(tmp_path: Path) -> None: + with pytest.raises(VMRuntimeError, match="positive integer"): + VMPersonalAgentRuntime( + RecordingCommand(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_output_chars=True, + ) + + @pytest.mark.asyncio async def test_completed_dispatch_is_idempotent_and_never_runs_twice(tmp_path: Path) -> None: target = RecordingCommand() @@ -272,6 +379,46 @@ async def execute_command(self, command: str, **kwargs: Any) -> dict[str, Any]: assert len(target.calls) == 1 +@pytest.mark.asyncio +async def test_separate_runtimes_sharing_json_store_claim_a_dispatch_once(tmp_path: Path) -> None: + class BlockingCommand: + def __init__(self) -> None: + self.started = asyncio.Event() + self.release = asyncio.Event() + self.calls = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.calls += 1 + self.started.set() + await self.release.wait() + return {"status": "completed", "exit_code": 0} + + target = BlockingCommand() + store = JsonVMReceiptStore(tmp_path / "receipts") + mapper = VMWorkspaceMapper(tmp_path, "/workspace") + first = VMPersonalAgentRuntime( + CommandVMTransport(target), workspace=mapper, receipt_store=store + ) + second = VMPersonalAgentRuntime( + CommandVMTransport(target), workspace=mapper, receipt_store=store + ) + + first_task = asyncio.create_task( + first.execute_command("echo once", dispatch_id="shared", session_id="s") + ) + await asyncio.wait_for(target.started.wait(), timeout=1) + second_task = asyncio.create_task( + second.execute_command("echo once", dispatch_id="shared", session_id="s") + ) + second_result = await asyncio.wait_for(second_task, timeout=1) + target.release.set() + first_result = await asyncio.wait_for(first_task, timeout=1) + + assert target.calls == 1 + assert first_result.status == "completed" + assert second_result.status == "recovery_required" + + @pytest.mark.asyncio async def test_idempotency_key_cannot_be_reused_for_a_different_command(tmp_path: Path) -> None: target = RecordingCommand() @@ -327,6 +474,77 @@ async def test_disconnect_then_new_runtime_resumes_without_duplicate_execution( assert transport.resume_calls == 1 +@pytest.mark.asyncio +async def test_resume_dispatch_restores_artifact_paths_from_json_receipt( + tmp_path: Path, +) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + transport = DisconnectingTransport() + store = JsonVMReceiptStore(tmp_path / "receipts") + workspace = VMWorkspaceMapper(tmp_path, "/workspace") + first_runtime = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + + disconnected = await first_runtime.execute_command( + "make verify", + dispatch_id="artifact-resume", + session_id="s", + artifact_paths=("result.json",), + ) + assert disconnected.artifact_paths == ("result.json",) + + restarted = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + resumed = await restarted.resume_dispatch("artifact-resume", session_id="s") + + assert resumed.artifact_paths == ("result.json",) + assert resumed.artifacts[0].relative_path == "result.json" + + +@pytest.mark.asyncio +async def test_resume_dispatch_rejects_a_receipt_with_an_unapproved_vm_workspace( + tmp_path: Path, +) -> None: + transport = DisconnectingTransport() + store = JsonVMReceiptStore(tmp_path / "receipts") + workspace = VMWorkspaceMapper(tmp_path, "/workspace") + runtime = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + + await runtime.execute_command("make verify", dispatch_id="tampered", session_id="s") + receipt_path = store._path("s:tampered") + payload = json.loads(receipt_path.read_text(encoding="utf-8")) + payload["vm_workspace"] = "/outside-tenant" + receipt_path.write_text(json.dumps(payload), encoding="utf-8") + + with pytest.raises(VMPathError, match="escapes"): + await runtime.resume_dispatch("tampered", session_id="s") + assert transport.resume_calls == 0 + + +@pytest.mark.parametrize("store_kind", ["memory", "json"]) +def test_find_fails_closed_for_ambiguous_dispatch_id( + store_kind: str, + tmp_path: Path, +) -> None: + store = ( + MemoryVMReceiptStore() + if store_kind == "memory" + else JsonVMReceiptStore(tmp_path / "receipts") + ) + target = RecordingCommand() + + async def populate() -> None: + runtime = VMPersonalAgentRuntime( + target, workspace=VMWorkspaceMapper(tmp_path, "/workspace"), receipt_store=store + ) + await runtime.execute_command("echo one", dispatch_id="shared", session_id="one") + await runtime.execute_command("echo two", dispatch_id="shared", session_id="two") + + asyncio.run(populate()) + + with pytest.raises(VMRuntimeError, match="ambiguous VM receipt"): + store.find("shared") + + def test_corrupt_json_receipt_fails_closed(tmp_path: Path) -> None: store = JsonVMReceiptStore(tmp_path / "receipts") receipt_path = store._path("session:dispatch") From c4680914f5e1e57c74fcf990bd20fc22f5ecce7b Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 07:02:06 +0900 Subject: [PATCH 06/41] test(task1-grok-vm-runtime): complete verification & hardening round 1 (security-and-boundary-audit) --- STATUS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/STATUS.md b/STATUS.md index 4a0f8e5d80..535d19df58 100644 --- a/STATUS.md +++ b/STATUS.md @@ -10,6 +10,6 @@ - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: 0b8542ec (adversarial runtime tests; current fixes uncommitted) -- 지금 손댄 파일: vm_agent_runtime.py, test_vm_agent_runtime.py, verification report -- 다음 할 일: required gates 재확인 후 커밋·푸시하고 Draft PR #3130 메타데이터 갱신 +- 마지막 커밋: 7252c48f (VM runtime boundary audit fixes) +- 지금 손댄 파일: committed; Draft PR #3130 checks are refreshing +- 다음 할 일: PR checks를 확인하고 Draft 상태와 live Grokbot 미검증 범위를 유지 From b1901beee02282081bfb9b488a201b305b96d7ae Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 07:11:48 +0900 Subject: [PATCH 07/41] fix(integrations): release idle runtime lock entries --- STATUS.md | 7 +- docs/verification/grok-bot-host-adapter.md | 39 +++++++++ src/ouroboros/integrations/_keyed_locks.py | 44 +++++++++++ .../integrations/personal_agent_host.py | 7 +- .../integrations/vm_agent_runtime.py | 27 +++++-- .../integrations/test_personal_agent_host.py | 23 ++++++ .../integrations/test_vm_agent_runtime.py | 79 +++++++++++++++++++ 7 files changed, 212 insertions(+), 14 deletions(-) create mode 100644 src/ouroboros/integrations/_keyed_locks.py diff --git a/STATUS.md b/STATUS.md index 535d19df58..aaf6242bc8 100644 --- a/STATUS.md +++ b/STATUS.md @@ -5,11 +5,12 @@ - [x] 2단계: VM Personal-Agent Runtime과 Grokbot VM 프로필 구현 - [x] 3단계: 단위 테스트와 보안·복구 시나리오 검증 - [x] 4단계: 전체 게이트 확인과 초안 PR 갱신 +- [x] 5단계: 동시성 스트레스·응답 실패 고정과 독립 검증 ## 🛑 블로커 - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: 7252c48f (VM runtime boundary audit fixes) -- 지금 손댄 파일: committed; Draft PR #3130 checks are refreshing -- 다음 할 일: PR checks를 확인하고 Draft 상태와 live Grokbot 미검증 범위를 유지 +- 마지막 커밋: working tree round-2 fixes pending commit +- 지금 손댄 파일: `_keyed_locks.py`, VM runtime/host adapter, focused tests, verification report +- 다음 할 일: required gate 실행 후 커밋·푸시하고 Draft PR #3130 checks 확인 diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index 1b9096426e..f51e3af4b4 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -129,6 +129,45 @@ The live paid Grok Bot account and provider-side VM remain unverified. The runtime evidence in this entry uses deterministic fake command and MCP transports. +## Evolution round 2: concurrency and state-lifecycle audit + +Date: 2026-11-30 (Asia/Seoul) + +The round-2 audit inspected the complete branch diff, ran the focused suite, +and stress-tested high-cardinality dispatches with an in-memory sink receipt +store. Three concrete issues were reproduced: + +- 5,000 unique successful dispatches left 5,000 per-key `asyncio.Lock` + objects in `VMPersonalAgentRuntime` and produced about 7.6 MiB of retained + allocation in the pre-fix `tracemalloc` comparison. +- A remote response containing an artifact path outside the workspace raised + `VMPathError` after the `running` receipt had been persisted, leaving the + receipt nonterminal and making the failure invisible to durable recovery. +- An unknown remote status such as `mystery-state` was stored as a nonterminal + receipt without an error, so retries could not distinguish an invalid + provider response from a resumable execution. + +The runtime and host adapter now share an idle-cleaning keyed lock pool. The +same 5,000-dispatch stress run leaves zero active lock entries after all +operations complete. Response parsing now converts artifact and payload +validation failures into terminal failed receipts, and unknown provider +statuses fail closed with an explicit error. New tests cover the stress path, +malformed artifact response, unknown status, and host lock cleanup. + +Round-2 verification: + +```text +uv run pytest tests/unit/integrations/ tests/integration/host/ -q +74 passed +uv run ruff format --check src/ tests/ +uv run ruff check src/ tests/ +uv run mypy src/ouroboros +python3 scripts/check-module-size.py --baseline-ref origin/main +``` + +The focused runtime and host checks pass locally. Live paid Grok Bot account +and provider-side VM execution remain unverified. + The repository-wide `uv run pytest` attempt under local Python 3.14 reached 9,739 passed, 119 skipped, and 1 xfailed before it was stopped after three unrelated failures: two existing cleanup tests in diff --git a/src/ouroboros/integrations/_keyed_locks.py b/src/ouroboros/integrations/_keyed_locks.py new file mode 100644 index 0000000000..a2def6b6a1 --- /dev/null +++ b/src/ouroboros/integrations/_keyed_locks.py @@ -0,0 +1,44 @@ +"""Small per-key async lock pool with idle-entry cleanup.""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Hashable +from contextlib import asynccontextmanager +from dataclasses import dataclass + + +@dataclass(slots=True) +class _LockEntry: + lock: asyncio.Lock + users: int = 0 + + +class KeyedAsyncLockPool: + """Serialize equal keys without retaining completed keys forever.""" + + def __init__(self) -> None: + self._entries: dict[Hashable, _LockEntry] = {} + + @property + def size(self) -> int: + """Return the number of keys with an active or waiting caller.""" + return len(self._entries) + + @asynccontextmanager + async def hold(self, key: Hashable) -> AsyncIterator[None]: + entry = self._entries.get(key) + if entry is None: + entry = _LockEntry(asyncio.Lock()) + self._entries[key] = entry + entry.users += 1 + try: + async with entry.lock: + yield + finally: + entry.users -= 1 + if entry.users == 0 and not entry.lock.locked(): + self._entries.pop(key, None) + + +__all__ = ["KeyedAsyncLockPool"] diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 126f70e1ce..de051f2db5 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -14,7 +14,6 @@ from __future__ import annotations -import asyncio from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace import json @@ -22,6 +21,7 @@ from typing import Any, Protocol from uuid import uuid4 +from ouroboros.integrations._keyed_locks import KeyedAsyncLockPool from ouroboros.integrations.vm_agent_profile import ( GROK_BOT_VM_PROFILE, GrokBotVMProfile, @@ -548,7 +548,7 @@ def __init__( self.host_name = host_name self.invocation_prefixes = tuple(invocation_prefixes) self.expected_runtime_backend = expected_runtime_backend - self._start_locks: dict[tuple[str | None, str, str, str], asyncio.Lock] = {} + self._start_locks = KeyedAsyncLockPool() self._start_receipts: dict[tuple[str | None, str, str, str], HostExecutionReceipt] = {} @property @@ -611,8 +611,7 @@ async def start( arguments["cwd"] = normalized_cwd key = _start_key(invocation, normalized_cwd) - lock = self._start_locks.setdefault(key, asyncio.Lock()) - async with lock: + async with self._start_locks.hold(key): cached = self._start_receipts.get(key) if cached is not None: return cached diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 25c867f778..649e6436d8 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -23,6 +23,8 @@ import tempfile from typing import Any, Protocol +from ouroboros.integrations._keyed_locks import KeyedAsyncLockPool + class VMRuntimeError(RuntimeError): """Base error for the VM runtime bridge.""" @@ -223,6 +225,7 @@ def to_dict(self) -> dict[str, Any]: _TERMINAL_STATUSES = frozenset({"completed", "failed"}) +_REMOTE_RUNNING_STATUSES = frozenset({"accepted", "queued", "running"}) @dataclass(frozen=True, slots=True) @@ -618,7 +621,7 @@ def __init__( self.receipt_store = receipt_store or MemoryVMReceiptStore() self.default_timeout_seconds = default_timeout_seconds self.max_output_chars = max_output_chars - self._locks: dict[str, asyncio.Lock] = {} + self._locks = KeyedAsyncLockPool() async def execute_command( self, @@ -701,8 +704,7 @@ async def resume_dispatch( artifact_paths=receipt.artifact_paths, ) request = self._prepare_request(persisted_request) - lock = self._locks.setdefault(request.correlation_key, asyncio.Lock()) - async with lock: + async with self._locks.hold(request.correlation_key): current = self.receipt_store.get(request.correlation_key) or receipt self._validate_receipt_match(current, request) if current.is_terminal: @@ -732,8 +734,7 @@ def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: async def _execute_request(self, request: VMExecutionRequest) -> VMExecutionReceipt: key = request.correlation_key - lock = self._locks.setdefault(key, asyncio.Lock()) - async with lock: + async with self._locks.hold(key): transport_request = self._prepare_request(request) existing = self.receipt_store.get(key) if existing is not None: @@ -852,7 +853,16 @@ async def _call_and_store( self.receipt_store.put(updated) return updated - updated = self._receipt_from_response(receipt, request, raw) + try: + updated = self._receipt_from_response(receipt, request, raw) + except Exception as exc: # malformed response evidence belongs in the receipt + updated = replace( + receipt, + status="failed", + error=f"invalid VM response: {exc}", + recovery_required=False, + finished_at=_now(), + ) self.receipt_store.put(updated) return updated @@ -918,7 +928,10 @@ def _receipt_from_response( ) elif status == "error" or status == "completed" and response_error is not None: status = "failed" - if status in {"queued", "running", "accepted"}: + elif status not in _REMOTE_RUNNING_STATUSES | _TERMINAL_STATUSES: + response_error = response_error or f"unsupported VM execution status: {status!r}" + status = "failed" + if status in _REMOTE_RUNNING_STATUSES: status = "running" exit_code = _optional_int(payload, "exit_code", None) artifact_paths = _artifact_paths(payload, request.artifact_paths) diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 4bf228558d..bb2edd8296 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -2,6 +2,8 @@ from __future__ import annotations +import asyncio + import pytest from ouroboros.integrations.personal_agent_host import ( @@ -13,6 +15,27 @@ ) +@pytest.mark.asyncio +async def test_start_lock_pool_releases_unique_request_keys() -> None: + calls = 0 + + async def call_tool(_name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + calls += 1 + return { + "meta": { + "job_id": f"job-{calls}", + "auto_session_id": f"auto-{calls}", + "runtime_backend": "host", + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + await asyncio.gather(*(adapter.start(f"/ouroboros request-{index}") for index in range(128))) + + assert adapter._start_locks.size == 0 + + def test_ordinary_messages_are_not_claimed() -> None: assert parse_explicit_invocation("please remember this for later") is None assert parse_explicit_invocation("a sentence containing /ouroboros midway") is None diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 7e70a9f29a..8c653b2b06 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -35,6 +35,22 @@ async def execute_command(self, command: str, **kwargs: Any) -> dict[str, Any]: return {"status": "completed", "exit_code": 0, "stdout": "ok"} +class SinkReceiptStore: + """Avoid receipt retention when stressing runtime coordination state.""" + + def get(self, _key: str) -> None: + return None + + def put(self, _receipt: Any) -> None: + return None + + def put_if_absent(self, _receipt: Any) -> None: + return None + + def find(self, _dispatch_id: str, _session_id: str | None = None) -> None: + return None + + class RecordingMCP: def __init__(self) -> None: self.calls: list[tuple[str, dict[str, Any]]] = [] @@ -379,6 +395,69 @@ async def execute_command(self, command: str, **kwargs: Any) -> dict[str, Any]: assert len(target.calls) == 1 +@pytest.mark.asyncio +async def test_unique_dispatch_stress_releases_idle_lock_entries(tmp_path: Path) -> None: + runtime = VMPersonalAgentRuntime( + CommandVMTransport(RecordingCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=SinkReceiptStore(), + ) + + await asyncio.gather( + *( + runtime.execute_command("echo once", dispatch_id=f"stress-{index}", session_id="s") + for index in range(512) + ) + ) + + assert runtime._locks.size == 0 + + +@pytest.mark.asyncio +async def test_malformed_remote_artifact_response_is_stored_as_failed_receipt( + tmp_path: Path, +) -> None: + class MaliciousArtifactCommand: + calls = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.calls += 1 + return {"status": "completed", "exit_code": 0, "artifacts": ["../escape.txt"]} + + target = MaliciousArtifactCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verify", dispatch_id="bad-artifact", session_id="s") + retried = await runtime.execute_command("verify", dispatch_id="bad-artifact", session_id="s") + + assert receipt.status == "failed" + assert receipt.is_terminal is True + assert "invalid VM response" in (receipt.error or "") + assert retried == receipt + assert target.calls == 1 + + +@pytest.mark.asyncio +async def test_unknown_remote_status_fails_closed(tmp_path: Path) -> None: + class UnknownStatusCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "mystery-state", "exit_code": 0} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(UnknownStatusCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verify", dispatch_id="bad-status", session_id="s") + + assert receipt.status == "failed" + assert receipt.is_terminal is True + assert "unsupported VM execution status" in (receipt.error or "") + + @pytest.mark.asyncio async def test_separate_runtimes_sharing_json_store_claim_a_dispatch_once(tmp_path: Path) -> None: class BlockingCommand: From a3cd70f3dbec2c4d44e81e0d67de91148c2f2117 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 07:13:34 +0900 Subject: [PATCH 08/41] chore: update round-2 task status --- STATUS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/STATUS.md b/STATUS.md index aaf6242bc8..86273f17a7 100644 --- a/STATUS.md +++ b/STATUS.md @@ -11,6 +11,6 @@ - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: working tree round-2 fixes pending commit -- 지금 손댄 파일: `_keyed_locks.py`, VM runtime/host adapter, focused tests, verification report -- 다음 할 일: required gate 실행 후 커밋·푸시하고 Draft PR #3130 checks 확인 +- 마지막 커밋: b1901bee (round-2 lock lifecycle and response hardening) +- 지금 손댄 파일: committed; Draft PR #3130 checks are refreshing +- 다음 할 일: PR checks를 확인하고 Draft 상태와 live Grokbot 미검증 범위를 유지 From 830774c950e664ebf3ea37fe48c7fe7ca147fd43 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 07:56:34 +0900 Subject: [PATCH 09/41] test(task1-grok-vm-runtime): complete verification & hardening round 3 (edge-case-and-recovery-matrix) --- STATE.md | 28 ++++++ STATUS.md | 8 +- docs/verification/grok-bot-host-adapter.md | 44 ++++++++++ .../integrations/vm_agent_runtime.py | 41 ++++++++- .../integrations/test_vm_agent_runtime.py | 86 +++++++++++++++++++ 5 files changed, 202 insertions(+), 5 deletions(-) create mode 100644 STATE.md diff --git a/STATE.md b/STATE.md new file mode 100644 index 0000000000..7ef761786e --- /dev/null +++ b/STATE.md @@ -0,0 +1,28 @@ +# Round 3 runtime verification state + +## Goal +- Prove crash, disconnect, restart, cancellation, and malformed-response behavior for the VM personal-agent runtime. +- Keep Draft PR #3130 open and preserve the explicit live Grokbot unverified boundary. + +## Constraints +- Work only in `/home/lee3q/work/night-20261130/worktrees/ouroboros-grok-vm`. +- Never merge a PR or add credentials. +- Required focused gate must exit 0 before completion. + +## Confirmed facts +- Branch: `feat/personal-agent-vm-runtime-20261130`. +- Baseline focused suite before Round 3: 74 passed. +- Round-3 pre-fix probes reproduced three issues: cancellation left `running`, corrupt JSON lookup returned `None`, and content-only MCP returned `VMTransportError`. +- Round-3 focused runtime tests after fixes: 45 passed. +- `python3 scripts/check-module-size.py --baseline-ref origin/main` passed before Round 3. + +## Round-3 changes +- Persist a recovery receipt when an external task cancellation interrupts a VM call, then re-raise cancellation. +- Fail closed when `JsonVMReceiptStore.find()` encounters a malformed final receipt file. +- Parse standard MCP text content as JSON payload or bounded command output. +- Add regression tests for all three cases and parametrized content variants. + +## Next actions +- Run focused pytest, Ruff format check, Ruff lint, MyPy, and module-size gate. +- Append final evidence and update PR #3130 body with verified and simulated boundaries. +- Commit and push the branch, then inspect the refreshed draft checks. diff --git a/STATUS.md b/STATUS.md index 86273f17a7..d4d8e6649e 100644 --- a/STATUS.md +++ b/STATUS.md @@ -6,11 +6,13 @@ - [x] 3단계: 단위 테스트와 보안·복구 시나리오 검증 - [x] 4단계: 전체 게이트 확인과 초안 PR 갱신 - [x] 5단계: 동시성 스트레스·응답 실패 고정과 독립 검증 +- [ ] 👉 6단계: 충돌·취소·손상 영수증·MCP 응답 경계의 Round 3 검증 (현재 위치) +- [ ] 7단계: 최종 게이트·커밋·Draft PR 갱신 ## 🛑 블로커 - 블로커: 없음 ## 🤖 AI 실행 맥락 -- 마지막 커밋: b1901bee (round-2 lock lifecycle and response hardening) -- 지금 손댄 파일: committed; Draft PR #3130 checks are refreshing -- 다음 할 일: PR checks를 확인하고 Draft 상태와 live Grokbot 미검증 범위를 유지 +- 마지막 커밋: a3cd70f3 (round-2 task status) +- 지금 손댄 파일: VM runtime, adversarial tests, round-3 verification report +- 다음 할 일: 전체 검증 게이트를 실행하고 커밋·푸시 후 Draft PR #3130 checks 확인 diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index f51e3af4b4..31af2cae03 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -174,3 +174,47 @@ unrelated failures: two existing cleanup tests in `tests/unit/boundary/test_base_regression.py` and one output-contract test in `tests/unit/cli/test_run_successors.py`. The touched integration/runtime tests and all required repository gates passed independently. + +## Evolution round 3: cancellation, corrupt receipt, and MCP response audit + +Date: 2026-11-30 (Asia/Seoul) + +This round inspected the complete `origin/main...HEAD` diff, checked Draft PR +#3130, reviewed the runtime receipt transitions, and ran direct failure probes. +The local `co status` snapshot showed 7.3 GiB available memory, 23 GiB free +swap, and 11% `/tmp` tmpfs use before the additional test work. + +The audit found three concrete failure modes. + +- Cancelling a host task while the VM transport was in flight left the durable + receipt in `running` with no recovery marker. A later retry could not tell + whether the host task had been interrupted or was still active. +- `JsonVMReceiptStore.find()` skipped malformed final JSON files and returned + `None` or another matching receipt. This hid durable-state corruption during + restart lookup. +- A standard MCP result containing only text content was rejected when it had + no `structuredContent`. Public MCP tools may return JSON or plain command + output in text content. + +The direct pre-fix probes reproduced `running / False / None` for cancellation, +`None` for lookup through a corrupt JSON file, and `VMTransportError` for the +content-only MCP result. + +The runtime now persists a `disconnected` recovery receipt before re-raising an +external cancellation, fails closed on malformed JSON during lookup, and +accepts MCP text content as either a JSON response object or command output. +The test suite covers cancellation followed by a no-replay retry, corrupt-store +lookup, JSON text content, and plain text content. + +Round-3 verification so far: + +```text +uv run pytest tests/unit/integrations/test_vm_agent_runtime.py -q +45 passed +uv run ruff format --check src/ouroboros/integrations tests/unit/integrations tests/integration/host +10 files already formatted +``` + +The live paid Grok Bot account and provider-side VM execution remain +unverified. The runtime evidence in this entry uses deterministic fake command +and MCP transports. diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 649e6436d8..92daee251c 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -436,8 +436,8 @@ def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionRe for path in self.directory.glob("*.json"): try: receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) - except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError): - continue + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise VMRuntimeError(f"corrupt VM receipt file {path.name!r}") from exc if receipt.dispatch_id == dispatch_id and ( session_id is None or receipt.session_id == session_id ): @@ -842,6 +842,15 @@ async def _call_and_store( ) self.receipt_store.put(updated) return updated + except asyncio.CancelledError: + updated = replace( + receipt, + status="disconnected", + error="VM execution task was cancelled before completion; refusing replay.", + recovery_required=True, + ) + self.receipt_store.put(updated) + raise except (ConnectionError, BrokenPipeError, EOFError) as exc: updated = replace( receipt, status="disconnected", error=str(exc), recovery_required=True @@ -1009,6 +1018,7 @@ def _payload(value: Any) -> dict[str, Any]: if structured is None: structured = getattr(value, "structuredContent", None) mapping = { + "content": getattr(value, "content", None), "structured_content": structured, "meta": getattr(value, "meta", None), "is_error": getattr(value, "is_error", getattr(value, "isError", False)), @@ -1029,6 +1039,17 @@ def _payload(value: Any) -> dict[str, Any]: payload.update(meta) if isinstance(structured, Mapping): payload.update(structured) + if not payload: + content_texts = _text_content_items(mapping.get("content")) + for text in content_texts: + try: + decoded = json.loads(text) + except (TypeError, ValueError, json.JSONDecodeError): + continue + if isinstance(decoded, Mapping): + payload.update(decoded) + if not payload and content_texts: + payload["output"] = "\n".join(content_texts) if not payload: raise VMTransportError("VM transport returned an empty or malformed payload") if not any( @@ -1048,6 +1069,22 @@ def _payload(value: Any) -> dict[str, Any]: return payload +def _text_content_items(content: Any) -> tuple[str, ...]: + if not isinstance(content, Iterable) or isinstance(content, (str, bytes, Mapping)): + return () + texts: list[str] = [] + for item in content: + if isinstance(item, Mapping): + item_type = item.get("type") + item_text = item.get("text") + else: + item_type = getattr(item, "type", None) + item_text = getattr(item, "text", None) + if getattr(item_type, "value", item_type) == "text" and isinstance(item_text, str): + texts.append(item_text) + return tuple(texts) + + def _is_error(raw: Any, payload: Mapping[str, Any]) -> bool: mapping = _mapping(raw) if mapping: diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 8c653b2b06..53af036616 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -266,6 +266,41 @@ async def test_mcp_transport_uses_a_generic_public_command_surface(tmp_path: Pat assert arguments["idempotency_key"] == "session-2:dispatch-2" +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("content_text", "expected_stdout"), + [ + ('{"status":"completed","exit_code":0,"stdout":"json-output"}', "json-output"), + ("plain-output", "plain-output"), + ], +) +async def test_mcp_transport_accepts_standard_content_text_payloads( + content_text: str, + expected_stdout: str, + tmp_path: Path, +) -> None: + class ContentOnlyResult: + def __init__(self, text: str) -> None: + self.content = ({"type": "text", "text": text},) + self.structured_content = None + self.meta: dict[str, Any] = {} + self.is_error = False + + class ContentOnlyMCP: + async def call_tool(self, _name: str, _arguments: dict[str, Any]) -> object: + return ContentOnlyResult(content_text) + + runtime = VMPersonalAgentRuntime( + MCPVMTransport(ContentOnlyMCP()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("echo test", dispatch_id="content", session_id="s") + + assert receipt.status == "completed" + assert receipt.stdout == expected_stdout + + @pytest.mark.asyncio @pytest.mark.parametrize( "payload", @@ -633,6 +668,14 @@ def test_corrupt_json_receipt_fails_closed(tmp_path: Path) -> None: store.get("session:dispatch") +def test_find_fails_closed_when_any_json_receipt_is_corrupt(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + (store.directory / "corrupt.json").write_text("not json", encoding="utf-8") + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt file"): + store.find("missing") + + class RunningTransport: def __init__(self) -> None: self.execute_calls = 0 @@ -697,6 +740,49 @@ async def execute(self, _request: Any) -> Any: assert "refusing to replay" in (recovered.error or "") +@pytest.mark.asyncio +async def test_external_cancellation_persists_recovery_and_never_replays( + tmp_path: Path, +) -> None: + class BlockingCommand: + def __init__(self) -> None: + self.started = asyncio.Event() + self.release = asyncio.Event() + self.calls = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.calls += 1 + self.started.set() + await self.release.wait() + return {"status": "completed", "exit_code": 0} + + target = BlockingCommand() + store = JsonVMReceiptStore(tmp_path / "receipts") + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=store, + ) + task = asyncio.create_task( + runtime.execute_command("long task", dispatch_id="cancelled", session_id="s") + ) + await target.started.wait() + task.cancel() + + with pytest.raises(asyncio.CancelledError): + await task + + receipt = store.get("s:cancelled") + assert receipt is not None + assert receipt.status == "disconnected" + assert receipt.recovery_required is True + assert "refusing replay" in (receipt.error or "") + + recovered = await runtime.execute_command("long task", dispatch_id="cancelled", session_id="s") + assert recovered.status == "recovery_required" + assert target.calls == 1 + + @pytest.mark.asyncio async def test_partial_timeout_cancels_the_remote_execution_before_receipt_is_stored( tmp_path: Path, From 975441297f908c2e2dbbc29432e00038d9f6819b Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 08:05:17 +0900 Subject: [PATCH 10/41] test(task1-grok-vm-runtime): complete architecture audit round 4 --- STATE.md | 28 ++++----- STATUS.md | 18 ------ docs/verification/grok-bot-host-adapter.md | 52 +++++++++++++++++ .../integrations/vm_agent_runtime.py | 58 ++++++++++++++----- .../integrations/test_vm_agent_runtime.py | 43 ++++++++++++++ 5 files changed, 153 insertions(+), 46 deletions(-) delete mode 100644 STATUS.md diff --git a/STATE.md b/STATE.md index 7ef761786e..00f4b2c51b 100644 --- a/STATE.md +++ b/STATE.md @@ -1,7 +1,7 @@ -# Round 3 runtime verification state +# Round 4 runtime verification state ## Goal -- Prove crash, disconnect, restart, cancellation, and malformed-response behavior for the VM personal-agent runtime. +- Prove crash, disconnect, restart, cancellation, malformed-response, path, idempotency, and exit-status behavior for the VM personal-agent runtime. - Keep Draft PR #3130 open and preserve the explicit live Grokbot unverified boundary. ## Constraints @@ -11,18 +11,18 @@ ## Confirmed facts - Branch: `feat/personal-agent-vm-runtime-20261130`. -- Baseline focused suite before Round 3: 74 passed. -- Round-3 pre-fix probes reproduced three issues: cancellation left `running`, corrupt JSON lookup returned `None`, and content-only MCP returned `VMTransportError`. -- Round-3 focused runtime tests after fixes: 45 passed. -- `python3 scripts/check-module-size.py --baseline-ref origin/main` passed before Round 3. +- Round-4 pre-fix probes reproduced three issues: overlapping host/VM roots doubled an absolute host path, blank idempotency keys were accepted, and `completed` with exit code 7 was recorded as success. +- Round-4 focused suite after fixes: 83 passed. +- Full Ruff format, Ruff lint, MyPy, module-size, focused acceptance, and touched-path lint gates passed after Round 4. +- Draft PR #3130 remains open and must stay unmerged. -## Round-3 changes -- Persist a recovery receipt when an external task cancellation interrupts a VM call, then re-raise cancellation. -- Fail closed when `JsonVMReceiptStore.find()` encounters a malformed final receipt file. -- Parse standard MCP text content as JSON payload or bounded command output. -- Add regression tests for all three cases and parametrized content variants. +## Round-4 changes +- Preserve absolute host paths when host and VM roots overlap, while retaining resolved VM containment checks. +- Reject blank or NUL-containing explicit idempotency keys before receipt correlation. +- Convert completed nonzero exit codes into failed terminal receipts with explicit error evidence. +- Remove the scratch root `STATUS.md` file. +- Add regression tests for all three audit findings. ## Next actions -- Run focused pytest, Ruff format check, Ruff lint, MyPy, and module-size gate. -- Append final evidence and update PR #3130 body with verified and simulated boundaries. -- Commit and push the branch, then inspect the refreshed draft checks. +- Append Round-4 evidence and verified-vs-unverified matrix to the Draft PR body. +- Commit and push the branch, then inspect the refreshed Draft PR checks. diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index d4d8e6649e..0000000000 --- a/STATUS.md +++ /dev/null @@ -1,18 +0,0 @@ -# Ouroboros - -## 🗺️ 단계 / 로드맵 -- [x] 1단계: 기준 호스트 어댑터와 검증 자료 확인 -- [x] 2단계: VM Personal-Agent Runtime과 Grokbot VM 프로필 구현 -- [x] 3단계: 단위 테스트와 보안·복구 시나리오 검증 -- [x] 4단계: 전체 게이트 확인과 초안 PR 갱신 -- [x] 5단계: 동시성 스트레스·응답 실패 고정과 독립 검증 -- [ ] 👉 6단계: 충돌·취소·손상 영수증·MCP 응답 경계의 Round 3 검증 (현재 위치) -- [ ] 7단계: 최종 게이트·커밋·Draft PR 갱신 - -## 🛑 블로커 -- 블로커: 없음 - -## 🤖 AI 실행 맥락 -- 마지막 커밋: a3cd70f3 (round-2 task status) -- 지금 손댄 파일: VM runtime, adversarial tests, round-3 verification report -- 다음 할 일: 전체 검증 게이트를 실행하고 커밋·푸시 후 Draft PR #3130 checks 확인 diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index 31af2cae03..0b8a534b15 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -218,3 +218,55 @@ uv run ruff format --check src/ouroboros/integrations tests/unit/integrations te The live paid Grok Bot account and provider-side VM execution remain unverified. The runtime evidence in this entry uses deterministic fake command and MCP transports. + +## Evolution round 4: architecture math and reviewer walkthrough audit + +Date: 2026-11-30 (Asia/Seoul) + +This round reviewed the complete `origin/main...HEAD` diff, inspected the open +Draft PR #3130 checks, and ran direct probes before changing the runtime. The +pre-fix probes reproduced three concrete contract gaps. + +- With a host root nested under the VM root, an absolute host dispatch path was + mapped twice. For example, a host path ending in `host/src` became + `host/host/src`, so a valid host cwd could execute in the wrong directory. +- A caller-supplied blank `idempotency_key` was accepted as the literal + correlation key. That key could collapse unrelated requests into one durable + receipt and was inconsistent with the required non-empty dispatch fields. +- A provider response of `status=completed` with `exit_code=7` was recorded as + successful completion, losing the command failure in the terminal receipt. + +The runtime now gives an absolute path already contained by the approved host +root host-path precedence before interpreting it as VM notation. Explicit VM +paths still pass through `map_vm_path()`, including its resolved containment +check. Explicit idempotency keys must contain non-whitespace text and no NUL +bytes. A completed response with a nonzero exit code is converted to a failed +receipt with the exit code preserved in the error evidence. + +New automated coverage proves the overlapping-root mapping, invalid-key +rejection, and nonzero-exit conversion. The existing 512-dispatch lock stress +test remains green, and the focused suite completed in 2.06 seconds with 83 +tests passing. The repository-wide Ruff, MyPy, module-size, and deterministic +focused acceptance gates all passed after the changes. + +Round-4 verification: + +```text +uv run ruff format --check src/ tests/ +1949 files already formatted +uv run ruff check src/ tests/ +All checks passed! +uv run mypy src/ouroboros +Success: no issues found in 819 source files +python3 scripts/check-module-size.py --baseline-ref origin/main +module-size: OK (818 modules, cap 2000, 23 grandfathered) +uv run pytest tests/unit/integrations/ tests/integration/host/ -q +83 passed in 2.06s +uv run ruff check src/ouroboros/integrations tests/unit/integrations tests/integration/host +All checks passed! +``` + +The root scratch `STATUS.md` was removed from the branch as required by the +independent hygiene review. The live paid Grok Bot account and provider-side VM +execution remain unverified. The runtime evidence in this entry uses +deterministic fake command and MCP transports. diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 92daee251c..d019b835fa 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -116,22 +116,25 @@ def map_vm_path(self, path: str) -> Path: def resolve_dispatch_workspace(self, path: str | Path) -> Path: """Resolve a dispatch cwd supplied in host or VM path notation.""" text = _path_text(path, "dispatch workspace") - vm_candidate = PurePosixPath(text) - if vm_candidate.is_relative_to(self.vm_root): - return self.map_vm_path(text) try: - candidate = Path(text).expanduser() + candidate = Path(text) + expanduser = getattr(candidate, "expanduser", None) + if callable(expanduser): + candidate = expanduser() except (OSError, RuntimeError, ValueError) as exc: raise VMPathError(f"dispatch workspace is invalid: {path!s}") from exc + if candidate.is_absolute(): + try: + resolved_host = candidate.resolve(strict=False) + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError(f"dispatch workspace is invalid: {path!s}") from exc + if resolved_host.is_relative_to(self.host_root): + return resolved_host + vm_candidate = PurePosixPath(text) + if vm_candidate.is_relative_to(self.vm_root): + return self.map_vm_path(text) if not candidate.is_absolute(): return self._resolve_host_path(candidate) - - try: - resolved_host = candidate.resolve(strict=False) - except (OSError, RuntimeError, ValueError) as exc: - raise VMPathError(f"dispatch workspace is invalid: {path!s}") from exc - if resolved_host.is_relative_to(self.host_root): - return resolved_host raise VMPathError(f"dispatch workspace escapes approved workspace: {path!s}") def host_relative(self, path: str | Path) -> str: @@ -141,10 +144,24 @@ def host_relative(self, path: str | Path) -> str: def resolve_artifact_path(self, path: str | Path) -> Path: """Resolve a host or VM artifact path using one containment rule.""" text = _path_text(path, "artifact path") + try: + candidate = Path(text) + expanduser = getattr(candidate, "expanduser", None) + if callable(expanduser): + candidate = expanduser() + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError(f"artifact path is invalid: {path!s}") from exc + if candidate.is_absolute(): + try: + resolved_host = candidate.resolve(strict=False) + except (OSError, RuntimeError, ValueError) as exc: + raise VMPathError(f"artifact path is invalid: {path!s}") from exc + if resolved_host.is_relative_to(self.host_root): + return resolved_host vm_candidate = PurePosixPath(text) if vm_candidate.is_absolute() and vm_candidate.is_relative_to(self.vm_root): return self.map_vm_path(text) - return self._resolve_host_path(text) + return self._resolve_host_path(candidate) def _resolve_host_path(self, path: str | Path) -> Path: text = _path_text(path, "host path") @@ -185,8 +202,13 @@ def __post_init__(self) -> None: raise VMRuntimeError(f"{name} must be non-empty text") if "\x00" in value: raise VMRuntimeError(f"{name} must not contain NUL bytes") - if self.idempotency_key is not None and not isinstance(self.idempotency_key, str): - raise VMRuntimeError("idempotency_key must be text") + if self.idempotency_key is not None: + if not isinstance(self.idempotency_key, str): + raise VMRuntimeError("idempotency_key must be text") + if not self.idempotency_key.strip(): + raise VMRuntimeError("idempotency_key must be non-empty text") + if "\x00" in self.idempotency_key: + raise VMRuntimeError("idempotency_key must not contain NUL bytes") if not isinstance(self.timeout_seconds, (int, float)) or not math.isfinite( self.timeout_seconds ): @@ -937,6 +959,14 @@ def _receipt_from_response( ) elif status == "error" or status == "completed" and response_error is not None: status = "failed" + elif status == "completed" and _optional_int(payload, "exit_code", None) not in ( + None, + 0, + ): + response_error = response_error or ( + f"VM execution exited with code {_optional_int(payload, 'exit_code', None)}" + ) + status = "failed" elif status not in _REMOTE_RUNNING_STATUSES | _TERMINAL_STATUSES: response_error = response_error or f"unsupported VM execution status: {status!r}" status = "failed" diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 53af036616..311a490f3c 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -100,6 +100,18 @@ def test_workspace_mapping_resolves_symlink_escapes(tmp_path: Path) -> None: mapper.map_host_path("link") +def test_overlapping_host_and_vm_roots_keep_absolute_host_paths_unambiguous( + tmp_path: Path, +) -> None: + host_root = tmp_path / "host" + host_root.mkdir() + mapper = VMWorkspaceMapper(host_root, str(tmp_path)) + host_child = host_root / "src" + + assert mapper.resolve_dispatch_workspace(host_child) == host_child + assert mapper.resolve_artifact_path(host_child) == host_child + + def test_artifact_collection_is_workspace_scoped(tmp_path: Path) -> None: artifact = tmp_path / "result.json" artifact.write_text('{"ok": true}', encoding="utf-8") @@ -161,6 +173,17 @@ def test_nul_bytes_are_rejected_as_vm_path_errors( runtime.collect_artifacts(["bad\x00name"]) +@pytest.mark.parametrize("key", ["", " ", "bad\x00key"]) +def test_invalid_explicit_idempotency_keys_are_rejected(key: str) -> None: + with pytest.raises(VMRuntimeError, match="idempotency_key"): + VMExecutionRequest( + dispatch_id="dispatch", + session_id="session", + command="echo test", + idempotency_key=key, + ) + + @pytest.mark.asyncio async def test_command_transport_maps_cwd_and_idempotency_key(tmp_path: Path) -> None: target = RecordingCommand() @@ -385,6 +408,26 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] assert receipt.error == "permission denied" +@pytest.mark.asyncio +async def test_completed_nonzero_exit_code_is_failed_instead_of_success( + tmp_path: Path, +) -> None: + class FailedCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 7} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(FailedCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("false", dispatch_id="exit", session_id="s") + + assert receipt.status == "failed" + assert receipt.is_terminal is True + assert receipt.error == "VM execution exited with code 7" + + def test_invalid_output_limit_is_rejected_as_runtime_input(tmp_path: Path) -> None: with pytest.raises(VMRuntimeError, match="positive integer"): VMPersonalAgentRuntime( From dc6fb1e9a1aa6d9922a199a782eaaefd1719381f Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 08:25:35 +0900 Subject: [PATCH 11/41] docs(task1-grok-vm-runtime): close round 4 state --- STATE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/STATE.md b/STATE.md index 00f4b2c51b..8383c37ced 100644 --- a/STATE.md +++ b/STATE.md @@ -15,6 +15,7 @@ - Round-4 focused suite after fixes: 83 passed. - Full Ruff format, Ruff lint, MyPy, module-size, focused acceptance, and touched-path lint gates passed after Round 4. - Draft PR #3130 remains open and must stay unmerged. +- Remote PR checks for implementation commit `97544129` all passed, including Python 3.12 and Windows sandbox. ## Round-4 changes - Preserve absolute host paths when host and VM roots overlap, while retaining resolved VM containment checks. @@ -24,5 +25,4 @@ - Add regression tests for all three audit findings. ## Next actions -- Append Round-4 evidence and verified-vs-unverified matrix to the Draft PR body. -- Commit and push the branch, then inspect the refreshed Draft PR checks. +- No implementation action remains. Keep PR #3130 in Draft state for maintainer review. From d69e74231f63779b56d8cd6d0d17f4fe74a7fb4e Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 08:44:57 +0900 Subject: [PATCH 12/41] fix(integrations): persist host lifecycle receipts --- STATE.md | 29 +- docs/runtime-guides/personal-agent-host.md | 23 +- docs/runtime-guides/vm-personal-agent.md | 4 +- docs/verification/grok-bot-host-adapter.md | 64 ++++- src/ouroboros/integrations/__init__.py | 6 + .../integrations/personal_agent_host.py | 251 ++++++++++++++++-- .../integrations/vm_agent_runtime.py | 23 +- .../integrations/test_personal_agent_host.py | 109 ++++++++ .../integrations/test_vm_agent_runtime.py | 26 ++ 9 files changed, 486 insertions(+), 49 deletions(-) diff --git a/STATE.md b/STATE.md index 8383c37ced..dc50696ec1 100644 --- a/STATE.md +++ b/STATE.md @@ -1,8 +1,8 @@ # Round 4 runtime verification state ## Goal -- Prove crash, disconnect, restart, cancellation, malformed-response, path, idempotency, and exit-status behavior for the VM personal-agent runtime. -- Keep Draft PR #3130 open and preserve the explicit live Grokbot unverified boundary. +- Verify the Grokbot/VM personal-agent bridge with durable receipts, safe workspace mapping, explicit host routing, disconnect recovery, and reviewer-readable evidence. +- Keep Draft PR #3130 open and preserve the live paid Grokbot unverified boundary. ## Constraints - Work only in `/home/lee3q/work/night-20261130/worktrees/ouroboros-grok-vm`. @@ -11,18 +11,19 @@ ## Confirmed facts - Branch: `feat/personal-agent-vm-runtime-20261130`. -- Round-4 pre-fix probes reproduced three issues: overlapping host/VM roots doubled an absolute host path, blank idempotency keys were accepted, and `completed` with exit code 7 was recorded as success. -- Round-4 focused suite after fixes: 83 passed. -- Full Ruff format, Ruff lint, MyPy, module-size, focused acceptance, and touched-path lint gates passed after Round 4. -- Draft PR #3130 remains open and must stay unmerged. -- Remote PR checks for implementation commit `97544129` all passed, including Python 3.12 and Windows sandbox. +- Round 4 continuation reproduced and fixed: host receipt state was memory-only across adapter restarts; sparse `job_wait` snapshots dropped pending dispatches and could regress cursors; boolean timeout and string artifact inputs crossed the VM boundary ambiguously. +- `JsonHostReceiptStore` now atomically persists start, wait, submit, result, and cancel receipt state under a deterministic explicit-request key. +- Focused suite after continuation fixes: 87 passed. +- Full Ruff format/lint, MyPy, module-size, focused acceptance, touched-path lint, and `git diff --check` passed. +- No root `STATUS.md` exists; tracked `STATE.md` remains the required execution anchor. +- Draft PR #3130 remains open and unmerged. Live paid Grokbot and provider-side VM execution remain unverified. -## Round-4 changes -- Preserve absolute host paths when host and VM roots overlap, while retaining resolved VM containment checks. -- Reject blank or NUL-containing explicit idempotency keys before receipt correlation. -- Convert completed nonzero exit codes into failed terminal receipts with explicit error evidence. -- Remove the scratch root `STATUS.md` file. -- Add regression tests for all three audit findings. +## Evidence paths +- `src/ouroboros/integrations/personal_agent_host.py` +- `src/ouroboros/integrations/vm_agent_runtime.py` +- `tests/unit/integrations/test_personal_agent_host.py` +- `tests/unit/integrations/test_vm_agent_runtime.py` +- `docs/verification/grok-bot-host-adapter.md` ## Next actions -- No implementation action remains. Keep PR #3130 in Draft state for maintainer review. +- Refresh PR #3130 body with continuation evidence, commit the verified changes, push the branch, and inspect the new remote checks without merging. diff --git a/docs/runtime-guides/personal-agent-host.md b/docs/runtime-guides/personal-agent-host.md index 8978b0b988..facdc32880 100644 --- a/docs/runtime-guides/personal-agent-host.md +++ b/docs/runtime-guides/personal-agent-host.md @@ -66,9 +66,16 @@ an MCP SDK dependency to the base package. The smallest host implementation is equivalent to: ```python -from ouroboros.integrations import GrokBotHostAdapter, MCPToolTransport +from ouroboros.integrations import ( + GrokBotHostAdapter, + JsonHostReceiptStore, + MCPToolTransport, +) -adapter = GrokBotHostAdapter(MCPToolTransport(mcp_client)) +adapter = GrokBotHostAdapter( + MCPToolTransport(mcp_client), + receipt_store=JsonHostReceiptStore(".ouroboros/host-receipts"), +) receipt = await adapter.start( message, host_session_id=host_conversation_id, @@ -97,7 +104,12 @@ correlation-mismatched dispatch is rejected and must not be replayed. The receipt records the host name, request ID, host session ID, Auto session ID, job ID, cursor, current state, pending dispatch identity, Seed, execution, evaluation, verification, failure, recovery, and a resume call. Unknown server -fields remain in `state` for forward compatibility. +fields remain in `state` for forward compatibility. `JsonHostReceiptStore` +atomically stores the receipt after every lifecycle response, so a restarted +adapter reloads the latest cursor and pending dispatches instead of starting a +second Auto session for the same explicit request. Use a stable +`host_session_id` for each conversation; without one, identical requests share +the deterministic fallback key. ## Runtime and execution location @@ -130,8 +142,9 @@ existing session-scope limitation is removed. ## Recovery and failure handling -- Persist `auto_session_id`, `job_id`, and the latest `cursor` after every - response. +- Configure `JsonHostReceiptStore` and let the adapter persist + `auto_session_id`, `job_id`, the latest monotonic `cursor`, and pending + dispatches after every response. - Resume with `ouroboros_start_auto` and `{"resume": ""}`; do not start a new goal when recovering an existing session. - Poll `ouroboros_job_wait` after a transport or host restart. Persisted Auto diff --git a/docs/runtime-guides/vm-personal-agent.md b/docs/runtime-guides/vm-personal-agent.md index 0faa4f21df..f4fd07fb8f 100644 --- a/docs/runtime-guides/vm-personal-agent.md +++ b/docs/runtime-guides/vm-personal-agent.md @@ -11,7 +11,9 @@ The runtime maps an approved host workspace to the VM workspace, persists a structured receipt for each `session_id` and `dispatch_id`, and records output, exit status, execution IDs, and artifact hashes. `JsonVMReceiptStore` can be placed under the project’s `.ouroboros` state directory so a host restart can -find the previous receipt. +find the previous receipt. Input boundaries reject a single string passed as an +artifact iterable and reject boolean timeout values, which otherwise look +numeric in Python but do not represent a deliberate runtime setting. Host dispatches may identify their working directory in either approved host path notation or approved VM path notation. Both forms are canonicalized and diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index 0b8a534b15..90467c712f 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -266,7 +266,63 @@ uv run ruff check src/ouroboros/integrations tests/unit/integrations tests/integ All checks passed! ``` -The root scratch `STATUS.md` was removed from the branch as required by the -independent hygiene review. The live paid Grok Bot account and provider-side VM -execution remain unverified. The runtime evidence in this entry uses -deterministic fake command and MCP transports. +No root `STATUS.md` exists in the final worktree or branch diff; the tracked +root `STATE.md` remains the required execution anchor. The live paid Grok Bot +account and provider-side VM execution remain unverified. The runtime evidence +in this entry uses deterministic fake command and MCP transports. + +## Evolution round 4 continuation: durable host state and sparse polling + +Date: 2026-11-30 (Asia/Seoul) + +This follow-up audit re-read the full integration diff and compared the +documented restart contract with the actual host adapter lifecycle. Three +additional concrete gaps were reproduced before the fixes: + +- The host adapter's duplicate-start cache existed only in memory. Recreating + the adapter after a host restart called `ouroboros_start_auto` again for the + same explicit conversation request. +- A normal `ouroboros_job_wait` snapshot can omit + `pending_host_dispatches` when there is no new event. The adapter previously + treated omission as an empty list and lost an actionable dispatch. A stale + lower cursor could also move the local cursor backwards and replay events. +- Python accepted `True` as a timeout and a string as an iterable of artifact + paths. Those values crossed the VM request boundary as misleading runtime + settings (`1` second or one-character paths). + +The adapter now provides `JsonHostReceiptStore`, uses a deterministic key from +the host session, explicit command, goal/resume target, and cwd, and atomically +stores the latest receipt after start, wait, submission, result, and cancel. +Sparse polling preserves pending dispatches when the field is absent and keeps +the cursor monotonic. `VMExecutionRequest` and `VMPersonalAgentRuntime` reject +the ambiguous VM inputs before a transport call. + +New automated coverage proves all three fixes: + +- `test_json_receipt_store_prevents_a_duplicate_start_after_host_restart` + persists a cursor update and reloads it through a fresh adapter while the + fake host receives only one start call. +- `test_sparse_wait_snapshot_preserves_pending_dispatch_and_cursor` verifies + pending dispatch retention and stale-cursor rejection. +- `test_vm_request_rejects_boolean_timeout_and_string_artifact_iterables` and + `test_execute_command_rejects_a_single_artifact_string` verify the VM input + boundary. + +Round-4 continuation evidence: + +```text +uv run pytest tests/unit/integrations/ tests/integration/host/ -q +87 passed +uv run ruff check src/ouroboros/integrations tests/unit/integrations tests/integration/host +All checks passed! +uv run mypy src/ouroboros +Success: no issues found in 819 source files +python3 scripts/check-module-size.py --baseline-ref origin/main +module-size: OK (818 modules, cap 2000, 23 grandfathered) +``` + +The durable receipt store, fake MCP/command transports, and sparse polling +cases are **[Verified locally]**. VM and host execution remain +**[Simulated VM/Fake Host E2E]**. A paid live Grok Bot account, provider VM, +private Bot API, and cloud-side execution remain **[Unverified: live paid +Grokbot account]**. diff --git a/src/ouroboros/integrations/__init__.py b/src/ouroboros/integrations/__init__.py index 46465e9eec..c33ae0b50e 100644 --- a/src/ouroboros/integrations/__init__.py +++ b/src/ouroboros/integrations/__init__.py @@ -14,10 +14,13 @@ HostCapabilityNegotiation, HostExecutionReceipt, HostInvocation, + HostReceiptStore, HostSubmissionError, HostToolResponse, HostToolTransport, + JsonHostReceiptStore, MCPToolTransport, + MemoryHostReceiptStore, PendingHostDispatch, PersonalAgentHostAdapter, normalize_tool_response, @@ -56,10 +59,13 @@ "HostAdapterError", "HostCapabilityNegotiation", "HostExecutionReceipt", + "HostReceiptStore", "HostInvocation", "HostSubmissionError", "HostToolResponse", "HostToolTransport", + "JsonHostReceiptStore", + "MemoryHostReceiptStore", "MCPToolTransport", "PendingHostDispatch", "PersonalAgentHostAdapter", diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index de051f2db5..8ecd9572ad 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -16,8 +16,12 @@ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace +import hashlib import json +import os +from pathlib import Path import shlex +import tempfile from typing import Any, Protocol from uuid import uuid4 @@ -230,6 +234,7 @@ class HostExecutionReceipt: auto_session_id: str job_id: str status: str + start_key: str = "" cursor: int = 0 is_terminal: bool = False result_available: bool = False @@ -261,6 +266,7 @@ def to_dict(self) -> dict[str, Any]: "auto_session_id": self.auto_session_id, "job_id": self.job_id, "status": self.status, + "start_key": self.start_key, "cursor": self.cursor, "is_terminal": self.is_terminal, "result_available": self.result_available, @@ -282,6 +288,98 @@ def to_dict(self) -> dict[str, Any]: }, } + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> HostExecutionReceipt: + """Restore durable lifecycle state without live MCP response objects.""" + return _host_receipt_from_dict(cls, value) + + +class HostReceiptStore(Protocol): + """Persistence seam for explicit host starts across adapter restarts.""" + + def get(self, key: str) -> HostExecutionReceipt | None: + """Read one receipt.""" + + def put(self, key: str, receipt: HostExecutionReceipt) -> None: + """Persist one receipt.""" + + def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: + """Atomically persist a first receipt for a key.""" + + +class MemoryHostReceiptStore: + """Small in-memory store for hosts that do not need process restart recovery.""" + + def __init__(self) -> None: + self._receipts: dict[str, HostExecutionReceipt] = {} + + def get(self, key: str) -> HostExecutionReceipt | None: + return self._receipts.get(key) + + def put(self, key: str, receipt: HostExecutionReceipt) -> None: + self._receipts[key] = receipt + + def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: + existing = self._receipts.get(key) + if existing is not None: + return existing + self._receipts[key] = receipt + return None + + +class JsonHostReceiptStore: + """Atomic JSON store for host receipts that must survive process restarts.""" + + def __init__(self, directory: str | Path) -> None: + self.directory = Path(directory).expanduser().resolve() + self.directory.mkdir(parents=True, exist_ok=True) + + def _path(self, key: str) -> Path: + digest = hashlib.sha256(key.encode("utf-8")).hexdigest() + return self.directory / f"{digest}.json" + + def get(self, key: str) -> HostExecutionReceipt | None: + path = self._path(key) + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return None + except (OSError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise HostAdapterError(f"corrupt host receipt for {key!r}") from exc + if not isinstance(raw, Mapping): + raise HostAdapterError(f"corrupt host receipt for {key!r}") + return HostExecutionReceipt.from_dict(raw) + + def put(self, key: str, receipt: HostExecutionReceipt) -> None: + path = self._path(key) + fd, temporary = tempfile.mkstemp(prefix=".host-receipt-", suffix=".tmp", dir=self.directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: + path = self._path(key) + fd, temporary = tempfile.mkstemp(prefix=".host-receipt-", suffix=".tmp", dir=self.directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + try: + os.link(temporary, path) + except FileExistsError: + return self.get(key) + return None + finally: + if os.path.exists(temporary): + os.unlink(temporary) + @dataclass(slots=True) class MCPToolTransport: @@ -429,17 +527,21 @@ def _new_request_id() -> str: def _start_key( invocation: HostInvocation, cwd: str | None, -) -> tuple[str | None, str, str, str]: +) -> str: action = ( f"resume:{invocation.resume_auto_session_id}" if invocation.is_resume else f"goal:{invocation.goal}" ) - return ( - invocation.host_session_id, - invocation.command_prefix.casefold(), - action, - cwd or "", + return json.dumps( + [ + invocation.host_session_id, + invocation.command_prefix.casefold(), + action, + cwd or "", + ], + ensure_ascii=False, + separators=(",", ":"), ) @@ -543,13 +645,15 @@ def __init__( host_name: str = "personal_agent", invocation_prefixes: Iterable[str] = _DEFAULT_INVOCATION_PREFIXES, expected_runtime_backend: str | None = "host", + receipt_store: HostReceiptStore | None = None, ) -> None: self.transport = transport self.host_name = host_name self.invocation_prefixes = tuple(invocation_prefixes) self.expected_runtime_backend = expected_runtime_backend + self.receipt_store = receipt_store or MemoryHostReceiptStore() self._start_locks = KeyedAsyncLockPool() - self._start_receipts: dict[tuple[str | None, str, str, str], HostExecutionReceipt] = {} + self._start_receipts: dict[str, HostExecutionReceipt] = {} @property def required_tools(self) -> tuple[str, ...]: @@ -615,6 +719,10 @@ async def start( cached = self._start_receipts.get(key) if cached is not None: return cached + persisted = self.receipt_store.get(key) + if persisted is not None: + self._start_receipts[key] = persisted + return persisted response = await self._call(START_AUTO_TOOL, arguments) payload = response.payload runtime_backend = payload.get("runtime_backend") @@ -638,9 +746,12 @@ async def start( payload=payload, response=response, start_response=response, + start_key=key, ) - self._start_receipts[key] = receipt - return receipt + claim = self.receipt_store.put_if_absent(key, receipt) + cached = claim or receipt + self._start_receipts[key] = cached + return cached async def wait( self, @@ -669,8 +780,12 @@ async def wait( }, ) payload = response.payload - pending = _pending_dispatches(payload.get("pending_host_dispatches"), JOB_WAIT_TOOL) - return _updated_receipt(receipt, payload, response, pending=pending) + pending = ( + _pending_dispatches(payload["pending_host_dispatches"], JOB_WAIT_TOOL) + if "pending_host_dispatches" in payload + else receipt.pending_host_dispatches + ) + return self._persist_receipt(_updated_receipt(receipt, payload, response, pending=pending)) async def submit_dispatch( self, @@ -732,25 +847,42 @@ async def submit_dispatch( for item in receipt.pending_host_dispatches if item.dispatch_id != dispatch.dispatch_id ) - return replace(receipt, pending_host_dispatches=remaining, last_submission=payload) + return self._persist_receipt( + replace(receipt, pending_host_dispatches=remaining, last_submission=payload) + ) async def result(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Fetch and preserve terminal Seed/execution/evaluation evidence.""" response = await self._call(JOB_RESULT_TOOL, {"job_id": receipt.job_id}) payload = response.payload - pending = _pending_dispatches(payload.get("pending_host_dispatches"), JOB_RESULT_TOOL) - return _updated_receipt( - receipt, - payload, - response, - pending=pending, - result_response=response, + pending = ( + _pending_dispatches(payload["pending_host_dispatches"], JOB_RESULT_TOOL) + if "pending_host_dispatches" in payload + else receipt.pending_host_dispatches + ) + return self._persist_receipt( + _updated_receipt( + receipt, + payload, + response, + pending=pending, + result_response=response, + ) ) async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Request cancellation while retaining the correlated receipt.""" response = await self._call(CANCEL_JOB_TOOL, {"job_id": receipt.job_id}) - return _updated_receipt(receipt, response.payload, response, pending=()) + return self._persist_receipt( + _updated_receipt(receipt, response.payload, response, pending=()) + ) + + def _persist_receipt(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Persist and refresh the in-process cache after every lifecycle response.""" + if receipt.start_key: + self.receipt_store.put(receipt.start_key, receipt) + self._start_receipts[receipt.start_key] = receipt + return receipt async def _call(self, tool_name: str, arguments: dict[str, Any]) -> HostToolResponse: caller = getattr(self.transport, "call_tool", self.transport) @@ -785,12 +917,14 @@ def __init__( *, invocation_prefixes: Iterable[str] = _DEFAULT_INVOCATION_PREFIXES, vm_profile: GrokBotVMProfile = GROK_BOT_VM_PROFILE, + receipt_store: HostReceiptStore | None = None, ) -> None: super().__init__( transport, host_name=GROK_BOT_HOST_NAME, invocation_prefixes=invocation_prefixes, expected_runtime_backend="host", + receipt_store=receipt_store, ) self.vm_profile = vm_profile @@ -877,6 +1011,7 @@ def _receipt_from_payload( payload: Mapping[str, Any], response: HostToolResponse, start_response: HostToolResponse, + start_key: str = "", ) -> HostExecutionReceipt: state = dict(payload) return HostExecutionReceipt( @@ -885,6 +1020,7 @@ def _receipt_from_payload( auto_session_id=auto_session_id, job_id=job_id, status=str(payload.get("status") or "queued"), + start_key=start_key, cursor=_non_negative_cursor(payload.get("cursor")), is_terminal=bool(payload.get("is_terminal", False)), result_available=bool(payload.get("result_available", False)), @@ -905,6 +1041,76 @@ def _receipt_from_payload( ) +def _host_receipt_from_dict( + receipt_type: type[HostExecutionReceipt], value: Mapping[str, Any] +) -> HostExecutionReceipt: + request = _model_mapping(value.get("request")) + if request is None: + raise HostAdapterError("host receipt is missing request state") + + def optional_text(item: Any) -> str | None: + return item.strip() if isinstance(item, str) and item.strip() else None + + invocation = HostInvocation( + request_id=_required_text(request, "request_id", "host receipt"), + host_session_id=optional_text(request.get("host_session_id")), + raw_message=_required_text(request, "raw_message", "host receipt"), + command_prefix=_required_text(request, "command_prefix", "host receipt"), + goal=optional_text(request.get("goal")), + resume_auto_session_id=optional_text(request.get("resume_auto_session_id")), + explicit=request.get("explicit") is True, + ) + pending_value = value.get("pending_host_dispatches", ()) + if not isinstance(pending_value, Sequence) or isinstance( + pending_value, (str, bytes, bytearray) + ): + raise HostAdapterError("host receipt pending dispatches must be a list") + pending: list[PendingHostDispatch] = [] + for item in pending_value: + raw = _model_mapping(item) + if raw is None: + raise HostAdapterError("host receipt pending dispatch must be an object") + working_directory = raw.get("working_directory") + if working_directory is not None and not isinstance(working_directory, str): + raise HostAdapterError("host receipt working_directory must be text") + pending.append( + PendingHostDispatch( + dispatch_id=_required_text(raw, "dispatch_id", "host receipt"), + fanout_id=_required_text(raw, "fanout_id", "host receipt"), + session_id=_required_text(raw, "session_id", "host receipt"), + result_correlation_key=_required_text( + raw, "result_correlation_key", "host receipt" + ), + submit_tool=_required_text(raw, "submit_tool", "host receipt"), + prompt=_required_text(raw, "prompt", "host receipt"), + working_directory=working_directory, + actionable=raw.get("actionable") is True, + raw=_mapping_value(raw.get("raw")), + ) + ) + return receipt_type( + host_name=_required_text(value, "host", "host receipt"), + invocation=invocation, + auto_session_id=_required_text(value, "auto_session_id", "host receipt"), + job_id=_required_text(value, "job_id", "host receipt"), + status=str(value.get("status") or "queued"), + start_key=str(value.get("start_key") or _start_key(invocation, None)), + cursor=_non_negative_cursor(value.get("cursor")), + is_terminal=value.get("is_terminal") is True, + result_available=value.get("result_available") is True, + links=_mapping_value(value.get("links")), + pending_host_dispatches=tuple(pending), + seed=_mapping_value(value.get("seed")), + execution=_mapping_value(value.get("execution")), + evaluation=_mapping_value(value.get("evaluation")), + verification=_mapping_value(value.get("verification")), + failure=_mapping_value(value.get("failure")), + recovery=_mapping_value(value.get("recovery")), + state=_mapping_value(value.get("state")), + last_submission=_mapping_value(value.get("last_submission")), + ) + + def _updated_receipt( receipt: HostExecutionReceipt, payload: Mapping[str, Any], @@ -917,7 +1123,7 @@ def _updated_receipt( return replace( receipt, status=str(payload.get("status") or receipt.status), - cursor=_non_negative_cursor(payload.get("cursor", receipt.cursor)), + cursor=max(receipt.cursor, _non_negative_cursor(payload.get("cursor", receipt.cursor))), is_terminal=bool( payload.get( "is_terminal", @@ -1026,10 +1232,13 @@ def _same_dispatch_claim(left: PendingHostDispatch, right: PendingHostDispatch) "HostAdapterError", "HostCapabilityNegotiation", "HostExecutionReceipt", + "HostReceiptStore", "HostInvocation", "HostSubmissionError", "HostToolResponse", "HostToolTransport", + "JsonHostReceiptStore", + "MemoryHostReceiptStore", "MCPToolTransport", "PendingHostDispatch", "PersonalAgentHostAdapter", diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index d019b835fa..011661e858 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -209,12 +209,23 @@ def __post_init__(self) -> None: raise VMRuntimeError("idempotency_key must be non-empty text") if "\x00" in self.idempotency_key: raise VMRuntimeError("idempotency_key must not contain NUL bytes") - if not isinstance(self.timeout_seconds, (int, float)) or not math.isfinite( - self.timeout_seconds + if ( + isinstance(self.timeout_seconds, bool) + or not isinstance(self.timeout_seconds, (int, float)) + or not math.isfinite(self.timeout_seconds) ): raise VMRuntimeError("timeout_seconds must be finite") if self.timeout_seconds <= 0: raise VMRuntimeError("timeout_seconds must be positive") + if isinstance(self.artifact_paths, (str, bytes)) or not isinstance( + self.artifact_paths, Iterable + ): + raise VMRuntimeError("artifact_paths must be an iterable of text paths") + for path in self.artifact_paths: + if not isinstance(path, str) or not path.strip(): + raise VMRuntimeError("artifact_paths must contain non-empty text paths") + if "\x00" in path: + raise VMRuntimeError("artifact_paths must not contain NUL bytes") @property def correlation_key(self) -> str: @@ -626,8 +637,10 @@ def __init__( default_timeout_seconds: float = 300.0, max_output_chars: int = 64 * 1024, ) -> None: - if not isinstance(default_timeout_seconds, (int, float)) or not math.isfinite( - default_timeout_seconds + if ( + isinstance(default_timeout_seconds, bool) + or not isinstance(default_timeout_seconds, (int, float)) + or not math.isfinite(default_timeout_seconds) ): raise VMRuntimeError("default_timeout_seconds must be finite") if default_timeout_seconds <= 0: @@ -657,6 +670,8 @@ async def execute_command( idempotency_key: str | None = None, ) -> VMExecutionReceipt: """Execute one command, or return the durable receipt for its retry.""" + if isinstance(artifact_paths, (str, bytes)): + raise VMRuntimeError("artifact_paths must be an iterable of text paths") request = VMExecutionRequest( dispatch_id=dispatch_id, session_id=session_id, diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index bb2edd8296..665f13b6df 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -3,11 +3,13 @@ from __future__ import annotations import asyncio +from pathlib import Path import pytest from ouroboros.integrations.personal_agent_host import ( HostAdapterError, + JsonHostReceiptStore, MCPToolTransport, PersonalAgentHostAdapter, normalize_tool_response, @@ -161,3 +163,110 @@ async def call_tool(_name: str, _arguments: dict[str, object]) -> dict[str, obje with pytest.raises(HostAdapterError, match="expected host runtime"): await adapter.start("/ouroboros do work") + + +@pytest.mark.asyncio +async def test_json_receipt_store_prevents_a_duplicate_start_after_host_restart( + tmp_path: Path, +) -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + calls += 1 + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-persisted", + "auto_session_id": "auto-persisted", + "runtime_backend": "host", + "status": "queued", + } + } + assert name == "ouroboros_job_wait" + return { + "meta": { + "job_id": "job-persisted", + "auto_session_id": "auto-persisted", + "runtime_backend": "host", + "status": "running", + "cursor": 4, + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + first_adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + first = await first_adapter.start( + "/ouroboros persist this request", + host_session_id="conversation-1", + cwd="/workspace", + ) + assert first is not None + await first_adapter.wait(first) + + second = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros persist this request", + host_session_id="conversation-1", + cwd="/workspace", + ) + + assert second is not None + assert second.cursor == 4 + assert calls == 2 + + +@pytest.mark.asyncio +async def test_sparse_wait_snapshot_preserves_pending_dispatch_and_cursor() -> None: + pending = { + "dispatch_id": "dispatch-1", + "fanout_id": "fanout-1", + "session_id": "auto-1", + "result_correlation_key": "result", + "submit_tool": "ouroboros_submit_fanout_results", + "actionable": True, + "subagents": [{"prompt": "run it", "context": {}}], + } + wait_calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal wait_calls + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-1", + "auto_session_id": "auto-1", + "runtime_backend": "host", + "status": "queued", + } + } + wait_calls += 1 + if wait_calls == 1: + return { + "meta": { + "job_id": "job-1", + "auto_session_id": "auto-1", + "runtime_backend": "host", + "status": "running", + "cursor": 2, + "pending_host_dispatches": [pending], + } + } + return { + "meta": { + "job_id": "job-1", + "auto_session_id": "auto-1", + "runtime_backend": "host", + "status": "running", + "cursor": 1, + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + receipt = await adapter.start("/ouroboros sparse polling") + assert receipt is not None + waiting = await adapter.wait(receipt) + repeated = await adapter.wait(waiting) + + assert len(repeated.pending_host_dispatches) == 1 + assert repeated.pending_host_dispatches[0].dispatch_id == "dispatch-1" + assert repeated.cursor == 2 diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 311a490f3c..d136cc75bf 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -184,6 +184,32 @@ def test_invalid_explicit_idempotency_keys_are_rejected(key: str) -> None: ) +def test_vm_request_rejects_boolean_timeout_and_string_artifact_iterables() -> None: + with pytest.raises(VMRuntimeError, match="timeout_seconds must be finite"): + VMExecutionRequest( + dispatch_id="dispatch", + session_id="session", + command="echo test", + timeout_seconds=True, + ) + + +@pytest.mark.asyncio +async def test_execute_command_rejects_a_single_artifact_string(tmp_path: Path) -> None: + runtime = VMPersonalAgentRuntime( + RecordingCommand(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + with pytest.raises(VMRuntimeError, match="artifact_paths must be an iterable"): + await runtime.execute_command( + "pytest -q", + dispatch_id="artifact-string", + session_id="session", + artifact_paths="result.json", + ) + + @pytest.mark.asyncio async def test_command_transport_maps_cwd_and_idempotency_key(tmp_path: Path) -> None: target = RecordingCommand() From eee86508be8fe5c7b69f4ae3e88dcc4ca826f866 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 09:20:45 +0900 Subject: [PATCH 13/41] test(task1-grok-vm-runtime): complete verification & hardening round 5 (ci-gate-and-regression-fortress) --- .../integrations/personal_agent_host.py | 32 +++++--- .../integrations/vm_agent_runtime.py | 48 ++++++------ .../integrations/test_personal_agent_host.py | 76 +++++++++++++++++++ .../integrations/test_vm_agent_runtime.py | 43 +++++++++++ 4 files changed, 166 insertions(+), 33 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 8ecd9572ad..402ed367e5 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -766,6 +766,8 @@ async def wait( default keeps a host loop from busy-spinning while still allowing a caller to request an immediate snapshot with ``timeout_seconds=0``. """ + if isinstance(timeout_seconds, bool) or not isinstance(timeout_seconds, int): + raise HostAdapterError("timeout_seconds must be an integer") if timeout_seconds < 0: raise HostAdapterError("timeout_seconds must be non-negative") response = await self._call( @@ -1120,21 +1122,29 @@ def _updated_receipt( result_response: HostToolResponse | None = None, ) -> HostExecutionReceipt: state = dict(payload) + reported_cursor = _non_negative_cursor(payload.get("cursor", receipt.cursor)) + incoming_status = str(payload.get("status") or receipt.status) + terminal_statuses = {"completed", "complete", "failed", "cancelled", "canceled", "interrupted"} + status = ( + receipt.status + if receipt.is_terminal and incoming_status not in terminal_statuses + else incoming_status + ) + pending_snapshot = ( + receipt.pending_host_dispatches if reported_cursor < receipt.cursor else pending + ) return replace( receipt, - status=str(payload.get("status") or receipt.status), - cursor=max(receipt.cursor, _non_negative_cursor(payload.get("cursor", receipt.cursor))), + status=status, + cursor=max(receipt.cursor, reported_cursor), is_terminal=bool( - payload.get( - "is_terminal", - receipt.is_terminal - or str(payload.get("status", "")).lower() - in {"completed", "complete", "failed", "cancelled", "canceled", "interrupted"}, - ) + receipt.is_terminal + or payload.get("is_terminal", False) + or incoming_status.lower() in terminal_statuses ), - result_available=bool(payload.get("result_available", receipt.result_available)), + result_available=bool(receipt.result_available or payload.get("result_available", False)), links=_mapping_value(payload.get("links")) or receipt.links, - pending_host_dispatches=pending, + pending_host_dispatches=pending_snapshot, seed=_named_evidence(state, "seed", "seed_state", "seed_result") or receipt.seed, execution=_named_evidence(state, "execution", "execution_state", "execution_result") or receipt.execution, @@ -1149,7 +1159,7 @@ def _updated_receipt( failure=_named_evidence(state, "failure", "failure_state", "error") or receipt.failure, recovery=_named_evidence(state, "recovery", "recovery_action", "next_step") or receipt.recovery, - state=state, + state={**receipt.state, **state}, last_response=response, result_response=result_response or receipt.result_response, ) diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 011661e858..6d91ea8e0a 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -966,28 +966,23 @@ def _receipt_from_response( execution_id = _optional_text(payload, "execution_id") or receipt.execution_id status = _optional_text(payload, "status") response_error = _optional_text(payload, "error") + exit_code = _response_exit_code(payload) if status is None: status = ( "failed" - if response_error is not None or _optional_int(payload, "exit_code", 0) != 0 + if response_error is not None or (exit_code is not None and exit_code != 0) else "completed" ) elif status == "error" or status == "completed" and response_error is not None: status = "failed" - elif status == "completed" and _optional_int(payload, "exit_code", None) not in ( - None, - 0, - ): - response_error = response_error or ( - f"VM execution exited with code {_optional_int(payload, 'exit_code', None)}" - ) + elif status == "completed" and exit_code not in (None, 0): + response_error = response_error or (f"VM execution exited with code {exit_code}") status = "failed" elif status not in _REMOTE_RUNNING_STATUSES | _TERMINAL_STATUSES: response_error = response_error or f"unsupported VM execution status: {status!r}" status = "failed" if status in _REMOTE_RUNNING_STATUSES: status = "running" - exit_code = _optional_int(payload, "exit_code", None) artifact_paths = _artifact_paths(payload, request.artifact_paths) artifacts = self.collect_artifacts(artifact_paths) stdout, stdout_truncated = _truncate_text( @@ -1161,23 +1156,32 @@ def _optional_text(values: Mapping[str, Any], key: str) -> str | None: return value.strip() if isinstance(value, str) and value.strip() else None -def _optional_int(values: Mapping[str, Any], key: str, default: int | None) -> int | None: - value = values.get(key, default) - try: - return int(value) if value is not None else None - except (TypeError, ValueError): - return default +def _response_exit_code(values: Mapping[str, Any]) -> int | None: + """Parse an exit code without turning malformed provider data into success.""" + if "exit_code" not in values or values["exit_code"] is None: + return None + value = values["exit_code"] + if isinstance(value, bool) or not isinstance(value, int): + raise VMTransportError("VM exit_code must be an integer or null") + return value def _artifact_paths(payload: Mapping[str, Any], requested: Iterable[str]) -> tuple[str, ...]: paths = list(requested) - remote = payload.get("artifacts") - if isinstance(remote, Iterable) and not isinstance(remote, (str, bytes, Mapping)): - for item in remote: - if isinstance(item, str): - paths.append(item) - elif isinstance(item, Mapping) and isinstance(item.get("path"), str): - paths.append(item["path"]) + if "artifacts" not in payload or payload["artifacts"] is None: + return tuple(dict.fromkeys(paths)) + remote = payload["artifacts"] + if not isinstance(remote, Iterable) or isinstance(remote, (str, bytes, Mapping)): + raise VMTransportError("VM artifacts must be a list of paths or path objects") + for item in remote: + if isinstance(item, str) and item.strip(): + paths.append(item) + elif isinstance(item, Mapping) and isinstance(item.get("path"), str): + if not item["path"].strip(): + raise VMTransportError("VM artifact path must be non-empty text") + paths.append(item["path"]) + else: + raise VMTransportError("VM artifacts must contain path strings or path objects") return tuple(dict.fromkeys(paths)) diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 665f13b6df..103c7b0643 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -270,3 +270,79 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert len(repeated.pending_host_dispatches) == 1 assert repeated.pending_host_dispatches[0].dispatch_id == "dispatch-1" assert repeated.cursor == 2 + + +@pytest.mark.asyncio +async def test_stale_wait_snapshot_cannot_regress_terminal_evidence() -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-terminal", + "auto_session_id": "auto-terminal", + "runtime_backend": "host", + "status": "queued", + } + } + calls += 1 + if calls == 1: + return { + "meta": { + "status": "complete", + "cursor": 4, + "is_terminal": True, + "result_available": True, + "verification": {"passed": True}, + "future_field": {"keep": True}, + } + } + return { + "meta": { + "status": "running", + "cursor": 3, + "is_terminal": False, + "result_available": False, + "future_field": {"new": True}, + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + receipt = await adapter.start("/ouroboros terminal evidence") + assert receipt is not None + terminal = await adapter.wait(receipt) + stale = await adapter.wait(terminal) + + assert stale.status == "complete" + assert stale.cursor == 4 + assert stale.is_terminal is True + assert stale.result_available is True + assert stale.verification == {"passed": True} + assert stale.state["future_field"] == {"new": True} + + +@pytest.mark.asyncio +async def test_wait_rejects_boolean_timeout_before_calling_host() -> None: + calls: list[str] = [] + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + calls.append(name) + return { + "meta": { + "job_id": "job-timeout", + "auto_session_id": "auto-timeout", + "runtime_backend": "host", + "status": "queued", + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + receipt = await adapter.start("/ouroboros timeout validation") + assert receipt is not None + + with pytest.raises(HostAdapterError, match="timeout_seconds must be an integer"): + await adapter.wait(receipt, timeout_seconds=True) + + assert calls == ["ouroboros_start_auto"] diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index d136cc75bf..ee50f2a48f 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -454,6 +454,49 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] assert receipt.error == "VM execution exited with code 7" +@pytest.mark.asyncio +async def test_malformed_exit_code_is_failed_instead_of_success(tmp_path: Path) -> None: + class MalformedExitCodeCommand: + calls = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.calls += 1 + return {"status": "completed", "exit_code": "not-an-integer"} + + target = MalformedExitCodeCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verify", dispatch_id="bad-exit", session_id="s") + retried = await runtime.execute_command("verify", dispatch_id="bad-exit", session_id="s") + + assert receipt.status == "failed" + assert receipt.is_terminal is True + assert "invalid VM response" in (receipt.error or "") + assert retried == receipt + assert target.calls == 1 + + +@pytest.mark.asyncio +async def test_malformed_artifact_container_is_failed_instead_of_ignored(tmp_path: Path) -> None: + class MalformedArtifactCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0, "artifacts": {"path": "../escape"}} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(MalformedArtifactCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verify", dispatch_id="bad-artifacts", session_id="s") + + assert receipt.status == "failed" + assert receipt.is_terminal is True + assert "invalid VM response" in (receipt.error or "") + + def test_invalid_output_limit_is_rejected_as_runtime_input(tmp_path: Path) -> None: with pytest.raises(VMRuntimeError, match="positive integer"): VMPersonalAgentRuntime( From b648436a678a2dcc05bc736ee8bf53cb15191ed4 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 09:55:23 +0900 Subject: [PATCH 14/41] test(task1-grok-vm-runtime): complete verification & hardening round 6 (real-runtime-e2e-simulation) --- STATE.md | 21 ++-- docs/verification/grok-bot-host-adapter.md | 53 +++++++++ .../integrations/personal_agent_host.py | 85 ++++++++++---- .../integrations/vm_agent_runtime.py | 11 ++ .../host/test_personal_agent_host.py | 99 +++++++++++++++-- .../integrations/test_personal_agent_host.py | 105 ++++++++++++++++++ .../integrations/test_vm_agent_runtime.py | 18 +++ 7 files changed, 354 insertions(+), 38 deletions(-) diff --git a/STATE.md b/STATE.md index dc50696ec1..2c955c6678 100644 --- a/STATE.md +++ b/STATE.md @@ -1,21 +1,23 @@ -# Round 4 runtime verification state +# Round 6 runtime verification state ## Goal -- Verify the Grokbot/VM personal-agent bridge with durable receipts, safe workspace mapping, explicit host routing, disconnect recovery, and reviewer-readable evidence. +- Verify the Grokbot/VM personal-agent bridge through a realistic explicit host journey, durable VM receipts, safe workspace mapping, and disconnect recovery. - Keep Draft PR #3130 open and preserve the live paid Grokbot unverified boundary. ## Constraints - Work only in `/home/lee3q/work/night-20261130/worktrees/ouroboros-grok-vm`. - Never merge a PR or add credentials. -- Required focused gate must exit 0 before completion. +- The focused acceptance command and repository gates must exit 0 before completion. ## Confirmed facts - Branch: `feat/personal-agent-vm-runtime-20261130`. -- Round 4 continuation reproduced and fixed: host receipt state was memory-only across adapter restarts; sparse `job_wait` snapshots dropped pending dispatches and could regress cursors; boolean timeout and string artifact inputs crossed the VM boundary ambiguously. -- `JsonHostReceiptStore` now atomically persists start, wait, submit, result, and cancel receipt state under a deterministic explicit-request key. -- Focused suite after continuation fixes: 87 passed. -- Full Ruff format/lint, MyPy, module-size, focused acceptance, touched-path lint, and `git diff --check` passed. -- No root `STATUS.md` exists; tracked `STATE.md` remains the required execution anchor. +- The Round 6 audit reproduced a legacy host-store claim crash, truthy string lifecycle flags, and VM MCP rejection of Ouroboros `Result` envelopes. +- Host receipt claims now fall back to read/write behavior for stores predating `put_if_absent`. JSON stores retain the atomic claim guarantee. +- Host lifecycle status, boolean flags, and cursors now fail closed on ambiguous wire values. +- VM MCP payload normalization now unwraps internal `Result` envelopes. +- A new fake-host/fake-VM integration journey covers accepted VM work, disconnect, runtime restart, resume by execution ID, host submission, and terminal verification. +- Focused suite after Round 6 changes: 97 passed. +- No root `STATUS.md` exists. Tracked `STATE.md` remains the execution anchor required by the worktree instructions. - Draft PR #3130 remains open and unmerged. Live paid Grokbot and provider-side VM execution remain unverified. ## Evidence paths @@ -23,7 +25,8 @@ - `src/ouroboros/integrations/vm_agent_runtime.py` - `tests/unit/integrations/test_personal_agent_host.py` - `tests/unit/integrations/test_vm_agent_runtime.py` +- `tests/integration/host/test_personal_agent_host.py` - `docs/verification/grok-bot-host-adapter.md` ## Next actions -- Refresh PR #3130 body with continuation evidence, commit the verified changes, push the branch, and inspect the new remote checks without merging. +- Run the full local gates, record final evidence, commit, push Draft PR #3130, and inspect the resulting remote checks without merging. diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index 90467c712f..37b557fb9c 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -326,3 +326,56 @@ cases are **[Verified locally]**. VM and host execution remain **[Simulated VM/Fake Host E2E]**. A paid live Grok Bot account, provider VM, private Bot API, and cloud-side execution remain **[Unverified: live paid Grokbot account]**. + +## Evolution round 6: realistic host journey and failure recovery simulation + +Date: 2026-11-30 (Asia/Seoul) + +The adversarial audit re-read the complete branch diff, checked Draft PR #3130, +ran the focused suite and repository gates, and used small direct probes before +the Round 6 changes. Three concrete contract gaps were reproduced. + +- A custom host receipt store implementing the pre-atomic `get` and `put` + methods raised `AttributeError` during the first explicit start because the + adapter called `put_if_absent` unconditionally. The documented compatibility + path existed in the PR boundary but not in the implementation. +- Host lifecycle payloads accepted truthy strings. A response with + `is_terminal: "false"` became a terminal receipt, and the cursor parser + silently converted malformed values such as `"2"` to zero. Both behaviors + could corrupt restart state or hide progress. +- A VM MCP transport returning Ouroboros's internal `Result.ok(...)` envelope + was treated as an unrecognized payload. The host-side adapter already + unwrapped this envelope, but the VM-side public MCP adapter did not. + +The adapter now uses a read/write compatibility fallback for legacy receipt +stores, preserves the atomic claim path for stores that implement it, validates +status, boolean, and cursor types at the host boundary, and derives terminal +state from terminal statuses. VM MCP normalization unwraps internal Result +envelopes without adding an optional SDK dependency. + +The new integration journey starts with an explicit `/ouroboros` request, +receives a host dispatch, runs it through a fake VM transport that disconnects +after accepting execution, recreates the runtime with the same JSON receipt +store, resumes the saved execution ID, submits the recovered result, and reads +the final verification evidence. It asserts one VM execute call and one resume +call, so the simulated restart does not replay the command. + +New automated coverage includes: + +- `test_start_supports_a_legacy_receipt_store_without_atomic_claim` +- `test_lifecycle_flags_reject_string_values_instead_of_coercing_them` +- `test_cursor_rejects_ambiguous_wire_values_instead_of_silently_resetting` +- `test_host_transport_unwraps_internal_result_envelopes` +- `test_mcp_transport_unwraps_internal_result_envelopes` +- `test_host_and_vm_journey_recovers_a_disconnected_worker_after_restart` + +Round-6 evidence: + +- **[Verified locally]** The focused acceptance suite passes with 97 tests. +- **[Verified locally]** Touched-path Ruff format and lint pass after the + changes. Repository-wide Ruff and MyPy remain required before the final + commit. +- **[Simulated VM/Fake Host E2E]** The linked recovery journey uses deterministic + fake host and VM transports. No provider-side execution is claimed. +- **[Unverified: live paid Grokbot account]** No paid live Grok Bot account, + provider VM, private Bot API, or cloud-side execution was available. diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 402ed367e5..db92abba8b 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -70,6 +70,9 @@ _DEFAULT_INVOCATION_PREFIXES: tuple[str, ...] = ("/ouroboros", "ooo auto") _RESUME_WORDS = frozenset({"resume", "--resume"}) +_HOST_TERMINAL_STATUSES = frozenset( + {"completed", "complete", "failed", "cancelled", "canceled", "interrupted"} +) class HostToolTransport(Protocol): @@ -419,7 +422,7 @@ def _model_mapping(value: Any) -> dict[str, Any] | None: def _unwrap_result(value: Any) -> Any: """Unwrap Ouroboros's ``Result`` without importing the core type.""" - if hasattr(value, "is_err") and hasattr(value, "value"): + if hasattr(value, "is_err"): if bool(value.is_err): error = getattr(value, "error", "MCP tool call failed") raise HostAdapterError(str(error)) @@ -748,8 +751,7 @@ async def start( start_response=response, start_key=key, ) - claim = self.receipt_store.put_if_absent(key, receipt) - cached = claim or receipt + cached = self._claim_receipt(key, receipt) self._start_receipts[key] = cached return cached @@ -886,6 +888,24 @@ def _persist_receipt(self, receipt: HostExecutionReceipt) -> HostExecutionReceip self._start_receipts[receipt.start_key] = receipt return receipt + def _claim_receipt(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Claim a first receipt while supporting older custom stores. + + Stores that implement ``put_if_absent`` provide the cross-process claim + guarantee. Older stores fall back to a read followed by a write so + they keep working, while their existing process-safety boundary stays + unchanged. + """ + claim = getattr(self.receipt_store, "put_if_absent", None) + if callable(claim): + existing = claim(key, receipt) + return existing or receipt + existing = self.receipt_store.get(key) + if existing is not None: + return existing + self.receipt_store.put(key, receipt) + return receipt + async def _call(self, tool_name: str, arguments: dict[str, Any]) -> HostToolResponse: caller = getattr(self.transport, "call_tool", self.transport) if not callable(caller): @@ -1016,16 +1036,18 @@ def _receipt_from_payload( start_key: str = "", ) -> HostExecutionReceipt: state = dict(payload) + status = _status_text(payload.get("status"), default="queued") return HostExecutionReceipt( host_name=host_name, invocation=invocation, auto_session_id=auto_session_id, job_id=job_id, - status=str(payload.get("status") or "queued"), + status=status, start_key=start_key, cursor=_non_negative_cursor(payload.get("cursor")), - is_terminal=bool(payload.get("is_terminal", False)), - result_available=bool(payload.get("result_available", False)), + is_terminal=_strict_bool(payload.get("is_terminal"), "is_terminal") + or status.casefold() in _HOST_TERMINAL_STATUSES, + result_available=_strict_bool(payload.get("result_available"), "result_available"), links=_mapping_value(payload.get("links")), seed=_named_evidence(state, "seed", "seed_state", "seed_result"), execution=_named_evidence(state, "execution", "execution_state", "execution_result"), @@ -1095,11 +1117,11 @@ def optional_text(item: Any) -> str | None: invocation=invocation, auto_session_id=_required_text(value, "auto_session_id", "host receipt"), job_id=_required_text(value, "job_id", "host receipt"), - status=str(value.get("status") or "queued"), + status=_status_text(value.get("status"), default="queued"), start_key=str(value.get("start_key") or _start_key(invocation, None)), cursor=_non_negative_cursor(value.get("cursor")), - is_terminal=value.get("is_terminal") is True, - result_available=value.get("result_available") is True, + is_terminal=_strict_bool(value.get("is_terminal"), "is_terminal"), + result_available=_strict_bool(value.get("result_available"), "result_available"), links=_mapping_value(value.get("links")), pending_host_dispatches=tuple(pending), seed=_mapping_value(value.get("seed")), @@ -1122,12 +1144,12 @@ def _updated_receipt( result_response: HostToolResponse | None = None, ) -> HostExecutionReceipt: state = dict(payload) - reported_cursor = _non_negative_cursor(payload.get("cursor", receipt.cursor)) - incoming_status = str(payload.get("status") or receipt.status) - terminal_statuses = {"completed", "complete", "failed", "cancelled", "canceled", "interrupted"} + reported_cursor = _non_negative_cursor(payload.get("cursor"), default=receipt.cursor) + incoming_status = _status_text(payload.get("status"), default=receipt.status) + terminal_statuses = _HOST_TERMINAL_STATUSES status = ( receipt.status - if receipt.is_terminal and incoming_status not in terminal_statuses + if receipt.is_terminal and incoming_status.casefold() not in terminal_statuses else incoming_status ) pending_snapshot = ( @@ -1139,10 +1161,13 @@ def _updated_receipt( cursor=max(receipt.cursor, reported_cursor), is_terminal=bool( receipt.is_terminal - or payload.get("is_terminal", False) - or incoming_status.lower() in terminal_statuses + or _strict_bool(payload.get("is_terminal"), "is_terminal") + or incoming_status.casefold() in _HOST_TERMINAL_STATUSES + ), + result_available=bool( + receipt.result_available + or _strict_bool(payload.get("result_available"), "result_available") ), - result_available=bool(receipt.result_available or payload.get("result_available", False)), links=_mapping_value(payload.get("links")) or receipt.links, pending_host_dispatches=pending_snapshot, seed=_named_evidence(state, "seed", "seed_state", "seed_result") or receipt.seed, @@ -1169,12 +1194,28 @@ def _mapping_value(value: Any) -> Mapping[str, Any]: return _model_mapping(value) or {} -def _non_negative_cursor(value: Any) -> int: - try: - cursor = int(value) - except (TypeError, ValueError): - return 0 - return max(cursor, 0) +def _status_text(value: Any, *, default: str) -> str: + if value is None: + return default + if not isinstance(value, str) or not value.strip(): + raise HostAdapterError("status must be non-empty text") + return value.strip() + + +def _strict_bool(value: Any, key: str) -> bool: + if value is None: + return False + if not isinstance(value, bool): + raise HostAdapterError(f"{key} must be a boolean") + return value + + +def _non_negative_cursor(value: Any, *, default: int = 0) -> int: + if value is None: + return default + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise HostAdapterError("cursor must be a non-negative integer") + return value def _named_evidence(payload: Mapping[str, Any], *names: str) -> Mapping[str, Any]: diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 6d91ea8e0a..076de5a3df 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -1043,7 +1043,18 @@ def _mapping(value: Any) -> Mapping[str, Any]: return {} +def _unwrap_result(value: Any) -> Any: + """Unwrap Ouroboros's ``Result`` without importing the core type.""" + if hasattr(value, "is_err"): + if bool(value.is_err): + error = getattr(value, "error", "VM MCP tool call failed") + raise VMTransportError(str(error)) + return value.value + return value + + def _payload(value: Any) -> dict[str, Any]: + value = _unwrap_result(value) if isinstance(value, (str, bytes, bytearray)): try: decoded = json.loads(value) diff --git a/tests/integration/host/test_personal_agent_host.py b/tests/integration/host/test_personal_agent_host.py index 1b31aa486c..be5f27ac71 100644 --- a/tests/integration/host/test_personal_agent_host.py +++ b/tests/integration/host/test_personal_agent_host.py @@ -13,6 +13,10 @@ GrokBotHostAdapter, HostSubmissionError, ) +from ouroboros.integrations.vm_agent_runtime import ( + JsonVMReceiptStore, + VMTransportDisconnected, +) def _response(meta: dict[str, Any], *, text: str = "ok") -> dict[str, Any]: @@ -23,7 +27,7 @@ def _response(meta: dict[str, Any], *, text: str = "ok") -> dict[str, Any]: } -def _pending() -> dict[str, Any]: +def _pending(working_directory: str = "/grok/cloud/workspace") -> dict[str, Any]: return { "dispatch_id": "fanout_dispatch_1", "fanout_id": "fanout_dispatch_1", @@ -38,7 +42,7 @@ def _pending() -> dict[str, Any]: "prompt": "WORKING DIRECTORY (mandatory): do the Seed work", "context": { "kind": "host_execution", - "working_directory": "/grok/cloud/workspace", + "working_directory": working_directory, "session_id": "auto_session_1", }, } @@ -49,9 +53,16 @@ def _pending() -> dict[str, Any]: class FakeHostTransport: """Deterministic stand-in for a host's MCP client and worker loop.""" - def __init__(self) -> None: + def __init__( + self, + *, + working_directory: str = "/grok/cloud/workspace", + expected_submission: dict[str, Any] | None = None, + ) -> None: self.calls: list[tuple[str, dict[str, Any]]] = [] self.submitted = False + self.working_directory = working_directory + self.expected_submission = expected_submission or {"final_message": "worker finished"} async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: self.calls.append((name, deepcopy(arguments))) @@ -79,7 +90,7 @@ async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any "is_terminal": False, "result_available": False, "links": {"session_id": "auto_session_1"}, - "pending_host_dispatches": [_pending()], + "pending_host_dispatches": [_pending(self.working_directory)], }, text="A host worker is required.", ) @@ -105,9 +116,7 @@ async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any assert arguments["fanout_id"] == "fanout_dispatch_1" assert arguments["session_id"] == "auto_session_1" assert arguments["correlation_key"] == "result" - assert arguments["results"] == [ - {"key": "result", "content": {"final_message": "worker finished"}} - ] + assert arguments["results"] == [{"key": "result", "content": self.expected_submission}] self.submitted = True return _response( { @@ -345,3 +354,79 @@ async def test_stale_dispatch_correlation_token_is_rejected() -> None: await adapter.submit_dispatch(waiting, stale_dispatch, {"final_message": "late"}) assert len(fake_host.calls) == call_count + + +@pytest.mark.integration +@pytest.mark.asyncio +async def test_host_and_vm_journey_recovers_a_disconnected_worker_after_restart( + tmp_path: Any, +) -> None: + workspace = tmp_path / "workspace" + workspace.mkdir() + expected_submission = { + "final_message": "worker recovered", + "vm_status": "completed", + "execution_id": "vm-execution-1", + } + fake_host = FakeHostTransport( + working_directory=str(workspace), + expected_submission=expected_submission, + ) + host_adapter = GrokBotHostAdapter(fake_host) + host_receipt = await host_adapter.start( + "/ouroboros run the verification in the VM", + host_session_id="grok-recovery", + cwd=str(workspace), + ) + assert host_receipt is not None + waiting = await host_adapter.wait(host_receipt) + dispatch = waiting.pending_host_dispatches[0] + + class DisconnectThenResume: + def __init__(self) -> None: + self.execute_calls = 0 + self.resume_calls = 0 + + async def execute(self, _request: Any) -> Any: + self.execute_calls += 1 + raise VMTransportDisconnected( + "VM connection dropped after acceptance", + execution_id="vm-execution-1", + ) + + async def resume(self, _request: Any, execution_id: str) -> Any: + self.resume_calls += 1 + assert execution_id == "vm-execution-1" + return {"status": "completed", "exit_code": 0, "stdout": "verified"} + + transport = DisconnectThenResume() + vm_receipts = JsonVMReceiptStore(tmp_path / "vm-receipts") + first_runtime = host_adapter.create_vm_runtime( + transport, + host_workspace=str(workspace), + receipt_store=vm_receipts, + ) + disconnected = await first_runtime.execute_dispatch(dispatch.to_dict()) + + assert disconnected.status == "disconnected" + assert disconnected.execution_id == "vm-execution-1" + + restarted_runtime = host_adapter.create_vm_runtime( + transport, + host_workspace=str(workspace), + receipt_store=vm_receipts, + ) + recovered = await restarted_runtime.resume_dispatch( + dispatch.dispatch_id, + session_id=dispatch.session_id, + ) + assert recovered.status == "completed" + assert recovered.stdout == "verified" + + submitted = await host_adapter.submit_dispatch(waiting, dispatch, expected_submission) + final = await host_adapter.wait(submitted) + + assert final.is_terminal is True + assert final.verification["status"] == "passed" + assert transport.execute_calls == 1 + assert transport.resume_calls == 1 diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 103c7b0643..bfdf35fc88 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -7,6 +7,7 @@ import pytest +from ouroboros.core.types import Result from ouroboros.integrations.personal_agent_host import ( HostAdapterError, JsonHostReceiptStore, @@ -215,6 +216,110 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 2 +@pytest.mark.asyncio +async def test_start_supports_a_legacy_receipt_store_without_atomic_claim() -> None: + class LegacyReceiptStore: + def __init__(self) -> None: + self.receipts: dict[str, object] = {} + + def get(self, key: str) -> object: + return self.receipts.get(key) + + def put(self, key: str, receipt: object) -> None: + self.receipts[key] = receipt + + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + return { + "meta": { + "job_id": "job-legacy", + "auto_session_id": "auto-legacy", + "runtime_backend": "host", + "status": "queued", + } + } + + store = LegacyReceiptStore() + first = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros preserve the old store contract", + host_session_id="legacy-session", + ) + second = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros preserve the old store contract", + host_session_id="legacy-session", + ) + + assert first is not None + assert second == first + assert calls == 1 + + +@pytest.mark.asyncio +async def test_lifecycle_flags_reject_string_values_instead_of_coercing_them() -> None: + async def call_tool(_name: str, _arguments: dict[str, object]) -> dict[str, object]: + return { + "meta": { + "job_id": "job-flags", + "auto_session_id": "auto-flags", + "runtime_backend": "host", + "status": "queued", + "is_terminal": "false", + } + } + + with pytest.raises(HostAdapterError, match="is_terminal must be a boolean"): + await PersonalAgentHostAdapter(call_tool).start("/ouroboros validate lifecycle flags") + + +@pytest.mark.asyncio +async def test_cursor_rejects_ambiguous_wire_values_instead_of_silently_resetting() -> None: + calls: list[str] = [] + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + calls.append(name) + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-cursor", + "auto_session_id": "auto-cursor", + "runtime_backend": "host", + "status": "queued", + } + } + return {"meta": {"status": "running", "cursor": "2"}} + + adapter = PersonalAgentHostAdapter(call_tool) + receipt = await adapter.start("/ouroboros validate cursor") + assert receipt is not None + + with pytest.raises(HostAdapterError, match="cursor must be a non-negative integer"): + await adapter.wait(receipt) + + assert calls == ["ouroboros_start_auto", "ouroboros_job_wait"] + + +@pytest.mark.asyncio +async def test_host_transport_unwraps_internal_result_envelopes() -> None: + response = normalize_tool_response( + "ouroboros_start_auto", + Result.ok( + { + "meta": { + "job_id": "job-result", + "auto_session_id": "auto-result", + "runtime_backend": "host", + } + } + ), + ) + + assert response.payload["job_id"] == "job-result" + + @pytest.mark.asyncio async def test_sparse_wait_snapshot_preserves_pending_dispatch_and_cursor() -> None: pending = { diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index ee50f2a48f..c4adf674e7 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -9,6 +9,7 @@ import pytest +from ouroboros.core.types import Result from ouroboros.integrations import ( GROK_BOT_VM_PROFILE, CommandVMTransport, @@ -315,6 +316,23 @@ async def test_mcp_transport_uses_a_generic_public_command_surface(tmp_path: Pat assert arguments["idempotency_key"] == "session-2:dispatch-2" +@pytest.mark.asyncio +async def test_mcp_transport_unwraps_internal_result_envelopes(tmp_path: Path) -> None: + class ResultMCP: + async def call_tool(self, _name: str, _arguments: dict[str, Any]) -> Result[Any, str]: + return Result.ok({"status": "completed", "exit_code": 0, "stdout": "ok"}) + + runtime = VMPersonalAgentRuntime( + MCPVMTransport(ResultMCP()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("echo test", dispatch_id="result", session_id="s") + + assert receipt.status == "completed" + assert receipt.stdout == "ok" + + @pytest.mark.asyncio @pytest.mark.parametrize( ("content_text", "expected_stdout"), From 8d2de81dde5bb5c71fa3c9469bbed7bbd2032fd3 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 10:16:47 +0900 Subject: [PATCH 15/41] test(task1-grok-vm-runtime): complete verification & hardening round 7 (performance-p99-hardening) --- STATUS.md | 15 ++ docs/verification/grok-bot-host-adapter.md | 18 ++ src/ouroboros/integrations/__init__.py | 4 + .../integrations/vm_agent_runtime.py | 239 +++++++++++++++--- .../integrations/test_vm_agent_runtime.py | 119 +++++++++ 5 files changed, 355 insertions(+), 40 deletions(-) create mode 100644 STATUS.md diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 0000000000..82e7b92850 --- /dev/null +++ b/STATUS.md @@ -0,0 +1,15 @@ +# Ouroboros Grokbot and VM Personal-Agent Runtime + +## 🗺️ 단계 / 로드맵 +- [x] 1단계: VM personal-agent host/runtime adapter baseline +- [x] 2단계: Round 6 durable receipts, disconnect recovery, and focused verification +- [ ] 👉 3단계: Round 7 p99 latency, backpressure, and resource-ceiling audit +- [ ] 4단계: Final gates, evidence, Draft PR update, and remote check inspection + +## 🛑 블로커 +- 블로커: 없음 + +## 🤖 AI 실행 맥락 +- 마지막 커밋: b648436a / feat/personal-agent-vm-runtime-20261130 +- 지금 손댄 파일: Round 7 runtime, tests, and verification evidence +- 다음 할 일: Run the focused suites, identify concrete bottlenecks, and implement verified fixes diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index 37b557fb9c..19632442c3 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -379,3 +379,21 @@ Round-6 evidence: fake host and VM transports. No provider-side execution is claimed. - **[Unverified: live paid Grokbot account]** No paid live Grok Bot account, provider VM, private Bot API, or cloud-side execution was available. + +## Round 7 p99, backpressure, and resource-ceiling audit + +Round 7 was audited on **2026-11-30** at the branch tip before the final gate run. + +The adversarial pass reproduced three concrete weaknesses in the Round 6 runtime. + +- Unique dispatches had only per-correlation locking. A burst could create an unbounded set of transport calls and waiting tasks. +- Artifact collection hashed every returned file synchronously without a byte ceiling. A large artifact could monopolize the event loop and delay unrelated work. +- A provider could return an unbounded artifact list before the receipt path validated it, increasing CPU and memory pressure during response normalization. + +The runtime now uses bounded admission with configurable `max_concurrent_executions` and `max_queue_size`. Excess callers receive `VMBackpressureError` before a durable execution claim is created. `resource_snapshot` exposes active and queued counts for host health reporting. Artifact collection limits both path count and total bytes hashed per response. + +New automated coverage includes a blocking burst that proves one active execution, one queued execution, and deterministic rejection of the third caller. A 32-dispatch burst proves active work never exceeds a three-execution ceiling. Artifact tests prove both byte and path limits fail closed. + +The local burst benchmark used 64 fake VM calls with a 3 ms service delay and a four-execution ceiling. It measured `max_active=4`, `p50=29.40 ms`, `p99=52.08 ms`, and `wall=59.35 ms`. The final resource snapshot was `active_executions=0` and `queued_executions=0`. + +Round 7 evidence is **[Verified locally]** for the focused integration suite, targeted Ruff, the burst benchmark, and the source changes. VM execution remains **[Simulated VM/Fake Host E2E]**. A paid live Grok Bot account, provider-side VM, private Bot API, and cloud execution remain **[Unverified: live paid Grokbot account]**. diff --git a/src/ouroboros/integrations/__init__.py b/src/ouroboros/integrations/__init__.py index c33ae0b50e..53577c21b9 100644 --- a/src/ouroboros/integrations/__init__.py +++ b/src/ouroboros/integrations/__init__.py @@ -38,12 +38,14 @@ MCPVMTransport, MemoryVMReceiptStore, VMArtifact, + VMBackpressureError, VMCommandTransport, VMExecutionReceipt, VMExecutionRequest, VMMCPTransport, VMPathError, VMPersonalAgentRuntime, + VMResourceSnapshot, VMRuntimeError, VMTransportDisconnected, VMTransportError, @@ -80,6 +82,7 @@ "MCPVMTransport", "MemoryVMReceiptStore", "VMArtifact", + "VMBackpressureError", "VMCommandTransport", "VMExecutionReceipt", "VMExecutionRequest", @@ -87,6 +90,7 @@ "VMPersonalAgentRuntime", "VMPathError", "VMRuntimeError", + "VMResourceSnapshot", "VMTransportDisconnected", "VMTransportTimeout", "VMTransportError", diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 076de5a3df..b799134558 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -12,6 +12,7 @@ import asyncio from collections.abc import Iterable, Mapping +from contextlib import asynccontextmanager from dataclasses import dataclass, field, replace from datetime import UTC, datetime import hashlib @@ -30,6 +31,10 @@ class VMRuntimeError(RuntimeError): """Base error for the VM runtime bridge.""" +class VMBackpressureError(VMRuntimeError): + """The runtime has reached its configured execution queue ceiling.""" + + class VMPathError(VMRuntimeError): """A host or VM path is outside the configured workspace.""" @@ -54,6 +59,85 @@ def __init__(self, message: str, *, execution_id: str | None = None) -> None: self.execution_id = execution_id +@dataclass(frozen=True, slots=True) +class VMResourceSnapshot: + """Current bounded-admission counters for one runtime instance.""" + + active_executions: int + queued_executions: int + max_concurrent_executions: int + max_queue_size: int + + +class _ExecutionAdmission: + """Bound transport work and reject excess callers before they allocate state.""" + + def __init__(self, max_concurrent: int, max_queue: int) -> None: + self.max_concurrent = max_concurrent + self.max_queue = max_queue + self._slots = asyncio.Semaphore(max_concurrent) + self._guard = asyncio.Lock() + self._active = 0 + self._queued = 0 + + @property + def active(self) -> int: + return self._active + + @property + def queued(self) -> int: + return self._queued + + @asynccontextmanager + async def slot(self): + """Wait for one execution slot while enforcing the total queue ceiling.""" + registered = False + slot_acquired = False + active_registered = False + async with self._guard: + if self._active + self._queued >= self.max_concurrent + self.max_queue: + raise VMBackpressureError( + "VM execution queue is full " + f"(active={self._active}, queued={self._queued}, " + f"max_concurrent={self.max_concurrent}, max_queue={self.max_queue})" + ) + self._queued += 1 + registered = True + try: + await self._slots.acquire() + slot_acquired = True + async with self._guard: + self._queued -= 1 + self._active += 1 + registered = False + active_registered = True + yield + except BaseException: + if registered or active_registered: + async with self._guard: + if registered: + self._queued -= 1 + registered = False + if active_registered: + self._active -= 1 + active_registered = False + if slot_acquired: + self._slots.release() + raise + else: + async with self._guard: + self._active -= 1 + self._slots.release() + + def snapshot(self) -> VMResourceSnapshot: + return VMResourceSnapshot( + active_executions=self._active, + queued_executions=self._queued, + max_concurrent_executions=self.max_concurrent, + max_queue_size=self.max_queue, + ) + + def _path_text(value: str | os.PathLike[str], label: str) -> str: """Return a path string while converting invalid path input to VMPathError.""" try: @@ -636,6 +720,10 @@ def __init__( receipt_store: VMReceiptStore | None = None, default_timeout_seconds: float = 300.0, max_output_chars: int = 64 * 1024, + max_concurrent_executions: int = 8, + max_queue_size: int = 128, + max_artifact_paths: int = 128, + max_artifact_bytes: int = 64 * 1024 * 1024, ) -> None: if ( isinstance(default_timeout_seconds, bool) @@ -651,12 +739,44 @@ def __init__( or max_output_chars <= 0 ): raise VMRuntimeError("max_output_chars must be a positive integer") + if ( + not isinstance(max_concurrent_executions, int) + or isinstance(max_concurrent_executions, bool) + or max_concurrent_executions <= 0 + ): + raise VMRuntimeError("max_concurrent_executions must be a positive integer") + if ( + not isinstance(max_queue_size, int) + or isinstance(max_queue_size, bool) + or max_queue_size < 0 + ): + raise VMRuntimeError("max_queue_size must be a non-negative integer") + if ( + not isinstance(max_artifact_paths, int) + or isinstance(max_artifact_paths, bool) + or max_artifact_paths <= 0 + ): + raise VMRuntimeError("max_artifact_paths must be a positive integer") + if ( + not isinstance(max_artifact_bytes, int) + or isinstance(max_artifact_bytes, bool) + or max_artifact_bytes <= 0 + ): + raise VMRuntimeError("max_artifact_bytes must be a positive integer") self.transport = transport self.workspace = workspace self.receipt_store = receipt_store or MemoryVMReceiptStore() self.default_timeout_seconds = default_timeout_seconds self.max_output_chars = max_output_chars + self.max_artifact_paths = max_artifact_paths + self.max_artifact_bytes = max_artifact_bytes self._locks = KeyedAsyncLockPool() + self._admission = _ExecutionAdmission(max_concurrent_executions, max_queue_size) + + @property + def resource_snapshot(self) -> VMResourceSnapshot: + """Return bounded execution and queue counters for health reporting.""" + return self._admission.snapshot() async def execute_command( self, @@ -670,8 +790,7 @@ async def execute_command( idempotency_key: str | None = None, ) -> VMExecutionReceipt: """Execute one command, or return the durable receipt for its retry.""" - if isinstance(artifact_paths, (str, bytes)): - raise VMRuntimeError("artifact_paths must be an iterable of text paths") + artifact_paths = _bounded_paths(artifact_paths, self.max_artifact_paths) request = VMExecutionRequest( dispatch_id=dispatch_id, session_id=session_id, @@ -680,7 +799,7 @@ async def execute_command( timeout_seconds=( self.default_timeout_seconds if timeout_seconds is None else timeout_seconds ), - artifact_paths=tuple(artifact_paths), + artifact_paths=artifact_paths, idempotency_key=idempotency_key, ) return await self._execute_request(request) @@ -746,12 +865,14 @@ async def resume_dispatch( self._validate_receipt_match(current, request) if current.is_terminal: return current - return await self._resume_or_recover(current, request) + async with self._admission.slot(): + return await self._resume_or_recover(current, request) def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: """Collect metadata only for files within the approved workspace.""" artifacts: list[VMArtifact] = [] - for path in paths: + total_bytes = 0 + for path in _bounded_paths(paths, self.max_artifact_paths): if not isinstance(path, str) or not path.strip(): raise VMPathError("artifact paths must be non-empty strings") host_path = self.workspace.resolve_artifact_path(path) @@ -763,9 +884,10 @@ def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: if not host_path.is_file(): raise VMPathError(f"artifact path is not a regular file: {path}") try: - size, digest = _hash_file(host_path) + size, digest = _hash_file(host_path, self.max_artifact_bytes - total_bytes) except OSError as exc: raise VMPathError(f"artifact path cannot be read: {path}") from exc + total_bytes += size artifacts.append(VMArtifact(relative, vm_path, True, size, digest)) return tuple(artifacts) @@ -778,31 +900,34 @@ async def _execute_request(self, request: VMExecutionRequest) -> VMExecutionRece self._validate_receipt_match(existing, transport_request) if existing.is_terminal: return existing - return await self._resume_or_recover(existing, transport_request) - - started = _now() - running = VMExecutionReceipt( - dispatch_id=request.dispatch_id, - session_id=request.session_id, - idempotency_key=key, - status="running", - command=request.command, - host_workspace=transport_request.host_workspace or str(self.workspace.host_root), - vm_workspace=transport_request.vm_workspace or str(self.workspace.vm_root), - timeout_seconds=request.timeout_seconds, - artifact_paths=request.artifact_paths, - started_at=started, - ) - claim = getattr(self.receipt_store, "put_if_absent", None) - existing_after_claim = ( - claim(running) if callable(claim) else self._put_without_claim(running) - ) - if existing_after_claim is not None: - self._validate_receipt_match(existing_after_claim, transport_request) - if existing_after_claim.is_terminal: - return existing_after_claim - return await self._resume_or_recover(existing_after_claim, transport_request) - return await self._call_and_store(running, transport_request, resume=False) + async with self._admission.slot(): + return await self._resume_or_recover(existing, transport_request) + + async with self._admission.slot(): + started = _now() + running = VMExecutionReceipt( + dispatch_id=request.dispatch_id, + session_id=request.session_id, + idempotency_key=key, + status="running", + command=request.command, + host_workspace=transport_request.host_workspace + or str(self.workspace.host_root), + vm_workspace=transport_request.vm_workspace or str(self.workspace.vm_root), + timeout_seconds=request.timeout_seconds, + artifact_paths=request.artifact_paths, + started_at=started, + ) + claim = getattr(self.receipt_store, "put_if_absent", None) + existing_after_claim = ( + claim(running) if callable(claim) else self._put_without_claim(running) + ) + if existing_after_claim is not None: + self._validate_receipt_match(existing_after_claim, transport_request) + if existing_after_claim.is_terminal: + return existing_after_claim + return await self._resume_or_recover(existing_after_claim, transport_request) + return await self._call_and_store(running, transport_request, resume=False) def _put_without_claim(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: """Keep compatibility with third-party stores predating atomic claims.""" @@ -983,7 +1108,9 @@ def _receipt_from_response( status = "failed" if status in _REMOTE_RUNNING_STATUSES: status = "running" - artifact_paths = _artifact_paths(payload, request.artifact_paths) + artifact_paths = _artifact_paths( + payload, request.artifact_paths, max_paths=self.max_artifact_paths + ) artifacts = self.collect_artifacts(artifact_paths) stdout, stdout_truncated = _truncate_text( _optional_text(payload, "stdout") or _optional_text(payload, "output") or "", @@ -1177,32 +1304,62 @@ def _response_exit_code(values: Mapping[str, Any]) -> int | None: return value -def _artifact_paths(payload: Mapping[str, Any], requested: Iterable[str]) -> tuple[str, ...]: - paths = list(requested) +def _bounded_paths(paths: Iterable[str], limit: int) -> tuple[str, ...]: + if isinstance(paths, (str, bytes)): + raise VMRuntimeError("artifact_paths must be an iterable of text paths") + try: + iterator = iter(paths) + except TypeError as exc: + raise VMRuntimeError("artifact_paths must be an iterable of text paths") from exc + bounded: list[str] = [] + for index, path in enumerate(iterator): + if index >= limit: + raise VMRuntimeError(f"artifact_paths cannot contain more than {limit} paths") + bounded.append(path) + return tuple(bounded) + + +def _artifact_paths( + payload: Mapping[str, Any], requested: Iterable[str], *, max_paths: int +) -> tuple[str, ...]: + paths = list(_bounded_paths(requested, max_paths)) + seen = set(paths) if "artifacts" not in payload or payload["artifacts"] is None: - return tuple(dict.fromkeys(paths)) + return tuple(paths) remote = payload["artifacts"] if not isinstance(remote, Iterable) or isinstance(remote, (str, bytes, Mapping)): raise VMTransportError("VM artifacts must be a list of paths or path objects") - for item in remote: + for index, item in enumerate(remote): + if index >= max_paths or len(paths) >= max_paths: + raise VMTransportError(f"VM artifacts cannot contain more than {max_paths} paths") if isinstance(item, str) and item.strip(): - paths.append(item) + path = item elif isinstance(item, Mapping) and isinstance(item.get("path"), str): if not item["path"].strip(): raise VMTransportError("VM artifact path must be non-empty text") - paths.append(item["path"]) + path = item["path"] else: raise VMTransportError("VM artifacts must contain path strings or path objects") - return tuple(dict.fromkeys(paths)) + if path not in seen: + paths.append(path) + seen.add(path) + return tuple(paths) -def _hash_file(path: Path) -> tuple[int, str]: +def _hash_file(path: Path, max_bytes: int) -> tuple[int, str]: + try: + if path.stat().st_size > max_bytes: + raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") + except OSError as exc: + raise VMPathError(f"artifact path cannot be read: {path}") from exc digest = hashlib.sha256() size = 0 flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) with os.fdopen(os.open(path, flags), "rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): size += len(chunk) + if size > max_bytes: + raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") digest.update(chunk) return size, digest.hexdigest() @@ -1234,6 +1391,7 @@ def _json_value(value: Any) -> Any: "ResumableVMTransport", "CancellableVMTransport", "VMArtifact", + "VMBackpressureError", "VMCommandTransport", "VMExecutionReceipt", "VMExecutionRequest", @@ -1242,6 +1400,7 @@ def _json_value(value: Any) -> Any: "VMPathError", "VMReceiptStore", "VMRuntimeError", + "VMResourceSnapshot", "VMTransport", "VMTransportDisconnected", "VMTransportTimeout", diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index c4adf674e7..902d2987b8 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -17,6 +17,7 @@ JsonVMReceiptStore, MCPVMTransport, MemoryVMReceiptStore, + VMBackpressureError, VMExecutionRequest, VMPathError, VMPersonalAgentRuntime, @@ -998,3 +999,121 @@ async def test_dispatch_object_uses_prompt_and_rejects_unapproved_working_direct "working_directory": str(tmp_path.parent), } ) + + +@pytest.mark.asyncio +async def test_burst_admission_caps_active_work_and_rejects_excess_queue( + tmp_path: Path, +) -> None: + class BlockingCommand: + def __init__(self) -> None: + self.started = asyncio.Event() + self.release = asyncio.Event() + self.active = 0 + self.max_active = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.active += 1 + self.max_active = max(self.max_active, self.active) + self.started.set() + try: + await self.release.wait() + return {"status": "completed", "exit_code": 0} + finally: + self.active -= 1 + + target = BlockingCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_concurrent_executions=1, + max_queue_size=1, + ) + + first = asyncio.create_task( + runtime.execute_command("first", dispatch_id="first", session_id="s") + ) + await target.started.wait() + second = asyncio.create_task( + runtime.execute_command("second", dispatch_id="second", session_id="s") + ) + for _ in range(20): + if runtime.resource_snapshot.queued_executions == 1: + break + await asyncio.sleep(0) + + assert runtime.resource_snapshot.active_executions == 1 + assert runtime.resource_snapshot.queued_executions == 1 + third = runtime.execute_command("third", dispatch_id="third", session_id="s") + with pytest.raises(VMBackpressureError, match="queue is full"): + await third + + target.release.set() + first_result, second_result = await asyncio.gather(first, second) + + assert first_result.status == "completed" + assert second_result.status == "completed" + assert target.max_active == 1 + assert runtime.resource_snapshot.active_executions == 0 + assert runtime.resource_snapshot.queued_executions == 0 + + +@pytest.mark.asyncio +async def test_burst_resource_snapshot_never_exceeds_concurrency_ceiling(tmp_path: Path) -> None: + class YieldingCommand: + def __init__(self) -> None: + self.active = 0 + self.max_active = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.active += 1 + self.max_active = max(self.max_active, self.active) + try: + await asyncio.sleep(0) + return {"status": "completed", "exit_code": 0} + finally: + self.active -= 1 + + target = YieldingCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_concurrent_executions=3, + max_queue_size=64, + ) + + receipts = await asyncio.gather( + *( + runtime.execute_command("burst", dispatch_id=f"burst-{index}", session_id="s") + for index in range(32) + ) + ) + + assert {receipt.status for receipt in receipts} == {"completed"} + assert target.max_active <= 3 + assert runtime.resource_snapshot.max_concurrent_executions == 3 + assert runtime.resource_snapshot.active_executions == 0 + assert runtime.resource_snapshot.queued_executions == 0 + + +def test_artifact_collection_enforces_byte_and_count_ceilings(tmp_path: Path) -> None: + artifact = tmp_path / "large.bin" + artifact.write_bytes(b"0123456789") + runtime = VMPersonalAgentRuntime( + RecordingCommand(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_artifact_bytes=4, + max_artifact_paths=1, + ) + + with pytest.raises(VMPathError, match="resource ceiling"): + runtime.collect_artifacts(["large.bin"]) + with pytest.raises(VMRuntimeError, match="more than 1 paths"): + asyncio.run( + runtime.execute_command( + "verify", + dispatch_id="too-many-artifacts", + session_id="s", + artifact_paths=("one", "two"), + ) + ) From 8ff212ed30a53d3b7710464c2febdf5de029152d Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 10:37:01 +0900 Subject: [PATCH 16/41] test(task1-grok-vm-runtime): complete verification & hardening round 9 (security-and-boundary-audit) --- STATUS.md | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 STATUS.md diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index 82e7b92850..0000000000 --- a/STATUS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Ouroboros Grokbot and VM Personal-Agent Runtime - -## 🗺️ 단계 / 로드맵 -- [x] 1단계: VM personal-agent host/runtime adapter baseline -- [x] 2단계: Round 6 durable receipts, disconnect recovery, and focused verification -- [ ] 👉 3단계: Round 7 p99 latency, backpressure, and resource-ceiling audit -- [ ] 4단계: Final gates, evidence, Draft PR update, and remote check inspection - -## 🛑 블로커 -- 블로커: 없음 - -## 🤖 AI 실행 맥락 -- 마지막 커밋: b648436a / feat/personal-agent-vm-runtime-20261130 -- 지금 손댄 파일: Round 7 runtime, tests, and verification evidence -- 다음 할 일: Run the focused suites, identify concrete bottlenecks, and implement verified fixes From 90d6a321a2a96f4c654b13736b52f28def6de55d Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 11:11:56 +0900 Subject: [PATCH 17/41] test(task1-grok-vm-runtime): complete verification & hardening round 13 (ci-gate-and-regression-fortress) --- .../integrations/personal_agent_host.py | 29 +++- .../integrations/vm_agent_runtime.py | 151 +++++++++++++----- 2 files changed, 132 insertions(+), 48 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index db92abba8b..eb74368970 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -454,14 +454,22 @@ def normalize_tool_response(tool_name: str, value: Any) -> HostToolResponse: structured = getattr(value, "structured_content", None) if structured is None: structured = getattr(value, "structuredContent", None) - is_error = bool(getattr(value, "is_error", getattr(value, "isError", False))) + is_error = _wire_bool( + getattr(value, "is_error", getattr(value, "isError", False)), + key="is_error", + tool_name=tool_name, + ) content = getattr(value, "content", None) raw_mapping = _model_mapping(value) if raw_mapping is not None: meta = _model_mapping(raw_mapping.get("meta")) or meta if structured is None: structured = raw_mapping.get("structuredContent", raw_mapping.get("structured_content")) - is_error = bool(raw_mapping.get("isError", raw_mapping.get("is_error", is_error))) + is_error = _wire_bool( + raw_mapping.get("isError", raw_mapping.get("is_error", is_error)), + key="is_error", + tool_name=tool_name, + ) content = raw_mapping.get("content", content) envelope_keys = { "content", @@ -1004,6 +1012,11 @@ def _pending_dispatches(value: Any, tool_name: str) -> tuple[PendingHostDispatch if worker is None: raise HostAdapterError("pending host worker must be an object", tool_name=tool_name) context = _model_mapping(worker.get("context")) or {} + working_directory = context.get("working_directory") + if working_directory is not None and not isinstance(working_directory, str): + raise HostAdapterError( + "host dispatch working_directory must be text", tool_name=tool_name + ) parsed.append( PendingHostDispatch( dispatch_id=_required_text(raw, "dispatch_id", tool_name), @@ -1012,11 +1025,7 @@ def _pending_dispatches(value: Any, tool_name: str) -> tuple[PendingHostDispatch result_correlation_key=_required_text(raw, "result_correlation_key", tool_name), submit_tool=_required_text(raw, "submit_tool", tool_name), prompt=_required_text(worker, "prompt", tool_name), - working_directory=( - str(context["working_directory"]) - if context.get("working_directory") is not None - else None - ), + working_directory=working_directory, actionable=raw.get("actionable") is True, raw=raw, ) @@ -1210,6 +1219,12 @@ def _strict_bool(value: Any, key: str) -> bool: return value +def _wire_bool(value: Any, *, key: str, tool_name: str) -> bool: + if not isinstance(value, bool): + raise HostAdapterError(f"{key} must be a boolean", tool_name=tool_name) + return value + + def _non_negative_cursor(value: Any, *, default: int = 0) -> int: if value is None: return default diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index b799134558..b605687186 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -190,7 +190,7 @@ def map_vm_path(self, path: str) -> Path: relative = candidate.relative_to(self.vm_root) except ValueError as exc: raise VMPathError(f"VM path escapes approved workspace: {path}") from exc - resolved = (self.host_root / Path(*relative.parts)).resolve(strict=False) + resolved = (self.host_root / Path(*relative.parts)).resolve() try: resolved.relative_to(self.host_root) except ValueError as exc: @@ -404,49 +404,67 @@ def to_dict(self) -> dict[str, Any]: def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: artifacts: list[VMArtifact] = [] raw_artifacts = value.get("artifacts", ()) - if isinstance(raw_artifacts, Iterable) and not isinstance(raw_artifacts, (str, bytes)): - for item in raw_artifacts: - if isinstance(item, Mapping): - artifacts.append( - VMArtifact( - relative_path=str(item.get("relative_path", "")), - vm_path=str(item.get("vm_path", "")), - exists=bool(item.get("exists", False)), - size=int(item.get("size", 0)), - sha256=( - str(item["sha256"]) if item.get("sha256") is not None else None - ), - ) - ) + if raw_artifacts is None: + raw_artifacts = () + if not isinstance(raw_artifacts, (list, tuple)): + raise ValueError("artifacts must be a list") + for item in raw_artifacts: + if not isinstance(item, Mapping): + raise ValueError("artifact entries must be objects") + artifacts.append( + VMArtifact( + relative_path=_receipt_text(item.get("relative_path"), "relative_path"), + vm_path=_receipt_text(item.get("vm_path"), "vm_path"), + exists=_receipt_bool(item.get("exists"), "exists", default=False), + size=_receipt_int(item.get("size"), "size", default=0, minimum=0), + sha256=_receipt_optional_text(item.get("sha256"), "sha256"), + ) + ) raw_artifact_paths = value.get("artifact_paths", ()) - artifact_paths = ( - tuple(item for item in raw_artifact_paths if isinstance(item, str)) - if isinstance(raw_artifact_paths, Iterable) - and not isinstance(raw_artifact_paths, (str, bytes)) - else () + if raw_artifact_paths is None: + raw_artifact_paths = () + if not isinstance(raw_artifact_paths, (list, tuple)): + raise ValueError("artifact_paths must be a list") + artifact_paths = tuple( + _receipt_text(item, "artifact_paths entry") for item in raw_artifact_paths ) + raw_payload = value.get("raw", {}) + if not isinstance(raw_payload, Mapping): + raise ValueError("raw receipt payload must be an object") return cls( - dispatch_id=str(value["dispatch_id"]), - session_id=str(value["session_id"]), - idempotency_key=str(value["idempotency_key"]), - status=str(value["status"]), - command=str(value.get("command", "")), - host_workspace=str(value.get("host_workspace", "")), - vm_workspace=str(value.get("vm_workspace", "")), - timeout_seconds=float(value.get("timeout_seconds", 300.0)), - execution_id=(str(value["execution_id"]) if value.get("execution_id") else None), - exit_code=(int(value["exit_code"]) if value.get("exit_code") is not None else None), - stdout=str(value.get("stdout", "")), - stdout_truncated=bool(value.get("stdout_truncated", False)), - stderr=str(value.get("stderr", "")), - stderr_truncated=bool(value.get("stderr_truncated", False)), + dispatch_id=_receipt_text(value.get("dispatch_id"), "dispatch_id"), + session_id=_receipt_text(value.get("session_id"), "session_id"), + idempotency_key=_receipt_text(value.get("idempotency_key"), "idempotency_key"), + status=_receipt_text(value.get("status"), "status"), + command=_receipt_text(value.get("command", ""), "command", allow_empty=True), + host_workspace=_receipt_text( + value.get("host_workspace", ""), "host_workspace", allow_empty=True + ), + vm_workspace=_receipt_text( + value.get("vm_workspace", ""), "vm_workspace", allow_empty=True + ), + timeout_seconds=_receipt_float( + value.get("timeout_seconds", 300.0), "timeout_seconds" + ), + execution_id=_receipt_optional_text(value.get("execution_id"), "execution_id"), + exit_code=_receipt_optional_int(value.get("exit_code"), "exit_code"), + stdout=_receipt_text(value.get("stdout", ""), "stdout", allow_empty=True), + stdout_truncated=_receipt_bool( + value.get("stdout_truncated"), "stdout_truncated", default=False + ), + stderr=_receipt_text(value.get("stderr", ""), "stderr", allow_empty=True), + stderr_truncated=_receipt_bool( + value.get("stderr_truncated"), "stderr_truncated", default=False + ), artifacts=tuple(artifacts), artifact_paths=artifact_paths, - error=(str(value["error"]) if value.get("error") is not None else None), - recovery_required=bool(value.get("recovery_required", False)), - started_at=str(value.get("started_at", "")), - finished_at=(str(value["finished_at"]) if value.get("finished_at") else None), - raw=_mapping(value.get("raw")), + error=_receipt_optional_text(value.get("error"), "error"), + recovery_required=_receipt_bool( + value.get("recovery_required"), "recovery_required", default=False + ), + started_at=_receipt_text(value.get("started_at", ""), "started_at", allow_empty=True), + finished_at=_receipt_optional_text(value.get("finished_at"), "finished_at"), + raw=dict(raw_payload), ) @@ -1170,6 +1188,53 @@ def _mapping(value: Any) -> Mapping[str, Any]: return {} +def _receipt_text(value: Any, key: str, *, allow_empty: bool = False) -> str: + if not isinstance(value, str) or (not allow_empty and not value.strip()): + raise ValueError(f"receipt {key} must be text") + return value + + +def _receipt_optional_text(value: Any, key: str) -> str | None: + if value is None: + return None + if not isinstance(value, str): + raise ValueError(f"receipt {key} must be text or null") + return value.strip() or None + + +def _receipt_bool(value: Any, key: str, *, default: bool) -> bool: + if value is None: + return default + if not isinstance(value, bool): + raise ValueError(f"receipt {key} must be boolean") + return value + + +def _receipt_int(value: Any, key: str, *, default: int, minimum: int) -> int: + if value is None: + return default + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise ValueError(f"receipt {key} must be an integer >= {minimum}") + return value + + +def _receipt_optional_int(value: Any, key: str) -> int | None: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"receipt {key} must be an integer or null") + return value + + +def _receipt_float(value: Any, key: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"receipt {key} must be finite") + number = float(value) + if not math.isfinite(number) or number <= 0: + raise ValueError(f"receipt {key} must be positive and finite") + return number + + def _unwrap_result(value: Any) -> Any: """Unwrap Ouroboros's ``Result`` without importing the core type.""" if hasattr(value, "is_err"): @@ -1290,8 +1355,12 @@ def _required_text(values: Mapping[str, Any], key: str) -> str: def _optional_text(values: Mapping[str, Any], key: str) -> str | None: - value = values.get(key) - return value.strip() if isinstance(value, str) and value.strip() else None + if key not in values or values[key] is None: + return None + value = values[key] + if not isinstance(value, str): + raise VMTransportError(f"VM {key} must be text or null") + return value.strip() or None def _response_exit_code(values: Mapping[str, Any]) -> int | None: From 5c057263cf33390ef03af2672b6841a5ad87b8ab Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 11:38:37 +0900 Subject: [PATCH 18/41] test(task1-grok-vm-runtime): complete verification & hardening round 15 (performance-p99-hardening) --- STATUS.md | 15 ++++ .../integrations/vm_agent_runtime.py | 78 +++++++++++++++-- .../test_vm_agent_runtime_round15.py | 86 +++++++++++++++++++ 3 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 STATUS.md create mode 100644 tests/unit/integrations/test_vm_agent_runtime_round15.py diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 0000000000..c37d2e596e --- /dev/null +++ b/STATUS.md @@ -0,0 +1,15 @@ +# Ouroboros — Grokbot & VM Personal-Agent Runtime Adapter + +## 🗺️ 단계 / 로드맵 +- [x] 1단계: VM personal-agent host/runtime baseline +- [x] 2단계: security, recovery, and CI hardening rounds +- [ ] 👉 3단계: Round 15 P99 tail latency, backpressure, and resource-ceiling verification (현재 위치) +- [ ] 4단계: draft PR review handoff + +## 🛑 블로커 +- 블로커: 없음 + +## 🤖 AI 실행 맥락 +- 마지막 커밋: 90d6a321 +- 지금 손댄 파일: audit evidence and integration runtime tests +- 다음 할 일: adversarial audit, targeted fixes, gate verification, and draft PR update diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index b605687186..7cdd8b6e23 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -305,7 +305,9 @@ def __post_init__(self) -> None: self.artifact_paths, Iterable ): raise VMRuntimeError("artifact_paths must be an iterable of text paths") - for path in self.artifact_paths: + materialized_paths = tuple(self.artifact_paths) + object.__setattr__(self, "artifact_paths", materialized_paths) + for path in materialized_paths: if not isinstance(path, str) or not path.strip(): raise VMRuntimeError("artifact_paths must contain non-empty text paths") if "\x00" in path: @@ -443,9 +445,7 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: vm_workspace=_receipt_text( value.get("vm_workspace", ""), "vm_workspace", allow_empty=True ), - timeout_seconds=_receipt_float( - value.get("timeout_seconds", 300.0), "timeout_seconds" - ), + timeout_seconds=_receipt_float(value.get("timeout_seconds", 300.0), "timeout_seconds"), execution_id=_receipt_optional_text(value.get("execution_id"), "execution_id"), exit_code=_receipt_optional_int(value.get("exit_code"), "exit_code"), stdout=_receipt_text(value.get("stdout", ""), "stdout", allow_empty=True), @@ -521,6 +521,10 @@ class JsonVMReceiptStore: def __init__(self, directory: str | Path) -> None: self.directory = Path(directory).expanduser().resolve() self.directory.mkdir(parents=True, exist_ok=True) + self._find_index_by_dispatch: dict[str, set[str]] | None = None + self._find_index_by_pair: dict[tuple[str, str], set[str]] | None = None + self._find_index_paths: dict[str, tuple[str, str]] | None = None + self._find_index_mtime_ns: int | None = None def _path(self, key: str) -> Path: digest = hashlib.sha256(key.encode("utf-8")).hexdigest() @@ -544,6 +548,7 @@ def put(self, receipt: VMExecutionReceipt) -> None: handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) + self._index_put(receipt, path.name) finally: if os.path.exists(temporary): os.unlink(temporary) @@ -561,14 +566,24 @@ def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | Non os.link(temporary, path) except FileExistsError: return self.get(receipt.idempotency_key) + self._index_put(receipt, path.name) return None finally: if os.path.exists(temporary): os.unlink(temporary) def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: + self._ensure_find_index() + assert self._find_index_by_dispatch is not None + assert self._find_index_by_pair is not None + path_names = ( + self._find_index_by_pair.get((dispatch_id, session_id), set()) + if session_id is not None + else self._find_index_by_dispatch.get(dispatch_id, set()) + ) matches: list[VMExecutionReceipt] = [] - for path in self.directory.glob("*.json"): + for path_name in path_names: + path = self.directory / path_name try: receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: @@ -581,6 +596,53 @@ def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionRe raise VMRuntimeError(f"ambiguous VM receipt for dispatch {dispatch_id!r}") return matches[0] if matches else None + def _ensure_find_index(self) -> None: + current_mtime_ns = self._directory_mtime_ns() + if self._find_index_by_dispatch is None or self._find_index_mtime_ns != current_mtime_ns: + self._build_find_index(current_mtime_ns) + + def _build_find_index(self, directory_mtime_ns: int) -> None: + by_dispatch: dict[str, set[str]] = {} + by_pair: dict[tuple[str, str], set[str]] = {} + paths: dict[str, tuple[str, str]] = {} + for path in self.directory.glob("*.json"): + try: + receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise VMRuntimeError(f"corrupt VM receipt file {path.name!r}") from exc + identity = (receipt.dispatch_id, receipt.session_id) + by_dispatch.setdefault(receipt.dispatch_id, set()).add(path.name) + by_pair.setdefault(identity, set()).add(path.name) + paths[path.name] = identity + self._find_index_by_dispatch = by_dispatch + self._find_index_by_pair = by_pair + self._find_index_paths = paths + self._find_index_mtime_ns = directory_mtime_ns + + def _index_put(self, receipt: VMExecutionReceipt, path_name: str) -> None: + """Update a warm lookup index without rescanning unrelated receipts.""" + if ( + self._find_index_by_dispatch is None + or self._find_index_by_pair is None + or self._find_index_paths is None + ): + return + old_identity = self._find_index_paths.pop(path_name, None) + if old_identity is not None: + self._find_index_by_dispatch[old_identity[0]].discard(path_name) + self._find_index_by_pair[old_identity].discard(path_name) + identity = (receipt.dispatch_id, receipt.session_id) + self._find_index_paths[path_name] = identity + self._find_index_by_dispatch.setdefault(receipt.dispatch_id, set()).add(path_name) + self._find_index_by_pair.setdefault(identity, set()).add(path_name) + self._find_index_mtime_ns = self._directory_mtime_ns() + + def _directory_mtime_ns(self) -> int: + try: + return self.directory.stat().st_mtime_ns + except OSError as exc: + raise VMRuntimeError("VM receipt directory cannot be inspected") from exc + class VMTransport(Protocol): """Transport-neutral command/turn execution surface.""" @@ -1391,8 +1453,12 @@ def _bounded_paths(paths: Iterable[str], limit: int) -> tuple[str, ...]: def _artifact_paths( payload: Mapping[str, Any], requested: Iterable[str], *, max_paths: int ) -> tuple[str, ...]: - paths = list(_bounded_paths(requested, max_paths)) + paths: list[str] = [] seen = set(paths) + for path in _bounded_paths(requested, max_paths): + if path not in seen: + paths.append(path) + seen.add(path) if "artifacts" not in payload or payload["artifacts"] is None: return tuple(paths) remote = payload["artifacts"] diff --git a/tests/unit/integrations/test_vm_agent_runtime_round15.py b/tests/unit/integrations/test_vm_agent_runtime_round15.py new file mode 100644 index 0000000000..d0b282a101 --- /dev/null +++ b/tests/unit/integrations/test_vm_agent_runtime_round15.py @@ -0,0 +1,86 @@ +"""Round 15 regression and bounded-latency coverage for the VM runtime.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +from ouroboros.integrations import ( + CommandVMTransport, + JsonVMReceiptStore, + VMExecutionRequest, + VMPersonalAgentRuntime, + VMWorkspaceMapper, +) + + +class CompletedCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0} + + +def test_vm_request_materializes_one_shot_artifact_iterables() -> None: + request = VMExecutionRequest( + dispatch_id="dispatch", + session_id="session", + command="verify", + artifact_paths=iter(("result.json",)), + ) + + assert request.artifact_paths == ("result.json",) + + +def test_duplicate_artifacts_are_hashed_once_and_recorded_once(tmp_path: Path) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + runtime = VMPersonalAgentRuntime( + CommandVMTransport(CompletedCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = asyncio.run( + runtime.execute_command( + "verify", + dispatch_id="duplicate-artifact", + session_id="session", + artifact_paths=("result.json", "result.json"), + ) + ) + + assert receipt.artifact_paths == ("result.json",) + assert len(receipt.artifacts) == 1 + + +class CountingReceiptStore(JsonVMReceiptStore): + def __init__(self, directory: Path) -> None: + self.index_builds = 0 + super().__init__(directory) + + def _build_find_index(self, directory_mtime_ns: int) -> None: + self.index_builds += 1 + super()._build_find_index(directory_mtime_ns) + + +def test_json_receipt_find_warms_a_bounded_lookup_index(tmp_path: Path) -> None: + store = CountingReceiptStore(tmp_path / "receipts") + runtime = VMPersonalAgentRuntime( + CommandVMTransport(CompletedCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=store, + ) + + async def populate() -> None: + for index in range(48): + await runtime.execute_command( + "verify", + dispatch_id=f"dispatch-{index}", + session_id="session", + ) + + asyncio.run(populate()) + assert store.find("dispatch-47", "session") is not None + for _ in range(100): + assert store.find("dispatch-47", "session") is not None + + assert store.index_builds == 1 From 49ec7a691ef93a4337b99bc22f2a75a2e731355d Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 12:11:09 +0900 Subject: [PATCH 19/41] test(task1-grok-vm-runtime): complete verification & hardening round 17 (security-and-boundary-audit) --- STATUS.md | 15 --- .../integrations/personal_agent_host.py | 4 + .../integrations/vm_agent_runtime.py | 76 ++++++++++- .../test_vm_agent_runtime_round17.py | 121 ++++++++++++++++++ 4 files changed, 199 insertions(+), 17 deletions(-) delete mode 100644 STATUS.md create mode 100644 tests/unit/integrations/test_vm_agent_runtime_round17.py diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index c37d2e596e..0000000000 --- a/STATUS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Ouroboros — Grokbot & VM Personal-Agent Runtime Adapter - -## 🗺️ 단계 / 로드맵 -- [x] 1단계: VM personal-agent host/runtime baseline -- [x] 2단계: security, recovery, and CI hardening rounds -- [ ] 👉 3단계: Round 15 P99 tail latency, backpressure, and resource-ceiling verification (현재 위치) -- [ ] 4단계: draft PR review handoff - -## 🛑 블로커 -- 블로커: 없음 - -## 🤖 AI 실행 맥락 -- 마지막 커밋: 90d6a321 -- 지금 손댄 파일: audit evidence and integration runtime tests -- 다음 할 일: adversarial audit, targeted fixes, gate verification, and draft PR update diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index eb74368970..c3f79b1072 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -559,6 +559,8 @@ def _start_key( def _normalized_session_id(value: str | None) -> str | None: if value is None: return None + if not isinstance(value, str): + raise HostAdapterError("host_session_id must be a string") normalized = value.strip() return normalized or None @@ -720,6 +722,8 @@ async def start( arguments = {"goal": invocation.goal} normalized_cwd: str | None = None if cwd is not None: + if not isinstance(cwd, str): + raise HostAdapterError("cwd must be a string") normalized_cwd = cwd.strip() if not normalized_cwd: raise HostAdapterError("cwd must not be empty") diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 7cdd8b6e23..55eab26806 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -21,6 +21,7 @@ import math import os from pathlib import Path, PurePosixPath +import stat import tempfile from typing import Any, Protocol @@ -926,6 +927,10 @@ async def resume_dispatch( session_id: str | None = None, ) -> VMExecutionReceipt: """Resume a persisted operation without replaying its original command.""" + if not isinstance(dispatch_id, str) or not dispatch_id.strip(): + raise VMRuntimeError("dispatch_id must be non-empty text") + if not isinstance(session_id, str) or not session_id.strip(): + raise VMRuntimeError("session_id is required to resume a VM dispatch") receipt = self.receipt_store.find(dispatch_id, session_id) if receipt is None: raise VMRuntimeError(f"no persisted VM receipt for dispatch {dispatch_id}") @@ -964,7 +969,11 @@ def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: if not host_path.is_file(): raise VMPathError(f"artifact path is not a regular file: {path}") try: - size, digest = _hash_file(host_path, self.max_artifact_bytes - total_bytes) + size, digest = _hash_file( + host_path, + self.max_artifact_bytes - total_bytes, + workspace_root=self.workspace.host_root, + ) except OSError as exc: raise VMPathError(f"artifact path cannot be read: {path}") from exc total_bytes += size @@ -1481,7 +1490,15 @@ def _artifact_paths( return tuple(paths) -def _hash_file(path: Path, max_bytes: int) -> tuple[int, str]: +def _hash_file( + path: Path, + max_bytes: int, + *, + workspace_root: Path | None = None, +) -> tuple[int, str]: + """Hash a file without reopening a parent symlink outside the workspace.""" + if workspace_root is not None and os.open in os.supports_dir_fd: + return _hash_file_beneath(path, workspace_root, max_bytes) try: if path.stat().st_size > max_bytes: raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") @@ -1499,6 +1516,61 @@ def _hash_file(path: Path, max_bytes: int) -> tuple[int, str]: return size, digest.hexdigest() +def _hash_file_beneath(path: Path, workspace_root: Path, max_bytes: int) -> tuple[int, str]: + """Open every workspace component with ``O_NOFOLLOW`` where supported.""" + try: + relative = path.relative_to(workspace_root) + except ValueError as exc: + raise VMPathError(f"artifact path escapes approved workspace: {path}") from exc + if not relative.parts: + raise VMPathError(f"artifact path is not a regular file: {path}") + + nofollow = getattr(os, "O_NOFOLLOW", 0) + directory = getattr(os, "O_DIRECTORY", 0) + root_fd = os.open(workspace_root, os.O_RDONLY | directory | nofollow) + parent_fd = root_fd + opened_parents: list[int] = [] + try: + for component in relative.parts[:-1]: + next_fd = os.open( + component, + os.O_RDONLY | directory | nofollow, + dir_fd=parent_fd, + ) + opened_parents.append(next_fd) + parent_fd = next_fd + file_fd = os.open( + relative.parts[-1], + os.O_RDONLY | nofollow, + dir_fd=parent_fd, + ) + try: + file_stat = os.fstat(file_fd) + if not stat.S_ISREG(file_stat.st_mode): + raise VMPathError(f"artifact path is not a regular file: {path}") + if file_stat.st_size > max_bytes: + raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") + digest = hashlib.sha256() + size = 0 + with os.fdopen(file_fd, "rb") as handle: + file_fd = -1 + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + size += len(chunk) + if size > max_bytes: + raise VMPathError( + f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}" + ) + digest.update(chunk) + return size, digest.hexdigest() + finally: + if file_fd >= 0: + os.close(file_fd) + finally: + for parent in reversed(opened_parents): + os.close(parent) + os.close(root_fd) + + def _truncate_text(value: str, limit: int, *, label: str = "stdout") -> tuple[str, bool]: if len(value) <= limit: return value, False diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py new file mode 100644 index 0000000000..f824af9e73 --- /dev/null +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -0,0 +1,121 @@ +"""Round 17 adversarial tests for VM isolation and fault recovery.""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Any + +import pytest + +from ouroboros.integrations.personal_agent_host import ( + HostAdapterError, + PersonalAgentHostAdapter, + parse_explicit_invocation, +) +from ouroboros.integrations.vm_agent_runtime import ( + VMPersonalAgentRuntime, + VMRuntimeError, + VMTransportDisconnected, + VMWorkspaceMapper, + _hash_file, +) + + +def test_artifact_hash_rejects_a_parent_symlink_after_path_resolution( + tmp_path: Path, +) -> None: + """A resolved path must not be reopened through a swapped parent symlink.""" + if os.open not in os.supports_dir_fd or not hasattr(os, "O_NOFOLLOW"): + pytest.skip("directory-relative no-follow opens are unavailable") + + workspace = tmp_path / "workspace" + workspace.mkdir() + parent = workspace / "nested" + parent.mkdir() + target = parent / "result.txt" + target.write_text("inside", encoding="utf-8") + resolved_target = target.resolve() + + outside = tmp_path / "outside" + outside.mkdir() + (outside / "result.txt").write_text("outside", encoding="utf-8") + parent.rename(tmp_path / "original-nested") + parent.symlink_to(outside, target_is_directory=True) + + with pytest.raises(OSError): + _hash_file(resolved_target, 1024, workspace_root=workspace) + + +@pytest.mark.asyncio +async def test_resume_requires_a_session_binding_for_tenant_isolation(tmp_path: Path) -> None: + class Disconnected: + resume_calls = 0 + + async def execute(self, _request: Any) -> Any: + raise VMTransportDisconnected("connection dropped", execution_id="remote-17") + + async def resume(self, _request: Any, _execution_id: str) -> Any: + self.resume_calls += 1 + return {"status": "completed", "exit_code": 0} + + transport = Disconnected() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + disconnected = await runtime.execute_command( + "verify", dispatch_id="shared", session_id="tenant-a" + ) + assert disconnected.status == "disconnected" + + with pytest.raises(VMRuntimeError, match="session_id is required"): + await runtime.resume_dispatch("shared") # type: ignore[call-arg] + assert transport.resume_calls == 0 + + +@pytest.mark.asyncio +async def test_disconnect_without_execution_id_is_never_replayed(tmp_path: Path) -> None: + class LostConnection: + execute_calls = 0 + resume_calls = 0 + + async def execute(self, _request: Any) -> Any: + self.execute_calls += 1 + raise VMTransportDisconnected("connection dropped before acceptance") + + async def resume(self, _request: Any, _execution_id: str) -> Any: + self.resume_calls += 1 + return {"status": "completed", "exit_code": 0} + + transport = LostConnection() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + first = await runtime.execute_command("verify", dispatch_id="lost", session_id="tenant-a") + second = await runtime.execute_command("verify", dispatch_id="lost", session_id="tenant-a") + + assert first.status == "disconnected" + assert first.recovery_required is True + assert second.status == "recovery_required" + assert transport.execute_calls == 1 + assert transport.resume_calls == 0 + + +def test_host_rejects_non_string_session_identity() -> None: + with pytest.raises(HostAdapterError, match="host_session_id must be a string"): + parse_explicit_invocation("/ouroboros verify", host_session_id=object()) # type: ignore[arg-type] + + +@pytest.mark.asyncio +async def test_host_rejects_non_string_cwd_before_transport_call() -> None: + calls: list[str] = [] + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + calls.append(name) + return {"meta": {"job_id": "job", "auto_session_id": "session", "runtime_backend": "host"}} + + with pytest.raises(HostAdapterError, match="cwd must be a string"): + await PersonalAgentHostAdapter(call_tool).start("/ouroboros verify", cwd=Path("/workspace")) # type: ignore[arg-type] + assert calls == [] From 5e8bc27378c49c30ad393c8268a581397b5c6052 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 12:16:54 +0900 Subject: [PATCH 20/41] test(task1-grok-vm-runtime): complete verification & hardening round 18 (empirical-scale-and-latency) --- STATUS.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 STATUS.md diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 0000000000..0fe7dda596 --- /dev/null +++ b/STATUS.md @@ -0,0 +1,15 @@ +# Ouroboros + +## 🗺️ 단계 / 로드맵 +- [x] 1단계: VM Personal-Agent host/runtime adapter baseline +- [ ] 👉 2단계: Round 18 empirical concurrency, leak, and latency verification (현재 위치) +- [ ] 3단계: Draft PR maintainer review readiness +- [ ] 4단계: Upstream merge and release follow-up + +## 🛑 블로커 +- 블로커: 없음 + +## 🤖 AI 실행 맥락 +- 마지막 커밋: feat/personal-agent-vm-runtime-20261130 +- 지금 손댄 파일: STATUS.md (temporary task tracker) +- 다음 할 일: Audit the complete diff, reproduce weaknesses, and run the required gates. From 41d4b135e694ec7da6df0fdca2596a740f822cee Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 12:56:26 +0900 Subject: [PATCH 21/41] test(task1-grok-vm-runtime): complete verification & hardening round 24 (final-maintainer-readiness-pass) --- STATUS.md | 15 -- src/ouroboros/integrations/__init__.py | 2 + .../integrations/personal_agent_host.py | 183 ++++++++++++++++-- .../integrations/test_personal_agent_host.py | 44 +++++ 4 files changed, 216 insertions(+), 28 deletions(-) delete mode 100644 STATUS.md diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index 0fe7dda596..0000000000 --- a/STATUS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Ouroboros - -## 🗺️ 단계 / 로드맵 -- [x] 1단계: VM Personal-Agent host/runtime adapter baseline -- [ ] 👉 2단계: Round 18 empirical concurrency, leak, and latency verification (현재 위치) -- [ ] 3단계: Draft PR maintainer review readiness -- [ ] 4단계: Upstream merge and release follow-up - -## 🛑 블로커 -- 블로커: 없음 - -## 🤖 AI 실행 맥락 -- 마지막 커밋: feat/personal-agent-vm-runtime-20261130 -- 지금 손댄 파일: STATUS.md (temporary task tracker) -- 다음 할 일: Audit the complete diff, reproduce weaknesses, and run the required gates. diff --git a/src/ouroboros/integrations/__init__.py b/src/ouroboros/integrations/__init__.py index 53577c21b9..3957d57e93 100644 --- a/src/ouroboros/integrations/__init__.py +++ b/src/ouroboros/integrations/__init__.py @@ -15,6 +15,7 @@ HostExecutionReceipt, HostInvocation, HostReceiptStore, + HostStartReservation, HostSubmissionError, HostToolResponse, HostToolTransport, @@ -63,6 +64,7 @@ "HostExecutionReceipt", "HostReceiptStore", "HostInvocation", + "HostStartReservation", "HostSubmissionError", "HostToolResponse", "HostToolTransport", diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index c3f79b1072..3ac662d0f6 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -14,8 +14,10 @@ from __future__ import annotations +import asyncio from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace +from datetime import UTC, datetime import hashlib import json import os @@ -73,6 +75,8 @@ _HOST_TERMINAL_STATUSES = frozenset( {"completed", "complete", "failed", "cancelled", "canceled", "interrupted"} ) +_START_RESERVATION_WAIT_SECONDS = 5.0 +_START_RESERVATION_POLL_SECONDS = 0.01 class HostToolTransport(Protocol): @@ -297,6 +301,15 @@ def from_dict(cls, value: Mapping[str, Any]) -> HostExecutionReceipt: return _host_receipt_from_dict(cls, value) +@dataclass(frozen=True, slots=True) +class HostStartReservation: + """Durable ownership of a start key before the external start call.""" + + key: str + arguments: Mapping[str, Any] + created_at: str + + class HostReceiptStore(Protocol): """Persistence seam for explicit host starts across adapter restarts.""" @@ -309,15 +322,24 @@ def put(self, key: str, receipt: HostExecutionReceipt) -> None: def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: """Atomically persist a first receipt for a key.""" + def reserve_start( + self, key: str, arguments: Mapping[str, Any] + ) -> tuple[bool, HostStartReservation | HostExecutionReceipt]: + """Reserve a start key before its external side effect.""" + + def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Publish the receipt for a previously reserved start key.""" + class MemoryHostReceiptStore: """Small in-memory store for hosts that do not need process restart recovery.""" def __init__(self) -> None: - self._receipts: dict[str, HostExecutionReceipt] = {} + self._receipts: dict[str, HostExecutionReceipt | HostStartReservation] = {} def get(self, key: str) -> HostExecutionReceipt | None: - return self._receipts.get(key) + value = self._receipts.get(key) + return value if isinstance(value, HostExecutionReceipt) else None def put(self, key: str, receipt: HostExecutionReceipt) -> None: self._receipts[key] = receipt @@ -325,10 +347,27 @@ def put(self, key: str, receipt: HostExecutionReceipt) -> None: def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: existing = self._receipts.get(key) if existing is not None: - return existing + return existing if isinstance(existing, HostExecutionReceipt) else None self._receipts[key] = receipt return None + def reserve_start( + self, key: str, arguments: Mapping[str, Any] + ) -> tuple[bool, HostStartReservation | HostExecutionReceipt]: + existing = self._receipts.get(key) + if existing is not None: + return False, existing + reservation = HostStartReservation(key, dict(arguments), _now()) + self._receipts[key] = reservation + return True, reservation + + def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + existing = self._receipts.get(key) + if isinstance(existing, HostExecutionReceipt): + return existing + self._receipts[key] = receipt + return receipt + class JsonHostReceiptStore: """Atomic JSON store for host receipts that must survive process restarts.""" @@ -342,16 +381,8 @@ def _path(self, key: str) -> Path: return self.directory / f"{digest}.json" def get(self, key: str) -> HostExecutionReceipt | None: - path = self._path(key) - try: - raw = json.loads(path.read_text(encoding="utf-8")) - except FileNotFoundError: - return None - except (OSError, TypeError, ValueError, json.JSONDecodeError) as exc: - raise HostAdapterError(f"corrupt host receipt for {key!r}") from exc - if not isinstance(raw, Mapping): - raise HostAdapterError(f"corrupt host receipt for {key!r}") - return HostExecutionReceipt.from_dict(raw) + record = self._read_record(key) + return record if isinstance(record, HostExecutionReceipt) else None def put(self, key: str, receipt: HostExecutionReceipt) -> None: path = self._path(key) @@ -383,6 +414,70 @@ def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutio if os.path.exists(temporary): os.unlink(temporary) + def reserve_start( + self, key: str, arguments: Mapping[str, Any] + ) -> tuple[bool, HostStartReservation | HostExecutionReceipt]: + """Atomically reserve a key before the start tool can create a job.""" + path = self._path(key) + reservation = HostStartReservation(key, dict(arguments), _now()) + fd, temporary = tempfile.mkstemp( + prefix=".host-reservation-", suffix=".tmp", dir=self.directory + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump( + { + "kind": "start_reservation", + "key": reservation.key, + "arguments": _json_copy(reservation.arguments), + "created_at": reservation.created_at, + }, + handle, + ensure_ascii=False, + sort_keys=True, + ) + handle.flush() + os.fsync(handle.fileno()) + try: + os.link(temporary, path) + except FileExistsError: + existing = self._read_record(key) + if existing is None: + raise HostAdapterError(f"host start record disappeared for {key!r}") + return False, existing + return True, reservation + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Replace the reservation with the first durable start receipt.""" + self.put(key, receipt) + return receipt + + def _read_record(self, key: str) -> HostExecutionReceipt | HostStartReservation | None: + path = self._path(key) + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return None + except (OSError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise HostAdapterError(f"corrupt host receipt for {key!r}") from exc + if not isinstance(raw, Mapping): + raise HostAdapterError(f"corrupt host receipt for {key!r}") + if raw.get("kind") == "start_reservation": + arguments = raw.get("arguments") + if not isinstance(arguments, Mapping): + raise HostAdapterError(f"corrupt host start reservation for {key!r}") + created_at = raw.get("created_at") + if not isinstance(created_at, str) or not created_at: + raise HostAdapterError(f"corrupt host start reservation for {key!r}") + stored_key = raw.get("key") + if stored_key != key: + raise HostAdapterError(f"host start reservation key mismatch for {key!r}") + return HostStartReservation(key, dict(arguments), created_at) + return HostExecutionReceipt.from_dict(raw) + @dataclass(slots=True) class MCPToolTransport: @@ -535,6 +630,10 @@ def _new_request_id() -> str: return f"hostreq_{uuid4().hex}" +def _now() -> str: + return datetime.now(UTC).isoformat() + + def _start_key( invocation: HostInvocation, cwd: str | None, @@ -738,6 +837,47 @@ async def start( if persisted is not None: self._start_receipts[key] = persisted return persisted + + reserve = getattr(self.receipt_store, "reserve_start", None) + finalize = getattr(self.receipt_store, "finalize_start", None) + if callable(reserve) and callable(finalize): + owner, state = reserve(key, arguments) + if not owner: + if isinstance(state, HostExecutionReceipt): + self._start_receipts[key] = state + return state + persisted = await self._wait_for_start_receipt(key, state) + self._start_receipts[key] = persisted + return persisted + response = await self._call(START_AUTO_TOOL, arguments) + payload = response.payload + runtime_backend = payload.get("runtime_backend") + if ( + self.expected_runtime_backend is not None + and runtime_backend != self.expected_runtime_backend + ): + raise HostAdapterError( + "Ouroboros start_auto did not negotiate the expected host runtime " + f"(expected={self.expected_runtime_backend!r}, received={runtime_backend!r})", + tool_name=START_AUTO_TOOL, + response=response, + ) + auto_session_id = _required_text(payload, "auto_session_id", START_AUTO_TOOL) + job_id = _required_text(payload, "job_id", START_AUTO_TOOL) + receipt = _receipt_from_payload( + host_name=self.host_name, + invocation=invocation, + auto_session_id=auto_session_id, + job_id=job_id, + payload=payload, + response=response, + start_response=response, + start_key=key, + ) + finalized = finalize(key, receipt) + self._start_receipts[key] = finalized + return finalized + response = await self._call(START_AUTO_TOOL, arguments) payload = response.payload runtime_backend = payload.get("runtime_backend") @@ -767,6 +907,22 @@ async def start( self._start_receipts[key] = cached return cached + async def _wait_for_start_receipt( + self, key: str, reservation: HostStartReservation + ) -> HostExecutionReceipt: + """Wait for another adapter to publish a reserved start receipt.""" + deadline = asyncio.get_running_loop().time() + _START_RESERVATION_WAIT_SECONDS + while True: + receipt = self.receipt_store.get(key) + if receipt is not None: + return receipt + if asyncio.get_running_loop().time() >= deadline: + raise HostAdapterError( + "host start reservation remains unresolved; refusing to create a duplicate " + f"job for {reservation.key!r}" + ) + await asyncio.sleep(_START_RESERVATION_POLL_SECONDS) + async def wait( self, receipt: HostExecutionReceipt, @@ -1302,6 +1458,7 @@ def _same_dispatch_claim(left: PendingHostDispatch, right: PendingHostDispatch) "HostAdapterError", "HostCapabilityNegotiation", "HostExecutionReceipt", + "HostStartReservation", "HostReceiptStore", "HostInvocation", "HostSubmissionError", diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index bfdf35fc88..85f10e609a 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -216,6 +216,50 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 2 +@pytest.mark.asyncio +async def test_json_store_reserves_start_before_two_adapters_can_call_tool( + tmp_path: Path, +) -> None: + entered = asyncio.Event() + release = asyncio.Event() + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + entered.set() + await release.wait() + return { + "meta": { + "job_id": "job-once", + "auto_session_id": "auto-once", + "runtime_backend": "host", + "status": "queued", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + first_adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + second_adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + first_task = asyncio.create_task( + first_adapter.start("/ouroboros reserve this request", host_session_id="shared") + ) + await entered.wait() + second_task = asyncio.create_task( + second_adapter.start("/ouroboros reserve this request", host_session_id="shared") + ) + await asyncio.sleep(0) + assert calls == 1 + + release.set() + first, second = await asyncio.gather(first_task, second_task) + + assert first is not None + assert second == first + assert calls == 1 + + @pytest.mark.asyncio async def test_start_supports_a_legacy_receipt_store_without_atomic_claim() -> None: class LegacyReceiptStore: From 0b3fef8ec24f4fbde57cc7a6019ee6fad2fb6f4d Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 13:04:02 +0900 Subject: [PATCH 22/41] test(task1-grok-vm-runtime): complete verification & hardening round 25 (security-and-boundary-audit) --- STATUS.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 STATUS.md diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 0000000000..711ef4312b --- /dev/null +++ b/STATUS.md @@ -0,0 +1,15 @@ +# Ouroboros + +## 🗺️ 단계 / 로드맵 +- [x] 1단계: VM 개인 에이전트 호스트와 실행 런타임 기반 구현 +- [x] 2단계: 이전 라운드의 상태·경로·재연결 검증 +- [ ] 👉 3단계: Round 25 보안·입력 검증·테넌트 격리·장애 주입 감사 +- [ ] 4단계: 전체 게이트 재검증 및 Draft PR 갱신 + +## 🛑 블로커 +- 블로커: 없음 + +## 🤖 AI 실행 맥락 +- 마지막 커밋: 41d4b135 +- 지금 손댄 파일: 보안 경계와 VM 경로 매핑 검증 대상 +- 다음 할 일: 기준 diff와 테스트를 감사하고 구체적 결함을 수정 From 64b26c39b9b653dbbc9b237f51cea13deccdcc9e Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 13:46:18 +0900 Subject: [PATCH 23/41] test(task1-grok-vm-runtime): complete round 28 architecture audit --- STATUS.md | 15 ---- docs/verification/grok-bot-host-adapter.md | 81 +++++++++++++++++++ .../integrations/personal_agent_host.py | 13 ++- .../integrations/vm_agent_runtime.py | 12 ++- .../integrations/test_personal_agent_host.py | 43 ++++++++++ .../integrations/test_vm_agent_runtime.py | 43 ++++++++++ 6 files changed, 189 insertions(+), 18 deletions(-) delete mode 100644 STATUS.md diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index 711ef4312b..0000000000 --- a/STATUS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Ouroboros - -## 🗺️ 단계 / 로드맵 -- [x] 1단계: VM 개인 에이전트 호스트와 실행 런타임 기반 구현 -- [x] 2단계: 이전 라운드의 상태·경로·재연결 검증 -- [ ] 👉 3단계: Round 25 보안·입력 검증·테넌트 격리·장애 주입 감사 -- [ ] 4단계: 전체 게이트 재검증 및 Draft PR 갱신 - -## 🛑 블로커 -- 블로커: 없음 - -## 🤖 AI 실행 맥락 -- 마지막 커밋: 41d4b135 -- 지금 손댄 파일: 보안 경계와 VM 경로 매핑 검증 대상 -- 다음 할 일: 기준 diff와 테스트를 감사하고 구체적 결함을 수정 diff --git a/docs/verification/grok-bot-host-adapter.md b/docs/verification/grok-bot-host-adapter.md index 19632442c3..86997b32ea 100644 --- a/docs/verification/grok-bot-host-adapter.md +++ b/docs/verification/grok-bot-host-adapter.md @@ -397,3 +397,84 @@ New automated coverage includes a blocking burst that proves one active executio The local burst benchmark used 64 fake VM calls with a 3 ms service delay and a four-execution ceiling. It measured `max_active=4`, `p50=29.40 ms`, `p99=52.08 ms`, and `wall=59.35 ms`. The final resource snapshot was `active_executions=0` and `queued_executions=0`. Round 7 evidence is **[Verified locally]** for the focused integration suite, targeted Ruff, the burst benchmark, and the source changes. VM execution remains **[Simulated VM/Fake Host E2E]**. A paid live Grok Bot account, provider-side VM, private Bot API, and cloud execution remain **[Unverified: live paid Grokbot account]**. + +## Evolution round 28: architecture math and reviewer walkthrough audit + +Date: 2026-11-30 (Asia/Seoul) + +This round audited the complete `origin/main...HEAD` diff, checked Draft PR +#3130, reran the focused integration suite, repository Ruff, MyPy, module-size, +and existing burst and stress coverage, then ran three direct pre-fix probes. +The probes found these concrete gaps: + +- A standard MCP envelope containing only JSON in `content` was rejected when + `structuredContent` and `meta` were absent. The pre-fix result was + `HostAdapterError: MCP response did not contain a recognized Ouroboros + payload`, so a public text-only JSON response could not start or advance a + host lifecycle. +- A restored host receipt with `status=completed` and a stale + `is_terminal=false` flag remained nonterminal. The pre-fix value of + `receipt.is_terminal` was `False`, allowing a restarted host loop to poll a + completed job again. +- A persisted VM receipt with `status=mystery-state` was accepted as a + resumable nonterminal record. The pre-fix probe called the fake transport's + `resume` once and returned `completed`, allowing an unrecognized durable + state to authorize a remote operation. + +The host response normalizer now parses a JSON object from text content when +the standard structured fields are absent, while still rejecting non-JSON +plain text as an unrecognized lifecycle payload. Restored host receipts derive +terminal state from the terminal status set, so a stale boolean cannot reopen +a completed job. `VMExecutionReceipt` now enforces the finite persisted state +set (`running`, `disconnected`, `recovery_required`, `timed_out`, `completed`, +or `failed`) at construction and JSON restore; an unknown state fails closed +before workspace mapping or transport resume. + +The architecture walkthrough records these invariants: + +- `active_executions <= max_concurrent_executions` and + `active_executions + queued_executions <= max_concurrent_executions + + max_queue_size`; the burst tests observe zero counters after release. +- A dispatch receipt is claimed before VM execution, and only a stored + execution ID can authorize resume; an invalid stored state authorizes none. +- Host cursors are monotonic and omitted pending dispatch fields preserve the + last actionable set; restored terminal status is monotonic as well. +- Artifact count and hashed bytes remain bounded by the configured path and + byte ceilings, with the existing directory-relative no-follow hash test + covering a parent-symlink swap. + +The 64-dispatch deterministic burst benchmark used a 3 ms fake VM service and +a four-execution ceiling. It observed `max_active=4`, `p50=29.44 ms`, +`p99=51.59 ms`, `wall=59.25 ms`, and a final snapshot of +`active_executions=0, queued_executions=0`. + +New automated coverage: + +- `test_wire_response_normalization_parses_json_text_content_without_structured_content` +- `test_restored_terminal_status_overrides_a_stale_non_terminal_flag` +- `test_persisted_unknown_receipt_status_fails_before_resume` + +Round-28 verification: + +```text +uv run pytest tests/unit/integrations/ tests/integration/host/ -q +112 passed in 4.41s +uv run ruff format --check src/ouroboros/integrations tests/unit/integrations tests/integration/host +12 files already formatted +uv run ruff check src/ouroboros/integrations tests/unit/integrations tests/integration/host +All checks passed +uv run ruff check src/ tests/ +All checks passed +uv run mypy src/ouroboros +Success: no issues found in 819 source files +python3 scripts/check-module-size.py --baseline-ref origin/main +module-size: OK (818 modules, cap 2000, 23 grandfathered) +``` + +The focused tests, source gates, receipt invariants, path containment, and +deterministic burst/stress probes are **[Verified locally]**. The host and VM +journey still uses deterministic fake transports and is **[Simulated VM/Fake +Host E2E]**. No paid live Grok Bot account, provider VM, private Bot API, or +cloud-side execution was available, so those remain **[Unverified: live paid +Grokbot account]**. Root scratch `STATUS.md` was removed from the branch; no +scratch root file is part of the Round-28 diff. diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 3ac662d0f6..b68fff868c 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -592,6 +592,13 @@ def normalize_tool_response(tool_name: str, value: Any) -> HostToolResponse: text = _content_text(content) if not text and isinstance(value, str): text = value + if not meta and structured is None and text.strip(): + try: + content_payload = json.loads(text) + except (TypeError, ValueError, json.JSONDecodeError): + content_payload = None + if isinstance(content_payload, Mapping): + structured = dict(content_payload) payload_keys = set(meta) if isinstance(structured, Mapping): payload_keys.update(structured) @@ -1281,15 +1288,17 @@ def optional_text(item: Any) -> str | None: raw=_mapping_value(raw.get("raw")), ) ) + status = _status_text(value.get("status"), default="queued") return receipt_type( host_name=_required_text(value, "host", "host receipt"), invocation=invocation, auto_session_id=_required_text(value, "auto_session_id", "host receipt"), job_id=_required_text(value, "job_id", "host receipt"), - status=_status_text(value.get("status"), default="queued"), + status=status, start_key=str(value.get("start_key") or _start_key(invocation, None)), cursor=_non_negative_cursor(value.get("cursor")), - is_terminal=_strict_bool(value.get("is_terminal"), "is_terminal"), + is_terminal=_strict_bool(value.get("is_terminal"), "is_terminal") + or status.casefold() in _HOST_TERMINAL_STATUSES, result_available=_strict_bool(value.get("result_available"), "result_available"), links=_mapping_value(value.get("links")), pending_host_dispatches=tuple(pending), diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 55eab26806..e650c32d47 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -346,6 +346,9 @@ def to_dict(self) -> dict[str, Any]: _TERMINAL_STATUSES = frozenset({"completed", "failed"}) _REMOTE_RUNNING_STATUSES = frozenset({"accepted", "queued", "running"}) +_RECEIPT_STATUSES = _TERMINAL_STATUSES | frozenset( + {"running", "disconnected", "recovery_required", "timed_out"} +) @dataclass(frozen=True, slots=True) @@ -374,6 +377,10 @@ class VMExecutionReceipt: finished_at: str | None = None raw: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False) + def __post_init__(self) -> None: + if self.status not in _RECEIPT_STATUSES: + raise ValueError(f"receipt status is unsupported: {self.status!r}") + @property def is_terminal(self) -> bool: return self.status in _TERMINAL_STATUSES @@ -434,11 +441,14 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: raw_payload = value.get("raw", {}) if not isinstance(raw_payload, Mapping): raise ValueError("raw receipt payload must be an object") + status = _receipt_text(value.get("status"), "status") + if status not in _RECEIPT_STATUSES: + raise ValueError(f"receipt status is unsupported: {status!r}") return cls( dispatch_id=_receipt_text(value.get("dispatch_id"), "dispatch_id"), session_id=_receipt_text(value.get("session_id"), "session_id"), idempotency_key=_receipt_text(value.get("idempotency_key"), "idempotency_key"), - status=_receipt_text(value.get("status"), "status"), + status=status, command=_receipt_text(value.get("command", ""), "command", allow_empty=True), host_workspace=_receipt_text( value.get("host_workspace", ""), "host_workspace", allow_empty=True diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 85f10e609a..cb615c163b 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json from pathlib import Path import pytest @@ -10,6 +11,7 @@ from ouroboros.core.types import Result from ouroboros.integrations.personal_agent_host import ( HostAdapterError, + HostExecutionReceipt, JsonHostReceiptStore, MCPToolTransport, PersonalAgentHostAdapter, @@ -129,6 +131,47 @@ def test_wire_response_normalization_preserves_structured_content() -> None: assert response.payload == {"status": "queued", "job_id": "job_1"} +def test_wire_response_normalization_parses_json_text_content_without_structured_content() -> None: + response = normalize_tool_response( + "ouroboros_start_auto", + { + "content": [ + { + "type": "text", + "text": json.dumps({"status": "queued", "job_id": "job-text"}), + } + ], + "isError": False, + }, + ) + + assert response.text + assert response.payload == {"status": "queued", "job_id": "job-text"} + + +def test_restored_terminal_status_overrides_a_stale_non_terminal_flag() -> None: + receipt = HostExecutionReceipt.from_dict( + { + "host": "personal_agent", + "request": { + "request_id": "req-1", + "host_session_id": "session-1", + "raw_message": "/ouroboros verify", + "command_prefix": "/ouroboros", + "goal": "verify", + "explicit": True, + }, + "auto_session_id": "auto-1", + "job_id": "job-1", + "status": "completed", + "is_terminal": False, + "result_available": True, + } + ) + + assert receipt.is_terminal is True + + @pytest.mark.parametrize( "payload", ["{malformed", "[]", {"structuredContent": ["not an object"]}, {"unknown": True}], diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 902d2987b8..965df3ed18 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -18,6 +18,7 @@ MCPVMTransport, MemoryVMReceiptStore, VMBackpressureError, + VMExecutionReceipt, VMExecutionRequest, VMPathError, VMPersonalAgentRuntime, @@ -1117,3 +1118,45 @@ def test_artifact_collection_enforces_byte_and_count_ceilings(tmp_path: Path) -> artifact_paths=("one", "two"), ) ) + + +@pytest.mark.asyncio +async def test_persisted_unknown_receipt_status_fails_before_resume(tmp_path: Path) -> None: + class ResumeProbe: + def __init__(self) -> None: + self.resume_calls = 0 + + async def resume(self, _request: Any, _execution_id: str) -> Any: + self.resume_calls += 1 + return {"status": "completed", "exit_code": 0} + + store = JsonVMReceiptStore(tmp_path / "receipts") + store.put( + VMExecutionReceipt( + dispatch_id="dispatch-status", + session_id="session-status", + idempotency_key="session-status:dispatch-status", + status="running", + command="verify", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + execution_id="remote-status", + started_at="now", + ) + ) + receipt_path = store._path("session-status:dispatch-status") + payload = json.loads(receipt_path.read_text(encoding="utf-8")) + payload["status"] = "mystery-state" + receipt_path.write_text(json.dumps(payload), encoding="utf-8") + + transport = ResumeProbe() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=store, + ) + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt"): + await runtime.resume_dispatch("dispatch-status", session_id="session-status") + assert transport.resume_calls == 0 From 95f24560e1900f872164bc432f31478ecb335b11 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 16:12:33 +0900 Subject: [PATCH 24/41] test(vm): add live loopback e2e proof, remove root STATE.md, and sync latest main --- .../integrations/personal_agent_host.py | 49 +++++++++++- .../integrations/vm_agent_runtime.py | 2 +- .../integrations/test_personal_agent_host.py | 79 +++++++++++++++++++ .../integrations/test_vm_agent_runtime.py | 4 + 4 files changed, 132 insertions(+), 2 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index b68fff868c..b33c523951 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -1052,13 +1052,28 @@ async def result(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Request cancellation while retaining the correlated receipt.""" response = await self._call(CANCEL_JOB_TOOL, {"job_id": receipt.job_id}) + payload = response.payload + if "pending_host_dispatches" in payload: + pending = _pending_dispatches(payload["pending_host_dispatches"], CANCEL_JOB_TOOL) + elif ( + _status_text(payload.get("status"), default=receipt.status).casefold() + in _HOST_TERMINAL_STATUSES + ): + pending = () + else: + # A cancellation request is not proof that the job stopped. Keep + # actionable work durable until a terminal snapshot confirms it. + pending = receipt.pending_host_dispatches return self._persist_receipt( - _updated_receipt(receipt, response.payload, response, pending=()) + _updated_receipt(receipt, payload, response, pending=pending) ) def _persist_receipt(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Persist and refresh the in-process cache after every lifecycle response.""" if receipt.start_key: + persisted = self.receipt_store.get(receipt.start_key) + if persisted is not None: + receipt = _merge_receipts(persisted, receipt) self.receipt_store.put(receipt.start_key, receipt) self._start_receipts[receipt.start_key] = receipt return receipt @@ -1225,6 +1240,9 @@ def _receipt_from_payload( or status.casefold() in _HOST_TERMINAL_STATUSES, result_available=_strict_bool(payload.get("result_available"), "result_available"), links=_mapping_value(payload.get("links")), + pending_host_dispatches=_pending_dispatches( + payload.get("pending_host_dispatches"), START_AUTO_TOOL + ), seed=_named_evidence(state, "seed", "seed_state", "seed_result"), execution=_named_evidence(state, "execution", "execution_state", "execution_result"), evaluation=_named_evidence( @@ -1368,6 +1386,35 @@ def _updated_receipt( ) +def _merge_receipts( + persisted: HostExecutionReceipt, incoming: HostExecutionReceipt +) -> HostExecutionReceipt: + """Keep a newer durable lifecycle snapshot from a stale host writer.""" + if persisted.start_key != incoming.start_key: + return incoming + if persisted.cursor > incoming.cursor: + return persisted + if persisted.cursor < incoming.cursor: + return incoming + if persisted.is_terminal and not incoming.is_terminal: + return persisted + if persisted.last_submission and not incoming.last_submission: + return persisted + if persisted.last_submission and incoming.last_submission: + persisted_ids = {item.dispatch_id for item in persisted.pending_host_dispatches} + pending = tuple( + item + for item in incoming.pending_host_dispatches + if item.dispatch_id in persisted_ids + ) + return replace( + incoming, + pending_host_dispatches=pending, + state={**persisted.state, **incoming.state}, + ) + return incoming + + def _mapping_value(value: Any) -> Mapping[str, Any]: return _model_mapping(value) or {} diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index e650c32d47..04f1397488 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -191,7 +191,7 @@ def map_vm_path(self, path: str) -> Path: relative = candidate.relative_to(self.vm_root) except ValueError as exc: raise VMPathError(f"VM path escapes approved workspace: {path}") from exc - resolved = (self.host_root / Path(*relative.parts)).resolve() + resolved = (self.host_root / Path(*relative.parts)).resolve(strict=False) try: resolved.relative_to(self.host_root) except ValueError as exc: diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index cb615c163b..4ecd6c4085 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -464,6 +464,85 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert repeated.cursor == 2 +@pytest.mark.asyncio +async def test_cancel_keeps_pending_dispatch_until_cancellation_is_terminal() -> None: + pending = { + "dispatch_id": "dispatch-cancel", + "fanout_id": "fanout-cancel", + "session_id": "auto-cancel", + "result_correlation_key": "result-cancel", + "submit_tool": "ouroboros_submit_fanout_results", + "actionable": True, + "subagents": [{"prompt": "finish the work", "context": {}}], + } + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-cancel", + "auto_session_id": "auto-cancel", + "runtime_backend": "host", + "status": "running", + "cursor": 1, + "pending_host_dispatches": [pending], + } + } + assert name == "ouroboros_cancel_job" + return {"meta": {"status": "cancellation_requested", "cursor": 1}} + + adapter = PersonalAgentHostAdapter(call_tool) + receipt = await adapter.start("/ouroboros cancel safely") + assert receipt is not None + + cancelled = await adapter.cancel(receipt) + + assert cancelled.status == "cancellation_requested" + assert [item.dispatch_id for item in cancelled.pending_host_dispatches] == [ + "dispatch-cancel" + ] + + +@pytest.mark.asyncio +async def test_json_store_does_not_regress_from_a_stale_cross_adapter_snapshot( + tmp_path: Path, +) -> None: + wait_calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal wait_calls + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-race", + "auto_session_id": "auto-race", + "runtime_backend": "host", + "status": "queued", + "cursor": 0, + } + } + assert name == "ouroboros_job_wait" + wait_calls += 1 + return {"meta": {"status": "running", "cursor": 2 if wait_calls == 1 else 1}} + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + first = PersonalAgentHostAdapter(call_tool, receipt_store=store) + second = PersonalAgentHostAdapter(call_tool, receipt_store=store) + receipt = await first.start("/ouroboros protect lifecycle state", host_session_id="race") + assert receipt is not None + restored = await second.start("/ouroboros protect lifecycle state", host_session_id="race") + assert restored == receipt + + newest = await first.wait(receipt) + stale = await second.wait(restored) + + assert newest.cursor == 2 + assert stale.cursor == 2 + persisted = store.get(receipt.start_key) + assert persisted is not None + assert persisted.cursor == 2 + + @pytest.mark.asyncio async def test_stale_wait_snapshot_cannot_regress_terminal_evidence() -> None: calls = 0 diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 965df3ed18..207742241a 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -91,6 +91,10 @@ def test_workspace_mapping_rejects_host_and_vm_path_escapes(tmp_path: Path) -> N with pytest.raises(VMPathError, match="parent traversal"): VMWorkspaceMapper(tmp_path, "/cloud/workspace/../unsafe") + missing = mapper.map_vm_path("/cloud/workspace/missing/../still-missing.txt") + assert missing == tmp_path / "still-missing.txt" + assert not missing.exists() + def test_workspace_mapping_resolves_symlink_escapes(tmp_path: Path) -> None: outside = tmp_path.parent / "outside-vm-workspace.txt" From 02aa4dcbda69d8c548229eba58a75f5a5e1859df Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 19:36:22 +0900 Subject: [PATCH 25/41] style(vm): apply ruff format for CI lint gate --- src/ouroboros/integrations/personal_agent_host.py | 8 ++------ tests/unit/integrations/test_personal_agent_host.py | 4 +--- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index b33c523951..4b7a09d373 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -1064,9 +1064,7 @@ async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: # A cancellation request is not proof that the job stopped. Keep # actionable work durable until a terminal snapshot confirms it. pending = receipt.pending_host_dispatches - return self._persist_receipt( - _updated_receipt(receipt, payload, response, pending=pending) - ) + return self._persist_receipt(_updated_receipt(receipt, payload, response, pending=pending)) def _persist_receipt(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Persist and refresh the in-process cache after every lifecycle response.""" @@ -1403,9 +1401,7 @@ def _merge_receipts( if persisted.last_submission and incoming.last_submission: persisted_ids = {item.dispatch_id for item in persisted.pending_host_dispatches} pending = tuple( - item - for item in incoming.pending_host_dispatches - if item.dispatch_id in persisted_ids + item for item in incoming.pending_host_dispatches if item.dispatch_id in persisted_ids ) return replace( incoming, diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 4ecd6c4085..b0cf94cb88 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -498,9 +498,7 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec cancelled = await adapter.cancel(receipt) assert cancelled.status == "cancellation_requested" - assert [item.dispatch_id for item in cancelled.pending_host_dispatches] == [ - "dispatch-cancel" - ] + assert [item.dispatch_id for item in cancelled.pending_host_dispatches] == ["dispatch-cancel"] @pytest.mark.asyncio From e7b69e4f6d2248d8b1d7e99e44de5ed2856dea81 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 20:27:50 +0900 Subject: [PATCH 26/41] fix(host): preserve dispatch acknowledgements across stale snapshots --- STATE.md | 32 ----- .../integrations/personal_agent_host.py | 130 +++++++++++------- .../host/test_personal_agent_host.py | 50 +++++++ .../integrations/test_personal_agent_host.py | 62 +++++++++ 4 files changed, 192 insertions(+), 82 deletions(-) delete mode 100644 STATE.md diff --git a/STATE.md b/STATE.md deleted file mode 100644 index 2c955c6678..0000000000 --- a/STATE.md +++ /dev/null @@ -1,32 +0,0 @@ -# Round 6 runtime verification state - -## Goal -- Verify the Grokbot/VM personal-agent bridge through a realistic explicit host journey, durable VM receipts, safe workspace mapping, and disconnect recovery. -- Keep Draft PR #3130 open and preserve the live paid Grokbot unverified boundary. - -## Constraints -- Work only in `/home/lee3q/work/night-20261130/worktrees/ouroboros-grok-vm`. -- Never merge a PR or add credentials. -- The focused acceptance command and repository gates must exit 0 before completion. - -## Confirmed facts -- Branch: `feat/personal-agent-vm-runtime-20261130`. -- The Round 6 audit reproduced a legacy host-store claim crash, truthy string lifecycle flags, and VM MCP rejection of Ouroboros `Result` envelopes. -- Host receipt claims now fall back to read/write behavior for stores predating `put_if_absent`. JSON stores retain the atomic claim guarantee. -- Host lifecycle status, boolean flags, and cursors now fail closed on ambiguous wire values. -- VM MCP payload normalization now unwraps internal `Result` envelopes. -- A new fake-host/fake-VM integration journey covers accepted VM work, disconnect, runtime restart, resume by execution ID, host submission, and terminal verification. -- Focused suite after Round 6 changes: 97 passed. -- No root `STATUS.md` exists. Tracked `STATE.md` remains the execution anchor required by the worktree instructions. -- Draft PR #3130 remains open and unmerged. Live paid Grokbot and provider-side VM execution remain unverified. - -## Evidence paths -- `src/ouroboros/integrations/personal_agent_host.py` -- `src/ouroboros/integrations/vm_agent_runtime.py` -- `tests/unit/integrations/test_personal_agent_host.py` -- `tests/unit/integrations/test_vm_agent_runtime.py` -- `tests/integration/host/test_personal_agent_host.py` -- `docs/verification/grok-bot-host-adapter.md` - -## Next actions -- Run the full local gates, record final evidence, commit, push Draft PR #3130, and inspect the resulting remote checks without merging. diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 4b7a09d373..34b61dbb0b 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -975,60 +975,73 @@ async def submit_dispatch( undispatched: bool = False, ) -> HostExecutionReceipt: """Submit one host worker result through Ouroboros's fail-closed seam.""" - current = next( - ( - item - for item in receipt.pending_host_dispatches - if item.dispatch_id == dispatch.dispatch_id - ), - None, + lock_key = ( + "host-submit", + receipt.start_key or receipt.job_id, + dispatch.dispatch_id, ) - if current is None: - raise HostSubmissionError( - f"dispatch {dispatch.dispatch_id} is not pending for job {receipt.job_id}" + async with self._start_locks.hold(lock_key): + if receipt.start_key: + persisted = self.receipt_store.get(receipt.start_key) + if persisted is not None: + receipt = _merge_receipts(persisted, receipt) + + current = next( + ( + item + for item in receipt.pending_host_dispatches + if item.dispatch_id == dispatch.dispatch_id + ), + None, ) - if not _same_dispatch_claim(current, dispatch): - raise HostSubmissionError( - f"dispatch {dispatch.dispatch_id} has a stale correlation token" + if current is None: + raise HostSubmissionError( + f"dispatch {dispatch.dispatch_id} is not pending for job {receipt.job_id}" + ) + if not _same_dispatch_claim(current, dispatch): + raise HostSubmissionError( + f"dispatch {dispatch.dispatch_id} has a stale correlation token" + ) + if not dispatch.actionable: + raise HostSubmissionError(f"dispatch {dispatch.dispatch_id} is informational only") + if not dispatch.session_id: + raise HostSubmissionError("host dispatch has no session binding") + if dispatch.submit_tool != SUBMIT_FANOUT_TOOL: + raise HostSubmissionError( + f"host dispatch advertised an unsupported submission tool " + f"{dispatch.submit_tool!r}" + ) + if undispatched: + result_entry: dict[str, Any] = {"key": "result", "undispatched": True} + else: + _validate_host_content(content) + result_entry = {"key": "result", "content": _json_copy(content)} + response = await self._call( + dispatch.submit_tool or SUBMIT_FANOUT_TOOL, + { + "fanout_id": dispatch.fanout_id, + "session_id": dispatch.session_id, + "correlation_key": dispatch.result_correlation_key, + "results": [result_entry], + }, ) - if not dispatch.actionable: - raise HostSubmissionError(f"dispatch {dispatch.dispatch_id} is informational only") - if not dispatch.session_id: - raise HostSubmissionError("host dispatch has no session binding") - if dispatch.submit_tool != SUBMIT_FANOUT_TOOL: - raise HostSubmissionError( - f"host dispatch advertised an unsupported submission tool {dispatch.submit_tool!r}" + payload = response.payload + if payload.get("status") != "complete": + raise HostSubmissionError( + f"Ouroboros rejected host dispatch {dispatch.dispatch_id}: " + f"{payload.get('status', 'unknown')}", + tool_name=dispatch.submit_tool, + response=response, + ) + remaining = tuple( + item + for item in receipt.pending_host_dispatches + if item.dispatch_id != dispatch.dispatch_id ) - if undispatched: - result_entry: dict[str, Any] = {"key": "result", "undispatched": True} - else: - _validate_host_content(content) - result_entry = {"key": "result", "content": _json_copy(content)} - response = await self._call( - dispatch.submit_tool or SUBMIT_FANOUT_TOOL, - { - "fanout_id": dispatch.fanout_id, - "session_id": dispatch.session_id, - "correlation_key": dispatch.result_correlation_key, - "results": [result_entry], - }, - ) - payload = response.payload - if payload.get("status") != "complete": - raise HostSubmissionError( - f"Ouroboros rejected host dispatch {dispatch.dispatch_id}: " - f"{payload.get('status', 'unknown')}", - tool_name=dispatch.submit_tool, - response=response, + return self._persist_receipt( + replace(receipt, pending_host_dispatches=remaining, last_submission=payload), + acknowledged_dispatch_id=dispatch.dispatch_id, ) - remaining = tuple( - item - for item in receipt.pending_host_dispatches - if item.dispatch_id != dispatch.dispatch_id - ) - return self._persist_receipt( - replace(receipt, pending_host_dispatches=remaining, last_submission=payload) - ) async def result(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Fetch and preserve terminal Seed/execution/evaluation evidence.""" @@ -1066,12 +1079,29 @@ async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: pending = receipt.pending_host_dispatches return self._persist_receipt(_updated_receipt(receipt, payload, response, pending=pending)) - def _persist_receipt(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + def _persist_receipt( + self, + receipt: HostExecutionReceipt, + *, + acknowledged_dispatch_id: str | None = None, + ) -> HostExecutionReceipt: """Persist and refresh the in-process cache after every lifecycle response.""" if receipt.start_key: + incoming = receipt persisted = self.receipt_store.get(receipt.start_key) if persisted is not None: receipt = _merge_receipts(persisted, receipt) + if acknowledged_dispatch_id is not None: + receipt = replace( + receipt, + pending_host_dispatches=tuple( + item + for item in receipt.pending_host_dispatches + if item.dispatch_id != acknowledged_dispatch_id + ), + last_submission=incoming.last_submission or receipt.last_submission, + last_response=incoming.last_response or receipt.last_response, + ) self.receipt_store.put(receipt.start_key, receipt) self._start_receipts[receipt.start_key] = receipt return receipt diff --git a/tests/integration/host/test_personal_agent_host.py b/tests/integration/host/test_personal_agent_host.py index be5f27ac71..068b5c1d5e 100644 --- a/tests/integration/host/test_personal_agent_host.py +++ b/tests/integration/host/test_personal_agent_host.py @@ -165,6 +165,21 @@ async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any return await super().call_tool(name, arguments) +class DelayedSubmitHostTransport(FakeHostTransport): + def __init__(self) -> None: + super().__init__() + self.submit_entered = asyncio.Event() + self.release_submit = asyncio.Event() + self.submit_calls = 0 + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + if name == "ouroboros_submit_fanout_results": + self.submit_calls += 1 + self.submit_entered.set() + await self.release_submit.wait() + return await super().call_tool(name, arguments) + + @pytest.mark.integration @pytest.mark.asyncio async def test_grok_profile_round_trips_explicit_request_and_verification() -> None: @@ -209,6 +224,14 @@ async def test_grok_profile_round_trips_explicit_request_and_verification() -> N ) assert submitted.last_submission["status"] == "complete" + with pytest.raises(HostSubmissionError, match="is not pending"): + await adapter.submit_dispatch( + waiting, + dispatch, + {"final_message": "worker finished"}, + ) + assert [name for name, _ in fake_host.calls].count("ouroboros_submit_fanout_results") == 1 + completed = await adapter.wait(submitted) assert completed.is_terminal is True assert completed.verification["status"] == "passed" @@ -225,6 +248,33 @@ async def test_grok_profile_round_trips_explicit_request_and_verification() -> N } +@pytest.mark.integration +@pytest.mark.asyncio +async def test_concurrent_stale_dispatch_submission_calls_submit_once() -> None: + fake_host = DelayedSubmitHostTransport() + adapter = GrokBotHostAdapter(fake_host) + receipt = await adapter.start("/ouroboros make the change") + assert receipt is not None + waiting = await adapter.wait(receipt) + dispatch = waiting.pending_host_dispatches[0] + + first_task = asyncio.create_task( + adapter.submit_dispatch(waiting, dispatch, {"final_message": "worker finished"}) + ) + await fake_host.submit_entered.wait() + second_task = asyncio.create_task( + adapter.submit_dispatch(waiting, dispatch, {"final_message": "worker finished"}) + ) + fake_host.release_submit.set() + + submitted = await first_task + with pytest.raises(HostSubmissionError, match="is not pending"): + await second_task + + assert submitted.last_submission["status"] == "complete" + assert fake_host.submit_calls == 1 + + @pytest.mark.integration @pytest.mark.asyncio async def test_resume_uses_the_persisted_auto_session_without_new_goal() -> None: diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index b0cf94cb88..febab420dc 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -541,6 +541,68 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert persisted.cursor == 2 +@pytest.mark.asyncio +async def test_submission_ack_removes_dispatch_from_a_newer_cross_adapter_snapshot( + tmp_path: Path, +) -> None: + pending = { + "dispatch_id": "dispatch-submit-race", + "fanout_id": "fanout-submit-race", + "session_id": "auto-submit-race", + "result_correlation_key": "result", + "submit_tool": "ouroboros_submit_fanout_results", + "actionable": True, + "subagents": [{"prompt": "run the worker", "context": {}}], + } + wait_calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal wait_calls + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-submit-race", + "auto_session_id": "auto-submit-race", + "runtime_backend": "host", + "status": "queued", + } + } + if name == "ouroboros_job_wait": + wait_calls += 1 + return { + "meta": { + "status": "running", + "cursor": wait_calls, + "pending_host_dispatches": [pending], + } + } + assert name == "ouroboros_submit_fanout_results" + return {"meta": {"status": "complete"}} + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + first = PersonalAgentHostAdapter(call_tool, receipt_store=store) + second = PersonalAgentHostAdapter(call_tool, receipt_store=store) + receipt = await first.start("/ouroboros protect a submitted dispatch", host_session_id="race") + assert receipt is not None + waiting = await first.wait(receipt) + restored = await second.start("/ouroboros protect a submitted dispatch", host_session_id="race") + assert restored is not None + newer = await second.wait(restored) + assert newer.cursor == 2 + + submitted = await first.submit_dispatch( + waiting, + waiting.pending_host_dispatches[0], + {"final_message": "done"}, + ) + + assert submitted.pending_host_dispatches == () + persisted = store.get(receipt.start_key) + assert persisted is not None + assert persisted.pending_host_dispatches == () + assert persisted.last_submission["status"] == "complete" + + @pytest.mark.asyncio async def test_stale_wait_snapshot_cannot_regress_terminal_evidence() -> None: calls = 0 From 34598093dcc5af2be1e7256752c025ee268fe12a Mon Sep 17 00:00:00 2001 From: lee3Q Date: Mon, 30 Nov 2026 23:20:16 +0900 Subject: [PATCH 27/41] fix(vm): harden workspace and receipt boundaries --- .../integrations/vm_agent_runtime.py | 154 ++++++++++++++++-- .../integrations/test_vm_agent_runtime.py | 133 +++++++++++++++ 2 files changed, 274 insertions(+), 13 deletions(-) diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 04f1397488..400d2bcb71 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -152,12 +152,42 @@ def _path_text(value: str | os.PathLike[str], label: str) -> str: return text +def _filesystem_is_case_insensitive(path: Path) -> bool: + """Detect case folding without creating a probe entry on the host filesystem.""" + for component in (path, *path.parents): + variant_name = component.name.swapcase() + if not component.name or variant_name == component.name: + continue + try: + if os.path.samefile(component, component.with_name(variant_name)): + return True + except OSError: + pass + + try: + with os.scandir(path) as entries: + for entry in entries: + variant_name = entry.name.swapcase() + if variant_name == entry.name: + continue + variant = os.path.join(path, variant_name) + try: + if os.path.samefile(entry.path, variant): + return True + except OSError: + continue + except OSError: + pass + return False + + @dataclass(frozen=True, slots=True) class VMWorkspaceMapper: """Map paths between one approved host root and one VM root.""" host_root: Path vm_root: PurePosixPath + _case_insensitive: bool = field(init=False, repr=False, compare=False) def __init__(self, host_root: str | Path, vm_root: str) -> None: host_text = _path_text(host_root, "host_root") @@ -173,11 +203,12 @@ def __init__(self, host_root: str | Path, vm_root: str) -> None: raise VMPathError("vm_root must not contain parent traversal") object.__setattr__(self, "host_root", host) object.__setattr__(self, "vm_root", vm) + object.__setattr__(self, "_case_insensitive", _filesystem_is_case_insensitive(host)) def map_host_path(self, path: str | Path) -> str: """Map an approved host path to its VM path, rejecting escapes.""" resolved = self._resolve_host_path(path) - relative = resolved.relative_to(self.host_root) + relative = self._relative_host_path(resolved) return str(self.vm_root / PurePosixPath(relative.as_posix())) def map_vm_path(self, path: str) -> Path: @@ -193,7 +224,7 @@ def map_vm_path(self, path: str) -> Path: raise VMPathError(f"VM path escapes approved workspace: {path}") from exc resolved = (self.host_root / Path(*relative.parts)).resolve(strict=False) try: - resolved.relative_to(self.host_root) + self._relative_host_path(resolved) except ValueError as exc: raise VMPathError(f"VM path escapes approved workspace: {path}") from exc return resolved @@ -213,7 +244,11 @@ def resolve_dispatch_workspace(self, path: str | Path) -> Path: resolved_host = candidate.resolve(strict=False) except (OSError, RuntimeError, ValueError) as exc: raise VMPathError(f"dispatch workspace is invalid: {path!s}") from exc - if resolved_host.is_relative_to(self.host_root): + try: + self._relative_host_path(resolved_host) + except ValueError: + pass + else: return resolved_host vm_candidate = PurePosixPath(text) if vm_candidate.is_relative_to(self.vm_root): @@ -224,7 +259,7 @@ def resolve_dispatch_workspace(self, path: str | Path) -> Path: def host_relative(self, path: str | Path) -> str: """Return a stable workspace-relative path for an artifact receipt.""" - return self._resolve_host_path(path).relative_to(self.host_root).as_posix() + return self._relative_host_path(self._resolve_host_path(path)).as_posix() def resolve_artifact_path(self, path: str | Path) -> Path: """Resolve a host or VM artifact path using one containment rule.""" @@ -241,7 +276,11 @@ def resolve_artifact_path(self, path: str | Path) -> Path: resolved_host = candidate.resolve(strict=False) except (OSError, RuntimeError, ValueError) as exc: raise VMPathError(f"artifact path is invalid: {path!s}") from exc - if resolved_host.is_relative_to(self.host_root): + try: + self._relative_host_path(resolved_host) + except ValueError: + pass + else: return resolved_host vm_candidate = PurePosixPath(text) if vm_candidate.is_absolute() and vm_candidate.is_relative_to(self.vm_root): @@ -258,11 +297,32 @@ def _resolve_host_path(self, path: str | Path) -> Path: except (OSError, RuntimeError, ValueError) as exc: raise VMPathError(f"host path is invalid: {path!s}") from exc try: - resolved.relative_to(self.host_root) + self._relative_host_path(resolved) except ValueError as exc: raise VMPathError(f"host path escapes approved workspace: {path!s}") from exc return resolved + def _relative_host_path(self, path: Path) -> Path: + """Return a relative path while honoring verified filesystem case folding.""" + try: + return path.relative_to(self.host_root) + except ValueError: + if not self._case_insensitive: + raise + root_parts = self.host_root.parts + path_parts = path.parts + if len(path_parts) < len(root_parts) or tuple( + part.casefold() for part in path_parts[: len(root_parts)] + ) != tuple(part.casefold() for part in root_parts): + raise ValueError + root_spelling = type(self.host_root)(*path_parts[: len(root_parts)]) + try: + if not os.path.samefile(root_spelling, self.host_root): + raise ValueError + except OSError as exc: + raise ValueError from exc + return type(self.host_root)(*path_parts[len(root_parts) :]) + @dataclass(frozen=True, slots=True) class VMExecutionRequest: @@ -349,6 +409,9 @@ def to_dict(self) -> dict[str, Any]: _RECEIPT_STATUSES = _TERMINAL_STATUSES | frozenset( {"running", "disconnected", "recovery_required", "timed_out"} ) +_MAX_RAW_RECEIPT_CHARS = 256 * 1024 +_MAX_BOUNDED_JSON_NODES = 4096 +_RAW_PAYLOAD_TRUNCATION_MARKER = "...[raw payload truncated]" @dataclass(frozen=True, slots=True) @@ -544,7 +607,7 @@ def _path(self, key: str) -> Path: def get(self, key: str) -> VMExecutionReceipt | None: path = self._path(key) try: - return VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) + return VMExecutionReceipt.from_dict(self._read_json(path)) except FileNotFoundError: return None except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: @@ -576,7 +639,12 @@ def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | Non try: os.link(temporary, path) except FileExistsError: - return self.get(receipt.idempotency_key) + existing = self.get(receipt.idempotency_key) + if existing is None: + raise VMRuntimeError( + "VM receipt claim disappeared; refusing to replay the command" + ) + return existing self._index_put(receipt, path.name) return None finally: @@ -596,7 +664,7 @@ def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionRe for path_name in path_names: path = self.directory / path_name try: - receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) + receipt = VMExecutionReceipt.from_dict(self._read_json(path)) except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: raise VMRuntimeError(f"corrupt VM receipt file {path.name!r}") from exc if receipt.dispatch_id == dispatch_id and ( @@ -618,7 +686,7 @@ def _build_find_index(self, directory_mtime_ns: int) -> None: paths: dict[str, tuple[str, str]] = {} for path in self.directory.glob("*.json"): try: - receipt = VMExecutionReceipt.from_dict(json.loads(path.read_text(encoding="utf-8"))) + receipt = VMExecutionReceipt.from_dict(self._read_json(path)) except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: raise VMRuntimeError(f"corrupt VM receipt file {path.name!r}") from exc identity = (receipt.dispatch_id, receipt.session_id) @@ -654,6 +722,19 @@ def _directory_mtime_ns(self) -> int: except OSError as exc: raise VMRuntimeError("VM receipt directory cannot be inspected") from exc + @staticmethod + def _read_json(path: Path) -> Any: + """Read a receipt without following a replacement symlink.""" + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags) + try: + with os.fdopen(descriptor, "r", encoding="utf-8") as handle: + descriptor = -1 + return json.load(handle) + finally: + if descriptor >= 0: + os.close(descriptor) + class VMTransport(Protocol): """Transport-neutral command/turn execution surface.""" @@ -1225,6 +1306,9 @@ def _receipt_from_response( ) if "stderr" in raw_payload: raw_payload["stderr"] = stderr + bounded_raw = _bounded_json_value(raw_payload, _MAX_RAW_RECEIPT_CHARS) + if not isinstance(bounded_raw, Mapping): + bounded_raw = {"value": _RAW_PAYLOAD_TRUNCATION_MARKER} return replace( receipt, status=status, @@ -1239,7 +1323,7 @@ def _receipt_from_response( error=response_error, recovery_required=status in {"running", "disconnected", "accepted", "queued"}, finished_at=None if status == "running" else _now(), - raw=raw_payload, + raw=bounded_raw, ) def _store_recovery(self, receipt: VMExecutionReceipt, error: str) -> VMExecutionReceipt: @@ -1591,15 +1675,59 @@ def _truncate_text(value: str, limit: int, *, label: str = "stdout") -> tuple[st def _json_value(value: Any) -> Any: + return _bounded_json_value(value, _MAX_RAW_RECEIPT_CHARS) + + +def _bounded_json_value( + value: Any, + budget: int, + depth: int = 0, + _remaining_nodes: list[int] | None = None, +) -> Any: + """Copy provider evidence while keeping durable receipt growth bounded.""" + if _remaining_nodes is None: + _remaining_nodes = [_MAX_BOUNDED_JSON_NODES] + if budget <= 0 or depth >= 8 or _remaining_nodes[0] <= 0: + return _RAW_PAYLOAD_TRUNCATION_MARKER + _remaining_nodes[0] -= 1 if isinstance(value, Mapping): - return {str(key): _json_value(item) for key, item in value.items()} + result: dict[str, Any] = {} + item_budget = max(1, budget // 64) + for index, (key, item) in enumerate(value.items()): + if index >= 64: + result["_truncated_items"] = _RAW_PAYLOAD_TRUNCATION_MARKER + break + key_text = str(key) + if len(key_text) > 256: + key_text = key_text[:232] + _RAW_PAYLOAD_TRUNCATION_MARKER + result[key_text] = _bounded_json_value(item, item_budget, depth + 1, _remaining_nodes) + if _json_size(result) > budget: + return _RAW_PAYLOAD_TRUNCATION_MARKER + return result if isinstance(value, (list, tuple)): - return [_json_value(item) for item in value] + result = [ + _bounded_json_value(item, max(1, budget // 64), depth + 1, _remaining_nodes) + for item in value[:64] + ] + if len(value) > 64: + result.append(_RAW_PAYLOAD_TRUNCATION_MARKER) + if _json_size(result) > budget: + return _RAW_PAYLOAD_TRUNCATION_MARKER + return result + if isinstance(value, str): + if len(value) <= budget: + return value + marker_length = len(_RAW_PAYLOAD_TRUNCATION_MARKER) + return value[: max(0, budget - marker_length)] + _RAW_PAYLOAD_TRUNCATION_MARKER if isinstance(value, (str, int, float, bool)) or value is None: return value return str(value) +def _json_size(value: Any) -> int: + return len(json.dumps(value, ensure_ascii=False)) + + __all__ = [ "CommandVMTransport", "JsonVMReceiptStore", diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 207742241a..e8cce5b6ed 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -107,6 +107,52 @@ def test_workspace_mapping_resolves_symlink_escapes(tmp_path: Path) -> None: mapper.map_host_path("link") +def test_workspace_mapping_accepts_case_variant_existing_path_on_casefolding_fs( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import ouroboros.integrations.vm_agent_runtime as runtime_module + + workspace = tmp_path / "CaseRoot" + payload = workspace / "Payload" + payload.mkdir(parents=True) + monkeypatch.setattr( + runtime_module.os.path, + "samefile", + lambda left, right: Path(left).as_posix().casefold() == Path(right).as_posix().casefold(), + ) + mapper = VMWorkspaceMapper(workspace, "/workspace") + + assert mapper.map_host_path(str(workspace).lower() + "/payload") == "/workspace/payload" + assert ( + mapper.resolve_dispatch_workspace(str(workspace).lower()).as_posix().casefold() + == str(workspace).casefold() + ) + assert ( + mapper.resolve_artifact_path(str(workspace).lower() + "/payload").as_posix().casefold() + == str(payload).casefold() + ) + + +def test_workspace_mapping_detects_casefolding_from_parent_for_empty_numeric_root( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import ouroboros.integrations.vm_agent_runtime as runtime_module + + workspace = tmp_path / "123" + workspace.mkdir() + monkeypatch.setattr( + runtime_module.os.path, + "samefile", + lambda left, right: Path(left).as_posix().casefold() == Path(right).as_posix().casefold(), + ) + mapper = VMWorkspaceMapper(workspace, "/workspace") + + variant = str(workspace).upper() + "/missing" + assert mapper.map_host_path(variant) == "/workspace/missing" + + def test_overlapping_host_and_vm_roots_keep_absolute_host_paths_unambiguous( tmp_path: Path, ) -> None: @@ -438,6 +484,53 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] assert receipt.raw["stderr"] == receipt.stderr +@pytest.mark.asyncio +async def test_nested_provider_metadata_is_bounded_before_receipt_persistence( + tmp_path: Path, +) -> None: + class VerboseCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return { + "status": "completed", + "exit_code": 0, + "metadata": {"debug": "x" * (512 * 1024)}, + } + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(VerboseCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verbose", dispatch_id="metadata", session_id="s") + + encoded = json.dumps(receipt.to_dict()["raw"]) + assert len(encoded) <= 256 * 1024 + assert receipt.raw["metadata"]["debug"].endswith("raw payload truncated]") + + +@pytest.mark.asyncio +async def test_wide_nested_provider_metadata_is_bounded_by_node_budget( + tmp_path: Path, +) -> None: + nested: dict[str, Any] = {"leaf": "value"} + for _ in range(8): + nested = {str(index): nested for index in range(64)} + + class VerboseCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0, "metadata": nested} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(VerboseCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("wide", dispatch_id="wide", session_id="s") + + encoded = json.dumps(receipt.to_dict()["raw"]) + assert len(encoded) <= 256 * 1024 + + @pytest.mark.asyncio async def test_command_error_payload_is_failed_instead_of_defaulting_to_success( tmp_path: Path, @@ -685,6 +778,36 @@ async def test_idempotency_key_cannot_be_reused_for_a_different_command(tmp_path assert len(target.calls) == 1 +def test_json_receipt_claim_disappearance_fails_closed(tmp_path: Path) -> None: + class HidingReceiptStore(JsonVMReceiptStore): + def __init__(self, directory: Path) -> None: + super().__init__(directory) + self.hide_receipt = False + + def get(self, key: str) -> VMExecutionReceipt | None: + if self.hide_receipt: + return None + return super().get(key) + + store = HidingReceiptStore(tmp_path / "receipts") + receipt = VMExecutionReceipt( + dispatch_id="claim", + session_id="s", + idempotency_key="s:claim", + status="running", + command="echo claim", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + started_at="now", + ) + store.put(receipt) + store.hide_receipt = True + + with pytest.raises(VMRuntimeError, match="claim disappeared"): + store.put_if_absent(receipt) + + class DisconnectingTransport: def __init__(self) -> None: self.execute_calls = 0 @@ -804,6 +927,16 @@ def test_corrupt_json_receipt_fails_closed(tmp_path: Path) -> None: store.get("session:dispatch") +def test_json_receipt_store_rejects_symlinked_receipts(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + outside = tmp_path / "outside.json" + outside.write_text("{}", encoding="utf-8") + store._path("session:dispatch").symlink_to(outside) + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt"): + store.get("session:dispatch") + + def test_find_fails_closed_when_any_json_receipt_is_corrupt(tmp_path: Path) -> None: store = JsonVMReceiptStore(tmp_path / "receipts") (store.directory / "corrupt.json").write_text("not json", encoding="utf-8") From 067db61a9f147e73017db1c811df40942bbf23cd Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 02:54:32 +0900 Subject: [PATCH 28/41] fix(vm): close round eight runtime audit gaps --- .../integrations/vm_agent_runtime.py | 62 +++++++++++++++---- .../integrations/test_vm_agent_runtime.py | 48 ++++++++++++++ .../test_vm_agent_runtime_round17.py | 21 +++++++ 3 files changed, 119 insertions(+), 12 deletions(-) diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 400d2bcb71..2e76b68767 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -172,8 +172,13 @@ def _filesystem_is_case_insensitive(path: Path) -> bool: continue variant = os.path.join(path, variant_name) try: - if os.path.samefile(entry.path, variant): - return True + entry.stat(follow_symlinks=True) + except OSError: + continue + try: + return os.path.samefile(entry.path, variant) + except FileNotFoundError: + return False except OSError: continue except OSError: @@ -1064,6 +1069,7 @@ def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: host_path, self.max_artifact_bytes - total_bytes, workspace_root=self.workspace.host_root, + relative_path=Path(relative), ) except OSError as exc: raise VMPathError(f"artifact path cannot be read: {path}") from exc @@ -1589,10 +1595,16 @@ def _hash_file( max_bytes: int, *, workspace_root: Path | None = None, + relative_path: Path | None = None, ) -> tuple[int, str]: """Hash a file without reopening a parent symlink outside the workspace.""" if workspace_root is not None and os.open in os.supports_dir_fd: - return _hash_file_beneath(path, workspace_root, max_bytes) + return _hash_file_beneath( + path, + workspace_root, + max_bytes, + relative_path=relative_path, + ) try: if path.stat().st_size > max_bytes: raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") @@ -1610,12 +1622,23 @@ def _hash_file( return size, digest.hexdigest() -def _hash_file_beneath(path: Path, workspace_root: Path, max_bytes: int) -> tuple[int, str]: +def _hash_file_beneath( + path: Path, + workspace_root: Path, + max_bytes: int, + *, + relative_path: Path | None = None, +) -> tuple[int, str]: """Open every workspace component with ``O_NOFOLLOW`` where supported.""" - try: - relative = path.relative_to(workspace_root) - except ValueError as exc: - raise VMPathError(f"artifact path escapes approved workspace: {path}") from exc + if relative_path is None: + try: + relative = path.relative_to(workspace_root) + except ValueError as exc: + raise VMPathError(f"artifact path escapes approved workspace: {path}") from exc + else: + relative = relative_path + if relative.is_absolute() or ".." in relative.parts: + raise VMPathError(f"artifact path escapes approved workspace: {path}") if not relative.parts: raise VMPathError(f"artifact path is not a regular file: {path}") @@ -1715,17 +1738,32 @@ def _bounded_json_value( return _RAW_PAYLOAD_TRUNCATION_MARKER return result if isinstance(value, str): - if len(value) <= budget: + if _json_size(value) <= budget: return value - marker_length = len(_RAW_PAYLOAD_TRUNCATION_MARKER) - return value[: max(0, budget - marker_length)] + _RAW_PAYLOAD_TRUNCATION_MARKER + return _truncate_json_string(value, budget) if isinstance(value, (str, int, float, bool)) or value is None: return value return str(value) def _json_size(value: Any) -> int: - return len(json.dumps(value, ensure_ascii=False)) + return len(json.dumps(value, ensure_ascii=False).encode("utf-8")) + + +def _truncate_json_string(value: str, budget: int) -> str: + """Keep a JSON string within a UTF-8 byte budget without splitting code points.""" + marker = _RAW_PAYLOAD_TRUNCATION_MARKER + if _json_size(marker) > budget: + return "" + low = 0 + high = len(value) + while low < high: + midpoint = (low + high + 1) // 2 + if _json_size(value[:midpoint] + marker) <= budget: + low = midpoint + else: + high = midpoint - 1 + return value[:low] + marker __all__ = [ diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index e8cce5b6ed..2832cd1c17 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -153,6 +153,30 @@ def test_workspace_mapping_detects_casefolding_from_parent_for_empty_numeric_roo assert mapper.map_host_path(variant) == "/workspace/missing" +def test_casefold_detector_stops_after_the_first_existing_alpha_entry( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import ouroboros.integrations.vm_agent_runtime as runtime_module + + workspace = tmp_path / "123" + workspace.mkdir() + (workspace / "First").write_text("one", encoding="utf-8") + (workspace / "Second").write_text("two", encoding="utf-8") + child_checks: list[Path] = [] + + def samefile(left: str | Path, right: str | Path) -> bool: + if Path(left).parent == workspace: + child_checks.append(Path(left)) + return False + + monkeypatch.setattr(runtime_module.os.path, "samefile", samefile) + + assert runtime_module._filesystem_is_case_insensitive(workspace) is False + assert len(child_checks) == 1 + assert child_checks[0] in {workspace / "First", workspace / "Second"} + + def test_overlapping_host_and_vm_roots_keep_absolute_host_paths_unambiguous( tmp_path: Path, ) -> None: @@ -484,6 +508,30 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] assert receipt.raw["stderr"] == receipt.stderr +@pytest.mark.asyncio +async def test_unicode_provider_metadata_respects_the_utf8_receipt_ceiling( + tmp_path: Path, +) -> None: + class UnicodeCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return { + "status": "completed", + "exit_code": 0, + "metadata": {"debug": "🚀" * (256 * 1024)}, + } + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(UnicodeCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("unicode", dispatch_id="unicode", session_id="s") + + assert len(json.dumps(receipt.to_dict()["raw"], ensure_ascii=False).encode("utf-8")) <= ( + 256 * 1024 + ) + + @pytest.mark.asyncio async def test_nested_provider_metadata_is_bounded_before_receipt_persistence( tmp_path: Path, diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py index f824af9e73..c14043dc59 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round17.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import os from pathlib import Path from typing import Any @@ -47,6 +48,26 @@ def test_artifact_hash_rejects_a_parent_symlink_after_path_resolution( _hash_file(resolved_target, 1024, workspace_root=workspace) +def test_artifact_hash_uses_the_verified_relative_path_for_case_variant_spelling( + tmp_path: Path, +) -> None: + workspace = tmp_path / "CaseRoot" + target = workspace / "nested" / "result.txt" + target.parent.mkdir(parents=True) + target.write_text("inside", encoding="utf-8") + + case_variant = Path(str(workspace).lower()) / "nested" / "result.txt" + size, digest = _hash_file( + case_variant, + 1024, + workspace_root=workspace, + relative_path=Path("nested/result.txt"), + ) + + assert size == len("inside") + assert digest == hashlib.sha256(b"inside").hexdigest() + + @pytest.mark.asyncio async def test_resume_requires_a_session_binding_for_tenant_isolation(tmp_path: Path) -> None: class Disconnected: From 4fbd057e5c5ab856a3b9d0cd28ed672fe6f67efa Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 03:36:41 +0900 Subject: [PATCH 29/41] fix(vm): verify case-folded workspace roots by identity --- .../integrations/vm_agent_runtime.py | 46 ++----------------- .../integrations/test_vm_agent_runtime.py | 40 ++++------------ 2 files changed, 15 insertions(+), 71 deletions(-) diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 2e76b68767..9bbbf9eb38 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -152,47 +152,12 @@ def _path_text(value: str | os.PathLike[str], label: str) -> str: return text -def _filesystem_is_case_insensitive(path: Path) -> bool: - """Detect case folding without creating a probe entry on the host filesystem.""" - for component in (path, *path.parents): - variant_name = component.name.swapcase() - if not component.name or variant_name == component.name: - continue - try: - if os.path.samefile(component, component.with_name(variant_name)): - return True - except OSError: - pass - - try: - with os.scandir(path) as entries: - for entry in entries: - variant_name = entry.name.swapcase() - if variant_name == entry.name: - continue - variant = os.path.join(path, variant_name) - try: - entry.stat(follow_symlinks=True) - except OSError: - continue - try: - return os.path.samefile(entry.path, variant) - except FileNotFoundError: - return False - except OSError: - continue - except OSError: - pass - return False - - @dataclass(frozen=True, slots=True) class VMWorkspaceMapper: """Map paths between one approved host root and one VM root.""" host_root: Path vm_root: PurePosixPath - _case_insensitive: bool = field(init=False, repr=False, compare=False) def __init__(self, host_root: str | Path, vm_root: str) -> None: host_text = _path_text(host_root, "host_root") @@ -208,7 +173,6 @@ def __init__(self, host_root: str | Path, vm_root: str) -> None: raise VMPathError("vm_root must not contain parent traversal") object.__setattr__(self, "host_root", host) object.__setattr__(self, "vm_root", vm) - object.__setattr__(self, "_case_insensitive", _filesystem_is_case_insensitive(host)) def map_host_path(self, path: str | Path) -> str: """Map an approved host path to its VM path, rejecting escapes.""" @@ -308,12 +272,11 @@ def _resolve_host_path(self, path: str | Path) -> Path: return resolved def _relative_host_path(self, path: Path) -> Path: - """Return a relative path while honoring verified filesystem case folding.""" + """Return a relative path while verifying case-folded roots by identity.""" try: return path.relative_to(self.host_root) except ValueError: - if not self._case_insensitive: - raise + pass root_parts = self.host_root.parts path_parts = path.parts if len(path_parts) < len(root_parts) or tuple( @@ -322,10 +285,11 @@ def _relative_host_path(self, path: Path) -> Path: raise ValueError root_spelling = type(self.host_root)(*path_parts[: len(root_parts)]) try: - if not os.path.samefile(root_spelling, self.host_root): - raise ValueError + same_root = os.path.samefile(root_spelling, self.host_root) except OSError as exc: raise ValueError from exc + if not same_root: + raise ValueError return type(self.host_root)(*path_parts[len(root_parts) :]) diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 2832cd1c17..94c4ac9d95 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -116,10 +116,14 @@ def test_workspace_mapping_accepts_case_variant_existing_path_on_casefolding_fs( workspace = tmp_path / "CaseRoot" payload = workspace / "Payload" payload.mkdir(parents=True) + + def samefile(left: str | Path, right: str | Path) -> bool: + return Path(left).as_posix().casefold() == Path(right).as_posix().casefold() + monkeypatch.setattr( runtime_module.os.path, "samefile", - lambda left, right: Path(left).as_posix().casefold() == Path(right).as_posix().casefold(), + samefile, ) mapper = VMWorkspaceMapper(workspace, "/workspace") @@ -134,47 +138,23 @@ def test_workspace_mapping_accepts_case_variant_existing_path_on_casefolding_fs( ) -def test_workspace_mapping_detects_casefolding_from_parent_for_empty_numeric_root( +def test_workspace_mapping_rejects_case_variant_without_samefile_identity( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: import ouroboros.integrations.vm_agent_runtime as runtime_module - workspace = tmp_path / "123" + workspace = tmp_path / "CaseRoot" workspace.mkdir() monkeypatch.setattr( runtime_module.os.path, "samefile", - lambda left, right: Path(left).as_posix().casefold() == Path(right).as_posix().casefold(), + lambda _left, _right: False, ) mapper = VMWorkspaceMapper(workspace, "/workspace") - variant = str(workspace).upper() + "/missing" - assert mapper.map_host_path(variant) == "/workspace/missing" - - -def test_casefold_detector_stops_after_the_first_existing_alpha_entry( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - import ouroboros.integrations.vm_agent_runtime as runtime_module - - workspace = tmp_path / "123" - workspace.mkdir() - (workspace / "First").write_text("one", encoding="utf-8") - (workspace / "Second").write_text("two", encoding="utf-8") - child_checks: list[Path] = [] - - def samefile(left: str | Path, right: str | Path) -> bool: - if Path(left).parent == workspace: - child_checks.append(Path(left)) - return False - - monkeypatch.setattr(runtime_module.os.path, "samefile", samefile) - - assert runtime_module._filesystem_is_case_insensitive(workspace) is False - assert len(child_checks) == 1 - assert child_checks[0] in {workspace / "First", workspace / "Second"} + with pytest.raises(VMPathError, match="escapes"): + mapper.map_host_path(str(workspace).lower() + "/payload") def test_overlapping_host_and_vm_roots_keep_absolute_host_paths_unambiguous( From 10d1ca95e0b73ba0bd2e8b4cd2987b21fba38e2e Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 04:29:20 +0900 Subject: [PATCH 30/41] fix(vm): close round eleven runtime audit gaps --- .../integrations/personal_agent_host.py | 31 ++++++++++++- .../integrations/vm_agent_runtime.py | 45 ++++++++++++++++--- .../integrations/test_personal_agent_host.py | 36 +++++++++++++++ .../integrations/test_vm_agent_runtime.py | 22 +++++++++ .../test_vm_agent_runtime_round17.py | 32 +++++++++++++ 5 files changed, 158 insertions(+), 8 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 34b61dbb0b..a12455bca2 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -330,6 +330,9 @@ def reserve_start( def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Publish the receipt for a previously reserved start key.""" + def abort_start(self, key: str) -> None: + """Release a reservation when the host explicitly rejected the start.""" + class MemoryHostReceiptStore: """Small in-memory store for hosts that do not need process restart recovery.""" @@ -368,6 +371,10 @@ def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecuti self._receipts[key] = receipt return receipt + def abort_start(self, key: str) -> None: + if isinstance(self._receipts.get(key), HostStartReservation): + del self._receipts[key] + class JsonHostReceiptStore: """Atomic JSON store for host receipts that must survive process restarts.""" @@ -452,8 +459,21 @@ def reserve_start( def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Replace the reservation with the first durable start receipt.""" + existing = self._read_record(key) + if isinstance(existing, HostExecutionReceipt): + return existing + if not isinstance(existing, HostStartReservation): + raise HostAdapterError(f"host start reservation disappeared for {key!r}") self.put(key, receipt) - return receipt + return self.get(key) or receipt + + def abort_start(self, key: str) -> None: + path = self._path(key) + try: + if isinstance(self._read_record(key), HostStartReservation): + path.unlink() + except FileNotFoundError: + return def _read_record(self, key: str) -> HostExecutionReceipt | HostStartReservation | None: path = self._path(key) @@ -856,7 +876,14 @@ async def start( persisted = await self._wait_for_start_receipt(key, state) self._start_receipts[key] = persisted return persisted - response = await self._call(START_AUTO_TOOL, arguments) + try: + response = await self._call(START_AUTO_TOOL, arguments) + except HostAdapterError as exc: + if exc.response is not None: + abort = getattr(self.receipt_store, "abort_start", None) + if callable(abort): + abort(key) + raise payload = response.payload runtime_backend = payload.get("runtime_backend") if ( diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 9bbbf9eb38..44727ec364 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -305,6 +305,7 @@ class VMExecutionRequest: timeout_seconds: float = 300.0 idempotency_key: str | None = None artifact_paths: tuple[str, ...] = () + vm_artifact_paths: tuple[str, ...] | None = None def __post_init__(self) -> None: for name, value in ( @@ -342,6 +343,18 @@ def __post_init__(self) -> None: raise VMRuntimeError("artifact_paths must contain non-empty text paths") if "\x00" in path: raise VMRuntimeError("artifact_paths must not contain NUL bytes") + if self.vm_artifact_paths is not None: + if isinstance(self.vm_artifact_paths, (str, bytes)) or not isinstance( + self.vm_artifact_paths, Iterable + ): + raise VMRuntimeError("vm_artifact_paths must be an iterable of text paths") + vm_paths = tuple(self.vm_artifact_paths) + object.__setattr__(self, "vm_artifact_paths", vm_paths) + for path in vm_paths: + if not isinstance(path, str) or not path.strip(): + raise VMRuntimeError("vm_artifact_paths must contain non-empty text paths") + if "\x00" in path: + raise VMRuntimeError("vm_artifact_paths must not contain NUL bytes") @property def correlation_key(self) -> str: @@ -791,6 +804,11 @@ class MCPVMTransport: cancel_tool: str = "vm.cancel" async def execute(self, request: VMExecutionRequest) -> Any: + artifact_paths = ( + request.artifact_paths + if request.vm_artifact_paths is None + else request.vm_artifact_paths + ) return await self._call( self.execute_tool, { @@ -801,7 +819,7 @@ async def execute(self, request: VMExecutionRequest) -> Any: "idempotency_key": request.correlation_key, "dispatch_id": request.dispatch_id, "session_id": request.session_id, - "artifact_paths": list(request.artifact_paths), + "artifact_paths": list(artifact_paths), }, ) @@ -1212,8 +1230,12 @@ async def _store_timeout( receipt, status="timed_out", execution_id=execution_id, - error=f"{detail}{cleanup_error or ''}", - recovery_required=execution_id is not None, + error=( + f"{detail}{cleanup_error or ''}" + if execution_id is not None + else f"{detail}; remote execution identity is unknown; recovery required" + ), + recovery_required=True, finished_at=_now(), ) self.receipt_store.put(updated) @@ -1223,12 +1245,15 @@ def _prepare_request(self, request: VMExecutionRequest) -> VMExecutionRequest: host_workspace = request.host_workspace or str(self.workspace.host_root) resolved_workspace = self.workspace._resolve_host_path(host_workspace) vm_workspace = self.workspace.map_host_path(resolved_workspace) - for artifact in request.artifact_paths: - self.workspace.resolve_artifact_path(artifact) + vm_artifact_paths = tuple( + self.workspace.map_host_path(self.workspace.resolve_artifact_path(path)) + for path in request.artifact_paths + ) return replace( request, host_workspace=str(resolved_workspace), vm_workspace=vm_workspace, + vm_artifact_paths=vm_artifact_paths, ) def _receipt_from_response( @@ -1608,7 +1633,15 @@ def _hash_file_beneath( nofollow = getattr(os, "O_NOFOLLOW", 0) directory = getattr(os, "O_DIRECTORY", 0) - root_fd = os.open(workspace_root, os.O_RDONLY | directory | nofollow) + try: + expected_root = os.stat(workspace_root, follow_symlinks=False) + root_fd = os.open(workspace_root, os.O_RDONLY | directory | nofollow) + actual_root = os.fstat(root_fd) + except OSError as exc: + raise VMPathError(f"artifact workspace cannot be opened: {workspace_root}") from exc + if (actual_root.st_dev, actual_root.st_ino) != (expected_root.st_dev, expected_root.st_ino): + os.close(root_fd) + raise VMPathError(f"artifact workspace changed during access: {workspace_root}") parent_fd = root_fd opened_parents: list[int] = [] try: diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index febab420dc..c2b8457835 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -303,6 +303,42 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 1 +@pytest.mark.asyncio +async def test_explicit_start_rejection_releases_the_reservation_for_retry( + tmp_path: Path, +) -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + if calls == 1: + return { + "isError": True, + "content": [{"type": "text", "text": "temporary rejection"}], + } + return { + "meta": { + "job_id": "job-retry", + "auto_session_id": "auto-retry", + "runtime_backend": "host", + "status": "queued", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + with pytest.raises(HostAdapterError, match="temporary rejection"): + await adapter.start("/ouroboros retry this request", host_session_id="retry") + + receipt = await adapter.start("/ouroboros retry this request", host_session_id="retry") + + assert receipt is not None + assert receipt.job_id == "job-retry" + assert calls == 2 + + @pytest.mark.asyncio async def test_start_supports_a_legacy_receipt_store_without_atomic_claim() -> None: class LegacyReceiptStore: diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 94c4ac9d95..4c92d13fc3 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -372,6 +372,26 @@ async def test_mcp_transport_uses_a_generic_public_command_surface(tmp_path: Pat assert arguments["idempotency_key"] == "session-2:dispatch-2" +@pytest.mark.asyncio +async def test_mcp_transport_maps_host_artifacts_to_vm_paths(tmp_path: Path) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + target = RecordingMCP() + runtime = VMPersonalAgentRuntime( + MCPVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/cloud/workspace"), + ) + + await runtime.execute_command( + "pytest -q", + dispatch_id="artifact-dispatch", + session_id="artifact-session", + artifact_paths=(str(artifact),), + ) + + assert target.calls[0][1]["artifact_paths"] == ["/cloud/workspace/result.json"] + + @pytest.mark.asyncio async def test_mcp_transport_unwraps_internal_result_envelopes(tmp_path: Path) -> None: class ResultMCP: @@ -1033,6 +1053,8 @@ async def execute(self, _request: Any) -> Any: ) assert timed_out.status == "timed_out" + assert timed_out.recovery_required is True + assert "recovery required" in (timed_out.error or "") assert recovered.status == "recovery_required" assert "refusing to replay" in (recovered.error or "") diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py index c14043dc59..68cd2ad537 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round17.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -15,6 +15,7 @@ parse_explicit_invocation, ) from ouroboros.integrations.vm_agent_runtime import ( + VMPathError, VMPersonalAgentRuntime, VMRuntimeError, VMTransportDisconnected, @@ -68,6 +69,37 @@ def test_artifact_hash_uses_the_verified_relative_path_for_case_variant_spelling assert digest == hashlib.sha256(b"inside").hexdigest() +def test_artifact_hash_rejects_workspace_replacement_before_open( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + if os.open not in os.supports_dir_fd: + pytest.skip("directory-relative opens are unavailable") + + workspace = tmp_path / "workspace" + workspace.mkdir() + target = workspace / "result.txt" + target.write_text("inside", encoding="utf-8") + original = tmp_path / "original-workspace" + real_stat = os.stat + expected_stat = real_stat(workspace, follow_symlinks=False) + swapped = False + + def racing_stat(path: Any, *args: Any, **kwargs: Any) -> os.stat_result: + nonlocal swapped + if Path(path) == workspace and not swapped: + workspace.rename(original) + workspace.mkdir() + (workspace / "result.txt").write_text("outside", encoding="utf-8") + swapped = True + return expected_stat + return real_stat(path, *args, **kwargs) + + monkeypatch.setattr(os, "stat", racing_stat) + with pytest.raises(VMPathError, match="changed during access"): + _hash_file(target, 1024, workspace_root=workspace) + + @pytest.mark.asyncio async def test_resume_requires_a_session_binding_for_tenant_isolation(tmp_path: Path) -> None: class Disconnected: From 48ba709c34cd1eaa033e4a6190ec65392fed0547 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 04:59:54 +0900 Subject: [PATCH 31/41] fix(vm): close runtime audit resource gaps --- .../integrations/personal_agent_host.py | 15 +++++++- .../integrations/vm_agent_runtime.py | 3 ++ .../integrations/test_personal_agent_host.py | 10 ++++++ .../test_vm_agent_runtime_round17.py | 35 +++++++++++++++++++ 4 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index a12455bca2..6416972c00 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -478,7 +478,7 @@ def abort_start(self, key: str) -> None: def _read_record(self, key: str) -> HostExecutionReceipt | HostStartReservation | None: path = self._path(key) try: - raw = json.loads(path.read_text(encoding="utf-8")) + raw = self._read_json(path) except FileNotFoundError: return None except (OSError, TypeError, ValueError, json.JSONDecodeError) as exc: @@ -498,6 +498,19 @@ def _read_record(self, key: str) -> HostExecutionReceipt | HostStartReservation return HostStartReservation(key, dict(arguments), created_at) return HostExecutionReceipt.from_dict(raw) + @staticmethod + def _read_json(path: Path) -> Any: + """Read a receipt without following a replacement symlink.""" + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags) + try: + with os.fdopen(descriptor, "r", encoding="utf-8") as handle: + descriptor = -1 + return json.load(handle) + finally: + if descriptor >= 0: + os.close(descriptor) + @dataclass(slots=True) class MCPToolTransport: diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 44727ec364..90693c56f0 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -1633,11 +1633,14 @@ def _hash_file_beneath( nofollow = getattr(os, "O_NOFOLLOW", 0) directory = getattr(os, "O_DIRECTORY", 0) + root_fd = -1 try: expected_root = os.stat(workspace_root, follow_symlinks=False) root_fd = os.open(workspace_root, os.O_RDONLY | directory | nofollow) actual_root = os.fstat(root_fd) except OSError as exc: + if root_fd >= 0: + os.close(root_fd) raise VMPathError(f"artifact workspace cannot be opened: {workspace_root}") from exc if (actual_root.st_dev, actual_root.st_ino) != (expected_root.st_dev, expected_root.st_ino): os.close(root_fd) diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index c2b8457835..4cace93e49 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -303,6 +303,16 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 1 +def test_json_store_rejects_symlinked_receipt_reads(tmp_path: Path) -> None: + store = JsonHostReceiptStore(tmp_path / "host-receipts") + outside = tmp_path / "outside.json" + outside.write_text("{}", encoding="utf-8") + store._path("receipt-key").symlink_to(outside) + + with pytest.raises(HostAdapterError, match="corrupt host receipt"): + store.get("receipt-key") + + @pytest.mark.asyncio async def test_explicit_start_rejection_releases_the_reservation_for_retry( tmp_path: Path, diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py index 68cd2ad537..2e89ce0ea4 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round17.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -100,6 +100,41 @@ def racing_stat(path: Any, *args: Any, **kwargs: Any) -> os.stat_result: _hash_file(target, 1024, workspace_root=workspace) +def test_artifact_hash_closes_workspace_after_root_stat_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + if os.open not in os.supports_dir_fd: + pytest.skip("directory-relative opens are unavailable") + + workspace = tmp_path / "workspace" + workspace.mkdir() + target = workspace / "result.txt" + target.write_text("inside", encoding="utf-8") + real_fstat = os.fstat + real_close = os.close + fstat_calls = 0 + closed: list[int] = [] + + def failing_fstat(descriptor: int) -> os.stat_result: + nonlocal fstat_calls + fstat_calls += 1 + if fstat_calls == 1: + raise OSError("simulated root fstat failure") + return real_fstat(descriptor) + + def recording_close(descriptor: int) -> None: + closed.append(descriptor) + real_close(descriptor) + + monkeypatch.setattr(os, "fstat", failing_fstat) + monkeypatch.setattr(os, "close", recording_close) + with pytest.raises(VMPathError, match="cannot be opened"): + _hash_file(target, 1024, workspace_root=workspace) + + assert closed + + @pytest.mark.asyncio async def test_resume_requires_a_session_binding_for_tenant_isolation(tmp_path: Path) -> None: class Disconnected: From 207a82aecf9a5d8fc63ccbf7bb5b0557c498783d Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 05:44:52 +0900 Subject: [PATCH 32/41] fix(vm): close round thirteen evidence boundaries --- .../integrations/vm_agent_runtime.py | 24 ++++++-- .../integrations/test_vm_agent_runtime.py | 60 +++++++++++++++++++ 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 90693c56f0..7eb8d36cfd 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -392,6 +392,7 @@ def to_dict(self) -> dict[str, Any]: {"running", "disconnected", "recovery_required", "timed_out"} ) _MAX_RAW_RECEIPT_CHARS = 256 * 1024 +_MAX_RECEIPT_FILE_BYTES = 2 * 1024 * 1024 _MAX_BOUNDED_JSON_NODES = 4096 _RAW_PAYLOAD_TRUNCATION_MARKER = "...[raw payload truncated]" @@ -710,6 +711,9 @@ def _read_json(path: Path) -> Any: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) descriptor = os.open(path, flags) try: + file_stat = os.fstat(descriptor) + if not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size > _MAX_RECEIPT_FILE_BYTES: + raise OSError("VM receipt file exceeds the resource ceiling") with os.fdopen(descriptor, "r", encoding="utf-8") as handle: descriptor = -1 return json.load(handle) @@ -1563,7 +1567,7 @@ def _artifact_paths( if not isinstance(remote, Iterable) or isinstance(remote, (str, bytes, Mapping)): raise VMTransportError("VM artifacts must be a list of paths or path objects") for index, item in enumerate(remote): - if index >= max_paths or len(paths) >= max_paths: + if index >= max_paths: raise VMTransportError(f"VM artifacts cannot contain more than {max_paths} paths") if isinstance(item, str) and item.strip(): path = item @@ -1573,9 +1577,12 @@ def _artifact_paths( path = item["path"] else: raise VMTransportError("VM artifacts must contain path strings or path objects") - if path not in seen: - paths.append(path) - seen.add(path) + if path in seen: + continue + if len(paths) >= max_paths: + raise VMTransportError(f"VM artifacts cannot contain more than {max_paths} paths") + paths.append(path) + seen.add(path) return tuple(paths) @@ -1741,9 +1748,14 @@ def _bounded_json_value( if _json_size(value) <= budget: return value return _truncate_json_string(value, budget) + if isinstance(value, int) and not isinstance(value, bool) and value.bit_length() > budget * 3: + return _RAW_PAYLOAD_TRUNCATION_MARKER if isinstance(value, (str, int, float, bool)) or value is None: - return value - return str(value) + return value if _json_size(value) <= budget else _RAW_PAYLOAD_TRUNCATION_MARKER + text = str(value) + if _json_size(text) <= budget: + return text + return _truncate_json_string(text, budget) def _json_size(value: Any) -> int: diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 4c92d13fc3..71ff2b71de 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -752,6 +752,66 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] assert target.calls == 1 +@pytest.mark.asyncio +async def test_duplicate_remote_artifact_does_not_consume_the_path_ceiling( + tmp_path: Path, +) -> None: + artifact = tmp_path / "result.txt" + artifact.write_text("ok", encoding="utf-8") + + class EchoingTransport: + async def execute(self, _request: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0, "artifacts": ["result.txt"]} + + runtime = VMPersonalAgentRuntime( + EchoingTransport(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_artifact_paths=1, + ) + + receipt = await runtime.execute_command( + "verify", + dispatch_id="duplicate-artifact", + session_id="s", + artifact_paths=("result.txt",), + ) + + assert receipt.status == "completed" + assert receipt.artifact_paths == ("result.txt",) + + +@pytest.mark.asyncio +async def test_raw_receipt_budget_bounds_large_scalar_and_binary_values(tmp_path: Path) -> None: + class OversizedMetadataTransport: + async def execute(self, _request: Any) -> dict[str, Any]: + return { + "status": "completed", + "exit_code": 0, + "metadata": {"large_integer": 10**5000, "large_bytes": b"x" * 5000}, + } + + runtime = VMPersonalAgentRuntime( + OversizedMetadataTransport(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verify", dispatch_id="raw-budget", session_id="s") + + metadata = receipt.raw["metadata"] + assert isinstance(metadata, dict) + assert metadata["large_integer"] == "...[raw payload truncated]" + assert metadata["large_bytes"].endswith("...[raw payload truncated]") + assert len(json.dumps(receipt.raw, ensure_ascii=False).encode("utf-8")) <= 256 * 1024 + + +def test_json_receipt_store_rejects_an_oversized_receipt_file(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + store._path("oversized").write_bytes(b"{" + b"x" * (2 * 1024 * 1024) + b"}") + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt"): + store.get("oversized") + + @pytest.mark.asyncio async def test_unknown_remote_status_fails_closed(tmp_path: Path) -> None: class UnknownStatusCommand: From e6e70864d796f56226cbd96229452bd23b1dd6cc Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 06:13:06 +0900 Subject: [PATCH 33/41] fix(host): bound receipt file reads --- src/ouroboros/integrations/personal_agent_host.py | 8 ++++++++ tests/unit/integrations/test_personal_agent_host.py | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 6416972c00..7c05186be0 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -23,6 +23,7 @@ import os from pathlib import Path import shlex +import stat import tempfile from typing import Any, Protocol from uuid import uuid4 @@ -77,6 +78,7 @@ ) _START_RESERVATION_WAIT_SECONDS = 5.0 _START_RESERVATION_POLL_SECONDS = 0.01 +_MAX_HOST_RECEIPT_FILE_BYTES = 2 * 1024 * 1024 class HostToolTransport(Protocol): @@ -504,6 +506,12 @@ def _read_json(path: Path) -> Any: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) descriptor = os.open(path, flags) try: + file_stat = os.fstat(descriptor) + if ( + not stat.S_ISREG(file_stat.st_mode) + or file_stat.st_size > _MAX_HOST_RECEIPT_FILE_BYTES + ): + raise OSError("host receipt file exceeds the resource ceiling") with os.fdopen(descriptor, "r", encoding="utf-8") as handle: descriptor = -1 return json.load(handle) diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 4cace93e49..ace0b5aa2c 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -313,6 +313,14 @@ def test_json_store_rejects_symlinked_receipt_reads(tmp_path: Path) -> None: store.get("receipt-key") +def test_json_store_rejects_an_oversized_receipt_file(tmp_path: Path) -> None: + store = JsonHostReceiptStore(tmp_path / "host-receipts") + store._path("oversized").write_bytes(b"{" + b"x" * (2 * 1024 * 1024) + b"}") + + with pytest.raises(HostAdapterError, match="corrupt host receipt"): + store.get("oversized") + + @pytest.mark.asyncio async def test_explicit_start_rejection_releases_the_reservation_for_retry( tmp_path: Path, From 193188afe1f99b6ff9910fe3549c180988a20e8b Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 07:20:29 +0900 Subject: [PATCH 34/41] fix(vm): harden crash recovery and receipt replay --- .../integrations/personal_agent_host.py | 117 +++++++++- .../integrations/vm_agent_runtime.py | 99 ++++++-- .../integrations/test_personal_agent_host.py | 211 ++++++++++++++++++ .../test_vm_agent_runtime_round15.py | 22 ++ .../test_vm_agent_runtime_round17.py | 28 +++ 5 files changed, 450 insertions(+), 27 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 7c05186be0..c2e6a3cccb 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -1007,10 +1007,11 @@ async def wait( }, ) payload = response.payload + _validate_lifecycle_identity(receipt, payload, JOB_WAIT_TOOL) pending = ( _pending_dispatches(payload["pending_host_dispatches"], JOB_WAIT_TOOL) if "pending_host_dispatches" in payload - else receipt.pending_host_dispatches + else self._durable_pending_dispatches(receipt) ) return self._persist_receipt(_updated_receipt(receipt, payload, response, pending=pending)) @@ -1059,11 +1060,19 @@ async def submit_dispatch( f"host dispatch advertised an unsupported submission tool " f"{dispatch.submit_tool!r}" ) + if _submission_is_in_flight(receipt.last_submission, dispatch.dispatch_id): + raise HostSubmissionError( + f"dispatch {dispatch.dispatch_id} has an unknown submission outcome; " + "wait for a fresh job snapshot before retrying" + ) if undispatched: result_entry: dict[str, Any] = {"key": "result", "undispatched": True} else: _validate_host_content(content) result_entry = {"key": "result", "content": _json_copy(content)} + receipt = self._persist_receipt( + replace(receipt, last_submission=_submission_intent(dispatch)) + ) response = await self._call( dispatch.submit_tool or SUBMIT_FANOUT_TOOL, { @@ -1095,10 +1104,11 @@ async def result(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Fetch and preserve terminal Seed/execution/evaluation evidence.""" response = await self._call(JOB_RESULT_TOOL, {"job_id": receipt.job_id}) payload = response.payload + _validate_lifecycle_identity(receipt, payload, JOB_RESULT_TOOL) pending = ( _pending_dispatches(payload["pending_host_dispatches"], JOB_RESULT_TOOL) if "pending_host_dispatches" in payload - else receipt.pending_host_dispatches + else self._durable_pending_dispatches(receipt) ) return self._persist_receipt( _updated_receipt( @@ -1114,6 +1124,7 @@ async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Request cancellation while retaining the correlated receipt.""" response = await self._call(CANCEL_JOB_TOOL, {"job_id": receipt.job_id}) payload = response.payload + _validate_lifecycle_identity(receipt, payload, CANCEL_JOB_TOOL) if "pending_host_dispatches" in payload: pending = _pending_dispatches(payload["pending_host_dispatches"], CANCEL_JOB_TOOL) elif ( @@ -1124,9 +1135,20 @@ async def cancel(self, receipt: HostExecutionReceipt) -> HostExecutionReceipt: else: # A cancellation request is not proof that the job stopped. Keep # actionable work durable until a terminal snapshot confirms it. - pending = receipt.pending_host_dispatches + pending = self._durable_pending_dispatches(receipt) return self._persist_receipt(_updated_receipt(receipt, payload, response, pending=pending)) + def _durable_pending_dispatches( + self, receipt: HostExecutionReceipt + ) -> tuple[PendingHostDispatch, ...]: + """Use a newer persisted pending set when a response is sparse.""" + if not receipt.start_key: + return receipt.pending_host_dispatches + persisted = self.receipt_store.get(receipt.start_key) + if persisted is not None and persisted.cursor >= receipt.cursor: + return persisted.pending_host_dispatches + return receipt.pending_host_dispatches + def _persist_receipt( self, receipt: HostExecutionReceipt, @@ -1291,6 +1313,37 @@ def _pending_dispatches(value: Any, tool_name: str) -> tuple[PendingHostDispatch return tuple(parsed) +def _validate_lifecycle_identity( + receipt: HostExecutionReceipt, payload: Mapping[str, Any], tool_name: str +) -> None: + """Reject lifecycle evidence that belongs to another job or session.""" + for key, expected in ( + ("job_id", receipt.job_id), + ("auto_session_id", receipt.auto_session_id), + ("session_id", receipt.auto_session_id), + ): + value = payload.get(key) + if value is None: + continue + if not isinstance(value, str) or not value.strip(): + raise HostAdapterError( + f"{tool_name} response {key} must be non-empty text", tool_name=tool_name + ) + if value.strip() != expected: + raise HostAdapterError( + f"{tool_name} response {key} does not match the active receipt", + tool_name=tool_name, + ) + links = _model_mapping(payload.get("links")) + if links is not None: + linked_session = links.get("session_id") + if linked_session is not None and linked_session != receipt.auto_session_id: + raise HostAdapterError( + f"{tool_name} response links.session_id does not match the active receipt", + tool_name=tool_name, + ) + + def _receipt_from_payload( *, host_name: str, @@ -1457,6 +1510,15 @@ def _updated_receipt( recovery=_named_evidence(state, "recovery", "recovery_action", "next_step") or receipt.recovery, state={**receipt.state, **state}, + last_submission=( + {} + if _submission_is_in_flight(receipt.last_submission, None) + and not any( + item.dispatch_id == receipt.last_submission.get("dispatch_id") + for item in pending_snapshot + ) + else receipt.last_submission + ), last_response=response, result_response=result_response or receipt.result_response, ) @@ -1468,12 +1530,38 @@ def _merge_receipts( """Keep a newer durable lifecycle snapshot from a stale host writer.""" if persisted.start_key != incoming.start_key: return incoming + if persisted.is_terminal and (not incoming.is_terminal or incoming.cursor < persisted.cursor): + return persisted if persisted.cursor > incoming.cursor: return persisted if persisted.cursor < incoming.cursor: return incoming - if persisted.is_terminal and not incoming.is_terminal: - return persisted + if persisted.is_terminal and incoming.is_terminal: + persisted_ids = {item.dispatch_id for item in persisted.pending_host_dispatches} + pending = incoming.pending_host_dispatches + if persisted.last_submission and incoming.last_submission: + pending = tuple(item for item in pending if item.dispatch_id in persisted_ids) + elif not pending: + pending = persisted.pending_host_dispatches + return replace( + incoming, + cursor=max(persisted.cursor, incoming.cursor), + is_terminal=persisted.is_terminal or incoming.is_terminal, + result_available=persisted.result_available or incoming.result_available, + links={**persisted.links, **incoming.links}, + pending_host_dispatches=pending, + seed={**persisted.seed, **incoming.seed}, + execution={**persisted.execution, **incoming.execution}, + evaluation={**persisted.evaluation, **incoming.evaluation}, + verification={**persisted.verification, **incoming.verification}, + failure={**persisted.failure, **incoming.failure}, + recovery={**persisted.recovery, **incoming.recovery}, + state={**persisted.state, **incoming.state}, + last_submission=incoming.last_submission or persisted.last_submission, + start_response=incoming.start_response or persisted.start_response, + last_response=incoming.last_response or persisted.last_response, + result_response=incoming.result_response or persisted.result_response, + ) if persisted.last_submission and not incoming.last_submission: return persisted if persisted.last_submission and incoming.last_submission: @@ -1566,6 +1654,25 @@ def _validate_host_content(content: Any) -> None: raise HostSubmissionError("successful host execution content needs substantive output") +def _submission_intent(dispatch: PendingHostDispatch) -> dict[str, Any]: + return { + "status": "in_flight", + "dispatch_id": dispatch.dispatch_id, + "fanout_id": dispatch.fanout_id, + "session_id": dispatch.session_id, + "correlation_key": dispatch.result_correlation_key, + } + + +def _submission_is_in_flight(submission: Mapping[str, Any], dispatch_id: str | None) -> bool: + if submission.get("status") != "in_flight": + return False + recorded_dispatch_id = submission.get("dispatch_id") + return isinstance(recorded_dispatch_id, str) and ( + dispatch_id is None or recorded_dispatch_id == dispatch_id + ) + + def _same_dispatch_claim(left: PendingHostDispatch, right: PendingHostDispatch) -> bool: return ( left.dispatch_id == right.dispatch_id diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 7eb8d36cfd..a23e30a962 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -551,6 +551,9 @@ def get(self, key: str) -> VMExecutionReceipt | None: return self._receipts.get(key) def put(self, receipt: VMExecutionReceipt) -> None: + existing = self.get(receipt.idempotency_key) + if existing is not None and existing.is_terminal: + return self._receipts[receipt.idempotency_key] = receipt def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: @@ -598,6 +601,9 @@ def get(self, key: str) -> VMExecutionReceipt | None: def put(self, receipt: VMExecutionReceipt) -> None: path = self._path(receipt.idempotency_key) + existing = self.get(receipt.idempotency_key) + if existing is not None and existing.is_terminal: + return fd, temporary = tempfile.mkstemp(prefix=".receipt-", suffix=".tmp", dir=self.directory) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: @@ -953,7 +959,13 @@ async def execute_command( idempotency_key: str | None = None, ) -> VMExecutionReceipt: """Execute one command, or return the durable receipt for its retry.""" - artifact_paths = _bounded_paths(artifact_paths, self.max_artifact_paths) + artifact_paths = _bounded_paths( + artifact_paths, + self.max_artifact_paths, + identity=lambda item: self.workspace.host_relative( + self.workspace.resolve_artifact_path(item) + ), + ) request = VMExecutionRequest( dispatch_id=dispatch_id, session_id=session_id, @@ -1038,12 +1050,22 @@ async def resume_dispatch( def collect_artifacts(self, paths: Iterable[str]) -> tuple[VMArtifact, ...]: """Collect metadata only for files within the approved workspace.""" artifacts: list[VMArtifact] = [] + seen_relative_paths: set[str] = set() total_bytes = 0 - for path in _bounded_paths(paths, self.max_artifact_paths): + for path in _bounded_paths( + paths, + self.max_artifact_paths, + identity=lambda item: self.workspace.host_relative( + self.workspace.resolve_artifact_path(item) + ), + ): if not isinstance(path, str) or not path.strip(): raise VMPathError("artifact paths must be non-empty strings") host_path = self.workspace.resolve_artifact_path(path) relative = self.workspace.host_relative(host_path) + if relative in seen_relative_paths: + continue + seen_relative_paths.add(relative) vm_path = self.workspace.map_host_path(host_path) if not host_path.exists(): artifacts.append(VMArtifact(relative, vm_path, False)) @@ -1174,8 +1196,7 @@ async def _call_and_store( error=str(exc), recovery_required=True, ) - self.receipt_store.put(updated) - return updated + return self._store_receipt(updated) except asyncio.CancelledError: updated = replace( receipt, @@ -1183,18 +1204,16 @@ async def _call_and_store( error="VM execution task was cancelled before completion; refusing replay.", recovery_required=True, ) - self.receipt_store.put(updated) + self._store_receipt(updated) raise except (ConnectionError, BrokenPipeError, EOFError) as exc: updated = replace( receipt, status="disconnected", error=str(exc), recovery_required=True ) - self.receipt_store.put(updated) - return updated + return self._store_receipt(updated) except Exception as exc: # transport errors are evidence in the receipt updated = replace(receipt, status="failed", error=str(exc), finished_at=_now()) - self.receipt_store.put(updated) - return updated + return self._store_receipt(updated) try: updated = self._receipt_from_response(receipt, request, raw) @@ -1206,8 +1225,7 @@ async def _call_and_store( recovery_required=False, finished_at=_now(), ) - self.receipt_store.put(updated) - return updated + return self._store_receipt(updated) async def _store_timeout( self, @@ -1242,8 +1260,7 @@ async def _store_timeout( recovery_required=True, finished_at=_now(), ) - self.receipt_store.put(updated) - return updated + return self._store_receipt(updated) def _prepare_request(self, request: VMExecutionRequest) -> VMExecutionRequest: host_workspace = request.host_workspace or str(self.workspace.host_root) @@ -1288,7 +1305,10 @@ def _receipt_from_response( if status in _REMOTE_RUNNING_STATUSES: status = "running" artifact_paths = _artifact_paths( - payload, request.artifact_paths, max_paths=self.max_artifact_paths + payload, + request.artifact_paths, + max_paths=self.max_artifact_paths, + workspace=self.workspace, ) artifacts = self.collect_artifacts(artifact_paths) stdout, stdout_truncated = _truncate_text( @@ -1327,8 +1347,15 @@ def _receipt_from_response( def _store_recovery(self, receipt: VMExecutionReceipt, error: str) -> VMExecutionReceipt: updated = replace(receipt, status="recovery_required", error=error, recovery_required=True) - self.receipt_store.put(updated) - return updated + return self._store_receipt(updated) + + def _store_receipt(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt: + """Keep a terminal receipt from being regressed by a stale writer.""" + existing = self.receipt_store.get(receipt.idempotency_key) + if existing is not None and existing.is_terminal: + return existing + self.receipt_store.put(receipt) + return receipt async def _await_if_needed(value: Any) -> Any: @@ -1537,7 +1564,12 @@ def _response_exit_code(values: Mapping[str, Any]) -> int | None: return value -def _bounded_paths(paths: Iterable[str], limit: int) -> tuple[str, ...]: +def _bounded_paths( + paths: Iterable[str], + limit: int, + *, + identity: Any = None, +) -> tuple[str, ...]: if isinstance(paths, (str, bytes)): raise VMRuntimeError("artifact_paths must be an iterable of text paths") try: @@ -1545,19 +1577,39 @@ def _bounded_paths(paths: Iterable[str], limit: int) -> tuple[str, ...]: except TypeError as exc: raise VMRuntimeError("artifact_paths must be an iterable of text paths") from exc bounded: list[str] = [] + seen: set[Any] = set() + raw_limit = limit if identity is None else max(limit * 4, limit + 32) for index, path in enumerate(iterator): - if index >= limit: + if index >= raw_limit: raise VMRuntimeError(f"artifact_paths cannot contain more than {limit} paths") + path_identity = path if identity is None else identity(path) + if path_identity in seen: + continue + if len(bounded) >= limit: + raise VMRuntimeError(f"artifact_paths cannot contain more than {limit} paths") + seen.add(path_identity) bounded.append(path) return tuple(bounded) def _artifact_paths( - payload: Mapping[str, Any], requested: Iterable[str], *, max_paths: int + payload: Mapping[str, Any], + requested: Iterable[str], + *, + max_paths: int, + workspace: VMWorkspaceMapper | None = None, ) -> tuple[str, ...]: paths: list[str] = [] seen = set(paths) - for path in _bounded_paths(requested, max_paths): + identity = ( + None + if workspace is None + else lambda item: workspace.host_relative(workspace.resolve_artifact_path(item)) + ) + seen_identities: set[Any] = set() + for path in _bounded_paths(requested, max_paths, identity=identity): + path_identity = path if identity is None else identity(path) + seen_identities.add(path_identity) if path not in seen: paths.append(path) seen.add(path) @@ -1566,8 +1618,9 @@ def _artifact_paths( remote = payload["artifacts"] if not isinstance(remote, Iterable) or isinstance(remote, (str, bytes, Mapping)): raise VMTransportError("VM artifacts must be a list of paths or path objects") + raw_limit = max(max_paths * 4, max_paths + 32) for index, item in enumerate(remote): - if index >= max_paths: + if index >= raw_limit: raise VMTransportError(f"VM artifacts cannot contain more than {max_paths} paths") if isinstance(item, str) and item.strip(): path = item @@ -1577,12 +1630,14 @@ def _artifact_paths( path = item["path"] else: raise VMTransportError("VM artifacts must contain path strings or path objects") - if path in seen: + path_identity = path if identity is None else identity(path) + if path_identity in seen_identities: continue if len(paths) >= max_paths: raise VMTransportError(f"VM artifacts cannot contain more than {max_paths} paths") paths.append(path) seen.add(path) + seen_identities.add(path_identity) return tuple(paths) diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index ace0b5aa2c..b85ed48da2 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -12,6 +12,7 @@ from ouroboros.integrations.personal_agent_host import ( HostAdapterError, HostExecutionReceipt, + HostSubmissionError, JsonHostReceiptStore, MCPToolTransport, PersonalAgentHostAdapter, @@ -303,6 +304,216 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 1 +@pytest.mark.asyncio +async def test_sparse_equal_cursor_snapshot_keeps_newer_pending_dispatch( + tmp_path: Path, +) -> None: + pending = { + "dispatch_id": "dispatch-sparse", + "fanout_id": "fanout-sparse", + "session_id": "auto-sparse", + "result_correlation_key": "result", + "submit_tool": "ouroboros_submit_fanout_results", + "actionable": True, + "subagents": [{"prompt": "run it", "context": {}}], + } + waits = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal waits + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-sparse", + "auto_session_id": "auto-sparse", + "runtime_backend": "host", + "status": "queued", + "cursor": 0, + } + } + waits += 1 + if waits == 1: + return { + "meta": { + "job_id": "job-sparse", + "auto_session_id": "auto-sparse", + "status": "running", + "cursor": 2, + "pending_host_dispatches": [pending], + } + } + return { + "meta": { + "job_id": "job-sparse", + "auto_session_id": "auto-sparse", + "status": "running", + "cursor": 2, + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + initial = await adapter.start("/ouroboros preserve sparse work", host_session_id="sparse") + assert initial is not None + newest = await adapter.wait(initial) + repeated = await adapter.wait(initial) + + assert newest.cursor == 2 + assert [item.dispatch_id for item in repeated.pending_host_dispatches] == ["dispatch-sparse"] + + +@pytest.mark.asyncio +async def test_lifecycle_snapshot_rejects_a_foreign_job_identity() -> None: + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-owned", + "auto_session_id": "auto-owned", + "runtime_backend": "host", + "status": "queued", + } + } + return { + "meta": { + "job_id": "job-foreign", + "auto_session_id": "auto-owned", + "status": "completed", + "is_terminal": True, + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + receipt = await adapter.start("/ouroboros reject foreign lifecycle state") + assert receipt is not None + + with pytest.raises(HostAdapterError, match="job_id does not match"): + await adapter.wait(receipt) + + +@pytest.mark.asyncio +async def test_equal_cursor_terminal_snapshot_keeps_persisted_evidence() -> None: + waits = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal waits + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-terminal-merge", + "auto_session_id": "auto-terminal-merge", + "runtime_backend": "host", + "status": "queued", + } + } + waits += 1 + if waits == 1: + return { + "meta": { + "job_id": "job-terminal-merge", + "auto_session_id": "auto-terminal-merge", + "status": "completed", + "cursor": 2, + "is_terminal": True, + "result_available": True, + "verification": {"passed": True}, + } + } + return { + "meta": { + "job_id": "job-terminal-merge", + "auto_session_id": "auto-terminal-merge", + "status": "completed", + "cursor": 2, + "is_terminal": True, + } + } + + adapter = PersonalAgentHostAdapter(call_tool) + initial = await adapter.start("/ouroboros preserve terminal evidence") + assert initial is not None + terminal = await adapter.wait(initial) + stale = await adapter.wait(initial) + + assert terminal.verification == {"passed": True} + assert stale.verification == {"passed": True} + assert stale.result_available is True + + +@pytest.mark.asyncio +async def test_submit_intent_blocks_replay_after_store_failure_after_acceptance( + tmp_path: Path, +) -> None: + pending = { + "dispatch_id": "dispatch-submit-crash", + "fanout_id": "fanout-submit-crash", + "session_id": "auto-submit-crash", + "result_correlation_key": "result", + "submit_tool": "ouroboros_submit_fanout_results", + "actionable": True, + "subagents": [{"prompt": "run it", "context": {}}], + } + + class CrashAfterAcceptanceStore(JsonHostReceiptStore): + def __init__(self, directory: Path) -> None: + super().__init__(directory) + self.put_calls = 0 + self.fail_on: int | None = None + + def put(self, key: str, receipt: HostExecutionReceipt) -> None: + self.put_calls += 1 + if self.fail_on == self.put_calls: + raise OSError("simulated crash after remote acceptance") + super().put(key, receipt) + + calls: list[str] = [] + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + calls.append(name) + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-submit-crash", + "auto_session_id": "auto-submit-crash", + "runtime_backend": "host", + "status": "queued", + } + } + if name == "ouroboros_job_wait": + return { + "meta": { + "job_id": "job-submit-crash", + "auto_session_id": "auto-submit-crash", + "status": "running", + "cursor": 1, + "pending_host_dispatches": [pending], + } + } + assert name == "ouroboros_submit_fanout_results" + return {"meta": {"status": "complete", "job_id": "job-submit-crash"}} + + store = CrashAfterAcceptanceStore(tmp_path / "host-receipts") + adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + receipt = await adapter.start("/ouroboros submit once", host_session_id="submit-crash") + assert receipt is not None + waiting = await adapter.wait(receipt) + dispatch = waiting.pending_host_dispatches[0] + store.fail_on = store.put_calls + 2 + + with pytest.raises(OSError, match="simulated crash"): + await adapter.submit_dispatch(waiting, dispatch, {"result": "done"}) + + restored = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros submit once", host_session_id="submit-crash" + ) + assert restored is not None + with pytest.raises(HostSubmissionError, match="unknown submission outcome"): + await PersonalAgentHostAdapter(call_tool, receipt_store=store).submit_dispatch( + restored, dispatch, {"result": "done"} + ) + assert calls.count("ouroboros_submit_fanout_results") == 1 + + def test_json_store_rejects_symlinked_receipt_reads(tmp_path: Path) -> None: store = JsonHostReceiptStore(tmp_path / "host-receipts") outside = tmp_path / "outside.json" diff --git a/tests/unit/integrations/test_vm_agent_runtime_round15.py b/tests/unit/integrations/test_vm_agent_runtime_round15.py index d0b282a101..2721b0b63c 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round15.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round15.py @@ -52,6 +52,28 @@ def test_duplicate_artifacts_are_hashed_once_and_recorded_once(tmp_path: Path) - assert len(receipt.artifacts) == 1 +def test_host_and_vm_artifact_aliases_are_hashed_once(tmp_path: Path) -> None: + artifact = tmp_path / "result.json" + artifact.write_text('{"ok": true}', encoding="utf-8") + runtime = VMPersonalAgentRuntime( + CommandVMTransport(CompletedCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_artifact_paths=1, + ) + + receipt = asyncio.run( + runtime.execute_command( + "verify", + dispatch_id="aliased-artifact", + session_id="session", + artifact_paths=("result.json", "/workspace/result.json"), + ) + ) + + assert receipt.artifact_paths == ("result.json",) + assert len(receipt.artifacts) == 1 + + class CountingReceiptStore(JsonVMReceiptStore): def __init__(self, directory: Path) -> None: self.index_builds = 0 diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py index 2e89ce0ea4..f0b73b4150 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round17.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import replace import hashlib import os from pathlib import Path @@ -15,6 +16,8 @@ parse_explicit_invocation, ) from ouroboros.integrations.vm_agent_runtime import ( + JsonVMReceiptStore, + VMExecutionReceipt, VMPathError, VMPersonalAgentRuntime, VMRuntimeError, @@ -135,6 +138,31 @@ def recording_close(descriptor: int) -> None: assert closed +def test_terminal_vm_receipt_cannot_be_regressed_by_a_stale_write(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + terminal = VMExecutionReceipt( + dispatch_id="stale-terminal", + session_id="tenant-a", + idempotency_key="tenant-a:stale-terminal", + status="completed", + command="verify", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + stdout="done", + started_at="now", + finished_at="later", + ) + store.put(terminal) + + store.put(replace(terminal, status="running", finished_at=None, stdout="")) + + persisted = store.get(terminal.idempotency_key) + assert persisted is not None + assert persisted.status == "completed" + assert persisted.stdout == "done" + + @pytest.mark.asyncio async def test_resume_requires_a_session_binding_for_tenant_isolation(tmp_path: Path) -> None: class Disconnected: From 1ee1577301da82a6e2902290f33adce87e17f4c7 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 07:33:48 +0900 Subject: [PATCH 35/41] fix(vm): serialize receipt recovery writes --- .../integrations/personal_agent_host.py | 135 ++++++++++++++++-- .../integrations/vm_agent_runtime.py | 40 +++--- .../integrations/test_personal_agent_host.py | 78 +++++++++- 3 files changed, 218 insertions(+), 35 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index c2e6a3cccb..ea1d846c01 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -28,6 +28,7 @@ from typing import Any, Protocol from uuid import uuid4 +from ouroboros.core.file_lock import file_lock from ouroboros.integrations._keyed_locks import KeyedAsyncLockPool from ouroboros.integrations.vm_agent_profile import ( GROK_BOT_VM_PROFILE, @@ -335,6 +336,19 @@ def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecuti def abort_start(self, key: str) -> None: """Release a reservation when the host explicitly rejected the start.""" + def put_merged( + self, + key: str, + incoming: HostExecutionReceipt, + acknowledged_dispatch_id: str | None = None, + ) -> HostExecutionReceipt: + """Merge and persist one lifecycle update atomically.""" + + def claim_submission( + self, key: str, receipt: HostExecutionReceipt, dispatch: PendingHostDispatch + ) -> tuple[HostExecutionReceipt, bool]: + """Claim one host dispatch exactly once across adapter processes.""" + class MemoryHostReceiptStore: """Small in-memory store for hosts that do not need process restart recovery.""" @@ -349,6 +363,28 @@ def get(self, key: str) -> HostExecutionReceipt | None: def put(self, key: str, receipt: HostExecutionReceipt) -> None: self._receipts[key] = receipt + def put_merged( + self, + key: str, + incoming: HostExecutionReceipt, + acknowledged_dispatch_id: str | None = None, + ) -> HostExecutionReceipt: + persisted = self.get(key) + receipt = _receipt_after_persist(persisted, incoming, acknowledged_dispatch_id) + self._receipts[key] = receipt + return receipt + + def claim_submission( + self, key: str, receipt: HostExecutionReceipt, dispatch: PendingHostDispatch + ) -> tuple[HostExecutionReceipt, bool]: + persisted = self.get(key) + current = _receipt_after_persist(persisted, receipt) + if _submission_is_in_flight(current.last_submission, dispatch.dispatch_id): + return current, False + claimed = replace(current, last_submission=_submission_intent(dispatch)) + self._receipts[key] = claimed + return claimed, True + def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: existing = self._receipts.get(key) if existing is not None: @@ -395,6 +431,10 @@ def get(self, key: str) -> HostExecutionReceipt | None: def put(self, key: str, receipt: HostExecutionReceipt) -> None: path = self._path(key) + with file_lock(path, stable_parent_authority=True): + self._put_unlocked(path, receipt) + + def _put_unlocked(self, path: Path, receipt: HostExecutionReceipt) -> None: fd, temporary = tempfile.mkstemp(prefix=".host-receipt-", suffix=".tmp", dir=self.directory) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: @@ -406,22 +446,39 @@ def put(self, key: str, receipt: HostExecutionReceipt) -> None: if os.path.exists(temporary): os.unlink(temporary) + def put_merged( + self, + key: str, + incoming: HostExecutionReceipt, + acknowledged_dispatch_id: str | None = None, + ) -> HostExecutionReceipt: + path = self._path(key) + with file_lock(path, stable_parent_authority=True): + persisted = self.get(key) + receipt = _receipt_after_persist(persisted, incoming, acknowledged_dispatch_id) + self._put_unlocked(path, receipt) + return receipt + + def claim_submission( + self, key: str, receipt: HostExecutionReceipt, dispatch: PendingHostDispatch + ) -> tuple[HostExecutionReceipt, bool]: + path = self._path(key) + with file_lock(path, stable_parent_authority=True): + persisted = self.get(key) + current = _receipt_after_persist(persisted, receipt) + if _submission_is_in_flight(current.last_submission, dispatch.dispatch_id): + return current, False + claimed = replace(current, last_submission=_submission_intent(dispatch)) + self._put_unlocked(path, claimed) + return claimed, True + def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: path = self._path(key) - fd, temporary = tempfile.mkstemp(prefix=".host-receipt-", suffix=".tmp", dir=self.directory) - try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) - handle.flush() - os.fsync(handle.fileno()) - try: - os.link(temporary, path) - except FileExistsError: + with file_lock(path, stable_parent_authority=True): + if path.exists(): return self.get(key) + self._put_unlocked(path, receipt) return None - finally: - if os.path.exists(temporary): - os.unlink(temporary) def reserve_start( self, key: str, arguments: Mapping[str, Any] @@ -1070,9 +1127,18 @@ async def submit_dispatch( else: _validate_host_content(content) result_entry = {"key": "result", "content": _json_copy(content)} - receipt = self._persist_receipt( - replace(receipt, last_submission=_submission_intent(dispatch)) - ) + claim_submission = getattr(self.receipt_store, "claim_submission", None) + if callable(claim_submission) and receipt.start_key: + receipt, claimed = claim_submission(receipt.start_key, receipt, dispatch) + if not claimed: + raise HostSubmissionError( + f"dispatch {dispatch.dispatch_id} has an unknown submission outcome; " + "wait for a fresh job snapshot before retrying" + ) + else: + receipt = self._persist_receipt( + replace(receipt, last_submission=_submission_intent(dispatch)) + ) response = await self._call( dispatch.submit_tool or SUBMIT_FANOUT_TOOL, { @@ -1084,6 +1150,15 @@ async def submit_dispatch( ) payload = response.payload if payload.get("status") != "complete": + self._persist_receipt( + replace( + receipt, + last_submission={ + **payload, + "status": payload.get("status", "rejected"), + }, + ) + ) raise HostSubmissionError( f"Ouroboros rejected host dispatch {dispatch.dispatch_id}: " f"{payload.get('status', 'unknown')}", @@ -1157,6 +1232,15 @@ def _persist_receipt( ) -> HostExecutionReceipt: """Persist and refresh the in-process cache after every lifecycle response.""" if receipt.start_key: + put_merged = getattr(self.receipt_store, "put_merged", None) + if callable(put_merged): + receipt = put_merged( + receipt.start_key, + receipt, + acknowledged_dispatch_id, + ) + self._start_receipts[receipt.start_key] = receipt + return receipt incoming = receipt persisted = self.receipt_store.get(receipt.start_key) if persisted is not None: @@ -1577,6 +1661,27 @@ def _merge_receipts( return incoming +def _receipt_after_persist( + persisted: HostExecutionReceipt | None, + incoming: HostExecutionReceipt, + acknowledged_dispatch_id: str | None = None, +) -> HostExecutionReceipt: + """Merge one lifecycle update before a store writes it under its lock.""" + receipt = _merge_receipts(persisted, incoming) if persisted is not None else incoming + if acknowledged_dispatch_id is not None: + receipt = replace( + receipt, + pending_host_dispatches=tuple( + item + for item in receipt.pending_host_dispatches + if item.dispatch_id != acknowledged_dispatch_id + ), + last_submission=incoming.last_submission or receipt.last_submission, + last_response=incoming.last_response or receipt.last_response, + ) + return receipt + + def _mapping_value(value: Any) -> Mapping[str, Any]: return _model_mapping(value) or {} diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index a23e30a962..c264b1ceaf 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -25,6 +25,7 @@ import tempfile from typing import Any, Protocol +from ouroboros.core.file_lock import file_lock from ouroboros.integrations._keyed_locks import KeyedAsyncLockPool @@ -551,10 +552,14 @@ def get(self, key: str) -> VMExecutionReceipt | None: return self._receipts.get(key) def put(self, receipt: VMExecutionReceipt) -> None: + self.put_monotonic(receipt) + + def put_monotonic(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt: existing = self.get(receipt.idempotency_key) if existing is not None and existing.is_terminal: - return + return existing self._receipts[receipt.idempotency_key] = receipt + return receipt def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: existing = self._receipts.get(receipt.idempotency_key) @@ -600,10 +605,18 @@ def get(self, key: str) -> VMExecutionReceipt | None: raise VMRuntimeError(f"corrupt VM receipt for {key!r}") from exc def put(self, receipt: VMExecutionReceipt) -> None: + self.put_monotonic(receipt) + + def put_monotonic(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt: path = self._path(receipt.idempotency_key) - existing = self.get(receipt.idempotency_key) - if existing is not None and existing.is_terminal: - return + with file_lock(path, stable_parent_authority=True): + existing = self.get(receipt.idempotency_key) + if existing is not None and existing.is_terminal: + return existing + self._put_unlocked(receipt, path) + return receipt + + def _put_unlocked(self, receipt: VMExecutionReceipt, path: Path) -> None: fd, temporary = tempfile.mkstemp(prefix=".receipt-", suffix=".tmp", dir=self.directory) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: @@ -619,26 +632,16 @@ def put(self, receipt: VMExecutionReceipt) -> None: def put_if_absent(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt | None: """Create a receipt without allowing concurrent runtimes to overwrite a claim.""" path = self._path(receipt.idempotency_key) - fd, temporary = tempfile.mkstemp(prefix=".receipt-", suffix=".tmp", dir=self.directory) - try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) - handle.flush() - os.fsync(handle.fileno()) - try: - os.link(temporary, path) - except FileExistsError: + with file_lock(path, stable_parent_authority=True): + if path.exists(): existing = self.get(receipt.idempotency_key) if existing is None: raise VMRuntimeError( "VM receipt claim disappeared; refusing to replay the command" ) return existing - self._index_put(receipt, path.name) + self._put_unlocked(receipt, path) return None - finally: - if os.path.exists(temporary): - os.unlink(temporary) def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionReceipt | None: self._ensure_find_index() @@ -1351,6 +1354,9 @@ def _store_recovery(self, receipt: VMExecutionReceipt, error: str) -> VMExecutio def _store_receipt(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt: """Keep a terminal receipt from being regressed by a stale writer.""" + put_monotonic = getattr(self.receipt_store, "put_monotonic", None) + if callable(put_monotonic): + return put_monotonic(receipt) existing = self.receipt_store.get(receipt.idempotency_key) if existing is not None and existing.is_terminal: return existing diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index b85ed48da2..6e4e9cc837 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -460,11 +460,16 @@ def __init__(self, directory: Path) -> None: self.put_calls = 0 self.fail_on: int | None = None - def put(self, key: str, receipt: HostExecutionReceipt) -> None: + def put_merged( + self, + key: str, + incoming: HostExecutionReceipt, + acknowledged_dispatch_id: str | None = None, + ) -> HostExecutionReceipt: self.put_calls += 1 if self.fail_on == self.put_calls: raise OSError("simulated crash after remote acceptance") - super().put(key, receipt) + return super().put_merged(key, incoming, acknowledged_dispatch_id) calls: list[str] = [] @@ -498,7 +503,7 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert receipt is not None waiting = await adapter.wait(receipt) dispatch = waiting.pending_host_dispatches[0] - store.fail_on = store.put_calls + 2 + store.fail_on = store.put_calls + 1 with pytest.raises(OSError, match="simulated crash"): await adapter.submit_dispatch(waiting, dispatch, {"result": "done"}) @@ -514,6 +519,73 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls.count("ouroboros_submit_fanout_results") == 1 +@pytest.mark.asyncio +async def test_rejected_submission_can_retry_when_dispatch_remains_pending( + tmp_path: Path, +) -> None: + pending = { + "dispatch_id": "dispatch-retry-rejected", + "fanout_id": "fanout-retry-rejected", + "session_id": "auto-retry-rejected", + "result_correlation_key": "result", + "submit_tool": "ouroboros_submit_fanout_results", + "actionable": True, + "subagents": [{"prompt": "run it", "context": {}}], + } + submissions = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal submissions + if name == "ouroboros_start_auto": + return { + "meta": { + "job_id": "job-retry-rejected", + "auto_session_id": "auto-retry-rejected", + "runtime_backend": "host", + "status": "queued", + } + } + if name == "ouroboros_job_wait": + return { + "meta": { + "job_id": "job-retry-rejected", + "auto_session_id": "auto-retry-rejected", + "status": "running", + "cursor": 1, + "pending_host_dispatches": [pending], + } + } + submissions += 1 + return { + "meta": { + "status": "partial" if submissions == 1 else "complete", + "job_id": "job-retry-rejected", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + receipt = await adapter.start("/ouroboros retry a rejected submission", host_session_id="retry") + assert receipt is not None + waiting = await adapter.wait(receipt) + dispatch = waiting.pending_host_dispatches[0] + + with pytest.raises(HostSubmissionError, match="partial"): + await adapter.submit_dispatch(waiting, dispatch, {"result": "first"}) + + restored = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros retry a rejected submission", host_session_id="retry" + ) + assert restored is not None + assert restored.last_submission["status"] == "partial" + retried = await PersonalAgentHostAdapter(call_tool, receipt_store=store).submit_dispatch( + restored, dispatch, {"result": "second"} + ) + + assert retried.last_submission["status"] == "complete" + assert submissions == 2 + + def test_json_store_rejects_symlinked_receipt_reads(tmp_path: Path) -> None: store = JsonHostReceiptStore(tmp_path / "host-receipts") outside = tmp_path / "outside.json" From 35354a8808f172089897f38073ab2a827d8eb747 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 09:11:55 +0900 Subject: [PATCH 36/41] test(hv1-ouroboros-vm-3130-security-and-integration): complete verification & hardening round 15 (crash-restart-idempotency) --- .../integrations/personal_agent_host.py | 136 ++++++++++--- .../integrations/vm_agent_runtime.py | 152 ++++++++++++-- .../integrations/test_personal_agent_host.py | 142 +++++++++++++ .../test_vm_agent_runtime_round15.py | 92 +++++++++ .../test_vm_agent_runtime_round17.py | 189 ++++++++++++++++++ 5 files changed, 663 insertions(+), 48 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index ea1d846c01..fff069e290 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -427,9 +427,12 @@ def _path(self, key: str) -> Path: def get(self, key: str) -> HostExecutionReceipt | None: record = self._read_record(key) + if isinstance(record, HostExecutionReceipt) and record.start_key != key: + raise HostAdapterError("host receipt key does not match its filename") return record if isinstance(record, HostExecutionReceipt) else None def put(self, key: str, receipt: HostExecutionReceipt) -> None: + receipt = _bind_host_receipt_key(key, receipt) path = self._path(key) with file_lock(path, stable_parent_authority=True): self._put_unlocked(path, receipt) @@ -438,10 +441,12 @@ def _put_unlocked(self, path: Path, receipt: HostExecutionReceipt) -> None: fd, temporary = tempfile.mkstemp(prefix=".host-receipt-", suffix=".tmp", dir=self.directory) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: - json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) + serialized = _bounded_host_json(receipt.to_dict()) + handle.write(serialized) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) + _fsync_directory(self.directory) finally: if os.path.exists(temporary): os.unlink(temporary) @@ -455,13 +460,18 @@ def put_merged( path = self._path(key) with file_lock(path, stable_parent_authority=True): persisted = self.get(key) - receipt = _receipt_after_persist(persisted, incoming, acknowledged_dispatch_id) + receipt = _receipt_after_persist( + persisted, + _bind_host_receipt_key(key, incoming), + acknowledged_dispatch_id, + ) self._put_unlocked(path, receipt) return receipt def claim_submission( self, key: str, receipt: HostExecutionReceipt, dispatch: PendingHostDispatch ) -> tuple[HostExecutionReceipt, bool]: + receipt = _bind_host_receipt_key(key, receipt) path = self._path(key) with file_lock(path, stable_parent_authority=True): persisted = self.get(key) @@ -473,6 +483,7 @@ def claim_submission( return claimed, True def put_if_absent(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt | None: + receipt = _bind_host_receipt_key(key, receipt) path = self._path(key) with file_lock(path, stable_parent_authority=True): if path.exists(): @@ -491,21 +502,21 @@ def reserve_start( ) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: - json.dump( - { - "kind": "start_reservation", - "key": reservation.key, - "arguments": _json_copy(reservation.arguments), - "created_at": reservation.created_at, - }, - handle, - ensure_ascii=False, - sort_keys=True, + handle.write( + _bounded_host_json( + { + "kind": "start_reservation", + "key": reservation.key, + "arguments": _json_copy(reservation.arguments), + "created_at": reservation.created_at, + } + ) ) handle.flush() os.fsync(handle.fileno()) try: os.link(temporary, path) + _fsync_directory(self.directory) except FileExistsError: existing = self._read_record(key) if existing is None: @@ -518,21 +529,25 @@ def reserve_start( def finalize_start(self, key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: """Replace the reservation with the first durable start receipt.""" - existing = self._read_record(key) - if isinstance(existing, HostExecutionReceipt): - return existing - if not isinstance(existing, HostStartReservation): - raise HostAdapterError(f"host start reservation disappeared for {key!r}") - self.put(key, receipt) - return self.get(key) or receipt + path = self._path(key) + with file_lock(path, stable_parent_authority=True): + existing = self._read_record(key) + if isinstance(existing, HostExecutionReceipt): + return existing + if not isinstance(existing, HostStartReservation): + raise HostAdapterError(f"host start reservation disappeared for {key!r}") + receipt = _bind_host_receipt_key(key, receipt) + self._put_unlocked(path, receipt) + return receipt def abort_start(self, key: str) -> None: path = self._path(key) - try: - if isinstance(self._read_record(key), HostStartReservation): - path.unlink() - except FileNotFoundError: - return + with file_lock(path, stable_parent_authority=True): + try: + if isinstance(self._read_record(key), HostStartReservation): + path.unlink() + except FileNotFoundError: + return def _read_record(self, key: str) -> HostExecutionReceipt | HostStartReservation | None: path = self._path(key) @@ -561,20 +576,45 @@ def _read_record(self, key: str) -> HostExecutionReceipt | HostStartReservation def _read_json(path: Path) -> Any: """Read a receipt without following a replacement symlink.""" flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) - descriptor = os.open(path, flags) + descriptor = -1 + parent_fd = -1 try: + if ( + os.name != "nt" + and hasattr(os, "O_DIRECTORY") + and os.open in os.supports_dir_fd + and os.stat in os.supports_dir_fd + and os.stat in os.supports_follow_symlinks + ): + parent_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + expected_parent = os.fstat(parent_fd) + descriptor = os.open(path.name, flags, dir_fd=parent_fd) + else: + descriptor = os.open(path, flags) file_stat = os.fstat(descriptor) if ( not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size > _MAX_HOST_RECEIPT_FILE_BYTES ): raise OSError("host receipt file exceeds the resource ceiling") - with os.fdopen(descriptor, "r", encoding="utf-8") as handle: + with os.fdopen(descriptor, "rb") as handle: descriptor = -1 - return json.load(handle) + data = handle.read(_MAX_HOST_RECEIPT_FILE_BYTES + 1) + if len(data) > _MAX_HOST_RECEIPT_FILE_BYTES: + raise OSError("host receipt file exceeds the resource ceiling") + if parent_fd >= 0: + current_parent = os.stat(path.parent, follow_symlinks=False) + if (expected_parent.st_dev, expected_parent.st_ino) != ( + current_parent.st_dev, + current_parent.st_ino, + ): + raise OSError("host receipt directory changed during read") + return json.loads(data.decode("utf-8")) finally: if descriptor >= 0: os.close(descriptor) + if parent_fd >= 0: + os.close(parent_fd) @dataclass(slots=True) @@ -600,6 +640,32 @@ def _json_copy(value: Any) -> Any: return value +def _bind_host_receipt_key(key: str, receipt: HostExecutionReceipt) -> HostExecutionReceipt: + """Keep a host receipt's durable key aligned with its filename.""" + if receipt.start_key and receipt.start_key != key: + raise HostAdapterError("host receipt key does not match its filename") + return receipt if receipt.start_key == key else replace(receipt, start_key=key) + + +def _bounded_host_json(value: Any) -> str: + """Serialize one host record without creating an unreadable receipt.""" + serialized = json.dumps(value, ensure_ascii=False, sort_keys=True) + if len(serialized.encode("utf-8")) > _MAX_HOST_RECEIPT_FILE_BYTES: + raise HostAdapterError("host receipt exceeds the resource ceiling") + return serialized + + +def _fsync_directory(directory: Path) -> None: + """Durably publish a host receipt rename on POSIX filesystems.""" + if os.name == "nt" or not hasattr(os, "O_DIRECTORY"): + return + descriptor = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + def _model_mapping(value: Any) -> dict[str, Any] | None: if isinstance(value, Mapping): return dict(value) @@ -742,6 +808,8 @@ def _now() -> str: def _start_key( invocation: HostInvocation, cwd: str | None, + *, + host_name: str = "", ) -> str: action = ( f"resume:{invocation.resume_auto_session_id}" @@ -750,6 +818,7 @@ def _start_key( ) return json.dumps( [ + host_name, invocation.host_session_id, invocation.command_prefix.casefold(), action, @@ -933,12 +1002,20 @@ async def start( raise HostAdapterError("cwd must not be empty") arguments["cwd"] = normalized_cwd - key = _start_key(invocation, normalized_cwd) + key = _start_key(invocation, normalized_cwd, host_name=self.host_name) async with self._start_locks.hold(key): cached = self._start_receipts.get(key) if cached is not None: return cached persisted = self.receipt_store.get(key) + if persisted is None: + legacy_key = _start_key(invocation, normalized_cwd) + if legacy_key != key: + legacy = self.receipt_store.get(legacy_key) + if legacy is not None and legacy.host_name == self.host_name: + migrated = replace(legacy, start_key=key) + self.receipt_store.put(key, migrated) + persisted = migrated if persisted is not None: self._start_receipts[key] = persisted return persisted @@ -968,6 +1045,9 @@ async def start( self.expected_runtime_backend is not None and runtime_backend != self.expected_runtime_backend ): + abort = getattr(self.receipt_store, "abort_start", None) + if callable(abort): + abort(key) raise HostAdapterError( "Ouroboros start_auto did not negotiate the expected host runtime " f"(expected={self.expected_runtime_backend!r}, received={runtime_backend!r})", diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index c264b1ceaf..2dc30ad3a1 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -12,7 +12,7 @@ import asyncio from collections.abc import Iterable, Mapping -from contextlib import asynccontextmanager +from contextlib import AbstractContextManager, asynccontextmanager from dataclasses import dataclass, field, replace from datetime import UTC, datetime import hashlib @@ -24,6 +24,7 @@ import stat import tempfile from typing import Any, Protocol +import unicodedata from ouroboros.core.file_lock import file_lock from ouroboros.integrations._keyed_locks import KeyedAsyncLockPool @@ -281,8 +282,8 @@ def _relative_host_path(self, path: Path) -> Path: root_parts = self.host_root.parts path_parts = path.parts if len(path_parts) < len(root_parts) or tuple( - part.casefold() for part in path_parts[: len(root_parts)] - ) != tuple(part.casefold() for part in root_parts): + _normalized_casefold(part) for part in path_parts[: len(root_parts)] + ) != tuple(_normalized_casefold(part) for part in root_parts): raise ValueError root_spelling = type(self.host_root)(*path_parts[: len(root_parts)]) try: @@ -396,6 +397,7 @@ def to_dict(self) -> dict[str, Any]: _MAX_RECEIPT_FILE_BYTES = 2 * 1024 * 1024 _MAX_BOUNDED_JSON_NODES = 4096 _RAW_PAYLOAD_TRUNCATION_MARKER = "...[raw payload truncated]" +_RESUME_LOCKS = KeyedAsyncLockPool() @dataclass(frozen=True, slots=True) @@ -595,10 +597,21 @@ def _path(self, key: str) -> Path: digest = hashlib.sha256(key.encode("utf-8")).hexdigest() return self.directory / f"{digest}.json" + def execution_lock(self, key: str) -> AbstractContextManager[None]: + """Return a cross-process lock for one remote resume operation.""" + digest = hashlib.sha256(key.encode("utf-8")).hexdigest() + return file_lock( + self.directory / f"{digest}.resume", + stable_parent_authority=True, + ) + def get(self, key: str) -> VMExecutionReceipt | None: path = self._path(key) try: - return VMExecutionReceipt.from_dict(self._read_json(path)) + receipt = VMExecutionReceipt.from_dict(self._read_json(path)) + if receipt.idempotency_key != key: + raise ValueError("receipt idempotency key does not match its filename") + return receipt except FileNotFoundError: return None except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: @@ -620,10 +633,14 @@ def _put_unlocked(self, receipt: VMExecutionReceipt, path: Path) -> None: fd, temporary = tempfile.mkstemp(prefix=".receipt-", suffix=".tmp", dir=self.directory) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: - json.dump(receipt.to_dict(), handle, ensure_ascii=False, sort_keys=True) + serialized = json.dumps(receipt.to_dict(), ensure_ascii=False, sort_keys=True) + if len(serialized.encode("utf-8")) > _MAX_RECEIPT_FILE_BYTES: + raise VMRuntimeError("VM receipt exceeds the resource ceiling") + handle.write(serialized) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) + _fsync_directory(self.directory) self._index_put(receipt, path.name) finally: if os.path.exists(temporary): @@ -657,6 +674,8 @@ def find(self, dispatch_id: str, session_id: str | None = None) -> VMExecutionRe path = self.directory / path_name try: receipt = VMExecutionReceipt.from_dict(self._read_json(path)) + if self._path(receipt.idempotency_key).name != path.name: + raise ValueError("receipt idempotency key does not match its filename") except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: raise VMRuntimeError(f"corrupt VM receipt file {path.name!r}") from exc if receipt.dispatch_id == dispatch_id and ( @@ -679,6 +698,8 @@ def _build_find_index(self, directory_mtime_ns: int) -> None: for path in self.directory.glob("*.json"): try: receipt = VMExecutionReceipt.from_dict(self._read_json(path)) + if self._path(receipt.idempotency_key).name != path.name: + raise ValueError("receipt idempotency key does not match its filename") except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: raise VMRuntimeError(f"corrupt VM receipt file {path.name!r}") from exc identity = (receipt.dispatch_id, receipt.session_id) @@ -718,17 +739,42 @@ def _directory_mtime_ns(self) -> int: def _read_json(path: Path) -> Any: """Read a receipt without following a replacement symlink.""" flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) - descriptor = os.open(path, flags) + descriptor = -1 + parent_fd = -1 try: + if ( + os.name != "nt" + and hasattr(os, "O_DIRECTORY") + and os.open in os.supports_dir_fd + and os.stat in os.supports_dir_fd + and os.stat in os.supports_follow_symlinks + ): + parent_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + expected_parent = os.fstat(parent_fd) + descriptor = os.open(path.name, flags, dir_fd=parent_fd) + else: + descriptor = os.open(path, flags) file_stat = os.fstat(descriptor) if not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size > _MAX_RECEIPT_FILE_BYTES: raise OSError("VM receipt file exceeds the resource ceiling") - with os.fdopen(descriptor, "r", encoding="utf-8") as handle: + with os.fdopen(descriptor, "rb") as handle: descriptor = -1 - return json.load(handle) + data = handle.read(_MAX_RECEIPT_FILE_BYTES + 1) + if len(data) > _MAX_RECEIPT_FILE_BYTES: + raise OSError("VM receipt file exceeds the resource ceiling") + if parent_fd >= 0: + current_parent = os.stat(path.parent, follow_symlinks=False) + if (expected_parent.st_dev, expected_parent.st_ino) != ( + current_parent.st_dev, + current_parent.st_ino, + ): + raise OSError("VM receipt directory changed during read") + return json.loads(data.decode("utf-8")) finally: if descriptor >= 0: os.close(descriptor) + if parent_fd >= 0: + os.close(parent_fd) class VMTransport(Protocol): @@ -1135,7 +1181,8 @@ def _put_without_claim(self, receipt: VMExecutionReceipt) -> VMExecutionReceipt def _validate_receipt_match(receipt: VMExecutionReceipt, request: VMExecutionRequest) -> None: """Reject accidental correlation-key reuse before touching the VM.""" if ( - receipt.dispatch_id != request.dispatch_id + receipt.idempotency_key != request.correlation_key + or receipt.dispatch_id != request.dispatch_id or receipt.session_id != request.session_id or receipt.command != request.command or receipt.vm_workspace != request.vm_workspace @@ -1149,6 +1196,22 @@ async def _resume_or_recover( self, receipt: VMExecutionReceipt, request: VMExecutionRequest, + ) -> VMExecutionReceipt: + async with _RESUME_LOCKS.hold(request.correlation_key): + durable_lock = getattr(self.receipt_store, "execution_lock", None) + if callable(durable_lock): + with durable_lock(request.correlation_key): + current = self.receipt_store.get(request.correlation_key) or receipt + self._validate_receipt_match(current, request) + if current.is_terminal: + return current + return await self._resume_or_recover_unlocked(current, request) + return await self._resume_or_recover_unlocked(receipt, request) + + async def _resume_or_recover_unlocked( + self, + receipt: VMExecutionReceipt, + request: VMExecutionRequest, ) -> VMExecutionReceipt: if receipt.execution_id is None: return self._store_recovery( @@ -1209,6 +1272,15 @@ async def _call_and_store( ) self._store_receipt(updated) raise + except ProcessLookupError as exc: + updated = replace( + receipt, + status="disconnected", + execution_id=getattr(exc, "execution_id", None) or receipt.execution_id, + error=f"VM subprocess disappeared: {exc}; refusing replay.", + recovery_required=True, + ) + return self._store_receipt(updated) except (ConnectionError, BrokenPipeError, EOFError) as exc: updated = replace( receipt, status="disconnected", error=str(exc), recovery_required=True @@ -1307,9 +1379,10 @@ def _receipt_from_response( status = "failed" if status in _REMOTE_RUNNING_STATUSES: status = "running" + known_artifact_paths = tuple(artifact.vm_path for artifact in receipt.artifacts) artifact_paths = _artifact_paths( payload, - request.artifact_paths, + (*request.artifact_paths, *known_artifact_paths), max_paths=self.max_artifact_paths, workspace=self.workspace, ) @@ -1341,7 +1414,7 @@ def _receipt_from_response( stderr=stderr, stderr_truncated=stderr_truncated, artifacts=artifacts, - artifact_paths=artifact_paths, + artifact_paths=request.artifact_paths, error=response_error, recovery_required=status in {"running", "disconnected", "accepted", "queued"}, finished_at=None if status == "running" else _now(), @@ -1370,6 +1443,22 @@ async def _await_if_needed(value: Any) -> Any: return value +def _normalized_casefold(value: str) -> str: + """Match case and canonical-equivalent spellings used by APFS.""" + return unicodedata.normalize("NFD", value).casefold() + + +def _fsync_directory(directory: Path) -> None: + """Durably publish a receipt rename on POSIX filesystems.""" + if os.name == "nt" or not hasattr(os, "O_DIRECTORY"): + return + descriptor = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + def _now() -> str: return datetime.now(UTC).isoformat() @@ -1663,19 +1752,42 @@ def _hash_file( relative_path=relative_path, ) try: - if path.stat().st_size > max_bytes: + resolved_path = path.resolve(strict=True) + if workspace_root is not None: + resolved_root = workspace_root.resolve(strict=True) + resolved_path.relative_to(resolved_root) + expected_stat = resolved_path.stat() + if not stat.S_ISREG(expected_stat.st_mode): + raise VMPathError(f"artifact path is not a regular file: {path}") + if expected_stat.st_size > max_bytes: raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") - except OSError as exc: + except (OSError, ValueError) as exc: raise VMPathError(f"artifact path cannot be read: {path}") from exc digest = hashlib.sha256() size = 0 flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) - with os.fdopen(os.open(path, flags), "rb") as handle: - for chunk in iter(lambda: handle.read(1024 * 1024), b""): - size += len(chunk) - if size > max_bytes: - raise VMPathError(f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}") - digest.update(chunk) + descriptor = os.open(resolved_path, flags | getattr(os, "O_NONBLOCK", 0)) + try: + opened_stat = os.fstat(descriptor) + if not stat.S_ISREG(opened_stat.st_mode): + raise VMPathError(f"artifact path is not a regular file: {path}") + if (opened_stat.st_dev, opened_stat.st_ino) != ( + expected_stat.st_dev, + expected_stat.st_ino, + ): + raise VMPathError(f"artifact path changed during access: {path}") + with os.fdopen(descriptor, "rb") as handle: + descriptor = -1 + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + size += len(chunk) + if size > max_bytes: + raise VMPathError( + f"artifact exceeds the {max_bytes}-byte resource ceiling: {path}" + ) + digest.update(chunk) + finally: + if descriptor >= 0: + os.close(descriptor) return size, digest.hexdigest() @@ -1726,7 +1838,7 @@ def _hash_file_beneath( parent_fd = next_fd file_fd = os.open( relative.parts[-1], - os.O_RDONLY | nofollow, + os.O_RDONLY | nofollow | getattr(os, "O_NONBLOCK", 0), dir_fd=parent_fd, ) try: diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 6e4e9cc837..dde337ef3d 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from dataclasses import replace import json from pathlib import Path @@ -47,6 +48,86 @@ def test_ordinary_messages_are_not_claimed() -> None: assert parse_explicit_invocation("a sentence containing /ouroboros midway") is None +@pytest.mark.asyncio +async def test_receipt_namespace_includes_host_identity(tmp_path: Path) -> None: + calls: list[str] = [] + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + assert name == "ouroboros_start_auto" + calls.append(name) + host = "personal" if len(calls) == 1 else "grok" + return { + "meta": { + "job_id": f"job-{host}", + "auto_session_id": f"auto-{host}", + "runtime_backend": "host", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + personal = PersonalAgentHostAdapter(call_tool, host_name="personal", receipt_store=store) + grok = PersonalAgentHostAdapter(call_tool, host_name="grok_bot", receipt_store=store) + + first = await personal.start("/ouroboros same request", host_session_id="session") + second = await grok.start("/ouroboros same request", host_session_id="session") + + assert first is not None and second is not None + assert first.host_name == "personal" + assert second.host_name == "grok_bot" + assert first.job_id != second.job_id + assert len(calls) == 2 + + +@pytest.mark.asyncio +async def test_host_receipt_replace_failure_preserves_previous_record( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import ouroboros.integrations.personal_agent_host as host_module + + async def call_tool(_name: str, _arguments: dict[str, object]) -> dict[str, object]: + return { + "meta": { + "job_id": "job-partial", + "auto_session_id": "auto-partial", + "runtime_backend": "host", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + receipt = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros partial write", host_session_id="partial" + ) + assert receipt is not None + + def fail_replace(_source: str, _destination: str) -> None: + raise OSError("simulated publish crash") + + monkeypatch.setattr(host_module.os, "replace", fail_replace) + with pytest.raises(OSError, match="simulated publish crash"): + store.put(receipt.start_key, receipt) + + assert store.get(receipt.start_key) == receipt + assert not tuple(store.directory.glob(".host-receipt-*.tmp")) + + +def test_host_receipt_write_is_bounded(tmp_path: Path) -> None: + store = JsonHostReceiptStore(tmp_path / "host-receipts") + invocation = parse_explicit_invocation("/ouroboros bounded", host_session_id="session") + assert invocation is not None + receipt = HostExecutionReceipt( + host_name="personal", + invocation=invocation, + auto_session_id="auto", + job_id="job", + status="queued", + start_key="key", + state={"large": "x" * (2 * 1024 * 1024)}, + ) + + with pytest.raises(HostAdapterError, match="resource ceiling"): + store.put("key", replace(receipt, start_key="key")) + + def test_explicit_goal_preserves_the_full_user_payload() -> None: invocation = parse_explicit_invocation( " /ouroboros refactor the payment boundary\nwhile preserving recovery ", @@ -604,6 +685,36 @@ def test_json_store_rejects_an_oversized_receipt_file(tmp_path: Path) -> None: store.get("oversized") +@pytest.mark.asyncio +async def test_json_host_receipt_store_rejects_a_symlinked_receipt_directory( + tmp_path: Path, +) -> None: + async def call_tool(_name: str, _arguments: dict[str, object]) -> dict[str, object]: + return { + "meta": { + "job_id": "job-parent-link", + "auto_session_id": "auto-parent-link", + "runtime_backend": "host", + } + } + + store = JsonHostReceiptStore(tmp_path / "receipts") + receipt = await PersonalAgentHostAdapter(call_tool, receipt_store=store).start( + "/ouroboros parent link", host_session_id="parent-link" + ) + assert receipt is not None + path = store._path(receipt.start_key) + original = tmp_path / "original-receipts" + outside = tmp_path / "outside-receipts" + outside.mkdir() + (outside / path.name).write_bytes(path.read_bytes()) + store.directory.rename(original) + store.directory.symlink_to(outside, target_is_directory=True) + + with pytest.raises(HostAdapterError, match="corrupt host receipt"): + store.get(receipt.start_key) + + @pytest.mark.asyncio async def test_explicit_start_rejection_releases_the_reservation_for_retry( tmp_path: Path, @@ -640,6 +751,37 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 2 +@pytest.mark.asyncio +async def test_backend_negotiation_failure_releases_the_reservation_for_retry( + tmp_path: Path, +) -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + return { + "meta": { + "job_id": f"job-{calls}", + "auto_session_id": f"auto-{calls}", + "runtime_backend": "vm" if calls == 1 else "host", + "status": "queued", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + with pytest.raises(HostAdapterError, match="expected host runtime"): + await adapter.start("/ouroboros backend retry", host_session_id="backend") + + receipt = await adapter.start("/ouroboros backend retry", host_session_id="backend") + + assert receipt is not None + assert receipt.job_id == "job-2" + assert calls == 2 + + @pytest.mark.asyncio async def test_start_supports_a_legacy_receipt_store_without_atomic_claim() -> None: class LegacyReceiptStore: diff --git a/tests/unit/integrations/test_vm_agent_runtime_round15.py b/tests/unit/integrations/test_vm_agent_runtime_round15.py index 2721b0b63c..d2a89a1e6d 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round15.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round15.py @@ -3,9 +3,12 @@ from __future__ import annotations import asyncio +from dataclasses import replace from pathlib import Path from typing import Any +import pytest + from ouroboros.integrations import ( CommandVMTransport, JsonVMReceiptStore, @@ -20,6 +23,95 @@ async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any] return {"status": "completed", "exit_code": 0} +def test_provider_artifacts_do_not_change_replay_identity(tmp_path: Path) -> None: + artifact = tmp_path / "provider.txt" + artifact.write_text("provider output", encoding="utf-8") + + class ProviderArtifactCommand: + calls = 0 + + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + self.calls += 1 + return { + "status": "completed", + "exit_code": 0, + "artifacts": ["provider.txt"], + } + + target = ProviderArtifactCommand() + runtime = VMPersonalAgentRuntime( + CommandVMTransport(target), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + first = asyncio.run(runtime.execute_command("verify", dispatch_id="provider", session_id="s")) + second = asyncio.run(runtime.execute_command("verify", dispatch_id="provider", session_id="s")) + + assert first == second + assert first.artifact_paths == () + assert first.artifacts[0].relative_path == "provider.txt" + assert target.calls == 1 + + +def test_resume_recollects_provider_artifacts_from_the_running_receipt( + tmp_path: Path, +) -> None: + artifact = tmp_path / "provider.txt" + artifact.write_text("provider output", encoding="utf-8") + + class ResumableProviderArtifactCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return { + "status": "running", + "execution_id": "remote-provider-artifact", + "artifacts": ["provider.txt"], + } + + async def resume_execution(self, _execution_id: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "completed", "exit_code": 0} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(ResumableProviderArtifactCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + running = asyncio.run(runtime.execute_command("verify", dispatch_id="provider", session_id="s")) + resumed = asyncio.run(runtime.resume_dispatch("provider", session_id="s")) + + assert running.artifacts[0].relative_path == "provider.txt" + assert resumed.status == "completed" + assert resumed.artifacts[0].relative_path == "provider.txt" + + +def test_vm_receipt_replace_failure_preserves_previous_record( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import ouroboros.integrations.vm_agent_runtime as runtime_module + + store = JsonVMReceiptStore(tmp_path / "receipts") + + class RunningCommand: + async def execute_command(self, _command: str, **_kwargs: Any) -> dict[str, Any]: + return {"status": "running", "execution_id": "remote-partial"} + + runtime = VMPersonalAgentRuntime( + CommandVMTransport(RunningCommand()), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=store, + ) + existing = asyncio.run(runtime.execute_command("verify", dispatch_id="partial", session_id="s")) + + def fail_replace(_source: str, _destination: str) -> None: + raise OSError("simulated publish crash") + + monkeypatch.setattr(runtime_module.os, "replace", fail_replace) + with pytest.raises(OSError, match="simulated publish crash"): + store.put(replace(existing, error="updated")) + + assert store.get(existing.idempotency_key) == existing + assert not tuple(store.directory.glob(".receipt-*.tmp")) + + def test_vm_request_materializes_one_shot_artifact_iterables() -> None: request = VMExecutionRequest( dispatch_id="dispatch", diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py index f0b73b4150..b9cb81b95b 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round17.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -2,8 +2,10 @@ from __future__ import annotations +import asyncio from dataclasses import replace import hashlib +import json import os from pathlib import Path from typing import Any @@ -52,6 +54,61 @@ def test_artifact_hash_rejects_a_parent_symlink_after_path_resolution( _hash_file(resolved_target, 1024, workspace_root=workspace) +def test_fallback_artifact_hash_rejects_workspace_swap( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import ouroboros.integrations.vm_agent_runtime as runtime_module + + workspace = tmp_path / "workspace" + workspace.mkdir() + target = workspace / "result.txt" + target.write_text("inside", encoding="utf-8") + original_workspace = tmp_path / "original-workspace" + real_open = os.open + swapped = False + + def racing_open(path: Any, flags: int, *args: Any, **kwargs: Any) -> int: + nonlocal swapped + if Path(path) == target and not swapped: + workspace.rename(original_workspace) + workspace.mkdir() + (workspace / "result.txt").write_text("outside", encoding="utf-8") + swapped = True + return real_open(path, flags, *args, **kwargs) + + monkeypatch.setattr( + runtime_module.os, + "supports_dir_fd", + set(runtime_module.os.supports_dir_fd) - {runtime_module.os.open}, + ) + monkeypatch.setattr(runtime_module.os, "open", racing_open) + + with pytest.raises(VMPathError, match="changed during access"): + _hash_file(target, 1024, workspace_root=workspace) + + +def test_fallback_artifact_hash_rejects_a_fifo_without_blocking( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + if not hasattr(os, "mkfifo"): + pytest.skip("FIFO creation is unavailable") + + import ouroboros.integrations.vm_agent_runtime as runtime_module + + workspace = tmp_path / "workspace" + workspace.mkdir() + fifo = workspace / "result.txt" + os.mkfifo(fifo) + monkeypatch.setattr( + runtime_module.os, + "supports_dir_fd", + set(runtime_module.os.supports_dir_fd) - {runtime_module.os.open}, + ) + + with pytest.raises(VMPathError, match="regular file"): + _hash_file(fifo, 1024, workspace_root=workspace) + + def test_artifact_hash_uses_the_verified_relative_path_for_case_variant_spelling( tmp_path: Path, ) -> None: @@ -72,6 +129,29 @@ def test_artifact_hash_uses_the_verified_relative_path_for_case_variant_spelling assert digest == hashlib.sha256(b"inside").hexdigest() +def test_workspace_mapping_accepts_apfs_normalized_case_variant( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import unicodedata + + import ouroboros.integrations.vm_agent_runtime as runtime_module + + workspace = tmp_path / "CaféRoot" + (workspace / "Payload").mkdir(parents=True) + + def samefile(left: str | Path, right: str | Path) -> bool: + def normalize(value: str | Path) -> str: + return unicodedata.normalize("NFD", str(value)).casefold() + + return normalize(left) == normalize(right) + + monkeypatch.setattr(runtime_module.os.path, "samefile", samefile) + mapper = VMWorkspaceMapper(workspace, "/workspace") + variant = tmp_path / "cafe\u0301root" / "payload" + + assert mapper.map_host_path(variant) == "/workspace/payload" + + def test_artifact_hash_rejects_workspace_replacement_before_open( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -138,6 +218,36 @@ def recording_close(descriptor: int) -> None: assert closed +def test_json_vm_receipt_store_rejects_a_symlinked_receipt_directory( + tmp_path: Path, +) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + receipt = VMExecutionReceipt( + dispatch_id="parent-link", + session_id="tenant-a", + idempotency_key="tenant-a:parent-link", + status="completed", + command="verify", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + started_at="now", + finished_at="later", + ) + store.put(receipt) + original = tmp_path / "original-receipts" + outside = tmp_path / "outside-receipts" + outside.mkdir() + (outside / store._path(receipt.idempotency_key).name).write_bytes( + store._path(receipt.idempotency_key).read_bytes() + ) + store.directory.rename(original) + store.directory.symlink_to(outside, target_is_directory=True) + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt"): + store.get(receipt.idempotency_key) + + def test_terminal_vm_receipt_cannot_be_regressed_by_a_stale_write(tmp_path: Path) -> None: store = JsonVMReceiptStore(tmp_path / "receipts") terminal = VMExecutionReceipt( @@ -163,6 +273,26 @@ def test_terminal_vm_receipt_cannot_be_regressed_by_a_stale_write(tmp_path: Path assert persisted.stdout == "done" +def test_vm_receipt_payload_must_match_its_filename_key(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + receipt = VMExecutionReceipt( + dispatch_id="other-dispatch", + session_id="tenant-a", + idempotency_key="other-key", + status="completed", + command="verify", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + started_at="now", + finished_at="later", + ) + store._path("expected-key").write_text(json.dumps(receipt.to_dict()), encoding="utf-8") + + with pytest.raises(VMRuntimeError, match="corrupt VM receipt"): + store.get("expected-key") + + @pytest.mark.asyncio async def test_resume_requires_a_session_binding_for_tenant_isolation(tmp_path: Path) -> None: class Disconnected: @@ -219,6 +349,65 @@ async def resume(self, _request: Any, _execution_id: str) -> Any: assert transport.resume_calls == 0 +@pytest.mark.asyncio +async def test_subprocess_lookup_failure_requires_recovery_without_replay(tmp_path: Path) -> None: + class CrashedProcess: + execute_calls = 0 + + async def execute(self, _request: Any) -> Any: + self.execute_calls += 1 + raise ProcessLookupError("worker exited") + + transport = CrashedProcess() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + first = await runtime.execute_command("verify", dispatch_id="crashed", session_id="tenant-a") + second = await runtime.execute_command("verify", dispatch_id="crashed", session_id="tenant-a") + + assert first.status == "disconnected" + assert first.recovery_required is True + assert second.status == "recovery_required" + assert transport.execute_calls == 1 + + +@pytest.mark.asyncio +async def test_concurrent_runtimes_resume_one_remote_execution(tmp_path: Path) -> None: + class Resumable: + def __init__(self) -> None: + self.resume_calls = 0 + self.started = asyncio.Event() + self.release = asyncio.Event() + + async def execute(self, _request: Any) -> Any: + return {"status": "running", "execution_id": "remote-resume"} + + async def resume(self, _request: Any, _execution_id: str) -> Any: + self.resume_calls += 1 + self.started.set() + await self.release.wait() + return {"status": "completed", "exit_code": 0} + + transport = Resumable() + store = JsonVMReceiptStore(tmp_path / "receipts") + workspace = VMWorkspaceMapper(tmp_path, "/workspace") + first = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + second = VMPersonalAgentRuntime(transport, workspace=workspace, receipt_store=store) + await first.execute_command("verify", dispatch_id="resume-race", session_id="tenant-a") + + first_task = asyncio.create_task(first.resume_dispatch("resume-race", session_id="tenant-a")) + await transport.started.wait() + second_task = asyncio.create_task(second.resume_dispatch("resume-race", session_id="tenant-a")) + await asyncio.sleep(0) + transport.release.set() + resumed = await asyncio.gather(first_task, second_task) + + assert {receipt.status for receipt in resumed} == {"completed"} + assert transport.resume_calls == 1 + + def test_host_rejects_non_string_session_identity() -> None: with pytest.raises(HostAdapterError, match="host_session_id must be a string"): parse_explicit_invocation("/ouroboros verify", host_session_id=object()) # type: ignore[arg-type] From 9a18ef34ef43530b5e831ae965e642a3ba850ce5 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 10:38:09 +0900 Subject: [PATCH 37/41] fix(vm): harden workspace and receipt boundaries --- .../integrations/personal_agent_host.py | 5 +++- .../integrations/vm_agent_runtime.py | 24 +++++++++++++++---- .../integrations/test_vm_agent_runtime.py | 1 + 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index fff069e290..6849fb078b 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -418,8 +418,11 @@ class JsonHostReceiptStore: """Atomic JSON store for host receipts that must survive process restarts.""" def __init__(self, directory: str | Path) -> None: - self.directory = Path(directory).expanduser().resolve() + self.directory = Path(directory).expanduser().absolute() self.directory.mkdir(parents=True, exist_ok=True) + directory_stat = self.directory.lstat() + if stat.S_ISLNK(directory_stat.st_mode) or not stat.S_ISDIR(directory_stat.st_mode): + raise HostAdapterError("host receipt directory must be a real directory") def _path(self, key: str) -> Path: digest = hashlib.sha256(key.encode("utf-8")).hexdigest() diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 2dc30ad3a1..4be3090181 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -160,6 +160,7 @@ class VMWorkspaceMapper: host_root: Path vm_root: PurePosixPath + _host_identity: tuple[int, int] def __init__(self, host_root: str | Path, vm_root: str) -> None: host_text = _path_text(host_root, "host_root") @@ -167,14 +168,18 @@ def __init__(self, host_root: str | Path, vm_root: str) -> None: try: host = Path(host_text).expanduser().resolve() vm = PurePosixPath(vm_text) + host_stat = host.stat() except (OSError, RuntimeError, ValueError) as exc: raise VMPathError("workspace paths must be valid paths") from exc + if not stat.S_ISDIR(host_stat.st_mode): + raise VMPathError("host_root must be a directory") if not vm.is_absolute(): raise VMPathError("vm_root must be an absolute POSIX path") if ".." in vm.parts: raise VMPathError("vm_root must not contain parent traversal") object.__setattr__(self, "host_root", host) object.__setattr__(self, "vm_root", vm) + object.__setattr__(self, "_host_identity", (host_stat.st_dev, host_stat.st_ino)) def map_host_path(self, path: str | Path) -> str: """Map an approved host path to its VM path, rejecting escapes.""" @@ -275,6 +280,12 @@ def _resolve_host_path(self, path: str | Path) -> Path: def _relative_host_path(self, path: Path) -> Path: """Return a relative path while verifying case-folded roots by identity.""" + try: + current_root = self.host_root.stat() + except OSError as exc: + raise ValueError from exc + if (current_root.st_dev, current_root.st_ino) != self._host_identity: + raise ValueError try: return path.relative_to(self.host_root) except ValueError: @@ -586,8 +597,11 @@ class JsonVMReceiptStore: """Atomic JSON receipt store that survives host process restarts.""" def __init__(self, directory: str | Path) -> None: - self.directory = Path(directory).expanduser().resolve() + self.directory = Path(directory).expanduser().absolute() self.directory.mkdir(parents=True, exist_ok=True) + directory_stat = self.directory.lstat() + if stat.S_ISLNK(directory_stat.st_mode) or not stat.S_ISDIR(directory_stat.st_mode): + raise VMRuntimeError("VM receipt directory must be a real directory") self._find_index_by_dispatch: dict[str, set[str]] | None = None self._find_index_by_pair: dict[tuple[str, str], set[str]] | None = None self._find_index_paths: dict[str, tuple[str, str]] | None = None @@ -1077,6 +1091,8 @@ async def resume_dispatch( receipt = self.receipt_store.find(dispatch_id, session_id) if receipt is None: raise VMRuntimeError(f"no persisted VM receipt for dispatch {dispatch_id}") + if len(receipt.artifact_paths) > self.max_artifact_paths: + raise VMRuntimeError("persisted VM receipt exceeds the configured artifact path limit") approved_host_workspace = self.workspace.map_vm_path(receipt.vm_workspace) persisted_request = VMExecutionRequest( dispatch_id=receipt.dispatch_id, @@ -1291,7 +1307,7 @@ async def _call_and_store( return self._store_receipt(updated) try: - updated = self._receipt_from_response(receipt, request, raw) + updated = await self._receipt_from_response(receipt, request, raw) except Exception as exc: # malformed response evidence belongs in the receipt updated = replace( receipt, @@ -1352,7 +1368,7 @@ def _prepare_request(self, request: VMExecutionRequest) -> VMExecutionRequest: vm_artifact_paths=vm_artifact_paths, ) - def _receipt_from_response( + async def _receipt_from_response( self, receipt: VMExecutionReceipt, request: VMExecutionRequest, @@ -1386,7 +1402,7 @@ def _receipt_from_response( max_paths=self.max_artifact_paths, workspace=self.workspace, ) - artifacts = self.collect_artifacts(artifact_paths) + artifacts = await asyncio.to_thread(self.collect_artifacts, artifact_paths) stdout, stdout_truncated = _truncate_text( _optional_text(payload, "stdout") or _optional_text(payload, "output") or "", self.max_output_chars, diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 71ff2b71de..baf19e51ab 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -713,6 +713,7 @@ async def test_unique_dispatch_stress_releases_idle_lock_entries(tmp_path: Path) CommandVMTransport(RecordingCommand()), workspace=VMWorkspaceMapper(tmp_path, "/workspace"), receipt_store=SinkReceiptStore(), + max_queue_size=512, ) await asyncio.gather( From c3ce2813960943eaffb6caa9b80e8e648638776d Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 14:21:56 +0900 Subject: [PATCH 38/41] test(vm): add round nineteen trust boundary regressions --- .../test_vm_agent_runtime_round17.py | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/tests/unit/integrations/test_vm_agent_runtime_round17.py b/tests/unit/integrations/test_vm_agent_runtime_round17.py index b9cb81b95b..935d14e48c 100644 --- a/tests/unit/integrations/test_vm_agent_runtime_round17.py +++ b/tests/unit/integrations/test_vm_agent_runtime_round17.py @@ -152,6 +152,20 @@ def normalize(value: str | Path) -> str: assert mapper.map_host_path(variant) == "/workspace/payload" +def test_workspace_mapping_rejects_root_replacement_before_mapping(tmp_path: Path) -> None: + workspace = tmp_path / "workspace" + workspace.mkdir() + mapper = VMWorkspaceMapper(workspace, "/workspace") + + original = tmp_path / "original-workspace" + workspace.rename(original) + workspace.mkdir() + (workspace / "result.txt").write_text("replacement", encoding="utf-8") + + with pytest.raises(VMPathError, match="escapes"): + mapper.map_host_path(workspace / "result.txt") + + def test_artifact_hash_rejects_workspace_replacement_before_open( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -408,6 +422,84 @@ async def resume(self, _request: Any, _execution_id: str) -> Any: assert transport.resume_calls == 1 +@pytest.mark.asyncio +async def test_cancelled_queued_execution_releases_admission_capacity(tmp_path: Path) -> None: + class BlockingTransport: + def __init__(self) -> None: + self.started = asyncio.Event() + self.release = asyncio.Event() + + async def execute(self, _request: Any) -> Any: + self.started.set() + await self.release.wait() + return {"status": "completed", "exit_code": 0} + + transport = BlockingTransport() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + max_concurrent_executions=1, + max_queue_size=1, + ) + first = asyncio.create_task( + runtime.execute_command("first", dispatch_id="first", session_id="session") + ) + await transport.started.wait() + queued = asyncio.create_task( + runtime.execute_command("queued", dispatch_id="queued", session_id="session") + ) + for _ in range(20): + if runtime.resource_snapshot.queued_executions == 1: + break + await asyncio.sleep(0) + queued.cancel() + with pytest.raises(asyncio.CancelledError): + await queued + + transport.release.set() + assert (await first).status == "completed" + assert runtime.resource_snapshot.active_executions == 0 + assert runtime.resource_snapshot.queued_executions == 0 + + +@pytest.mark.asyncio +async def test_resume_rejects_persisted_artifact_count_over_runtime_limit(tmp_path: Path) -> None: + class ResumeProbe: + resume_calls = 0 + + async def resume(self, _request: Any, _execution_id: str) -> Any: + self.resume_calls += 1 + return {"status": "completed", "exit_code": 0} + + store = JsonVMReceiptStore(tmp_path / "receipts") + store.put( + VMExecutionReceipt( + dispatch_id="artifact-limit", + session_id="session", + idempotency_key="session:artifact-limit", + status="running", + command="verify", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + execution_id="remote-artifact-limit", + artifact_paths=("one.txt", "two.txt"), + started_at="now", + ) + ) + transport = ResumeProbe() + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=store, + max_artifact_paths=1, + ) + + with pytest.raises(VMRuntimeError, match="artifact path limit"): + await runtime.resume_dispatch("artifact-limit", session_id="session") + assert transport.resume_calls == 0 + + def test_host_rejects_non_string_session_identity() -> None: with pytest.raises(HostAdapterError, match="host_session_id must be a string"): parse_explicit_invocation("/ouroboros verify", host_session_id=object()) # type: ignore[arg-type] From c35aab44f77d2ed85f5290a5a644efe9d31cab97 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 15:05:03 +0900 Subject: [PATCH 39/41] fix(vm): bound raw receipt evidence on reload --- .../integrations/vm_agent_runtime.py | 9 ++-- .../integrations/test_vm_agent_runtime.py | 52 +++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index 4be3090181..da119f6f59 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -501,6 +501,9 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: raw_payload = value.get("raw", {}) if not isinstance(raw_payload, Mapping): raise ValueError("raw receipt payload must be an object") + bounded_raw = _bounded_json_value(raw_payload, _MAX_RAW_RECEIPT_CHARS) + if not isinstance(bounded_raw, Mapping): + bounded_raw = {"value": _RAW_PAYLOAD_TRUNCATION_MARKER} status = _receipt_text(value.get("status"), "status") if status not in _RECEIPT_STATUSES: raise ValueError(f"receipt status is unsupported: {status!r}") @@ -535,7 +538,7 @@ def from_dict(cls, value: Mapping[str, Any]) -> VMExecutionReceipt: ), started_at=_receipt_text(value.get("started_at", ""), "started_at", allow_empty=True), finished_at=_receipt_optional_text(value.get("finished_at"), "finished_at"), - raw=dict(raw_payload), + raw=dict(bounded_raw), ) @@ -1934,7 +1937,7 @@ def _bounded_json_value( return _RAW_PAYLOAD_TRUNCATION_MARKER return result if isinstance(value, str): - if _json_size(value) <= budget: + if len(value) <= budget and _json_size(value) <= budget: return value return _truncate_json_string(value, budget) if isinstance(value, int) and not isinstance(value, bool) and value.bit_length() > budget * 3: @@ -1957,7 +1960,7 @@ def _truncate_json_string(value: str, budget: int) -> str: if _json_size(marker) > budget: return "" low = 0 - high = len(value) + high = min(len(value), budget) while low < high: midpoint = (low + high + 1) // 2 if _json_size(value[:midpoint] + marker) <= budget: diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index baf19e51ab..35744cd320 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -805,6 +805,58 @@ async def execute(self, _request: Any) -> dict[str, Any]: assert len(json.dumps(receipt.raw, ensure_ascii=False).encode("utf-8")) <= 256 * 1024 +@pytest.mark.asyncio +async def test_raw_receipt_budget_handles_a_giant_provider_string(tmp_path: Path) -> None: + class GiantMetadataTransport: + async def execute(self, _request: Any) -> dict[str, Any]: + return { + "status": "completed", + "exit_code": 0, + "metadata": {"debug": "x" * (2 * 1024 * 1024)}, + } + + runtime = VMPersonalAgentRuntime( + GiantMetadataTransport(), + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + ) + + receipt = await runtime.execute_command("verify", dispatch_id="giant-raw", session_id="s") + + metadata = receipt.raw["metadata"] + assert isinstance(metadata, dict) + assert metadata["debug"].endswith("...[raw payload truncated]") + assert len(json.dumps(receipt.raw, ensure_ascii=False).encode("utf-8")) <= 256 * 1024 + + +def test_reloaded_receipt_raw_payload_is_bounded_before_exposure(tmp_path: Path) -> None: + store = JsonVMReceiptStore(tmp_path / "receipts") + receipt = VMExecutionReceipt( + dispatch_id="raw-reload", + session_id="session", + idempotency_key="session:raw-reload", + status="completed", + command="verify", + host_workspace=str(tmp_path), + vm_workspace="/workspace", + timeout_seconds=30.0, + started_at="now", + finished_at="later", + ) + store.put(receipt) + path = store._path(receipt.idempotency_key) + payload = json.loads(path.read_text(encoding="utf-8")) + payload["raw"] = {"metadata": {"debug": "x" * (512 * 1024)}} + path.write_text(json.dumps(payload), encoding="utf-8") + + reloaded = store.get(receipt.idempotency_key) + + assert reloaded is not None + metadata = reloaded.raw["metadata"] + assert isinstance(metadata, dict) + assert metadata["debug"].endswith("...[raw payload truncated]") + assert len(json.dumps(reloaded.raw).encode("utf-8")) <= 256 * 1024 + + def test_json_receipt_store_rejects_an_oversized_receipt_file(tmp_path: Path) -> None: store = JsonVMReceiptStore(tmp_path / "receipts") store._path("oversized").write_bytes(b"{" + b"x" * (2 * 1024 * 1024) + b"}") From 7ce877c8c443c364ece46f3fdb0512670431ed99 Mon Sep 17 00:00:00 2001 From: lee3Q Date: Tue, 1 Dec 2026 20:01:27 +0900 Subject: [PATCH 40/41] fix(vm): harden retry and start receipt recovery --- .../integrations/personal_agent_host.py | 100 +++++++++++++++--- .../integrations/vm_agent_runtime.py | 1 + .../integrations/test_personal_agent_host.py | 73 +++++++++++++ .../integrations/test_vm_agent_runtime.py | 36 ++++++- 4 files changed, 196 insertions(+), 14 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 6849fb078b..8910f249c5 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -1057,20 +1057,51 @@ async def start( tool_name=START_AUTO_TOOL, response=response, ) - auto_session_id = _required_text(payload, "auto_session_id", START_AUTO_TOOL) - job_id = _required_text(payload, "job_id", START_AUTO_TOOL) - receipt = _receipt_from_payload( - host_name=self.host_name, - invocation=invocation, - auto_session_id=auto_session_id, - job_id=job_id, - payload=payload, - response=response, - start_response=response, - start_key=key, - ) - finalized = finalize(key, receipt) + try: + auto_session_id = _required_text(payload, "auto_session_id", START_AUTO_TOOL) + job_id = _required_text(payload, "job_id", START_AUTO_TOOL) + receipt = _receipt_from_payload( + host_name=self.host_name, + invocation=invocation, + auto_session_id=auto_session_id, + job_id=job_id, + payload=payload, + response=response, + start_response=response, + start_key=key, + ) + except Exception as exc: + receipt = _start_recovery_receipt( + host_name=self.host_name, + invocation=invocation, + key=key, + payload=payload, + response=response, + error=exc, + ) + try: + finalized = finalize(key, receipt) + except Exception as exc: + # A malformed or oversized successful response must still + # leave a durable outcome. Retry finalization with a + # bounded recovery receipt so a serialization failure + # cannot strand the reservation or permit a duplicate. + recovery = _start_recovery_receipt( + host_name=self.host_name, + invocation=invocation, + key=key, + payload={}, + response=response, + error=exc, + ) + finalized = finalize(key, recovery) self._start_receipts[key] = finalized + if finalized.status == "recovery_required": + raise HostAdapterError( + str(finalized.failure.get("message", "start_auto response is invalid")), + tool_name=START_AUTO_TOOL, + response=response, + ) return finalized response = await self._call(START_AUTO_TOOL, arguments) @@ -1555,6 +1586,49 @@ def _receipt_from_payload( ) +def _start_recovery_receipt( + *, + host_name: str, + invocation: HostInvocation, + key: str, + payload: Mapping[str, Any], + response: HostToolResponse, + error: Exception, +) -> HostExecutionReceipt: + """Resolve a successful but unusable start without permitting a duplicate.""" + token = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16] + auto_session_id = payload.get("auto_session_id") + job_id = payload.get("job_id") + safe_auto_session_id = ( + auto_session_id.strip() + if isinstance(auto_session_id, str) and auto_session_id.strip() + else f"unknown-start-{token}" + ) + safe_job_id = ( + job_id.strip() if isinstance(job_id, str) and job_id.strip() else f"unknown-start-{token}" + ) + message = str(error) + return HostExecutionReceipt( + host_name=host_name, + invocation=invocation, + auto_session_id=safe_auto_session_id, + job_id=safe_job_id, + status="recovery_required", + start_key=key, + failure={ + "message": message, + "kind": "invalid_start_auto_response", + }, + recovery={ + "action": "inspect_start_auto_outcome", + "reason": "start_auto returned an unusable success response", + }, + state={"start_auto_response": "payload validation failed; inspect the live start outcome"}, + start_response=response, + last_response=response, + ) + + def _host_receipt_from_dict( receipt_type: type[HostExecutionReceipt], value: Mapping[str, Any] ) -> HostExecutionReceipt: diff --git a/src/ouroboros/integrations/vm_agent_runtime.py b/src/ouroboros/integrations/vm_agent_runtime.py index da119f6f59..4e02f2f0b8 100644 --- a/src/ouroboros/integrations/vm_agent_runtime.py +++ b/src/ouroboros/integrations/vm_agent_runtime.py @@ -1205,6 +1205,7 @@ def _validate_receipt_match(receipt: VMExecutionReceipt, request: VMExecutionReq or receipt.session_id != request.session_id or receipt.command != request.command or receipt.vm_workspace != request.vm_workspace + or receipt.timeout_seconds != request.timeout_seconds or receipt.artifact_paths != request.artifact_paths ): raise VMRuntimeError( diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index dde337ef3d..98ffce5c6a 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -782,6 +782,79 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 2 +@pytest.mark.asyncio +async def test_invalid_start_response_is_durable_across_a_fresh_adapter_retry( + tmp_path: Path, +) -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + return { + "meta": { + "job_id": "job-without-session", + "runtime_backend": "host", + "status": "queued", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + first = PersonalAgentHostAdapter(call_tool, receipt_store=store) + with pytest.raises(HostAdapterError, match="missing required auto_session_id"): + await first.start("/ouroboros preserve an unusable start", host_session_id="missing") + + second = PersonalAgentHostAdapter(call_tool, receipt_store=store) + recovered = await second.start( + "/ouroboros preserve an unusable start", host_session_id="missing" + ) + + assert recovered is not None + assert recovered.status == "recovery_required" + assert recovered.failure["kind"] == "invalid_start_auto_response" + assert recovered.auto_session_id.startswith("unknown-start-") + assert calls == 1 + + +@pytest.mark.asyncio +async def test_oversized_invalid_start_response_resolves_the_reservation( + tmp_path: Path, +) -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + return { + "meta": { + "job_id": "job-oversized-invalid", + "auto_session_id": "auto-oversized-invalid", + "runtime_backend": "host", + "status": "queued", + "diagnostic": "x" * (2 * 1024 * 1024), + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + first = PersonalAgentHostAdapter(call_tool, receipt_store=store) + with pytest.raises(HostAdapterError, match="host receipt exceeds the resource ceiling"): + await first.start("/ouroboros preserve oversized invalid start", host_session_id="large") + + second = PersonalAgentHostAdapter(call_tool, receipt_store=store) + recovered = await second.start( + "/ouroboros preserve oversized invalid start", host_session_id="large" + ) + + assert recovered is not None + assert recovered.status == "recovery_required" + assert recovered.state["start_auto_response"] == ( + "payload validation failed; inspect the live start outcome" + ) + assert calls == 1 + + @pytest.mark.asyncio async def test_start_supports_a_legacy_receipt_store_without_atomic_claim() -> None: class LegacyReceiptStore: diff --git a/tests/unit/integrations/test_vm_agent_runtime.py b/tests/unit/integrations/test_vm_agent_runtime.py index 35744cd320..75dc6337af 100644 --- a/tests/unit/integrations/test_vm_agent_runtime.py +++ b/tests/unit/integrations/test_vm_agent_runtime.py @@ -1008,6 +1008,35 @@ async def test_disconnect_then_new_runtime_resumes_without_duplicate_execution( assert transport.resume_calls == 1 +@pytest.mark.asyncio +async def test_retry_rejects_a_changed_timeout_but_resume_uses_persisted_timeout( + tmp_path: Path, +) -> None: + transport = DisconnectingTransport() + store = JsonVMReceiptStore(tmp_path / "receipts") + runtime = VMPersonalAgentRuntime( + transport, + workspace=VMWorkspaceMapper(tmp_path, "/workspace"), + receipt_store=store, + ) + + disconnected = await runtime.execute_command( + "make verify", dispatch_id="timeout-policy", session_id="s", timeout_seconds=20 + ) + assert disconnected.status == "disconnected" + + with pytest.raises(VMRuntimeError, match="different VM request"): + await runtime.execute_command( + "make verify", dispatch_id="timeout-policy", session_id="s", timeout_seconds=2 + ) + + assert transport.resume_calls == 0 + resumed = await runtime.resume_dispatch("timeout-policy", session_id="s") + assert resumed.status == "completed" + assert resumed.timeout_seconds == 20 + assert transport.resume_calls == 1 + + @pytest.mark.asyncio async def test_resume_dispatch_restores_artifact_paths_from_json_receipt( tmp_path: Path, @@ -1245,7 +1274,12 @@ async def cancel(self, _request: Any, execution_id: str) -> Any: workspace=VMWorkspaceMapper(tmp_path, "/workspace"), ) - running = await runtime.execute_command("long task", dispatch_id="zombie", session_id="s") + running = await runtime.execute_command( + "long task", + dispatch_id="zombie", + session_id="s", + timeout_seconds=0.01, + ) timed_out = await runtime.execute_command( "long task", dispatch_id="zombie", From f245f38e084c61c4b241c0f83d5a5cc22bf32b8f Mon Sep 17 00:00:00 2001 From: lee3Q Date: Thu, 3 Dec 2026 01:03:41 +0900 Subject: [PATCH 41/41] chore(fix_pr3130_start_reservation_abort): checkpoint verified stage --- .../integrations/personal_agent_host.py | 11 +++--- .../integrations/test_personal_agent_host.py | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/ouroboros/integrations/personal_agent_host.py b/src/ouroboros/integrations/personal_agent_host.py index 8910f249c5..0c1c4dc86f 100644 --- a/src/ouroboros/integrations/personal_agent_host.py +++ b/src/ouroboros/integrations/personal_agent_host.py @@ -1037,10 +1037,13 @@ async def start( try: response = await self._call(START_AUTO_TOOL, arguments) except HostAdapterError as exc: - if exc.response is not None: - abort = getattr(self.receipt_store, "abort_start", None) - if callable(abort): - abort(key) + # A failed start call cannot be finalized into a durable + # receipt. Release the reservation even when the + # transport produced no response, so a retry is not + # stranded behind an incomplete start. + abort = getattr(self.receipt_store, "abort_start", None) + if callable(abort): + abort(key) raise payload = response.payload runtime_backend = payload.get("runtime_backend") diff --git a/tests/unit/integrations/test_personal_agent_host.py b/tests/unit/integrations/test_personal_agent_host.py index 98ffce5c6a..519c1a6353 100644 --- a/tests/unit/integrations/test_personal_agent_host.py +++ b/tests/unit/integrations/test_personal_agent_host.py @@ -751,6 +751,41 @@ async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, objec assert calls == 2 +@pytest.mark.asyncio +async def test_transport_start_failure_releases_the_reservation_for_retry( + tmp_path: Path, +) -> None: + calls = 0 + + async def call_tool(name: str, _arguments: dict[str, object]) -> dict[str, object]: + nonlocal calls + assert name == "ouroboros_start_auto" + calls += 1 + if calls == 1: + raise ConnectionError("host disconnected before start_auto completed") + return { + "meta": { + "job_id": "job-transport-retry", + "auto_session_id": "auto-transport-retry", + "runtime_backend": "host", + "status": "queued", + } + } + + store = JsonHostReceiptStore(tmp_path / "host-receipts") + adapter = PersonalAgentHostAdapter(call_tool, receipt_store=store) + with pytest.raises(HostAdapterError, match="host tool call failed"): + await adapter.start("/ouroboros retry after transport failure", host_session_id="transport") + + receipt = await adapter.start( + "/ouroboros retry after transport failure", host_session_id="transport" + ) + + assert receipt is not None + assert receipt.job_id == "job-transport-retry" + assert calls == 2 + + @pytest.mark.asyncio async def test_backend_negotiation_failure_releases_the_reservation_for_retry( tmp_path: Path,