diff --git a/docs/acp-delegation.md b/docs/acp-delegation.md new file mode 100644 index 00000000..8ec2b3c0 --- /dev/null +++ b/docs/acp-delegation.md @@ -0,0 +1,353 @@ +# ACP delegation: hand one task to an external harness + +This page describes `delegate_acp`, the **opt-in** way for a running RustScript +Agent gateway run to hand one explicit task to a locally launched external +Agent Client Protocol (ACP) v1 harness. The RSS main loop keeps the main +session, the main model, its tools, run state, approvals, and the final answer. +The external harness answers only the task it was given, using its own model, +account, quota, and permission policy. + +This is the opposite direction from [ACP mode](acp-mode.md). There, an editor +drives RustScript Agent as an **ACP proxy** and the external harness calls +RustScript's six MCP tools. Here, RustScript is the ACP **client** and the +external program is the agent. The two paths are independent: enabling +delegation changes neither the proxy's tool profile nor the MCP tool list. + +> **Availability.** This opt-in feature is in the current development tree; +> it is separate from the published v0.1.0 and v0.2.0 release contracts. + +Scope: Linux only, ACP v1 over local stdio, one prompt per delegation, no +remote transport, no ACP v2, no nested delegation, and no parallel fan-out. +The single-run CLI (`rustscript-agent --script …`) does not expose the tool; +only an opted-in Gateway run using the bundled coding harness and a durable +store does. The `process: deny` policy still refuses a new delegation; `allow` +does not replace the explicit human approval. + +## What each side owns + +| Area | RustScript gateway run | External ACP harness | +| --- | --- | --- | +| Main conversation, system prompt, history | Owns | Never receives the parent history | +| Model, account, credential, quota | Owns for the main loop | Owns; RustScript does not receive or proxy them | +| Task text | Sends one task per delegation | Receives only that task | +| Tool approvals | Requires a user approval for every delegation | Uses its own permission policy | +| Workspace | Supplies the admitted, canonical run workspace as `cwd` | Uses that directory with the privileges of its launch identity | +| Result | Treats the returned text as an untrusted tool result | Returns one prompt result and text updates | + +RustScript talks to the harness only over ACP v1 stdio: it writes ACP requests +to the child's stdin and reads ACP responses and notifications from stdout. +It does not read, parse, or copy the harness's own configuration, credentials, +or session files. Those stay with the harness. + +## Enable delegation + +Delegation is off by default. Configure it in the agent home's existing +`config.yaml`; no new command-line flag, environment variable, or file is +introduced. + +```yaml +version: 1 +agent: + source: bundled:coding +acp_harnesses: + - id: opencode + command: /opt/bin/opencode + args: [acp] +``` + +- The top-level `acp_harnesses` list is optional. An absent or empty list + registers no `delegate_acp` tool; the default tool table and every existing + caller stay exactly as they are. +- `id` is a logical name chosen by the operator. It is not the program name, + not a model, and not a credential. IDs must be unique. +- `command` must be an absolute path to an executable. `args` is an optional + list of at most 32 literal strings with at most 8 KiB in total. The process + is executed directly, never through a shell, and the task text is never + inserted into `argv`. +- At most 8 entries are accepted. Repeated IDs, relative paths, and entries + over the size bounds are configuration errors. +- The table only records how to start a local stdio process. It carries no + account, model, timeout, or storage setting for the harness, and no secret. +- The table is used by the native launcher only. The public configuration + snapshot and RSS keep their original fields; command and arguments are not + projected into them. + +The tool is visible only to a normal gateway run that opted in. MCP tool +servers, child harnesses, and custom guests cannot obtain it through this +entry, so a delegated program has no recursive delegation path. + +## Tool contract + +Input, with no additional fields: +```json +{"harness_id": "opencode", "task": "Check the test coverage of this change"} +``` + +Each delegation is a separate call and needs its own approval. A later round +is not a follow-up message: it is a new input whose `task` contains only the +new work, for example: +```json +{"harness_id": "opencode", "task": "Add the missing assertions you recommended"} +``` + +`task` is non-empty UTF-8 text of at most 8 KiB. The model cannot choose an +executable, `argv`, environment, `cwd`, MCP server list, or timeout. The +working directory is the run's already admitted, canonical workspace, and its +bounds are re-checked immediately before launch. + +The result is a named structure with a closed status: +```json +{ + "harness_id": "opencode", + "status": "completed", + "text": "...", + "stop_reason": "end_turn", + "truncated": false +} +``` + +| `status` | Meaning | +| --- | --- | +| `completed` | The harness returned `end_turn` and RustScript's own process cleanup finished | +| `busy` | Another delegation already owns this session binding; nothing was started or queued | +| `denied` | The approval was refused, cancelled, expired, or no longer valid; no process was started | +| `timeout` | The single absolute deadline expired | +| `cancelled` | The harness reported a cancelled turn, or the parent run was cancelled | +| `failed` | Any other typed stop reason, a protocol failure, or an unexpected exit | +| `indeterminate` | Restart or teardown left no trustworthy settlement; never treated as retryable | + +Text is collected only from ordered `agent_message_chunk` updates of the +current turn. Thinking, tool arguments, and other update kinds are ignored. +At most 32 KiB of text is returned, further bounded by the run's tool-output +allowance; overflow is cut on a UTF-8 boundary and flagged with `truncated`. +`completed` is used only when the turn ended with `end_turn` **and** the +process RustScript owns has been cleaned up. Diagnostics are static codes; raw +frames, stderr, launch arguments, and credentials are never echoed. + +The text enters the main loop as an ordinary untrusted tool result. It has no +system-instruction authority and cannot approve anything. + +## Approvals + +Every delegation, including a resumed one, requires an explicit **user** +approval. Guardian's automatic allow rules cannot satisfy it. + +The approval preview shows the harness ID, the workspace, the task text, and +whether the call creates or continues an external session, plus a statement of +the external program's permissions. When no adequate preview can be produced, +the call is refused. + +An approval binds the run and call identity, the configuration snapshot, the +workspace, the input, and either the current pin revision or the expectation +that a session will be created. These are re-validated before launch; a change +means a new approval, which by itself does not unlock a binding that has +already become pending or unusable. A refusal, cancellation, duplicate +decision, or stale approval starts no process, and an unregistered ID or an +unauthorized workspace starts none either. + +## Session binding, resume, and restart + +The first successful delegation for a `(principal, RSS main session ID, harness +ID)` triple performs `initialize`, then `session/new`, stores the returned +external session ID, and sends the task. Later delegations for the same triple +reuse the stored binding: `initialize`, then a restore method naming the same +ID, then the new task. + +Each prompt contains only this call's task. Earlier delegated subtasks and the +parent session's history are not copied into it; the only context the harness +sees is its own stored session history. A durable call identity and its +prepared state are recorded before the process is spawned, so a delegation is +never accounted as read-only or rollbackable, and an external side effect is +not atomic with the local transaction. + +### Two rounds in one RSS session + +Suppose the user keeps one RSS conversation open, asks for a first task, +approves that call, and later asks for a follow-up and approves the second +call. They see two approval prompts in the same conversation, not one approval +covering both. Round 2 resumes the stored external session, so the harness +remembers round 1, but the prompt for round 2 contains only the new request. + +| | Round 1 | Round 2 | +| --- | --- | --- | +| RSS main session | The conversation stays open | Same session and main model; its history is not sent to the harness | +| Harness | The configured `opencode` entry | Same entry, same stored external session | +| Call | A new `delegate_acp` call | A separate new `delegate_acp` call | +| Approval | The user approves round 1 | The user approves round 2 again; the round-1 decision is not reused | +| Task sent | The first task only | The second task only; round 1 is not resent or replayed | +| ACP session step | `initialize`, `session/new`, then the prompt | `initialize`, then `session/resume` (or `session/load`) with the stored external session ID, then the prompt | +| Context available | The harness's own new session | The harness's own history from round 1, not the RSS history | + +The external session ID is internal state: it is kept in the durable binding +and is not shown to the main model or repeated in the tool result. Approving +round 2 authorizes that call only. It does not re-approve round 1, resend the +first task, or append anything from the parent conversation. If round 2 relies +on a fact from round 1, the harness recalls it from its own session history; if +that history is unavailable, the call ends with a restore error instead of +quietly starting a new session. + +- The binding is durable and keyed by that triple; the key itself never + changes. It records the canonical workspace and its authorization identity, + the identity of RustScript's own launch definition (`command`, `args`), the + external session ID, and a CAS revision. A different workspace or launch + definition is refused before any ACP request: it neither silently reuses the + old binding nor creates a second binding for the same triple. +- A binding is *pending* when a crash left its call without a trustworthy + settlement and the stored state cannot prove that the external session is + safe to continue. A pending binding refuses every later delegation on its + triple; a new approval does not clear, replace, or unlock it, and this + version has no operator command that dispositions it. +- At most 8 bindings exist per main session. Deleting the RSS session removes + the local mapping; it does not promise to delete history inside the harness. +- Capabilities are re-read on every handshake. If the agent advertises + `agentCapabilities.sessionCapabilities.resume`, RustScript uses + `session/resume`. If it advertises only `agentCapabilities.loadSession: true`, + RustScript uses `session/load`. If it advertises neither, the call fails with + `acp_session_restore_unsupported` and no `session/new` is sent. +- `session/load` replays history during the restore step. That replay is + consumed only to complete the restore and is never appended to this call's + result. The new task is the only prompt sent. +- A failed restore on an existing binding (missing session, refusal, vanished + capability) is a typed error. RustScript does not fall back to `session/new` + and does not retry with the other method. Starting an explicit new RSS main + session is how a user begins a different external session. +- Only one delegation at a time may own a binding. A second call is reported + as `busy` immediately; there is no background queue and no second child + session. + +### Restart and recovery, in order + +| Situation | What happens | +| --- | --- | +| Gateway restarts between delegations, with no unsettled call | The durable binding survives. The next approved delegation performs `initialize`, then `session/resume` (or `session/load`) with the same external ID, then the new task. | +| Normal teardown after a settled call | The child process and stdio may close after every call; the external session stays with the harness and the binding stays usable. | +| Gateway restarts or a call crashes with no settled result | The call is `indeterminate`. The binding is left pending unless the external ID was already stored and no prompt-send intent had been written (crash point 2 below). RustScript does not start a process, resend the prompt, rebuild the session, or touch the harness-side session. A pending binding refuses every later delegation on its triple; the only way to continue is a new RSS main session, whose new triple starts a new external session. This version has no operator command that dispositions or unlocks a pending binding, and approving a new call is not one: a new approval neither dispositions, replaces, nor unlocks it. | +| Crash point 1: `session/new` may have run, before the external ID is stored | The external session may exist with no local ID. The binding stays pending: RustScript does not send `session/new` again, does not adopt or guess an ID, and does not replay the prompt. A new approval does not unlock it; the user can continue only by starting a new RSS main session, which begins a new external session. | +| Crash point 2: after the external ID is stored, before the prompt-send intent is written | The original call is settled as interrupted under the ordinary call rules, and the binding stays usable. A later, separately approved call performs `initialize`, then `session/resume` (or `session/load`) with that same external ID, and sends only its own new task. | +| Crash point 3: after the prompt-send intent is written, before settlement | The prompt may have reached the harness, so the binding stays pending. RustScript does not resend or replay the prompt, does not rebuild or resume the session automatically, and a new approval does not unlock it. Only an explicit new RSS main session sets the old context aside. | +| The harness exits, loses the session, or refuses the restore | A typed restore error is returned; no new session is created implicitly. | +| The workspace or the local launch definition changed | The key stays `(principal, RSS main session, harness ID)`, so this is the same binding with a different stored workspace or launch identity. The call is refused before any process starts: zero ACP requests are sent, including no `initialize`, no external session is created, and the stored binding is neither migrated nor replaced. Approving again under the new workspace or launch definition does not replace or unlock it; the old binding stays unusable and its harness-side session is untouched. To delegate from the new workspace, the user starts a new RSS main session. | +| The same binding is called concurrently | `busy` for the later call; nothing is queued. | +| The user starts an explicit new RSS main session | A new triple gets a new external session; the previous binding and the harness's history are untouched. This explicit step is the only way to set aside a pending or otherwise unusable binding: the user accepts that the old context is not carried over, and RustScript does not describe the new session as a resume. | + +Retrying a delegated task is always a new, separately approved call. Neither a +`timeout` nor a failed restore is retried automatically, and resuming a +session is never the same operation as replaying a prompt. Of the three crash +points above, two leave the binding pending: `session/new` may have run with no +stored ID, or the prompt may have been sent with no settlement. Only when the +ID is stored and no prompt-send intent was written is the interrupted call +settled, after which a separately approved call may resume the same external +ID. A pending binding is not cleared, unlocked, or replaced by a new approval, +and this version exposes no separate operator command that dispositions or +unlocks it. If the user chooses to abandon the old external context, they start +a new RSS main session deliberately; RustScript never presents that as +automatic recovery and never carries the old harness history into the new +session. + +## Limits and cleanup + +- One prompt per delegation. One delegation per run at a time, and at most 4 + live delegated processes across the service; excess calls are refused rather + than queued. +- One absolute deadline per call of `min(120 s, remaining run deadline)`. + Cancellation does not wait for the model or for new messages. +- A separate absolute budget of at most 5 s is used for cleanup. An in-flight + prompt is cancelled with `session/cancel`; a normally finished turn closes + stdio directly without asking the harness to close or delete the session. + The dedicated process group is terminated if needed and the direct child is + reaped. +- Frames are bounded at 1 MiB each. The pending queue holds at most 64 + messages and 4 MiB, and overflow terminates the call instead of waiting for + the consumer. Capacity is released only after verifiable teardown; if + teardown cannot be confirmed, the call is indeterminate and the capacity + stays held. +- Each delegation counts as one tool call for the run's existing budget. + +## Permissions: what RustScript does and does not constrain + +On the ACP connection RustScript declares no filesystem and no terminal +capability, sends `mcpServers: []` in session setup, refuses every +`session/request_permission`, answers with the protocol's cancel outcome, and +refuses other unsupported server requests. Main-session approvals are never +forwarded to the harness and raw frames are never relayed. + +Those are bounds on the ACP connection, not an operating-system sandbox. The +external program still has every local and network permission of the identity +that launched it, including its own built-in tools, its own MCP servers, and +any child processes it starts. RustScript does not promise OS isolation, +automatic rollback of external writes, or coverage of descendants that leave +the process group. Configure only harnesses you trust, and prefer an +operator-launched wrapper with limited privileges. Empty `mcpServers` does not +disable the harness's built-in tools. + +## Where the third party's state lives + +The harness owns its own configuration, authentication, model choice, and +session storage. RustScript does not inspect or copy those files, does not pass +gateway credentials into the child, and does not perform ACP login on its +behalf. Use the harness's own login flow, keeping secrets out of `args` and out +of the editor or gateway configuration. + +If the operator changes which account or storage a launch command resolves to, +that is a different external program identity: register it under a new harness +ID instead of reusing the old binding. A new ID is a different binding key, not +a way around an old one: the old binding is not replaced, migrated, or +unlocked, and the harness-side session behind it is left untouched. RustScript +cannot detect the change itself, because it never reads third-party files. + +## Relationship to ACP proxy mode and the MCP six tools + +| | ACP proxy (`acp proxy`) | Delegation (`delegate_acp`) | +| --- | --- | --- | +| Who starts the conversation | Editor or ACP client | RSS gateway run | +| Who is the ACP client | The editor | RustScript | +| Who owns the model loop | External harness | RSS for the main loop, harness for the delegated task | +| RustScript tools exposed | Six MCP tools (`read_file`, `search_files`, `write_file`, `patch`, `terminal`, `process`), optionally read-only | None; `mcpServers: []` | +| Session storage | Harness only | Durable pin in the gateway; history stays in the harness | +| Approvals | Harness's own policy | RustScript user approval for every call | +| Effect of enabling | Unchanged | Opt-in only; default table unchanged | + +The proxy's launch syntax, tool profile, and troubleshooting behavior are +unchanged by this feature. See [ACP mode](acp-mode.md) for the editor-facing +path. + +## Protocol pre-verification for this candidate + +Before any RustScript integration, the ACP v1 restore contract was checked +against a pinned external harness, **OpenCode 1.19.6**, with a scripted +loopback model and a standalone ACP client: + +- Round 1 in one controlled process: `initialize`, then `session/new`, then one + prompt. The turn ended with `end_turn` and the scripted answer. +- Round 2 in a second process with a shared isolated home: + `initialize`, then `session/resume` naming the **same external session ID**, + then one different prompt. That turn also ended with `end_turn`. +- The model request for round 2 contained the earlier turn (the first task and + its answer) while the round-2 prompt itself did not contain the phrase; the + round-2 answer reproduced that phrase, so the answer depended on the carried + context rather than on the second prompt. +- Both harness processes exited on client EOF with status 0. The harness ran + with a disposable config and storage under a temporary home, with the + provider pointed at a stdio-local scripted server, inside an isolated + network namespace whose loopback was up and which had no default route. + No real account, credential, project content, or network inference was used, + and the external session ID is kept private in this record. + +This is transport and restore evidence for the pinned harness. It is **not** +acceptance of the RustScript gateway path: approvals, durable pins, call +settlement, quotas, crash points, and the end-to-end RSS tool result still need +the integration tests described in the implementation plan. + +## Troubleshooting + +| Symptom | What to check | +| --- | --- | +| `delegate_acp` is absent | `acp_harnesses` is missing or empty, or the run did not opt in. The tool never appears in the default registry. | +| Start-up fails after adding the table | Check for duplicate IDs, a non-absolute `command`, more than 8 entries, more than 32 arguments, or more than 8 KiB of arguments. | +| `denied` and no process started | The approval was refused, cancelled, expired, or its snapshot changed. Ask again with a current preview. | +| `busy` | Another delegation owns the same binding. Wait for it to settle; there is no queue. | +| `acp_session_restore_unsupported` | The harness advertises neither the `resume` session capability nor `loadSession`. Delegation cannot restore a session on it; start a new RSS main session if a fresh session is acceptable. | +| A restore fails after a restart | The external session may be gone or the capability may have changed. RustScript will not create a new session silently; start a new main session deliberately. | +| `indeterminate` after a crash | Only the previous call's result is unsettled; that result does not by itself decide the binding's state. If the external ID was already stored and no prompt-send intent had been written, the binding stays usable: a later, separately approved call resumes that same external session and sends only its own new task. Otherwise the binding is pending and refuses every later delegation on its triple. Do not assume the prompt ran or did not run; RustScript does not resend or replay it. This version has no operator command that dispositions or unlocks a pending binding, and a new approval does not unlock, replace, or resume it. To abandon the old context, start a new RSS main session explicitly; RustScript never presents that as automatic recovery. | +| `timeout` or `cancelled` | The absolute deadline or the parent run's cancellation ended the turn. RustScript performs bounded cleanup and does not resend the prompt. | +| The harness cannot find its own configuration or login | Configure it through its own files and login flow under the launch identity. RustScript does not pass gateway credentials or third-party configuration. | diff --git a/docs/acp-mode.md b/docs/acp-mode.md index 687d724e..423cf307 100644 --- a/docs/acp-mode.md +++ b/docs/acp-mode.md @@ -121,6 +121,19 @@ harness grandchildren or other processes started outside RustScript's control. Keep protocol frames on stdout and diagnostics on stderr for both the ACP and MCP stdio connections. +## Delegation from a gateway run + +This page describes the editor-facing direction: an ACP client starts the +proxy, and the harness calls RustScript's tools. The reverse direction is a +separate, opt-in feature: a normal bundled coding Gateway run can +hand one task to a configured local harness with `delegate_acp`, keep its own +main session and model, and resume the same external ACP session on later +calls. That path sends `mcpServers: []`, exposes no RustScript tools to the +harness, and owns its own approval and durable session pin. It does not change +this proxy, its tool profile, or the MCP six-tool list. See +[ACP delegation](acp-delegation.md) for its configuration, recovery, and +permission rules. + ## Troubleshooting | Symptom | What to check | diff --git a/docs/configuration.md b/docs/configuration.md index da36abb2..625fa9de 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -271,6 +271,43 @@ provider settings. Configure authentication, model selection, and permissions in the external harness. See [ACP mode](acp-mode.md) for editor launch examples, compatibility, and troubleshooting. +## ACP delegation harnesses (`config.yaml`) + +The current development tree accepts this optional table in the existing +agent-home `config.yaml`. A non-empty table enables the `delegate_acp` tool +for the bundled coding Gateway with a durable store. It introduces no new +file, flag, or environment variable and does not change the default catalog, +the ACP proxy, or the MCP six-tool list. + +```yaml +version: 1 +agent: + source: bundled:coding +acp_harnesses: + - id: opencode + command: /opt/bin/opencode + args: [acp] +``` + +| Field | Type | Required | Notes | +| --- | --- | --- | --- | +| `acp_harnesses` | list, absent or empty by default | no | Local stdio harnesses eligible for `delegate_acp`. Empty or absent registers no delegation tool. | +| `id` | string | yes | Unique logical ID shown in the tool input and approval preview; not a model or credential. | +| `command` | absolute path | yes | Executable started directly, without a shell. | +| `args` | list of strings | no | At most 32 literal arguments, 8 KiB in total. The task text is never inserted here. | + +At most 8 entries are accepted. Duplicate IDs, a relative `command`, more than +32 arguments, or more than 8 KiB of arguments are configuration errors. The +table carries no account, model, timeout, or storage setting for the harness +and no secret; the program's own configuration and credentials stay its own. +Only the native launcher reads the table. The public configuration snapshot +and RSS keep their original fields and do not receive `command` or `args`. + +Delegation itself is opt-in per run and off by default. See +[ACP delegation](acp-delegation.md) for the tool input and result, approval +requirements, durable session pin and resume rules, restart behavior, and the +operating-system permissions that remain with a trusted local harness. + ## CLI arguments (runner binary) In single-run mode, `rustscript-agent` compiles one script and drives its diff --git a/docs/deployment.md b/docs/deployment.md index d005d977..186dff61 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -71,7 +71,7 @@ manifest binaries. After the `v0.2.0` tag workflow succeeds, the downloadable - executable binaries at `bin/rustscript-agent` and `bin/rustscript-agent-gateway`; -- all 82 required production RSS files, with relative imports preserved, at +- all 83 required production RSS files, with relative imports preserved, at `share/rustscript-agent/rss/`; - YAML schemas at `share/rustscript-agent/schemas/` and production examples at `share/rustscript-agent/examples/`; diff --git a/docs/status.md b/docs/status.md index 08ed0e7b..d256e81a 100644 --- a/docs/status.md +++ b/docs/status.md @@ -48,6 +48,7 @@ project is pre-v1, and absent routes or adapters are listed explicitly. | Parallel tool calls | Not implemented; rejected as `unsupported_parallel`. | | Parallel subagents/fan-out | Not implemented and excluded from the current milestone. The interrupt compatibility route only cancels a run handle by ID. | | General-purpose harness beyond the implemented tool approval/pinned-tool paths | Excluded from the current product claim. | +| ACP delegation from a gateway run (`delegate_acp`) | Development feature, off by default. The bundled coding Gateway can opt in via `acp_harnesses` with a durable store. Each new call requires explicit human approval; the same external session can be restored after a Gateway restart. The ACP proxy and MCP tool list are unchanged. See [ACP delegation](acp-delegation.md). | ## Plugin graphs and state diff --git a/release/rss-production.txt b/release/rss-production.txt index f5aa0985..66b01e42 100644 --- a/release/rss-production.txt +++ b/release/rss-production.txt @@ -63,6 +63,7 @@ rss/storage/plugins.rss rss/storage/runs.rss rss/storage/schema.rss rss/storage/sessions.rss +rss/tools/delegate_acp.rss rss/tools/dispatch.rss rss/tools/dispatch_entry.rss rss/tools/patch.rss diff --git a/rss/agent/main.rss b/rss/agent/main.rss index cbc54243..54cb05a6 100644 --- a/rss/agent/main.rss +++ b/rss/agent/main.rss @@ -12,6 +12,7 @@ use agent; use agent_runtime; use json; use super::tools::dispatch as tools; +use super::tools::delegate_acp as delegate_acp; use super::agent::guardian as guardian; use super::agent::provider_body; use super::llm::tool_descriptor; @@ -817,7 +818,12 @@ fn dispatch_reviewed(context: map, call: map) -> map { }; let facts: map = tools::approval_context(dispatch_input); let mut result: map = {}; - if ctx_bool(facts, "ok", false) == false { + if ctx_string(call, "name", "") == "delegate_acp" && delegate_acp::admitted(native_tools_from_context(context)) { + result = delegate_acp::invoke( + call, call_arguments_json(call), ctx_string(call, "id", ""), + ctx_string(context, "run_id", ""), identity + ); + } else if ctx_bool(facts, "ok", false) == false { result = tools::dispatch(dispatch_input); } else { let tool_metadata: map = ctx_map(facts, "metadata"); diff --git a/rss/storage/debug.rss b/rss/storage/debug.rss index 56fffa0e..78d7579c 100644 --- a/rss/storage/debug.rss +++ b/rss/storage/debug.rss @@ -232,6 +232,8 @@ fn storage_dispatch(db_id: resource, command: StorageCommand) result = storage_raw_ok(request_id, op, sessions::storage_session_list(db_id, input.profile, input.platform, command.max_rows, command.max_bytes)); } else if command.op == "session.touch" { result = storage_raw_ok(request_id, op, sessions::storage_session_touch(db_id, command.payload_json, command.max_rows, command.max_bytes)); + } else if command.op == "session.acp_delegation_cas" { + result = storage_unwrap(request_id, op, sessions::storage_session_acp_delegation_cas(db_id, command.payload_json, command.max_rows, command.max_bytes)); } else if command.op == "message.append" { result = storage_unwrap(request_id, op, messages::storage_message_append(db_id, command.payload_json, command.max_rows, command.max_bytes)); } else if command.op == "message.get" { diff --git a/rss/storage/main.rss b/rss/storage/main.rss index 425b6160..94da089d 100644 --- a/rss/storage/main.rss +++ b/rss/storage/main.rss @@ -494,6 +494,8 @@ fn storage_dispatch(db_id: resource, command: StorageCommand) result = storage_raw_ok(request_id, op, sessions::storage_session_list(db_id, input.profile, input.platform, command.max_rows, command.max_bytes)); } else if command.op == "session.touch" { result = storage_raw_ok(request_id, op, sessions::storage_session_touch(db_id, command.payload_json, command.max_rows, command.max_bytes)); + } else if command.op == "session.acp_delegation_cas" { + result = storage_unwrap(request_id, op, sessions::storage_session_acp_delegation_cas(db_id, command.payload_json, command.max_rows, command.max_bytes)); } else if command.op == "session.workspace_bind" { result = storage_unwrap(request_id, op, sessions::storage_session_workspace_bind(db_id, command.payload_json, command.max_rows, command.max_bytes)); } else if command.op == "message.append" { diff --git a/rss/storage/sessions.rss b/rss/storage/sessions.rss index 232da49c..3c8d9ba5 100644 --- a/rss/storage/sessions.rss +++ b/rss/storage/sessions.rss @@ -88,6 +88,17 @@ struct SessionWorkspaceBindInput { now_ms: int } +struct SessionAcpDelegationCasInput { + session_id: string, + owner: string, + created_at_ms: int, + expected_version: int, + lease_path: string, + lease_call: string, + document_json: string, + now_ms: int +} + fn session_tx_rows_affected(entry: SqliteTransactionResult) -> int { let mut affected: int = 0; if entry.kind == "execute" { @@ -146,6 +157,44 @@ pub fn storage_session_touch(db_id: resource, payload_json: s storage_session_get(db_id, input.session_id, max_rows, max_bytes) } +/// Compare-and-swap of the private `$.acp_delegation` document. +/// +/// The whole read-check-write is one UPDATE whose predicates are enforced by +/// SQLite: the session identity (id, owner and durable `created_at_ms`), the +/// expected document version and, when `lease_path` is non-empty, the exact +/// call that currently owns that pin's lease. A zero-row update is an explicit +/// "not committed" response (`applied = 0`), never a silent success. The +/// matching row is returned in the same transaction so a caller can retry +/// from the authoritative document without a separate read. +pub fn storage_session_acp_delegation_cas(db_id: resource, payload_json: string, max_rows: int, max_bytes: int) -> map { + let input: SessionAcpDelegationCasInput = json::decode::(payload_json); + let params: array = [sql_text(input.document_json.copy()), sql_int(input.now_ms.copy()), sql_text(input.session_id.copy()), sql_text(input.owner.copy()), sql_int(input.created_at_ms.copy()), sql_int(input.expected_version.copy()), sql_text(input.lease_path.copy()), sql_text(input.lease_path.copy()), sql_text(input.lease_call.copy())]; + let update: SqliteStatement = { + sql: "UPDATE sessions SET metadata_json = json_set(CASE WHEN json_valid(metadata_json) AND json_type(metadata_json) = 'object' THEN metadata_json ELSE '{}' END, '$.acp_delegation', json(?)), updated_at_ms = ? WHERE id = ? AND user_id = ? AND created_at_ms = ? AND COALESCE(json_extract(metadata_json, '$.acp_delegation.version'), -1) = ? AND (? = '' OR COALESCE(json_extract(metadata_json, ?), '') = ?)", + params: Some(params), + query: Some(false), + limits: Some(sql_limits(1000, 4194304)) + }; + let get: SqliteStatement = storage_session_get_statement(input.session_id.copy(), max_rows, max_bytes); + let statements: array = [update, get]; + let results: array = sqlite::transaction(&db_id, statements); + let mut applied: int = 0; + if results.length > 0 { + applied = session_tx_rows_affected(results[0].copy()); + } + let mut queried: SqliteQueryResult = {columns: [], rows: [], truncated: false, next_cursor: no_int()}; + if results.length > 1 { + let second: SqliteTransactionResult = results[1].copy(); + queried = match second.query { Some(value) => value, None => {columns: [], rows: [], truncated: false, next_cursor: no_int()} }; + } + { + ok: true, + code: "ok", + message: "", + result: { applied: applied == 1, columns: queried.columns, rows: queried.rows, truncated: queried.truncated } + } +} + /// Atomically binds a validated workspace to an idle session. The workspace /// selector policy and native authority are resolved by the agent RSS entry; /// this command only merges its display metadata and guards active runs. diff --git a/rss/tools/delegate_acp.rss b/rss/tools/delegate_acp.rss new file mode 100644 index 00000000..b13b2065 --- /dev/null +++ b/rss/tools/delegate_acp.rss @@ -0,0 +1,37 @@ +// The native bridge is present only for the ordinary bundled Gateway run. +// A descriptor alone never authorizes external execution. +use agent_runtime; +use self::dispatch as tools; +use self::types as types; + +pub fn admitted(registry: array) -> bool { + let mut i: int = 0; + let mut found: bool = false; + while i < registry.length && found == false { + let candidate: map = registry[i]; + found = types::map_string(candidate, "name", "") == "delegate_acp"; + i += 1; + } + found +} + +pub fn invoke(call: map, canonical: string, call_id: string, run_id: string, registry_identity: string) -> map { + let invoked: PinnedToolInvokeResult = agent_runtime::invoke_pinned_tool({ + tool_name: "delegate_acp", + call_id: call_id, + canonical_arguments: canonical.copy(), + canonical_input: "", + run_id: run_id, + registry_identity: registry_identity, + argument_digest: canonical, + risk_class: "execute", + summary: "delegate_acp", + untrusted_graph_id: "" + }); + let canonical_result: string = invoked.canonical_result.copy(); + if canonical_result.length == 0 => { + tools::approval_failure({ call: call }, invoked.code.copy(), invoked.message.copy()) + } else => { + tools::result_envelope(call, invoked) + } +} diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs new file mode 100644 index 00000000..18869a04 --- /dev/null +++ b/src/acp/delegated_client.rs @@ -0,0 +1,4187 @@ +//! Bounded ACP v1 stdio client for RSS delegation. +//! +//! This module owns one external harness process and exposes the delegation +//! phases separately: spawn, `initialize`, session setup (`session/new` or a +//! single advertised restore method), exactly one `session/prompt`, and close. +//! It deliberately has no combined "run task" API: the later durable scope must +//! receive and persist the session ID before it publishes a prompt. +//! +//! Process and wire ownership: +//! - the child is started from a trusted absolute program, an explicit argv and +//! an admitted absolute working directory; no shell is involved; +//! - only `HOME`, `PATH`, `LANG`, `LC_ALL` and `TZ` are inherited from the +//! gateway environment, never arbitrary credential variables; +//! - the child runs in its own process group. The supervisor signals that +//! group only while the direct leader is still its unreaped child, verified +//! with `waitid(WNOWAIT)`. It then reaps that exact child and confirms +//! absence only when a non-delivering `kill(-pgid, 0)` reports `ESRCH` for +//! the original group. A cached numeric group is never signalled after +//! reaping, and a group that still exists keeps the supervisor's capacity. +//! This proof assumes the ordinary POSIX contract that an owned group stays +//! allocated while its unreaped leader is waitable and that orphaned +//! descendants are normally reaped; a host whose syscall filtering breaks +//! `waitid` or signal 0 is rejected at connect as unsupported; +//! - each inbound line is limited to 1 MiB. Every line is classified at the +//! serial ingress boundary before it can enter the SDK's unbounded transport +//! channel: only the response matching the currently outstanding request is +//! forwarded, so at most one unconsumed frame can ever be queued. Notifications +//! are validated and consumed inline, and peer requests are answered inline, +//! so a long ready stream is not charged cumulatively. Forwarded frames are +//! limited to 64 messages and 4 MiB actually unconsumed; +//! - only typed `agent_message_chunk` text is captured, capped at 32 KiB on a +//! UTF-8 boundary with an explicit truncation bit. +//! - a setup request is interruptible by shutdown, so `close` does not wait for +//! the run deadline while `initialize`, `session/new` or a restore reply is +//! pending. The bounded stdio writer owns prompt publication: it discards a +//! frame when shutdown, the deadline or caller withdrawal won before the +//! first byte, writes at most one `session/cancel` after a complete frame +//! that remains unanswered, and suppresses the SDK's deferred automatic +//! `$/cancel_request` for that reserved prompt id. Protocol draining gets a +//! small slice of the single absolute cleanup budget so process reaping keeps +//! the remainder; +//! - the supervisor publishes typed final cleanup evidence through +//! [`AcpCleanupObserver`] and only then releases its process slot. A caller +//! can hold that observer across `close` or a drop, so a timed-out `close` +//! never transfers unverified capacity to the next delegation. +//! +//! The SDK still owns JSON-RPC framing, IDs, request correlation and dispatch. +//! The client observes each inbound line before the SDK does, so it can bind the +//! text phase to the exact JSON-RPC ID reserved for its single prompt request. +//! A response with any other ID (including the same number encoded as a string) +//! is discarded and never reaches the SDK. That ordering is the phase boundary +//! used to discard `session/load` replay: replay notifications arrive before the +//! load response, while the collector only admits text after this client has +//! begun its single prompt. +//! +//! Demonstrated SDK limit: the v1 `ActiveSession` helpers combine setup and a +//! prompt-oriented read loop. This module uses raw typed requests instead so a +//! caller can persist the new ID between `session/new` and `session/prompt`. +//! `session/load` replay is only dropped safely when the harness follows the +//! ACP contract and completes replay before answering the load request. + +use std::ffi::OsString; +use std::io; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::process::ExitStatus; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; + +use agent_client_protocol::v1::schema::{ + CancelNotification, ContentBlock, Implementation, InitializeRequest, LoadSessionRequest, + NewSessionRequest, PromptRequest, PromptResponse, RequestPermissionOutcome, + RequestPermissionResponse, ResumeSessionRequest, SessionId, SessionNotification, SessionUpdate, +}; +use agent_client_protocol::{ + Agent, Client, Error as SdkError, Lines, RawJsonRpcId, RawJsonRpcMessage, RawJsonRpcParams, + schema::ProtocolVersion, +}; +use futures_util::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader}; +use futures_util::{Sink, Stream, sink, stream}; +use serde_json::Value; +use tokio::io::{AsyncWriteExt, ReadBuf}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::time::{Instant, sleep, sleep_until, timeout, timeout_at}; + +/// Largest accepted ACP frame, measured before LF. The SDK sees only complete +/// lines at or below this size. +pub const MAX_FRAME_BYTES: usize = 1024 * 1024; +/// Maximum frames forwarded to the SDK but not yet consumed. +pub const MAX_TURN_NOTIFICATIONS: usize = 64; +/// Maximum bytes of forwarded-but-unconsumed frames. +pub const MAX_TURN_NOTIFICATION_BYTES: usize = 4 * 1024 * 1024; +/// Maximum text returned from one prompt. +pub const MAX_RESULT_TEXT_BYTES: usize = 32 * 1024; +/// Maximum delegated task accepted by [`DelegatedAcpClient::prompt`]. +pub const MAX_TASK_BYTES: usize = 8 * 1024; +/// Separate absolute process-cleanup budget. +pub const CLEANUP_BUDGET: Duration = Duration::from_secs(5); +/// Small slice of [`CLEANUP_BUDGET`] spent draining accepted protocol output +/// after a shutdown request. The rest of the same absolute budget belongs to +/// process-group termination and reaping; the two never add up. +const PROTOCOL_DRAIN_BUDGET: Duration = Duration::from_millis(500); +/// Scheduling allowance on top of [`CLEANUP_BUDGET`] for [`DelegatedAcpClient::close`] +/// to observe the supervisor's completion. Draining the connection and reaping +/// the child group share the same absolute cleanup budget; this is not a second +/// drain budget. +const CLOSE_SCHEDULING_SLACK: Duration = Duration::from_millis(250); +const MAX_HARNESS_ARGUMENTS: usize = 32; +const MAX_HARNESS_ARGUMENT_BYTES: usize = 8 * 1024; + +/// Stable diagnostic codes. No code contains peer text, stderr or argv. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AcpDelegationError { + InvalidLaunch, + SpawnFailed, + /// The host cannot prove the kernel-backed process-group cleanup contract + /// (for example a syscall filter breaks `waitid` or signal 0). Delegation + /// is refused before a child is started. + CleanupUnsupported, + DeadlineExceeded, + NotInitialized, + InvalidPhase, + ProtocolVersion, + InitializeFailed, + SessionCreateFailed, + RestoreUnsupported, + RestoreFailed, + SessionMismatch, + PromptFailed, + TaskInvalid, + FrameTooLarge, + NotificationFlood, + HarnessExited, + Cancelled, + Closed, +} + +impl AcpDelegationError { + /// Fixed diagnostic code suitable for logs and result envelopes. + pub const fn code(self) -> &'static str { + match self { + Self::InvalidLaunch => "acp_delegation_invalid_launch", + Self::SpawnFailed => "acp_delegation_spawn_failed", + Self::CleanupUnsupported => "acp_delegation_cleanup_unsupported", + Self::DeadlineExceeded => "acp_delegation_deadline", + Self::NotInitialized => "acp_delegation_not_initialized", + Self::InvalidPhase => "acp_delegation_invalid_phase", + Self::ProtocolVersion => "acp_delegation_protocol_version", + Self::InitializeFailed => "acp_delegation_initialize_failed", + Self::SessionCreateFailed => "acp_session_create_failed", + Self::RestoreUnsupported => "acp_session_restore_unsupported", + Self::RestoreFailed => "acp_session_restore_failed", + Self::SessionMismatch => "acp_session_mismatch", + Self::PromptFailed => "acp_delegation_prompt_failed", + Self::TaskInvalid => "acp_delegation_task_invalid", + Self::FrameTooLarge => "acp_delegation_frame_too_large", + Self::NotificationFlood => "acp_delegation_notification_flood", + Self::HarnessExited => "acp_harness_exited", + Self::Cancelled => "acp_delegation_cancelled", + Self::Closed => "acp_delegation_closed", + } + } +} + +impl std::fmt::Display for AcpDelegationError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.code()) + } +} + +impl std::error::Error for AcpDelegationError {} + +/// Trusted local launch definition. The future configuration scope may build +/// this from its own validated table, but this type accepts no model input. +#[derive(Debug, Clone)] +pub struct AcpDelegationLaunch { + command: PathBuf, + arguments: Vec, + cwd: PathBuf, +} + +impl AcpDelegationLaunch { + /// Validate an absolute program, bounded argv and an admitted absolute cwd. + pub fn new( + command: impl Into, + arguments: Vec, + cwd: impl Into, + ) -> Result { + let command = command.into(); + let cwd = cwd.into(); + if !command.is_absolute() || !cwd.is_absolute() { + return Err(AcpDelegationError::InvalidLaunch); + } + if arguments.len() > MAX_HARNESS_ARGUMENTS { + return Err(AcpDelegationError::InvalidLaunch); + } + let bytes: usize = arguments + .iter() + .map(|argument| argument.as_encoded_bytes().len()) + .sum(); + if bytes > MAX_HARNESS_ARGUMENT_BYTES { + return Err(AcpDelegationError::InvalidLaunch); + } + Ok(Self { + command, + arguments, + cwd, + }) + } + + pub fn command(&self) -> &Path { + &self.command + } + + pub fn arguments(&self) -> &[OsString] { + &self.arguments + } + + pub fn cwd(&self) -> &Path { + &self.cwd + } +} + +/// Advertised restore capabilities from the initialize response. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AcpAgentCapabilities { + pub resume: bool, + pub load: bool, +} + +impl AcpAgentCapabilities { + /// Resume is preferred whenever it is advertised. `session/load` is used + /// only when it is the sole advertised restore method. + pub fn restore_method(self) -> Option { + if self.resume { + Some(AcpRestoreMethod::Resume) + } else if self.load { + Some(AcpRestoreMethod::Load) + } else { + None + } + } +} + +/// Which restore request this connection actually used. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AcpRestoreMethod { + Resume, + Load, +} + +/// Closed stop-reason surface for the later host result envelope. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AcpStopReason { + EndTurn, + MaxTokens, + MaxTurnRequests, + Refusal, + Cancelled, + Other, +} + +/// Text and stop reason from exactly one prompt turn. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AcpPromptResult { + pub text: String, + pub truncated: bool, + pub stop_reason: AcpStopReason, +} + +impl AcpPromptResult { + /// `completed` requires a successful stop reason and confirmed process + /// cleanup. Any other stop reason, truncation alone, or unconfirmed cleanup + /// is not a completed delegation. + pub fn completed(&self, cleanup: &AcpCleanupReport) -> bool { + self.stop_reason == AcpStopReason::EndTurn && cleanup.cleanup_confirmed + } +} + +/// Evidence from terminating the owned direct child and its process group. +#[derive(Debug, Clone)] +pub struct AcpCleanupReport { + pub direct_child_reaped: bool, + pub exit_status: Option, + pub group_signal_sent: bool, + /// A group `SIGKILL` was sent after the TERM grace while the leader still + /// pinned the group identity. + pub forced: bool, + /// The owned process group was affirmatively proven absent after the direct + /// leader was reaped: the kernel reported `ESRCH` for the original group on + /// a non-delivering signal-0 query. + pub group_clear: bool, + pub cleanup_confirmed: bool, +} + +/// Independent subscription to the owned supervisor's final cleanup evidence. +/// +/// Clone one from [`DelegatedAcpClient::cleanup_observer`] before calling +/// `close` or dropping the client. The supervisor publishes this report only +/// after cleanup is proven, then releases its process slot and exits. The +/// observer resolves independently of the handle and is still delivered when +/// `close` returned unconfirmed or the client was dropped, so a service layer +/// can hand the caller an unconfirmed result and release its own capacity later +/// from this proof. +#[derive(Debug, Clone)] +pub struct AcpCleanupObserver { + report: watch::Receiver>, + active: Arc, +} + +impl AcpCleanupObserver { + /// Latest published report, if the supervisor has finished cleanup. + /// + /// A `Some` value proves cleanup. It does not by itself prove the slot + /// counter reached `0`; see [`Self::active`] and [`Self::wait_for_cleanup`]. + pub fn latest(&self) -> Option { + self.report.borrow().clone() + } + + /// Process slots still charged to this supervisor: `1` until it has both + /// published the confirmed report and released the slot, then `0`. + pub fn active(&self) -> usize { + self.active.load(Ordering::Acquire) + } + + /// Wait until the supervisor has published final cleanup evidence, released + /// its slot and exited. + /// + /// Returns `None` only if the supervisor ended without a report (a panic). + /// Task exit is ordered after both publication and release, so a `Some` + /// value here proves the slot is already released even though a report seen + /// only through [`Self::latest`] may briefly precede that release. + pub async fn wait_for_cleanup(mut self) -> Option { + // Wait for the channel to close instead of returning on the first + // change: task exit is the fence that proves the slot was released. + while self.report.changed().await.is_ok() {} + self.report.borrow().clone() + } +} + +/// Handle to one supervised harness connection. +/// +/// The hidden supervisor task owns the child. Dropping this handle requests +/// shutdown but never aborts that supervisor; [`Self::close`] waits for its +/// completion evidence. +pub struct DelegatedAcpClient { + commands: Option>, + shutdown: watch::Sender, + supervisor: Option>, + proof: watch::Receiver>, + pid: u32, + deadline: Instant, + active: Arc, + shared: Arc, + initialized: bool, + session_id: Option, + prompted: bool, + closed: bool, +} + +/// Final launch veto observed immediately before the one process creation. +/// +/// This is internal to the delegation policy and is deliberately not part of +/// the public connection API: `connect`/`spawn` keep their existing contract. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct AcpLaunchVeto(&'static str); + +impl AcpLaunchVeto { + pub(crate) const fn new(code: &'static str) -> Self { + Self(code) + } + + /// Stable diagnostic code of the veto. + pub(crate) const fn code(self) -> &'static str { + self.0 + } +} + +/// Why a guarded launch did not produce a client. +enum SpawnFailure { + Error(AcpDelegationError), + Veto(AcpLaunchVeto), +} + +impl DelegatedAcpClient { + /// Spawn a harness and start its supervised ACP connection. + /// + /// The launch itself is not an ACP operation and sends no request. The + /// caller must invoke [`Self::initialize`] and then exactly one session + /// setup method. + pub async fn connect( + launch: AcpDelegationLaunch, + deadline: Instant, + ) -> Result { + Self::connect_with_stdin(launch, deadline, |stdin| Box::new(stdin)).await + } + + /// Create the process and its supervisor without awaiting anything. + /// + /// This is the delegation spawn commit seam: a caller that holds its + /// arbitration locks can call it synchronously, then release them and run + /// the asynchronous `initialize`/session/prompt handshake. `connect` keeps + /// the ordinary async contract for every other caller. + pub fn spawn( + launch: AcpDelegationLaunch, + deadline: Instant, + ) -> Result { + match Self::spawn_with_stdin(launch, deadline, |stdin| Box::new(stdin), None) { + Ok(client) => Ok(client), + Err(SpawnFailure::Error(error)) => Err(error), + // Without a precondition there is no veto path. + Err(SpawnFailure::Veto(_)) => Err(AcpDelegationError::SpawnFailed), + } + } + + /// Create the process only when the caller's final precondition still + /// holds at the true `Command::spawn` boundary. + /// + /// The predicate runs inside the launch after every preparation step and + /// immediately before `spawn(2)`, so time spent in arbitration, storage + /// waits, hooks and revalidation is covered. A refusal never creates a + /// process. + pub(crate) fn spawn_preconditioned( + launch: AcpDelegationLaunch, + deadline: Instant, + precondition: impl FnOnce() -> Result<(), AcpLaunchVeto> + Send + 'static, + ) -> Result { + match Self::spawn_with_stdin( + launch, + deadline, + |stdin| Box::new(stdin), + Some(Box::new(precondition)), + ) { + Ok(client) => Ok(client), + Err(SpawnFailure::Veto(veto)) => Err(veto), + Err(SpawnFailure::Error(error)) => Err(AcpLaunchVeto::new(error.code())), + } + } + + /// Connect with a caller-supplied write end in place of the child's stdin. + /// + /// Production always calls this with the plain `ChildStdin`. A unit test + /// uses the same connection, actor and writer with a controllable sink so + /// the SDK's real poll order can be exercised without changing production + /// ordering. + async fn connect_with_stdin( + launch: AcpDelegationLaunch, + deadline: Instant, + wrap_stdin: impl FnOnce(ChildStdin) -> StdinWriter, + ) -> Result { + match Self::spawn_with_stdin(launch, deadline, wrap_stdin, None) { + Ok(client) => Ok(client), + Err(SpawnFailure::Error(error)) => Err(error), + Err(SpawnFailure::Veto(_)) => Err(AcpDelegationError::SpawnFailed), + } + } + + fn spawn_with_stdin( + launch: AcpDelegationLaunch, + deadline: Instant, + wrap_stdin: impl FnOnce(ChildStdin) -> StdinWriter, + precondition: Option Result<(), AcpLaunchVeto> + Send>>, + ) -> Result { + if Instant::now() >= deadline { + return Err(SpawnFailure::Error(AcpDelegationError::DeadlineExceeded)); + } + // Refuse a host whose syscall filtering makes the kernel-backed group + // proof untrustworthy. `waitid` on a non-child must report ECHILD and a + // zero signal to ourselves must be permitted; anything else is treated + // as unsupported rather than guessing about cleanup. + if !kernel_cleanup_supported() { + return Err(SpawnFailure::Error(AcpDelegationError::CleanupUnsupported)); + } + let mut child = match OwnedChild::spawn(&launch, precondition) { + Ok(child) => child, + Err(ChildSpawnError::Io) => { + return Err(SpawnFailure::Error(AcpDelegationError::SpawnFailed)); + } + Err(ChildSpawnError::Veto(veto)) => return Err(SpawnFailure::Veto(veto)), + }; + let pid = child.pid(); + let (stdin, stdout) = child + .take_pipes() + .map_err(|_| SpawnFailure::Error(AcpDelegationError::SpawnFailed))?; + + let (command_tx, command_rx) = mpsc::channel(1); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let shared = Arc::new(Shared::new(shutdown_tx.subscribe(), deadline)); + let wire = Arc::new(Wire::new(wrap_stdin(stdin), shared.clone())); + let transport = bounded_lines(stdout, wire.clone(), shared.clone()); + // No clone of the wire may outlive the connection inside the supervisor + // task: an outer `Arc` held by the task would keep the child's + // stdin open and defeat the natural-EOF path. The actor closure gets + // one clone; the supervisor keeps one only to close the write end. + let actor_wire = wire.clone(); + let supervisor_wire = wire.clone(); + drop(wire); + let shared_for_client = shared.clone(); + let (proof_tx, proof_rx) = watch::channel(None); + let active = Arc::new(AtomicUsize::new(1)); + let supervisor_active = active.clone(); + let cwd = launch.cwd().to_owned(); + let mut supervisor_shutdown = shutdown_tx.subscribe(); + + let mut supervisor_child = child; + let supervisor = tokio::spawn(async move { + let mut connection = Box::pin( + Client + .v1() + .name("rustscript-agent-delegation") + .connect_with(transport, { + let shared = shared.clone(); + let wire = actor_wire; + async move |connection| { + run_actor( + connection, + command_rx, + shared, + wire, + cwd, + deadline, + shutdown_rx, + ) + .await + } + }), + ); + // One absolute cleanup budget is anchored at the first observed + // stop: external shutdown, the original run deadline, the actor's + // cleanup-start notification, or connection completion. The + // supervisor therefore does not depend on the actor being polled + // first, and it can start cleanup even when the SDK connection is + // stuck finishing a physical writer drain after the actor returned. + let cleanup_anchor = shared.cleanup_anchor.notified(); + tokio::pin!(cleanup_anchor); + let mut connection_done = false; + let cleanup_start = tokio::select! { + _result = &mut connection => { + connection_done = true; + shared.mark_cleanup_start() + } + _ = supervisor_shutdown.changed() => shared.mark_cleanup_start(), + _ = sleep_until(deadline) => shared.mark_cleanup_start(), + _ = &mut cleanup_anchor => shared.mark_cleanup_start(), + }; + let cleanup_deadline = shared.cleanup_deadline(); + debug_assert_eq!(cleanup_start + CLEANUP_BUDGET, cleanup_deadline); + // Every path into cleanup gets the same bounded drain slice of the + // one anchored budget. A connection that cannot finish its own + // physical drain is discarded when that slice expires. + let drain_deadline = (cleanup_start + PROTOCOL_DRAIN_BUDGET).min(cleanup_deadline); + if !connection_done { + let _ = timeout_at(drain_deadline, &mut connection).await; + } + drop(connection); + // Discarding the connection released the writer; take and drop our + // write end immediately so a benign harness observes EOF and can + // exit before any group signal. The take is bounded by the same + // drain slice so an unfinished writer cannot hold it open. + let _ = timeout_at(drain_deadline, supervisor_wire.close_stdin()).await; + let mut report = supervisor_child.terminate(cleanup_deadline).await; + // Capacity stays owned until cleanup is proven. The retry loop keeps + // the unreaped leader as the group identity anchor, so a cached PID + // is never signalled after reaping. + while !report.cleanup_confirmed { + sleep(Duration::from_millis(250)).await; + report = supervisor_child + .terminate(Instant::now() + Duration::from_secs(1)) + .await; + } + // Publish the proof, then release the slot before the task exits. + // `wait_for_cleanup` fences on task exit, so a returned report is + // ordered after both steps; `latest()` may observe the report just + // before the counter drops. + let _ = proof_tx.send(Some(report.clone())); + supervisor_active.store(0, Ordering::Release); + SupervisorReport { cleanup: report } + }); + + Ok(Self { + commands: Some(command_tx), + shutdown: shutdown_tx, + supervisor: Some(supervisor), + proof: proof_rx, + pid, + deadline, + active, + shared: shared_for_client, + initialized: false, + session_id: None, + prompted: false, + closed: false, + }) + } + + /// OS process ID of the direct harness child. + pub fn pid(&self) -> u32 { + self.pid + } + + /// `1` from launch until the supervisor has finished cleanup, then `0`. + /// + /// The counter is owned by the supervisor; use + /// [`Self::cleanup_observer`] to track it after `close` or a drop. + pub fn active_count(&self) -> usize { + self.active.load(Ordering::Acquire) + } + + /// Subscribe to the supervisor's final cleanup evidence. + /// + /// Clone this before `close` (or before dropping the client). The returned + /// observer stays valid independently of this handle and is resolved only + /// after the supervisor has proven cleanup and released its process slot. + pub fn cleanup_observer(&self) -> AcpCleanupObserver { + AcpCleanupObserver { + report: self.proof.clone(), + active: self.active.clone(), + } + } + + /// Request supervisor shutdown without consuming the handle. + /// + /// This is the same one-way signal [`Self::close`] and `Drop` send. It is + /// exposed so a caller or a deterministic test can establish the + /// pre-publication stop condition before issuing a prompt. + #[doc(hidden)] + pub fn request_shutdown(&self) { + let _ = self.shutdown.send(true); + } + + /// Diagnostic ingress counters: the peak number of frames forwarded to the + /// SDK but not yet consumed, inline permission rejections, other inline + /// request rejections and ignored session updates. + #[doc(hidden)] + pub fn ingress_diagnostics(&self) -> (usize, usize, usize, usize) { + ( + self.shared.forwarded_peak(), + self.shared.permissions.load(Ordering::Relaxed), + self.shared.rejected_requests.load(Ordering::Relaxed), + self.shared.ignored_updates.load(Ordering::Relaxed), + ) + } + + /// Actual pipe-writer evidence for the one prompt: `"pending"`, + /// `"discarded"`, `"written"`, `"partial"`, `"failed"`, or `None` when no + /// prompt was armed. SDK publication alone is never reported as `"written"`. + #[doc(hidden)] + pub fn prompt_wire_state(&self) -> Option<&'static str> { + self.shared.prompt_wire().map(|wire| match wire { + PromptWire::Pending => "pending", + PromptWire::Discarded => "discarded", + PromptWire::Written => "written", + PromptWire::Partial => "partial", + PromptWire::Failed => "failed", + }) + } + + /// Send `initialize`. No file-system or terminal client capability is + /// advertised. + pub async fn initialize(&mut self) -> Result { + if self.initialized { + return Err(AcpDelegationError::InvalidPhase); + } + let response = self + .exchange( + |reply| ActorCommand::Initialize { reply }, + AcpDelegationError::InitializeFailed, + ) + .await?; + self.initialized = true; + Ok(response) + } + + /// Create exactly one new session and return its peer-assigned ID. + /// + /// The caller owns durable persistence of this ID and the prompt send + /// intent before calling [`Self::prompt`]. + pub async fn new_session(&mut self) -> Result { + if !self.initialized { + return Err(AcpDelegationError::NotInitialized); + } + if self.session_id.is_some() { + return Err(AcpDelegationError::InvalidPhase); + } + let id = self + .exchange( + |reply| ActorCommand::NewSession { reply }, + AcpDelegationError::SessionCreateFailed, + ) + .await?; + self.session_id = Some(id.clone()); + Ok(id) + } + + /// Restore the bound session using the advertised method, preferring + /// `resume`. If neither method is advertised, no setup request is sent. + pub async fn restore_session( + &mut self, + session_id: impl Into, + ) -> Result { + if !self.initialized { + return Err(AcpDelegationError::NotInitialized); + } + if self.session_id.is_some() { + return Err(AcpDelegationError::InvalidPhase); + } + let session_id = session_id.into(); + let method = self + .exchange( + |reply| ActorCommand::RestoreSession { + session_id: session_id.clone(), + reply, + }, + AcpDelegationError::RestoreFailed, + ) + .await?; + self.session_id = Some(session_id); + Ok(method) + } + + /// Send the single prompt for this connection. + /// + /// The session ID must exactly match the ID returned by setup. No text from + /// session setup or `session/load` replay is included in the result. + pub async fn prompt( + &mut self, + session_id: &str, + task: &str, + ) -> Result { + if !self.initialized { + return Err(AcpDelegationError::NotInitialized); + } + if task.is_empty() || task.len() > MAX_TASK_BYTES { + return Err(AcpDelegationError::TaskInvalid); + } + if self.prompted { + return Err(AcpDelegationError::InvalidPhase); + } + if self.session_id.as_deref() != Some(session_id) { + return Err(AcpDelegationError::SessionMismatch); + } + self.prompted = true; + // Arm the caller-side withdrawal before the command is enqueued. If + // this future is dropped while the writer is parked, the signal is + // recorded synchronously and the writer re-arbitrates under the same + // lock before its first byte. + let withdrawal = self.shared.withdrawal_guard(); + let outcome = self + .exchange( + |reply| ActorCommand::Prompt { + session_id: session_id.to_owned(), + task: task.to_owned(), + reply, + }, + AcpDelegationError::PromptFailed, + ) + .await; + withdrawal.disarm(); + outcome + } + + /// Request shutdown and wait for the owned supervisor's cleanup evidence. + /// + /// If the supervisor cannot prove cleanup within the shared absolute budget + /// plus a scheduling allowance, the supervisor remains alive with its + /// capacity until it completes; this call returns unconfirmed evidence. + pub async fn close(self) -> AcpCleanupReport { + self.close_with_wait(CLEANUP_BUDGET + CLOSE_SCHEDULING_SLACK) + .await + } + + /// Bound how long the close call waits for supervisor evidence. + /// + /// The supervisor keeps ownership when this wait expires and continues + /// until cleanup is proven, so callers must use the observer for the final + /// result. The default [`Self::close`] uses [`CLEANUP_BUDGET`] plus a + /// scheduling allowance; this seam exists so a test can observe an + /// unconfirmed bounded close without changing the production budget. + #[doc(hidden)] + pub async fn close_with_wait(mut self, wait: Duration) -> AcpCleanupReport { + self.closed = true; + let _ = self.shutdown.send(true); + self.commands.take(); + let Some(supervisor) = self.supervisor.take() else { + return AcpCleanupReport::unconfirmed(); + }; + match timeout(wait, supervisor).await { + Ok(Ok(report)) => report.cleanup, + Ok(Err(_)) | Err(_) => AcpCleanupReport::unconfirmed(), + } + } + + async fn exchange( + &self, + build: impl FnOnce(oneshot::Sender>) -> ActorCommand, + fallback: AcpDelegationError, + ) -> Result { + let commands = self.commands.as_ref().ok_or(AcpDelegationError::Closed)?; + let (reply_tx, reply_rx) = oneshot::channel(); + commands + .send(build(reply_tx)) + .await + .map_err(|_| AcpDelegationError::Closed)?; + let outcome = match timeout_at(self.deadline + CLEANUP_BUDGET, reply_rx).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => { + if Instant::now() >= self.deadline { + Err(AcpDelegationError::DeadlineExceeded) + } else { + Err(self.shared.fatal().unwrap_or(fallback)) + } + } + Err(_) => { + let _ = self.shutdown.send(true); + Err(AcpDelegationError::DeadlineExceeded) + } + }; + // Ingress quota for the matching response belongs to the actor branch + // that consumes it, not to this caller wait: the wait can be abandoned + // while the response still reaches the SDK. + outcome + } +} + +impl Drop for DelegatedAcpClient { + fn drop(&mut self) { + if self.closed { + return; + } + let _ = self.shutdown.send(true); + self.commands.take(); + // The supervisor task owns the child and its cleanup. Dropping the + // JoinHandle detaches it instead of cancelling it. + self.supervisor.take(); + } +} + +impl AcpCleanupReport { + fn unconfirmed() -> Self { + Self { + direct_child_reaped: false, + exit_status: None, + group_signal_sent: false, + forced: false, + group_clear: false, + cleanup_confirmed: false, + } + } +} + +struct SupervisorReport { + cleanup: AcpCleanupReport, +} + +enum ActorCommand { + Initialize { + reply: oneshot::Sender>, + }, + NewSession { + reply: oneshot::Sender>, + }, + RestoreSession { + session_id: String, + reply: oneshot::Sender>, + }, + Prompt { + session_id: String, + task: String, + reply: oneshot::Sender>, + }, +} + +struct Actor { + connection: agent_client_protocol::v1::ConnectionTo, + shared: Arc, + wire: Arc, + cwd: PathBuf, + deadline: Instant, + initialized: bool, + capabilities: AcpAgentCapabilities, + session_id: Option, + prompted: bool, +} + +async fn run_actor( + connection: agent_client_protocol::v1::ConnectionTo, + commands: mpsc::Receiver, + shared: Arc, + wire: Arc, + cwd: PathBuf, + deadline: Instant, + shutdown: watch::Receiver, +) -> Result<(), SdkError> { + let cleanup = shared.clone(); + let result = + run_actor_commands(connection, commands, shared, wire, cwd, deadline, shutdown).await; + // The SDK keeps the physical transport draining after this foreground task + // returns, so its connection future is a late and unreliable termination + // signal; the supervisor could otherwise wait for the run deadline. Publish + // the single idempotent cleanup anchor at the one common exit of every + // outcome: clean prompt completion, early setup error, caller withdrawal + // and command EOF. Earlier stops still anchor first, at their own point. + cleanup.mark_cleanup_start(); + result +} + +async fn run_actor_commands( + connection: agent_client_protocol::v1::ConnectionTo, + mut commands: mpsc::Receiver, + shared: Arc, + wire: Arc, + cwd: PathBuf, + deadline: Instant, + mut shutdown: watch::Receiver, +) -> Result<(), SdkError> { + let mut actor = Actor { + connection, + shared, + wire, + cwd, + deadline, + initialized: false, + capabilities: AcpAgentCapabilities { + resume: false, + load: false, + }, + session_id: None, + prompted: false, + }; + loop { + tokio::select! { + _ = shutdown.changed() => { + actor.shared.mark_cleanup_start(); + return Ok(()); + } + _ = sleep_until(deadline) => { + actor.shared.mark_cleanup_start(); + return Ok(()); + } + command = commands.recv() => match command { + Some(ActorCommand::Initialize { reply }) => { + if actor.initialized { + let _ = reply.send(Err(AcpDelegationError::InvalidPhase)); + continue; + } + // A pending setup request must not pin shutdown until the + // run deadline. Dropping the request future asks the SDK to + // cancel it locally; the connection is being torn down. + let result = tokio::select! { + _ = shutdown.changed() => { + let _ = reply.send(Err(AcpDelegationError::Cancelled)); + return Ok(()); + } + result = actor.initialize() => result, + }; + if result.is_ok() { + actor.initialized = true; + } + let _ = reply.send(result); + } + Some(ActorCommand::NewSession { reply }) => { + let result = tokio::select! { + _ = shutdown.changed() => { + let _ = reply.send(Err(AcpDelegationError::Cancelled)); + return Ok(()); + } + result = actor.new_session() => result, + }; + let _ = reply.send(result); + } + Some(ActorCommand::RestoreSession { session_id, reply }) => { + let result = tokio::select! { + _ = shutdown.changed() => { + let _ = reply.send(Err(AcpDelegationError::Cancelled)); + return Ok(()); + } + result = actor.restore_session(session_id) => result, + }; + let _ = reply.send(result); + } + Some(ActorCommand::Prompt { + session_id, + task, + reply, + }) => { + let mut reply = reply; + let result = actor + .prompt(&session_id, &task, &mut shutdown, &mut reply) + .await; + let _ = reply.send(result); + // One prompt per connection. The supervisor now closes + // stdio and verifies process cleanup. + return Ok(()); + } + None => return Ok(()), + }, + } + } +} + +impl Actor { + async fn initialize(&mut self) -> Result { + let request = InitializeRequest::new(ProtocolVersion::V1).client_info(Implementation::new( + "rustscript-agent", + env!("CARGO_PKG_VERSION"), + )); + let prepared = self.connection.prepare_request(request); + let request_id = prepared.raw_id().clone(); + self.shared.expect_response(request_id.clone()); + let outcome = timeout_at(self.deadline, prepared.block_task()).await; + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); + let response = match outcome { + Err(_) => return Err(AcpDelegationError::DeadlineExceeded), + Ok(Ok(response)) => response, + Ok(Err(error)) => return Err(self.initialize_failure(error)), + }; + if response.protocol_version != ProtocolVersion::V1 { + return Err(AcpDelegationError::ProtocolVersion); + } + let capabilities = AcpAgentCapabilities { + resume: response + .agent_capabilities + .session_capabilities + .resume + .is_some(), + load: response.agent_capabilities.load_session, + }; + self.capabilities = capabilities; + Ok(capabilities) + } + + async fn new_session(&mut self) -> Result { + if !self.initialized { + return Err(AcpDelegationError::NotInitialized); + } + if self.session_id.is_some() { + return Err(AcpDelegationError::InvalidPhase); + } + let request = NewSessionRequest::new(&self.cwd).mcp_servers(Vec::new()); + let prepared = self.connection.prepare_request(request); + let request_id = prepared.raw_id().clone(); + self.shared.expect_response(request_id.clone()); + let outcome = timeout_at(self.deadline, prepared.block_task()).await; + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); + let response = match outcome { + Err(_) => return Err(AcpDelegationError::DeadlineExceeded), + Ok(Ok(response)) => response, + Ok(Err(_)) => return Err(self.failure(AcpDelegationError::SessionCreateFailed)), + }; + let id = response.session_id.to_string(); + self.shared.set_session(&id); + self.session_id = Some(id.clone()); + Ok(id) + } + + async fn restore_session( + &mut self, + session_id: String, + ) -> Result { + if !self.initialized { + return Err(AcpDelegationError::NotInitialized); + } + if self.session_id.is_some() { + return Err(AcpDelegationError::InvalidPhase); + } + let method = self + .capabilities + .restore_method() + .ok_or(AcpDelegationError::RestoreUnsupported)?; + let session = SessionId::from(session_id.clone()); + match method { + AcpRestoreMethod::Resume => { + let request = ResumeSessionRequest::new(session, &self.cwd).mcp_servers(Vec::new()); + let prepared = self.connection.prepare_request(request); + let request_id = prepared.raw_id().clone(); + self.shared.expect_response(request_id.clone()); + let outcome = timeout_at(self.deadline, prepared.block_task()).await; + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); + match outcome { + Err(_) => return Err(AcpDelegationError::DeadlineExceeded), + Ok(Ok(_)) => {} + Ok(Err(_)) => return Err(self.failure(AcpDelegationError::RestoreFailed)), + } + } + AcpRestoreMethod::Load => { + let request = LoadSessionRequest::new(session, &self.cwd).mcp_servers(Vec::new()); + let prepared = self.connection.prepare_request(request); + let request_id = prepared.raw_id().clone(); + self.shared.expect_response(request_id.clone()); + let outcome = timeout_at(self.deadline, prepared.block_task()).await; + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); + match outcome { + Err(_) => return Err(AcpDelegationError::DeadlineExceeded), + Ok(Ok(_)) => {} + Ok(Err(_)) => return Err(self.failure(AcpDelegationError::RestoreFailed)), + } + } + } + self.shared.set_session(&session_id); + self.session_id = Some(session_id); + Ok(method) + } + + async fn prompt( + &mut self, + session_id: &str, + task: &str, + shutdown: &mut watch::Receiver, + reply: &mut oneshot::Sender>, + ) -> Result { + if !self.initialized { + return Err(AcpDelegationError::NotInitialized); + } + if self.prompted { + return Err(AcpDelegationError::InvalidPhase); + } + if self.session_id.as_deref() != Some(session_id) { + return Err(AcpDelegationError::SessionMismatch); + } + self.prompted = true; + + // A stop already decided before arming is not a wire attempt at all. + // This is only a fast path: the writer repeats the decision under the + // arbitration lock immediately before its first byte, so a race here + // cannot force an unwanted frame onto the pipe. + let expired = Instant::now() >= self.deadline; + let withdrawn = reply.is_closed(); + if expired || withdrawn || *shutdown.borrow() { + return Err(if expired { + AcpDelegationError::DeadlineExceeded + } else { + AcpDelegationError::Cancelled + }); + } + + let request = PromptRequest::new( + SessionId::from(session_id.to_owned()), + vec![ContentBlock::from(task.to_owned())], + ); + let prepared = self.connection.prepare_request(request); + let request_id = prepared.raw_id().clone(); + // Arm the exact response ID and the writer record before the SDK can + // enqueue the request. Only the pipe writer may transition the record + // to a committed frame: SDK reservation, queue entry and a first + // `Pending` poll prove nothing about the wire. + self.shared.begin_prompt(session_id, request_id.clone()); + let mut response = Box::pin(prepared.block_task()); + + enum Stopped { + Shutdown, + Withdrawn, + Deadline, + Failed, + } + + // Caller withdrawal is a stop input, not a polled guess: the reply + // channel closes the moment the caller drops the wait. + let withdrawn = std::future::poll_fn(|cx| reply.poll_closed(cx)); + tokio::pin!(withdrawn); + + let outcome = tokio::select! { + _ = shutdown.changed() => Err(Stopped::Shutdown), + _ = &mut withdrawn => Err(Stopped::Withdrawn), + result = timeout_at(self.deadline, &mut response) => { + match result { + Err(_) => Err(Stopped::Deadline), + Ok(Ok(response)) => Ok(response), + Ok(Err(_)) => Err(Stopped::Failed), + } + } + }; + + match outcome { + Ok(response) => { + self.shared.release_forwarded(&request_id); + Ok(self.finish_prompt_response(response)) + } + Err(Stopped::Failed) => { + // A publication, transport or peer error is not a caller + // cancellation, so it never requests `session/cancel`. If the + // writer never started, record that no byte was exposed. + self.shared.abandon_unwritten_prompt(&request_id); + self.shared.release_forwarded(&request_id); + Err(self.failure(AcpDelegationError::PromptFailed)) + } + Err(stop) => { + // Anchor the single cleanup window at this first observed stop, + // before any IO, and charge the cancel serialization to its + // bounded drain slice. TERM and reap keep the rest of the + // budget, so a stuck cancel write can never push them out. + self.shared.mark_cleanup_start(); + let drain_deadline = self.shared.cancel_drain_deadline(); + match self.shared.request_prompt_cancel(&request_id) { + CancelAction::SendNow => { + if timeout_at(drain_deadline, self.wire.write_session_cancel(&request_id)) + .await + .is_err() + { + // The cancel line could not be taken and flushed + // inside the drain slice. A partial line may now be + // on the wire: stop appending, settle the + // arbitration and let group cleanup proceed. + self.wire.poison(); + self.shared.finish_cancel_write(&request_id); + } + } + CancelAction::Deferred => { + // Give the writer one bounded chance to finish its own + // transition inside the same drain slice. It either + // discards the frame before any byte or completes it and + // writes the single cancel. + let _ = timeout_at( + drain_deadline, + self.shared.wait_prompt_settled(&request_id), + ) + .await; + } + CancelAction::None => {} + } + self.shared.release_forwarded(&request_id); + Err(match stop { + Stopped::Deadline => AcpDelegationError::DeadlineExceeded, + _ => AcpDelegationError::Cancelled, + }) + } + } + } + + fn finish_prompt_response(&self, response: PromptResponse) -> AcpPromptResult { + let (text, truncated) = { + // Close the prompt phase before sampling so a notification written + // after the response cannot join this turn's result. + self.shared.finish_prompt(); + self.shared.take_text() + }; + AcpPromptResult { + text, + truncated, + stop_reason: map_stop_reason(response.stop_reason), + } + } + + fn failure(&self, fallback: AcpDelegationError) -> AcpDelegationError { + self.shared.fatal().unwrap_or(fallback) + } + + /// The SDK reports a negotiated-version mismatch as an invalid request with + /// a protocol-version explanation in its data. Surface that case with the + /// dedicated code instead of a generic initialize failure. + fn initialize_failure(&self, error: SdkError) -> AcpDelegationError { + let version_mismatch = error + .data + .as_ref() + .and_then(Value::as_str) + .is_some_and(|data| data.contains("ACP protocol version")); + if version_mismatch { + AcpDelegationError::ProtocolVersion + } else { + self.failure(AcpDelegationError::InitializeFailed) + } + } +} + +fn map_stop_reason(reason: agent_client_protocol::v1::schema::StopReason) -> AcpStopReason { + use agent_client_protocol::v1::schema::StopReason; + match reason { + StopReason::EndTurn => AcpStopReason::EndTurn, + StopReason::MaxTokens => AcpStopReason::MaxTokens, + StopReason::MaxTurnRequests => AcpStopReason::MaxTurnRequests, + StopReason::Refusal => AcpStopReason::Refusal, + StopReason::Cancelled => AcpStopReason::Cancelled, + _ => AcpStopReason::Other, + } +} + +const PHASE_SETUP: u8 = 0; +const PHASE_PROMPT: u8 = 1; +const PHASE_DONE: u8 = 2; + +/// Actual pipe-writer evidence for the one prompt this connection may send. +/// +/// SDK publication (`PreparedRequest::block_task`) only enqueues the frame; it +/// does not prove the bytes reached the child. These states distinguish a frame +/// the writer discarded before any byte from one it committed, and a partial or +/// zero-byte write from a delivered prompt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PromptWire { + /// Armed, but the writer has not made its pre-write decision yet. + Pending, + /// Shutdown, the deadline or caller withdrawal won before any byte, so the + /// writer dropped the frame without touching the pipe. + Discarded, + /// The complete request line, its delimiter and the flush were written. + Written, + /// Some bytes of the request line were written, but the framed line was + /// not completed; the peer cannot have parsed a prompt. + Partial, + /// The writer failed before writing any byte of the request line. + Failed, +} + +/// Writer transition for the one prompt. A zero-byte `poll_write` or the first +/// `Poll::Pending` leaves the frame `Armed` and therefore revocable; `Writing` +/// is only entered once the kernel accepted at least one byte, and `Complete` +/// only once every byte of the line *and* its delimiter was accepted. The +/// first-byte decision and every transition happen under the arbitration lock, +/// in the same critical section as the `poll_write` that produced the byte +/// count. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PromptState { + /// Armed, no byte of the frame has been confirmed on the pipe. + Armed, + /// At least one byte was confirmed but the frame (delimiter included) is + /// not complete. A stop now can only mark it possibly executed. + Writing, + Discarded, + FailedNoBytes, + Partial, + Complete, +} + +/// Settlement of the prompt request itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PromptOutcome { + Outstanding, + /// The serial ingress forwarded the matching response. This wins over any + /// later cancellation. + Answered, + /// Exactly one intentional `session/cancel` owns this turn. + CancelClaimed, +} + +/// What the actor must do after recording a cancellation request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CancelAction { + /// Nothing was or can be sent. + None, + /// The writer has not finished its own transition; it will discard the + /// frame or write the single cancel when it completes. + Deferred, + /// The frame is complete and outstanding; write the single cancel now. + SendNow, +} + +struct PromptGate { + id: RawJsonRpcId, + session: String, + state: PromptState, + outcome: PromptOutcome, + /// A stop observed by the actor before the writer settled the frame. + cancel_requested: bool, + /// Set once, by the single owner that serializes `session/cancel`. + cancel_claimed: bool, + /// Set after that owner's write attempt finished (including a failed one). + cancel_done: bool, +} + +impl PromptGate { + fn new(session: &str, id: RawJsonRpcId) -> Self { + Self { + id, + session: session.to_owned(), + state: PromptState::Armed, + outcome: PromptOutcome::Outstanding, + cancel_requested: false, + cancel_claimed: false, + cancel_done: false, + } + } +} + +/// Serialized ingress and prompt arbitration state. +/// +/// `expected` is the single response ID the ingress may forward; `prompt` is +/// the one writer-owned prompt record. Both live under one mutex, so the +/// writer's first-byte decision, the matching-response claim and the +/// cancellation decision are one linearizable ordering rather than snapshots +/// spread across the SDK, actor and sink. +#[derive(Default)] +struct Ingress { + expected: Option, + prompt: Option, + /// Waker of the pipe writer currently parked in `poll_write`. A stop + /// recorded under this lock takes and wakes it, so an unfinished frame is + /// re-arbitrated instead of waiting for pipe readiness or the deadline. + writer_waker: Option, + /// Caller-side withdrawal, recorded synchronously under this lock when the + /// caller's future is dropped. The writer re-reads it immediately before + /// its first byte, so it never depends on the actor being polled first. + withdrawn: bool, +} + +/// Frames handed to the SDK but not yet consumed by it. +#[derive(Default)] +struct ForwardedBudget { + messages: usize, + bytes: usize, + peak: usize, + /// Request ID and wire size of each forwarded frame, released by the actor + /// branch that owns the corresponding request once the SDK has consumed the + /// response (or the connection ended). + outstanding: Vec<(RawJsonRpcId, usize)>, +} + +/// Monotonic stop inputs checked by the writer under the arbitration lock. +struct Stop { + shutdown: watch::Receiver, + deadline: Instant, +} + +impl Stop { + fn tripped(&self) -> bool { + *self.shutdown.borrow() || Instant::now() >= self.deadline + } +} + +#[derive(Default)] +struct Shared { + phase: AtomicU8, + ingress: Mutex, + session: Mutex>, + text: Mutex, + truncated: AtomicBool, + forwarded: Mutex, + fatal: Mutex>, + permissions: AtomicUsize, + rejected_requests: AtomicUsize, + ignored_updates: AtomicUsize, + /// `None` in unit tests that do not model a live connection. + stop: Option, + /// First instant a stop was observed. Protocol drain, cancel serialization, + /// group termination and reaping all share one absolute budget anchored + /// here, so later IO cannot extend the cleanup window. + cleanup_start: Mutex>, + /// Fires once when [`Shared::mark_cleanup_start`] stores the first anchor. + /// The supervisor watches this independently of the actor and the + /// connection future, so an actor-side stop still starts cleanup when the + /// SDK cannot finish its physical drain. + cleanup_anchor: tokio::sync::Notify, + /// Wakes an actor waiting for the writer's terminal transition. + settled: tokio::sync::Notify, +} + +impl Shared { + fn new(shutdown: watch::Receiver, deadline: Instant) -> Self { + Self { + stop: Some(Stop { shutdown, deadline }), + ..Self::default() + } + } + + fn set_session(&self, session_id: &str) { + *self.session.lock().unwrap() = Some(session_id.to_owned()); + self.phase.store(PHASE_SETUP, Ordering::Release); + } + + fn begin_prompt(&self, session_id: &str, request_id: RawJsonRpcId) { + self.text.lock().unwrap().clear(); + self.truncated.store(false, Ordering::Release); + *self.session.lock().unwrap() = Some(session_id.to_owned()); + let mut ingress = self.ingress.lock().unwrap(); + // Arm the exact response ID and the writer record before the request + // can be published, so neither the ingress nor the pipe writer can + // observe this prompt without the arbitration record in place. + ingress.expected = Some(request_id.clone()); + ingress.prompt = Some(PromptGate::new(session_id, request_id)); + self.phase.store(PHASE_PROMPT, Ordering::Release); + } + + fn expect_response(&self, request_id: RawJsonRpcId) { + self.ingress.lock().unwrap().expected = Some(request_id); + } + + fn clear_expected(&self, request_id: &RawJsonRpcId) { + let mut ingress = self.ingress.lock().unwrap(); + if ingress.expected.as_ref() == Some(request_id) { + ingress.expected = None; + } + } + + fn stop_tripped(&self) -> bool { + self.stop.as_ref().is_some_and(Stop::tripped) + } + + /// Arm the caller-side withdrawal signal before the prompt command is + /// handed to the actor. Dropping the guard is the same event as the + /// caller's future being dropped, and records the decision synchronously + /// so a parked writer cannot publish a first byte merely because the actor + /// was not polled yet. + fn withdrawal_guard(self: &Arc) -> CallerWithdrawal { + CallerWithdrawal { + shared: self.clone(), + armed: true, + } + } + + /// Record caller withdrawal under the arbitration lock and wake a parked + /// writer. Mirrors [`Self::request_prompt_cancel`], but originates from the + /// caller's drop instead of a later actor poll. + fn withdraw(&self) { + let waker = { + let mut ingress = self.ingress.lock().unwrap(); + ingress.withdrawn = true; + ingress.writer_waker.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + } + + /// True once the caller's wait was dropped. Checked under the same ingress + /// lock as the first-byte decision. + #[cfg(test)] + fn withdrawn(&self) -> bool { + self.ingress.lock().unwrap().withdrawn + } + + /// Anchor the single absolute cleanup budget at the first observed stop. + /// Repeated calls (shutdown, run deadline, prompt failure, supervisor) + /// return the same instant, so IO cannot extend the window. + fn mark_cleanup_start(&self) -> Instant { + let start = { + let mut start = self.cleanup_start.lock().unwrap(); + *start.get_or_insert_with(Instant::now) + }; + // Publish the anchor to a supervisor that is still waiting on the SDK + // connection. A stored permit covers the race where the anchor lands + // before the supervisor's `notified` future is first polled. + self.cleanup_anchor.notify_one(); + start + } + + fn cleanup_start(&self) -> Option { + *self.cleanup_start.lock().unwrap() + } + + /// Bounded slice of the cleanup budget for serializing a `session/cancel` + /// line and for taking the stdin lock. Never longer than the existing + /// protocol-drain slice. + fn cancel_drain_deadline(&self) -> Instant { + self.cleanup_start() + .map(|start| (start + PROTOCOL_DRAIN_BUDGET).min(start + CLEANUP_BUDGET)) + .unwrap_or_else(|| Instant::now() + PROTOCOL_DRAIN_BUDGET) + } + + /// The single absolute cleanup deadline anchored at the first stop. + fn cleanup_deadline(&self) -> Instant { + self.cleanup_start() + .map(|start| start + CLEANUP_BUDGET) + .unwrap_or_else(|| Instant::now() + CLEANUP_BUDGET) + } + + /// Record a fully written frame. Returns `true` when this transition claimed + /// the single `session/cancel` for a still-outstanding prompt. + fn complete_prompt_write(&self, request_id: &RawJsonRpcId) -> bool { + let mut ingress = self.ingress.lock().unwrap(); + let stop = self.stop.as_ref().is_some_and(Stop::tripped); + let Some(prompt) = ingress.prompt.as_mut() else { + return false; + }; + if prompt.id != *request_id { + return false; + } + prompt.state = PromptState::Complete; + if prompt.outcome == PromptOutcome::Outstanding && (prompt.cancel_requested || stop) { + prompt.outcome = PromptOutcome::CancelClaimed; + return true; + } + false + } + + /// Called when the SDK request future failed before the writer was observed. + /// A frame the writer already started is left to its own transition. + fn abandon_unwritten_prompt(&self, request_id: &RawJsonRpcId) { + let mut ingress = self.ingress.lock().unwrap(); + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + && prompt.state == PromptState::Armed + { + prompt.state = PromptState::Discarded; + ingress.expected = None; + } + } + + /// Record an actor-observed stop. The writer, not this call, decides whether + /// any byte was exposed; a parked writer is woken so it re-arbitrates under + /// the same lock before its next byte. + fn request_prompt_cancel(&self, request_id: &RawJsonRpcId) -> CancelAction { + let mut ingress = self.ingress.lock().unwrap(); + let action = match ingress.prompt.as_mut() { + Some(prompt) if prompt.id == *request_id => match prompt.state { + PromptState::Armed | PromptState::Writing => { + if prompt.outcome != PromptOutcome::Outstanding { + CancelAction::None + } else { + prompt.cancel_requested = true; + CancelAction::Deferred + } + } + PromptState::Complete => match prompt.outcome { + PromptOutcome::Outstanding => { + prompt.outcome = PromptOutcome::CancelClaimed; + CancelAction::SendNow + } + // The writer's completion transition already claimed the + // cancel and is about to write it under the stdin lock. + // Wait for that bounded transition instead of returning + // early and risking a dropped connection before the line + // is flushed. + PromptOutcome::CancelClaimed if !prompt.cancel_done => CancelAction::Deferred, + PromptOutcome::Answered | PromptOutcome::CancelClaimed => CancelAction::None, + }, + PromptState::Discarded | PromptState::FailedNoBytes | PromptState::Partial => { + CancelAction::None + } + }, + _ => CancelAction::None, + }; + let waker = if matches!(action, CancelAction::Deferred) { + ingress.writer_waker.take() + } else { + None + }; + drop(ingress); + if let Some(waker) = waker { + waker.wake(); + } + action + } + + /// Claim the single right to serialize `session/cancel`, returning the + /// prompt session exactly once. + fn begin_cancel_write(&self, request_id: &RawJsonRpcId) -> Option { + let mut ingress = self.ingress.lock().unwrap(); + let prompt = ingress.prompt.as_mut()?; + if prompt.id != *request_id + || prompt.outcome != PromptOutcome::CancelClaimed + || prompt.cancel_claimed + { + return None; + } + prompt.cancel_claimed = true; + Some(prompt.session.clone()) + } + + /// Mark the single cancel write attempt finished, even when the pipe write + /// failed, and wake a waiter that was fenced on that attempt. + fn finish_cancel_write(&self, request_id: &RawJsonRpcId) { + let mut ingress = self.ingress.lock().unwrap(); + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + { + prompt.cancel_done = true; + } + drop(ingress); + self.settle_prompt(); + } + + fn settle_prompt(&self) { + self.settled.notify_waiters(); + } + + async fn wait_prompt_settled(&self, request_id: &RawJsonRpcId) { + loop { + let notified = self.settled.notified(); + { + let ingress = self.ingress.lock().unwrap(); + let settled = match ingress.prompt.as_ref() { + Some(prompt) if prompt.id == *request_id => { + let terminal = matches!( + prompt.state, + PromptState::Discarded + | PromptState::FailedNoBytes + | PromptState::Partial + | PromptState::Complete + ); + // A writer-owned cancel is not settled until its line + // has actually been written (or answered before then). + terminal + && (prompt.outcome != PromptOutcome::CancelClaimed + || prompt.cancel_done) + } + _ => true, + }; + if settled { + return; + } + } + notified.await; + } + } + + /// True while `id` is the reserved prompt request, so the wire can suppress + /// the SDK's deferred automatic `$/cancel_request` for it. + fn is_reserved_prompt_id(&self, request_id: &RawJsonRpcId) -> bool { + self.ingress + .lock() + .unwrap() + .prompt + .as_ref() + .is_some_and(|prompt| prompt.id == *request_id) + } + + fn prompt_wire(&self) -> Option { + self.ingress + .lock() + .unwrap() + .prompt + .as_ref() + .map(|prompt| match prompt.state { + PromptState::Armed | PromptState::Writing => PromptWire::Pending, + PromptState::Discarded => PromptWire::Discarded, + PromptState::FailedNoBytes => PromptWire::Failed, + PromptState::Partial => PromptWire::Partial, + PromptState::Complete => PromptWire::Written, + }) + } + + fn finish_prompt(&self) { + self.phase.store(PHASE_DONE, Ordering::Release); + } + + fn take_text(&self) -> (String, bool) { + ( + self.text.lock().unwrap().clone(), + self.truncated.load(Ordering::Acquire), + ) + } + + fn fatal(&self) -> Option { + *self.fatal.lock().unwrap() + } + + fn set_fatal(&self, error: AcpDelegationError) { + let mut fatal = self.fatal.lock().unwrap(); + if fatal.is_none() { + *fatal = Some(error); + } + } + + /// Charge a frame that is about to enter the SDK transport. The charge is + /// released by [`Self::release_forwarded`] in the actor branch that consumes + /// the response for `request_id`. + fn admit_forward(&self, request_id: &RawJsonRpcId, bytes: usize) -> Result<(), io::Error> { + let mut forwarded = self.forwarded.lock().unwrap(); + if forwarded.messages + 1 > MAX_TURN_NOTIFICATIONS + || forwarded.bytes.saturating_add(bytes) > MAX_TURN_NOTIFICATION_BYTES + { + drop(forwarded); + self.set_fatal(AcpDelegationError::NotificationFlood); + return Err(io::Error::other("acp ingress quota exceeded")); + } + forwarded.messages += 1; + forwarded.bytes += bytes; + forwarded.outstanding.push((request_id.clone(), bytes)); + forwarded.peak = forwarded.peak.max(forwarded.messages); + Ok(()) + } + + /// Release the quota charged for exactly `request_id`, if it is still + /// outstanding. Called from the actor branch after the SDK has consumed the + /// response, so abandoning the caller's wait cannot leak the slot. + fn release_forwarded(&self, request_id: &RawJsonRpcId) { + let mut forwarded = self.forwarded.lock().unwrap(); + let Some(index) = forwarded + .outstanding + .iter() + .position(|(id, _)| id == request_id) + else { + return; + }; + let (_, bytes) = forwarded.outstanding.remove(index); + forwarded.messages -= 1; + forwarded.bytes -= bytes; + } + + fn forwarded_peak(&self) -> usize { + self.forwarded.lock().unwrap().peak + } + + /// Validate one `session/update` with the locked SDK schema and append only + /// matching `agent_message_chunk` text for the current prompt session. + fn ingest_update(&self, params: Option<&RawJsonRpcParams>) { + let Some(RawJsonRpcParams::Object(params)) = params else { + self.ignored_updates.fetch_add(1, Ordering::Relaxed); + return; + }; + if self.phase.load(Ordering::Acquire) != PHASE_PROMPT { + return; + } + let Ok(notification) = + serde_json::from_value::(Value::Object(params.clone())) + else { + self.ignored_updates.fetch_add(1, Ordering::Relaxed); + return; + }; + let session_matches = { + let session = self.session.lock().unwrap(); + session.as_deref() == Some(notification.session_id.0.as_ref()) + }; + if !session_matches { + self.ignored_updates.fetch_add(1, Ordering::Relaxed); + return; + } + if let SessionUpdate::AgentMessageChunk(chunk) = notification.update + && let ContentBlock::Text(content) = chunk.content + { + self.append_text(&content.text); + } + } + + /// Answer a peer request inline so it never enters the SDK dispatch queue. + async fn reject_request( + &self, + wire: &Wire, + request_id: &RawJsonRpcId, + method: &str, + ) -> Result<(), io::Error> { + let response = if method == "session/request_permission" { + self.permissions.fetch_add(1, Ordering::Relaxed); + let result = serde_json::to_value(RequestPermissionResponse::new( + RequestPermissionOutcome::Cancelled, + )) + .map_err(io::Error::other)?; + RawJsonRpcMessage::response(request_id.clone(), Ok(result)) + } else { + self.rejected_requests.fetch_add(1, Ordering::Relaxed); + RawJsonRpcMessage::response( + request_id.clone(), + Err(agent_client_protocol::Error::method_not_found()), + ) + }; + let line = serde_json::to_string(&response).map_err(io::Error::other)?; + wire.write_line(&line).await + } + + /// Serial ingress gate. Returns `true` only for the response matching the + /// outstanding request; every other frame is fully handled or discarded + /// here and never reaches the SDK's unbounded transport channel. + async fn classify(&self, line: &str, wire: &Wire) -> Result { + let Ok(message) = serde_json::from_str::(line) else { + return Ok(false); + }; + match message { + RawJsonRpcMessage::Response(response) => { + if !self.take_expected(response.id()) { + return Ok(false); + } + // Seal before the SDK dispatches the response, so text written + // after it can never join this turn. + if self.phase.load(Ordering::Acquire) == PHASE_PROMPT { + self.finish_prompt(); + } + self.admit_forward(response.id(), line.len())?; + Ok(true) + } + RawJsonRpcMessage::Request(request) => { + self.reject_request(wire, &request.id, request.method.as_ref()) + .await?; + Ok(false) + } + RawJsonRpcMessage::Notification(notification) => { + if notification.method.as_ref() == "session/update" { + self.ingest_update(notification.params.as_ref()); + } + Ok(false) + } + } + } + + /// Claim the expected response ID. Only the first response with exactly + /// this typed ID (string and number forms differ) is forwarded. Claiming + /// the prompt response also settles the cancel arbitration under the same + /// lock, so a matching response can never be followed by a late cancel. + /// + /// A response for the prompt is accepted only once the writer has proven a + /// complete frame (line *and* delimiter accepted by the kernel). A partial + /// or merely in-progress frame is never promoted to `Complete`: an honest + /// peer cannot have answered it, so the response is dropped. + fn take_expected(&self, request_id: &RawJsonRpcId) -> bool { + let mut ingress = self.ingress.lock().unwrap(); + if ingress.expected.as_ref() != Some(request_id) { + return false; + } + let mut accept = true; + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + { + match prompt.state { + PromptState::Complete => { + if prompt.outcome == PromptOutcome::Outstanding { + prompt.outcome = PromptOutcome::Answered; + } + prompt.cancel_requested = false; + } + PromptState::Armed + | PromptState::Writing + | PromptState::Discarded + | PromptState::FailedNoBytes + | PromptState::Partial => accept = false, + } + } + if accept { + ingress.expected = None; + } + accept + } + + fn append_text(&self, text: &str) { + if self.truncated.load(Ordering::Acquire) { + return; + } + let mut output = self.text.lock().unwrap(); + let remaining = MAX_RESULT_TEXT_BYTES.saturating_sub(output.len()); + if text.len() <= remaining { + output.push_str(text); + return; + } + let mut end = remaining.min(text.len()); + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + output.push_str(&text[..end]); + self.truncated.store(true, Ordering::Release); + } +} + +/// Caller-side RAII withdrawal signal for the single prompt. +/// +/// Armed before the prompt command enters the actor channel and dropped +/// together with the caller's future. Disarming is used only after the +/// exchange completed, so a finished prompt cannot later look withdrawn. +struct CallerWithdrawal { + shared: Arc, + armed: bool, +} + +impl CallerWithdrawal { + fn disarm(mut self) { + self.armed = false; + } +} + +impl Drop for CallerWithdrawal { + fn drop(&mut self) { + if self.armed { + self.shared.withdraw(); + } + } +} + +/// The exclusive write end. Production always holds the child's `ChildStdin`; +/// the boxed form lets a deterministic test substitute a controllable sink +/// while the same writer, arbitration and ordering code runs unchanged. +type StdinWriter = Box; + +/// Serialized writer shared by the SDK outgoing sink and ingress rejections. +/// +/// Whole lines are written under one lock so protocol responses authored at the +/// ingress boundary never interleave with SDK frames. This writer is also the +/// only authority on prompt publication: it decides under the arbitration lock +/// immediately before the first byte, records the actual frame outcome, writes +/// the single intentional `session/cancel`, and suppresses the SDK's deferred +/// automatic `$/cancel_request` for the reserved prompt id. +struct Wire { + /// Exclusive write end of the child's stdin. Held as an `Option` so the + /// supervisor can take and drop it after discarding the connection, which + /// closes the pipe and gives a benign harness its natural EOF before any + /// group signal. + stdin: tokio::sync::Mutex>, + shared: Arc, + /// A partially delivered prompt line poisons the connection: no follow-on + /// line, including a cancellation, may be appended to the truncated line. + poisoned: AtomicBool, +} + +impl Wire { + fn new(stdin: StdinWriter, shared: Arc) -> Self { + Self { + stdin: tokio::sync::Mutex::new(Some(stdin)), + shared, + poisoned: AtomicBool::new(false), + } + } + + /// Take and drop the write end so the harness observes EOF. The caller + /// bounds this so a writer that never yields cannot pin the close. + async fn close_stdin(&self) -> bool { + let mut stdin = self.stdin.lock().await; + stdin.take().is_some() + } + + fn poison(&self) { + self.poisoned.store(true, Ordering::Release); + } + + async fn write_line(&self, line: &str) -> io::Result<()> { + if self.poisoned.load(Ordering::Acquire) { + return Ok(()); + } + let frame = OutgoingFrame::parse(line); + if let OutgoingFrame::SdkCancelRequest(id) = &frame + && self.shared.is_reserved_prompt_id(id) + { + // The client owns cancellation of its prompt: it writes at most one + // intentional `session/cancel` and never lets the SDK's deferred + // drop-time `$/cancel_request` reach this prompt. + return Ok(()); + } + let mut stdin = self.stdin.lock().await; + if self.poisoned.load(Ordering::Acquire) { + return Ok(()); + } + let Some(stdin) = stdin.as_mut() else { + return Ok(()); + }; + match frame { + OutgoingFrame::Prompt(id) => { + let (result, wire) = write_prompt_frame(stdin, line, &id, &self.shared).await; + match wire { + PromptWire::Written => { + if self.shared.complete_prompt_write(&id) { + let _ = self.write_cancel_locked(stdin, &id).await; + } + } + PromptWire::Partial => { + // Some bytes of the line may have reached the peer. Do + // not append anything into the incomplete line; the + // supervisor's cleanup terminates the process. + self.poison(); + } + PromptWire::Failed | PromptWire::Pending | PromptWire::Discarded => {} + } + self.shared.settle_prompt(); + result + } + _ => write_plain_line(stdin, line).await, + } + } + + /// Write the single intentional `session/cancel` when the actor's + /// `CancelAction::SendNow` claimed it. + async fn write_session_cancel(&self, request_id: &RawJsonRpcId) -> io::Result<()> { + if self.poisoned.load(Ordering::Acquire) { + self.shared.finish_cancel_write(request_id); + return Ok(()); + } + let Some(session) = self.shared.begin_cancel_write(request_id) else { + return Ok(()); + }; + let mut stdin = self.stdin.lock().await; + let result = match stdin.as_mut() { + Some(stdin) if !self.poisoned.load(Ordering::Acquire) => { + write_cancel_line(stdin, &session).await + } + _ => Ok(()), + }; + drop(stdin); + self.shared.finish_cancel_write(request_id); + result + } + + /// Write the deferred cancel owned by the writer's completion transition, + /// while the stdin lock and therefore the prompt's wire order are held. + async fn write_cancel_locked( + &self, + stdin: &mut W, + request_id: &RawJsonRpcId, + ) -> io::Result<()> + where + W: tokio::io::AsyncWrite + Unpin, + { + let Some(session) = self.shared.begin_cancel_write(request_id) else { + return Ok(()); + }; + let result = write_cancel_line(stdin, &session).await; + self.shared.finish_cancel_write(request_id); + result + } +} + +enum OutgoingFrame { + Prompt(RawJsonRpcId), + /// The SDK's deferred automatic cancellation of one outgoing request. + SdkCancelRequest(RawJsonRpcId), + Other, +} + +impl OutgoingFrame { + fn parse(line: &str) -> Self { + if !line.contains("session/prompt") && !line.contains("$/cancel_request") { + return Self::Other; + } + let Ok(message) = serde_json::from_str::(line) else { + return Self::Other; + }; + match message { + RawJsonRpcMessage::Request(request) if request.method.as_ref() == "session/prompt" => { + Self::Prompt(request.id) + } + RawJsonRpcMessage::Notification(notification) + if notification.method.as_ref() == "$/cancel_request" => + { + let Some(RawJsonRpcParams::Object(params)) = notification.params else { + return Self::Other; + }; + let Some(value) = params.get("requestId") else { + return Self::Other; + }; + match serde_json::from_value::(value.clone()) { + Ok(id) => Self::SdkCancelRequest(id), + Err(_) => Self::Other, + } + } + _ => Self::Other, + } + } +} + +async fn write_plain_line(stdin: &mut W, line: &str) -> io::Result<()> +where + W: tokio::io::AsyncWrite + Unpin, +{ + stdin.write_all(line.as_bytes()).await?; + stdin.write_all(b"\n").await?; + stdin.flush().await +} + +/// Write one whole prompt frame under the arbitration lock. +/// +/// Every poll re-validates the recorded stop (shutdown, absolute deadline and +/// the caller withdrawal the actor folded into `cancel_requested`) under the +/// same lock that guards the state transition, immediately before one +/// non-blocking `poll_write`. The frame is only `Complete` once the kernel +/// accepted every byte including the delimiter; a `Pending` write or a +/// zero-byte return with no confirmed byte leaves the frame `Armed` and fully +/// revocable. A stop after a positive byte marks the frame `Partial`: the +/// connection is never appended to and no cancel notification is emitted. +async fn write_prompt_frame( + stdin: &mut W, + line: &str, + request_id: &RawJsonRpcId, + shared: &Shared, +) -> (io::Result<()>, PromptWire) +where + W: tokio::io::AsyncWrite + Unpin, +{ + let mut frame = Vec::with_capacity(line.len() + 1); + frame.extend_from_slice(line.as_bytes()); + frame.push(b'\n'); + let total = frame.len(); + let mut written = 0usize; + + std::future::poll_fn(|cx| { + let mut ingress = shared.ingress.lock().unwrap(); + // Read the recorded stop and the caller withdrawal only after taking + // the arbitration lock, so neither can land between the check and the + // first-byte decision. + let stop = shared.stop_tripped(); + let withdrawn = ingress.withdrawn; + // Read the arbitration record under the lock, then drop the borrow + // before mutating disjoint fields so the state update and the byte + // write can share this critical section. + let (known, state, cancel_requested) = match ingress.prompt.as_ref() { + Some(prompt) if prompt.id == *request_id => { + (true, prompt.state, prompt.cancel_requested) + } + _ => (false, PromptState::Armed, false), + }; + if !known || (written == 0 && state != PromptState::Armed) { + ingress.writer_waker = None; + return Poll::Ready((Ok(()), PromptWire::Discarded)); + } + // A stop recorded under this lock loses to an already-complete frame + // (which owes one cancel) but wins over any revocable or partial one. + if cancel_requested || withdrawn || stop { + if written == 0 { + if let Some(prompt) = ingress.prompt.as_mut() { + prompt.state = PromptState::Discarded; + } + ingress.expected = None; + ingress.writer_waker = None; + return Poll::Ready((Ok(()), PromptWire::Discarded)); + } + if written < total { + if let Some(prompt) = ingress.prompt.as_mut() { + prompt.state = PromptState::Partial; + } + ingress.expected = None; + ingress.writer_waker = None; + return Poll::Ready(( + Err(io::Error::new( + io::ErrorKind::Interrupted, + "prompt frame aborted after a partial write", + )), + PromptWire::Partial, + )); + } + // The delimiter is already on the pipe: fall through and report the + // complete frame so the single cancel can be claimed. + } + // Park the writer here so a stop recorded by the actor wakes this poll + // even while the pipe itself is not writable. + ingress.writer_waker = Some(cx.waker().clone()); + if written < total { + match Pin::new(&mut *stdin).poll_write(cx, &frame[written..]) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Ok(0)) => { + let wire = if written == 0 { + PromptWire::Failed + } else { + PromptWire::Partial + }; + if let Some(prompt) = ingress.prompt.as_mut() { + prompt.state = if written == 0 { + PromptState::FailedNoBytes + } else { + PromptState::Partial + }; + } + ingress.expected = None; + ingress.writer_waker = None; + return Poll::Ready((Err(io::Error::from(io::ErrorKind::WriteZero)), wire)); + } + Poll::Ready(Ok(count)) => { + written += count; + if written < total { + if let Some(prompt) = ingress.prompt.as_mut() { + prompt.state = PromptState::Writing; + } + // Make progress now instead of waiting for pipe + // readiness; the next poll re-validates the stop first. + cx.waker().wake_by_ref(); + return Poll::Pending; + } + // The kernel accepted the delimiter: complete-frame + // evidence. Only this positive return promotes the record. + if let Some(prompt) = ingress.prompt.as_mut() { + prompt.state = PromptState::Complete; + } + } + Poll::Ready(Err(error)) => { + let wire = if written == 0 { + PromptWire::Failed + } else { + PromptWire::Partial + }; + if let Some(prompt) = ingress.prompt.as_mut() { + prompt.state = if written == 0 { + PromptState::FailedNoBytes + } else { + PromptState::Partial + }; + } + ingress.expected = None; + ingress.writer_waker = None; + return Poll::Ready((Err(error), wire)); + } + } + } + match Pin::new(&mut *stdin).poll_flush(cx) { + Poll::Pending => Poll::Pending, + Poll::Ready(Ok(())) => { + ingress.writer_waker = None; + Poll::Ready((Ok(()), PromptWire::Written)) + } + Poll::Ready(Err(error)) => { + ingress.writer_waker = None; + Poll::Ready((Err(error), PromptWire::Written)) + } + } + }) + .await +} + +fn session_cancel_frame(session: &str) -> io::Result { + let params = serde_json::to_value(CancelNotification::new(SessionId::from(session.to_owned()))) + .map_err(io::Error::other)?; + let message = RawJsonRpcMessage::notification("session/cancel".to_owned(), params) + .map_err(io::Error::other)?; + serde_json::to_string(&message).map_err(io::Error::other) +} + +async fn write_cancel_line(stdin: &mut W, session: &str) -> io::Result<()> +where + W: tokio::io::AsyncWrite + Unpin, +{ + let frame = session_cancel_frame(session)?; + write_plain_line(stdin, &frame).await +} + +fn bounded_lines( + stdout: ChildStdout, + wire: Arc, + shared: Arc, +) -> Lines< + impl Sink + Send + 'static, + impl Stream> + Send + 'static, +> { + let incoming_wire = wire.clone(); + let incoming = stream::try_unfold(BufReader::new(ChildIo(stdout)), move |mut reader| { + let shared = shared.clone(); + let wire = incoming_wire.clone(); + async move { + loop { + let mut line = Vec::new(); + loop { + let chunk = reader.fill_buf().await?; + if chunk.is_empty() { + if line.is_empty() { + return Ok(None); + } + break; + } + let lf = chunk.iter().position(|byte| *byte == b'\n'); + let take = lf.unwrap_or(chunk.len()); + if line.len() + take > MAX_FRAME_BYTES { + shared.set_fatal(AcpDelegationError::FrameTooLarge); + return Err(io::Error::other("acp frame exceeds limit")); + } + line.extend_from_slice(&chunk[..take]); + reader.consume_unpin(take + usize::from(lf.is_some())); + if lf.is_some() { + if line.last() == Some(&b'\r') { + line.pop(); + } + break; + } + } + let line = String::from_utf8_lossy(&line).into_owned(); + if line.trim().is_empty() { + continue; + } + if shared.classify(&line, &wire).await? { + return Ok(Some((line, reader))); + } + // Fully consumed inline; continue without yielding. + } + } + }); + let outgoing = sink::unfold(wire, |wire: Arc, line: String| async move { + wire.write_line(&line).await?; + Ok::<_, io::Error>(wire) + }); + Lines::new(outgoing, incoming) +} + +/// `Lines` uses futures I/O; the owned child uses Tokio I/O. +struct ChildIo(T); + +impl AsyncRead for ChildIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &mut [u8], + ) -> Poll> { + let mut buffer = ReadBuf::new(bytes); + std::task::ready!(Pin::new(&mut self.0).poll_read(cx, &mut buffer))?; + Poll::Ready(Ok(buffer.filled().len())) + } +} + +impl AsyncWrite for ChildIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.0).poll_write(cx, bytes) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_flush(cx) + } + + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_shutdown(cx) + } +} + +struct OwnedChild { + child: Child, + pid: u32, + reaped: bool, + exit_status: Option, + /// Sticky for the whole cleanup episode: a later retry after the reap must + /// still report that the group was signalled before the anchor was lost. + group_signal_sent: bool, + forced: bool, +} + +/// One non-reaping observation of the direct child. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LeaderObservation { + Running, + /// Exited but still our unreaped child; the pid and group stay pinned. + Exited, + /// `waitid` reports ECHILD: this pid is not our unreaped child. + Gone, + /// The syscall failed for a reason other than ECHILD. + Unknown, +} + +/// Kernel answer to a non-delivering signal-0 query for the original group. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GroupPresence { + /// `ESRCH`: no process group with the original number remains. + Absent, + /// The group still exists, or the number was reused by a new group. + Present, + /// The query proved neither state (for example `EPERM`). + Unconfirmed, +} + +#[cfg(unix)] +fn observe_leader(pid: u32) -> LeaderObservation { + let Ok(raw) = libc::pid_t::try_from(pid) else { + return LeaderObservation::Unknown; + }; + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is a valid out-pointer. WNOHANG|WNOWAIT neither blocks nor + // releases the child, so an exited leader stays as our unreaped zombie and + // keeps the pid and process-group identity pinned. + let result = unsafe { + libc::waitid( + libc::P_PID, + raw as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + if result == 0 { + // SAFETY: the kernel filled `info` for this exited child. + return if unsafe { info.si_pid() } == 0 { + LeaderObservation::Running + } else { + LeaderObservation::Exited + }; + } + match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECHILD) => LeaderObservation::Gone, + _ => LeaderObservation::Unknown, + } +} + +#[cfg(not(unix))] +fn observe_leader(_pid: u32) -> LeaderObservation { + LeaderObservation::Unknown +} + +#[cfg(unix)] +fn classify_group_query(result: libc::c_int, errno: Option) -> GroupPresence { + if result == 0 { + GroupPresence::Present + } else if errno == Some(libc::ESRCH) { + GroupPresence::Absent + } else { + GroupPresence::Unconfirmed + } +} + +/// Non-delivering group-presence query. +/// +/// Only `ESRCH` proves absence. A zero result means some member, or a group that +/// reused the number, still exists; `EPERM` or any other errno is unknown. This +/// runs only after the exact direct child has been affirmatively reaped and it +/// never delivers a signal to the cached group number. +#[cfg(unix)] +fn group_presence(pgid: u32) -> GroupPresence { + let Ok(raw) = libc::pid_t::try_from(pgid) else { + return GroupPresence::Unconfirmed; + }; + // SAFETY: signal 0 only performs an existence/permission check. + let result = unsafe { libc::kill(-raw, 0) }; + let errno = if result == 0 { + None + } else { + std::io::Error::last_os_error().raw_os_error() + }; + classify_group_query(result, errno) +} + +#[cfg(not(unix))] +fn group_presence(_pgid: u32) -> GroupPresence { + GroupPresence::Unconfirmed +} + +#[cfg(unix)] +fn classify_wait_probe(result: libc::c_int, errno: Option) -> bool { + result != 0 && errno == Some(libc::ECHILD) +} + +/// Preflight for the kernel-backed cleanup proof. +/// +/// `waitid` on a pid that is not our child must report `ECHILD` (not `ENOSYS` +/// or a seccomp `EPERM`), and signal 0 to ourselves must be permitted. A host +/// that fails either check has untrustworthy syscall semantics for this +/// contract and is rejected before any child exists. +#[cfg(unix)] +fn kernel_cleanup_supported() -> bool { + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + let result = unsafe { + libc::waitid( + libc::P_PID, + std::process::id() as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + let errno = if result == 0 { + None + } else { + std::io::Error::last_os_error().raw_os_error() + }; + if !classify_wait_probe(result, errno) { + return false; + } + // SAFETY: signal 0 performs an existence/permission check only. + unsafe { libc::kill(std::process::id() as libc::pid_t, 0) == 0 } +} + +#[cfg(not(unix))] +fn kernel_cleanup_supported() -> bool { + false +} + +/// One creation attempt that either produced an owned child, hit an OS error, +/// or was vetoed by the caller's final launch precondition. +enum ChildSpawnError { + Io, + Veto(AcpLaunchVeto), +} + +impl OwnedChild { + fn spawn( + launch: &AcpDelegationLaunch, + precondition: Option Result<(), AcpLaunchVeto> + Send>>, + ) -> Result { + let mut command = Command::new(launch.command()); + command + .args(launch.arguments()) + .current_dir(launch.cwd()) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true); + command.env_clear(); + for key in ["HOME", "PATH", "LANG", "LC_ALL", "TZ"] { + if let Some(value) = std::env::var_os(key) { + command.env(key, value); + } + } + if std::env::var_os("PATH").is_none() { + command.env("PATH", "/usr/local/bin:/usr/bin:/bin"); + } + #[cfg(unix)] + command.process_group(0); + // The caller's last synchronous observation happens here: after every + // preparation step and immediately before the one process creation. + if let Some(precondition) = precondition { + precondition().map_err(ChildSpawnError::Veto)?; + } + let child = command.spawn().map_err(|_| ChildSpawnError::Io)?; + let pid = child.id().ok_or(ChildSpawnError::Io)?; + Ok(Self { + child, + pid, + reaped: false, + exit_status: None, + group_signal_sent: false, + forced: false, + }) + } + + fn pid(&self) -> u32 { + self.pid + } + + fn take_pipes(&mut self) -> io::Result<(ChildStdin, ChildStdout)> { + let stdin = self + .child + .stdin + .take() + .ok_or_else(|| io::Error::other("harness stdin unavailable"))?; + let stdout = self + .child + .stdout + .take() + .ok_or_else(|| io::Error::other("harness stdout unavailable"))?; + Ok((stdin, stdout)) + } + + /// Terminate the owned process group while the direct leader still pins its + /// identity, then reap that exact child and prove the original group absent. + /// + /// Every group signal is delivered before the reap. While the leader is our + /// unreaped child its pid names the group we created; after reaping the + /// kernel may reuse the number, so this method never signals the cached + /// group again. Absence is confirmed only by `ESRCH` on a non-delivering + /// signal-0 query taken after the affirmative exact reap. A lagging member, + /// an unconfirmed query or a failed reap keeps cleanup unconfirmed, so the + /// supervisor retains its capacity and retries instead of claiming success. + async fn terminate(&mut self, deadline: Instant) -> AcpCleanupReport { + if !self.reaped { + // Give a harness that closed stdio a short window to exit on its + // own. The leader stays unreaped throughout. + let natural_deadline = (Instant::now() + Duration::from_millis(300)).min(deadline); + loop { + match observe_leader(self.pid) { + LeaderObservation::Exited => break, + LeaderObservation::Running => { + if Instant::now() >= natural_deadline { + break; + } + sleep(Duration::from_millis(10)).await; + } + LeaderObservation::Gone | LeaderObservation::Unknown => { + return AcpCleanupReport { + direct_child_reaped: false, + exit_status: self.exit_status, + group_signal_sent: self.group_signal_sent, + forced: self.forced, + group_clear: false, + cleanup_confirmed: false, + }; + } + } + } + + // Escalate only while the exact child is still pinned. TERM gets a + // full grace: while the leader is a waitable zombie the kernel + // retains the group, so signal 0 cannot distinguish a lingering + // member from the zombie itself. Waiting the grace is therefore the + // only way not to force-kill a member that is already exiting. + if matches!( + observe_leader(self.pid), + LeaderObservation::Running | LeaderObservation::Exited + ) { + self.group_signal_sent |= signal_group(self.pid, libc::SIGTERM); + let term_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline); + loop { + match observe_leader(self.pid) { + LeaderObservation::Gone | LeaderObservation::Unknown => break, + LeaderObservation::Running | LeaderObservation::Exited => { + if Instant::now() >= term_deadline { + break; + } + sleep(Duration::from_millis(10)).await; + } + } + } + } + + // A member that ignored TERM can only be reached while the leader + // is still unreaped. After the reap the numeric group is never + // signalled again; a lagging member therefore keeps the supervisor + // occupied instead of being mistaken for absent. + if matches!( + observe_leader(self.pid), + LeaderObservation::Running | LeaderObservation::Exited + ) { + self.forced = true; + self.group_signal_sent |= signal_group(self.pid, libc::SIGKILL); + } + + let reap_deadline = deadline; + loop { + match self.child.try_wait() { + Ok(Some(status)) => { + self.reaped = true; + self.exit_status = Some(status); + break; + } + Ok(None) => { + if Instant::now() >= reap_deadline { + break; + } + sleep(Duration::from_millis(5)).await; + } + Err(_) => break, + } + } + } + + // Only an affirmative exact reap can anchor the negative proof: while a + // zombie existed the kernel retained the group, so ESRCH after the reap + // means the original group really is empty. + let group_clear = self.reaped && group_presence(self.pid) == GroupPresence::Absent; + AcpCleanupReport { + direct_child_reaped: self.reaped, + exit_status: self.exit_status, + group_signal_sent: self.group_signal_sent, + forced: self.forced, + group_clear, + cleanup_confirmed: self.reaped && group_clear, + } + } +} + +impl Drop for OwnedChild { + fn drop(&mut self) { + if self.reaped { + return; + } + // Cancellation cannot await. The leader is still unreaped here, so the + // cached pid still names the group this client created; this is the + // last safe point to signal it. After a reap, Drop never signals. + if matches!( + observe_leader(self.pid), + LeaderObservation::Running | LeaderObservation::Exited + ) { + signal_group(self.pid, libc::SIGKILL); + } + let _ = self.child.start_kill(); + } +} + +#[cfg(unix)] +fn signal_group(pid: u32, signal: libc::c_int) -> bool { + let Ok(raw) = libc::pid_t::try_from(pid) else { + return false; + }; + // SAFETY: caller only invokes this while the leader is still our unreaped + // child, so the negative pid still names the group created for it. Signal 0 + // is used separately after reaping and never delivers anything. + unsafe { libc::kill(-raw, signal) == 0 } +} + +#[cfg(not(unix))] +fn signal_group(_pid: u32, _signal: libc::c_int) -> bool { + false +} + +/// Kernel-backed group-presence proof and prompt-arbitration unit tests. +/// +/// These are pure state/byte checks plus one benign owned `/bin/sh` fixture that +/// records the kernel contract the cleanup proof depends on. No gateway service, +/// network or real account is involved. +#[cfg(all(test, unix))] +mod cleanup_proof_tests { + use super::{GroupPresence, classify_group_query, classify_wait_probe}; + use std::io; + use std::time::{Duration, Instant}; + + #[test] + fn group_query_is_absent_only_on_esrch() { + assert_eq!(classify_group_query(0, None), GroupPresence::Present); + assert_eq!( + classify_group_query(-1, Some(libc::ESRCH)), + GroupPresence::Absent + ); + assert_eq!( + classify_group_query(-1, Some(libc::EPERM)), + GroupPresence::Unconfirmed + ); + assert_eq!( + classify_group_query(-1, Some(libc::EINVAL)), + GroupPresence::Unconfirmed + ); + assert_eq!(classify_group_query(-1, None), GroupPresence::Unconfirmed); + } + + #[test] + fn wait_probe_requires_echild() { + assert!(classify_wait_probe(-1, Some(libc::ECHILD))); + assert!(!classify_wait_probe(-1, Some(libc::ENOSYS))); + assert!(!classify_wait_probe(-1, Some(libc::EPERM))); + assert!(!classify_wait_probe(-1, None)); + assert!(!classify_wait_probe(0, None)); + } + + /// The cleanup proof relies on this kernel contract: an owned single-member + /// group remains while its exited leader is still waitable with WNOWAIT, and + /// only the exact reap frees the group number, after which signal 0 reports + /// ESRCH. This records the operating assumption on the host running the + /// suite; it does not by itself qualify production cleanup. + #[test] + fn kernel_retains_owned_group_until_exact_reap() { + use std::os::unix::process::CommandExt; + use std::process::Command; + + let mut child = Command::new("/bin/sh") + .arg("-c") + .arg("exit 0") + .process_group(0) + .spawn() + .expect("spawn benign owned fixture"); + let pid = child.id(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + let result = unsafe { + libc::waitid( + libc::P_PID, + pid as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + assert_eq!(result, 0, "waitid(WNOWAIT) succeeds for our child"); + // SAFETY: the kernel filled `info` for this exited child. + if unsafe { info.si_pid() } != 0 { + break; + } + assert!(Instant::now() < deadline, "benign fixture did not exit"); + std::thread::sleep(Duration::from_millis(10)); + } + + // Presence here only means the kernel still retains the owned group + // because its zombie leader is waitable; it is not evidence of a live + // member. + let present = unsafe { libc::kill(-(pid as libc::pid_t), 0) }; + assert_eq!( + present, 0, + "the kernel retains the owned group while the leader is waitable" + ); + + let status = child.wait().expect("exact direct reap"); + assert!(status.success()); + + let absent = unsafe { libc::kill(-(pid as libc::pid_t), 0) }; + assert_eq!(absent, -1); + assert_eq!( + io::Error::last_os_error().raw_os_error(), + Some(libc::ESRCH), + "after the exact reap the original group is gone" + ); + } +} + +#[cfg(test)] +mod prompt_arbitration_tests { + use super::test_writer::{FAIL, GateState, GateWriter, PENDING, WRITE}; + use super::{ + CLEANUP_BUDGET, CancelAction, PROTOCOL_DRAIN_BUDGET, PromptWire, Shared, write_prompt_frame, + }; + use agent_client_protocol::RawJsonRpcId; + use std::future::Future; + use std::task::Context; + use std::time::Duration; + + const PROMPT_LINE: &str = concat!( + "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"session/prompt\",", + "\"params\":{\"sessionId\":\"fixture-session\",\"prompt\":[]}}" + ); + + fn prompt_id() -> RawJsonRpcId { + RawJsonRpcId::Number(7) + } + + fn noop_context() -> Context<'static> { + Context::from_waker(futures_util::task::noop_waker_ref()) + } + + #[test] + fn stop_before_first_byte_discards_without_any_cancel() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + assert!( + !shared.take_expected(&id), + "an Armed prompt has no reply yet" + ); + assert_eq!( + shared.request_prompt_cancel(&id), + CancelAction::Deferred, + "the actor records the stop before the writer runs" + ); + } + + #[tokio::test] + async fn complete_frame_yields_exactly_one_cancel() { + let (_shutdown, shutdown_rx) = tokio::sync::watch::channel(false); + let shared = Shared::new( + shutdown_rx, + tokio::time::Instant::now() + Duration::from_secs(30), + ); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(WRITE, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let (result, wire) = write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared).await; + assert!(result.is_ok()); + assert_eq!(wire, PromptWire::Written); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Written)); + + // Trip the recorded stop after the complete frame but before the + // writer's completion transition: the frame then owes one cancel. + _shutdown.send(true).expect("trip recorded stop"); + assert!( + shared.complete_prompt_write(&id), + "a complete frame with a pending stop owes one cancel" + ); + assert_eq!( + shared.request_prompt_cancel(&id), + CancelAction::Deferred, + "the writer owns the cancel until its line is written" + ); + assert_eq!( + shared.begin_cancel_write(&id).as_deref(), + Some("fixture-session") + ); + assert_eq!( + shared.begin_cancel_write(&id), + None, + "the intentional cancel is written at most once" + ); + shared.finish_cancel_write(&id); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + } + + #[tokio::test] + async fn complete_frame_then_cancel_claims_one_send_now() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(WRITE, usize::MAX); + let mut writer = GateWriter::new(state); + let (result, wire) = write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared).await; + assert!(result.is_ok()); + assert_eq!(wire, PromptWire::Written); + assert!(!shared.complete_prompt_write(&id)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::SendNow); + assert_eq!( + shared.request_prompt_cancel(&id), + CancelAction::Deferred, + "once claimed, the pending line is the writer's to finish" + ); + assert!(shared.begin_cancel_write(&id).is_some()); + assert_eq!(shared.begin_cancel_write(&id), None); + shared.finish_cancel_write(&id); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + } + + #[tokio::test] + async fn matching_response_wins_over_later_cancel() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(WRITE, usize::MAX); + let mut writer = GateWriter::new(state); + let (result, wire) = write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared).await; + assert!(result.is_ok()); + assert_eq!(wire, PromptWire::Written); + assert!( + shared.take_expected(&id), + "the ingress claims the response only after a complete frame" + ); + assert!(shared.is_reserved_prompt_id(&id)); + assert_eq!( + shared.request_prompt_cancel(&id), + CancelAction::None, + "a claimed response forbids a late session/cancel" + ); + assert_eq!(shared.begin_cancel_write(&id), None); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Written)); + } + + #[test] + fn sdk_failure_before_the_writer_discards_the_armed_prompt() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + shared.abandon_unwritten_prompt(&id); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + } + + /// Boundary 1: a park on the first poll confirms no byte, so a stop that + /// lands while the pipe is not writable must leave the frame revocable and + /// produce zero bytes and zero cancels on the next poll. + #[test] + fn parked_before_first_byte_rediscards_stop_with_zero_writes_and_no_cancel() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(PENDING, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let mut pump = Box::pin(write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared)); + let mut cx = noop_context(); + + // First poll parks on the pipe without accepting a byte. + assert!(pump.as_mut().poll(&mut cx).is_pending()); + assert_eq!(state.calls(), 1, "one non-blocking probe, no delivery"); + assert!(state.bytes().is_empty(), "a Pending write confirms no byte"); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Pending)); + + // Stop recorded while parked, then the pipe becomes writable: the + // re-poll must re-arbitrate before the first byte and write nothing. + state.set_mode(WRITE); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::Deferred); + let outcome = pump.as_mut().poll(&mut cx); + assert!(outcome.is_ready(), "the parked writer is woken and settles"); + drop(pump); + + assert!( + state.bytes().is_empty(), + "zero bytes: the stop won before the first positive return" + ); + assert_eq!( + state.calls(), + 1, + "the stop poll re-arbitrates instead of writing again" + ); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + assert_eq!(shared.begin_cancel_write(&id), None); + assert!(!shared.take_expected(&id)); + } + + /// Boundary 1 with a real positive return: a stop after a partial frame may + /// only mark the prompt possibly executed. It must not append the rest of + /// the frame or emit a cancel notification. + #[test] + fn partial_frame_stop_marks_possible_execution_and_never_appends() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(WRITE, 10); + let mut writer = GateWriter::new(state.clone()); + let mut pump = Box::pin(write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared)); + let mut cx = noop_context(); + + assert!(pump.as_mut().poll(&mut cx).is_pending()); + assert_eq!(state.calls(), 1); + let prefix = state.bytes(); + assert_eq!( + prefix.len(), + 10, + "only the accepted prefix reaches the wire" + ); + assert_eq!(prefix.as_slice(), &PROMPT_LINE.as_bytes()[..10]); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Pending)); + + assert_eq!( + shared.request_prompt_cancel(&id), + CancelAction::Deferred, + "a positive prefix is not yet a complete frame" + ); + assert!( + pump.as_mut().poll(&mut cx).is_ready(), + "the stop settles the parked writer" + ); + drop(pump); + + assert_eq!( + state.bytes(), + prefix, + "no byte is appended to the half frame" + ); + assert_eq!(state.calls(), 1, "no further write is attempted"); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Partial)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + assert_eq!(shared.begin_cancel_write(&id), None); + assert!( + !shared.take_expected(&id), + "a partial frame can never claim the response" + ); + } + + /// Boundary 3: the write-side Pending path with a deadline-only stop. The + /// re-poll discards without bytes, and the cleanup window is anchored at + /// the first stop so the cancel drain and TERM keep separate slices. + #[test] + fn deadline_only_park_discards_and_keeps_one_cleanup_deadline() { + let (_shutdown, shutdown_rx) = tokio::sync::watch::channel(false); + let shared = Shared::new( + shutdown_rx, + tokio::time::Instant::now() + Duration::from_millis(40), + ); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(PENDING, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let mut pump = Box::pin(write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared)); + let mut cx = noop_context(); + assert!(pump.as_mut().poll(&mut cx).is_pending()); + assert_eq!(state.calls(), 1); + + // The absolute run deadline trips; the actor anchors cleanup there. + std::thread::sleep(Duration::from_millis(60)); + let started = shared.mark_cleanup_start(); + assert_eq!( + shared.mark_cleanup_start(), + started, + "a later stop cannot extend the cleanup window" + ); + assert_eq!( + shared.cancel_drain_deadline(), + started + PROTOCOL_DRAIN_BUDGET + ); + assert_eq!(shared.cleanup_deadline(), started + CLEANUP_BUDGET); + assert!( + PROTOCOL_DRAIN_BUDGET <= Duration::from_millis(500), + "cancel IO stays inside the existing drain slice" + ); + + assert!( + pump.as_mut().poll(&mut cx).is_ready(), + "the deadline wakes and settles the parked writer" + ); + drop(pump); + assert!( + state.bytes().is_empty(), + "a deadline-only stop sends nothing" + ); + assert_eq!(state.calls(), 1); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + assert_eq!(shared.begin_cancel_write(&id), None); + } + + /// Boundary 1: a zero-byte return never counts as a delivery. + #[tokio::test] + async fn zero_byte_write_sends_nothing() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + let state = GateState::new(FAIL, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let (result, wire) = write_prompt_frame(&mut writer, PROMPT_LINE, &id, &shared).await; + assert!(result.is_err()); + assert_eq!(wire, PromptWire::Failed); + assert!(state.bytes().is_empty()); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Failed)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + assert_eq!(shared.begin_cancel_write(&id), None); + } +} + +/// Controllable non-blocking sink used by the writer tests. +/// +/// `PENDING` mimics a full pipe and confirms no byte; `WRITE` accepts up to a +/// byte limit in order and then parks; `FAIL` returns a broken pipe. Call +/// counters and the accepted byte prefix are shared so a test can inspect them +/// while the future still borrows the writer. +#[cfg(test)] +mod test_writer { + use std::io; + use std::pin::Pin; + use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; + use std::task::{Context, Poll}; + + pub const PENDING: u8 = 0; + pub const WRITE: u8 = 1; + pub const FAIL: u8 = 2; + + pub struct GateState { + mode: AtomicU8, + allow: AtomicUsize, + written: Mutex>, + calls: AtomicUsize, + } + + impl GateState { + pub fn new(mode: u8, allow: usize) -> Arc { + Arc::new(Self { + mode: AtomicU8::new(mode), + allow: AtomicUsize::new(allow), + written: Mutex::new(Vec::new()), + calls: AtomicUsize::new(0), + }) + } + + pub fn set_mode(&self, mode: u8) { + self.mode.store(mode, Ordering::Release); + } + + pub fn calls(&self) -> usize { + self.calls.load(Ordering::Acquire) + } + + pub fn bytes(&self) -> Vec { + self.written.lock().unwrap().clone() + } + } + + pub struct GateWriter { + state: Arc, + } + + impl GateWriter { + pub fn new(state: Arc) -> Self { + Self { state } + } + } + + impl tokio::io::AsyncWrite for GateWriter { + fn poll_write( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + self.state.calls.fetch_add(1, Ordering::AcqRel); + match self.state.mode.load(Ordering::Acquire) { + PENDING => Poll::Pending, + FAIL => Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe))), + _ => { + let mut written = self.state.written.lock().unwrap(); + let remaining = self + .state + .allow + .load(Ordering::Acquire) + .saturating_sub(written.len()); + if remaining == 0 { + return Poll::Pending; + } + let take = remaining.min(buf.len()); + written.extend_from_slice(&buf[..take]); + Poll::Ready(Ok(take)) + } + } + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + } +} + +#[cfg(test)] +mod writer_outcome_tests { + use super::test_writer::{FAIL, GateState, GateWriter, WRITE}; + use super::{ + CancelAction, OutgoingFrame, PromptWire, Shared, session_cancel_frame, write_prompt_frame, + }; + use agent_client_protocol::RawJsonRpcId; + use std::future::Future; + use std::task::Context; + + const LINE: &str = r#"{"jsonrpc":"2.0","id":7,"method":"session/prompt","params":{}}"#; + + fn armed_shared() -> (Shared, RawJsonRpcId) { + let shared = Shared::default(); + let id = RawJsonRpcId::Number(7); + shared.begin_prompt("fixture-session", id.clone()); + (shared, id) + } + + #[tokio::test] + async fn complete_line_is_reported_written() { + let (shared, id) = armed_shared(); + let state = GateState::new(WRITE, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let (result, wire) = write_prompt_frame(&mut writer, LINE, &id, &shared).await; + assert!(result.is_ok()); + assert_eq!(wire, PromptWire::Written); + let bytes = state.bytes(); + assert_eq!(bytes.as_slice(), format!("{LINE}\n").as_bytes()); + let text = String::from_utf8(bytes).expect("utf8 frame"); + assert_eq!( + text.matches("\"method\":\"session/prompt\"").count(), + 1, + "exactly one request is on the wire" + ); + assert_eq!(text.matches('\n').count(), 1, "one delimiter, at the end"); + assert!(text.ends_with('\n')); + } + + #[tokio::test] + async fn failure_before_any_byte_is_not_a_delivery() { + let (shared, id) = armed_shared(); + let state = GateState::new(FAIL, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let (result, wire) = write_prompt_frame(&mut writer, LINE, &id, &shared).await; + assert!(result.is_err()); + assert_eq!(wire, PromptWire::Failed); + assert!(state.bytes().is_empty()); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Failed)); + } + + #[tokio::test] + async fn truncated_line_is_reported_partial() { + let (shared, id) = armed_shared(); + let state = GateState::new(WRITE, 5); + let mut writer = GateWriter::new(state.clone()); + let mut pump = Box::pin(write_prompt_frame(&mut writer, LINE, &id, &shared)); + let mut cx = Context::from_waker(futures_util::task::noop_waker_ref()); + assert!(pump.as_mut().poll(&mut cx).is_pending()); + assert_eq!(state.bytes().as_slice(), &LINE.as_bytes()[..5]); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::Deferred); + assert!(pump.as_mut().poll(&mut cx).is_ready()); + drop(pump); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Partial)); + assert_eq!(state.bytes().as_slice(), &LINE.as_bytes()[..5]); + } + + #[test] + fn session_cancel_frame_is_the_intended_notification() { + let frame = session_cancel_frame("fixture-session").expect("cancel frame"); + let value: serde_json::Value = serde_json::from_str(&frame).expect("json"); + assert_eq!(value["jsonrpc"], "2.0"); + assert_eq!(value["method"], "session/cancel"); + assert_eq!(value["params"]["sessionId"], "fixture-session"); + } + + #[test] + fn sdk_cancel_request_is_recognized_for_the_exact_prompt_id() { + let line = serde_json::to_string( + &agent_client_protocol::RawJsonRpcMessage::notification( + "$/cancel_request".to_owned(), + serde_json::json!({ "requestId": 7 }), + ) + .expect("notification"), + ) + .expect("json"); + match OutgoingFrame::parse(&line) { + OutgoingFrame::SdkCancelRequest(id) => { + assert_eq!(id, RawJsonRpcId::Number(7)); + } + _ => panic!("the SDK cancellation must be recognized at the wire"), + } + } + + // Keep the deterministic block form referenced so the helper is exercised + // in a single-poll writer too. + #[tokio::test] + async fn single_poll_complete_frame_is_written() { + let (shared, id) = armed_shared(); + let state = GateState::new(WRITE, usize::MAX); + let mut writer = GateWriter::new(state.clone()); + let (result, wire) = write_prompt_frame(&mut writer, LINE, &id, &shared).await; + assert!(result.is_ok()); + assert_eq!(wire, PromptWire::Written); + } +} + +/// Reproduces the reviewed ordering over the real ACP SDK: the outgoing sink +/// parks the prompt frame before its first byte, the caller's `prompt` future +/// is dropped, and the next poll of the connection reaches the transport +/// writer before the actor. The transport becomes writable in that same step, +/// so a writer that only learns about withdrawal from a later actor poll would +/// publish the frame. +#[cfg(test)] +mod sdk_caller_withdrawal_tests { + use super::{Client, DelegatedAcpClient, Lines, PromptWire, SdkError, Shared, Wire, run_actor}; + use futures_util::{Stream, sink, stream}; + use std::collections::VecDeque; + use std::future::Future; + use std::io; + use std::pin::Pin; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; + use std::task::{Context, Poll, Waker}; + use std::time::Duration; + use tokio::sync::{mpsc, watch}; + use tokio::time::Instant; + + #[derive(Default)] + struct Loopback { + inbound: Mutex>, + inbound_waker: Mutex>, + wire_bytes: Mutex>, + prompt_polls: AtomicUsize, + prompt_writable: AtomicBool, + } + + impl Loopback { + fn record(&self, bytes: &[u8]) { + self.wire_bytes.lock().unwrap().extend_from_slice(bytes); + } + + fn respond(&self, method: &str, request: &serde_json::Value) { + let id = request + .get("id") + .cloned() + .unwrap_or(serde_json::Value::Null); + let response = match method { + "initialize" => serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { + "protocolVersion": 1, + "agentCapabilities": { + "loadSession": true, + "sessionCapabilities": { "resume": {} }, + "promptCapabilities": { + "image": false, + "audio": false, + "embeddedContext": false + } + }, + "agentInfo": { "name": "loopback-agent", "version": "0.1.0" } + } + }), + "session/new" => serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": "loopback-session" } + }), + _ => return, + }; + self.inbound.lock().unwrap().push_back(response.to_string()); + if let Some(waker) = self.inbound_waker.lock().unwrap().take() { + waker.wake(); + } + } + + fn prompt_polls(&self) -> usize { + self.prompt_polls.load(Ordering::Acquire) + } + + fn release_prompt(&self) { + self.prompt_writable.store(true, Ordering::Release); + } + + fn wire_text(&self) -> String { + String::from_utf8_lossy(&self.wire_bytes.lock().unwrap()).into_owned() + } + } + + struct LoopbackSink { + peer: Arc, + } + + impl tokio::io::AsyncWrite for LoopbackSink { + fn poll_write( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let request = if buf.first() == Some(&b'{') { + serde_json::from_slice::(buf).ok() + } else { + None + }; + if let Some(request) = request { + match request.get("method").and_then(serde_json::Value::as_str) { + Some("session/prompt") => { + self.peer.prompt_polls.fetch_add(1, Ordering::AcqRel); + if !self.peer.prompt_writable.load(Ordering::Acquire) { + // The pipe is not writable: no byte is accepted. + return Poll::Pending; + } + } + Some(method) => { + self.peer.record(buf); + self.peer.respond(method, &request); + return Poll::Ready(Ok(buf.len())); + } + None => {} + } + } + self.peer.record(buf); + Poll::Ready(Ok(buf.len())) + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + } + + fn inbound_stream(peer: Arc) -> impl Stream> { + stream::poll_fn(move |cx| { + let mut queue = peer.inbound.lock().unwrap(); + if let Some(line) = queue.pop_front() { + Poll::Ready(Some(Ok(line))) + } else { + *peer.inbound_waker.lock().unwrap() = Some(cx.waker().clone()); + Poll::Pending + } + }) + } + + fn drive( + request: &mut Pin>>, + connection: &mut Pin>>>, + ) -> T { + let waker = futures_util::task::noop_waker(); + let mut cx = Context::from_waker(&waker); + for _ in 0..100_000 { + if let Poll::Ready(value) = request.as_mut().poll(&mut cx) { + return value; + } + if let Poll::Ready(result) = connection.as_mut().poll(&mut cx) { + panic!("connection ended while a request was pending: {result:?}"); + } + } + panic!("request did not settle"); + } + + #[tokio::test] + async fn caller_drop_before_first_byte_wins_over_the_sdk_transport_poll() { + let peer = Arc::new(Loopback::default()); + let deadline = Instant::now() + Duration::from_secs(30); + let (command_tx, command_rx) = mpsc::channel(1); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let shared = Arc::new(Shared::new(shutdown_tx.subscribe(), deadline)); + let wire = Arc::new(Wire::new( + Box::new(LoopbackSink { peer: peer.clone() }), + shared.clone(), + )); + let outgoing = sink::unfold(wire.clone(), |wire: Arc, line: String| async move { + wire.write_line(&line).await?; + Ok::<_, io::Error>(wire) + }); + let transport = Lines::new(outgoing, inbound_stream(peer.clone())); + let cwd = std::env::temp_dir(); + let mut connection = Box::pin(Client.v1().name("withdrawal-loopback").connect_with( + transport, + { + let shared = shared.clone(); + let wire = wire.clone(); + async move |connection| { + run_actor( + connection, + command_rx, + shared, + wire, + cwd, + deadline, + shutdown_rx, + ) + .await + } + }, + )); + let (proof_tx, proof_rx) = watch::channel(None); + let mut client = DelegatedAcpClient { + commands: Some(command_tx), + shutdown: shutdown_tx, + supervisor: None, + proof: proof_rx, + pid: 0, + deadline, + active: Arc::new(AtomicUsize::new(0)), + shared: shared.clone(), + initialized: false, + session_id: None, + prompted: false, + closed: false, + }; + + let capabilities = + drive(&mut Box::pin(client.initialize()), &mut connection).expect("initialize"); + assert!(capabilities.resume); + let session = + drive(&mut Box::pin(client.new_session()), &mut connection).expect("session/new"); + assert_eq!(session, "loopback-session"); + + let mut prompt = Box::pin(client.prompt(&session, "withdraw this turn")); + let waker = futures_util::task::noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!(prompt.as_mut().poll(&mut cx).is_pending()); + for _ in 0..10_000 { + if let Poll::Ready(result) = connection.as_mut().poll(&mut cx) { + panic!("connection ended before the prompt frame parked: {result:?}"); + } + if peer.prompt_polls() > 0 { + break; + } + } + assert_eq!( + peer.prompt_polls(), + 1, + "the first byte was probed exactly once and parked" + ); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Pending)); + assert!(!shared.withdrawn()); + + // The caller drops its wait. The guard records withdrawal before the + // actor is polled; the transport becomes writable in the next poll. + drop(prompt); + peer.release_prompt(); + + let mut ended = false; + for _ in 0..10_000 { + if let Poll::Ready(result) = connection.as_mut().poll(&mut cx) { + assert!(result.is_ok(), "clean connection end: {result:?}"); + ended = true; + break; + } + } + assert!(ended, "the connection settled after the withdrawal"); + + let text = peer.wire_text(); + assert_eq!( + peer.prompt_polls(), + 1, + "the writer re-arbitrated before any second poll_write: {text:?}" + ); + assert_eq!( + shared.prompt_wire(), + Some(PromptWire::Discarded), + "a parked frame before its first byte is discarded" + ); + assert!( + shared.withdrawn(), + "the caller's drop recorded the withdrawal" + ); + assert!( + !text.contains("session/prompt"), + "zero prompt frames reached the wire: {text:?}" + ); + assert!( + !text.contains("session/cancel"), + "zero intentional cancels reached the wire: {text:?}" + ); + assert!( + !text.contains("$/cancel_request"), + "zero SDK cancellations reached the wire: {text:?}" + ); + drop(proof_tx); + } +} + +/// The supervisor must start cleanup from the original run deadline even when +/// the SDK connection cannot finish its physical writer drain. No `close` and +/// no shutdown request is used: only the deadline expires. +#[cfg(test)] +mod supervisor_deadline_tests { + use super::{ + AcpDelegationError, AcpDelegationLaunch, CLEANUP_BUDGET, CLOSE_SCHEDULING_SLACK, + DelegatedAcpClient, + }; + use std::ffi::OsString; + use std::io; + use std::pin::Pin; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::task::{Context, Poll}; + use std::time::Duration; + use tokio::time::{Instant, timeout}; + + #[derive(Default)] + struct ParkState { + polls: AtomicUsize, + } + + struct ParkedSink { + state: Arc, + } + + impl tokio::io::AsyncWrite for ParkedSink { + fn poll_write( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + _buf: &[u8], + ) -> Poll> { + self.state.polls.fetch_add(1, Ordering::AcqRel); + // The physical drain never completes. + Poll::Pending + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + } + + #[cfg(unix)] + fn pid_alive(pid: u32) -> bool { + let Ok(raw) = libc::pid_t::try_from(pid) else { + return false; + }; + // SAFETY: signal 0 only probes existence. + unsafe { libc::kill(raw, 0) == 0 } + } + + #[tokio::test] + async fn run_deadline_starts_cleanup_while_the_sdk_drain_is_stuck() { + let state = Arc::new(ParkState::default()); + let deadline = Instant::now() + Duration::from_millis(400); + let launch = AcpDelegationLaunch::new( + "/bin/sh", + vec![OsString::from("-c"), OsString::from("exec sleep 60")], + std::env::temp_dir(), + ) + .expect("valid inert launch"); + let mut client = DelegatedAcpClient::connect_with_stdin(launch, deadline, { + let state = state.clone(); + move |_stdin| Box::new(ParkedSink { state }) + }) + .await + .expect("connect"); + let pid = client.pid(); + let observer = client.cleanup_observer(); + + let result = timeout(Duration::from_secs(5), client.initialize()) + .await + .expect("initialize is bounded by the run deadline"); + assert!( + matches!( + result, + Err(AcpDelegationError::DeadlineExceeded) | Err(AcpDelegationError::Closed) + ), + "only the run deadline stops initialize: {result:?}" + ); + assert!( + state.polls.load(Ordering::Acquire) >= 1, + "the request reached the inert sink and parked there" + ); + + // Deliberately no close and no request_shutdown. + let report = timeout( + CLEANUP_BUDGET + CLOSE_SCHEDULING_SLACK + Duration::from_secs(2), + observer.clone().wait_for_cleanup(), + ) + .await + .expect("supervisor must not wait for the stuck connection drain") + .expect("supervisor published final cleanup evidence"); + assert!(report.cleanup_confirmed, "{report:?}"); + assert_eq!(observer.active(), 0, "the process slot follows the proof"); + assert!(!pid_alive(pid), "the direct child was reaped"); + } +} + +/// End-to-end supervisor path for the actor-exit boundary. +/// +/// The ACP SDK separates the foreground closure from the physical transport: +/// after the closure returns it keeps draining until the owned transport +/// finishes. `connect_with`'s future therefore is not a signal that the actor +/// ended. This test performs a normal handshake over the real SDK with a real +/// child harness, withdraws the prompt before it is armed, and never calls +/// `close` or requests shutdown. It requires confirmed cleanup, an exact reap +/// and an empty post-handshake wire well before the far run deadline; the +/// anchor itself is isolated from the connection in the companion test. +#[cfg(test)] +mod sdk_actor_exit_cleanup_tests { + use super::{ + AcpDelegationLaunch, CLEANUP_BUDGET, CLOSE_SCHEDULING_SLACK, Client, DelegatedAcpClient, + Lines, SdkError, Shared, Wire, run_actor, + }; + use futures_util::Sink; + use std::ffi::OsString; + use std::fs; + use std::future::Future; + use std::io; + use std::path::PathBuf; + use std::pin::Pin; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::task::{Context, Poll}; + use std::time::Duration; + use tokio::io::AsyncWrite; + use tokio::process::ChildStdout; + use tokio::time::{Instant, timeout}; + + static NEXT_TEST: AtomicUsize = AtomicUsize::new(0); + + /// Compile the deterministic harness the integration tests use, so this + /// regression also performs a real stdio handshake with a real child. + mod fixture_build { + include!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/acp/delegation_build.rs" + )); + } + + fn assigned_tmp_root() -> PathBuf { + std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .or_else(|| std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMPDIR")) + .or_else(|| std::env::var_os("TMPDIR")) + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir) + } + + struct TestRoot { + path: PathBuf, + } + + impl TestRoot { + fn new(label: &str) -> Self { + let sequence = NEXT_TEST.fetch_add(1, Ordering::Relaxed); + let path = assigned_tmp_root().join(format!( + "acp-actor-exit-{label}-{}-{sequence}", + std::process::id(), + )); + fs::create_dir_all(&path).expect("create isolated actor-exit test root"); + fs::create_dir_all(path.join("work")).expect("create harness cwd"); + Self { path } + } + } + + impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + /// Private write seam: forwards the handshake bytes to the child, then, + /// once the test arms it, records every post-handshake byte and parks + /// `flush`/`shutdown`. The parked physical finish keeps the SDK connection + /// future alive after the foreground closure returns, which is exactly the + /// condition the supervisor must not depend on. + struct GateStdin { + inner: tokio::process::ChildStdin, + armed: Arc, + post_handshake_bytes: Arc, + } + + impl AsyncWrite for GateStdin { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let poll = Pin::new(&mut self.inner).poll_write(cx, buf); + if let Poll::Ready(Ok(written)) = poll + && self.armed.load(Ordering::Acquire) + { + self.post_handshake_bytes + .fetch_add(written, Ordering::AcqRel); + } + poll + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.armed.load(Ordering::Acquire) { + return Poll::Pending; + } + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.armed.load(Ordering::Acquire) { + return Poll::Pending; + } + Pin::new(&mut self.inner).poll_shutdown(cx) + } + } + + #[cfg(unix)] + fn pid_alive(pid: u32) -> bool { + let Ok(raw) = libc::pid_t::try_from(pid) else { + return false; + }; + // SAFETY: signal 0 only probes existence. + unsafe { libc::kill(raw, 0) == 0 } + } + + #[tokio::test] + async fn actor_exit_starts_cleanup_without_close_or_shutdown() { + let root = TestRoot::new("withdraw-before-arm"); + let binary = root.path.join("delegation_agent"); + fixture_build::compile_delegation_agent(&binary); + let events = root.path.join("events.jsonl"); + let launch = AcpDelegationLaunch::new( + binary, + vec![ + OsString::from("--events"), + events.clone().into_os_string(), + OsString::from("--mode"), + OsString::from("normal"), + ], + root.path.join("work"), + ) + .expect("valid fixture launch"); + + // A far deadline isolates the actor's notification from the timer + // fallback: only the notification can end cleanup inside the bound. + let deadline = Instant::now() + Duration::from_secs(30); + let armed = Arc::new(AtomicBool::new(false)); + let post_handshake_bytes = Arc::new(AtomicUsize::new(0)); + let mut client = DelegatedAcpClient::connect_with_stdin(launch, deadline, { + let armed = armed.clone(); + let post_handshake_bytes = post_handshake_bytes.clone(); + move |stdin| { + Box::new(GateStdin { + inner: stdin, + armed, + post_handshake_bytes, + }) + } + }) + .await + .expect("connect"); + let pid = client.pid(); + let observer = client.cleanup_observer(); + + // Normal handshake: both requests are answered by the real fixture. + client.initialize().await.expect("initialize"); + let session = client.new_session().await.expect("session/new"); + + // Stop counting the handshake at this point: any later byte would be a + // prompt or cancel and a writer-initiated finish must not complete + // silently. The child keeps stdin and stdout open. + armed.store(true, Ordering::Release); + + // The prompt command is enqueued, then the caller drops the wait + // before the actor can arm the frame. The actor's reply channel is + // already closed when it takes the fast path. + let mut prompt = Box::pin(client.prompt(&session, "withdraw before arm")); + let waker = futures_util::task::noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!( + prompt.as_mut().poll(&mut cx).is_pending(), + "the prompt waits for a reply the actor can no longer deliver" + ); + drop(prompt); + + // Deliberately no `close`, no `request_shutdown` and no shutdown send. + let report = timeout( + CLEANUP_BUDGET + CLOSE_SCHEDULING_SLACK + Duration::from_secs(2), + observer.clone().wait_for_cleanup(), + ) + .await + .expect("cleanup completed well before the far run deadline") + .expect("supervisor published final cleanup evidence"); + + let started = client + .shared + .cleanup_start() + .expect("cleanup anchor was published"); + assert!( + deadline.saturating_duration_since(started) > Duration::from_secs(20), + "the anchor came from the actor exit, not the run deadline: {started:?}" + ); + assert!(report.cleanup_confirmed, "{report:?}"); + assert!(report.direct_child_reaped, "{report:?}"); + assert_eq!(observer.active(), 0, "the internal slot went back to zero"); + assert!(!pid_alive(pid), "the direct child was reaped"); + + // The withdrawal won before arming: no prompt and no cancel ever + // reached the wire, and the writer never armed the prompt record. + assert_eq!( + post_handshake_bytes.load(Ordering::Acquire), + 0, + "no byte was written after the handshake" + ); + assert_eq!( + client.prompt_wire_state(), + None, + "the prompt was never armed on the wire" + ); + let recorded = fs::read_to_string(&events).unwrap_or_default(); + assert_eq!(recorded.matches("\"initialize\"").count(), 1); + assert_eq!(recorded.matches("\"session/new\"").count(), 1); + assert!( + !recorded.contains("\"session/prompt\""), + "zero prompt frames reached the harness: {recorded}" + ); + assert!( + !recorded.contains("\"session/cancel\""), + "zero intentional cancels reached the harness: {recorded}" + ); + assert!( + !recorded.contains("\"$/cancel_request\""), + "zero SDK cancellations reached the harness: {recorded}" + ); + + // Keep the handle so no implicit Drop shutdown is sent. + std::mem::forget(client); + } + + /// A test-controlled hold at the transport boundary. The sink still writes + /// through the production [`Wire`], but its close parks once the test arms + /// it. The SDK's connection future therefore cannot resolve after the actor + /// returns, which is the window the supervisor must never depend on. + struct HeldCloseSink { + inner: Pin>, + hold: Arc, + } + + impl Sink for HeldCloseSink + where + S: Sink, + { + type Error = io::Error; + + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.inner.as_mut().poll_ready(cx) + } + + fn start_send(mut self: Pin<&mut Self>, item: String) -> io::Result<()> { + self.inner.as_mut().start_send(item) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.inner.as_mut().poll_flush(cx) + } + + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.hold.load(Ordering::Acquire) { + // The test drops the connection instead of waiting for a wake. + return Poll::Pending; + } + self.inner.as_mut().poll_close(cx) + } + } + + /// Read the fixture's real stdout as newline-delimited frames. This minimal + /// reader is the only piece not shared with production: the point of the + /// regression is the actor/supervisor boundary, so the test holds the + /// transport close directly instead of re-deriving the ingress classifier. + fn child_lines(stdout: ChildStdout) -> impl futures_util::Stream> { + let reader = futures_util::io::BufReader::new(super::ChildIo(stdout)); + futures_util::stream::unfold(reader, |mut reader| async move { + use futures_util::io::AsyncBufReadExt as _; + loop { + let mut line = String::new(); + match reader.read_line(&mut line).await { + Ok(0) => return None, + Ok(_) => { + let trimmed = line.trim_end_matches(['\r', '\n']); + if trimmed.is_empty() { + continue; + } + return Some((Ok(trimmed.to_owned()), reader)); + } + Err(error) => return Some((Err(error), reader)), + } + } + }) + } + + /// Poll two manually driven futures, letting the runtime's I/O reactor run + /// between polls. + async fn drive( + request: &mut Pin>>, + connection: &mut Pin>>>, + ) -> T { + let bound = Instant::now() + Duration::from_secs(10); + loop { + let waker = futures_util::task::noop_waker(); + let mut cx = Context::from_waker(&waker); + if let Poll::Ready(value) = request.as_mut().poll(&mut cx) { + return value; + } + if let Poll::Ready(result) = connection.as_mut().poll(&mut cx) { + panic!("connection ended while a request was pending: {result:?}"); + } + assert!(Instant::now() < bound, "request did not settle"); + tokio::time::sleep(Duration::from_millis(1)).await; + } + } + + /// The precise invariant: the actor's exit must publish the idempotent + /// cleanup anchor even while the SDK connection is still pending. Without + /// it the supervisor has no evidence of the actor's termination and can + /// only fall back to the run deadline. + #[tokio::test] + async fn actor_exit_anchor_is_published_before_the_sdk_connection_resolves() { + let root = TestRoot::new("anchor-before-connection"); + let binary = root.path.join("delegation_agent"); + fixture_build::compile_delegation_agent(&binary); + let events = root.path.join("events.jsonl"); + let mut child = tokio::process::Command::new(&binary) + .arg("--events") + .arg(&events) + .arg("--mode") + .arg("normal") + .current_dir(root.path.join("work")) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true) + .spawn() + .expect("spawn fixture"); + let stdin = child.stdin.take().expect("child stdin"); + let stdout = child.stdout.take().expect("child stdout"); + + let deadline = Instant::now() + Duration::from_secs(30); + let (command_tx, command_rx) = tokio::sync::mpsc::channel(1); + let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false); + let shared = Arc::new(Shared::new(shutdown_tx.subscribe(), deadline)); + let wire = Arc::new(Wire::new(Box::new(stdin), shared.clone())); + let hold = Arc::new(AtomicBool::new(false)); + let outgoing = + futures_util::sink::unfold(wire.clone(), |wire: Arc, line: String| async move { + wire.write_line(&line).await?; + Ok::<_, io::Error>(wire) + }); + let transport = Lines::new( + HeldCloseSink { + inner: Box::pin(outgoing), + hold: hold.clone(), + }, + child_lines(stdout), + ); + let cwd = root.path.join("work"); + let mut connection = Box::pin(Client.v1().name("actor-exit-anchor").connect_with( + transport, + { + let shared = shared.clone(); + let wire = wire.clone(); + async move |connection| { + run_actor( + connection, + command_rx, + shared, + wire, + cwd, + deadline, + shutdown_rx, + ) + .await + } + }, + )); + let (proof_tx, proof_rx) = tokio::sync::watch::channel(None); + let mut client = DelegatedAcpClient { + commands: Some(command_tx), + shutdown: shutdown_tx, + supervisor: None, + proof: proof_rx, + pid: child.id().unwrap_or(0), + deadline, + active: Arc::new(AtomicUsize::new(0)), + shared: shared.clone(), + initialized: false, + session_id: None, + prompted: false, + closed: false, + }; + drop(proof_tx); + drop(wire); + + // Normal handshake against the real child. + let capabilities = drive(&mut Box::pin(client.initialize()), &mut connection) + .await + .expect("initialize"); + assert!(capabilities.resume, "fixture advertises resume"); + let session = drive(&mut Box::pin(client.new_session()), &mut connection) + .await + .expect("session/new"); + + // From here on the SDK transport cannot finish, so connection + // completion can never stand in for the actor's termination. + hold.store(true, Ordering::Release); + + let mut prompt = Box::pin(client.prompt(&session, "withdraw before arm")); + let waker = futures_util::task::noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!( + prompt.as_mut().poll(&mut cx).is_pending(), + "the prompt waits for a reply the actor can no longer deliver" + ); + drop(prompt); + + let bound = Instant::now() + Duration::from_secs(5); + let mut observed_pending = false; + while Instant::now() < bound { + let mut cx = Context::from_waker(&waker); + match connection.as_mut().poll(&mut cx) { + Poll::Ready(result) => { + panic!("the held transport close must keep the connection pending: {result:?}") + } + Poll::Pending => observed_pending = true, + } + if shared.cleanup_start().is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(2)).await; + } + assert!(observed_pending, "the connection was observed pending"); + assert!( + shared.cleanup_start().is_some(), + "the actor's exit must publish the cleanup anchor before the SDK connection resolves" + ); + assert_eq!( + client.prompt_wire_state(), + None, + "the withdrawn prompt was never armed on the wire" + ); + let recorded = fs::read_to_string(&events).unwrap_or_default(); + assert!( + !recorded.contains("\"session/prompt\"") && !recorded.contains("\"session/cancel\""), + "zero prompt or cancel frames reached the harness: {recorded}" + ); + + // Keep the raw harness alive until the assertions are done, then let + // the runtime close the pipes and reap the child. + std::mem::forget(client); + drop(connection); + let _ = timeout(Duration::from_secs(2), child.wait()).await; + } +} diff --git a/src/acp/mod.rs b/src/acp/mod.rs index 0fffe94c..f0f07420 100644 --- a/src/acp/mod.rs +++ b/src/acp/mod.rs @@ -5,9 +5,18 @@ //! ordinary ACP `initialize`; the SDK's internal `proxy/initialize` role is not //! exposed to clients. All framing, request IDs, response routing, and //! cancellation use the official `agent-client-protocol` v1 connections. +//! +//! The delegation client is separate from the proxy and is not wired into RSS +//! yet. It exposes explicit initialize/setup/prompt/close phases so a later +//! durable scope can persist the peer-assigned session ID before prompting. pub mod config; +pub mod delegated_client; pub mod proxy; pub use config::{AcpConfigError, AcpProxyConfig}; +pub use delegated_client::{ + AcpAgentCapabilities, AcpCleanupObserver, AcpCleanupReport, AcpDelegationError, + AcpDelegationLaunch, AcpPromptResult, AcpRestoreMethod, AcpStopReason, DelegatedAcpClient, +}; pub use proxy::{AcpProxyError, ProxyDisposition, run_proxy}; diff --git a/src/bin/rustscript-agent-gateway.rs b/src/bin/rustscript-agent-gateway.rs index f656b48b..ee3e1825 100644 --- a/src/bin/rustscript-agent-gateway.rs +++ b/src/bin/rustscript-agent-gateway.rs @@ -223,6 +223,28 @@ async fn main() -> Result<(), Box> { .map_err(|_| std::io::Error::other("agent provider profile could not be registered"))?; } drop(service); + // ACP delegation is opt-in through the existing `config.yaml`. A table that + // cannot be launched as an exact argv fails startup here, before the + // listener binds and before any entry point is registered. The launch + // definitions stay host-private; only the capability flag is observable. + if let Some(loaded) = loaded_config.as_ref() + && !loaded.acp_harnesses.is_empty() + { + let persistence = state.persistence().ok_or_else(|| { + std::io::Error::other("agent acp_harnesses requires the durable gateway store") + })?; + let policy = rustscript_agent::service::acp_session_pins::AcpDelegationPolicy::install( + loaded, + persistence, + state.service(), + ) + .map_err(std::io::Error::other)? + .map(std::sync::Arc::new); + state + .service() + .install_acp_delegation(policy) + .map_err(std::io::Error::other)?; + } let state = if explicit_home { state.with_workspace_home(home) } else { diff --git a/src/config_file.rs b/src/config_file.rs index 0ef901ea..2c5bc474 100644 --- a/src/config_file.rs +++ b/src/config_file.rs @@ -165,6 +165,50 @@ pub struct ConfigFile { pub approvals: ApprovalSettings, #[serde(default)] pub compaction: CompactionSettings, + /// Operator-owned local ACP harness launch table. + /// + /// This is host-private startup data: it is accepted from `config.yaml` and + /// retained on the native side so the gateway can launch a trusted harness, + /// but it is never serialized into the RSS-visible public config snapshot. + /// An absent or empty table leaves the delegation capability disabled. + #[serde(default, skip_serializing)] + pub acp_harnesses: Vec, +} + +/// Bounds of the operator-owned ACP harness launch table. +pub const MAX_ACP_HARNESSES: usize = 8; +pub const MAX_ACP_HARNESS_ID_BYTES: usize = 32; +pub const MAX_ACP_HARNESS_ARGUMENTS: usize = 32; +pub const MAX_ACP_HARNESS_ARGUMENT_BYTES: usize = 8 * 1024; + +/// One local stdio ACP harness launch definition. +/// +/// Only the logical ID and the exact argv are configurable. The definition is +/// executed directly (never through a shell) and no delegated task text is +/// ever spliced into it. +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct AcpHarnessSettings { + pub id: String, + pub command: PathBuf, + #[serde(default)] + pub args: Vec, +} + +impl AcpHarnessSettings { + /// Total bytes of the argument vector after the executable. + pub fn argument_bytes(&self) -> usize { + self.args.iter().map(String::len).sum() + } +} + +/// True when `id` is a valid bounded harness selector token. +pub fn valid_acp_harness_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= MAX_ACP_HARNESS_ID_BYTES + && id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') } /// Compatibility name for the persisted non-secret document. @@ -444,6 +488,89 @@ impl ConfigFile { Ok(()) } + /// Resolves one configured harness launch definition by logical ID. + pub fn acp_harness(&self, id: &str) -> Option<&AcpHarnessSettings> { + self.acp_harnesses.iter().find(|harness| harness.id == id) + } + + /// Validates the bounded, host-private ACP harness launch table. + /// + /// Every entry is refused before startup when it could not be launched as + /// an exact argv: unknown or duplicate IDs, relative executables, too many + /// arguments or an oversized argument vector. + fn validate_acp_harnesses(&self, source: &Path) -> Result<(), ConfigFileError> { + if self.acp_harnesses.len() > MAX_ACP_HARNESSES { + return Err(invalid_value( + source, + "acp_harnesses", + "must contain at most 8 harnesses", + )); + } + let mut seen = std::collections::BTreeSet::new(); + for (index, harness) in self.acp_harnesses.iter().enumerate() { + let path = format!("acp_harnesses[{index}]"); + if !valid_acp_harness_id(&harness.id) { + return Err(invalid_value( + source, + &format!("{path}.id"), + "must be a non-empty token of at most 32 ASCII alphanumeric, '-' or '_' bytes", + )); + } + if !seen.insert(harness.id.clone()) { + return Err(invalid_value( + source, + &format!("{path}.id"), + "duplicate harness id", + )); + } + let command = harness.command.to_str().ok_or_else(|| { + invalid_value( + source, + &format!("{path}.command"), + "must be a UTF-8 absolute path", + ) + })?; + if command.is_empty() || command.contains('\0') { + return Err(invalid_value( + source, + &format!("{path}.command"), + "must be a non-empty absolute path", + )); + } + if harness.command.is_relative() { + return Err(invalid_value( + source, + &format!("{path}.command"), + "must be an absolute path", + )); + } + if harness.args.len() > MAX_ACP_HARNESS_ARGUMENTS { + return Err(invalid_value( + source, + &format!("{path}.args"), + "must contain at most 32 arguments", + )); + } + for argument in &harness.args { + if argument.contains('\0') { + return Err(invalid_value( + source, + &format!("{path}.args"), + "arguments must not contain NUL bytes", + )); + } + } + if harness.argument_bytes() > MAX_ACP_HARNESS_ARGUMENT_BYTES { + return Err(invalid_value( + source, + &format!("{path}.args"), + "argument bytes must not exceed 8192", + )); + } + } + Ok(()) + } + fn from_yaml_bytes(path: &Path, bytes: &[u8]) -> Result { preflight_yaml(bytes).map_err(|error| ConfigFileError::from_yaml_preflight(path, error))?; let value: Value = parse_yaml_value(bytes).map_err(|_| ConfigFileError::MalformedYaml { @@ -620,6 +747,7 @@ impl ConfigFile { "must not exceed max_context_messages", )); } + self.validate_acp_harnesses(source)?; Ok(()) } } @@ -990,6 +1118,7 @@ fn validate_config_shape(source: &Path, value: &Value) -> Result<(), ConfigFileE "workspaces", "approvals", "compaction", + "acp_harnesses", ], )?; if let Some(agent) = root.get(Value::String("agent".to_string())) { @@ -1080,6 +1209,44 @@ fn validate_config_shape(source: &Path, value: &Value) -> Result<(), ConfigFileE &["enabled", "max_context_messages", "retained_tail"], )?; } + if let Some(harnesses) = root.get(Value::String("acp_harnesses".to_string())) { + let entries = match harnesses { + Value::Sequence(entries) => entries, + Value::Null => { + return Ok(()); + } + _ => { + return Err(invalid_value( + source, + "acp_harnesses", + "must be a sequence of harness definitions", + )); + } + }; + for (index, entry) in entries.iter().enumerate() { + let path = format!("acp_harnesses[{index}]"); + let mapping = as_mapping(entry, source, &path)?; + validate_known_keys(source, &path, mapping, &["id", "command", "args"])?; + if let Some(args) = mapping.get(Value::String("args".to_string())) + && !args.is_null() + { + let Some(args) = args.as_sequence() else { + return Err(invalid_value( + source, + &format!("{path}.args"), + "must be a sequence of strings", + )); + }; + if args.iter().any(|arg| arg.as_str().is_none()) { + return Err(invalid_value( + source, + &format!("{path}.args"), + "must be a sequence of strings", + )); + } + } + } + } Ok(()) } diff --git a/src/effects/managed_authority_tests.rs b/src/effects/managed_authority_tests.rs index 1cb925ff..7e4b4229 100644 --- a/src/effects/managed_authority_tests.rs +++ b/src/effects/managed_authority_tests.rs @@ -328,6 +328,7 @@ async fn fresh_host_rejects_wrong_risk_name_arguments_and_registry_then_same_vm_ let native = crate::runtime::agent_host::AgentHostState { child_call: None, child_read: None, + acp_tool: None, provider: Arc::new(ScriptedProvider::new()), cancellation: host.cancellation.clone().unwrap(), sleeps: Arc::clone(&host.sleeps), diff --git a/src/effects/mod.rs b/src/effects/mod.rs index 1f708874..1d073dfc 100644 --- a/src/effects/mod.rs +++ b/src/effects/mod.rs @@ -55,11 +55,12 @@ pub use journal::{ ManagedRestoreGraphSelection, ManagedRestoreRunInput, }; pub use types::{ - BranchEpoch, BranchId, CheckpointId, CheckpointRequest, EffectCancellation, EffectDeadline, - EffectError, EffectErrorKind, EffectFailure, ExternalEffectNotice, ImportConsistency, - ImportWorkspace, JournalEntry, JournalKind, MAX_TREE_BYTES, MAX_TREE_DEPTH, MAX_TREE_ENTRIES, - OpenViewRequest, OwnerId, PublicCheckpointRef, PublicWorkspaceRef, Publication, PublishRequest, - ResourceQuota, RestoreRequest, TreeId, WorkspaceId, + BranchEpoch, BranchId, CheckpointId, CheckpointRequest, DelegationSettlement, + EffectCancellation, EffectDeadline, EffectError, EffectErrorKind, EffectFailure, + ExternalEffectNotice, ImportConsistency, ImportWorkspace, JournalEntry, JournalKind, + MAX_TREE_BYTES, MAX_TREE_DEPTH, MAX_TREE_ENTRIES, OpenViewRequest, OwnerId, + PublicCheckpointRef, PublicWorkspaceRef, Publication, PublishRequest, ResourceQuota, + RestoreRequest, TreeId, WorkspaceId, }; #[cfg(feature = "workspace-io-fault")] pub use workspace::SimulatedIoFault; diff --git a/src/effects/types.rs b/src/effects/types.rs index 47e4a655..e2a5b793 100644 --- a/src/effects/types.rs +++ b/src/effects/types.rs @@ -458,3 +458,18 @@ pub struct ExternalEffectNotice { kind: String, reference: String, } + +/// Durable disposition of one external delegation call. +/// +/// The gateway's irreversible-effect vocabulary distinguishes three states that +/// a crash can leave behind. A call that never prepared is `NotStarted`; a call +/// whose outcome is durable is `Settled`; anything in between may have produced +/// an effect that cannot be proven, so it is `Indeterminate` and must never be +/// re-executed automatically. +#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DelegationSettlement { + NotStarted, + Settled, + Indeterminate, +} diff --git a/src/gateway/store.rs b/src/gateway/store.rs index 87870708..237b5f21 100644 --- a/src/gateway/store.rs +++ b/src/gateway/store.rs @@ -224,6 +224,13 @@ fn consume_exact_readback_reply( } pub struct GatewayPersistence { + /// Serializes durable session identity, approval and delegation-lease + /// writers against the one delegation spawn commit. It is a plain + /// process-local gate on purpose: it is only held across synchronous + /// storage commands and `fork`/`exec`, never across an await, handshake or + /// cleanup. Replacement rows are additionally refused by the durable + /// `(id, owner, created_at_ms)` predicate in every CAS. + session_fence: Arc>, #[cfg(test)] pub(crate) managed_request_hook: Mutex>, #[cfg(feature = "workspace-io-fault")] @@ -2479,6 +2486,7 @@ impl GatewayPersistence { #[cfg(any(test, feature = "workspace-io-fault"))] executed_commands, }, + session_fence: Arc::new(Mutex::new(())), max_events: config.max_events_per_run as i64, broadcast_capacity: config.broadcast_capacity, metrics, @@ -4443,6 +4451,26 @@ impl GatewayPersistence { self.command_data("session.touch", payload) } + /// Conditional write of the private `$.acp_delegation` document. + /// + /// The predicates (session owner and durable creation identity, expected + /// document version, and the exact call owning one pin lease) are enforced + /// by the storage transaction. `applied = 0` is a typed not-committed + /// result and never overwrites a concurrent owner. + pub fn session_acp_delegation_cas(&self, payload: &Value) -> Result { + let _fence = self + .session_fence + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + self.command_data("session.acp_delegation_cas", payload) + } + + /// Process-local arbitration shared by the durable session, approval and + /// delegation writers and the single synchronous spawn commit. + pub(crate) fn session_fence(&self) -> Arc> { + Arc::clone(&self.session_fence) + } + /// Atomically binds trusted workspace display metadata to an idle session /// through the RSS session command, preserving unrelated metadata keys. pub fn session_workspace_bind( @@ -4468,6 +4496,10 @@ impl GatewayPersistence { /// Cascades one session (messages, runs, events, links, approvals, /// compactions, delivery cursors, idempotency, run graph refs) in one transaction. pub fn session_delete(&self, session_id: &str) -> Result { + let _fence = self + .session_fence + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); self.command_data("session.delete", &json!({ "session_id": session_id })) } @@ -4950,6 +4982,10 @@ impl GatewayPersistence { } } } + let _fence = self + .session_fence + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); self.command_data("approval.resolve", payload) } @@ -5095,8 +5131,8 @@ impl GatewayPersistence { }); } - /// Caller-side barrier for one exact resolve. Service precheck has already - /// passed; the storage worker has not been entered. + /// Rendezvous for callers resolving the same approval, after service + /// precheck but before taking the session fence or entering the worker. #[cfg(feature = "config-fixture")] pub fn inject_approval_resolve_gate( &self, diff --git a/src/gateway/telegram.rs b/src/gateway/telegram.rs index 2cd02f43..c524434f 100644 --- a/src/gateway/telegram.rs +++ b/src/gateway/telegram.rs @@ -1996,6 +1996,24 @@ async fn cmd_list_approvals( } } +/// Parse the single approval-id token of `/approve` and `/deny`. +/// +/// The prefix is only a syntax check. The durable row, run, session, owner and +/// picker binding decide whether the decision is authorized; a delegation id +/// grants nothing by itself. +fn approval_command_target(arguments: &str) -> Option<&str> { + let mut tokens = arguments.split_whitespace(); + let token = tokens.next()?; + if tokens.next().is_some() || token.len() > 512 { + return None; + } + if token.starts_with("guardian-approval:") || token.starts_with("acp-delegation:") { + Some(token) + } else { + None + } +} + fn callback_decision(data: &str) -> Option<(bool, &str)> { let (approved, run_id) = if let Some(run_id) = data.strip_prefix("a:") { (true, run_id) @@ -2143,8 +2161,7 @@ async fn cmd_approval( thread_id: Option, command: ApprovalCommand<'_>, ) { - let tokens: Vec<&str> = command.approval_arguments.split_whitespace().collect(); - if tokens.len() != 1 || tokens[0].len() > 512 || !tokens[0].starts_with("guardian-approval:") { + let Some(approval_id) = approval_command_target(command.approval_arguments) else { let _ = reply( api, chat_id, @@ -2153,7 +2170,7 @@ async fn cmd_approval( ) .await; return; - } + }; let run_id = { let store = runtime.state.store.read(); session_active_run(&runtime.active_runs, &store, command.session_id) @@ -2163,7 +2180,7 @@ async fn cmd_approval( return; }; let service = runtime.state.service(); - let approval_id = tokens[0].to_string(); + let approval_id = approval_id.to_string(); let approval_locator = approval_id.clone(); let decision = if command.approved { "approved" @@ -2554,11 +2571,6 @@ async fn publish_pending_pickers( chat_id: i64, thread_id: Option, ) { - if !state.service().sealed_user_reviewer(run_id) - && !state.service().sealed_auto_reviewer(run_id) - { - return; - } let Some(persistence) = state.persistence() else { return; }; @@ -2617,6 +2629,8 @@ async fn publish_pending_pickers( .and_then(Value::as_str) .filter(|text| !text.trim().is_empty()) .unwrap_or("Action preview unavailable; do not approve this action."); + let delegated = approval.get("tool_name").and_then(Value::as_str) + == Some(crate::service::acp_session_pins::DELEGATION_TOOL_NAME); let mut shown = redacted.to_string(); let mut owner_terminal = false; if private_owner { @@ -2640,19 +2654,41 @@ async fn publish_pending_pickers( owner_terminal = true; } } - let card = super::telegram_format::approval_card(&shown, owner_terminal); + let card = if delegated { + // This preview was matched against the durable call and owner. + // Deliver the whole text without Markdown interpretation. Shared + // chats use the owner-checked command path, not a public picker. + let text = format!("ACP delegation approval\n{redacted}\n\nApproval ID: {approval_id}"); + if redacted == "Action preview unavailable; do not approve this action." + || super::telegram_format::utf16_units(&text) > 4096 + { + continue; + } + super::telegram_format::ApprovalCard { + text, + attach_keyboard: private_owner, + } + } else { + super::telegram_format::approval_card(&shown, owner_terminal) + }; if !card.attach_keyboard { - let _ = api.send_message(chat_id, thread_id, &card.text).await; - service.suppress_picker_publication(approval_id); + let sent = api.send_message(chat_id, thread_id, &card.text).await; + if !delegated || sent.is_ok() { + service.suppress_picker_publication(approval_id); + } continue; } let Some(markup) = picker_keyboard(run_id) else { continue; }; - let Ok(sent) = api - .send_message_with_keyboard(chat_id, thread_id, &card.text, markup) - .await - else { + let sent = if delegated { + api.send_text(chat_id, thread_id, &card.text, None, Some(&markup)) + .await + } else { + api.send_message_with_keyboard(chat_id, thread_id, &card.text, markup) + .await + }; + let Ok(sent) = sent else { continue; }; let picker = TelegramApprovalPicker { @@ -3406,6 +3442,21 @@ mod tests { } } + #[test] + fn approval_command_target_accepts_only_single_known_ids() { + assert_eq!( + approval_command_target("guardian-approval:run:call"), + Some("guardian-approval:run:call") + ); + assert_eq!( + approval_command_target("acp-delegation:run:call"), + Some("acp-delegation:run:call") + ); + assert_eq!(approval_command_target("acp-delegation:a b"), None); + assert_eq!(approval_command_target("write-approval:run:call"), None); + assert_eq!(approval_command_target(""), None); + } + #[test] fn parse_command_recognizes_only_canonical_commands() { assert_eq!( diff --git a/src/lib.rs b/src/lib.rs index 0fbef5e9..c18eb5e4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,8 +51,8 @@ pub use auth::store_host::{AuthFixtureHost, auth_store_fixture_catalog}; pub use auth::token::{AuthStatus, CredentialId, TokenError}; pub use config::{AgentGatewayConfig, TelegramConfig}; pub use config_file::{ - AgentPaths, BoundedPublicConfig, ConfigFile, ConfigFileError, ConfigPaths, LoadedConfig, - RuntimeConfig, load_config, + AcpHarnessSettings, AgentPaths, BoundedPublicConfig, ConfigFile, ConfigFileError, ConfigPaths, + LoadedConfig, RuntimeConfig, load_config, }; #[cfg(feature = "config-fixture")] pub mod config_fixture { diff --git a/src/runtime/agent_host.rs b/src/runtime/agent_host.rs index daa9ef84..c79a14de 100644 --- a/src/runtime/agent_host.rs +++ b/src/runtime/agent_host.rs @@ -2231,6 +2231,8 @@ fn now_ms() -> u64 { .unwrap_or(0) } +pub(crate) type AcpToolInvoke = dyn Fn(&str, &JsonValue) -> JsonValue + Send + Sync; + /// Per-VM state installed before `run(context)`. #[derive(Clone)] pub struct AgentHostState { @@ -2253,6 +2255,7 @@ pub struct AgentHostState { pub(crate) expected_call: Option, pub plugin_state_call: Option, pub(crate) provider_arguments: Arc>>, + pub(crate) acp_tool: Option>, /// Crate-private caller-side plumbing for the one captured child call. pub(crate) child_call: Option>, /// Crate-private child-side adapter; only child-role closures see it. @@ -3031,6 +3034,34 @@ impl AgentHostState { if let Err(code) = pinned.check_execution_authority(Some(&self.cancellation)) { return pinned_outcome(false, "", "", code, code, ""); } + if tool_name == crate::service::acp_session_pins::DELEGATION_TOOL_NAME { + // The ACP tool uses its own external-effect settlement. Unlike + // stateless development mode it requires a durable provider parent. + let durable_parent = self + .lifecycle + .as_ref() + .zip(self.capability_owner.as_ref()) + .and_then(|(lifecycle, owner)| { + lifecycle + .parent_arguments(owner, &call_id, &tool_name) + .ok() + .flatten() + }); + if durable_parent.as_ref() != Some(&arguments) { + return pinned_call_mismatch(); + } + return match &self.acp_tool { + Some(invoke) => invoke(&call_id, &arguments), + None => pinned_outcome( + false, + "", + "", + "acp_delegation_disabled", + "ACP delegation is not enabled for this run", + "", + ), + }; + } if let Some(binding) = &pinned.managed { let replay = if pinned.child.is_some() { // Re-derived from the current sealed pin and the original @@ -5403,7 +5434,7 @@ fn invoke_pinned_plugin_child_adapter(vm: &mut Vm, args: &[Value]) -> VmResult map { expected_call: None, plugin_state_call: None, provider_arguments: Default::default(), + acp_tool: None, }); assert!(matches!(vm.run().expect("RSS root"), VmStatus::Halted)); vm @@ -7744,6 +7777,7 @@ mod guardian_real_entry_tests { expected_call: None, plugin_state_call: None, provider_arguments: Default::default(), + acp_tool: None, }); assert!(matches!(vm.run().expect("RSS root"), VmStatus::Halted)); vm diff --git a/src/runtime/agent_host/option_text_tests.rs b/src/runtime/agent_host/option_text_tests.rs index 66e526ed..a9414351 100644 --- a/src/runtime/agent_host/option_text_tests.rs +++ b/src/runtime/agent_host/option_text_tests.rs @@ -139,6 +139,7 @@ fn probe_vm(provider: Arc) -> Vm { vm.host_context().set_module_state(AgentHostState { child_call: None, child_read: None, + acp_tool: None, provider, cancellation: RunCancellation::with_timeout(CANCEL), sleeps: Arc::new(Mutex::new(SleepLog::default())), @@ -516,6 +517,7 @@ fn main_loop_vm(provider: Arc) -> Vm { vm.host_context().set_module_state(AgentHostState { child_call: None, child_read: None, + acp_tool: None, provider, cancellation: RunCancellation::with_timeout(CANCEL), sleeps: Arc::new(Mutex::new(SleepLog::default())), diff --git a/src/runtime/agent_host/preview_tests.rs b/src/runtime/agent_host/preview_tests.rs index e111da0c..0cf99fc9 100644 --- a/src/runtime/agent_host/preview_tests.rs +++ b/src/runtime/agent_host/preview_tests.rs @@ -183,6 +183,7 @@ fn probe_vm(provider: Arc) -> Vm { vm.host_context().set_module_state(AgentHostState { child_call: None, child_read: None, + acp_tool: None, provider, cancellation: RunCancellation::with_timeout(CANCEL), sleeps: Arc::new(Mutex::new(SleepLog::default())), @@ -437,6 +438,7 @@ fn main_loop_vm(provider: Arc, fixture: &LifecycleFixture vm.host_context().set_module_state(AgentHostState { child_call: None, child_read: None, + acp_tool: None, provider, cancellation: RunCancellation::with_timeout(CANCEL), sleeps: Arc::new(Mutex::new(SleepLog::default())), diff --git a/src/runtime/rss_runner.rs b/src/runtime/rss_runner.rs index e8496f4b..3d52254e 100644 --- a/src/runtime/rss_runner.rs +++ b/src/runtime/rss_runner.rs @@ -782,6 +782,9 @@ struct RunCancellationInner { stop: Arc, /// Process token linked to this root. `request` and deadline fire cancel it. token: CancellationToken, + /// Async wake for native async callers. `request` publishes `true` once; + /// readers await the change instead of polling the atomic reason. + cancel_watch: tokio::sync::watch::Sender, /// Set when a timeout/deadline cannot be represented as `Instant`. deadline_overflow: AtomicBool, /// Set by the watcher after it really jumped the VM epoch. A test can wait @@ -812,7 +815,35 @@ pub enum RunnerPrepareFault { pub const MAX_RUN_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60); +/// Guard proving the caller's spawn decision is ordered against the first +/// `RunCancellation::request`. Constructed only by +/// [`RunCancellation::spawn_arbitration`]. +pub struct RunSpawnArbitration<'a> { + requested: std::sync::MutexGuard<'a, Option>, +} + +impl RunSpawnArbitration<'_> { + /// The first typed cancellation reason, if a stop already won. + pub fn requested(&self) -> Option { + *self.requested + } +} + impl RunCancellation { + /// Synchronous arbitration shared with [`Self::request`]. + /// + /// The returned guard holds the same mutex `request` takes to publish the + /// first typed reason. A caller that checks cancellation and creates the + /// external process while holding it establishes one real order: a stop + /// either happened before the check (zero spawn) or waits until the + /// process exists and is then observed by the normal cancellation path. + /// The guard is deliberately not `Send` and must never cross an await. + pub fn spawn_arbitration(&self) -> RunSpawnArbitration<'_> { + RunSpawnArbitration { + requested: self.inner.requested.lock().expect("requested lock"), + } + } + pub(crate) fn same_root(&self, other: &Self) -> bool { Arc::ptr_eq(&self.inner, &other.inner) } @@ -839,6 +870,7 @@ impl RunCancellation { watcher: Arc::new(Mutex::new(None)), stop: Arc::new(AtomicBool::new(false)), token: CancellationToken::new(), + cancel_watch: tokio::sync::watch::channel(false).0, deadline_overflow: AtomicBool::new(false), epoch_advanced: Arc::new(AtomicBool::new(false)), }), @@ -912,12 +944,35 @@ impl RunCancellation { } drop(requested); self.inner.token.cancel(); + self.inner.cancel_watch.send_replace(true); } pub fn requested(&self) -> Option { *self.inner.requested.lock().expect("requested lock") } + /// Resolves as soon as this run's cancellation is requested. Native async + /// callers await this instead of polling `requested()`, so the first + /// request is observed without waiting for a poll interval. + pub fn cancelled(&self) -> impl std::future::Future + Send + 'static { + let mut watch = self.inner.cancel_watch.subscribe(); + async move { + if *watch.borrow_and_update() { + return; + } + loop { + if watch.changed().await.is_err() { + // The owning run state is gone; cancellation can no longer + // be published, so this wait never completes. + std::future::pending::<()>().await; + } + if *watch.borrow_and_update() { + return; + } + } + } + } + /// Native dispatcher parent token linked to this cancellation root. pub fn token(&self) -> CancellationToken { self.inner.token.clone() @@ -954,6 +1009,7 @@ impl RunCancellation { watcher: Arc::new(Mutex::new(None)), stop: Arc::new(AtomicBool::new(false)), token: self.inner.token.clone(), + cancel_watch: self.inner.cancel_watch.clone(), deadline_overflow: AtomicBool::new( self.inner.deadline_overflow.load(Ordering::SeqCst), ), @@ -1046,6 +1102,7 @@ pub struct AgentRunner { /// legacy `from_source`/`from_file` runners. bundled_origin: Option, expected_call: Option, + acp_tool: Option>, /// Crate-private caller-side child plumbing for the one captured /// stateless delegation. Install before the caller VM can run. pub(crate) child_call: Option>, @@ -1078,6 +1135,12 @@ pub(crate) struct WorkspaceAuthority { /// Set only by this captured authority's explicit Native revoke method. /// The host owner may also retire with the guest VM; that is not a revoke. explicitly_revoked: AtomicBool, + /// Shared with the delegation spawn commit, so a revoke either publishes + /// before the spawn decision or waits until the process exists. + spawn_gate: Arc>, + /// Explicit-revoke wakeup for an already started delegation. `revoke` + /// publishes `true` once; a running call awaits this instead of polling. + revoke_watch: tokio::sync::watch::Sender, } impl WorkspaceAuthority { @@ -1105,10 +1168,27 @@ impl WorkspaceAuthority { } pub(crate) fn revoke(&self) { + let _gate = self + .spawn_gate + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); self.explicitly_revoked.store(true, Ordering::Release); + self.revoke_watch.send_replace(true); self.binding.host.revoke(); } + /// Arbitration shared with the delegation spawn commit. + pub(crate) fn spawn_gate(&self) -> Arc> { + Arc::clone(&self.spawn_gate) + } + + /// Wakeup for a delegation that already started. The receiver observes the + /// current explicit-revoke fact and every later publication; guest + /// teardown (`release`) never publishes here. + pub(crate) fn revoked_watch(&self) -> tokio::sync::watch::Receiver { + self.revoke_watch.subscribe() + } + /// Guest capability teardown: release the host owners without recording an /// explicit authority revocation. The completion owner must not treat its /// own run-end cleanup as a withdrawal of the workspace authority. @@ -1339,6 +1419,7 @@ impl AgentRunner { child_call: None, child_read: None, child_state: None, + acp_tool: None, }) } @@ -1423,6 +1504,14 @@ impl AgentRunner { } /// Replaces the full host-bridge bundle for one run. + pub(crate) fn with_acp_tool( + mut self, + tool: Option>, + ) -> Self { + self.acp_tool = tool; + self + } + pub fn with_host(mut self, host: AgentHostBridges) -> Self { if self.provider_mode == ProviderMode::Enabled && host.provider.is_none() @@ -1526,6 +1615,8 @@ impl AgentRunner { binding, grant, explicitly_revoked: AtomicBool::new(false), + spawn_gate: Arc::new(std::sync::Mutex::new(())), + revoke_watch: tokio::sync::watch::channel(false).0, })), (Some(_), None) => { return Err(RunError::Setup(VmError::HostError( @@ -1718,6 +1809,7 @@ impl AgentRunner { .and_then(|grant| grant.plugin_state_call.clone()) .or_else(|| self.child_state.clone()), provider_arguments: Default::default(), + acp_tool: self.acp_tool.clone(), child_call: self.child_call.clone(), child_read: self.child_read.clone(), }); @@ -2338,6 +2430,7 @@ pub(crate) fn invoke_retained_tool_with_child( bundled_origin: None, expected_call, child_call, + acp_tool: None, child_read: None, child_state: None, }; @@ -2379,6 +2472,7 @@ pub(crate) fn invoke_retained_child( bundled_origin: None, expected_call: None, child_call: None, + acp_tool: None, child_read: Some(adapter), child_state, }; diff --git a/src/service.rs b/src/service.rs index 6c3a8bb0..c42ff51d 100644 --- a/src/service.rs +++ b/src/service.rs @@ -59,6 +59,7 @@ use crate::config::{ validate_request_hash, validate_visible_name, }; use crate::config_file::CompactionSettings; +pub mod acp_session_pins; mod managed_branches; mod managed_checkpoints; mod managed_completion; @@ -1502,6 +1503,9 @@ struct AgentServiceInner { /// Explicit embedding-supplied legacy root; default RunLimits never /// become ambient authority for production HTTP or Telegram requests. trusted_legacy_workspace_root: RwLock>, + /// Installed ACP delegation policy. `None` is the default: the capability + /// is disabled and no entry point exists. + acp_delegation: Mutex>>, /// Compiled agent source reused across workers so compile does not reset the deadline. runner: Mutex>, import_validation_memo: crate::runtime::module_snapshot::ImportValidationMemo, @@ -1651,6 +1655,242 @@ fn durable_admission_status_is_terminal(status: &str) -> bool { matches!(status, "completed" | "failed" | "cancelled") } +impl acp_session_pins::AcpApprovalGateway for AgentService { + fn request_manual_approval( + &self, + request: &acp_session_pins::AcpApprovalRequest, + ) -> Result<(), &'static str> { + let handle = self.handle(&request.run_id).ok_or("acp_run_inactive")?; + if handle.is_terminal() || handle.cancel.requested().is_some() { + return Err("acp_run_inactive"); + } + // Delegated external execution always ends at a human decision. An + // explicit user reviewer gets a single-call row; every other sealed + // reviewer (including the Telegram default and an unset reviewer) + // enters the real durable `human_pending` state, which Guardian's + // automatic allow path never owns. + let decision_scope = match self.sealed_reviewer(&request.run_id).as_deref() { + Some("user") => "single_call", + Some("auto") | Some("guardian") | None => "human_pending", + Some(_) => return Err("acp_human_review_required"), + }; + let context = self + .inner + .contexts + .lock() + .expect("contexts lock") + .get(&request.run_id) + .cloned() + .ok_or("acp_run_inactive")?; + if context.session_id != request.session_id { + return Err("acp_binding_mismatch"); + } + let persistence = self.persistence_handle().ok_or("acp_storage_unavailable")?; + let request_scope = if decision_scope == "human_pending" { + "guardian_pending" + } else { + decision_scope + }; + let payload = json!({ + "id": request.approval_id, + "run_id": request.run_id, + "session_id": request.session_id, + "tool_call_id": request.tool_call_id, + "tool_name": acp_session_pins::DELEGATION_TOOL_NAME, + "arguments_json": "{}", + "risk_class": "execute", + "decision_scope": request_scope, + "one_time": 1, + "requested_at_ms": timestamp(), + "expires_at_ms": request.expires_at_ms, + }); + persistence + .approval_request(&payload) + .map_err(|_| "acp_storage_unavailable")?; + if request_scope != decision_scope { + // The store refuses to create `human_pending` directly. Reach it + // through the same durable handoff Guardian uses when it escalates + // to a human; no automatic decision is recorded here. + let handed = persistence + .approval_handoff(&json!({ + "id": request.approval_id, + "run_id": request.run_id, + "session_id": request.session_id, + "tool_call_id": request.tool_call_id, + "tool_name": acp_session_pins::DELEGATION_TOOL_NAME, + "now_ms": timestamp(), + })) + .map_err(|_| "acp_storage_unavailable")?; + if handed.get("rows_affected").and_then(JsonValue::as_i64) != Some(1) { + return Err("acp_approval_unavailable"); + } + } + let current = persistence + .approval_get(&request.approval_id) + .map_err(|_| "acp_storage_unavailable")?; + let row = current + .get("rows") + .and_then(JsonValue::as_array) + .and_then(|rows| rows.first()) + .and_then(JsonValue::as_array) + .ok_or("acp_approval_unavailable")?; + if row.first().and_then(JsonValue::as_str) != Some(request.approval_id.as_str()) + || row.get(1).and_then(JsonValue::as_str) != Some(request.run_id.as_str()) + || row.get(2).and_then(JsonValue::as_str) != Some(request.session_id.as_str()) + || row.get(3).and_then(JsonValue::as_str) != Some(request.tool_call_id.as_str()) + || row.get(4).and_then(JsonValue::as_str) + != Some(acp_session_pins::DELEGATION_TOOL_NAME) + || row.get(5).and_then(JsonValue::as_str) != Some("{}") + || row.get(6).and_then(JsonValue::as_str) != Some("execute") + || row.get(7).and_then(JsonValue::as_str) != Some("pending") + || row.get(8).and_then(JsonValue::as_str) != Some(decision_scope) + || row.get(11).and_then(JsonValue::as_i64) != Some(request.expires_at_ms as i64) + { + return Err("acp_approval_unavailable"); + } + let binding = PendingApprovalPreviewBinding::new( + &request.session_id, + &request.approval_id, + &request.tool_call_id, + acp_session_pins::DELEGATION_TOOL_NAME, + "execute", + request.expires_at_ms as i64, + ); + self.store_pending_approval_preview(&request.run_id, &binding, &request.preview, None) + } + + fn manual_approval_resolver( + &self, + run_id: &str, + approval_id: &str, + ) -> Result { + let persistence = self.persistence_handle().ok_or("acp_storage_unavailable")?; + let current = persistence + .approval_get(approval_id) + .map_err(|_| "acp_storage_unavailable")?; + let row = current + .get("rows") + .and_then(JsonValue::as_array) + .and_then(|rows| rows.first()) + .and_then(JsonValue::as_array) + .ok_or("acp_approval_not_found")?; + if row.first().and_then(JsonValue::as_str) != Some(approval_id) + || row.get(1).and_then(JsonValue::as_str) != Some(run_id) + || row.get(4).and_then(JsonValue::as_str) + != Some(acp_session_pins::DELEGATION_TOOL_NAME) + || row.get(7).and_then(JsonValue::as_str) != Some("approved") + { + return Err("acp_approval_mismatch"); + } + let resolver = row + .get(13) + .and_then(JsonValue::as_str) + .ok_or("acp_approval_not_user")?; + let manual = resolver == "http-bearer" + || resolver + .strip_prefix("telegram:") + .is_some_and(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit())); + if !manual { + return Err("acp_approval_not_user"); + } + let scope = row.get(8).and_then(JsonValue::as_str).unwrap_or(""); + if !self.manual_approval_eligible(run_id, acp_session_pins::DELEGATION_TOOL_NAME, scope) { + return Err("acp_approval_not_user"); + } + let expires_at_ms = row.get(11).and_then(JsonValue::as_i64).unwrap_or_default(); + if expires_at_ms != 0 && expires_at_ms <= i64::try_from(timestamp()).unwrap_or(i64::MAX) { + return Err("acp_approval_expired"); + } + Ok(resolver.to_string()) + } + + fn run_active(&self, run_id: &str) -> bool { + self.handle(run_id) + .is_some_and(|handle| !handle.is_terminal() && handle.cancel.requested().is_none()) + } + + fn run_facts(&self, run_id: &str) -> Option { + let handle = self.handle(run_id)?; + let context = self + .inner + .contexts + .lock() + .expect("contexts lock") + .get(run_id) + .cloned()?; + if context.session_id.is_empty() { + return None; + } + let deadline_ms = context + .metadata + .get("deadline_at_ms") + .and_then(metadata_u64) + .unwrap_or(0); + Some(acp_session_pins::AcpRunFacts { + session_id: context.session_id, + reviewer: self.sealed_reviewer(run_id), + workspace: handle.workspace_authority.as_ref().map(|authority| { + Arc::new(RunWorkspaceAuthority(Arc::clone(authority))) + as Arc + }), + cancellation: handle.cancel.clone(), + deadline_ms, + }) + } + + fn durable_run_terminal(&self, run_id: &str) -> Result { + let persistence = self.persistence_handle().ok_or("acp_storage_unavailable")?; + let result = persistence + .run_get(run_id) + .map_err(|_| "acp_storage_unavailable")?; + let row = result + .get("rows") + .and_then(JsonValue::as_array) + .and_then(|rows| rows.first()) + .and_then(JsonValue::as_array) + .ok_or("acp_run_inactive")?; + let status = row.get(3).and_then(JsonValue::as_str).unwrap_or_default(); + Ok(durable_admission_status_is_terminal(status)) + } +} + +/// Narrow view of the admitted run's retained workspace authority. +struct RunWorkspaceAuthority(Arc); + +impl acp_session_pins::AcpWorkspaceAuthority for RunWorkspaceAuthority { + fn check(&self) -> Result<(), &'static str> { + self.0.check().map_err(|_| "acp_workspace_invalid") + } + + fn revoked(&self) -> bool { + self.0.revoked() + } + + fn canonical_path(&self) -> &str { + self.0.canonical_path() + } + + fn generation(&self) -> u64 { + self.0.generation() + } + + fn spawn_gate(&self) -> Arc> { + self.0.spawn_gate() + } + + fn revoked_watch(&self) -> Option> { + Some(self.0.revoked_watch()) + } +} + +/// Admission metadata stores the deadline either as a JSON number or, after a +/// test seam, as a decimal string. +fn metadata_u64(value: &JsonValue) -> Option { + value + .as_u64() + .or_else(|| value.as_str().and_then(|text| text.parse().ok())) +} + impl AgentService { pub(crate) fn new( config: Arc, @@ -1750,6 +1990,7 @@ impl AgentService { #[cfg(test)] workspace_runner_constructions: [AtomicUsize::new(0), AtomicUsize::new(0)], trusted_legacy_workspace_root: RwLock::new(None), + acp_delegation: Mutex::new(None), runner: Mutex::new(None), import_validation_memo: Default::default(), compaction_runner: Mutex::new(None), @@ -6060,7 +6301,7 @@ impl AgentService { .and_then(JsonValue::as_str) .ok_or("storage_unavailable")?; let decision_scope = row.get(8).and_then(JsonValue::as_str).unwrap_or(""); - if !self.manual_approval_eligible(run_id, decision_scope) { + if !self.manual_approval_eligible(run_id, tool_name, decision_scope) { continue; } let binding = PendingApprovalPreviewBinding::new( @@ -6134,15 +6375,27 @@ impl AgentService { self.sealed_reviewer(run_id).as_deref() == Some("auto") } - /// Manual resolve is explicit user, or sealed auto after the same row is - /// `human_pending`. `guardian_pending` is not clickable. - fn manual_approval_eligible(&self, run_id: &str, decision_scope: &str) -> bool { + /// Manual resolve is explicit user, or a sealed reviewer after the same row + /// reached `human_pending`. `guardian_pending` is not clickable. Delegation + /// rows always require a human decision, so their `human_pending` row is + /// resolvable for every sealed reviewer topology; other tools keep their + /// existing eligibility. + fn manual_approval_eligible( + &self, + run_id: &str, + tool_name: &str, + decision_scope: &str, + ) -> bool { match self.sealed_reviewer(run_id).as_deref() { Some("user") => { decision_scope != "guardian_pending" && decision_scope != "human_pending" } Some("auto") => decision_scope == "human_pending", - _ => false, + Some("guardian") | None => { + tool_name == acp_session_pins::DELEGATION_TOOL_NAME + && decision_scope == "human_pending" + } + Some(_) => false, } } @@ -6169,10 +6422,10 @@ impl AgentService { { return Err("approval_preview_invalid"); } - if !self.sealed_user_reviewer(&picker.run_id) && !self.sealed_auto_reviewer(&picker.run_id) - { - return Err("approval_reviewer_not_user"); - } + // Eligibility is decided by the durable row and reviewer topology in + // `pending_approvals_for_actor` below. A guardian/unset reviewer is + // only offered a delegation `human_pending` row; other tools keep + // their existing prohibition. let _ = self.pending_approvals_for_actor( &picker.run_id, &picker.session_id, @@ -6407,7 +6660,8 @@ impl AgentService { return Err("approval_not_pending"); } let decision_scope = row.get(8).and_then(JsonValue::as_str).unwrap_or(""); - if !self.manual_approval_eligible(run_id, decision_scope) { + let row_tool_name = row.get(4).and_then(JsonValue::as_str).unwrap_or(""); + if !self.manual_approval_eligible(run_id, row_tool_name, decision_scope) { return Err("approval_reviewer_not_user"); } let now = i64::try_from(timestamp()).unwrap_or(i64::MAX); @@ -6485,6 +6739,190 @@ impl AgentService { self.inner.persistence.clone() } + /// Installs the optional ACP delegation policy built from the existing + /// `config.yaml` launch table. + /// + /// Install during Gateway startup, before runs are admitted. Only the + /// immutable bundled coding harness receives the opt-in tool catalog. + pub fn install_acp_delegation( + &self, + policy: Option>, + ) -> Result<(), String> { + if policy.is_some() && self.inner.persistence.is_none() { + return Err( + "acp delegation requires the durable gateway store; no store is configured" + .to_string(), + ); + } + let mut installed = self.inner.acp_delegation.lock().expect("ACP policy lock"); + if installed.is_some() { + return Err("ACP delegation policy is already installed".into()); + } + if policy.is_some() && self.acp_bundled_entry() { + let mut registry = self.inner.tool_registry.write(); + let mut descriptors = registry.descriptors().to_vec(); + descriptors.push(crate::tool_schema::acp_delegation_descriptor()); + *registry = + ToolRegistry::from_descriptors(descriptors).map_err(|error| error.to_string())?; + } + *installed = policy; + Ok(()) + } + + fn acp_bundled_entry(&self) -> bool { + matches!( + self.inner.agent_entry.lock().expect("agent entry lock").as_ref(), + Some(AgentEntry::Bundled(key)) if key == "rss/agent/main.rss" + ) + } + + fn acp_tool_for_run( + &self, + run_id: &str, + ) -> Option> { + if !self.acp_bundled_entry() { + return None; + } + let policy = self.acp_delegation()?; + let registry = self + .inner + .context_registries + .lock() + .expect("context registries lock") + .get(run_id)? + .clone(); + let descriptor = crate::tool_schema::acp_delegation_descriptor(); + if registry.descriptor(&descriptor.name) != Some(&descriptor) { + return None; + } + let context = self + .inner + .contexts + .lock() + .expect("contexts lock") + .get(run_id)? + .clone(); + if context.parent_run_id.is_some() { + return None; + } + let facts = acp_session_pins::AcpApprovalGateway::run_facts(self, run_id)?; + let persistence = self.persistence_handle()?; + let service = self.clone(); + let runtime = tokio::runtime::Handle::current(); + Some(Arc::new(move |call_id, arguments| { + let result = runtime.block_on(acp_session_pins::run_rss_delegation( + &policy, + &persistence, + &context, + &facts, + ®istry, + call_id, + arguments, + )); + service.publish_acp_observation(&context.run_id, call_id, result) + })) + } + + // Persist the observation before RSS refreshes context from durable + // history. The policy's earlier settlement remains the effect authority: + // publication failure can never authorize a repeat of the external work. + fn publish_acp_observation( + &self, + run_id: &str, + call_id: &str, + invoked: JsonValue, + ) -> JsonValue { + use crate::runtime::agent_host::pinned_outcome; + let canonical = invoked["canonical_result"].as_str().unwrap_or_default(); + if canonical.is_empty() + || self + .handle(run_id) + .is_some_and(|handle| handle.cancel.requested().is_some()) + { + return invoked; + } + let Ok(data) = serde_json::from_str::(canonical) else { + return pinned_outcome( + false, + "", + "", + "acp_result_invalid", + "ACP result was not valid", + "", + ); + }; + let text = invoked["content"].as_str().unwrap_or_default(); + let truncated = invoked["truncated"].as_bool().unwrap_or(false); + let code = invoked["code"].as_str().unwrap_or_default(); + let mut result = if invoked["ok"].as_bool() == Some(true) { + ToolResult::success(text, data) + } else { + ToolResult::failure_with(code, code, text, data, truncated) + }; + result.truncated = truncated; + let event = if result.ok { + "tool.completed" + } else { + "tool.failed" + }; + let mut public = json!({ + "tool_call_id": call_id, "name": acp_session_pins::DELEGATION_TOOL_NAME, + "ok": result.ok, "truncated": truncated, + }); + if !result.ok { + public["error_code"] = json!(code); + } + if self + .commit_tool_step(run_id, event, public, Some(&result)) + .is_err() + { + return pinned_outcome( + false, + "", + "", + "event_persist_failed", + "ACP observation could not be published", + "", + ); + } + invoked + } + + /// Installed delegation policy, if the capability is enabled. + pub fn acp_delegation(&self) -> Option> { + self.inner + .acp_delegation + .lock() + .expect("acp delegation policy") + .clone() + } + + /// Executes one approved delegation through the installed policy. + /// + /// The caller supplies the exact admitted call identity and its durable + /// approval witness; every other fact is re-read from the store. When the + /// capability is not installed the call is refused without any side effect. + pub async fn delegate_acp( + &self, + scope: acp_session_pins::AcpDelegationScope, + request: acp_session_pins::AcpDelegationRequest, + witness: acp_session_pins::AcpApprovalWitness, + ) -> acp_session_pins::AcpDelegationResult { + let harness_id = request.harness_id.clone(); + let Some(policy) = self.acp_delegation() else { + return acp_session_pins::AcpDelegationResult { + harness_id, + status: acp_session_pins::AcpDelegationStatus::Denied, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_delegation_disabled"), + replayed: false, + }; + }; + policy.delegate(&scope, &request, &witness).await + } + /// Resolves and durably changes a session workspace through the shared RSS /// selection entry and the atomic storage session command. pub(crate) async fn bind_session_workspace( @@ -9248,6 +9686,20 @@ impl AgentService { .and_then(|pin| pin.managed.clone()) } + /// Fixture-only run-scoped wrapper around the captured ordinary run + /// workspace authority's existing revoke method. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn revoke_run_workspace_authority(&self, run_id: &str) -> bool { + let Some(handle) = self.handle(run_id) else { + return false; + }; + let Some(authority) = handle.workspace_authority.as_ref() else { + return false; + }; + authority.revoke(); + authority.check().is_err() + } + /// Fixture-only run-scoped wrapper around the captured Native workspace /// authority's existing revoke method. It returns whether the same exact /// authority now refuses its own check. @@ -9651,14 +10103,14 @@ impl AgentService { .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .take(); + let acp_tool = self.acp_tool_for_run(&run_id); let mut worker = tokio::task::spawn_blocking(move || { #[cfg(test)] let _worker_probe = worker_probe.map(|probe| probe.install()); - runner.with_host(host).run_with_context_and_events( - context, - &mut sink, - &run_cancellation, - ) + runner + .with_host(host) + .with_acp_tool(acp_tool) + .run_with_context_and_events(context, &mut sink, &run_cancellation) }); let remaining = cancellation .remaining_deadline() @@ -11696,9 +12148,12 @@ impl DurableEventCommitter for ServiceEventCommitter { } else { String::new() }; - let content = result - .filter(|_| attach_message) - .map(|result| tool_result_content_json(&tool_call_id, result)); + let content = result.filter(|_| attach_message).map(|result| { + let include_failure_data = data.get("name").and_then(JsonValue::as_str) + == Some(acp_session_pins::DELEGATION_TOOL_NAME) + && result.data.get("status").is_some(); + tool_result_content_json_with_data(&tool_call_id, result, include_failure_data) + }); let reserved = { let store = self.store.read(); let Some(run) = store.runs.get(&self.run_id) else { @@ -12285,6 +12740,14 @@ fn apply_terminal( } pub(crate) fn tool_result_content_json(tool_call_id: &str, result: &ToolResult) -> JsonValue { + tool_result_content_json_with_data(tool_call_id, result, false) +} + +fn tool_result_content_json_with_data( + tool_call_id: &str, + result: &ToolResult, + include_failure_data: bool, +) -> JsonValue { let (content, cut) = truncate_utf8_chars(&result.content, MAX_DURABLE_TEXT_CHARS); let truncated = result.truncated || cut; let error = result.error.as_ref().map(|error| { @@ -12303,7 +12766,7 @@ pub(crate) fn tool_result_content_json(tool_call_id: &str, result: &ToolResult) tool_call_id: Some(tool_call_id.to_string()), content: Some(content), is_error: Some(!result.ok), - result: if result.ok { + result: if result.ok || include_failure_data { Some(result.data.clone()) } else { None diff --git a/src/service/acp_session_pins.rs b/src/service/acp_session_pins.rs new file mode 100644 index 00000000..647755a3 --- /dev/null +++ b/src/service/acp_session_pins.rs @@ -0,0 +1,3889 @@ +//! Durable ACP delegation policy. +//! +//! This module owns the boundary between the operator's immutable +//! `config.yaml` launch table and one delegated ACP call: +//! +//! - it resolves a configured logical harness ID to an exact, shell-free argv; +//! - it requires a durable approval produced by the gateway's real manual +//! approval surface (an authenticated `http-bearer` or `telegram:` +//! decision bound to the live run, the call and the displayed preview), never +//! an automatic reviewer decision; +//! - it keeps the peer-assigned external session ID, every call phase and the +//! approval binding in the session's private durable metadata +//! (`$.acp_delegation`), which is never projected into the public config +//! snapshot, a tool input, an event or a log; +//! - every write is a database-enforced compare-and-swap of the whole private +//! document keyed by the session's durable identity, its owner, the expected +//! document version and, while a call owns a pin, that exact lease. A +//! zero-row update is an explicit not-committed result; two pins in one +//! session cannot lose each other's update and two store connections cannot +//! both win a stale version; +//! - it separates the durable "prompt send intent" write from the result +//! settlement, so a crash can never silently re-run a prompt; +//! - it settles the call and releases the pin lease in one durable write; +//! - it only reports `completed` after the peer returned `end_turn` *and* the +//! supervisor published confirmed process cleanup. +//! +//! The external harness session is created once per `(session, harness)` and +//! restored afterwards. A pin whose remote state is unknown (a create that may +//! have run without a persisted ID, or a prompt that may have run without a +//! settlement) is never rebuilt or continued automatically. +//! +//! Concurrency: the in-process per-pin gate only turns a same-pin collision +//! into an immediate `busy`; it is not the authority. Ownership is the durable +//! lease, and the storage transaction's conditional update is what makes a +//! competing writer fail with an explicit not-committed result. The policy then +//! re-reads the authoritative document and retries its own mutation. +//! +//! Run facts come from the gateway's live run: the retained workspace +//! authority, the run's cancellation root, the admitted deadline and the sealed +//! reviewer. Session display metadata and caller-supplied replacements are +//! never used as authority. A durable lease left behind by another call is only +//! reclaimed after the store's own run/restart recovery proves that the owning +//! run reached a terminal state; an idle local gate, a fresh store connection or +//! an elapsed lease clock is not ownership evidence. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::OsString; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::sync::Semaphore; +use tokio::time::Instant; + +use crate::acp::{AcpDelegationError, AcpDelegationLaunch, AcpStopReason, DelegatedAcpClient}; +use crate::config_file::{ + AcpHarnessSettings, ConfigFile, MAX_ACP_HARNESS_ARGUMENT_BYTES, MAX_ACP_HARNESS_ARGUMENTS, + MAX_ACP_HARNESSES, +}; +use crate::gateway::store::GatewayPersistence; +use crate::runtime::rss_runner::RunCancellation; +use crate::sqlite_storage_rows::sqlite_storage_first_row; + +/// Logical tool name the approval witness is bound to. +pub const DELEGATION_TOOL_NAME: &str = "delegate_acp"; +/// Maximum accepted task bytes. +pub const MAX_TASK_BYTES: usize = 8 * 1024; +/// Maximum accepted peer session ID bytes. +pub const MAX_EXTERNAL_SESSION_ID_BYTES: usize = 1024; +/// Maximum concurrent bindings kept per RSS session. +pub const MAX_BINDINGS_PER_SESSION: usize = 8; +/// Maximum durable call records per session. Records are never pruned while +/// they can still prove replay safety: at the cap a new call is refused. +pub const MAX_CALL_RECORDS: usize = 16; +/// Maximum outstanding approval bindings per session. +pub const MAX_PENDING_APPROVALS: usize = 8; +/// Upper bound of one private delegation document. +const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; +/// Maximum active harness processes across the service; no call waits. +pub const MAX_ACTIVE_PROCESSES: usize = 4; +/// Cap of one delegated run. +pub const DELEGATION_DEADLINE_MS: u64 = 120_000; +/// Bounded approval preview budget. +const MAX_PREVIEW_BYTES: usize = 2048; +/// Metadata key owning every private delegation record in one session. +const METADATA_KEY: &str = "acp_delegation"; +/// Bounded retries of a lost compare-and-swap. +const CAS_ATTEMPTS: usize = 8; + +/// Closed delegation status surface. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AcpDelegationStatus { + Completed, + Busy, + Denied, + Timeout, + Cancelled, + Failed, + Indeterminate, +} + +impl AcpDelegationStatus { + pub const fn as_str(self) -> &'static str { + match self { + Self::Completed => "completed", + Self::Busy => "busy", + Self::Denied => "denied", + Self::Timeout => "timeout", + Self::Cancelled => "cancelled", + Self::Failed => "failed", + Self::Indeterminate => "indeterminate", + } + } +} + +/// One delegated task, exactly as the host typed it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcpDelegationRequest { + pub harness_id: String, + pub task: String, +} + +/// Turn outcome handed back to the main tool loop. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcpDelegationResult { + pub harness_id: String, + pub status: AcpDelegationStatus, + pub text: String, + pub stop_reason: Option, + pub truncated: bool, + pub code: Option<&'static str>, + /// True when the exact call was already settled and this result is the + /// durable replay rather than a new delegation. + pub replayed: bool, +} + +impl AcpDelegationResult { + fn refusal(harness_id: &str, status: AcpDelegationStatus, code: &'static str) -> Self { + Self { + harness_id: harness_id.to_string(), + status, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code), + replayed: false, + } + } + + fn settled( + harness_id: &str, + status: AcpDelegationStatus, + text: String, + stop_reason: Option, + truncated: bool, + code: Option<&'static str>, + replayed: bool, + ) -> Self { + Self { + harness_id: harness_id.to_string(), + status, + text, + stop_reason, + truncated, + code, + replayed, + } + } + + /// Bounded JSON envelope for the tool result path. + pub fn to_json(&self) -> Value { + json!({ + "harness_id": self.harness_id, + "status": self.status.as_str(), + "text": self.text, + "stop_reason": self.stop_reason.map(stop_reason_code), + "truncated": self.truncated, + "code": self.code.unwrap_or(""), + "replayed": self.replayed, + }) + } + + /// The serialized public-boundary envelope, but only when it really fits. + /// `None` means no ACP JSON may be emitted for this budget. + pub fn to_json_within(&self, budget: usize) -> Option { + (envelope_len(self) <= budget).then(|| self.to_json()) + } + + /// Serialized byte length of the public-boundary envelope. + pub fn serialized_envelope_bytes(&self) -> usize { + envelope_len(self) + } +} + +/// Durable approval challenge returned to the approval surface. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcpApprovalChallenge { + pub approval_id: String, + pub preview: String, + pub expires_at_ms: u64, +} + +/// Durable approval witness accepted by [`AcpDelegationPolicy::delegate`]. +/// +/// Only the ID is caller-supplied: every other fact (run, session, call, tool, +/// arguments, decision, deadline) is re-read from the durable approval row. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcpApprovalWitness { + pub approval_id: String, +} + +impl AcpApprovalWitness { + pub fn new(approval_id: impl Into) -> Self { + Self { + approval_id: approval_id.into(), + } + } +} + +/// Retained workspace authority of one live admitted run. +/// +/// The policy only sees the operations it needs to revalidate the exact grant +/// the run was admitted with; it cannot mint, replace or widen an authority. +pub trait AcpWorkspaceAuthority: Send + Sync { + fn check(&self) -> Result<(), &'static str>; + fn revoked(&self) -> bool; + fn canonical_path(&self) -> &str; + fn generation(&self) -> u64; + /// Mutex shared with the production revoke publication. It is only held by + /// the synchronous spawn commit, never across an await. + fn spawn_gate(&self) -> Arc>; + /// Wakeup published once by this exact authority's explicit revocation. + /// + /// `None` means the implementation offers no revocation notification; a + /// started delegation then observes only the run's cancellation root. A + /// `Some` receiver resolves when the authority was already revoked and on + /// every later publication, without polling. + fn revoked_watch(&self) -> Option> { + None + } +} + +/// Authoritative facts of one live run, read from the gateway's admitted run. +/// +/// These are the only inputs used for workspace identity, cancellation, the +/// absolute deadline and the reviewer topology. A caller cannot substitute a +/// different cancellation root, workspace or clock. +#[derive(Clone)] +pub struct AcpRunFacts { + pub session_id: String, + /// The reviewer sealed at admission (`None` means the configured default). + pub reviewer: Option, + pub workspace: Option>, + pub cancellation: RunCancellation, + /// Absolute admitted deadline in wall-clock milliseconds; `0` means the + /// gateway recorded no deadline and only the delegation cap applies. + pub deadline_ms: u64, +} + +/// One manual approval creation routed through the gateway's live approval +/// surface. The surface owns row insertion and the in-memory preview that the +/// HTTP/Telegram decision endpoint requires. +#[derive(Clone, Debug)] +pub struct AcpApprovalRequest { + pub run_id: String, + pub session_id: String, + pub tool_call_id: String, + pub approval_id: String, + pub expires_at_ms: u64, + /// Full submitted task text plus every summary field; never an excerpt. + pub preview: String, +} + +/// The gateway operations the policy needs. Implemented by `AgentService`; a +/// test cannot fabricate a decision because resolution always goes through the +/// production approval endpoints. +pub trait AcpApprovalGateway: Send + Sync { + /// Inserts the pending row and binds the exact preview to the live run. + fn request_manual_approval(&self, request: &AcpApprovalRequest) -> Result<(), &'static str>; + /// Resolver of an already-approved row, only when it names the manual + /// user path (`http-bearer` or `telegram:`) and the run's sealed + /// reviewer still permits a manual decision. + fn manual_approval_resolver( + &self, + run_id: &str, + approval_id: &str, + ) -> Result; + /// Whether the owning run is still live (not terminal, not cancelled). + fn run_active(&self, run_id: &str) -> bool; + /// Authoritative live facts of one run. `None` means the run is unknown to + /// this gateway instance. + fn run_facts(&self, run_id: &str) -> Option; + /// Whether the durable store already records this run as terminal. + /// + /// The gateway's own restart recovery commits an interrupted active run to + /// a terminal state; that durable fact is the ownership evidence used to + /// reclaim a lease left by a previous process. + fn durable_run_terminal(&self, run_id: &str) -> Result; +} + +/// Exact durable identity of one delegation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcpDelegationScope { + pub run_id: String, + pub session_id: String, + pub tool_call_id: String, +} + +/// Why a delegation was refused before any successful settlement. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AcpPolicyRefusal { + Denied(&'static str), + Busy(&'static str), + Failed(&'static str), + TimedOut(&'static str), +} + +impl AcpPolicyRefusal { + pub fn status(self) -> AcpDelegationStatus { + match self { + Self::Denied(_) => AcpDelegationStatus::Denied, + Self::Busy(_) => AcpDelegationStatus::Busy, + Self::Failed(_) => AcpDelegationStatus::Failed, + Self::TimedOut(_) => AcpDelegationStatus::Timeout, + } + } + + pub fn code(self) -> &'static str { + match self { + Self::Denied(code) | Self::Busy(code) | Self::Failed(code) | Self::TimedOut(code) => { + code + } + } + } +} + +/// Test-only fault cut driven at the recovery boundaries. The policy closes +/// the child and then leaves the durable phase where a crash there would. +#[cfg(feature = "workspace-io-fault")] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AcpPolicyFault { + #[default] + None, + /// The durable prepare committed, but the process was never launched. + AfterPrepareBeforeSpawn, + /// `session/new` may have run; the peer ID was never persisted. + AfterSessionCreate, + /// The peer ID is persisted; the prompt send intent was never written. + AfterSessionPersisted, + /// A restore of an already-bound session succeeded, but the prompt send + /// intent was never written. This is a recoverable interruption. + AfterRestoreBeforeIntent, + /// The prompt may have run; no settlement was written. + AfterPromptPublished, + /// The cleanup was confirmed but settlement is deferred to the real + /// supervisor observer instead of the inline report. + DeferToObserver, + /// The cleanup observer ended without any report. + CleanupObserverLost, + /// The cleanup report arrived explicitly unconfirmed. + CleanupUnconfirmed, +} + +struct HarnessLaunch { + command: PathBuf, + arguments: Vec, + /// Immutable identity compared on every later call. + fingerprint: String, +} + +struct PolicyInner { + persistence: Arc, + gateway: Arc, + harnesses: BTreeMap, + allowed_roots: Vec, + max_result_bytes: usize, + quota: Arc, + /// Slots whose cleanup could not be proven. They stay charged for the rest + /// of the service lifetime; the entry owns the permit explicitly. + quarantine: Mutex>, + per_run: Arc>>, + gates: Mutex>>>, + #[cfg(feature = "workspace-io-fault")] + fault: Mutex, + #[cfg(feature = "workspace-io-fault")] + pre_spawn_hook: Mutex>>, + /// Test-only hook at the final commit point: after every async storage + /// read and immediately before the arbitration locks. + #[cfg(feature = "workspace-io-fault")] + commit_hook: Mutex>>, + /// Test-only hook inside the arbitration locks, immediately before the + /// synchronous process creation. + #[cfg(feature = "workspace-io-fault")] + fence_hook: Mutex>>, + /// Test-only one-shot observation immediately before the first CAS attempt. + #[cfg(feature = "workspace-io-fault")] + cas_hook: Mutex>>, + /// Test-only rendezvous: the spawned cleanup observer signals entry and + /// waits for release before settling, so a test can prove ownership while + /// the observer is still holding it. + #[cfg(feature = "workspace-io-fault")] + cleanup_hold: Mutex, Arc)>>, +} + +/// Installed delegation policy. Cloning shares the same durable gates. +#[derive(Clone)] +pub struct AcpDelegationPolicy { + inner: Arc, +} + +impl AcpDelegationPolicy { + /// Builds the immutable launch table from the already validated config. + /// + /// An empty table yields `None`: the capability stays disabled and no + /// entry point is registered. Every entry is also checked as a launchable + /// executable here, before any listener or delegation exists. + pub fn install( + config: &ConfigFile, + persistence: Arc, + gateway: Arc, + ) -> Result, String> { + if config.acp_harnesses.is_empty() { + return Ok(None); + } + if config.acp_harnesses.len() > MAX_ACP_HARNESSES { + return Err("agent acp_harnesses exceeds the configured bound".to_string()); + } + let mut harnesses = BTreeMap::new(); + for harness in &config.acp_harnesses { + let launch = build_launch(harness)?; + harnesses.insert(harness.id.clone(), launch); + } + let max_result_bytes = config + .agent + .max_tool_output_bytes + .min(crate::acp::delegated_client::MAX_RESULT_TEXT_BYTES); + Ok(Some(Self { + inner: Arc::new(PolicyInner { + persistence, + gateway, + harnesses, + allowed_roots: config.workspaces.allowed_roots.clone(), + max_result_bytes, + quota: Arc::new(Semaphore::new(MAX_ACTIVE_PROCESSES)), + quarantine: Mutex::new(Vec::new()), + per_run: Arc::new(Mutex::new(HashSet::new())), + gates: Mutex::new(HashMap::new()), + #[cfg(feature = "workspace-io-fault")] + fault: Mutex::new(AcpPolicyFault::None), + #[cfg(feature = "workspace-io-fault")] + pre_spawn_hook: Mutex::new(None), + #[cfg(feature = "workspace-io-fault")] + commit_hook: Mutex::new(None), + #[cfg(feature = "workspace-io-fault")] + fence_hook: Mutex::new(None), + #[cfg(feature = "workspace-io-fault")] + cas_hook: Mutex::new(None), + #[cfg(feature = "workspace-io-fault")] + cleanup_hold: Mutex::new(None), + }), + })) + } + + /// Configured logical IDs, in stable order. + pub fn harness_ids(&self) -> Vec { + self.inner.harnesses.keys().cloned().collect() + } + + /// Free process slots of the service-wide delegation quota. + pub fn available_processes(&self) -> usize { + self.inner.quota.available_permits() + } + + /// A call whose smallest possible complete result or typed refusal cannot + /// fit the run's tool-output budget can never deliver anything. It is + /// refused before an approval row or a process exists, and the refusal is + /// typed rather than an oversized ACP JSON envelope. + fn require_deliverable_budget(&self, harness_id: &str) -> Result<(), AcpPolicyRefusal> { + if minimum_deliverable_envelope_bytes(harness_id) > self.inner.max_result_bytes { + return Err(AcpPolicyRefusal::Failed("acp_delegation_budget")); + } + Ok(()) + } + + #[cfg(feature = "workspace-io-fault")] + pub fn arm_fault(&self, fault: AcpPolicyFault) { + *self.inner.fault.lock().expect("acp policy fault") = fault; + } + + /// Test-only hook invoked after the durable pre-spawn prepare and before + /// the process is launched, so a cancellation can be observed at the exact + /// last boundary. + #[cfg(feature = "workspace-io-fault")] + pub fn arm_pre_spawn_hook(&self, hook: impl Fn() + Send + Sync + 'static) { + *self + .inner + .pre_spawn_hook + .lock() + .expect("acp pre-spawn hook") = Some(Arc::new(hook)); + } + + /// Test-only hook at the final commit point, after the last async read and + /// before the arbitration locks. + #[cfg(feature = "workspace-io-fault")] + pub fn arm_commit_hook(&self, hook: impl Fn() + Send + Sync + 'static) { + *self.inner.commit_hook.lock().expect("acp commit hook") = Some(Arc::new(hook)); + } + + /// Test-only hook inside the arbitration locks, immediately before the + /// synchronous process creation. + #[cfg(feature = "workspace-io-fault")] + pub fn arm_fence_hook(&self, hook: impl Fn() + Send + Sync + 'static) { + *self.inner.fence_hook.lock().expect("acp fence hook") = Some(Arc::new(hook)); + } + + /// Test-only one-shot hook invoked after the authoritative read and before + /// the first conditional write of one mutation. + #[cfg(feature = "workspace-io-fault")] + pub fn arm_cas_hook(&self, hook: impl Fn() + Send + Sync + 'static) { + *self.inner.cas_hook.lock().expect("acp cas hook") = Some(Arc::new(hook)); + } + + /// Test-only rendezvous around the spawned cleanup settlement. The returned + /// `entered` notification fires once the observer task owns the permit and + /// the proof; `release` lets it continue. + #[cfg(feature = "workspace-io-fault")] + pub fn arm_cleanup_hold( + &self, + entered: Arc, + release: Arc, + ) { + *self.inner.cleanup_hold.lock().expect("acp cleanup hold") = Some((entered, release)); + } + + #[cfg(feature = "workspace-io-fault")] + fn run_cas_hook(&self) { + let hook = self.inner.cas_hook.lock().expect("acp cas hook").take(); + if let Some(hook) = hook { + hook(); + } + } + + #[cfg(feature = "workspace-io-fault")] + fn take_cleanup_fault(&self) -> Option { + let mut fault = self.inner.fault.lock().expect("acp policy fault"); + match *fault { + AcpPolicyFault::CleanupObserverLost | AcpPolicyFault::CleanupUnconfirmed => { + let taken = *fault; + *fault = AcpPolicyFault::None; + Some(taken) + } + _ => None, + } + } + + #[cfg(feature = "workspace-io-fault")] + fn take_fault(&self, expected: AcpPolicyFault) -> bool { + let mut fault = self.inner.fault.lock().expect("acp policy fault"); + if *fault == expected { + *fault = AcpPolicyFault::None; + true + } else { + false + } + } + + #[cfg(feature = "workspace-io-fault")] + fn run_pre_spawn_hook(&self) { + let hook = self + .inner + .pre_spawn_hook + .lock() + .expect("acp pre-spawn hook") + .take(); + if let Some(hook) = hook { + hook(); + } + } + + #[cfg(feature = "workspace-io-fault")] + fn run_commit_hook(&self) { + let hook = self + .inner + .commit_hook + .lock() + .expect("acp commit hook") + .take(); + if let Some(hook) = hook { + hook(); + } + } + + #[cfg(feature = "workspace-io-fault")] + fn take_fence_hook(&self) -> Option> { + self.inner.fence_hook.lock().expect("acp fence hook").take() + } + + /// Durable settlement classification of one call. + /// + /// `NotStarted` means no call record exists at all. A prepared or creating + /// call may already have spawned a process or created a peer session and is + /// therefore `Indeterminate`; `Settled` means the recorded outcome is + /// authoritative. + pub async fn call_settlement( + &self, + session_id: &str, + call_id: &str, + ) -> Result { + let snapshot = self.read_session(session_id).await?; + let doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + Ok(doc + .calls + .get(call_id) + .map(|call| call.phase.settlement()) + .unwrap_or(crate::effects::DelegationSettlement::NotStarted)) + } + + /// Creates the durable pending approval for one exact delegation through + /// the gateway's real manual approval surface. + /// + /// The preview repeats the complete submitted task and every summary field; + /// it is refused before a row exists when it cannot fit the approval + /// surface's bounded preview. + pub async fn request_approval( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + ) -> Result { + validate_request(request)?; + let Some(launch) = self.inner.harnesses.get(&request.harness_id) else { + return Err(AcpPolicyRefusal::Denied("acp_harness_unknown")); + }; + self.require_deliverable_budget(&request.harness_id)?; + let facts = self + .inner + .gateway + .run_facts(&scope.run_id) + .ok_or(AcpPolicyRefusal::Denied("acp_run_inactive"))?; + if facts.session_id != scope.session_id { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + if facts.cancellation.requested().is_some() { + return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")); + } + if !self.inner.gateway.run_active(&scope.run_id) { + return Err(AcpPolicyRefusal::Denied("acp_run_inactive")); + } + let snapshot = self.read_session(&scope.session_id).await?; + let workspace = admitted_workspace(&facts, &self.inner.allowed_roots)?; + let doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let pin = doc.pins.get(&request.harness_id); + let pin_version = pin.map(|pin| pin.version).unwrap_or(0); + let new_session = pin + .and_then(|pin| pin.external_session_id.as_ref()) + .is_none(); + let approval_id = approval_id(&scope.run_id, &scope.tool_call_id)?; + let now_ms = crate::domain::timestamp(); + let expires_at_ms = effective_deadline_ms(run_deadline_ms(&facts), now_ms); + if expires_at_ms <= now_ms { + return Err(AcpPolicyRefusal::Denied("acp_delegation_deadline")); + } + let preview = build_preview( + &request.harness_id, + &workspace.path, + new_session, + &request.task, + )?; + let binding = ApprovalBinding { + run_id: scope.run_id.clone(), + session_id: scope.session_id.clone(), + session_identity: snapshot.identity(), + tool_call_id: scope.tool_call_id.clone(), + harness_id: request.harness_id.clone(), + task: request.task.clone(), + launch: launch.fingerprint.clone(), + workspace: workspace.path.clone(), + workspace_generation: workspace.generation, + owner: snapshot.owner.clone(), + toolset_hash: snapshot.toolset_hash.clone(), + pin_version, + new_session, + expires_at_ms, + }; + let key = approval_id.clone(); + let stored = binding.clone(); + let approval_identity = snapshot.identity(); + self.mutate( + &scope.session_id, + &approval_identity, + move |doc, snapshot| { + if snapshot.owner != stored.owner { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + if snapshot.identity() != stored.session_identity { + return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); + } + doc.expire_approvals(now_ms); + if let Some(existing) = doc.pending_approvals.get(&key) { + return if existing == &stored { + Ok(None) + } else { + Err(AcpPolicyRefusal::Denied("acp_approval_stale")) + }; + } + if doc.pending_approvals.len() >= MAX_PENDING_APPROVALS { + return Err(AcpPolicyRefusal::Failed("acp_approval_capacity")); + } + doc.pending_approvals.insert(key.clone(), stored.clone()); + Ok(None) + }, + ) + .await?; + let gateway = self.inner.gateway.clone(); + let surface_request = AcpApprovalRequest { + run_id: scope.run_id.clone(), + session_id: scope.session_id.clone(), + tool_call_id: scope.tool_call_id.clone(), + approval_id: approval_id.clone(), + expires_at_ms, + preview: preview.clone(), + }; + match blocking_gateway(move || gateway.request_manual_approval(&surface_request)).await { + Ok(()) => Ok(AcpApprovalChallenge { + approval_id, + preview, + expires_at_ms, + }), + Err(refusal) => Err(refusal), + } + } + + /// Executes one approved delegation. + /// + /// The call runs on its own task and owns its charged slot, per-run + /// admission and pin gate from before the spawn commit. Dropping this + /// future detaches the work: a call that may already have started keeps + /// its capacity until real cleanup settles it, and one that has not + /// reached the process-creation boundary settles as cancelled instead of + /// spawning for an absent caller. + /// + /// Every refusal before the spawn point returns without creating a process. + pub async fn delegate( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + witness: &AcpApprovalWitness, + ) -> AcpDelegationResult { + let harness_id = request.harness_id.clone(); + if self.require_deliverable_budget(&harness_id).is_err() { + return AcpDelegationResult::refusal( + &harness_id, + AcpDelegationStatus::Failed, + "acp_delegation_budget", + ); + } + let abandoned = Arc::new(AtomicBool::new(false)); + // Dropping this guard marks the caller as gone. It must exist before + // the await: a call that has not yet passed the final launch predicate + // then settles without spawning, while one that already did keeps + // running under its own ownership. + let _abandon_on_drop = AbandonOnDrop(Arc::clone(&abandoned)); + let policy = self.clone(); + let scope = scope.clone(); + let request = request.clone(); + let witness = witness.clone(); + let joined = tokio::spawn(async move { + policy + .delegate_inner(&scope, &request, &witness, &abandoned) + .await + }) + .await; + let result = match joined { + Ok(Ok(result)) => result, + Ok(Err(refusal)) => { + AcpDelegationResult::refusal(&harness_id, refusal.status(), refusal.code()) + } + Err(_) => AcpDelegationResult::refusal( + &harness_id, + AcpDelegationStatus::Indeterminate, + "acp_session_indeterminate", + ), + }; + bounded_result(result, self.inner.max_result_bytes) + } + + async fn delegate_inner( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + witness: &AcpApprovalWitness, + abandoned: &Arc, + ) -> Result { + validate_request(request)?; + let Some(launch) = self.inner.harnesses.get(&request.harness_id) else { + return Err(AcpPolicyRefusal::Denied("acp_harness_unknown")); + }; + self.require_deliverable_budget(&request.harness_id)?; + let facts = self + .inner + .gateway + .run_facts(&scope.run_id) + .ok_or(AcpPolicyRefusal::Denied("acp_run_inactive"))?; + if facts.session_id != scope.session_id { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + // A settled call is a durable replay, not a new delegation: it must + // remain readable while this run's admission slot is handed to a + // cleanup owner. + let initial = self.read_session(&scope.session_id).await?; + let initial_identity = initial.identity(); + let initial_doc = PinDocument::from_metadata(initial.metadata.as_deref()); + if let Some(existing) = initial_doc.calls.get(&scope.tool_call_id) { + if existing.phase == CallPhase::Settled { + let outcome = existing + .outcome + .clone() + .ok_or(AcpPolicyRefusal::Failed("acp_call_record_invalid"))?; + self.check_live_run(scope, &facts)?; + self.verify_replay(existing, scope, request, witness, &initial, &facts, launch) + .await?; + return Ok(outcome.to_result(&request.harness_id, true)); + } + return Err(AcpPolicyRefusal::Denied("acp_call_indeterminate")); + } + let gate = self.pin_gate(&scope.session_id, &request.harness_id); + // A conflicting call is refused immediately: there is no wait queue. + let _pin_guard = match gate.try_lock() { + Ok(guard) => guard, + Err(_) => return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")), + }; + // One delegation per run, also refused rather than queued. + { + let mut per_run = self.inner.per_run.lock().expect("acp per-run gate"); + if !per_run.insert(scope.run_id.clone()) { + return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + } + } + let run_guard = RunGate { + runs: Arc::clone(&self.inner.per_run), + run_id: scope.run_id.clone(), + }; + // A competing call must fail at the run gate, before taking the + // cancellation mutex held by the owner during spawn arbitration. + self.check_live_run(scope, &facts)?; + let cancellation = facts.cancellation.clone(); + + let mut snapshot = self.read_session(&scope.session_id).await?; + if snapshot.identity() != initial_identity { + return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); + } + let original_identity = initial_identity; + let workspace = admitted_workspace(&facts, &self.inner.allowed_roots)?; + let doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + + if let Some(existing) = doc.calls.get(&scope.tool_call_id) { + if existing.phase == CallPhase::Settled { + let outcome = existing + .outcome + .clone() + .ok_or(AcpPolicyRefusal::Failed("acp_call_record_invalid"))?; + self.verify_replay(existing, scope, request, witness, &snapshot, &facts, launch) + .await?; + return Ok(outcome.to_result(&request.harness_id, true)); + } + // The exact call already reached an unrecoverable phase: never + // restart it, and never let a second delivery look like a retry. + return Err(AcpPolicyRefusal::Denied("acp_call_indeterminate")); + } + + let pin_version = doc + .pins + .get(&request.harness_id) + .map(|pin| pin.version) + .unwrap_or(0); + // A replay of this exact settled call was already returned above and + // never spawns. Pin ownership and takeover are decided below. + let mut stale_call: Option = None; + if let Some(pin) = doc.pins.get(&request.harness_id) { + if pin.owner != snapshot.owner + || pin.workspace != workspace.path + || pin.workspace_generation != workspace.generation + || pin.launch != launch.fingerprint + { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + if pin.phase.blocks_new_calls() { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + if let Some(lease) = pin.active.as_ref() { + // A free in-process gate proves nothing about another process. + // Reclaim only a call whose own run the durable store already + // records as terminal, and only when its phase means the peer + // session may be restored without replaying a prompt. + if lease.call_id == scope.tool_call_id { + return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + } + let reclaimable = !pin.cleanup_pending + && doc.calls.get(&lease.call_id).is_some_and(|call| { + call.cleanup_confirmed + && matches!(call.phase, CallPhase::SessionBound | CallPhase::Restoring) + }); + if !reclaimable { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + let owned_run = lease.run_id.clone(); + let gateway = self.inner.gateway.clone(); + let terminal = + blocking_gateway(move || gateway.durable_run_terminal(&owned_run)).await?; + if !terminal { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + stale_call = Some(lease.call_id.clone()); + } + } + + // The approval is revalidated against the current immutable config, the + // current pin version, the admitted workspace and the exact call. + self.validate_witness(witness, scope, request, &snapshot, &facts) + .await?; + if pin_version + != doc + .pins + .get(&request.harness_id) + .map(|pin| pin.version) + .unwrap_or(0) + { + return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); + } + let deadline = frozen_deadline(&facts); + if Instant::now() >= deadline { + return Err(AcpPolicyRefusal::TimedOut("acp_delegation_deadline")); + } + let permit = self + .inner + .quota + .clone() + .try_acquire_owned() + .map_err(|_| AcpPolicyRefusal::Busy("acp_delegation_capacity"))?; + + // Acquiring the permit is a real boundary: re-read the authoritative + // session and revalidate the run, approval and deadline before the + // durable preparation. + snapshot = self.read_session(&scope.session_id).await?; + if snapshot.identity() != original_identity { + return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); + } + let workspace = admitted_workspace(&facts, &self.inner.allowed_roots)?; + let doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let current_pin_version = doc + .pins + .get(&request.harness_id) + .map(|pin| pin.version) + .unwrap_or(0); + if current_pin_version != pin_version { + return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); + } + if !self.inner.gateway.run_active(&scope.run_id) { + return Err(AcpPolicyRefusal::Denied("acp_run_inactive")); + } + if cancellation.requested().is_some() { + return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")); + } + let witness_facts = self + .validate_witness(witness, scope, request, &snapshot, &facts) + .await?; + if Instant::now() >= deadline { + return Err(AcpPolicyRefusal::Failed("acp_delegation_deadline")); + } + + let binding = ApprovalBinding { + run_id: scope.run_id.clone(), + session_id: scope.session_id.clone(), + session_identity: snapshot.identity(), + tool_call_id: scope.tool_call_id.clone(), + harness_id: request.harness_id.clone(), + task: request.task.clone(), + launch: launch.fingerprint.clone(), + workspace: workspace.path.clone(), + workspace_generation: workspace.generation, + owner: snapshot.owner.clone(), + toolset_hash: snapshot.toolset_hash.clone(), + pin_version, + new_session: doc + .pins + .get(&request.harness_id) + .and_then(|pin| pin.external_session_id.as_ref()) + .is_none(), + expires_at_ms: witness_facts.expires_at_ms, + }; + + // Durable preparation: consume the approval binding, insert the + // prepared call and take the lease in one conditional write. + let call = AcpCallRecord { + call_id: scope.tool_call_id.clone(), + run_id: scope.run_id.clone(), + session_identity: original_identity.clone(), + harness_id: request.harness_id.clone(), + approval_id: witness.approval_id.clone(), + approval_resolver: Some(witness_facts.resolver.clone()), + task: request.task.clone(), + launch: launch.fingerprint.clone(), + workspace: workspace.path.clone(), + workspace_generation: workspace.generation, + owner: snapshot.owner.clone(), + toolset_hash: snapshot.toolset_hash.clone(), + pin_version_at_start: pin_version, + phase: CallPhase::Prepared, + cleanup_confirmed: false, + outcome: None, + prompt_intent_at_ms: 0, + }; + let expected_binding = binding.clone(); + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let approval_key = witness.approval_id.clone(); + let owner = snapshot.owner.clone(); + let run_id = scope.run_id.clone(); + let prepare_workspace = workspace.clone(); + let prepare_identity = original_identity.clone(); + let (prepared_snapshot, _) = self + .mutate( + &scope.session_id, + &original_identity, + move |doc, snapshot| { + if snapshot.owner != owner { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + if snapshot.identity() != prepare_identity { + return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); + } + if !doc.pins.contains_key(&harness_id) + && doc.pins.len() >= MAX_BINDINGS_PER_SESSION + { + return Err(AcpPolicyRefusal::Failed("acp_delegation_retention")); + } + if doc.calls.len() >= MAX_CALL_RECORDS { + return Err(AcpPolicyRefusal::Failed("acp_delegation_retention")); + } + let pin = doc.pins.entry(harness_id.clone()).or_insert_with(|| { + AcpPin::new( + owner.clone(), + &prepare_workspace, + launch.fingerprint.clone(), + ) + }); + if pin.owner != owner + || pin.workspace != prepare_workspace.path + || pin.workspace_generation != prepare_workspace.generation + || pin.launch != launch.fingerprint + { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + if pin.phase.blocks_new_calls() { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + let mut lease_guard = None; + let doc_calls = &mut doc.calls; + if let Some(active) = pin.active.clone() { + // The takeover must name the exact interruption proven + // above; a newer owner is never displaced by this write. + if stale_call.as_deref() != Some(active.call_id.as_str()) + || pin.cleanup_pending + { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + let Some(interrupted) = doc_calls.get_mut(&active.call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + }; + if !matches!( + interrupted.phase, + CallPhase::SessionBound | CallPhase::Restoring + ) { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + // The old call is settled in the same durable write that + // reserves the new one; it is never replayed. + interrupted.phase = CallPhase::Settled; + interrupted.outcome = Some(SettledOutcome { + status: AcpDelegationStatus::Indeterminate, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_call_interrupted".to_string()), + }); + lease_guard = Some((harness_id.clone(), active.call_id.clone())); + } else if stale_call.is_some() { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + let Some(binding) = doc.pending_approvals.get(&approval_key) else { + return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); + }; + if binding != &expected_binding || binding.pin_version != pin.version { + return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); + } + if binding.expires_at_ms <= crate::domain::timestamp() { + return Err(AcpPolicyRefusal::Denied("acp_approval_expired")); + } + // Consumption and preparation are the same durable write. + doc.pending_approvals.remove(&approval_key); + doc_calls.insert(call_id.clone(), call.clone()); + pin.active = Some(ActiveLease { + call_id: call_id.clone(), + run_id: run_id.clone(), + expires_at_ms: crate::domain::timestamp() + DELEGATION_DEADLINE_MS, + }); + pin.cleanup_pending = false; + pin.version += 1; + Ok(lease_guard) + }, + ) + .await?; + snapshot = prepared_snapshot; + let permit = CallPermit::new( + Arc::clone(&self.inner), + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + run_guard, + permit, + ); + + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterPrepareBeforeSpawn) { + // A crash here leaves the exact call `prepared` with its lease. + // It is never reported as not started and never re-executed. + self.quarantine_ownership(permit); + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + + // The durable write is authoritative; confirm the lease that will + // guard the process and reject a concurrently replaced document. + if !self.lease_names(&snapshot, &request.harness_id, &scope.tool_call_id) { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + + // Last boundary before spawn. The test hook lands exactly here so a + // stop, a revocation or an elapsed clock can be applied before the + // arbitration below. + #[cfg(feature = "workspace-io-fault")] + self.run_pre_spawn_hook(); + + // Fresh authoritative reads: the durable session identity and lease, + // then the manual witness. These are the last storage waits. + let fresh = self.read_session(&scope.session_id).await?; + if fresh.identity() != original_identity { + return self + .abort_pre_spawn( + scope, + request, + &original_identity, + fresh, + permit, + AcpDelegationStatus::Denied, + "acp_session_identity_changed", + ) + .await; + } + if !self.lease_names(&fresh, &request.harness_id, &scope.tool_call_id) { + return self + .abort_pre_spawn( + scope, + request, + &original_identity, + fresh, + permit, + AcpDelegationStatus::Failed, + "acp_storage_conflict", + ) + .await; + } + if let Err(refusal) = self + .validate_witness(witness, scope, request, &fresh, &facts) + .await + { + return self + .abort_pre_spawn( + scope, + request, + &original_identity, + fresh, + permit, + refusal.status(), + refusal.code(), + ) + .await; + } + // Re-read the live run facts after the last storage wait. The + // cancellation root, reviewer, workspace authority and admitted + // deadline are the gateway's, never the caller's. + let Some(live) = self.inner.gateway.run_facts(&scope.run_id) else { + return self + .abort_pre_spawn( + scope, + request, + &original_identity, + fresh, + permit, + AcpDelegationStatus::Denied, + "acp_run_inactive", + ) + .await; + }; + if live.session_id != facts.session_id || live.reviewer != facts.reviewer { + return self + .abort_pre_spawn( + scope, + request, + &original_identity, + fresh, + permit, + AcpDelegationStatus::Denied, + "acp_binding_mismatch", + ) + .await; + } + // The frozen deadline stays authoritative: the live read above can + // never extend it. + snapshot = fresh; + + // Final commit point. Every asynchronous storage read is finished; + // the hook lands exactly before the arbitration locks. + #[cfg(feature = "workspace-io-fault")] + self.run_commit_hook(); + + let launch_handle = AcpDelegationLaunch::new( + launch.command.clone(), + launch.arguments.clone(), + workspace.path.clone(), + ) + .map_err(|_| AcpPolicyRefusal::Failed("acp_delegation_invalid_launch"))?; + + let spawned = match self + .commit_spawn( + scope, + request, + witness, + &original_identity, + &facts, + &workspace, + launch_handle, + deadline, + Arc::clone(abandoned), + ) + .await + { + Ok(Ok(client)) => client, + Ok(Err((status, code))) => { + return self + .abort_pre_spawn( + scope, + request, + &original_identity, + snapshot, + permit, + status, + code, + ) + .await; + } + Err(refusal) => return Err(refusal), + }; + + self.run_call( + scope, + request, + &original_identity, + spawned, + cancellation.clone(), + facts.workspace.clone(), + &mut snapshot, + permit, + ) + .await + } + + fn check_live_run( + &self, + scope: &AcpDelegationScope, + facts: &AcpRunFacts, + ) -> Result<(), AcpPolicyRefusal> { + if facts.cancellation.requested().is_some() { + return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")); + } + if !self.inner.gateway.run_active(&scope.run_id) { + return Err(AcpPolicyRefusal::Denied("acp_run_inactive")); + } + Ok(()) + } + + /// The single synchronous spawn commit. + /// + /// The durable session identity, the approval row and the delegation lease + /// are re-read while holding the same gates their writers use, then the + /// process is created without releasing them. A stop, revoke, session + /// replacement or expired approval that already happened is therefore + /// observed here with zero spawns; one that happens afterwards waits until + /// the process exists and follows the normal cancel/cleanup path. + #[allow(clippy::too_many_arguments)] + async fn commit_spawn( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + witness: &AcpApprovalWitness, + identity: &SessionIdentity, + facts: &AcpRunFacts, + workspace: &AdmittedWorkspace, + launch: AcpDelegationLaunch, + deadline: Instant, + abandoned: Arc, + ) -> Result< + Result, + AcpPolicyRefusal, + > { + let persistence = Arc::clone(&self.inner.persistence); + let gateway = Arc::clone(&self.inner.gateway); + let cancellation = facts.cancellation.clone(); + let authority = facts.workspace.clone(); + let session_id = scope.session_id.clone(); + let run_id = scope.run_id.clone(); + let call_id = scope.tool_call_id.clone(); + let harness_id = request.harness_id.clone(); + let approval_id = witness.approval_id.clone(); + let expected_identity = identity.clone(); + let expected_path = workspace.path.clone(); + let expected_generation = workspace.generation; + #[cfg(feature = "workspace-io-fault")] + let fence_hook = self.take_fence_hook(); + + let joined = tokio::task::spawn_blocking(move || { + let fence = persistence.session_fence(); + let _fence = fence + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let run_arbitration = cancellation.spawn_arbitration(); + let Some(authority) = authority.as_ref() else { + return Ok(Err((AcpDelegationStatus::Denied, "acp_workspace_unbound"))); + }; + let workspace_gate = authority.spawn_gate(); + let _workspace = workspace_gate + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + // Re-read the exact original row; a replacement is never written + // or spawned from. + let snapshot = match persistence.session_get(&session_id) { + Ok(value) => match first_row(&value).and_then(SessionSnapshot::from_row) { + Some(snapshot) => snapshot, + None => { + return Ok(Err((AcpDelegationStatus::Denied, "acp_session_unknown"))); + } + }, + Err(_) => return Err("acp_storage_unavailable"), + }; + if snapshot.identity() != expected_identity { + return Ok(Err(( + AcpDelegationStatus::Denied, + "acp_session_identity_changed", + ))); + } + if !PinDocument::from_metadata(snapshot.metadata.as_deref()) + .pins + .get(&harness_id) + .and_then(|pin| pin.active.as_ref()) + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Ok(Err((AcpDelegationStatus::Failed, "acp_storage_conflict"))); + } + let approval = match persistence.approval_get(&approval_id) { + Ok(value) => value, + Err(_) => return Err("acp_storage_unavailable"), + }; + let Some(row) = first_row(&approval) else { + return Ok(Err((AcpDelegationStatus::Denied, "acp_approval_not_found"))); + }; + let field = |index: usize| row.get(index).and_then(Value::as_str); + if field(0) != Some(approval_id.as_str()) + || field(1) != Some(run_id.as_str()) + || field(2) != Some(session_id.as_str()) + || field(3) != Some(call_id.as_str()) + || field(4) != Some(DELEGATION_TOOL_NAME) + || field(7) != Some("approved") + || row.get(9).and_then(Value::as_i64) != Some(1) + { + return Ok(Err((AcpDelegationStatus::Denied, "acp_approval_mismatch"))); + } + if !matches!(field(6).unwrap_or_default(), "execute" | "privileged") { + return Ok(Err((AcpDelegationStatus::Denied, "acp_approval_risk"))); + } + let expires_at_ms = row + .get(11) + .and_then(Value::as_i64) + .unwrap_or_default() + .max(0) as u64; + if expires_at_ms != 0 && expires_at_ms <= crate::domain::timestamp() { + return Ok(Err((AcpDelegationStatus::Denied, "acp_approval_expired"))); + } + // Resolver eligibility goes through the production gateway method, + // which checks the sealed reviewer topology and the manual user + // surface again at commit time. + if gateway + .manual_approval_resolver(&run_id, &approval_id) + .is_err() + { + return Ok(Err((AcpDelegationStatus::Denied, "acp_approval_not_user"))); + } + // Arbitration order: stop, frozen deadline, run liveness, then + // workspace revoke. + if run_arbitration.requested().is_some() { + return Ok(Err(( + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + ))); + } + if Instant::now() >= deadline { + return Ok(Err(( + AcpDelegationStatus::Timeout, + "acp_delegation_deadline", + ))); + } + if authority.revoked() || authority.check().is_err() { + return Ok(Err((AcpDelegationStatus::Denied, "acp_workspace_invalid"))); + } + if authority.canonical_path() != expected_path + || authority.generation() != expected_generation + { + return Ok(Err((AcpDelegationStatus::Denied, "acp_binding_mismatch"))); + } + #[cfg(feature = "workspace-io-fault")] + if let Some(hook) = fence_hook { + hook(); + } + // The one process creation is guarded by the caller's final + // predicate, evaluated here after every preparation step and + // immediately before `spawn(2)`: the frozen run deadline, the real + // durable approval expiry and an abandoned caller are all observed + // at the true boundary. Any observed expiry is zero spawn. + let final_guard = move || { + if abandoned.load(Ordering::Acquire) { + return Err(crate::acp::delegated_client::AcpLaunchVeto::new( + "acp_delegation_cancelled", + )); + } + if Instant::now() >= deadline { + return Err(crate::acp::delegated_client::AcpLaunchVeto::new( + "acp_delegation_deadline", + )); + } + if expires_at_ms != 0 && crate::domain::timestamp() >= expires_at_ms { + return Err(crate::acp::delegated_client::AcpLaunchVeto::new( + "acp_approval_expired", + )); + } + Ok(()) + }; + match crate::acp::DelegatedAcpClient::spawn_preconditioned( + launch, + deadline, + final_guard, + ) { + Ok(client) => Ok(Ok(client)), + Err(veto) => { + let code = veto.code(); + let status = match code { + "acp_delegation_deadline" => AcpDelegationStatus::Timeout, + "acp_approval_expired" => AcpDelegationStatus::Denied, + "acp_delegation_cancelled" => AcpDelegationStatus::Cancelled, + _ => AcpDelegationStatus::Failed, + }; + Ok(Err((status, code))) + } + } + }) + .await + .map_err(|_| AcpPolicyRefusal::Failed("acp_delegation_spawn_failed"))?; + joined.map_err(AcpPolicyRefusal::Failed) + } + + /// Settles a prepared call that never spawned a process. + #[allow(clippy::too_many_arguments)] + async fn abort_pre_spawn( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: SessionSnapshot, + permit: CallPermit, + status: AcpDelegationStatus, + code: &'static str, + ) -> Result { + let mut snapshot = snapshot; + let outcome = SettledOutcome { + status, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code.to_string()), + }; + match self + .settle_outcome(scope, request, identity, &mut snapshot, outcome, true, true) + .await + { + Ok(result) => { + permit.release(); + Ok(result) + } + Err(_) => { + self.quarantine_ownership(permit); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } + } + + /// Drives one already-spawned connection from handshake to settlement. + #[allow(clippy::too_many_arguments)] + async fn run_call( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + mut client: DelegatedAcpClient, + cancellation: crate::runtime::rss_runner::RunCancellation, + workspace: Option>, + snapshot: &mut SessionSnapshot, + permit: CallPermit, + ) -> Result { + let observer = client.cleanup_observer(); + let mut revocation = workspace.and_then(|authority| authority.revoked_watch()); + + let capabilities = { + let future = client.initialize(); + tokio::pin!(future); + tokio::select! { + biased; + interruption = delegation_interrupted(&cancellation, &mut revocation) => Err(interruption), + result = &mut future => Ok(result), + } + }; + let capabilities = match capabilities { + Err(interruption) => { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + interruption.status(), + interruption.code(), + true, + ) + .await; + } + Ok(Ok(capabilities)) => capabilities, + Ok(Err(error)) => { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + error.code(), + true, + ) + .await; + } + }; + + let bound_id = PinDocument::from_metadata(snapshot.metadata.as_deref()) + .pins + .get(&request.harness_id) + .and_then(|pin| pin.external_session_id.clone()); + + let session_id = match bound_id { + Some(existing) => { + if capabilities.restore_method().is_none() { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + "acp_session_restore_unsupported", + true, + ) + .await; + } + // Record the restore attempt durably before it is issued: an + // interruption here is an explicit recoverable state, distinct + // from an unknown `session/new`. + if self + .mark_session_restoring(scope, request, identity, snapshot) + .await + .is_err() + { + // No restore or prompt was sent. Preserve the known ID only + // when cleanup is proven and this exact lease settles. + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + "acp_storage_not_committed", + true, + ) + .await; + } + let restored = { + let future = client.restore_session(existing.clone()); + tokio::pin!(future); + tokio::select! { + biased; + interruption = delegation_interrupted(&cancellation, &mut revocation) => Err(interruption), + result = &mut future => Ok(result), + } + }; + match restored { + Err(interruption) => { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + interruption.status(), + interruption.code(), + true, + ) + .await; + } + Ok(Err(error)) => { + // A failed restore never falls back to `session/new`. + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + error.code(), + true, + ) + .await; + } + Ok(Ok(_)) => { + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterRestoreBeforeIntent) { + let report = client.close().await; + if report.cleanup_confirmed + && self + .mark_cleanup_confirmed(scope, request, identity, snapshot) + .await + .is_ok() + { + permit.release(); + } else { + self.quarantine_ownership(permit); + } + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + existing + } + } + } + None => { + let marked = self + .mark_session_creating(scope, request, identity, snapshot) + .await; + if marked.is_err() { + return self + .abort_unknown_state( + scope, request, identity, snapshot, client, observer, permit, + ) + .await; + } + let created = { + let future = client.new_session(); + tokio::pin!(future); + tokio::select! { + biased; + interruption = delegation_interrupted(&cancellation, &mut revocation) => Err(interruption), + result = &mut future => Ok(result), + } + }; + let created = match created { + Err(interruption) => { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + interruption.status(), + interruption.code(), + false, + ) + .await; + } + Ok(Ok(created)) => created, + Ok(Err(error)) => { + return self + .fail_created_unknown( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + error.code(), + ) + .await; + } + }; + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterSessionCreate) { + let _ = client.close().await; + // The pin and call stay `creating`: the ID was never + // persisted. The permit stays charged because cleanup was + // not observed here. + self.quarantine_ownership(permit); + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + if created.is_empty() || created.len() > MAX_EXTERNAL_SESSION_ID_BYTES { + return self + .reject_external_id( + scope, request, identity, snapshot, client, observer, permit, + ) + .await; + } + if let Err(_error) = self + .persist_bound_id(scope, request, identity, snapshot, &created) + .await + { + return self + .abort_unknown_state( + scope, request, identity, snapshot, client, observer, permit, + ) + .await; + } + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterSessionPersisted) { + let report = client.close().await; + if report.cleanup_confirmed + && self + .mark_cleanup_confirmed(scope, request, identity, snapshot) + .await + .is_ok() + { + permit.release(); + } else { + self.quarantine_ownership(permit); + } + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + created + } + }; + + if let Some(interruption) = current_interruption(&cancellation, &revocation) { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + interruption.status(), + interruption.code(), + true, + ) + .await; + } + + // Durable prompt-send intent, strictly after the bound ID write. + if let Err(_error) = self + .write_prompt_intent(scope, request, identity, snapshot) + .await + { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + "acp_storage_not_committed", + true, + ) + .await; + } + // The intent is durable, so this call can no longer be treated as a + // zero-send call even if cancellation wins the next poll. + if let Some(interruption) = current_interruption(&cancellation, &revocation) { + return self + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + interruption.status(), + interruption.code(), + false, + ) + .await; + } + + let prompt_outcome = { + let prompt = client.prompt(&session_id, &request.task); + tokio::pin!(prompt); + tokio::select! { + biased; + interruption = delegation_interrupted(&cancellation, &mut revocation) => PromptWait::Interrupted(interruption), + result = &mut prompt => PromptWait::Done(result), + } + }; + + let report = client.close().await; + // Any outcome whose cleanup is not proven leaves the prompt result + // unknown; only a positive cleanup report may release the slot. + #[cfg(feature = "workspace-io-fault")] + if let Some(fault) = self.take_cleanup_fault() { + let expected_version = self + .current_pin_version(&scope.session_id, &request.harness_id) + .await + .unwrap_or(u64::MAX); + let (proof, code) = match fault { + AcpPolicyFault::CleanupObserverLost => { + (CleanupProof::Lost, "acp_cleanup_unverified") + } + _ => ( + CleanupProof::Unconfirmed(unconfirmed_report()), + "acp_cleanup_unverified", + ), + }; + let released = self + .settle_after_cleanup( + scope, + &request.harness_id, + identity, + proof, + Some(permit), + expected_version, + ) + .await; + let _ = released; + return Ok(AcpDelegationResult::refusal( + &request.harness_id, + AcpDelegationStatus::Indeterminate, + code, + )); + } + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::DeferToObserver) { + return self + .hold_until_cleanup(scope, request, identity, observer, permit) + .await; + } + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, identity, observer, permit) + .await; + } + + let (settled, keeps_binding) = match prompt_outcome { + PromptWait::Done(Ok(result)) => { + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterPromptPublished) { + let _ = self + .mark_pin_unknown(scope, request, identity, snapshot) + .await; + permit.release(); + return Err(AcpPolicyRefusal::Failed("acp_prompt_indeterminate")); + } + let mut text = result.text; + let mut truncated = result.truncated; + clamp_text(&mut text, self.inner.max_result_bytes, &mut truncated); + let (status, code) = match result.stop_reason { + AcpStopReason::EndTurn => (AcpDelegationStatus::Completed, None), + AcpStopReason::Cancelled => ( + AcpDelegationStatus::Cancelled, + Some("acp_delegation_cancelled"), + ), + _ => (AcpDelegationStatus::Failed, Some("acp_stop_reason")), + }; + ( + SettledOutcome { + status, + text, + stop_reason: Some(stop_reason_code(result.stop_reason).to_string()), + truncated, + code: code.map(str::to_string), + }, + true, + ) + } + PromptWait::Done(Err(AcpDelegationError::DeadlineExceeded)) => ( + SettledOutcome { + status: AcpDelegationStatus::Timeout, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_delegation_deadline".to_string()), + }, + false, + ), + PromptWait::Interrupted(DelegationInterruption::Revoked) => ( + SettledOutcome { + status: AcpDelegationStatus::Denied, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_workspace_invalid".to_string()), + }, + false, + ), + PromptWait::Done(Err(AcpDelegationError::Cancelled)) + | PromptWait::Interrupted(DelegationInterruption::Cancelled) => ( + SettledOutcome { + status: AcpDelegationStatus::Cancelled, + text: String::new(), + stop_reason: Some(stop_reason_code(AcpStopReason::Cancelled).to_string()), + truncated: false, + code: Some("acp_delegation_cancelled".to_string()), + }, + false, + ), + PromptWait::Done(Err(error)) => ( + SettledOutcome { + status: AcpDelegationStatus::Failed, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(error.code().to_string()), + }, + false, + ), + }; + match self + .settle_outcome( + scope, + request, + identity, + snapshot, + settled, + keeps_binding, + true, + ) + .await + { + Ok(result) => { + permit.release(); + Ok(result) + } + Err(_) => { + self.quarantine_ownership(permit); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } + } + + /// Closes a client whose prompt was never published and settles the call. + #[allow(clippy::too_many_arguments)] + async fn unsent_close( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: CallPermit, + status: AcpDelegationStatus, + code: &'static str, + keeps_binding: bool, + ) -> Result { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, identity, observer, permit) + .await; + } + let outcome = SettledOutcome { + status, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code.to_string()), + }; + match self + .settle_outcome( + scope, + request, + identity, + snapshot, + outcome, + keeps_binding, + true, + ) + .await + { + Ok(result) => { + permit.release(); + Ok(result) + } + Err(_) => { + self.quarantine_ownership(permit); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } + } + + /// A create may have succeeded but its ID is unusable: never rebuild. + #[allow(clippy::too_many_arguments)] + async fn fail_created_unknown( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: CallPermit, + code: &'static str, + ) -> Result { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, identity, observer, permit) + .await; + } + let outcome = SettledOutcome { + status: AcpDelegationStatus::Indeterminate, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code.to_string()), + }; + match self + .settle_outcome(scope, request, identity, snapshot, outcome, false, true) + .await + { + Ok(result) => { + permit.release(); + Ok(result) + } + Err(_) => { + self.quarantine_ownership(permit); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } + } + + /// A remote session may exist but the peer ID is empty or oversized. + #[allow(clippy::too_many_arguments)] + async fn reject_external_id( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: CallPermit, + ) -> Result { + self.fail_created_unknown( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + "acp_session_create_failed", + ) + .await + } + + /// Durable writes failed after the spawn: leave the durable phase exactly + /// where it was unless cleanup is really proven, and never discard a still + /// usable observer. Confirmed cleanup settles the call as indeterminate in + /// the same lease it started with; unproven cleanup hands the whole + /// ownership (observer, permit, per-run slot) to the one cleanup owner. + #[allow(clippy::too_many_arguments)] + async fn abort_unknown_state( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: CallPermit, + ) -> Result { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, identity, observer, permit) + .await; + } + let outcome = SettledOutcome { + status: AcpDelegationStatus::Indeterminate, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_session_indeterminate".to_string()), + }; + match self + .settle_outcome(scope, request, identity, snapshot, outcome, false, true) + .await + { + Ok(_) => { + permit.release(); + Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")) + } + Err(_) => { + self.quarantine_ownership(permit); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } + } + + /// One durable conditional write settles the outcome and releases the pin + /// lease. The storage predicate still names this exact call as the lease + /// owner, and the closure re-checks that lease, so a stale settlement can + /// neither clear a newer owner nor settle a call that lost ownership. + #[allow(clippy::too_many_arguments)] + async fn settle_outcome( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + outcome: SettledOutcome, + keeps_binding: bool, + cleanup_confirmed: bool, + ) -> Result { + let call_id = scope.tool_call_id.clone(); + let harness_id = request.harness_id.clone(); + let run_id = scope.run_id.clone(); + let settle = outcome.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(call) = doc.calls.get(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + if call.phase == CallPhase::Settled { + return Err(AcpPolicyRefusal::Failed("acp_call_settled")); + } + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + let owns = pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id); + if !owns { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + let Some(call) = doc.calls.get_mut(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + call.phase = CallPhase::Settled; + call.cleanup_confirmed = cleanup_confirmed; + call.outcome = Some(settle.clone()); + let pin = doc.pins.get_mut(&harness_id).expect("checked pin"); + pin.active = None; + pin.cleanup_pending = false; + if !keeps_binding { + pin.phase = PinPhase::Unknown; + } + pin.version += 1; + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(outcome.to_result(&request.harness_id, false)) + } + + /// Records a real confirmed cleanup without settling the call, so a later + /// owner may take the stale lease over only when the child is proven gone. + async fn mark_cleanup_confirmed( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let run_id = scope.run_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + if !pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + let Some(call) = doc.calls.get_mut(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + if call.phase == CallPhase::Settled { + return Err(AcpPolicyRefusal::Failed("acp_call_settled")); + } + call.cleanup_confirmed = true; + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + /// Marks the pin as un-reusable after an unknown remote effect, but only + /// while this exact call still owns the lease. + async fn mark_pin_unknown( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let run_id = scope.run_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + if !pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + let pin = doc.pins.get_mut(&harness_id).expect("checked pin"); + pin.phase = PinPhase::Unknown; + pin.active = None; + pin.version += 1; + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + async fn mark_session_creating( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let run_id = scope.run_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + if !pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + if !doc.calls.contains_key(&call_id) { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + } + let pin = doc.pins.get_mut(&harness_id).expect("checked pin"); + pin.phase = PinPhase::Creating; + let call = doc.calls.get_mut(&call_id).expect("checked call"); + if call.phase != CallPhase::Settled { + call.phase = CallPhase::Creating; + } + pin.version += 1; + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + async fn mark_session_restoring( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let run_id = scope.run_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + if !pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + let Some(call) = doc.calls.get(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + if call.phase != CallPhase::Prepared { + return Err(AcpPolicyRefusal::Failed("acp_call_record_invalid")); + } + let call = doc.calls.get_mut(&call_id).expect("checked call"); + call.phase = CallPhase::Restoring; + let pin = doc.pins.get_mut(&harness_id).expect("checked pin"); + pin.phase = PinPhase::Bound; + pin.version += 1; + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + async fn persist_bound_id( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + external_session_id: &str, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let run_id = scope.run_id.clone(); + let external = external_session_id.to_string(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + if !pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + if !doc.calls.contains_key(&call_id) { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + } + let pin = doc.pins.get_mut(&harness_id).expect("checked pin"); + pin.phase = PinPhase::Bound; + pin.external_session_id = Some(external.clone()); + pin.version += 1; + let call = doc.calls.get_mut(&call_id).expect("checked call"); + if call.phase != CallPhase::Settled { + call.phase = CallPhase::SessionBound; + } + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + async fn write_prompt_intent( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let run_id = scope.run_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + if !pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id) + { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + let call = doc + .calls + .get_mut(&call_id) + .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; + call.phase = CallPhase::PromptIntent; + call.prompt_intent_at_ms = crate::domain::timestamp(); + let pin = doc.pins.get_mut(&harness_id).expect("checked pin"); + pin.phase = PinPhase::Bound; + pin.version += 1; + Ok(Some((harness_id.clone(), call_id.clone()))) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + /// Replays a settled call only when every recorded fact still matches the + /// original request, session, run, call, harness and approval identity. + #[allow(clippy::too_many_arguments)] + async fn verify_replay( + &self, + call: &AcpCallRecord, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + witness: &AcpApprovalWitness, + snapshot: &SessionSnapshot, + facts: &AcpRunFacts, + launch: &HarnessLaunch, + ) -> Result<(), AcpPolicyRefusal> { + let Some(authority) = facts.workspace.as_ref() else { + return Err(AcpPolicyRefusal::Denied("acp_workspace_unbound")); + }; + if call.call_id != scope.tool_call_id + || call.run_id != scope.run_id + || call.session_identity != snapshot.identity() + || call.harness_id != request.harness_id + || call.task != request.task + || call.launch != launch.fingerprint + || call.workspace != authority.canonical_path() + || call.workspace_generation != authority.generation() + || call.owner != snapshot.owner + || call.toolset_hash != snapshot.toolset_hash + || call.approval_id != witness.approval_id + { + return Err(AcpPolicyRefusal::Denied("acp_call_mismatch")); + } + let persistence = self.inner.persistence.clone(); + let id = witness.approval_id.clone(); + let result = blocking(move || persistence.approval_get(&id)).await?; + let row = first_row(&result).ok_or(AcpPolicyRefusal::Denied("acp_approval_not_found"))?; + let field = |index: usize| row.get(index).and_then(Value::as_str); + let resolver = field(13).unwrap_or_default(); + if field(0) != Some(witness.approval_id.as_str()) + || field(1) != Some(scope.run_id.as_str()) + || field(2) != Some(scope.session_id.as_str()) + || field(3) != Some(scope.tool_call_id.as_str()) + || field(4) != Some(DELEGATION_TOOL_NAME) + || field(7) != Some("approved") + || call.approval_resolver.as_deref() != Some(resolver) + || !manual_resolver(resolver) + { + return Err(AcpPolicyRefusal::Denied("acp_call_mismatch")); + } + Ok(()) + } + + /// Pins that could not prove cleanup and therefore keep their process slot. + pub fn quarantined_slots(&self) -> usize { + self.inner.quarantine.lock().expect("acp quarantine").len() + } + + /// Pin key and owning call of every quarantined slot, for diagnostics. + pub fn quarantined_calls(&self) -> Vec<(String, String)> { + self.inner + .quarantine + .lock() + .expect("acp quarantine") + .iter() + .map(|slot| (slot.pin_key.clone(), slot.call_id.clone())) + .collect() + } + + /// Parks one call's charged capacity for the service lifetime and keeps + /// its per-run admission slot handed off. Used only when cleanup could not + /// be proven; a confirmed cleanup releases both instead. + fn quarantine_ownership(&self, permit: CallPermit) { + // `CallPermit::drop` performs the handoff and parks the exact permit; + // keeping one path makes a missed release impossible to express. + drop(permit); + } + + /// Last durable pin version written by this policy for one harness. + async fn current_pin_version(&self, session_id: &str, harness_id: &str) -> Option { + let snapshot = self.read_session(session_id).await.ok()?; + PinDocument::from_metadata(snapshot.metadata.as_deref()) + .pins + .get(harness_id) + .map(|pin| pin.version) + } + + /// Waits for the supervisor's cleanup evidence and hands the exact call + /// ownership (identity, permit, per-run slot) to the one settlement path. + async fn hold_until_cleanup( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + identity: &SessionIdentity, + observer: crate::acp::AcpCleanupObserver, + permit: CallPermit, + ) -> Result { + let policy = self.clone(); + let scope = scope.clone(); + let identity = identity.clone(); + let harness_id = request.harness_id.clone(); + let expected_version = self + .current_pin_version(&scope.session_id, &harness_id) + .await + .unwrap_or(u64::MAX); + #[cfg(feature = "workspace-io-fault")] + let cleanup_hold = self + .inner + .cleanup_hold + .lock() + .expect("acp cleanup hold") + .take(); + tokio::spawn(async move { + #[cfg(feature = "workspace-io-fault")] + if let Some((entered, release)) = cleanup_hold { + entered.notify_one(); + release.notified().await; + } + let proof = match observer.wait_for_cleanup().await { + Some(report) if report.cleanup_confirmed => CleanupProof::Confirmed(report), + Some(report) => CleanupProof::Unconfirmed(report), + None => CleanupProof::Lost, + }; + policy + .settle_after_cleanup( + &scope, + &harness_id, + &identity, + proof, + Some(permit), + expected_version, + ) + .await; + }); + Ok(AcpDelegationResult::refusal( + &request.harness_id, + AcpDelegationStatus::Indeterminate, + "acp_cleanup_unconfirmed", + )) + } + + /// Settles a call whose prompt outcome was lost, using the cleanup proof. + /// + /// The slot and the per-run admission are released exactly once and only + /// when the settlement itself committed under the original identity and + /// lease and cleanup was proven; otherwise both stay charged in the + /// service-lifetime quarantine. The pin becomes `unknown` when the call + /// had a durable prompt intent, and only a call without one may keep its + /// known binding. + async fn settle_after_cleanup( + &self, + scope: &AcpDelegationScope, + harness_id: &str, + identity: &SessionIdentity, + proof: CleanupProof, + permit: Option, + expected_version: u64, + ) -> bool { + let confirmed = match &proof { + CleanupProof::Confirmed(report) => report.cleanup_confirmed, + CleanupProof::Unconfirmed(report) => report.cleanup_confirmed, + CleanupProof::Lost => false, + }; + let code = if confirmed { + "acp_prompt_unsettled" + } else { + "acp_cleanup_unverified" + }; + let call_id = scope.tool_call_id.clone(); + let harness_id_owned = harness_id.to_string(); + let run_id = scope.run_id.clone(); + let settled = self + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(call) = doc.calls.get(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + if call.phase == CallPhase::Settled { + return Err(AcpPolicyRefusal::Failed("acp_call_settled")); + } + let Some(pin) = doc.pins.get(&harness_id_owned) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + let owns = pin.version == expected_version + && pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id); + if !owns { + return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); + } + let had_intent = + call.phase == CallPhase::PromptIntent || call.phase == CallPhase::Creating; + let call = doc.calls.get_mut(&call_id).expect("checked call"); + call.phase = CallPhase::Settled; + call.cleanup_confirmed = confirmed; + call.outcome = Some(SettledOutcome { + status: AcpDelegationStatus::Indeterminate, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code.to_string()), + }); + let pin = doc.pins.get_mut(&harness_id_owned).expect("checked pin"); + if !confirmed { + // Ownership is not released without a real terminal + // cleanup. The active lease and the process slot stay + // charged; a later call must not take this pin. + pin.phase = PinPhase::CleanupPending; + pin.cleanup_pending = true; + } else { + pin.active = None; + pin.cleanup_pending = false; + pin.phase = if had_intent { + PinPhase::Unknown + } else { + PinPhase::Bound + }; + } + pin.version += 1; + Ok(Some((harness_id_owned.clone(), call_id.clone()))) + }) + .await; + let committed = settled.is_ok(); + match (committed, confirmed, permit) { + // The single proven release: settlement committed and the + // supervisor proved that no owned process remains. + (true, true, Some(permit)) => { + permit.release(); + } + (_, _, Some(permit)) => self.quarantine_ownership(permit), + (_, _, None) => {} + } + committed && confirmed + } + + /// Test-only entry that settles with a stale version and no charged slot, + /// so a test can prove an old settlement never clears a newer owner. + #[cfg(feature = "workspace-io-fault")] + #[doc(hidden)] + pub async fn settle_stale_cleanup_for_test( + &self, + scope: &AcpDelegationScope, + harness_id: &str, + expected_version: u64, + ) { + let Ok(snapshot) = self.read_session(&scope.session_id).await else { + return; + }; + let identity = snapshot.identity(); + self.settle_after_cleanup( + scope, + harness_id, + &identity, + CleanupProof::Unconfirmed(unconfirmed_report()), + None, + expected_version, + ) + .await; + } + + /// Re-reads and revalidates the durable manual approval. + async fn validate_witness( + &self, + witness: &AcpApprovalWitness, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &SessionSnapshot, + facts: &AcpRunFacts, + ) -> Result { + let persistence = self.inner.persistence.clone(); + let id = witness.approval_id.clone(); + let result = blocking(move || persistence.approval_get(&id)).await?; + let row = first_row(&result).ok_or(AcpPolicyRefusal::Denied("acp_approval_not_found"))?; + let field = |index: usize| row.get(index).and_then(Value::as_str); + if field(0) != Some(witness.approval_id.as_str()) + || field(1) != Some(scope.run_id.as_str()) + || field(2) != Some(scope.session_id.as_str()) + || field(3) != Some(scope.tool_call_id.as_str()) + || field(4) != Some(DELEGATION_TOOL_NAME) + || field(7) != Some("approved") + { + return Err(AcpPolicyRefusal::Denied("acp_approval_mismatch")); + } + // The policy's own row has no model-supplied argument text; every + // binding fact lives in the private durable document instead. + if field(5) != Some("{}") { + return Err(AcpPolicyRefusal::Denied("acp_approval_mismatch")); + } + if row.get(9).and_then(Value::as_i64) != Some(1) { + return Err(AcpPolicyRefusal::Denied("acp_approval_not_one_time")); + } + let expires_at_ms = row + .get(11) + .and_then(Value::as_i64) + .unwrap_or_default() + .max(0) as u64; + if expires_at_ms != 0 && expires_at_ms <= crate::domain::timestamp() { + return Err(AcpPolicyRefusal::Denied("acp_approval_expired")); + } + let risk = field(6).unwrap_or_default(); + if !matches!(risk, "execute" | "privileged") { + return Err(AcpPolicyRefusal::Denied("acp_approval_risk")); + } + // The decision scope must describe the reviewer topology sealed into + // this exact run: an explicit user row is a single call; every other + // reviewer (including the Telegram default and an unset reviewer) must + // reach a real durable `human_pending` decision. + let decision_scope = field(8).unwrap_or_default(); + let expected_scope = match facts.reviewer.as_deref() { + Some("user") => "single_call", + Some("auto") | Some("guardian") | None => "human_pending", + Some(_) => return Err(AcpPolicyRefusal::Denied("acp_approval_not_user")), + }; + if decision_scope != expected_scope { + return Err(AcpPolicyRefusal::Denied("acp_approval_mismatch")); + } + let _ = (snapshot, request); + // The decision must come from the authenticated manual surface. An + // automatic/Guardian row has a different resolver and is refused here. + let gateway = self.inner.gateway.clone(); + let run_id = scope.run_id.clone(); + let approval_id = witness.approval_id.clone(); + let resolver = + blocking_gateway(move || gateway.manual_approval_resolver(&run_id, &approval_id)) + .await?; + Ok(WitnessFacts { + resolver, + expires_at_ms, + }) + } + + async fn read_session(&self, session_id: &str) -> Result { + let persistence = self.inner.persistence.clone(); + let id = session_id.to_string(); + let result = blocking(move || persistence.session_get(&id)).await?; + let row = first_row(&result).ok_or(AcpPolicyRefusal::Denied("acp_session_unknown"))?; + SessionSnapshot::from_row(row).ok_or(AcpPolicyRefusal::Denied("acp_session_unknown")) + } + + /// Applies one mutation to the authoritative document through the storage + /// compare-and-swap, retrying from the returned document on conflict. + /// + /// `identity` is the original session row this call was approved and + /// observed against. Every read and retry must still be that exact row; a + /// replacement (even with the same owner) is never written. + /// + /// The closure must be idempotent and only touch its own pin/call. It + /// returns the lease the update expects to still own, which the storage + /// predicate checks in the same transaction. + async fn mutate( + &self, + session_id: &str, + identity: &SessionIdentity, + mut apply: F, + ) -> Result<(SessionSnapshot, PinDocument), AcpPolicyRefusal> + where + F: FnMut( + &mut PinDocument, + &SessionSnapshot, + ) -> Result, AcpPolicyRefusal>, + { + let mut snapshot = self.read_session(session_id).await?; + // A retry is only a revision conflict on this exact row. If the row is + // deleted and recreated (or its owner changes), the original identity + // is gone and no approval, lease or outcome may be carried into the new + // instance. + if &snapshot.identity() != identity { + return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); + } + #[cfg(feature = "workspace-io-fault")] + self.run_cas_hook(); + for _ in 0..CAS_ATTEMPTS { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let expected_version = doc.version; + let lease = apply(&mut doc, &snapshot)?; + doc.version = expected_version.saturating_add(1); + let document_json = serde_json::to_string(&doc) + .map_err(|_| AcpPolicyRefusal::Failed("acp_pin_invalid"))?; + if document_json.len() > MAX_DOCUMENT_BYTES { + return Err(AcpPolicyRefusal::Failed("acp_delegation_retention")); + } + let (lease_path, lease_call) = match lease { + Some((harness_id, call_id)) => (lease_path(&harness_id), call_id), + None => (String::new(), String::new()), + }; + let payload = json!({ + "session_id": session_id, + "owner": identity.owner, + "created_at_ms": identity.created_at_ms, + "expected_version": expected_version, + "lease_path": lease_path, + "lease_call": lease_call, + "document_json": document_json, + "now_ms": crate::domain::timestamp() as i64, + }); + let persistence = self.inner.persistence.clone(); + let result = blocking(move || persistence.session_acp_delegation_cas(&payload)).await?; + let applied = result.get("applied").and_then(Value::as_bool) == Some(true); + let row = result + .get("rows") + .and_then(Value::as_array) + .and_then(|rows| rows.first()) + .and_then(Value::as_array) + .cloned() + .ok_or(AcpPolicyRefusal::Failed("acp_session_unknown"))?; + let next = SessionSnapshot::from_row(row) + .ok_or(AcpPolicyRefusal::Failed("acp_session_unknown"))?; + if &next.identity() != identity { + return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); + } + snapshot = next; + if applied { + return Ok((snapshot, doc)); + } + } + Err(AcpPolicyRefusal::Failed("acp_storage_conflict")) + } + + fn lease_names(&self, snapshot: &SessionSnapshot, harness_id: &str, call_id: &str) -> bool { + PinDocument::from_metadata(snapshot.metadata.as_deref()) + .pins + .get(harness_id) + .and_then(|pin| pin.active.as_ref()) + .is_some_and(|lease| lease.call_id == call_id) + } + + fn pin_gate(&self, session_id: &str, harness_id: &str) -> Arc> { + let key = format!("{session_id}\u{1f}{harness_id}"); + let mut gates = self.inner.gates.lock().expect("acp pin gates"); + gates + .entry(key) + .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))) + .clone() + } +} + +fn unconfirmed_report() -> crate::acp::AcpCleanupReport { + crate::acp::AcpCleanupReport { + direct_child_reaped: false, + exit_status: None, + group_signal_sent: false, + forced: false, + group_clear: false, + cleanup_confirmed: false, + } +} + +/// Cleanup evidence observed for a delegation whose prompt outcome was lost. +#[derive(Debug)] +enum CleanupProof { + Confirmed(crate::acp::AcpCleanupReport), + Unconfirmed(crate::acp::AcpCleanupReport), + Lost, +} + +/// One process slot kept charged because cleanup could not be proven. +struct QuarantinedSlot { + pin_key: String, + call_id: String, + _admission: CallAdmission, +} + +/// The two admission tokens move together, including after cleanup handoff. +/// Field order releases the run gate before making process capacity visible. +struct CallAdmission { + _run: RunGate, + _process: tokio::sync::OwnedSemaphorePermit, +} + +/// Owns one call's charged slots independently of the caller future. +/// Dropping the owner without `release` parks both tokens in quarantine. +struct CallPermit { + policy: Arc, + pin_key: String, + call_id: String, + admission: Option, +} + +impl CallPermit { + fn new( + policy: Arc, + pin_key: String, + call_id: String, + run: RunGate, + process: tokio::sync::OwnedSemaphorePermit, + ) -> Self { + Self { + policy, + pin_key, + call_id, + admission: Some(CallAdmission { + _run: run, + _process: process, + }), + } + } + + /// Releases both slots once, after confirmed cleanup and settlement. + fn release(mut self) { + drop(self.admission.take()); + } +} + +impl Drop for CallPermit { + fn drop(&mut self) { + let Some(admission) = self.admission.take() else { + return; + }; + self.policy + .quarantine + .lock() + .expect("acp quarantine") + .push(QuarantinedSlot { + pin_key: std::mem::take(&mut self.pin_key), + call_id: std::mem::take(&mut self.call_id), + _admission: admission, + }); + } +} + +/// Marks the awaiting caller as gone when its delegate future is dropped. +struct AbandonOnDrop(Arc); + +impl Drop for AbandonOnDrop { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } +} + +struct RunGate { + runs: Arc>>, + run_id: String, +} + +impl Drop for RunGate { + fn drop(&mut self) { + self.runs + .lock() + .expect("acp per-run gate") + .remove(&self.run_id); + } +} + +#[derive(Clone, Copy)] +enum DelegationInterruption { + Cancelled, + Revoked, +} + +impl DelegationInterruption { + fn status(self) -> AcpDelegationStatus { + match self { + Self::Cancelled => AcpDelegationStatus::Cancelled, + Self::Revoked => AcpDelegationStatus::Denied, + } + } + + fn code(self) -> &'static str { + match self { + Self::Cancelled => "acp_delegation_cancelled", + Self::Revoked => "acp_workspace_invalid", + } + } +} + +type WorkspaceRevocation = Option>; + +fn current_interruption( + cancellation: &crate::runtime::rss_runner::RunCancellation, + revocation: &WorkspaceRevocation, +) -> Option { + if cancellation.requested().is_some() { + Some(DelegationInterruption::Cancelled) + } else if revocation.as_ref().is_some_and(|watch| *watch.borrow()) { + Some(DelegationInterruption::Revoked) + } else { + None + } +} + +async fn delegation_interrupted( + cancellation: &crate::runtime::rss_runner::RunCancellation, + revocation: &mut WorkspaceRevocation, +) -> DelegationInterruption { + let revoked = async { + if let Some(watch) = revocation + && watch.wait_for(|revoked| *revoked).await.is_ok() + { + return; + } + std::future::pending::<()>().await; + }; + tokio::select! { + biased; + _ = cancellation.cancelled() => DelegationInterruption::Cancelled, + _ = revoked => DelegationInterruption::Revoked, + } +} + +enum PromptWait { + Done(Result), + Interrupted(DelegationInterruption), +} + +fn build_launch(harness: &AcpHarnessSettings) -> Result { + if harness.args.len() > MAX_ACP_HARNESS_ARGUMENTS + || harness.argument_bytes() > MAX_ACP_HARNESS_ARGUMENT_BYTES + { + return Err("agent acp_harnesses entry exceeds the argument bound".to_string()); + } + let command = harness + .command + .to_str() + .ok_or_else(|| "agent acp_harnesses command must be UTF-8".to_string())? + .to_string(); + if !harness.command.is_absolute() { + return Err("agent acp_harnesses command must be absolute".to_string()); + } + // A command that cannot be executed is not a launch definition. This is + // checked at startup (install) and again by the launch constructor. + let metadata = std::fs::metadata(&harness.command) + .map_err(|_| "agent acp_harnesses command must name an executable file".to_string())?; + if !metadata.is_file() || !executable(&metadata) { + return Err("agent acp_harnesses command must name an executable file".to_string()); + } + let fingerprint = serde_json::to_string(&json!({ + "command": command, + "args": harness.args, + })) + .map_err(|_| "agent acp_harnesses entry is not serializable".to_string())?; + Ok(HarnessLaunch { + command: harness.command.clone(), + arguments: harness.args.iter().map(OsString::from).collect(), + fingerprint, + }) +} + +fn executable(metadata: &std::fs::Metadata) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + metadata.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + let _ = metadata; + true + } +} + +fn validate_request(request: &AcpDelegationRequest) -> Result<(), AcpPolicyRefusal> { + if !crate::config_file::valid_acp_harness_id(&request.harness_id) { + return Err(AcpPolicyRefusal::Denied("acp_harness_invalid")); + } + if request.task.is_empty() || request.task.len() > MAX_TASK_BYTES || request.task.contains('\0') + { + return Err(AcpPolicyRefusal::Denied("acp_task_invalid")); + } + Ok(()) +} + +fn approval_id(run_id: &str, call_id: &str) -> Result { + if run_id.is_empty() + || call_id.is_empty() + || run_id.len() > 256 + || call_id.len() > 256 + || run_id.contains('\0') + || call_id.contains('\0') + { + return Err(AcpPolicyRefusal::Denied("acp_call_invalid")); + } + Ok(format!("acp-delegation:{run_id}:{call_id}")) +} + +/// The admitted run deadline, when the gateway recorded one. +fn run_deadline_ms(facts: &AcpRunFacts) -> Option { + (facts.deadline_ms > 0).then_some(facts.deadline_ms) +} + +fn effective_deadline_ms(run_deadline_ms: Option, now_ms: u64) -> u64 { + let cap = now_ms.saturating_add(DELEGATION_DEADLINE_MS); + match run_deadline_ms { + Some(deadline) if deadline > 0 => deadline.min(cap), + _ => cap, + } +} + +fn frozen_deadline(facts: &AcpRunFacts) -> Instant { + let now = Instant::now(); + let now_ms = crate::domain::timestamp(); + let cap = now + Duration::from_millis(DELEGATION_DEADLINE_MS); + let wall = match run_deadline_ms(facts) { + Some(deadline) if deadline <= now_ms => now, + Some(deadline) => now + Duration::from_millis(deadline - now_ms), + None => cap, + }; + let monotonic = facts + .cancellation + .deadline_instant() + .map(Instant::from_std) + .unwrap_or(cap); + cap.min(wall).min(monotonic) +} + +fn build_preview( + harness_id: &str, + workspace: &str, + new_session: bool, + task: &str, +) -> Result { + let mode = if new_session { + "create a new external session" + } else { + "continue the bound external session" + }; + // The complete submitted text is shown; an approval must never cover a + // task the operator could not read in full. + let preview = format!( + "Delegate to ACP harness `{harness_id}` in workspace `{workspace}` ({mode}).\n\ + Task ({bytes} bytes, complete):\n{task}\n\ + The external program runs as the local user with this gateway's file and network \ + access; RustScript does not sandbox it or proxy its model credential.", + bytes = task.len() + ); + if preview.len() > MAX_PREVIEW_BYTES { + return Err(AcpPolicyRefusal::Denied("acp_approval_preview_unavailable")); + } + Ok(preview) +} + +fn stop_reason_code(reason: AcpStopReason) -> &'static str { + match reason { + AcpStopReason::EndTurn => "end_turn", + AcpStopReason::MaxTokens => "max_tokens", + AcpStopReason::MaxTurnRequests => "max_turn_requests", + AcpStopReason::Refusal => "refusal", + AcpStopReason::Cancelled => "cancelled", + AcpStopReason::Other => "other", + } +} + +fn stop_reason_from_code(code: &str) -> Option { + match code { + "end_turn" => Some(AcpStopReason::EndTurn), + "max_tokens" => Some(AcpStopReason::MaxTokens), + "max_turn_requests" => Some(AcpStopReason::MaxTurnRequests), + "refusal" => Some(AcpStopReason::Refusal), + "cancelled" => Some(AcpStopReason::Cancelled), + "other" => Some(AcpStopReason::Other), + _ => None, + } +} + +fn clamp_text(text: &mut String, budget: usize, truncated: &mut bool) { + if text.len() <= budget { + return; + } + let mut end = budget; + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + *truncated = true; +} + +/// Shrinks the text until the whole serialized result envelope fits the run's +/// tool-output budget, preserving UTF-8 boundaries. +/// +/// The pre-spawn budget check guarantees that the typed budget refusal itself +/// fits. An outcome that cannot carry any text is therefore replaced by that +/// refusal directly; there is no intermediate "drop the code and hope" path. +fn bounded_result(mut result: AcpDelegationResult, budget: usize) -> AcpDelegationResult { + if envelope_len(&result) <= budget { + return result; + } + let source = result.text.clone(); + let mut boundaries: Vec = source.char_indices().map(|(index, _)| index).collect(); + boundaries.push(source.len()); + let fitting = boundaries.partition_point(|&end| { + result.text = source[..end].to_string(); + envelope_len(&result) <= budget + }); + let chosen = if fitting == 0 { + 0 + } else { + boundaries[fitting - 1] + }; + result.text = source[..chosen].to_string(); + if chosen < source.len() { + result.truncated = true; + } + if envelope_len(&result) <= budget { + return result; + } + budget_refusal_result(&result.harness_id, result.replayed) +} + +/// Smallest possible typed refusal for one harness. Below this budget no ACP +/// result envelope may be emitted at all. +fn minimum_success_envelope_bytes(harness_id: &str) -> usize { + let result = AcpDelegationResult::settled( + harness_id, + AcpDelegationStatus::Completed, + String::new(), + Some(AcpStopReason::EndTurn), + false, + None, + false, + ); + result.serialized_envelope_bytes() +} + +/// Smallest possible typed refusal for one harness. +fn minimum_refusal_envelope_bytes(harness_id: &str) -> usize { + envelope_len(&budget_refusal_result(harness_id, false)) +} + +/// Smallest budget at which either a complete success or the typed budget +/// refusal can always be delivered at the public boundary. +fn minimum_deliverable_envelope_bytes(harness_id: &str) -> usize { + minimum_success_envelope_bytes(harness_id).max(minimum_refusal_envelope_bytes(harness_id)) +} + +/// Minimal bounded refusal used when an outcome cannot be encoded within the +/// configured budget. It never claims a delivered result. +fn budget_refusal_result(harness_id: &str, replayed: bool) -> AcpDelegationResult { + AcpDelegationResult::settled( + harness_id, + AcpDelegationStatus::Failed, + String::new(), + None, + false, + Some("acp_delegation_budget"), + replayed, + ) +} + +fn envelope_len(result: &AcpDelegationResult) -> usize { + serde_json::to_vec(&result.to_json()) + .map(|bytes| bytes.len()) + .unwrap_or(usize::MAX) +} + +fn lease_path(harness_id: &str) -> String { + format!("$.\"{METADATA_KEY}\".\"pins\".\"{harness_id}\".\"active\".\"call_id\"") +} + +fn manual_resolver(resolver: &str) -> bool { + resolver == "http-bearer" + || resolver + .strip_prefix("telegram:") + .is_some_and(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit())) +} + +async fn blocking(operation: F) -> Result +where + F: FnOnce() -> Result + Send + 'static, + T: Send + 'static, +{ + match tokio::task::spawn_blocking(operation).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(_)) | Err(_) => Err(AcpPolicyRefusal::Failed("acp_storage_unavailable")), + } +} + +async fn blocking_gateway(operation: F) -> Result +where + F: FnOnce() -> Result + Send + 'static, + T: Send + 'static, +{ + match tokio::task::spawn_blocking(operation).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(code)) => Err(AcpPolicyRefusal::Denied(code)), + Err(_) => Err(AcpPolicyRefusal::Failed("acp_storage_unavailable")), + } +} + +fn first_row(value: &Value) -> Option> { + sqlite_storage_first_row(value) +} + +/// Admitted workspace resolved from the session's authoritative binding. +#[derive(Clone)] +struct AdmittedWorkspace { + path: String, + generation: u64, +} + +fn admitted_workspace( + facts: &AcpRunFacts, + allowed_roots: &[PathBuf], +) -> Result { + let Some(authority) = facts.workspace.as_ref() else { + return Err(AcpPolicyRefusal::Denied("acp_workspace_unbound")); + }; + if authority.revoked() { + return Err(AcpPolicyRefusal::Denied("acp_workspace_invalid")); + } + authority + .check() + .map_err(|_| AcpPolicyRefusal::Denied("acp_workspace_invalid"))?; + let path = PathBuf::from(authority.canonical_path()); + if !path.is_absolute() + || path + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + { + return Err(AcpPolicyRefusal::Denied("acp_workspace_invalid")); + } + // The admitted boundary must still be the canonical directory. + let canonical = std::fs::canonicalize(&path) + .map_err(|_| AcpPolicyRefusal::Denied("acp_workspace_invalid"))?; + if canonical != path { + return Err(AcpPolicyRefusal::Denied("acp_workspace_invalid")); + } + if !allowed_roots.is_empty() && !allowed_roots.iter().any(|root| path.starts_with(root)) { + return Err(AcpPolicyRefusal::Denied("acp_workspace_invalid")); + } + Ok(AdmittedWorkspace { + path: authority.canonical_path().to_string(), + generation: authority.generation(), + }) +} + +/// Durable identity of one exact session row. A replacement row with the same +/// id but a new owner or creation time is a different instance and never +/// inherits an approval, lease, outcome or charge. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +struct SessionIdentity { + owner: String, + created_at_ms: i64, +} + +/// Durable session columns read by the policy. +#[derive(Clone)] +struct SessionSnapshot { + owner: String, + toolset_hash: String, + metadata: Option, + created_at_ms: i64, +} + +impl SessionSnapshot { + /// Durable row identity: a recreated session with the same ID but a new + /// owner or creation time is a different instance and never inherits a + /// previous document. + fn identity(&self) -> SessionIdentity { + SessionIdentity { + owner: self.owner.clone(), + created_at_ms: self.created_at_ms, + } + } + + fn from_row(row: Vec) -> Option { + let text = |index: usize| { + row.get(index) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + row.first()?.as_str()?; + Some(Self { + owner: text(6), + toolset_hash: text(12), + metadata: row.get(13).and_then(Value::as_str).map(str::to_string), + created_at_ms: row.get(15).and_then(Value::as_i64).unwrap_or_default(), + }) + } +} + +/// Private durable delegation document kept under `$.acp_delegation`. +#[derive(Clone, Debug, Serialize, Deserialize)] +struct PinDocument { + #[serde(default)] + version: i64, + #[serde(default)] + pins: BTreeMap, + #[serde(default)] + calls: BTreeMap, + #[serde(default)] + pending_approvals: BTreeMap, +} + +impl Default for PinDocument { + fn default() -> Self { + Self { + version: -1, + pins: BTreeMap::new(), + calls: BTreeMap::new(), + pending_approvals: BTreeMap::new(), + } + } +} + +impl PinDocument { + fn from_metadata(metadata: Option<&str>) -> Self { + let Some(metadata) = metadata else { + return Self::default(); + }; + let Ok(value) = serde_json::from_str::(metadata) else { + return Self::default(); + }; + let Some(mut document) = value.get(METADATA_KEY).cloned() else { + return Self::default(); + }; + if document.get("version").is_none() + && let Some(object) = document.as_object_mut() + { + // An absent document is version -1; a stored document without a + // version field is treated as the first durable generation. + object.insert("version".to_string(), Value::from(-1)); + } + serde_json::from_value(document).unwrap_or_default() + } + + fn expire_approvals(&mut self, now_ms: u64) { + self.pending_approvals + .retain(|_, binding| binding.expires_at_ms > now_ms); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum PinPhase { + /// A remote session may exist but its ID is not durable: never reuse. + Creating, + /// The peer session ID is durable and may be restored. + #[default] + Bound, + /// A prompt may have run without settlement: never reuse or rebuild. + Unknown, + /// Cleanup of one call could not be proven. Ownership of the pin and its + /// process slot is retained until a real terminal cleanup exists. + CleanupPending, +} + +impl PinPhase { + fn blocks_new_calls(self) -> bool { + !matches!(self, Self::Bound) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct AcpPin { + owner: String, + workspace: String, + #[serde(default)] + workspace_generation: u64, + launch: String, + phase: PinPhase, + #[serde(default)] + external_session_id: Option, + #[serde(default)] + active: Option, + /// A cleanup proof was never obtained; the pin and its process slot stay + /// owned and no later call may take this binding. + #[serde(default)] + cleanup_pending: bool, + version: u64, +} + +impl AcpPin { + fn new(owner: String, workspace: &AdmittedWorkspace, launch: String) -> Self { + Self { + owner, + workspace: workspace.path.clone(), + workspace_generation: workspace.generation, + launch, + phase: PinPhase::Bound, + external_session_id: None, + active: None, + cleanup_pending: false, + version: 0, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct ActiveLease { + call_id: String, + run_id: String, + expires_at_ms: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum CallPhase { + /// Durable preparation before any process exists. A crash after this write + /// may have spawned, so the call is never reported as `NotStarted`. + Prepared, + /// `session/new` may have run and its ID was never persisted. + Creating, + /// The peer session ID is durable; no prompt intent was written. + SessionBound, + /// A restore of an already-bound peer session was issued; the prompt send + /// intent was not written. Recoverable once the owning run is terminal. + Restoring, + /// The prompt send intent is durable; no settlement exists. + PromptIntent, + /// The call settled; the recorded outcome is authoritative. + Settled, +} + +impl CallPhase { + /// Durable settlement classification shared with the effect vocabulary. + fn settlement(self) -> crate::effects::DelegationSettlement { + match self { + Self::Settled => crate::effects::DelegationSettlement::Settled, + Self::Prepared + | Self::Creating + | Self::SessionBound + | Self::Restoring + | Self::PromptIntent => crate::effects::DelegationSettlement::Indeterminate, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct AcpCallRecord { + call_id: String, + run_id: String, + #[serde(default)] + session_identity: SessionIdentity, + harness_id: String, + approval_id: String, + #[serde(default)] + approval_resolver: Option, + task: String, + launch: String, + workspace: String, + #[serde(default)] + workspace_generation: u64, + owner: String, + toolset_hash: String, + pin_version_at_start: u64, + phase: CallPhase, + /// A real terminal cleanup report for this call was observed. Only such a + /// call may have its stale lease reclaimed after its owning run is durable + /// terminal; a terminal run alone never proves the child was reaped. + #[serde(default)] + cleanup_confirmed: bool, + #[serde(default)] + outcome: Option, + #[serde(default)] + prompt_intent_at_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct ApprovalBinding { + run_id: String, + session_id: String, + #[serde(default)] + session_identity: SessionIdentity, + tool_call_id: String, + harness_id: String, + task: String, + launch: String, + workspace: String, + workspace_generation: u64, + owner: String, + toolset_hash: String, + pin_version: u64, + new_session: bool, + expires_at_ms: u64, +} + +struct WitnessFacts { + resolver: String, + expires_at_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct SettledOutcome { + status: AcpDelegationStatus, + text: String, + #[serde(default)] + stop_reason: Option, + truncated: bool, + #[serde(default)] + code: Option, +} + +impl SettledOutcome { + fn to_result(&self, harness_id: &str, replayed: bool) -> AcpDelegationResult { + AcpDelegationResult::settled( + harness_id, + self.status, + self.text.clone(), + self.stop_reason.as_deref().and_then(stop_reason_from_code), + self.truncated, + self.code.as_deref().and_then(known_code), + replayed, + ) + } +} + +/// Only static diagnostic codes are re-emitted; anything else is dropped. +fn known_code(code: &str) -> Option<&'static str> { + const CODES: &[&str] = &[ + "acp_delegation_invalid_launch", + "acp_delegation_spawn_failed", + "acp_delegation_deadline", + "acp_delegation_not_initialized", + "acp_delegation_invalid_phase", + "acp_delegation_protocol_version", + "acp_delegation_initialize_failed", + "acp_session_create_failed", + "acp_session_restore_unsupported", + "acp_session_restore_failed", + "acp_session_mismatch", + "acp_delegation_prompt_failed", + "acp_delegation_task_invalid", + "acp_delegation_frame_too_large", + "acp_delegation_notification_flood", + "acp_harness_exited", + "acp_delegation_cancelled", + "acp_delegation_closed", + "acp_stop_reason", + "acp_cleanup_unconfirmed", + "acp_cleanup_unverified", + "acp_session_indeterminate", + "acp_prompt_indeterminate", + "acp_storage_unavailable", + "acp_storage_conflict", + "acp_storage_not_committed", + "acp_pin_invalid", + "acp_call_missing", + "acp_pin_missing", + "acp_call_record_invalid", + "acp_call_settled", + "acp_call_mismatch", + "acp_call_interrupted", + "acp_delegation_budget", + "acp_session_identity_changed", + "acp_delegation_retention", + "acp_approval_capacity", + "acp_approval_stale", + "acp_approval_mismatch", + "acp_approval_expired", + "acp_approval_not_one_time", + "acp_approval_risk", + "acp_approval_preview_unavailable", + "acp_approval_not_user", + "acp_approval_not_found", + "acp_approval_unavailable", + "acp_human_review_required", + "acp_run_inactive", + "acp_binding_mismatch", + "acp_workspace_unbound", + "acp_workspace_invalid", + "acp_harness_invalid", + "acp_task_invalid", + "acp_call_invalid", + "acp_harness_unknown", + ]; + CODES.iter().copied().find(|known| *known == code) +} + +/// Adapter between the bundled RSS pinned invocation and the delegation policy. +/// Scope and registry come from the service's retained run, never the guest. +pub(crate) async fn run_rss_delegation( + policy: &AcpDelegationPolicy, + persistence: &Arc, + context: &crate::domain::RunContext, + facts: &AcpRunFacts, + registry: &crate::registry::ToolRegistrySnapshot, + call_id: &str, + arguments: &Value, +) -> Value { + use crate::effects::DelegationSettlement; + use crate::runtime::agent_host::pinned_outcome; + + let bare_refusal = |code| pinned_outcome(false, "", "", code, code, ""); + if context.metadata["registry_identity"].as_str() != Some(registry.identity()) + || registry + .validate_arguments(DELEGATION_TOOL_NAME, arguments) + .is_err() + { + return bare_refusal("acp_arguments_invalid"); + } + let Some(harness_id) = arguments["harness_id"].as_str() else { + return bare_refusal("acp_arguments_invalid"); + }; + let Some(task) = arguments["task"].as_str() else { + return bare_refusal("acp_arguments_invalid"); + }; + let Some(budget) = context.limits["max_tool_output_bytes"] + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + else { + return bare_refusal("acp_delegation_budget"); + }; + // Refuse before an approval or process when the canonical minimum cannot + // fit. No oversized failure result is emitted either. + let smallest = AcpDelegationResult::settled( + harness_id, + AcpDelegationStatus::Completed, + String::new(), + Some(AcpStopReason::EndTurn), + true, + None, + false, + ); + if encode_rss_result(&smallest, call_id, budget).is_none() { + return bare_refusal("acp_delegation_budget"); + } + let refusal = |status, code| AcpDelegationResult::refusal(harness_id, status, code); + let request = AcpDelegationRequest { + harness_id: harness_id.to_owned(), + task: task.to_owned(), + }; + let scope = AcpDelegationScope { + run_id: context.run_id.clone(), + session_id: context.session_id.clone(), + tool_call_id: call_id.to_owned(), + }; + let outcome = async { + let key = approval_id(&scope.run_id, &scope.tool_call_id)?; + let witness = AcpApprovalWitness::new(key); + match policy.call_settlement(&scope.session_id, call_id).await? { + DelegationSettlement::Settled => { + return Ok(policy.delegate(&scope, &request, &witness).await); + } + DelegationSettlement::Indeterminate => { + return Ok(refusal( + AcpDelegationStatus::Indeterminate, + "acp_call_indeterminate", + )); + } + DelegationSettlement::NotStarted => {} + } + if !matches!( + context.metadata["approval_settings"]["process"].as_str(), + Some("ask" | "allow") + ) { + return Err(AcpPolicyRefusal::Denied("approval_policy_denied")); + } + let challenge = policy.request_approval(&scope, &request).await?; + wait_for_rss_approval(persistence, &scope, facts, &challenge).await?; + Ok(policy.delegate(&scope, &request, &witness).await) + } + .await; + let result = + outcome.unwrap_or_else(|error: AcpPolicyRefusal| refusal(error.status(), error.code())); + encode_rss_result(&result, call_id, budget) + .unwrap_or_else(|| bare_refusal("acp_delegation_budget")) +} + +async fn wait_for_rss_approval( + persistence: &Arc, + scope: &AcpDelegationScope, + facts: &AcpRunFacts, + challenge: &AcpApprovalChallenge, +) -> Result<(), AcpPolicyRefusal> { + loop { + if facts.cancellation.requested().is_some() { + return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")); + } + if crate::domain::timestamp() >= challenge.expires_at_ms { + return Err(AcpPolicyRefusal::TimedOut("acp_approval_expired")); + } + let store = Arc::clone(persistence); + let id = challenge.approval_id.clone(); + let stored = tokio::select! { + biased; + _ = facts.cancellation.cancelled() => return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")), + stored = blocking_gateway(move || store.approval_get(&id).map_err(|_| "acp_storage_unavailable")) => stored?, + }; + let row = sqlite_storage_first_row(&stored) + .ok_or(AcpPolicyRefusal::Denied("acp_approval_unavailable"))?; + if row.first().and_then(Value::as_str) != Some(challenge.approval_id.as_str()) + || row.get(1).and_then(Value::as_str) != Some(scope.run_id.as_str()) + || row.get(2).and_then(Value::as_str) != Some(scope.session_id.as_str()) + || row.get(3).and_then(Value::as_str) != Some(scope.tool_call_id.as_str()) + || row.get(4).and_then(Value::as_str) != Some(DELEGATION_TOOL_NAME) + { + return Err(AcpPolicyRefusal::Denied("acp_approval_invalid")); + } + match row.get(7).and_then(Value::as_str) { + Some("approved") => return Ok(()), // policy independently verifies the human resolver + Some("pending") => tokio::select! { + biased; + _ = facts.cancellation.cancelled() => return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")), + _ = tokio::time::sleep(Duration::from_millis(50)) => {}, + }, + _ => return Err(AcpPolicyRefusal::Denied("acp_approval_denied")), + } + } +} + +#[derive(Serialize)] +struct AcpPublicResult<'a> { + harness_id: &'a str, + status: AcpDelegationStatus, + text: &'a str, + stop_reason: Option<&'static str>, + truncated: bool, +} + +/// Bound the actual projected block, including both the fallback display text +/// and the typed canonical result. This counts JSON escapes and UTF-8 bytes. +fn encode_rss_result(result: &AcpDelegationResult, call_id: &str, budget: usize) -> Option { + let ok = result.status == AcpDelegationStatus::Completed; + let code = result.code.unwrap_or(""); + let error = if ok { + json!({}) + } else { + json!({"code": code, "message": code}) + }; + let encode = |text: &str, truncated: bool| { + let data = serde_json::to_value(AcpPublicResult { + harness_id: &result.harness_id, + status: result.status, + text, + stop_reason: result.stop_reason.map(stop_reason_code), + truncated, + }) + .ok()?; + let block = json!({ + "type": "tool_result", "tool_call_id": call_id, "name": DELEGATION_TOOL_NAME, + "content": text, "is_error": !ok, "result": data, "error": error, "truncated": truncated, + }); + (block.to_string().len() <= budget).then(|| { + crate::runtime::agent_host::pinned_outcome(ok, text, "", code, code, &data.to_string()) + }) + }; + if let Some(full) = encode(&result.text, result.truncated) { + return Some(full); + } + let mut prefix = encode("", true)?; + let mut low = 1; + let mut high = result.text.len(); + while low <= high { + let middle = low + (high - low) / 2; + let mut end = middle; + while !result.text.is_char_boundary(end) { + end -= 1; + } + if let Some(encoded) = encode(&result.text[..end], true) { + prefix = encoded; + low = middle + 1; + } else { + high = middle - 1; + } + } + Some(prefix) +} diff --git a/src/tool_schema.rs b/src/tool_schema.rs index cbf96fe5..b645b20b 100644 --- a/src/tool_schema.rs +++ b/src/tool_schema.rs @@ -38,7 +38,26 @@ impl ToolDescriptor { } } -/// The only toolsets enabled by the RSS registry. +/// Gateway-owned opt-in descriptor. The default RSS registry does not include it. +pub(crate) fn acp_delegation_descriptor() -> ToolDescriptor { + ToolDescriptor::new( + crate::service::acp_session_pins::DELEGATION_TOOL_NAME, + "Delegate a specific task to an operator-configured ACP harness. Each call requires human approval. Later calls to the same harness in this session continue its bound external session.", + Toolset::PROCESS, + "execute", + serde_json::json!({ + "type": "object", + "additionalProperties": false, + "required": ["harness_id", "task"], + "properties": { + "harness_id": {"type": "string", "minLength": 1}, + "task": {"type": "string", "minLength": 1, "maxLength": 8192} + } + }), + ) +} + +/// The only toolsets enabled by the RSS registry policy. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Toolset { diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs new file mode 100644 index 00000000..1db73655 --- /dev/null +++ b/tests/acp_delegation_client_tests.rs @@ -0,0 +1,1446 @@ +//! Delegated ACP v1 client contract. +//! +//! These tests drive the real [`DelegatedAcpClient`] against a deterministic +//! local stdio harness. No model, provider, credential or network path is +//! exercised. The harness source is compiled with `rustc` using the +//! `serde_json` rlib already built for this test profile. + +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use rustscript_agent::acp::{ + AcpAgentCapabilities, AcpDelegationError, AcpDelegationLaunch, AcpRestoreMethod, AcpStopReason, + DelegatedAcpClient, +}; +use serde_json::Value; +use tokio::time::{Instant, timeout}; + +#[path = "fixtures/acp/delegation_build.rs"] +mod fixture_build; + +const SETUP_BOUND: Duration = Duration::from_secs(20); +const OPERATION_BOUND: Duration = Duration::from_secs(10); +const CLEANUP_BOUND: Duration = Duration::from_secs(7); +static NEXT_TEST: AtomicU64 = AtomicU64::new(0); + +fn assigned_tmp_root() -> PathBuf { + std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .or_else(|| std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMPDIR")) + .or_else(|| std::env::var_os("TMPDIR")) + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir) +} + +struct TestRoot { + path: PathBuf, +} + +impl TestRoot { + fn new(label: &str) -> Self { + let sequence = NEXT_TEST.fetch_add(1, Ordering::Relaxed); + let path = assigned_tmp_root().join(format!( + "acp-delegation-{label}-{}-{sequence}", + std::process::id() + )); + fs::create_dir_all(&path).expect("create isolated delegation test root"); + Self { path } + } + + fn record_path(&self) -> PathBuf { + self.path.join("events.jsonl") + } + + fn store_path(&self) -> PathBuf { + self.path.join("sessions.txt") + } + + fn workdir(&self) -> PathBuf { + let path = self.path.join("work"); + fs::create_dir_all(&path).expect("create harness cwd"); + path + } +} + +impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn fixture_binary() -> &'static Path { + static FIXTURE: OnceLock = OnceLock::new(); + FIXTURE + .get_or_init(|| { + let root = assigned_tmp_root().join(format!( + "acp-delegation-fixture-{}-{}", + std::process::id(), + NEXT_TEST.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).expect("create fixture build directory"); + let binary = root.join("delegation_agent"); + fixture_build::compile_delegation_agent(&binary); + binary + }) + .as_path() +} + +fn args(root: &TestRoot, mode: &str) -> Vec { + vec![ + OsString::from("--events"), + root.record_path().into_os_string(), + OsString::from("--store"), + root.store_path().into_os_string(), + OsString::from("--mode"), + OsString::from(mode), + ] +} + +fn with_extra(root: &TestRoot, mode: &str, values: &[&str]) -> Vec { + let mut args = args(root, mode); + args.extend(values.iter().map(OsString::from)); + args +} + +fn launch(root: &TestRoot, args: Vec) -> AcpDelegationLaunch { + AcpDelegationLaunch::new(fixture_binary().to_owned(), args, root.workdir()) + .expect("valid fixture launch") +} + +async fn connect(root: &TestRoot, args: Vec, budget: Duration) -> DelegatedAcpClient { + timeout( + SETUP_BOUND, + DelegatedAcpClient::connect(launch(root, args), Instant::now() + budget), + ) + .await + .expect("connect completes") + .expect("fixture launches") +} + +fn read_events(path: &Path) -> Vec { + // The fixture appends one JSON object per line. A read may catch a line that + // is still being written, so complete lines are parsed and the trailing + // partial line is ignored; the wait helpers re-read until the fence appears. + let contents = String::from_utf8_lossy(&fs::read(path).unwrap_or_default()).into_owned(); + let mut events = Vec::new(); + for line in contents.lines().filter(|line| !line.trim().is_empty()) { + match serde_json::from_str(line) { + Ok(event) => events.push(event), + Err(_) => break, + } + } + events +} + +fn named<'a>(events: &'a [Value], name: &str) -> Vec<&'a Value> { + events + .iter() + .filter(|event| event.get("event").and_then(Value::as_str) == Some(name)) + .collect() +} + +fn count(events: &[Value], name: &str) -> usize { + named(events, name).len() +} + +/// Count frames whose raw JSON-RPC method the fixture recorded as unsupported. +/// The fixture logs every unknown request/notification, including the SDK's +/// automatic `$/cancel_request`, so this observes the actual wire. +fn unsupported_method_count(events: &[Value], method: &str) -> usize { + named(events, "unsupported_request") + .iter() + .filter(|event| event["data"]["method"].as_str() == Some(method)) + .count() +} + +fn pid_alive(pid: u32) -> bool { + // SAFETY: signal 0 only performs an existence/permission check. + unsafe { libc::kill(pid as libc::pid_t, 0) == 0 } +} + +async fn wait_pid_gone(pid: u32) { + let deadline = Instant::now() + Duration::from_secs(2); + while Instant::now() < deadline { + if !pid_alive(pid) { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(!pid_alive(pid), "fixture process {pid} was not reaped"); +} + +/// Identity of one observed process: PID plus its kernel start time. +/// +/// Cleanup is verified through this identity instead of re-running the client's +/// own `/proc` group scan, so a recycled PID cannot pass as the process the test +/// saw and the assertion does not share the oracle it is checking. +#[derive(Debug, Clone, Copy)] +struct StartIdentity { + pid: u32, + start_ticks: u64, +} + +impl StartIdentity { + fn capture(pid: u32) -> Option { + let fields = proc_stat_fields(pid)?; + let start_ticks = std::str::from_utf8(fields.get(19)?) + .ok()? + .parse::() + .ok()?; + Some(Self { pid, start_ticks }) + } + + /// Alive, non-zombie, and still the same process start. + fn alive(self) -> bool { + let Some(fields) = proc_stat_fields(self.pid) else { + return false; + }; + let state = fields.first().copied().unwrap_or_default(); + let start = fields + .get(19) + .and_then(|field| std::str::from_utf8(field).ok()) + .and_then(|field| field.parse::().ok()); + start == Some(self.start_ticks) && state != b"Z" && state != b"X" + } +} + +fn proc_stat_fields(pid: u32) -> Option> { + // The test only uses this while the test binary runs; leak the stat bytes so + // the field slices stay simple. Fixture PIDs are few. + let stat: &'static [u8] = Box::leak( + fs::read(format!("/proc/{pid}/stat")) + .ok()? + .into_boxed_slice(), + ); + let close = stat.iter().rposition(|byte| *byte == b')')?; + Some( + stat[close + 1..] + .split(|byte| byte.is_ascii_whitespace()) + .filter(|field| !field.is_empty()) + .collect(), + ) +} + +async fn wait_identity_gone(identity: StartIdentity) { + let deadline = Instant::now() + Duration::from_secs(2); + while identity.alive() { + if Instant::now() >= deadline { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!( + !identity.alive(), + "observed process {} (start {}) is still alive", + identity.pid, + identity.start_ticks + ); +} + +/// Wait for one fixture event as an observable fence. The wait is bounded; it +/// never orders the test by a fixed sleep. +async fn wait_for_event(path: &Path, name: &str) -> Value { + let deadline = Instant::now() + SETUP_BOUND; + loop { + if let Some(event) = read_events(path) + .into_iter() + .find(|event| event.get("event").and_then(Value::as_str) == Some(name)) + { + return event; + } + assert!( + Instant::now() < deadline, + "fixture did not record event {name}" + ); + tokio::time::sleep(Duration::from_millis(5)).await; + } +} + +#[tokio::test] +async fn new_session_returns_peer_id_and_one_new_request() { + let root = TestRoot::new("new"); + let mut client = connect(&root, args(&root, "normal"), OPERATION_BOUND).await; + assert_eq!(client.active_count(), 1); + let pid = client.pid(); + + let capabilities: AcpAgentCapabilities = client.initialize().await.expect("initialize"); + assert!(capabilities.resume, "fixture advertises resume"); + assert!(capabilities.load, "fixture advertises load"); + + let session_id = client.new_session().await.expect("session/new"); + assert!( + session_id.starts_with("fixture-session-"), + "peer-assigned id is returned verbatim" + ); + let result = client + .prompt(&session_id, "inspect the fixture") + .await + .expect("prompt"); + assert_eq!(result.text, "delegated-reply"); + assert!(!result.truncated); + assert_eq!(result.stop_reason, AcpStopReason::EndTurn); + assert_eq!( + client.prompt_wire_state(), + Some("written"), + "the pipe writer, not just SDK publication, delivered the prompt frame" + ); + + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed, "direct child was reaped"); + assert!(cleanup.direct_child_reaped); + assert!( + result.completed(&cleanup), + "end_turn plus cleanup completes" + ); + wait_pid_gone(pid).await; + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "initialize"), 1); + assert_eq!(count(&events, "session/new"), 1); + assert_eq!(count(&events, "session/resume"), 0); + assert_eq!(count(&events, "session/load"), 0); + assert_eq!(count(&events, "session/prompt"), 1); + assert_eq!( + count(&events, "session/cancel"), + 0, + "a matching response consumed before close forbids a late cancel" + ); + let new = named(&events, "session/new")[0]; + assert_eq!(new["data"]["params"]["mcpServers"], serde_json::json!([])); + assert_eq!( + new["data"]["params"]["cwd"], + root.workdir().to_string_lossy().as_ref() + ); + let prompt = named(&events, "session/prompt")[0]; + assert_eq!(prompt["data"]["sessionId"], session_id); + assert_eq!( + prompt["data"]["prompt"], + serde_json::json!([{ "type": "text", "text": "inspect the fixture" }]) + ); +} + +#[tokio::test] +async fn resume_is_preferred_and_reuses_one_bound_id_across_children() { + let root = TestRoot::new("resume"); + let mut first = connect( + &root, + with_extra(&root, "normal", &["--reply", "first-reply"]), + OPERATION_BOUND, + ) + .await; + let first_pid = first.pid(); + first.initialize().await.expect("initialize"); + let session_id = first.new_session().await.expect("session/new"); + assert_eq!( + first + .prompt(&session_id, "remember the first task") + .await + .expect("first prompt") + .text, + "first-reply" + ); + first.close().await; + + for (index, reply) in ["second-reply", "third-reply"].iter().enumerate() { + let mut next = connect( + &root, + with_extra(&root, "normal", &["--reply", reply]), + OPERATION_BOUND, + ) + .await; + assert_ne!(next.pid(), first_pid, "each delegation owns a new child"); + let capabilities = next.initialize().await.expect("initialize"); + assert!(capabilities.resume); + assert_eq!( + next.restore_session(session_id.clone()) + .await + .expect("restore"), + AcpRestoreMethod::Resume + ); + let result = next + .prompt(&session_id, &format!("continue task {index}")) + .await + .expect("restored prompt"); + assert_eq!(result.text, *reply); + let cleanup = next.close().await; + assert!(cleanup.cleanup_confirmed); + } + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "start"), 3); + assert_eq!(count(&events, "session/new"), 1); + assert_eq!(count(&events, "session/resume"), 2); + assert_eq!(count(&events, "session/load"), 0); + assert_eq!(count(&events, "session/prompt"), 3); + for prompt in named(&events, "session/prompt") { + assert_eq!(prompt["data"]["sessionId"], session_id); + } +} + +#[tokio::test] +async fn load_only_discards_replay_history() { + let root = TestRoot::new("load"); + let mut first = connect(&root, args(&root, "load_only"), OPERATION_BOUND).await; + first.initialize().await.expect("initialize"); + let session_id = first.new_session().await.expect("session/new"); + first + .prompt(&session_id, "create the session") + .await + .expect("first prompt"); + first.close().await; + + let mut restored = connect(&root, args(&root, "load_only"), OPERATION_BOUND).await; + let capabilities = restored.initialize().await.expect("initialize"); + assert!(!capabilities.resume, "load-only fixture has no resume"); + assert!(capabilities.load); + assert_eq!( + restored + .restore_session(session_id.clone()) + .await + .expect("restore"), + AcpRestoreMethod::Load + ); + let result = restored + .prompt(&session_id, "only the fresh answer") + .await + .expect("prompt"); + assert_eq!(result.text, "delegated-reply"); + assert!( + !result.text.contains("REPLAY-SHOULD-NOT-APPEAR"), + "load replay must not enter the prompt result" + ); + restored.close().await; + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/new"), 1); + assert_eq!(count(&events, "session/resume"), 0); + assert_eq!(count(&events, "session/load"), 1); +} + +#[tokio::test] +async fn restore_without_capability_sends_no_setup_request() { + let root = TestRoot::new("no-restore"); + let mut client = connect(&root, args(&root, "no_restore"), OPERATION_BOUND).await; + let capabilities = client.initialize().await.expect("initialize"); + assert!(!capabilities.resume); + assert!(!capabilities.load); + assert_eq!( + client.restore_session("fixture-session-other").await, + Err(AcpDelegationError::RestoreUnsupported) + ); + client.close().await; + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/new"), 0); + assert_eq!(count(&events, "session/resume"), 0); + assert_eq!(count(&events, "session/load"), 0); +} + +#[tokio::test] +async fn restore_failure_does_not_fall_back_to_new_or_load() { + let root = TestRoot::new("reject-restore"); + let mut first = connect(&root, args(&root, "normal"), OPERATION_BOUND).await; + first.initialize().await.expect("initialize"); + let session_id = first.new_session().await.expect("session/new"); + first + .prompt(&session_id, "create") + .await + .expect("first prompt"); + first.close().await; + + let mut rejected = connect(&root, args(&root, "reject_restore"), OPERATION_BOUND).await; + let capabilities = rejected.initialize().await.expect("initialize"); + assert!(capabilities.resume, "restore is advertised but rejected"); + assert_eq!( + rejected.restore_session(session_id).await, + Err(AcpDelegationError::RestoreFailed) + ); + rejected.close().await; + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/new"), 1, "no fresh fallback"); + assert_eq!(count(&events, "session/resume"), 1); + assert_eq!(count(&events, "session/load"), 0, "no load retry"); +} + +#[tokio::test] +async fn permission_is_cancelled_and_unsupported_request_is_denied() { + let permission_root = TestRoot::new("permission"); + let mut client = connect( + &permission_root, + with_extra(&permission_root, "normal", &["--permission"]), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "request permission") + .await + .expect("prompt"); + assert!(result.text.contains("delegated-reply")); + client.close().await; + let events = read_events(&permission_root.record_path()); + let responses = named(&events, "permission_response"); + assert_eq!(responses.len(), 1); + assert_eq!( + responses[0]["data"]["result"]["outcome"], + serde_json::json!({ "outcome": "cancelled" }), + "permission is answered with the protocol cancellation outcome" + ); + let unsupported_root = TestRoot::new("unsupported"); + let sentinel = unsupported_root.path.join("sentinel-must-not-exist"); + let mut client = connect( + &unsupported_root, + with_extra( + &unsupported_root, + "normal", + &["--unsupported", "--sentinel", sentinel.to_str().unwrap()], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + client + .prompt(&session_id, "call an unsupported client method") + .await + .expect("prompt"); + client.close().await; + assert!( + !sentinel.exists(), + "unsupported callback had no side effect" + ); + let events = read_events(&unsupported_root.record_path()); + let responses = named(&events, "unsupported_response"); + assert_eq!(responses.len(), 1); + assert_eq!( + responses[0]["data"]["error"]["code"], + serde_json::json!(-32601), + "unsupported client request is denied with method-not-found" + ); +} + +#[tokio::test] +async fn prompt_text_is_truncated_on_a_utf8_boundary() { + let root = TestRoot::new("utf8"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--utf8-cut"]), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "return a large answer") + .await + .expect("prompt"); + assert!(result.truncated, "overflow is explicit"); + assert_eq!(result.text.len(), 32_766); + assert!(result.text.bytes().all(|byte| byte == b'a')); + assert!(!result.text.contains('€')); + client.close().await; +} + +#[tokio::test] +async fn late_update_after_prompt_response_is_not_collected() { + let root = TestRoot::new("late"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &[ + "--reply", + "authoritative", + "--late", + "LATE-SHOULD-NOT-APPEAR", + ], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "answer once") + .await + .expect("prompt"); + assert_eq!(result.text, "authoritative"); + assert!(!result.text.contains("LATE-SHOULD-NOT-APPEAR")); + client.close().await; +} + +#[tokio::test] +async fn long_update_stream_is_consumed_inline_and_truncated() { + let root = TestRoot::new("long-stream"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--flood", "200", "--flood-bytes", "32768"], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "long stream") + .await + .expect("a ready consumer accepts more than 64 updates"); + assert!(result.truncated, "output overflow is explicit"); + assert_eq!(result.text.len(), 32 * 1024); + assert_eq!(result.stop_reason, AcpStopReason::EndTurn); + let (peak, _, _, _) = client.ingress_diagnostics(); + assert_eq!( + peak, 1, + "only the matching response is ever handed to the SDK unconsumed" + ); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} + +#[tokio::test] +async fn oversized_frame_terminates_before_sdk_dispatch() { + let root = TestRoot::new("big-frame"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--big-frame"]), + OPERATION_BOUND, + ) + .await; + assert_eq!( + client.initialize().await, + Err(AcpDelegationError::FrameTooLarge) + ); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} + +#[tokio::test] +async fn stubborn_child_is_cleaned_within_the_cleanup_budget() { + let root = TestRoot::new("stubborn"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--stubborn"]), + Duration::from_millis(700), + ) + .await; + let pid = client.pid(); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let started = Instant::now(); + assert_eq!( + client.prompt(&session_id, "never answer").await, + Err(AcpDelegationError::DeadlineExceeded) + ); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + assert!( + started.elapsed() < CLEANUP_BOUND, + "cleanup stays inside the separate absolute budget" + ); + wait_pid_gone(pid).await; +} + +#[tokio::test] +async fn dropping_the_client_hands_cleanup_to_the_owned_supervisor() { + let root = TestRoot::new("drop"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--stubborn"]), + OPERATION_BOUND, + ) + .await; + let pid = client.pid(); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let event_path = root.record_path(); + { + let prompt = client.prompt(&session_id, "hold until cancellation"); + tokio::pin!(prompt); + tokio::select! { + result = &mut prompt => panic!("stubborn prompt unexpectedly completed: {result:?}"), + // Observable fence: the fixture recorded the prompt only after the + // frame reached its stdin, so publication definitely happened. + _ = wait_for_event(&event_path, "session/prompt") => {} + } + } + drop(client); + wait_pid_gone(pid).await; + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/prompt"), 1); + assert_eq!( + count(&events, "session/cancel"), + 1, + "drop requests session cancellation before process cleanup" + ); +} + +#[tokio::test] +async fn crash_reports_harness_exit_and_reaps_the_child() { + let root = TestRoot::new("crash"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--crash"]), + OPERATION_BOUND, + ) + .await; + let pid = client.pid(); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + assert!(matches!( + client.prompt(&session_id, "crash").await, + Err(AcpDelegationError::PromptFailed | AcpDelegationError::HarnessExited) + )); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + assert_eq!( + cleanup.exit_status.and_then(|status| status.code()), + Some(3) + ); + wait_pid_gone(pid).await; +} + +#[tokio::test] +async fn prompt_requires_the_matching_session_and_runs_once() { + let root = TestRoot::new("one-prompt"); + let mut client = connect(&root, args(&root, "normal"), OPERATION_BOUND).await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + assert_eq!( + client.prompt("fixture-session-other", "wrong").await, + Err(AcpDelegationError::SessionMismatch) + ); + let result = client + .prompt(&session_id, "the only prompt") + .await + .expect("first prompt"); + assert_eq!(result.stop_reason, AcpStopReason::EndTurn); + assert_eq!( + client.prompt(&session_id, "second prompt").await, + Err(AcpDelegationError::InvalidPhase) + ); + client.close().await; + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/prompt"), 1); +} + +#[tokio::test] +async fn cancelled_stop_reason_is_preserved() { + let root = TestRoot::new("cancelled-reason"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--stop-reason", "cancelled"]), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "return cancelled") + .await + .expect("prompt"); + assert_eq!(result.stop_reason, AcpStopReason::Cancelled); + client.close().await; +} + +#[tokio::test] +async fn process_group_descendant_is_terminated() { + let root = TestRoot::new("group"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--descendant"]), + OPERATION_BOUND, + ) + .await; + let leader = StartIdentity::capture(client.pid()).expect("leader identity"); + // Capture the descendant before any cleanup can start: its identity is + // independent of the client's own `/proc` group scan. + let descendant_pid = wait_for_event(&root.record_path(), "descendant").await["data"]["pid"] + .as_u64() + .expect("descendant pid") as u32; + let descendant = StartIdentity::capture(descendant_pid).expect("descendant identity"); + assert!(descendant.alive(), "descendant is running before cleanup"); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + client + .prompt(&session_id, "spawn a descendant") + .await + .expect("prompt"); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + wait_identity_gone(descendant).await; + wait_identity_gone(leader).await; +} + +#[tokio::test] +async fn long_byte_stream_is_consumed_inline_and_truncated() { + let root = TestRoot::new("long-byte-stream"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--flood", "200", "--flood-bytes", "60000"], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "twelve megabyte stream") + .await + .expect("consumed text is released, not charged cumulatively"); + assert!(result.truncated); + assert_eq!(result.text.len(), 32 * 1024); + assert_eq!(client.ingress_diagnostics().0, 1); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} + +#[tokio::test] +async fn unrelated_and_mismatched_responses_do_not_seal_prompt_text() { + let root = TestRoot::new("decoy"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &[ + "--decoy", + "--reply", + "REAL", + "--late", + "LATE-SHOULD-NOT-APPEAR", + ], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "answer through decoys") + .await + .expect("prompt"); + assert_eq!( + result.text, "P-S-REAL", + "only the response carrying the prompt id closes the text phase" + ); + assert!(!result.text.contains("LATE-SHOULD-NOT-APPEAR")); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} + +#[tokio::test] +async fn non_v1_handshake_is_rejected() { + let root = TestRoot::new("protocol-version"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--protocol-version", "2"]), + OPERATION_BOUND, + ) + .await; + assert_eq!( + client.initialize().await, + Err(AcpDelegationError::ProtocolVersion) + ); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} + +#[tokio::test] +async fn wrong_session_and_malformed_updates_are_ignored() { + let root = TestRoot::new("bad-update"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--bad-update", "--reply", "REAL"]), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "ignore bad updates") + .await + .expect("prompt"); + assert_eq!(result.text, "VALID-REAL"); + assert!(!result.text.contains("WRONG-SESSION")); + client.close().await; +} + +#[tokio::test] +async fn terminal_callback_is_rejected_without_side_effect() { + let root = TestRoot::new("terminal"); + let sentinel = root.path.join("terminal-side-effect-must-not-exist"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--terminal", "--sentinel", sentinel.to_str().unwrap()], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "create a terminal") + .await + .expect("prompt"); + assert_eq!(result.text, "delegated-reply"); + client.close().await; + assert!( + !sentinel.exists(), + "rejected terminal callback had no side effect" + ); + let events = read_events(&root.record_path()); + let responses = named(&events, "terminal_response"); + assert_eq!(responses.len(), 1); + assert_eq!( + responses[0]["data"]["error"]["code"], + serde_json::json!(-32601), + "terminal callback is denied with method-not-found" + ); +} + +#[tokio::test] +async fn permission_burst_is_rejected_without_backlog() { + let root = TestRoot::new("permission-burst"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--permission-flood", "128"]), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "ask many times") + .await + .expect("prompt"); + assert_eq!(result.text, "delegated-reply"); + let (peak, permissions, rejected, _) = client.ingress_diagnostics(); + assert_eq!(peak, 1, "request handling never queues in the SDK path"); + assert_eq!(permissions, 128); + assert_eq!(rejected, 0); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + let events = read_events(&root.record_path()); + let responses = named(&events, "permission_response"); + assert_eq!(responses.len(), 128); + for response in responses { + assert_eq!( + response["data"]["result"]["outcome"], + serde_json::json!({ "outcome": "cancelled" }) + ); + } +} + +#[tokio::test] +async fn mixed_burst_never_queues_frames_in_the_sdk_ingress() { + let root = TestRoot::new("mixed-burst"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &[ + "--bad-update", + "--decoy", + "--reply", + "REAL", + "--flood", + "200", + "--flood-bytes", + "8192", + "--late", + "LATE-SHOULD-NOT-APPEAR", + ], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "mixed burst") + .await + .expect("prompt"); + assert!(result.truncated); + assert!( + result.text.starts_with("VALID-P-S-"), + "updates before the matching response keep their wire order" + ); + assert!(!result.text.contains("WRONG-SESSION")); + assert!(!result.text.contains("LATE-SHOULD-NOT-APPEAR")); + let (peak, _, _, ignored) = client.ingress_diagnostics(); + assert_eq!( + peak, 1, + "200+ valid and invalid frames never accumulate in the SDK ingress" + ); + assert_eq!( + ignored, 3, + "wrong-session and two malformed updates ignored" + ); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} + +#[tokio::test] +async fn leader_exit_first_and_lingering_group_member_is_force_terminated() { + let root = TestRoot::new("group-forced"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--exit-after-prompt", "--group-helper", "3"], + ), + OPERATION_BOUND, + ) + .await; + let helper = StartIdentity::capture( + wait_for_event(&root.record_path(), "group_helper").await["data"]["pid"] + .as_u64() + .expect("group helper pid") as u32, + ) + .expect("group helper identity"); + assert!(helper.alive(), "helper is running before cleanup"); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + client + .prompt(&session_id, "answer then exit") + .await + .expect("prompt"); + let started = Instant::now(); + let cleanup = client.close().await; + assert!( + cleanup.cleanup_confirmed, + "cleanup only completes once the group is gone" + ); + assert!(cleanup.group_signal_sent); + assert!( + cleanup.forced, + "a member that ignores TERM requires the forced group termination path" + ); + assert_ne!( + helper.start_ticks, 0, + "identity was captured from the kernel" + ); + wait_identity_gone(helper).await; + assert!( + started.elapsed() < CLEANUP_BOUND, + "group termination stays inside the shared absolute budget" + ); +} + +#[tokio::test] +async fn self_exiting_group_member_is_given_a_term_grace() { + let root = TestRoot::new("group-grace"); + let marker = root.path.join("helper-exited"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &[ + "--exit-after-prompt", + "--group-helper", + "0.9", + "--helper-marker", + marker.to_str().unwrap(), + ], + ), + OPERATION_BOUND, + ) + .await; + let helper = StartIdentity::capture( + wait_for_event(&root.record_path(), "group_helper").await["data"]["pid"] + .as_u64() + .expect("group helper pid") as u32, + ) + .expect("group helper identity"); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + client + .prompt(&session_id, "answer then exit") + .await + .expect("prompt"); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + wait_identity_gone(helper).await; + assert!( + marker.exists(), + "the leader-exit-first path must not force-kill a member inside its TERM grace" + ); +} + +#[tokio::test] +async fn close_interrupts_a_pending_setup_request() { + let root = TestRoot::new("hang-setup"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--hang-setup"]), + Duration::from_secs(30), + ) + .await; + let leader = StartIdentity::capture(client.pid()).expect("leader identity"); + client.initialize().await.expect("initialize"); + let mut setup = Box::pin(client.new_session()); + let event_path = root.record_path(); + let barrier = wait_for_event(&event_path, "session/new"); + tokio::pin!(barrier); + tokio::select! { + result = &mut setup => panic!("setup unexpectedly completed: {result:?}"), + event = &mut barrier => { + assert_eq!(event["data"]["attempt"], serde_json::json!(1)); + } + } + // The setup request is in flight and will never be answered. Abandon the + // caller's wait; the supervisor still owns the child. + drop(setup); + let observer = client.cleanup_observer(); + assert_eq!(observer.active(), 1); + assert!(observer.latest().is_none()); + + let capacity = observer.clone(); + let started = Instant::now(); + let cleanup = client.close().await; + assert!( + started.elapsed() < Duration::from_secs(2), + "close must interrupt a pending setup instead of waiting for the run deadline" + ); + assert!( + cleanup.cleanup_confirmed, + "the owned group is reaped within the shared budget: {cleanup:?}" + ); + + let final_report = observer + .wait_for_cleanup() + .await + .expect("supervisor published final cleanup evidence"); + assert!(final_report.cleanup_confirmed); + assert_eq!( + capacity.active(), + 0, + "the slot is released only after proof" + ); + wait_identity_gone(leader).await; + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/new"), 1, "no setup retry"); + assert_eq!( + count(&events, "session/prompt"), + 0, + "shutdown never prompts without a session" + ); +} + +#[tokio::test] +async fn cleanup_observer_confirms_after_the_client_is_dropped() { + let root = TestRoot::new("observer"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--exit-after-prompt", "--group-helper", "2.5"], + ), + OPERATION_BOUND, + ) + .await; + let leader = StartIdentity::capture(client.pid()).expect("leader identity"); + let helper = StartIdentity::capture( + wait_for_event(&root.record_path(), "group_helper").await["data"]["pid"] + .as_u64() + .expect("group helper pid") as u32, + ) + .expect("group helper identity"); + assert!(helper.alive(), "the helper delays the group cleanup"); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + client + .prompt(&session_id, "answer then exit") + .await + .expect("prompt"); + + let observer = client.cleanup_observer(); + drop(client); + assert_eq!( + observer.active(), + 1, + "the slot stays charged while the owned group is still alive" + ); + assert!( + observer.latest().is_none(), + "no cleanup evidence exists before the group is reaped" + ); + + let capacity = observer.clone(); + let report = observer + .wait_for_cleanup() + .await + .expect("supervisor published final cleanup evidence"); + assert!(report.cleanup_confirmed); + assert_eq!(capacity.active(), 0, "the slot follows the final proof"); + wait_identity_gone(helper).await; + wait_identity_gone(leader).await; +} + +#[tokio::test] +async fn abandoned_setup_wait_does_not_leak_ingress_quota() { + let root = TestRoot::new("quota-release"); + let fence = root.path.join("release-first-new"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--reject-first-new", "--fence", fence.to_str().unwrap()], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + + let mut first = Box::pin(client.new_session()); + let event_path = root.record_path(); + let barrier = wait_for_event(&event_path, "session/new"); + tokio::pin!(barrier); + tokio::select! { + result = &mut first => panic!("first setup unexpectedly completed: {result:?}"), + _ = &mut barrier => {} + } + // Abandon the caller's wait while the response is still in flight. + drop(first); + // Observable fence: the fixture answers only after this file appears. + fs::write(&fence, b"go").expect("release the fixture response"); + + let session_id = client + .new_session() + .await + .expect("a later setup is not charged for the abandoned response"); + assert_eq!( + client.ingress_diagnostics().0, + 1, + "the actor released the consumed protocol-error response" + ); + let result = client + .prompt(&session_id, "the connection stays usable") + .await + .expect("prompt"); + assert_eq!(result.text, "delegated-reply"); + assert!(client.close().await.cleanup_confirmed); +} + +#[tokio::test] +async fn cancelled_before_publication_sends_no_prompt_and_no_cancel() { + let root = TestRoot::new("pre-publish-stop"); + let mut client = connect(&root, args(&root, "normal"), OPERATION_BOUND).await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + + // Establish the shutdown decision before the prompt command is submitted. + // Whether the actor observes the watch first or the queued command first, + // the pre-publication gate must refuse to enqueue the prompt. + client.request_shutdown(); + let result = client + .prompt(&session_id, "must never reach the harness") + .await; + assert!( + result.is_err(), + "a decided stop must refuse publication: {result:?}" + ); + assert_eq!( + client.prompt_wire_state(), + None, + "no prompt frame may be armed for an unpublished prompt" + ); + + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/prompt"), 0, "zero wire prompts"); + assert_eq!(count(&events, "session/cancel"), 0, "zero cancels"); +} + +#[tokio::test] +async fn deadline_before_publication_sends_no_prompt_and_no_cancel() { + let root = TestRoot::new("pre-publish-deadline"); + // Build/resolve the fixture and its cwd before starting the clock, so the + // absolute deadline measures only the ACP connection, not test setup. + let launch = launch(&root, args(&root, "normal")); + let deadline = Instant::now() + Duration::from_secs(2); + let mut client = timeout(SETUP_BOUND, DelegatedAcpClient::connect(launch, deadline)) + .await + .expect("connect completes") + .expect("fixture launches"); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + + // Wait for the actual absolute deadline instead of guessing a duration. + tokio::time::sleep_until(deadline).await; + let result = client + .prompt(&session_id, "must not be published after the deadline") + .await; + assert!( + matches!( + result, + Err(AcpDelegationError::DeadlineExceeded | AcpDelegationError::Closed) + ), + "expired deadline is reported without a prompt: {result:?}" + ); + assert_eq!(client.prompt_wire_state(), None); + + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/prompt"), 0); + assert_eq!(count(&events, "session/cancel"), 0); +} + +#[tokio::test] +async fn published_prompt_still_outstanding_sends_exactly_one_cancel() { + let root = TestRoot::new("published-cancel"); + let mut client = connect( + &root, + with_extra(&root, "normal", &["--stubborn"]), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let event_path = root.record_path(); + { + let prompt = client.prompt(&session_id, "hold the turn"); + tokio::pin!(prompt); + tokio::select! { + result = &mut prompt => panic!("stubborn prompt unexpectedly completed: {result:?}"), + // The fixture records the prompt only after its stdin received the + // complete frame, so this fence proves publication and delivery. + _ = wait_for_event(&event_path, "session/prompt") => {} + } + } + // The caller's wait is withdrawn here while the turn is still outstanding. + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/prompt"), 1, "one published attempt"); + assert_eq!( + count(&events, "session/cancel"), + 1, + "a published outstanding prompt gets exactly one cancel" + ); + assert_eq!( + unsupported_method_count(&events, "$/cancel_request"), + 0, + "the SDK's deferred automatic cancellation must not reach the wire" + ); +} + +#[tokio::test] +async fn unconfirmed_bounded_close_completes_through_the_observer() { + let root = TestRoot::new("bounded-close"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--exit-after-prompt", "--group-helper", "2.5"], + ), + OPERATION_BOUND, + ) + .await; + let leader = StartIdentity::capture(client.pid()).expect("leader identity"); + let helper = StartIdentity::capture( + wait_for_event(&root.record_path(), "group_helper").await["data"]["pid"] + .as_u64() + .expect("group helper pid") as u32, + ) + .expect("group helper identity"); + assert!(helper.alive(), "the helper delays group termination"); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + client + .prompt(&session_id, "answer then exit") + .await + .expect("prompt"); + + let observer = client.cleanup_observer(); + // The group helper ignores SIGTERM for 2.5s, so a 50ms close cannot have + // observed termination; the default production wait is unchanged. + let report = client.close_with_wait(Duration::from_millis(50)).await; + assert!( + !report.cleanup_confirmed, + "bounded close must return unconfirmed evidence: {report:?}" + ); + assert_eq!( + observer.active(), + 1, + "the supervisor keeps capacity until cleanup is proven" + ); + assert!(observer.latest().is_none()); + + let final_report = observer + .clone() + .wait_for_cleanup() + .await + .expect("supervisor published final cleanup evidence"); + assert!(final_report.cleanup_confirmed); + assert_eq!(observer.active(), 0, "the slot follows the final proof"); + wait_identity_gone(helper).await; + wait_identity_gone(leader).await; +} + +/// A clean close must really close our stdin write end. The benign fixture +/// records `stdin_eof` only after the pipe returns EOF and then exits zero, so +/// this proves the natural-exit window runs before any group signal instead of +/// relying on a flag or on the supervisor task dropping its last handle later. +#[tokio::test] +async fn clean_close_closes_stdin_and_the_harness_exits_on_eof() { + let root = TestRoot::new("eof"); + let mut client = connect(&root, args(&root, "normal"), OPERATION_BOUND).await; + let pid = client.pid(); + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + let result = client + .prompt(&session_id, "answer exactly once") + .await + .expect("prompt"); + assert_eq!(result.text, "delegated-reply"); + + let cleanup = client.close().await; + assert!( + cleanup.cleanup_confirmed, + "cleanup was confirmed: {cleanup:?}" + ); + assert_eq!( + cleanup.exit_status.and_then(|status| status.code()), + Some(0), + "the harness exited normally on EOF, not on a group signal: {cleanup:?}" + ); + wait_pid_gone(pid).await; + + let events = read_events(&root.record_path()); + assert_eq!(count(&events, "session/prompt"), 1); + assert_eq!( + count(&events, "stdin_eof"), + 1, + "our stdin write end was actually closed before the group was terminated" + ); + assert_eq!( + events.last().and_then(|event| event["event"].as_str()), + Some("stdin_eof"), + "EOF is observed after the prompt and immediately before natural exit" + ); +} diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs new file mode 100644 index 00000000..a1fe3ed6 --- /dev/null +++ b/tests/acp_delegation_e2e_tests.rs @@ -0,0 +1,3434 @@ +//! Real two-process Gateway harness for the ACP delegation acceptance work. +//! +//! The parent test never opens the SQLite store and never reopens the service +//! in-process. It spawns two independent OS processes that each boot the +//! production Gateway router (`build_agent_gateway_app`), the production +//! durable store, and the bundled RSS agent loop against one private Agent home +//! and database. The loopback bearer is a per-test synthetic value passed only +//! through the child environment. The fixture model is the existing +//! `ScriptedProvider`; its requests are appended to a transcript file so the +//! parent can inspect exactly what the second process put on the model wire. +//! +//! This file currently proves the transport/restart control: two real runs are +//! admitted over HTTP and completed by the first Gateway process; the Gateway +//! is stopped and reaped and its listener is closed; a second Gateway process +//! on the same private home/store admits a third distinct run on the same RSS +//! session, and its actual model input contains both prior turns in order. +//! +//! The provider override installed by `AgentService::inject_provider_host` is +//! consumed by exactly one worker, so each run asks the child over the private +//! stdin/stdout control pipe to install the model script prepared for that run +//! key and waits for the matching acknowledgement before admitting HTTP. + +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::str::FromStr; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use axum::serve; +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::Request; +use hyper::header::{ACCEPT, AUTHORIZATION, HOST}; +use hyper_util::rt::TokioIo; +use rustscript_agent::config::ProviderProfile; +use rustscript_agent::config_file::{AgentPaths, ConfigFileError}; +use rustscript_agent::{ + AgentGatewayConfig, AgentGatewayState, AgentProviderHost, ConfigFile, RunCancellation, + ScriptedProvider, build_agent_gateway_app, +}; +use serde_json::{Value, json}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +const CHILD_ENTRY: &str = "gateway_harness_child_entry"; +const SPEC_ENV: &str = "RSS_ACP_DELEGATION_E2E_CHILD_SPEC"; +const TOKEN_ENV: &str = "RSS_ACP_DELEGATION_E2E_CHILD_TOKEN"; + +const FIRST_PROMPT_MARKER: &str = "first-turn-prompt-marker-7f3c"; +const FIRST_ANSWER_MARKER: &str = "first-turn-answer-marker-91ab"; +const SECOND_PROMPT_MARKER: &str = "second-turn-prompt-marker-2d58"; +const SECOND_ANSWER_MARKER: &str = "second-turn-answer-marker-4e60"; +const THIRD_PROMPT_MARKER: &str = "third-turn-prompt-marker-5a17"; +const THIRD_ANSWER_MARKER: &str = "third-turn-answer-marker-8c33"; + +/// The child Gateway compiles the bundled RSS program at startup, which is +/// CPU-bound and stretches on a loaded host. The bound is still finite and +/// unchanged in kind: past it the startup wrapper drops the guard, which +/// reclaims the exact child inside the same independent reclamation window used +/// everywhere else. It was raised from 300 s after a measured 317 s cold start +/// on this 8-core host; the reclamation budget itself is untouched. +const READY_BUDGET: Duration = Duration::from_secs(900); +const RUN_BUDGET: Duration = Duration::from_secs(120); +const HTTP_BUDGET: Duration = Duration::from_secs(240); +const REAP_BUDGET: Duration = Duration::from_secs(30); +/// Bounded wait for the child's explicit provider-install acknowledgement. The +/// child either installs the exact script for the requested run key or reports +/// a refusal; silence is a failure, never an assumed success. +const ACK_BUDGET: Duration = Duration::from_secs(30); +/// One independent, absolute reclamation window for an owned child. A startup +/// timeout and a normal stop timeout both hand the guard here instead of +/// waiting without a bound, and every later attempt (explicit or `Drop`) +/// shares the same one instead of stacking fresh windows or forced signals. +const RECLAIM_BUDGET: Duration = Duration::from_secs(5); +const RECLAIM_POLL: Duration = Duration::from_millis(25); +/// The fixed number of `/proc//stat` rereads that the fallback used to +/// allow before it abandoned a child whose command line had already gone. Linux +/// clears the argument vector in `exit_mm` and only later publishes `Z` in +/// `exit_notify`, so this count could be exhausted while the exact child was +/// still alive. It is kept only as the threshold the regression must outlive; +/// the fallback itself now runs under `RECLAIM_BUDGET`. +#[cfg(unix)] +const FORMER_EXIT_RACE_REREADS: usize = 8; + +// TODO(harness): per-request connect/read deadlines are fixed per `request` +// and are not yet folded into the remaining run deadline; that needs a larger +// transport refactor and is out of scope for this test hardening. + +fn lease_tmp() -> PathBuf { + let base = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMPDIR") + .expect("RUSTSCRIPT_AGENT_TEST_TMPDIR must point into the assigned lease tmp"); + let base = PathBuf::from(base); + assert!( + base.is_dir(), + "the assigned lease tmp directory must exist before the fixture starts" + ); + base +} + +fn text_response(text: &str) -> Value { + json!({ + "text": text, + "tool_calls": [], + "usage": { "input_tokens": 1, "output_tokens": 1, "total_tokens": 2 }, + "reasoning": "", + "stop_reason": "stop" + }) +} + +/// One model turn prepared by the parent before the child process starts. Only +/// the `key` crosses the control pipe; the child resolves the answer and its +/// private transcript path from this profile, so the control pipe never carries +/// model content or credentials. +#[derive(Clone)] +struct FixtureRun { + key: String, + answer: Value, + acp_call: Option, + output_budget: Option, +} + +impl FixtureRun { + fn new(label: &str, answer_marker: &str) -> Self { + Self { + key: format!("{label}-{}", uuid::Uuid::new_v4().simple()), + answer: text_response(answer_marker), + acp_call: None, + output_budget: None, + } + } +} + +/// A control line the child wrote on its stdout. Lines that are not fixture +/// control objects (the libtest report, for example) are ignored by the parent. +fn fixture_control_line(line: &str) -> Option { + let value: Value = serde_json::from_str(line.trim()).ok()?; + value.get("fixture")?; + Some(value) +} + +fn acknowledge_control(payload: Value) { + let mut stdout = std::io::stdout().lock(); + writeln!(stdout, "{payload}").expect("write fixture control acknowledgement"); + stdout + .flush() + .expect("flush fixture control acknowledgement"); +} + +/// Child side of the per-run install handshake. The command carries only the +/// run key; the answer and transcript path come from the private spec the +/// parent wrote before spawning this process. +fn install_fixture_provider(state: &AgentGatewayState, runs: &[Value], key: &str) { + let Some(run) = runs.iter().find(|run| run["key"].as_str() == Some(key)) else { + acknowledge_control(json!({ + "fixture": "provider-install-refused", + "run_key": key, + "reason": "unknown_run_key", + })); + return; + }; + let transcript_path = run["transcript_path"] + .as_str() + .expect("prepared run transcript path"); + if let Some(budget) = run["output_budget"].as_u64() { + let limits = rustscript_agent::config::RunLimits::new( + 8, + 8, + budget, + Path::new(transcript_path) + .parent() + .unwrap() + .join("workspace"), + ) + .expect("fixture limits"); + state + .service() + .set_run_limits(limits) + .expect("apply fixture run limits before admission"); + } + let scripted = ScriptedProvider::new(); + scripted.push_ok(run["answer"].clone()); + let recorder = RecordingProvider { + inner: scripted, + acp_call: run["acp_call"] + .as_object() + .map(|object| Value::Object(object.clone())), + turn: Mutex::new(0), + transcript: Mutex::new( + fs::File::create(transcript_path).expect("create provider transcript"), + ), + }; + state + .service() + .inject_provider_host(std::sync::Arc::new(recorder)); + acknowledge_control(json!({ + "fixture": "provider-installed", + "run_key": key, + })); +} + +/// The model transport used by the child Gateway. It records the actual request +/// before delegating to the stock scripted provider, so the parent can assert +/// on the second process's model input even though that input never crosses the +/// process boundary as a test-owned object. +struct RecordingProvider { + inner: ScriptedProvider, + acp_call: Option, + turn: Mutex, + transcript: Mutex, +} + +impl AgentProviderHost for RecordingProvider { + fn call(&self, request: &Value, cancellation: &RunCancellation) -> Value { + { + let mut transcript = self.transcript.lock().expect("transcript lock"); + writeln!(transcript, "{}", json!({ "request": request })) + .expect("append provider transcript"); + transcript.flush().expect("flush provider transcript"); + } + let Some(call) = self.acp_call.as_ref() else { + return self.inner.call(request, cancellation); + }; + let mut turn = self.turn.lock().expect("fixture turn lock"); + *turn += 1; + let response = match *turn { + 1 => { + assert!( + request["tools"] + .as_array() + .unwrap() + .iter() + .any(|tool| tool["name"] == "delegate_acp"), + "configured ACP descriptor missing from actual model request" + ); + json!({"text":"","reasoning":"","stop_reason":"tool_calls","tool_calls":[call]}) + } + 2 => { + let block = acp_result(request, call["id"].as_str().unwrap()); + text_response(&format!( + "runner saw {}: {}", + block["result"]["status"].as_str().unwrap(), + block["content"].as_str().unwrap() + )) + } + _ => panic!("unexpected provider turn in ACP fixture"), + }; + json!({"ok":true,"response":response,"error":{}}) + } +} + +/// One private Agent home + workspace + SQLite database, shared by both the +/// first and the restarted Gateway process. +struct GatewayFixture { + root: PathBuf, + home: PathBuf, + workspace: PathBuf, + db_path: PathBuf, +} + +impl GatewayFixture { + fn new(label: &str) -> Self { + let root = lease_tmp().join(format!( + "acp-delegation-e2e-{label}-{}", + uuid::Uuid::new_v4().simple() + )); + let home = root.join("home"); + let workspace = root.join("workspace"); + fs::create_dir_all(&home).expect("create private Agent home"); + fs::create_dir_all(&workspace).expect("create trusted workspace"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)) + .expect("private fixture root mode"); + fs::set_permissions(&home, fs::Permissions::from_mode(0o700)) + .expect("private Agent home mode"); + fs::set_permissions(&workspace, fs::Permissions::from_mode(0o700)) + .expect("private workspace mode"); + } + let config = format!( + "version: 1\nmodel:\n provider: local-test\n model: synthetic\nproviders:\n local-test:\n protocol: codex-responses\n base_url: https://127.0.0.1:1\nworkspaces:\n allowed_roots:\n - '{workspace}'\n default: '{workspace}'\n named:\n project: '{workspace}'\n", + workspace = workspace.display() + ); + let config_path = home.join("config.yaml"); + fs::write(&config_path, config).expect("write trusted workspace policy"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&config_path, fs::Permissions::from_mode(0o600)) + .expect("private config mode"); + } + Self { + db_path: root.join("gateway.sqlite3"), + root, + home, + workspace, + } + } +} + +impl Drop for GatewayFixture { + fn drop(&mut self) { + // A failing fixture is preserved for inspection, but unwinding must + // never perform diagnostic I/O that could block or panic again. + if std::thread::panicking() { + return; + } + let _ = fs::remove_dir_all(&self.root); + } +} + +/// Owns one spawned harness child from the instant `spawn` returns. Every +/// early return, panic, or startup deadline between spawn and readiness runs +/// this guard's drop, which reclaims the exact process inside one finite +/// window instead of leaving an orphan Gateway or blocking forever. +struct ChildGuard { + child: Child, + pid: u32, + reaped: Option, + /// Opened by the first forced stop. An explicit reclamation and a later + /// `Drop` fallback share this one window and its single signal attempt + /// instead of stacking fresh ones. + reclaim: Option, +} + +impl ChildGuard { + fn new(child: Child) -> Self { + Self { + pid: child.id(), + child, + reaped: None, + reclaim: None, + } + } + + fn pid(&self) -> u32 { + self.pid + } + + fn stdin_mut(&mut self) -> &mut std::process::ChildStdin { + self.child.stdin.as_mut().expect("child stdin") + } + + fn take_stdin(&mut self) -> Option { + self.child.stdin.take() + } + + fn take_stdout(&mut self) -> Option { + self.child.stdout.take() + } + + /// Polls the exact owned child without taking ownership. An observed exit + /// was already reaped by `try_wait`, so the guard must never signal that + /// pid again. An interrupted poll is reported to the caller, whose own + /// deadline decides whether to retry; the guard itself never blocks. + fn try_wait(&mut self) -> std::io::Result> { + if let Some(status) = self.reaped { + return Ok(Some(status)); + } + let status = self.child.try_wait()?; + if let Some(status) = status { + self.reaped = Some(status); + } + Ok(status) + } + + /// Signals and reaps the exact owned child inside one finite, absolute + /// window and reports how reclamation concluded. + /// + /// A natural exit can win the race with the signal, so the bounded + /// observation below, not the `kill` result, decides whether this parent + /// reaped the child. Only an observed terminal status marks the guard + /// reaped; a failed or incomplete reclamation keeps the handle, the pid, + /// and the reason instead of pretending success. Every later entry opens + /// no new window and sends no second signal. + fn terminate(&mut self) -> Result { + if let Some(status) = self.reaped { + return Ok(Reclaim::AlreadyExited(status)); + } + match self.try_wait() { + Ok(Some(status)) => return Ok(Reclaim::AlreadyExited(status)), + Ok(None) => {} + // EINTR leaves the terminal state unknown but still owned, so a + // signal is safe and the bounded observation below stays the + // authority. + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} + // Do not signal a pid whose live ownership can no longer be proven + // by an observation; report the reclamation error instead. + Err(error) => { + return Err(ReclaimError { + pid: self.pid, + signal_error: None, + poll_error: Some(error), + }); + } + } + let pid = self.pid; + let window = self + .reclaim + .get_or_insert_with(|| ReclaimWindow::new(Instant::now(), RECLAIM_BUDGET)); + let outcome = window.reclaim(pid, &mut self.child)?; + let status = match &outcome { + Reclaim::AlreadyExited(status) | Reclaim::Signalled { status, .. } => *status, + }; + // A terminal state was observed by `try_wait`, which already reaped it. + self.reaped = Some(status); + Ok(outcome) + } +} + +/// The one absolute reclamation window for an owned child. It is opened by the +/// first forced stop, so an explicit timeout and a later `Drop` share one +/// deadline and at most one forced signal instead of stacking fresh attempts. +struct ReclaimWindow { + deadline: Instant, + /// Set before the first forced signal, so even a failed `kill` is never + /// retried by a later entry. + signal_attempted: bool, +} + +impl ReclaimWindow { + fn new(now: Instant, budget: Duration) -> Self { + Self { + deadline: now + budget, + signal_attempted: false, + } + } + + /// Signals and observes the target until the shared deadline. The first + /// entry performs exactly one forced signal attempt; a repeated entry + /// never signals again and never waits past the original window. A spent + /// window performs only the single non-blocking observation inside + /// `reclaim_until_terminal`. + fn reclaim( + &mut self, + pid: u32, + target: &mut T, + ) -> Result { + let mut signal_error = None; + let mut signalled = false; + if !self.signal_attempted { + self.signal_attempted = true; + signalled = true; + signal_error = target.signal().err(); + } + let status = match reclaim_until_terminal(pid, self.deadline, || target.wait()) { + Ok(status) => status, + Err(mut error) => { + error.signal_error = signal_error; + return Err(error); + } + }; + Ok(if signalled { + Reclaim::Signalled { + status, + signal_error, + } + } else { + Reclaim::AlreadyExited(status) + }) + } +} + +/// The two actions reclamation needs from an owned child: one forced signal and +/// one non-blocking terminal observation. A test double can drive the same +/// state machine when a real child cannot be held in a failing window. +trait ReclaimTarget { + fn signal(&mut self) -> std::io::Result<()>; + fn wait(&mut self) -> std::io::Result>; +} + +impl ReclaimTarget for Child { + fn signal(&mut self) -> std::io::Result<()> { + self.kill() + } + + fn wait(&mut self) -> std::io::Result> { + self.try_wait() + } +} + +/// How a successful reclamation concluded: an exit observed without a signal, +/// or a signal (possibly failed) followed by an observed terminal state. +#[derive(Debug)] +enum Reclaim { + AlreadyExited(ExitStatus), + Signalled { + status: ExitStatus, + signal_error: Option, + }, +} + +impl std::fmt::Display for Reclaim { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::AlreadyExited(status) => write!(f, "already exited with {status}"), + Self::Signalled { + status, + signal_error: Some(error), + } => write!(f, "signalled despite {error}, then exited with {status}"), + Self::Signalled { + status, + signal_error: None, + } => write!(f, "signalled, then exited with {status}"), + } + } +} + +/// A bounded reclamation that could not observe a terminal state. The guard +/// stays unreaped and keeps its child handle; `Drop` retries only inside the +/// same absolute window. +#[derive(Debug)] +struct ReclaimError { + pid: u32, + signal_error: Option, + poll_error: Option, +} + +impl std::fmt::Display for ReclaimError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "child {} did not reach a terminal state before the cleanup deadline", + self.pid + )?; + if let Some(error) = &self.signal_error { + write!(f, "; signal failed: {error}")?; + } + if let Some(error) = &self.poll_error { + write!(f, "; last wait error: {error}")?; + } + Ok(()) + } +} + +/// Observes the exact child until it reports a terminal status or the shared +/// absolute deadline passes. Errors are retained for the failure report but do +/// not end the observation early: only a real terminal state or the deadline +/// concludes reclamation. +fn reclaim_until_terminal( + pid: u32, + deadline: Instant, + mut observe: F, +) -> Result +where + F: FnMut() -> std::io::Result>, +{ + let mut poll_error; + loop { + match observe() { + Ok(Some(status)) => return Ok(status), + Ok(None) => poll_error = None, + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => { + poll_error = Some(error); + } + Err(error) => poll_error = Some(error), + } + let now = Instant::now(); + if now >= deadline { + return Err(ReclaimError { + pid, + signal_error: None, + poll_error, + }); + } + std::thread::sleep(RECLAIM_POLL.min(deadline - now)); + } +} + +impl Drop for ChildGuard { + fn drop(&mut self) { + if self.reaped.is_some() { + return; + } + // Never panic or write diagnostics while unwinding, and never mark an + // unreclaimed child as reaped: the bounded failure is simply retried + // inside the same window, which cannot signal a second time. + let _ = self.terminate(); + } +} + +/// The kernel facts the safety net needs from one `/proc//stat` read. +#[cfg(unix)] +#[derive(Clone, Copy, Debug)] +struct ProcStat { + state: char, + ppid: u32, + start_time: u64, +} + +/// One `/proc//stat` read. `None` when the pid is gone or its record is +/// unreadable. Identity is deliberately not validated here so the caller can +/// compare the fields itself. +#[cfg(unix)] +fn read_proc_stat(pid: u32) -> Option { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let (_, rest) = stat.rsplit_once(')')?; + // Fields after `comm` begin at field 3; `starttime` is field 22, i.e. the + // 20th whitespace field of the remainder. + let fields: Vec<&str> = rest.split_whitespace().collect(); + if fields.len() < 20 { + return None; + } + Some(ProcStat { + state: fields[0].chars().next()?, + ppid: fields[1].parse().ok()?, + start_time: fields[19].parse().ok()?, + }) +} + +/// One identity-proofed observation of the exact child. Only a child that still +/// shows its harness command line may be signalled; a terminal child and one +/// whose command line is already gone may only be waited for. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ExactChild { + /// Proven this exact child and still running the harness entry. + Live, + /// Proven this exact child with no command line text left: the kernel + /// clears the argument vector during exit, before the terminal state is + /// published, so waiting for it is the only safe action. + NoCommandLine, + /// Proven this exact child, already terminal: reap it without a signal. + Zombie, + /// Gone, or the pid no longer provably belongs to this child. + Lost, +} + +/// Spawn identity captured immediately after `spawn`, before any readiness +/// work. It lets the negative control prove which exact OS process the owning +/// guard had to reap, and lets an independent outer reclaimer refuse to signal +/// a pid that no longer matches this identity. +#[cfg(unix)] +#[derive(Clone, Copy, Debug)] +struct ChildIdentity { + pid: u32, + start_time: u64, +} + +#[cfg(unix)] +impl ChildIdentity { + fn capture(pid: u32) -> Option { + Some(Self { + pid, + start_time: read_proc_stat(pid)?.start_time, + }) + } + + fn write_witness(&self, path: &Path) { + fs::write( + path, + json!({ "pid": self.pid, "start_time": self.start_time }).to_string(), + ) + .expect("record the spawned child identity witness"); + } + + fn read_witness(path: &Path) -> Option { + let witness: Value = serde_json::from_str(&fs::read_to_string(path).ok()?).ok()?; + Some(Self { + pid: u32::try_from(witness["pid"].as_u64()?).ok()?, + start_time: witness["start_time"].as_u64()?, + }) + } + + /// This exact child's state, accepted only while the observation is + /// provably this child (`pid`, spawn start time, and parent must all + /// match). Anything else is `Lost`: the fallback then touches nothing. + fn exact_state(&self) -> ExactChild { + self.exact_state_observed(&mut || {}) + } + + /// `exact_state` with one test-only control point between the identity stat + /// and the command-line read. The exit-race regression makes the exact + /// child terminate inside precisely that window through this hook. + fn exact_state_observed(&self, after_first_stat: &mut dyn FnMut()) -> ExactChild { + let Some(stat) = self.matching_stat() else { + return ExactChild::Lost; + }; + after_first_stat(); + if stat.state == 'Z' { + return ExactChild::Zombie; + } + let Ok(cmdline) = fs::read(format!("/proc/{}/cmdline", self.pid)) else { + return ExactChild::Lost; + }; + if String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY) { + return ExactChild::Live; + } + if cmdline.iter().all(|byte| *byte == 0) { + // The kernel empties the argument vector in `exit_mm` before + // `exit_notify` publishes `Z`, and an empty argument vector reads + // as no text at all. Neither carries a command line any more, so + // this exact child may only be waited for, never signalled. + return ExactChild::NoCommandLine; + } + // A readable command line naming another program means this pid is no + // longer the harness child. + ExactChild::Lost + } + + /// One `/proc` stat of this pid, accepted only while it is provably this + /// exact child: the parent and spawn start time must both still match. + fn matching_stat(&self) -> Option { + let stat = read_proc_stat(self.pid)?; + (stat.ppid == std::process::id() && stat.start_time == self.start_time).then_some(stat) + } + + /// Independent outer safety net for the negative control. The identity + /// observation decides both safety and whether a signal is needed: only a + /// still-running exact child that still shows its harness command line is + /// signalled, while an exact child that is already terminal, or whose + /// command line is already gone, is only waited for. Anything that lost the + /// identity proof is left untouched. One absolute `RECLAIM_BUDGET` deadline + /// bounds the observation and every later wait. + fn reclaim_if_exact(&self) { + self.reclaim_if_exact_observed(&mut || {}, &mut |_| {}, &mut |_| {}); + } + + /// `reclaim_if_exact` with test-only hooks: the observation control point, + /// a record of every signal attempt, and the state seen by each bounded + /// wait attempt. A regression can therefore prove that a terminal or + /// command-line-free child is reaped without a signal, that the wait + /// outlives the former fixed re-read count, that it ends at the one + /// deadline when the exact child never terminates, and that a window spent + /// by an observation is refused before any signal or wait starts. + fn reclaim_if_exact_observed( + &self, + after_first_stat: &mut dyn FnMut(), + record_signal: &mut dyn FnMut(libc::pid_t), + on_wait: &mut dyn FnMut(char), + ) { + self.reclaim_if_exact_with_clock( + &|| Instant::now(), + after_first_stat, + record_signal, + on_wait, + ); + } + + /// The same safety net with an injected monotonic clock. The deadline is + /// still created here, before the identity observation, so a regression + /// cannot reopen the window after the observation has run; the regression + /// clock only makes that exact boundary reachable without a real wait. + fn reclaim_if_exact_with_clock( + &self, + clock: &dyn Fn() -> Instant, + after_first_stat: &mut dyn FnMut(), + record_signal: &mut dyn FnMut(libc::pid_t), + on_wait: &mut dyn FnMut(char), + ) { + let pid = self.pid as libc::pid_t; + // Opened before the identity observation, so the observation and every + // wait below share one window instead of stacking fresh ones. + let deadline = clock() + RECLAIM_BUDGET; + let observed = self.exact_state_observed(after_first_stat); + // The identity observation is fallback work itself: once it has spent + // the shared window, no signal or wait may start. + if clock() >= deadline { + return; + } + match observed { + ExactChild::Lost => return, + ExactChild::Zombie | ExactChild::NoCommandLine => {} + ExactChild::Live => { + // The identity observation above (pid, spawn start time, + // parent, and the harness command line) is what makes this + // signal safe; a bare cached pid is not. This is the only + // signal this safety net ever attempts. + record_signal(pid); + // A slow recorder must not hide a window that expired during + // it: this last check, not the callback, decides the syscall. + if clock() >= deadline { + return; + } + unsafe { + libc::kill(pid, libc::SIGKILL); + } + } + } + loop { + // Never begin a fresh identity re-read or a new poll once the + // window has expired; the last observation stays authoritative. + if clock() >= deadline { + return; + } + // Re-prove the identity immediately before every non-blocking + // wait, so a pid that is gone or no longer provably this child is + // never waited for. A matching non-terminal child is still a + // candidate: it needs no extra poll-for-`Z` round and no second + // budget. + let Some(stat) = self.matching_stat() else { + return; + }; + on_wait(stat.state); + // The observation above may have consumed the remaining window; + // this check sits next to the syscall so no wait starts after it. + if clock() >= deadline { + return; + } + let mut status = 0; + let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) }; + if waited == pid { + return; + } + if waited < 0 { + // EINTR keeps the same deadline; any other failure means this + // pid is not an unreaped child of ours, so there is nothing + // more this safety net may do. + let interrupted = + std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted; + if !interrupted { + return; + } + } + let now = clock(); + if now >= deadline { + return; + } + std::thread::sleep(RECLAIM_POLL.min(deadline - now)); + } + } +} + +/// The exact child-entry process before readiness has been admitted. The +/// guard is the only owner of the OS process from `spawn` onward. +struct HarnessChild { + guard: ChildGuard, + token: String, + ready_path: PathBuf, + stderr_path: PathBuf, +} + +fn spawn_harness_child( + fixture: &GatewayFixture, + label: &str, + db_path: &Path, + ready_path: &Path, + runs: &[FixtureRun], + hold_before_ready_ms: u64, +) -> HarnessChild { + let run_specs: Vec = runs + .iter() + .map(|run| { + json!({ + "key": run.key, + "answer": run.answer, + "acp_call": run.acp_call, + "output_budget": run.output_budget, + "transcript_path": fixture + .root + .join(format!("transcript-{label}-{}.jsonl", run.key)) + .to_string_lossy(), + }) + }) + .collect(); + let spec_path = fixture.root.join(format!("spec-{label}.json")); + fs::write( + &spec_path, + json!({ + "db_path": db_path.to_string_lossy(), + "workspace_home": fixture.home.to_string_lossy(), + "ready_path": ready_path.to_string_lossy(), + "runs": run_specs, + "run_timeout_ms": RUN_BUDGET.as_millis() as u64, + "hold_before_ready_ms": hold_before_ready_ms, + }) + .to_string(), + ) + .expect("write child Gateway spec"); + + let token = format!("rss-acp-e2e-{}", uuid::Uuid::new_v4().simple()); + let stderr_path = fixture.root.join(format!("stderr-{label}.log")); + let stderr = fs::File::create(&stderr_path).expect("create child stderr log"); + let assigned_tmp = lease_tmp(); + + let exe = std::env::current_exe().expect("current test executable"); + let mut command = Command::new(exe); + command + .args(["--exact", CHILD_ENTRY, "--ignored", "--nocapture"]) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .env("HOME", &fixture.home) + .env("TMPDIR", &assigned_tmp) + .env("TMP", &assigned_tmp) + .env("TEMP", &assigned_tmp) + .env("TEST_TMPDIR", &assigned_tmp) + .env("RUSTSCRIPT_AGENT_TEST_TMP", &assigned_tmp) + .env("RUSTSCRIPT_AGENT_TEST_TMPDIR", &assigned_tmp) + .env(SPEC_ENV, &spec_path) + .env(TOKEN_ENV, &token) + .current_dir(&fixture.workspace) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::from(stderr)); + let child = command.spawn().expect("Gateway harness child must spawn"); + // Ownership moves to the guard before any readiness work can fail. + let guard = ChildGuard::new(child); + // Record the exact spawn identity before the readiness wait, so the + // negative control can prove which process the owner had to reap even when + // the failure path unwinds. The write is fallible, so it runs only after + // the guard owns the process; its failure still reclaims that process. + #[cfg(unix)] + if let Some(identity) = ChildIdentity::capture(guard.pid()) { + identity.write_witness(&fixture.root.join(format!("identity-{label}.json"))); + } + HarnessChild { + guard, + token, + ready_path: ready_path.to_path_buf(), + stderr_path, + } +} + +/// Starts `cat` with empty `argv[0]` and no operands. While its stdin pipe +/// remains open, the exact live child has no command-line text, just like the +/// wait-only exit window. Start it directly: `execve` from a libtest worker +/// thread can temporarily expose the old thread-group leader as `Z` under the +/// same PID, before the new program takes over. +#[cfg(unix)] +fn spawn_empty_cmdline_child(fixture: &GatewayFixture) -> (ChildGuard, ChildIdentity) { + use std::os::unix::process::CommandExt; + + let assigned_tmp = lease_tmp(); + let cat = ["/bin/cat", "/usr/bin/cat"] + .into_iter() + .find(|path| Path::new(path).is_file()) + .expect("the empty-command-line control requires cat"); + let cat = fs::canonicalize(cat).expect("resolve the cat executable"); + let child = Command::new(&cat) + .arg0("") + .env_clear() + .env("TMPDIR", &assigned_tmp) + .env("TMP", &assigned_tmp) + .env("TEMP", &assigned_tmp) + .env("TEST_TMPDIR", &assigned_tmp) + .env("RUSTSCRIPT_AGENT_TEST_TMP", &assigned_tmp) + .env("RUSTSCRIPT_AGENT_TEST_TMPDIR", &assigned_tmp) + .current_dir(&fixture.root) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("the empty-command-line helper must spawn"); + let mut guard = ChildGuard::new(child); + let identity = ChildIdentity::capture(guard.pid()) + .expect("the empty-command-line helper must have a spawn identity"); + // `spawn` may return before Linux switches `/proc` to the new image. + // Confirm the image as well as the exact child's empty command line before + // the reclaim controls take their first observation. + let deadline = Instant::now() + RECLAIM_BUDGET; + let exe_path = format!("/proc/{}/exe", identity.pid); + loop { + assert!( + guard + .try_wait() + .expect("the empty-command-line helper must be pollable") + .is_none(), + "the helper must be live with stdin still open" + ); + if fs::read_link(&exe_path).is_ok_and(|exe| exe == cat) + && identity.exact_state() == ExactChild::NoCommandLine + { + return (guard, identity); + } + let now = Instant::now(); + assert!( + now < deadline, + "the helper must start with no command-line text" + ); + std::thread::sleep(RECLAIM_POLL.min(deadline - now)); + } +} + +/// A startup that never produced a usable listener. The retained guard is the +/// only owner of the exact child: the shared startup wrapper drops it while +/// unwinding, or the caller inspects it before dropping it itself. +struct StartFailure { + reason: String, + pid: u32, + status: Option, + ready_path: PathBuf, + stderr_path: PathBuf, + /// Boxed so the startup error variant stays small; the box still drops the + /// guard (and thus reclaims) on every unwind path. + guard: Box, +} + +impl std::fmt::Display for StartFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let status = match self.status { + Some(status) => status.to_string(), + None => "still running".to_string(), + }; + write!( + f, + "Gateway harness child {} (pid {}) was not admitted: {} [{}]\n{}", + self.ready_path.display(), + self.pid, + self.reason, + status, + fs::read_to_string(&self.stderr_path).unwrap_or_default() + ) + } +} + +/// A real Gateway OS process: the current test executable re-entered at one +/// exact ignored child test. The parent drives it only over loopback HTTP. +struct GatewayProcess { + child: ChildGuard, + address: SocketAddr, + token: String, + stderr_path: PathBuf, + /// Fixture-only control channel: the child writes one JSON object per line + /// on stdout; the parent waits for the acknowledgement that matches the + /// exact run key it asked the child to install. + control: tokio::sync::mpsc::UnboundedReceiver, +} + +impl std::fmt::Debug for GatewayProcess { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "GatewayProcess {{ pid: {}, address: {} }}", + self.child.pid(), + self.address + ) + } +} + +impl GatewayProcess { + fn start(fixture: &GatewayFixture, label: &str, runs: &[FixtureRun]) -> Self { + Self::start_bounded(fixture, label, runs, READY_BUDGET, 0) + } + + /// The single startup failure wrapper. The ordinary tests use the + /// production-size readiness budget; the negative control uses a short + /// observation clock so the real child is still alive and unready. Both + /// enter the same `Err => panic!` unwind, and that unwind drops the guard, + /// which is the only reclaimer of the exact child. + fn start_bounded( + fixture: &GatewayFixture, + label: &str, + runs: &[FixtureRun], + budget: Duration, + hold_before_ready_ms: u64, + ) -> Self { + let ready_path = fixture.root.join(format!("ready-{label}.json")); + match Self::start_with_budget_at( + fixture, + label, + runs, + ready_path, + fixture.db_path.clone(), + budget, + hold_before_ready_ms, + ) { + Ok(process) => process, + Err(failure) => panic!("{failure}"), + } + } + + /// Bounded readiness wait used by the ordinary tests and by the startup + /// failure controls. The returned guard always owns the exact child; on + /// failure the caller can inspect it instead of losing it to a panic. + fn start_with_budget_at( + fixture: &GatewayFixture, + label: &str, + runs: &[FixtureRun], + ready_path: PathBuf, + db_path: PathBuf, + budget: Duration, + hold_before_ready_ms: u64, + ) -> Result { + let launch = spawn_harness_child( + fixture, + label, + &db_path, + &ready_path, + runs, + hold_before_ready_ms, + ); + let HarnessChild { + mut guard, + token, + ready_path, + stderr_path, + } = launch; + let pid = guard.pid(); + // Drain the child's control channel from the moment the pipe exists, so + // an acknowledgement can never block the child on a full pipe. + let stdout = guard + .take_stdout() + .expect("the Gateway harness child must have a control stdout pipe"); + let (control_tx, control) = tokio::sync::mpsc::unbounded_channel::(); + std::thread::spawn(move || { + let reader = BufReader::new(stdout); + for line in reader.lines() { + match line { + Ok(line) => { + if control_tx.send(line).is_err() { + return; + } + } + Err(_) => return, + } + } + }); + let deadline = Instant::now() + budget; + loop { + match guard.try_wait() { + Ok(Some(status)) => { + return Err(StartFailure { + reason: format!("exited before publishing readiness ({status})"), + pid, + status: Some(status), + ready_path, + stderr_path, + guard: Box::new(guard), + }); + } + Ok(None) => {} + // An interrupted poll is not an exit: keep observing until the + // startup deadline below, which bounds this loop. + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} + Err(error) => { + return Err(StartFailure { + reason: format!("could not poll the child: {error}"), + pid, + status: None, + ready_path, + stderr_path, + guard: Box::new(guard), + }); + } + } + if let Ok(text) = fs::read_to_string(&ready_path) + && let Ok(ready) = serde_json::from_str::(&text) + && let Some(address) = ready.get("address").and_then(Value::as_str) + && let Ok(address) = SocketAddr::from_str(address) + { + return Ok(Self { + child: guard, + address, + token, + stderr_path, + control, + }); + } + if Instant::now() >= deadline { + return Err(StartFailure { + reason: format!("published no usable readiness within {budget:?}"), + pid, + status: None, + ready_path, + stderr_path, + guard: Box::new(guard), + }); + } + std::thread::sleep(Duration::from_millis(25)); + } + } + + fn stderr(&self) -> String { + fs::read_to_string(&self.stderr_path).unwrap_or_default() + } + + async fn health(&self) -> (u16, Value) { + let deadline = Instant::now() + READY_BUDGET; + loop { + if let Ok(response) = self.request("GET", "/health/detailed", None).await { + return response; + } + assert!( + Instant::now() < deadline, + "Gateway harness health did not become available: {}", + self.stderr() + ); + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + + async fn request( + &self, + method: &str, + path: &str, + body: Option<&Value>, + ) -> std::io::Result<(u16, Value)> { + let mut stream = + tokio::time::timeout(Duration::from_secs(10), TcpStream::connect(self.address)) + .await + .map_err(|_| { + std::io::Error::new(std::io::ErrorKind::TimedOut, "connect timed out") + })??; + let body = body.map(Value::to_string).unwrap_or_default(); + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: {}\r\nAuthorization: Bearer {}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + self.address, + self.token, + body.len() + ); + stream.write_all(request.as_bytes()).await?; + let mut response = Vec::new(); + tokio::time::timeout(HTTP_BUDGET, stream.read_to_end(&mut response)) + .await + .map_err(|_| { + std::io::Error::new(std::io::ErrorKind::TimedOut, "response timed out") + })??; + let response = String::from_utf8(response) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?; + let (headers, body) = response.split_once("\r\n\r\n").ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::InvalidData, "missing HTTP headers") + })?; + let status = headers + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid HTTP status") + })?; + let body = serde_json::from_str(body.trim()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?; + Ok((status, body)) + } + + /// Installs the model script for exactly one prepared run key on the child + /// and waits for the child's explicit acknowledgement of that same key. + /// + /// The production override is one-shot, so every admission has to be + /// preceded by this handshake. An empty, refused, mismatched, or missing + /// acknowledgement fails the fixture instead of admitting a run whose + /// model call would silently fall back to the real transport. + async fn install_run_provider(&mut self, key: &str) { + assert!( + !key.is_empty() + && key + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-'), + "the fixture run key must be a non-empty control token" + ); + { + let stdin = self.child.stdin_mut(); + writeln!(stdin, "install-provider {key}").expect("send provider install command"); + stdin.flush().expect("flush provider install command"); + } + let deadline = Instant::now() + ACK_BUDGET; + loop { + assert!( + Instant::now() < deadline, + "the child did not acknowledge provider {key} within {ACK_BUDGET:?}: {}", + self.stderr() + ); + let remaining = deadline.saturating_duration_since(Instant::now()); + match tokio::time::timeout(remaining, self.control.recv()).await { + Ok(Some(line)) => { + let Some(ack) = fixture_control_line(&line) else { + continue; + }; + match ack["fixture"].as_str() { + Some("provider-installed") => { + let acked = ack["run_key"].as_str().unwrap_or(""); + assert!( + !acked.is_empty(), + "the child sent an empty provider-install acknowledgement" + ); + assert_eq!( + acked, key, + "the child acknowledged a different run key than the one requested" + ); + return; + } + Some("provider-install-refused") => panic!( + "the child refused the provider install for {key}: {}", + ack["reason"].as_str().unwrap_or("unspecified") + ), + _ => panic!("the child sent an unusable provider-install acknowledgement"), + } + } + Ok(None) => { + panic!("the child control channel closed before acknowledging provider {key}") + } + Err(_) => continue, + } + } + } + + /// Reads this run's SSE stream until its own terminal event. The HTTP/1.1 + /// transfer framing is decoded by hyper, then only complete `data:` JSON + /// objects are trusted; a string assembled across chunks or a terminal for + /// another run id can never satisfy the observation. Connect, request, + /// read, and the optional `after_seq` continuation share one absolute + /// deadline. + async fn observe_terminal(&self, run_id: &str, budget: Duration) -> SseFrame { + let deadline = Instant::now() + budget; + let mut after_seq: Option = None; + let mut last_outcome = "no complete SSE event was observed".to_string(); + loop { + assert!( + Instant::now() < deadline, + "run {run_id} did not publish its terminal event within {budget:?}: {last_outcome}" + ); + match self.read_sse_to_terminal(run_id, after_seq, deadline).await { + Ok(SseOutcome::Terminal(frame)) => return frame, + Ok(SseOutcome::Ended { last_seq }) => { + after_seq = last_seq.or(after_seq); + last_outcome = format!( + "the event stream ended at seq {after_seq:?} without this run's terminal" + ); + } + Err(reason) => last_outcome = reason, + } + let pause = + Duration::from_millis(50).min(deadline.saturating_duration_since(Instant::now())); + tokio::time::sleep(pause).await; + } + } + + async fn read_sse_to_terminal( + &self, + run_id: &str, + after_seq: Option, + deadline: Instant, + ) -> Result { + let stream = + tokio::time::timeout(remaining_until(deadline)?, TcpStream::connect(self.address)) + .await + .map_err(|_| "SSE connect hit the shared deadline".to_string())? + .map_err(|error| format!("SSE connect failed: {error}"))?; + let (mut sender, connection) = tokio::time::timeout( + remaining_until(deadline)?, + hyper::client::conn::http1::handshake(TokioIo::new(stream)), + ) + .await + .map_err(|_| "SSE handshake hit the shared deadline".to_string())? + .map_err(|error| format!("SSE handshake failed: {error}"))?; + tokio::spawn(async move { + let _ = connection.await; + }); + + let path = match after_seq { + Some(seq) => format!("/v1/runs/{run_id}/events?after_seq={seq}"), + None => format!("/v1/runs/{run_id}/events"), + }; + let request = Request::builder() + .method("GET") + .uri(format!("http://{}{path}", self.address)) + .header(HOST, self.address.to_string()) + .header(AUTHORIZATION, format!("Bearer {}", self.token)) + .header(ACCEPT, "text/event-stream") + .body(Full::new(Bytes::new())) + .map_err(|error| format!("build SSE request: {error}"))?; + let mut response = + tokio::time::timeout(remaining_until(deadline)?, sender.send_request(request)) + .await + .map_err(|_| "SSE response headers hit the shared deadline".to_string())? + .map_err(|error| format!("SSE request failed: {error}"))?; + if !response.status().is_success() { + return Err(format!( + "SSE endpoint returned status {}", + response.status() + )); + } + + let mut buffer: Vec = Vec::new(); + let mut last_seq = after_seq; + loop { + let chunk = + match tokio::time::timeout(remaining_until(deadline)?, response.body_mut().frame()) + .await + { + Err(_) => return Err("SSE read hit the shared deadline".to_string()), + Ok(None) => return Ok(SseOutcome::Ended { last_seq }), + Ok(Some(Err(error))) => return Err(format!("SSE body failed: {error}")), + Ok(Some(Ok(frame))) => frame, + }; + let Some(data) = chunk.data_ref() else { + continue; + }; + buffer.extend_from_slice(data); + while let Some(raw) = take_sse_event(&mut buffer) { + let Some(frame) = parse_sse_frame(&raw) else { + continue; + }; + if frame.run_id != run_id { + return Err("SSE stream delivered an event for a different run".to_string()); + } + last_seq = Some(frame.seq); + if frame.is_terminal() { + return Ok(SseOutcome::Terminal(frame)); + } + } + } + } + + /// Graceful stop through the child's stdin control channel, bounded wait, + /// and an explicit proof that the process is gone and its listener closed. + fn stop_and_reap(mut self) { + { + let stdin = self.child.stdin_mut(); + writeln!(stdin, "shutdown").expect("send shutdown to the Gateway harness"); + stdin.flush().expect("flush shutdown"); + } + drop(self.child.take_stdin()); + + let deadline = Instant::now() + REAP_BUDGET; + loop { + match self.child.try_wait() { + Ok(Some(status)) => { + assert!( + status.success(), + "Gateway harness did not exit cleanly ({status}): {}", + self.stderr() + ); + break; + } + Ok(None) => {} + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} + Err(error) => panic!("could not poll the Gateway harness child: {error}"), + } + if Instant::now() >= deadline { + // A normal stop timeout hands the exact child to the same + // finite cleanup window the startup failure uses, then fails; + // the guard is reaped here, so its `Drop` cannot start a + // second window. + let reclaim = self.child.terminate(); + let detail = match &reclaim { + Ok(outcome) => outcome.to_string(), + Err(error) => error.to_string(), + }; + panic!( + "Gateway harness did not stop within {REAP_BUDGET:?} ({detail}): {}", + self.stderr() + ); + } + std::thread::sleep(Duration::from_millis(25)); + } + + let listener_deadline = Instant::now() + Duration::from_secs(5); + loop { + let refused = + std::net::TcpStream::connect_timeout(&self.address, Duration::from_millis(200)) + .is_err(); + if refused { + return; + } + assert!( + Instant::now() < listener_deadline, + "the stopped Gateway listener at {} is still accepting connections", + self.address + ); + std::thread::sleep(Duration::from_millis(50)); + } + } +} + +/// One complete event decoded from the SSE `data:` payload. Only the fields +/// the fixture needs for correlation are retained; the rest of the payload is +/// not interpreted. +#[derive(Debug)] +struct SseFrame { + event: String, + run_id: String, + seq: u64, + output: String, + /// Static failure text published with a non-completed terminal, kept only + /// for fixture diagnostics; successful terminals leave it empty. + error: String, +} + +impl SseFrame { + fn is_terminal(&self) -> bool { + matches!( + self.event.as_str(), + "run.completed" | "run.cancelled" | "run.failed" + ) + } +} + +enum SseOutcome { + Terminal(SseFrame), + Ended { last_seq: Option }, +} + +fn remaining_until(deadline: Instant) -> Result { + let now = Instant::now(); + if now >= deadline { + Err("the shared SSE deadline elapsed".to_string()) + } else { + Ok(deadline - now) + } +} + +/// Removes one complete SSE event from the front of `buffer`. Both LF and CRLF +/// event separators are accepted, so a frame is only handed out once its +/// terminating blank line has actually arrived. +fn take_sse_event(buffer: &mut Vec) -> Option { + let lf = buffer.windows(2).position(|window| window == b"\n\n"); + let crlf = buffer.windows(4).position(|window| window == b"\r\n\r\n"); + let (end, delimiter_len) = match (lf, crlf) { + (None, None) => return None, + (Some(end), None) => (end, 2), + (None, Some(end)) => (end, 4), + (Some(lf_end), Some(crlf_end)) if lf_end <= crlf_end => (lf_end, 2), + (Some(_), Some(crlf_end)) => (crlf_end, 4), + }; + let event = String::from_utf8_lossy(&buffer[..end]).into_owned(); + buffer.drain(..end + delimiter_len); + Some(event) +} + +/// Parses one SSE event, requiring the `event:` line and the JSON payload's own +/// `event`, `run_id`, and `seq` to be present and consistent. Keepalive +/// comments and frames without a complete JSON payload yield `None`. +fn parse_sse_frame(raw: &str) -> Option { + let mut event_name: Option<&str> = None; + let mut data_lines: Vec<&str> = Vec::new(); + for line in raw.lines() { + if line.starts_with(':') { + continue; + } + let Some((field, value)) = line.split_once(':') else { + continue; + }; + let value = value.strip_prefix(' ').unwrap_or(value); + match field { + "event" => event_name = Some(value), + "data" => data_lines.push(value), + _ => {} + } + } + let event_name = event_name?; + let payload: Value = serde_json::from_str(&data_lines.join("\n")).ok()?; + let event = payload.get("event")?.as_str()?; + if event != event_name { + return None; + } + Some(SseFrame { + event: event.to_string(), + run_id: payload.get("run_id")?.as_str()?.to_string(), + seq: payload.get("seq")?.as_u64()?, + output: sse_output_text(&payload), + error: payload + .get("error_message") + .and_then(Value::as_str) + .or_else(|| { + payload + .get("error") + .and_then(|error| error.get("message")) + .and_then(Value::as_str) + }) + .unwrap_or("") + .to_string(), + }) +} + +/// Extracts the run's final assistant text from either published terminal +/// shape: the provider-step branch carries `output.text`, while the plain +/// message branch carries `output.message.content`. +fn sse_output_text(payload: &Value) -> String { + let output = payload.get("output"); + if let Some(text) = output + .and_then(|output| output.get("text")) + .and_then(Value::as_str) + { + return text.to_string(); + } + match output + .and_then(|output| output.get("message")) + .and_then(|message| message.get("content")) + { + Some(Value::String(text)) => text.clone(), + Some(Value::Array(blocks)) => blocks + .iter() + .filter(|block| block["type"] == json!("text")) + .filter_map(|block| block["text"].as_str()) + .collect::>() + .join(" "), + _ => String::new(), + } +} + +fn transcript_requests(fixture: &GatewayFixture, label: &str, run_key: &str) -> Vec { + let path = fixture + .root + .join(format!("transcript-{label}-{run_key}.jsonl")); + let file = fs::File::open(&path).expect("provider transcript must exist"); + BufReader::new(file) + .lines() + .map(|line| { + let line = line.expect("read provider transcript line"); + serde_json::from_str::(&line).expect("parse provider transcript line") + }) + .collect() +} + +fn acp_result<'a>(request: &'a Value, call_id: &str) -> &'a Value { + let matches = request["messages"] + .as_array() + .unwrap() + .iter() + .filter_map(|message| message["content"].as_array()) + .flatten() + .filter(|block| block["type"] == "tool_result" && block["tool_call_id"] == call_id) + .collect::>(); + assert_eq!( + matches.len(), + 1, + "expected one result bound to the current ACP call" + ); + matches[0] +} + +fn message_text(message: &Value) -> String { + message["content"] + .as_array() + .into_iter() + .flatten() + .filter(|block| block["type"] == "text") + .filter_map(|block| block["text"].as_str()) + .collect::>() + .join(" ") +} + +/// The ordered user turns that reached the model in one actual request. +fn user_prompt_texts(request: &Value) -> Vec { + request["messages"] + .as_array() + .map(|messages| { + messages + .iter() + .filter(|message| message["role"] == json!("user")) + .map(message_text) + .collect() + }) + .unwrap_or_default() +} + +async fn create_session(process: &GatewayProcess, session_id: &str) { + let (status, created) = process + .request( + "POST", + "/api/sessions", + Some(&json!({ "session_id": session_id, "source": "http" })), + ) + .await + .expect("create session request"); + assert_eq!(status, 201, "session creation: {created}"); + assert_eq!(created["session"]["id"], json!(session_id)); +} + +async fn bind_workspace(process: &GatewayProcess, session_id: &str) { + let (status, bound) = process + .request( + "POST", + &format!("/v1/sessions/{session_id}/workspace"), + Some(&json!({ "workspace": "name:project" })), + ) + .await + .expect("bind workspace request"); + assert_eq!(status, 200, "workspace binding: {bound}"); + assert_eq!( + bound["session"]["workspace"]["selector"], + json!("name:project") + ); +} + +async fn admit_run(process: &GatewayProcess, session_id: &str, prompt: &str) -> String { + let (status, run) = process + .request( + "POST", + "/v1/runs", + Some(&json!({ "session_id": session_id, "input": { "message": prompt } })), + ) + .await + .expect("admit run request"); + assert_eq!(status, 202, "run admission: {run}"); + run["run_id"].as_str().expect("admitted run id").to_string() +} + +/// Boots the exact child entry as a real Gateway OS process. The child owns the +/// production router, the production SQLite store, and the bundled RSS loop. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "spawned as a real Gateway harness process by the parent test"] +async fn gateway_harness_child_entry() { + let Ok(spec_path) = std::env::var(SPEC_ENV) else { + return; + }; + let spec: Value = + serde_json::from_str(&fs::read_to_string(&spec_path).expect("read child Gateway spec")) + .expect("parse child Gateway spec"); + let token = std::env::var(TOKEN_ENV).expect("child synthetic bearer"); + let db_path = spec["db_path"].as_str().expect("child db path"); + let workspace_home = spec["workspace_home"].as_str().expect("child home"); + let ready_path = spec["ready_path"].as_str().expect("child ready path"); + let runs_spec = spec["runs"] + .as_array() + .cloned() + .expect("child run profiles"); + let run_timeout_ms = spec["run_timeout_ms"].as_u64().unwrap_or(90_000); + // Test-only startup control: hold after the listener is bound and before + // readiness is published or the stdin control thread exists. It makes the + // "spawned but not ready" ownership window deterministic without touching + // production code. + let hold_before_ready_ms = spec["hold_before_ready_ms"].as_u64().unwrap_or(0); + + let mut config = AgentGatewayConfig { + bearer_token: Some(token), + run_timeout: Duration::from_millis(run_timeout_ms), + ..AgentGatewayConfig::default() + }; + // Mirror the production gateway's source selection request exactly: load + // the same home config.yaml, derive `config_present`/`config_source`/ + // compaction from that one snapshot, and admit the decision through the + // RSS source policy. The test never names a checkout entry or compiles a + // file source; with this fixture the policy selects the embedded + // `bundled:coding` resource, which `/health/detailed` must report as + // `source.kind == "bundled"`. + let workspace_home = Path::new(workspace_home); + let paths = AgentPaths::from_home(workspace_home) + .expect("resolve the production Agent home for the child"); + let loaded_config = match ConfigFile::load(paths.config_path()) { + Ok(config) => Some(config), + Err(ConfigFileError::MissingFile { .. }) => None, + Err(_) => panic!("the child fixture config.yaml could not be loaded"), + }; + if let Some(loaded) = &loaded_config { + config.approvals = loaded.approvals.clone(); + } + let config_present = loaded_config.is_some(); + let config_source = loaded_config + .as_ref() + .map(|config| config.agent.source.clone()); + let compaction_settings = loaded_config + .as_ref() + .map(|config| config.compaction.clone()) + .unwrap_or_default(); + let mut selection = serde_json::Map::new(); + selection.insert("config_present".to_string(), Value::Bool(config_present)); + if let Some(source) = config_source { + selection.insert("config_source".to_string(), Value::String(source)); + } + let state = AgentGatewayState::with_agent_selection_and_compaction( + config, + Value::Object(selection), + Some(Path::new(db_path)), + compaction_settings, + ) + .expect("the production bundled RSS selection must compile against the durable store") + .with_workspace_home(workspace_home); + // The provider override is one-shot, so the child installs a fresh scripted + // host only when the parent asks for a specific prepared run key and then + // acknowledges exactly that key. Nothing is installed at startup: a run + // admitted without this handshake must fall back to the real transport. + if let Some(loaded) = loaded_config + .as_ref() + .filter(|loaded| !loaded.acp_harnesses.is_empty()) + { + let policy = rustscript_agent::service::acp_session_pins::AcpDelegationPolicy::install( + loaded, + state.persistence().expect("durable fixture store"), + state.service(), + ) + .expect("validate configured ACP harness") + .map(std::sync::Arc::new); + state + .service() + .install_acp_delegation(policy) + .expect("install ACP policy"); + } + state + .service() + .set_provider_profile(ProviderProfile::builtin("local-agent").expect("local-agent profile")) + .expect("install the local-agent provider profile"); + + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("bind real loopback Gateway listener"); + let address = listener.local_addr().expect("child listener address"); + if hold_before_ready_ms > 0 { + std::thread::sleep(Duration::from_millis(hold_before_ready_ms)); + } + fs::write( + ready_path, + json!({ "address": address.to_string(), "pid": std::process::id() }).to_string(), + ) + .expect("publish child readiness"); + + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let control_state = state.clone(); + std::thread::spawn(move || { + let mut line = String::new(); + loop { + line.clear(); + match std::io::stdin().lock().read_line(&mut line) { + Ok(0) => { + let _ = shutdown_tx.send(()); + return; + } + Ok(_) => { + let command = line.trim(); + if command == "shutdown" { + let _ = shutdown_tx.send(()); + return; + } + if let Some(key) = command.strip_prefix("install-provider ") { + install_fixture_provider(&control_state, &runs_spec, key.trim()); + } + } + Err(_) => { + let _ = shutdown_tx.send(()); + return; + } + } + } + }); + + let app = build_agent_gateway_app(state.clone()); + serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(async move { + let _ = shutdown_rx.await; + }) + .await + .expect("real Gateway router must serve until shutdown"); + + // Test control channel: the parent writes `shutdown` to stdin, which drops + // the oneshot and ends the graceful serve future, then this child stops + // admission, cancels/joins the owned service workers, and exits 0. The + // standalone harness does not exercise the stock binary's SIGINT + // registration/orchestration path. + let deadline = Instant::now() + Duration::from_secs(15); + loop { + match state.service().shutdown().await { + Ok(()) => break, + Err(error) => { + assert!( + Instant::now() < deadline, + "Gateway service did not shut down after the router stopped: {error}" + ); + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + } + drop(state); +} + +#[cfg(target_os = "linux")] +#[path = "fixtures/acp_policy/build.rs"] +mod acp_fixture; + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn configured_acp_is_exposed_to_the_admitted_rss_model() { + let fixture = GatewayFixture::new("acp"); + let peer = fixture.root.join("acp-peer"); + acp_fixture::compile_policy_agent(&peer); + let config = fixture.home.join("config.yaml"); + writeln!( + fs::OpenOptions::new().append(true).open(config).unwrap(), + "acp_harnesses:\n - id: fixture\n command: {}", + json!(peer), + ) + .unwrap(); + let turn = FixtureRun::new("schema", "schema-checked"); + let mut gateway = GatewayProcess::start(&fixture, "acp", std::slice::from_ref(&turn)); + let session_id = "acp-schema-session"; + create_session(&gateway, session_id).await; + bind_workspace(&gateway, session_id).await; + gateway.install_run_provider(&turn.key).await; + let run_id = admit_run(&gateway, session_id, "Check the configured tool catalog.").await; + let terminal = gateway.observe_terminal(&run_id, HTTP_BUDGET).await; + gateway.stop_and_reap(); + assert_eq!(terminal.event, "run.completed"); + let requests = transcript_requests(&fixture, "acp", &turn.key); + assert_eq!(requests.len(), 1); + let tools = requests[0]["request"]["tools"] + .as_array() + .expect("model tool array"); + let delegate = tools.iter().find(|tool| tool["name"] == "delegate_acp"); + assert!( + delegate.is_some(), + "configured ACP descriptor missing from actual model request" + ); + assert_eq!( + model_tool_schema(delegate.unwrap())["additionalProperties"], + false + ); +} + +#[cfg(target_os = "linux")] +fn model_tool_schema(tool: &Value) -> Value { + tool.get("schema") + .or_else(|| tool.get("input_schema")) + .cloned() + .or_else(|| { + tool["schema_json"] + .as_str() + .and_then(|raw| serde_json::from_str(raw).ok()) + }) + .expect("actual model schema") +} + +#[cfg(target_os = "linux")] +fn configure_acp(fixture: &GatewayFixture, extra: &[&str]) { + let peer = fixture.root.join("acp-peer"); + acp_fixture::compile_policy_agent(&peer); + let mut args = vec![ + json!("--spawn-log"), + json!(fixture.root.join("spawns")), + json!("--events"), + json!(fixture.root.join("events")), + json!("--store"), + json!(fixture.root.join("child-store")), + json!("--caps"), + json!(fixture.root.join("caps")), + json!("--reply"), + json!("external-reply"), + json!("--replay"), + json!("history-replay-excluded"), + ]; + args.extend(extra.iter().map(|arg| json!(arg))); + writeln!( + fs::OpenOptions::new().append(true).open(fixture.home.join("config.yaml")).unwrap(), + "approvals:\n process: allow\n reviewer: auto\nacp_harnesses:\n - id: fixture\n command: {}\n args: {}", + json!(peer), json!(args), + ).unwrap(); +} + +#[cfg(target_os = "linux")] +fn delegation_turn(label: &str, task: &str) -> FixtureRun { + let mut turn = FixtureRun::new(label, "unused ACP fixture answer"); + turn.acp_call = Some(json!({ + "id": format!("acp-call-{}", turn.key), + "name": "delegate_acp", + "arguments": {"harness_id": "fixture", "task": task}, + })); + turn +} + +#[cfg(target_os = "linux")] +fn peer_spawns(fixture: &GatewayFixture) -> usize { + fs::read_to_string(fixture.root.join("spawns")) + .unwrap_or_default() + .lines() + .count() +} + +#[cfg(target_os = "linux")] +fn peer_events(fixture: &GatewayFixture) -> Vec { + fs::read_to_string(fixture.root.join("events")) + .unwrap_or_default() + .lines() + .map(|line| serde_json::from_str(line).expect("parse peer phase")) + .collect() +} + +#[cfg(target_os = "linux")] +async fn decide_delegation( + gateway: &GatewayProcess, + fixture: &GatewayFixture, + run_id: &str, + turn: &FixtureRun, + expected_spawns: usize, + decision: &str, + continued: bool, +) { + let call = turn.acp_call.as_ref().unwrap(); + let call_id = call["id"].as_str().unwrap(); + let list_path = format!("/v1/runs/{run_id}/approvals"); + let deadline = Instant::now() + Duration::from_secs(40); + let approval = loop { + let (status, list) = + tokio::time::timeout_at(deadline.into(), gateway.request("GET", &list_path, None)) + .await + .expect("approval deadline") + .expect("list approvals"); + assert_eq!(status, 200, "run ended before the manual ACP challenge"); + assert_eq!(list["run_id"], run_id); + let items = list["approvals"].as_array().unwrap(); + if let Some(row) = items.first() { + assert_eq!(items.len(), 1); + break row.clone(); + } + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert_eq!(approval["run_id"], run_id); + assert_eq!(approval["tool_name"], "delegate_acp"); + assert_eq!( + approval["approval_id"], + format!("acp-delegation:{run_id}:{call_id}") + ); + let preview = approval["preview"].as_str().unwrap(); + assert!(preview.contains(call["arguments"]["task"].as_str().unwrap())); + assert!(preview.contains(if continued { + "continue the bound external session" + } else { + "create a new external session" + })); + assert_eq!( + peer_spawns(fixture), + expected_spawns, + "the peer launched before approval" + ); + let path = format!("{list_path}/{}", approval["approval_id"].as_str().unwrap()); + let (status, _) = gateway + .request("POST", &path, Some(&json!({"decision":decision}))) + .await + .expect("resolve real HTTP approval"); + assert_eq!(status, 200); +} + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn gateway_restarts_between_three_approved_rss_delegations() { + let fixture = GatewayFixture::new("approved-acp-restart"); + configure_acp(&fixture, &["--hold-task", "hold this prompt"]); + let session_id = "approved-acp-restart"; + let tasks = [ + "Store a private benign history marker 9a7c", + "Continue with the next operation", + "Continue after restart", + ]; + let turns = [ + delegation_turn("first", tasks[0]), + delegation_turn("second", tasks[1]), + delegation_turn("third", tasks[2]), + ]; + let mut run_ids = std::collections::HashSet::new(); + let mut gateway_pids = std::collections::HashSet::new(); + let controls = [ + delegation_turn("deny", "denied benign task"), + delegation_turn("load", "load-only benign task"), + delegation_turn("stop", "hold this prompt"), + delegation_turn("after-stop", "confirm unknown outcome remains fenced"), + delegation_turn( + "fresh-after-stop", + "use a clean main session after cancellation", + ), + ]; + let mut invalid = delegation_turn("extra-argument", "invalid input should not launch"); + let mut budgets = [ + delegation_turn("budget-below", "under minimum"), + delegation_turn("budget-equal", "at minimum"), + delegation_turn("budget-above", "above minimum"), + ]; + for (index, turn) in budgets.iter_mut().enumerate() { + let call = turn.acp_call.as_ref().unwrap(); + let minimal = json!({ + "type":"tool_result", "tool_call_id":call["id"], "name":"delegate_acp", + "content":"", "is_error":false, "error":{}, "truncated":true, + "result":{"harness_id":"fixture","status":"completed","text":"","stop_reason":"end_turn","truncated":true}, + }); + turn.output_budget = + Some(u64::try_from(minimal.to_string().len()).unwrap() + [0, 1, 5][index] - 1); + } + invalid.acp_call.as_mut().unwrap()["arguments"]["cwd"] = json!("untrusted"); + for (label, indices) in [("first", 0..2), ("second", 2..3)] { + let mut profiles = turns[indices.clone()].iter().collect::>(); + if label == "second" { + profiles.extend(controls.iter()); + profiles.push(&invalid); + profiles.extend(budgets.iter()); + } + let profiles = profiles.into_iter().cloned().collect::>(); + let mut gateway = GatewayProcess::start(&fixture, label, &profiles); + assert!( + gateway_pids.insert(gateway.child.pid()), + "Gateway did not change PID" + ); + let (status, health) = gateway.health().await; + assert_eq!(status, 200); + assert_bundled_source(&health, label); + if indices.start == 0 { + create_session(&gateway, session_id).await; + bind_workspace(&gateway, session_id).await; + } else { + let (status, reopened) = gateway + .request("GET", &format!("/api/sessions/{session_id}"), None) + .await + .unwrap(); + assert_eq!(status, 200); + assert_persisted_workspace(&reopened, &fixture); + } + for index in indices { + let turn = &turns[index]; + gateway.install_run_provider(&turn.key).await; + let run_id = admit_run( + &gateway, + session_id, + &format!("Delegate requested round {}", index + 1), + ) + .await; + assert!(run_ids.insert(run_id.clone())); + decide_delegation( + &gateway, + &fixture, + &run_id, + turn, + index, + "approved", + index != 0, + ) + .await; + let terminal = gateway.observe_terminal(&run_id, HTTP_BUDGET).await; + assert_eq!( + terminal.event, "run.completed", + "delegation run failed: {}", + terminal.error + ); + let expected = format!("ctx={index};reply=external-reply"); + assert_eq!(terminal.output, format!("runner saw completed: {expected}")); + let requests = transcript_requests(&fixture, label, &turn.key); + assert_eq!( + requests.len(), + 2, + "one tool selection and one feedback turn" + ); + let call_id = turn.acp_call.as_ref().unwrap()["id"].as_str().unwrap(); + let block = acp_result(&requests[1]["request"], call_id); + assert_eq!(block["content"], expected); + assert_eq!( + block["result"], + json!({"harness_id":"fixture", "status":"completed", "text":expected, "stop_reason":"end_turn", "truncated":false}) + ); + assert_eq!(peer_spawns(&fixture), index + 1); + assert_latest_peer_reaped(&fixture); + } + if label == "second" { + assert_three_peer_rounds(&fixture, tasks); + let fresh_session = "acp-fresh-after-cancellation"; + exercise_acp_controls( + &mut gateway, + &fixture, + session_id, + fresh_session, + &controls, + &invalid, + ) + .await; + exercise_acp_budgets(&mut gateway, &fixture, fresh_session, &budgets).await; + } + gateway.stop_and_reap(); + } + assert_eq!(run_ids.len(), 3); + assert_eq!(gateway_pids.len(), 2); + println!( + "ACP restart: Gateway processes=2 runs=3 approvals=3 child launches=3 new=1 resume_ack=2 prompt=3 same_external_id=true current_call_feedback=3" + ); +} + +#[cfg(target_os = "linux")] +fn assert_three_peer_rounds(fixture: &GatewayFixture, tasks: [&str; 3]) { + let events = peer_events(fixture); + let by_name = |name: &str| { + events + .iter() + .filter(|event| event["event"] == name) + .collect::>() + }; + let created = by_name("session/new"); + let recovered = by_name("session/resume"); + let accepted = by_name("setup_responded"); + let prompts = by_name("session/prompt"); + assert_eq!( + ( + created.len(), + recovered.len(), + accepted.len(), + prompts.len() + ), + (1, 2, 2, 3) + ); + assert!( + accepted + .iter() + .all(|event| event["data"]["method"] == "session/resume") + ); + assert!(by_name("session/load").is_empty()); + let external_id = created[0]["data"]["sessionId"] + .as_str() + .expect("one external ID"); + for event in recovered { + assert!( + event["data"]["params"]["sessionId"] == external_id, + "restore changed external identity" + ); + } + for (index, event) in prompts.into_iter().enumerate() { + assert!( + event["data"]["sessionId"] == external_id, + "prompt changed external identity" + ); + assert_eq!( + event["data"]["prompt"], + json!([{"type":"text", "text":tasks[index]}]) + ); + } + let spawned = by_name("process/spawn"); + let eof = by_name("stdin/eof"); + assert_eq!(spawned.len(), 3); + assert_eq!(eof.len(), 3); + let pids = spawned + .iter() + .map(|event| event["data"]["pid"].as_u64().unwrap()) + .collect::>(); + assert_eq!(pids.len(), 3); + assert_eq!( + eof.iter() + .map(|event| event["data"]["pid"].as_u64().unwrap()) + .collect::>(), + pids + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { + let fixture = GatewayFixture::new("restart"); + let session_id = format!( + "acp-delegation-e2e-session-{}", + uuid::Uuid::new_v4().simple() + ); + let prompts = [ + format!("{FIRST_PROMPT_MARKER}: note the durable first turn."), + format!("{SECOND_PROMPT_MARKER}: continue from the durable session."), + format!("{THIRD_PROMPT_MARKER}: continue after the Gateway restart."), + ]; + let prompt_markers = [ + FIRST_PROMPT_MARKER, + SECOND_PROMPT_MARKER, + THIRD_PROMPT_MARKER, + ]; + let answer_markers = [ + FIRST_ANSWER_MARKER, + SECOND_ANSWER_MARKER, + THIRD_ANSWER_MARKER, + ]; + let turns = [ + FixtureRun::new("turn1", FIRST_ANSWER_MARKER), + FixtureRun::new("turn2", SECOND_ANSWER_MARKER), + FixtureRun::new("turn3", THIRD_ANSWER_MARKER), + ]; + + // ---- First Gateway OS process: create/bind the session, run turns 1-2. ---- + let mut first = GatewayProcess::start(&fixture, "first", &turns[..2]); + let (status, health) = first.health().await; + assert_eq!(status, 200, "first Gateway health: {health}"); + assert_eq!(health["status"], json!("ok")); + assert_bundled_source(&health, "first"); + + create_session(&first, &session_id).await; + bind_workspace(&first, &session_id).await; + + let mut first_runs = Vec::new(); + for index in 0..2 { + // The one-shot provider override is installed for this exact run key + // and acknowledged before the parent admits the real HTTP run. + first.install_run_provider(&turns[index].key).await; + let run_id = admit_run(&first, &session_id, &prompts[index]).await; + let terminal = first.observe_terminal(&run_id, HTTP_BUDGET).await; + assert_eq!( + terminal.event, + "run.completed", + "turn {} must complete (event {}, error {:?}): {terminal:?}", + index + 1, + terminal.event, + terminal.error + ); + assert_eq!( + terminal.run_id, + run_id, + "turn {} terminal must belong to its own run", + index + 1 + ); + assert!( + terminal.output.contains(answer_markers[index]), + "turn {} terminal must carry its own fixture answer", + index + 1 + ); + for (other, marker) in answer_markers.iter().enumerate() { + if other != index { + assert!( + !terminal.output.contains(marker), + "turn {} terminal must not carry another turn's answer", + index + 1 + ); + } + } + first_runs.push(run_id); + } + assert_ne!( + first_runs[0], first_runs[1], + "the two runs in one Gateway process must be distinct real run ids" + ); + + // Each turn's own transcript holds exactly one actual provider request; + // the ordered user turns and the absent future answer are checked per run. + for index in 0..2 { + let requests = transcript_requests(&fixture, "first", &turns[index].key); + assert_eq!( + requests.len(), + 1, + "turn {} must make exactly one provider call: {requests:?}", + index + 1 + ); + let request = &requests[0]["request"]; + assert_eq!(request["provider"], json!("local-agent")); + assert_eq!( + request["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| tool["name"].as_str().unwrap()) + .collect::>(), + [ + "read_file", + "search_files", + "write_file", + "patch", + "terminal", + "process" + ] + ); + let wire = request.to_string(); + assert!( + !wire.contains(answer_markers[index]), + "turn {} must not see its own future answer: {request}", + index + 1 + ); + let user_texts = user_prompt_texts(request); + assert_eq!( + user_texts.len(), + index + 1, + "turn {} must carry exactly its expected user history: {request}", + index + 1 + ); + for (position, text) in user_texts.iter().enumerate() { + assert!( + text.contains(prompt_markers[position]), + "turn {} must carry user turn {} in order: {request}", + index + 1, + position + 1 + ); + } + } + + // Stop the exact first OS process, reap it, and prove its listener closed. + first.stop_and_reap(); + + // ---- Second Gateway OS process: same home/store, new run on the session. ---- + let mut second = GatewayProcess::start(&fixture, "second", &turns[2..]); + let (status, health) = second.health().await; + assert_eq!(status, 200, "second Gateway health: {health}"); + assert_bundled_source(&health, "second"); + + let (status, reopened_session) = second + .request("GET", &format!("/api/sessions/{session_id}"), None) + .await + .expect("reopened session readback"); + assert_eq!(status, 200, "reopened session: {reopened_session}"); + assert_persisted_workspace(&reopened_session, &fixture); + + // Both earlier terminals are readable from the fresh process over real SSE, + // and each replays only its own run's answer. + for index in 0..2 { + let terminal = second + .observe_terminal(&first_runs[index], HTTP_BUDGET) + .await; + assert_eq!( + terminal.event, + "run.completed", + "run {} must still be terminal after the restart (event {}, error {:?}): {terminal:?}", + index + 1, + terminal.event, + terminal.error + ); + assert_eq!( + terminal.run_id, + first_runs[index], + "run {} terminal must keep its own run id after the restart", + index + 1 + ); + assert!( + terminal.output.contains(answer_markers[index]), + "run {} output must survive the restart", + index + 1 + ); + for (other, marker) in answer_markers.iter().enumerate() { + if other != index { + assert!( + !terminal.output.contains(marker), + "run {} terminal must not carry another turn's answer after the restart", + index + 1 + ); + } + } + } + + second.install_run_provider(&turns[2].key).await; + let third_run = admit_run(&second, &session_id, &prompts[2]).await; + assert!( + first_runs.iter().all(|run| run != &third_run), + "the restarted Gateway must admit a distinct real run id" + ); + let third_terminal = second.observe_terminal(&third_run, HTTP_BUDGET).await; + assert_eq!( + third_terminal.event, "run.completed", + "the third turn must complete (event {}, error {:?}): {third_terminal:?}", + third_terminal.event, third_terminal.error + ); + assert_eq!(third_terminal.run_id, third_run); + assert!( + third_terminal.output.contains(THIRD_ANSWER_MARKER), + "the third turn terminal must carry its own fixture answer" + ); + for marker in [FIRST_ANSWER_MARKER, SECOND_ANSWER_MARKER] { + assert!( + !third_terminal.output.contains(marker), + "the third terminal must not carry an earlier turn's answer" + ); + } + + // The decisive control: the second Gateway's actual third-run input carries + // both distinct earlier user turns and both persisted assistant answers in + // order, plus the new prompt, and nothing of its own future answer. + let third_requests = transcript_requests(&fixture, "second", &turns[2].key); + assert_eq!( + third_requests.len(), + 1, + "the third turn must make exactly one provider call: {third_requests:?}" + ); + let third_request = &third_requests[0]["request"]; + let third_wire = third_request.to_string(); + assert!( + !third_wire.contains(THIRD_ANSWER_MARKER), + "the third model input must not already contain its own future answer: {third_request}" + ); + for marker in [FIRST_ANSWER_MARKER, SECOND_ANSWER_MARKER] { + assert!( + third_wire.contains(marker), + "the third model input must include the earlier assistant record: {third_request}" + ); + } + let third_user_texts = user_prompt_texts(third_request); + assert_eq!( + third_user_texts.len(), + 3, + "three persisted user turns must reach the third model call: {third_request}" + ); + for (position, text) in third_user_texts.iter().enumerate() { + assert!( + text.contains(prompt_markers[position]), + "the third model input must carry user turn {} in order: {third_request}", + position + 1 + ); + } + + let (status, messages) = second + .request("GET", &format!("/api/sessions/{session_id}/messages"), None) + .await + .expect("second Gateway session messages"); + assert_eq!(status, 200, "second session messages: {messages}"); + let user_messages: Vec<&Value> = messages["data"] + .as_array() + .expect("session message list") + .iter() + .filter(|message| message["role"] == json!("user")) + .collect(); + assert_eq!( + user_messages.len(), + 3, + "all three user turns must be persisted: {messages}" + ); + for (position, message) in user_messages.iter().enumerate() { + assert!( + message_text(message).contains(prompt_markers[position]), + "durable user turn {} must keep its order", + position + 1 + ); + } + + second.stop_and_reap(); +} + +/// Independent outer safety net for the startup negative control. It only +/// signals a pid still proven to be the exact child spawned by this test +/// (spawn start time, parent, and child entry), never a recycled cached pid, +/// and it waits for that child as well. It is dropped during unwinding, after +/// the owner's reclamation assertion had its chance. +#[cfg(unix)] +struct WitnessedChildReclaimer { + identity: Option, +} + +#[cfg(unix)] +impl Drop for WitnessedChildReclaimer { + fn drop(&mut self) { + if let Some(identity) = self.identity { + identity.reclaim_if_exact(); + } + } +} + +#[cfg(unix)] +fn panic_text(payload: Box) -> String { + if let Some(text) = payload.downcast_ref::() { + text.clone() + } else if let Some(text) = payload.downcast_ref::<&'static str>() { + (*text).to_string() + } else { + "".to_string() + } +} + +/// Startup failure control: a real child that never publishes usable +/// readiness must still be reclaimed by its owning guard. The test never calls +/// `terminate` itself: it enters the ordinary `GatewayProcess::start` failure +/// wrapper with a short observation clock, lets the wrapper's unwind drop the +/// guard, and then proves the exact spawned pid was reaped. A killed but +/// unreaped (zombie) child would still be visible under `/proc`. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn gateway_startup_failure_reclaims_the_real_child() { + let fixture = GatewayFixture::new("startup-failure"); + + // ---- Case 1: owner-driven reclamation through the startup wrapper. ---- + // + // The child holds 120 s after binding its listener and before publishing + // readiness, so the short observation clock expires while the exact + // process is alive and unready; no stdin control thread exists yet, so + // closing stdin could not stop it either. The wrapper panics exactly as + // `GatewayProcess::start` does; only the guard's `Drop` may reclaim it. + let blocked_ready = fixture.root.join("ready-blocked.json"); + let identity_path = fixture.root.join("identity-blocked.json"); + let observe = Duration::from_secs(5); + let started = Instant::now(); + let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _unready = GatewayProcess::start_bounded(&fixture, "blocked", &[], observe, 120_000); + })); + let elapsed = started.elapsed(); + // Read the witness written right after spawn, then arm the independent + // reclaimer before asserting: a regressed owner `Drop` must fail this test + // without leaking the exact child. + let outer = WitnessedChildReclaimer { + identity: ChildIdentity::read_witness(&identity_path), + }; + let failure = panic_text( + unwound.expect_err("a child that never publishes readiness must fail the startup wrapper"), + ); + assert!( + failure.contains("published no usable readiness"), + "the observation clock, not an early exit, must reject startup: {failure}" + ); + assert!( + failure.contains("still running"), + "the unready child must still be alive at the startup deadline: {failure}" + ); + assert!( + elapsed >= observe, + "the observation clock must actually elapse before startup is rejected" + ); + assert!( + elapsed < observe + RECLAIM_BUDGET + Duration::from_secs(2), + "startup rejection and owner reclamation must share one bounded cleanup window: {elapsed:?}" + ); + let identity = *outer + .identity + .as_ref() + .expect("the spawn identity witness must be recorded before the guard unwinds"); + assert!( + !Path::new(&format!("/proc/{}", identity.pid)).exists(), + "the parent must have reaped the exact unready child (pid {}); a live or zombie process would still appear under /proc", + identity.pid + ); + assert!( + !blocked_ready.exists(), + "the child must not have published readiness before owner reclamation" + ); + + // ---- Case 2: invalid readiness is never admitted. ---- + // + // A pre-seeded readiness file that names no listener must not produce a + // process. The child cannot open its durable store, so it exits before + // publishing anything; the parent observes that real natural exit and has + // already reaped it without any signal. + let invalid_ready = fixture.root.join("ready-invalid.json"); + let invalid_body = br#"{"address":"not-a-socket-address"}"#; + fs::write(&invalid_ready, invalid_body).expect("seed invalid readiness"); + let broken_db = fixture + .root + .join("missing-database-directory/gateway.sqlite3"); + let failure = GatewayProcess::start_with_budget_at( + &fixture, + "invalid-ready", + &[], + invalid_ready.clone(), + broken_db, + READY_BUDGET, + 0, + ) + .expect_err("invalid readiness must never be admitted"); + assert_eq!( + failure.guard.pid(), + failure.pid, + "the retained guard must own the exact inspected child" + ); + let status = failure + .status + .expect("the child must have exited before readiness"); + assert!( + !status.success(), + "a child that cannot open its store must exit unsuccessfully: {status}" + ); + assert!( + !Path::new(&format!("/proc/{}", failure.pid)).exists(), + "the exited child pid {} must already be reaped", + failure.pid + ); + assert_eq!( + fs::read(&invalid_ready).expect("invalid readiness readback"), + invalid_body, + "the child must not replace or accept invalid readiness" + ); + + // ---- Case 3: the bounded observation itself is a real wall-clock bound. ---- + // + // A real child stuck in an unobservable kernel state cannot be produced + // portably, so this one narrow path uses a test double: an observer that + // never reports a terminal state. Every real-child case above still drives + // the production reclamation path. + let fake_pid = u32::MAX - 1; + let window = Duration::from_millis(150); + let wait_started = Instant::now(); + let error = reclaim_until_terminal(fake_pid, wait_started + window, || Ok(None)) + .expect_err("an observation that never reaches a terminal state must hit its deadline"); + let waited = wait_started.elapsed(); + assert!( + waited >= window, + "the bounded observation must consume its window before failing: {waited:?}" + ); + assert!( + waited < window + Duration::from_secs(1), + "the bounded observation must not extend into a second cleanup window: {waited:?}" + ); + assert!( + error.to_string().contains("did not reach a terminal state"), + "the deadline failure must be reported as a reclamation error: {error}" + ); + + // EINTR is not a terminal state: the observer is retried, and a real + // terminal status still concludes reclamation. + use std::os::unix::process::ExitStatusExt; + let status = ExitStatus::from_raw(0); + let mut polls = 0; + let observed = + reclaim_until_terminal(fake_pid, Instant::now() + Duration::from_secs(1), || { + polls += 1; + if polls < 3 { + Err(std::io::Error::from(std::io::ErrorKind::Interrupted)) + } else { + Ok(Some(status)) + } + }) + .expect("interrupted observations must be retried"); + assert_eq!(observed, status); + assert_eq!( + polls, 3, + "interrupted polls must not be mistaken for an exit" + ); + + // ---- Case 4: one forced signal for the whole reclamation window. ---- + // + // A real child always dies to the first SIGKILL, so the failing window is + // driven through the same state machine with a controllable target: its + // signal fails once and its wait never reports a terminal state. The + // explicit stop consumes the window; the retry a `Drop` performs must + // neither signal again nor wait again. + struct UnreclaimedTarget { + signals: usize, + observations: usize, + } + + impl ReclaimTarget for UnreclaimedTarget { + fn signal(&mut self) -> std::io::Result<()> { + self.signals += 1; + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } + + fn wait(&mut self) -> std::io::Result> { + self.observations += 1; + Ok(None) + } + } + + let mut target = UnreclaimedTarget { + signals: 0, + observations: 0, + }; + let mut window = ReclaimWindow::new(Instant::now(), Duration::from_millis(150)); + let error = window + .reclaim(fake_pid, &mut target) + .expect_err("an unobservable target must exhaust the cleanup window"); + assert!( + error.signal_error.is_some(), + "the failed signal must be reported: {error}" + ); + assert_eq!( + target.signals, 1, + "the explicit forced stop must signal exactly once" + ); + let observations_before_retry = target.observations; + let retry = window + .reclaim(fake_pid, &mut target) + .expect_err("a spent window must not report an unobserved child as reaped"); + assert_eq!( + target.signals, 1, + "the retry a `Drop` performs must never signal a second time" + ); + assert_eq!( + target.observations - observations_before_retry, + 1, + "the retry must not start a second wait beyond one non-blocking check" + ); + assert!( + retry.signal_error.is_none(), + "the retry must not claim a new signal attempt: {retry}" + ); + + // ---- Case 5: the outer net reaps an exact child that already exited. ---- + // + // A real harness child is spawned and killed before it can publish + // readiness, but deliberately left unreaped by its owner, so `/proc` shows + // the exact child as a zombie with an empty command line. The outer net + // must recognise that state and reap that one pid instead of signalling a + // process that has already terminated. + let zombie_ready = fixture.root.join("ready-zombie.json"); + let HarnessChild { mut guard, .. } = + spawn_harness_child(&fixture, "zombie", &fixture.db_path, &zombie_ready, &[], 0); + let zombie_identity = ChildIdentity::read_witness(&fixture.root.join("identity-zombie.json")) + .expect("the zombie control needs the spawn identity witness"); + let zombie_pid = guard.pid() as libc::pid_t; + unsafe { + libc::kill(zombie_pid, libc::SIGKILL); + } + let zombie_deadline = Instant::now() + RECLAIM_BUDGET; + while zombie_identity.exact_state() != ExactChild::Zombie { + assert!( + Instant::now() < zombie_deadline, + "the killed child must become a zombie of this parent" + ); + std::thread::sleep(RECLAIM_POLL); + } + assert!( + fs::read(format!("/proc/{zombie_pid}/cmdline")).is_ok_and(|cmdline| cmdline.is_empty()), + "a zombie is exactly the state where the command line is empty" + ); + zombie_identity.reclaim_if_exact(); + assert!( + !Path::new(&format!("/proc/{zombie_pid}")).exists(), + "the outer net must reap the exact exited child instead of signalling it" + ); + // The retained owner handle observes the now-reaped pid through `try_wait` + // and must report the failure instead of claiming a fresh signal or reap. + assert!( + guard.terminate().is_err(), + "a child reaped elsewhere must not be reported as reaped by its owner" + ); + + // ---- Case 6: an exit between the identity stat and the command-line ---- + // read is still reaped, without a signal. + // + // The child is alive when the identity stat is taken and exits through the + // hook before the command-line read. That window used to read as a lost + // identity (empty `cmdline` against a pre-exit stat), so the outer net + // skipped `waitpid` and left the zombie unreaped. The bounded re-read must + // observe the same exact child in `Z` and reclaim it by waiting only. + let exiting_ready = fixture.root.join("ready-exiting.json"); + let HarnessChild { mut guard, .. } = spawn_harness_child( + &fixture, + "exiting", + &fixture.db_path, + &exiting_ready, + &[], + 0, + ); + let exiting_pid = guard.pid(); + let exiting_identity = ChildIdentity::read_witness(&fixture.root.join("identity-exiting.json")) + .expect("the exit-race control needs the spawn identity witness"); + assert_eq!( + exiting_identity.pid, exiting_pid, + "the witness must describe the exact spawned child" + ); + assert_ne!( + read_proc_stat(exiting_pid).map(|stat| stat.state), + Some('Z'), + "the exit-race child must still be running when its identity stat is taken" + ); + let mut hook_calls = 0usize; + let mut saw_empty_cmdline = false; + let mut saw_matching_zombie = false; + let mut after_first_stat = || { + hook_calls += 1; + unsafe { + libc::kill(exiting_pid as libc::pid_t, libc::SIGKILL); + } + let deadline = Instant::now() + RECLAIM_BUDGET; + loop { + let zombie = read_proc_stat(exiting_pid).is_some_and(|stat| { + stat.state == 'Z' + && stat.ppid == std::process::id() + && stat.start_time == exiting_identity.start_time + }); + if zombie { + saw_matching_zombie = true; + break; + } + if Instant::now() >= deadline { + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + saw_empty_cmdline = fs::read(format!("/proc/{exiting_pid}/cmdline")) + .is_ok_and(|cmdline| cmdline.is_empty()); + }; + let mut signalled = 0usize; + let mut record_signal = |_pid: libc::pid_t| signalled += 1; + let mut counted_waits = 0usize; + let mut count_wait = |_state: char| counted_waits += 1; + exiting_identity.reclaim_if_exact_observed( + &mut after_first_stat, + &mut record_signal, + &mut count_wait, + ); + assert!( + counted_waits > 0, + "the outer net must wait for the exact child it just observed" + ); + assert_eq!( + hook_calls, 1, + "the exit-race hook must run exactly once, between the identity stat and the command-line read" + ); + assert!( + saw_matching_zombie, + "the exact child must be a zombie of this parent once the hook has killed it" + ); + assert!( + saw_empty_cmdline, + "the exited child must be observed with an empty command line" + ); + assert_eq!( + signalled, 0, + "an exact child that already exited must be reaped, never signalled" + ); + assert!( + !Path::new(&format!("/proc/{exiting_pid}")).exists(), + "the outer net must wait/reap the exact exited child (pid {exiting_pid})" + ); + assert!( + guard.terminate().is_err(), + "a child reaped by the outer net must not be reported as reaped by its owner" + ); + + // ---- Case 7: an identity that no longer matches is refused. ---- + // + // The same observation order is armed with a witness whose spawn start time + // cannot match the live child, so the stat identity proof fails before the + // command-line read. The safety net must neither signal nor wait. + let mismatch_ready = fixture.root.join("ready-mismatch.json"); + let HarnessChild { mut guard, .. } = spawn_harness_child( + &fixture, + "mismatch", + &fixture.db_path, + &mismatch_ready, + &[], + 0, + ); + let mismatch_pid = guard.pid(); + let real_identity = ChildIdentity::read_witness(&fixture.root.join("identity-mismatch.json")) + .expect("the mismatch control needs the spawn identity witness"); + assert_eq!(real_identity.pid, mismatch_pid); + let wrong_identity = ChildIdentity { + pid: real_identity.pid, + start_time: real_identity.start_time.saturating_add(1), + }; + let mut reached_cmdline = false; + let mut after_first_stat = || reached_cmdline = true; + let mut signalled = 0usize; + let mut record_signal = |_pid: libc::pid_t| signalled += 1; + let mut waited = 0usize; + let mut count_wait = |_state: char| waited += 1; + wrong_identity.reclaim_if_exact_observed( + &mut after_first_stat, + &mut record_signal, + &mut count_wait, + ); + assert!( + !reached_cmdline, + "a stat failing the parent/start-time proof must be refused before the command-line read" + ); + assert_eq!(signalled, 0, "a refused identity must never be signalled"); + assert_eq!( + waited, 0, + "a refused identity must never be waited for, not even once" + ); + assert!( + Path::new(&format!("/proc/{mismatch_pid}")).exists(), + "a refused identity must leave the live child untouched" + ); + assert!( + guard + .try_wait() + .expect("the refused child must still be pollable") + .is_none(), + "the refused child must still be running and owned by this test" + ); + guard + .terminate() + .expect("the owner must still reap its own live child"); + assert!( + !Path::new(&format!("/proc/{mismatch_pid}")).exists(), + "owner reclamation must remove the mismatched child" + ); + + // ---- Case 8: a live exact child with no command-line text is waited for + // past the removed fixed re-read count, then reaped without a signal. ---- + // + // Linux clears the argument vector in `exit_mm` and publishes `Z` only + // later in `exit_notify`, so a fixed number of stat re-reads can run out + // while the exact child is still alive. That transient cannot be held open + // on demand, so this control uses the same kernel observation in its + // reproducible form: a real child starts with empty `argv[0]` and blocks + // on its stdin pipe. `/proc` + // really reports a live non-`Z` child with no command-line text, and only + // closing that pipe ends it. + let (mut free_child, free_identity) = spawn_empty_cmdline_child(&fixture); + let free_pid = free_child.pid(); + assert_eq!( + free_identity.pid, free_pid, + "the witness must describe the exact spawned child" + ); + let mut free_stdin = Some( + free_child + .take_stdin() + .expect("the helper owns its stdin pipe"), + ); + let mut observed_states = Vec::new(); + let mut on_wait = |state: char| { + observed_states.push(state); + if observed_states.len() == FORMER_EXIT_RACE_REREADS + 2 { + // Release the blocked child only after strictly more wait attempts + // than the removed re-read budget ever made. + free_stdin = None; + } + }; + let mut signalled = 0usize; + let mut record_signal = |_pid: libc::pid_t| signalled += 1; + let started = Instant::now(); + free_identity.reclaim_if_exact_observed(&mut || {}, &mut record_signal, &mut on_wait); + let elapsed = started.elapsed(); + assert_eq!( + signalled, 0, + "a child without command-line text must be waited for, never signalled" + ); + assert!( + observed_states.len() > FORMER_EXIT_RACE_REREADS, + "the fallback must keep waiting past the former {FORMER_EXIT_RACE_REREADS}-read give-up: {observed_states:?}" + ); + assert!( + observed_states + .iter() + .take(FORMER_EXIT_RACE_REREADS + 1) + .all(|state| *state != 'Z'), + "the exact child must stay non-terminal across more observations than the removed budget: {observed_states:?}" + ); + assert!( + !Path::new(&format!("/proc/{free_pid}")).exists(), + "the fallback must reap the exact command-line-free child once it ends (pid {free_pid})" + ); + assert!( + elapsed < RECLAIM_BUDGET + Duration::from_secs(2), + "the wait must stay inside its one absolute window: {elapsed:?}" + ); + assert!( + free_child.terminate().is_err(), + "a child reaped by the outer net must not be reported as reaped by its owner" + ); + + // ---- Case 9: a matching child that never terminates still ends the wait + // at the one absolute deadline. ---- + // + // Same real observation, but the stdin pipe stays open, so the exact child + // is still alive and non-terminal when the window expires. The wait must + // return at that original deadline, not start another one, and must leave + // the live child to its owner. + let (mut stuck_child, stuck_identity) = spawn_empty_cmdline_child(&fixture); + let stuck_pid = stuck_child.pid(); + let mut stuck_states = 0usize; + let mut on_wait = |state: char| { + assert_ne!( + state, 'Z', + "the stuck child must not become terminal during the window" + ); + stuck_states += 1; + }; + let started = Instant::now(); + stuck_identity.reclaim_if_exact_observed(&mut || {}, &mut |_| {}, &mut on_wait); + let elapsed = started.elapsed(); + assert!( + elapsed >= RECLAIM_BUDGET, + "a matching wait that never completes must consume the whole window before returning: {elapsed:?}" + ); + assert!( + elapsed < RECLAIM_BUDGET + Duration::from_secs(2), + "a matching wait must return at the original window instead of starting another: {elapsed:?}" + ); + assert!( + stuck_states > FORMER_EXIT_RACE_REREADS, + "the wait must observe the matching child repeatedly instead of giving up: {stuck_states}" + ); + assert!( + Path::new(&format!("/proc/{stuck_pid}")).exists(), + "the deadline path must leave the still-running exact child to its owner (pid {stuck_pid})" + ); + stuck_child + .terminate() + .expect("the owner must still reap its own live child after the deadline path"); + assert!( + !Path::new(&format!("/proc/{stuck_pid}")).exists(), + "owner reclamation must remove the timed-out child" + ); +} + +/// Deterministic proof that the outer fallback never signals once its single +/// window is spent: the identity observation of a still-live exact child +/// advances the test-only monotonic clock to exactly the entry deadline, and +/// the only trustworthy refutation of a signal is that the process is still +/// alive and owned afterwards. This control also rejects a window opened +/// after the observation, which would land a full budget later. +#[cfg(unix)] +#[test] +fn gateway_fallback_refuses_sigkill_after_live_deadline() { + use std::cell::Cell; + use std::os::unix::process::CommandExt; + + let tick = Cell::new(Instant::now()); + let clock = || tick.get(); + + // ---- Live at the first observation, window already spent. ---- + // + // The identity stat still proves a live child of this test; the observation + // hook then advances the clock to exactly the entry deadline. Signalling + // here used to be reachable, and the only trustworthy refutation is that + // the exact process is still alive and owned afterwards. Had the deadline + // been opened after the observation, it would land a full budget later, + // so this control also rejects a deferred window. + // + // `argv[0]` carries the harness entry so the identity proof sees `Live`, + // while `/bin/sleep` keeps this control cheap enough not to compete with + // the real-gateway cases for CPU. + let mut live_command = Command::new("/bin/sleep"); + live_command + .arg0(CHILD_ENTRY) + .arg("60") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let mut live_child = ChildGuard::new( + live_command + .spawn() + .expect("the deadline control needs a real live child"), + ); + let live_pid = live_child.pid(); + let live_identity = ChildIdentity::capture(live_pid) + .expect("the live deadline child must have a spawn identity"); + assert_eq!(live_identity.pid, live_pid); + tick.set(Instant::now()); + let mut spend_the_window = || tick.set(tick.get() + RECLAIM_BUDGET); + let mut signalled = 0usize; + let mut record_signal = |_pid: libc::pid_t| signalled += 1; + live_identity.reclaim_if_exact_with_clock( + &clock, + &mut spend_the_window, + &mut record_signal, + &mut |_state| {}, + ); + assert_eq!( + signalled, 0, + "an observation that spent the window must not record a signal attempt" + ); + assert_eq!( + live_child + .try_wait() + .expect("the live exact child must still be pollable"), + None, + "a window spent by the identity observation must never reach SIGKILL" + ); + assert!( + Path::new(&format!("/proc/{live_pid}")).exists(), + "the exact child must still be alive and owned after the refused fallback (pid {live_pid})" + ); + live_child + .terminate() + .expect("the owner must reap its still-live child after the refused fallback"); + assert!( + !Path::new(&format!("/proc/{live_pid}")).exists(), + "owner reclamation must remove the live child (pid {live_pid})" + ); +} + +/// Deterministic proof that the outer fallback never waits once its single +/// window is spent: the first awaitable observation of a real zombie advances +/// the test-only monotonic clock to exactly the deadline, and the zombie must +/// stay unreaped under `/proc` until its exact owner collects it. A window +/// opened after the observation would remain unexpired and the `WNOHANG` wait +/// would reap it. +#[cfg(unix)] +#[test] +fn gateway_fallback_refuses_waitpid_after_wait_only_deadline() { + use std::cell::Cell; + + let fixture = GatewayFixture::new("fallback-wait-only-deadline"); + let tick = Cell::new(Instant::now()); + let clock = || tick.get(); + + // ---- A matched wait-only child at the expired boundary. ---- + // + // The exact child has really exited and is a zombie of this test. The + // first awaitable observation consumes the window, so the fallback must + // return without reaping it: the zombie is still under `/proc`, and its + // owner performs the only reap. A deferred window would stay unexpired + // here, and the WNOHANG wait would reap the zombie immediately. + let (mut zombie_child, zombie_identity) = spawn_empty_cmdline_child(&fixture); + let zombie_pid = zombie_child.pid(); + drop( + zombie_child + .take_stdin() + .expect("the helper owns its stdin pipe"), + ); + let zombie_deadline = Instant::now() + RECLAIM_BUDGET; + loop { + let zombie = read_proc_stat(zombie_pid).is_some_and(|stat| { + stat.state == 'Z' + && stat.ppid == std::process::id() + && stat.start_time == zombie_identity.start_time + }); + if zombie { + break; + } + assert!( + Instant::now() < zombie_deadline, + "the released helper must become a zombie of this test" + ); + std::thread::sleep(Duration::from_millis(2)); + } + tick.set(Instant::now()); + let mut awaited_states = Vec::new(); + let mut first_observation_spends = |state: char| { + awaited_states.push(state); + tick.set(tick.get() + RECLAIM_BUDGET); + }; + zombie_identity.reclaim_if_exact_with_clock( + &clock, + &mut || {}, + &mut |_| {}, + &mut first_observation_spends, + ); + assert_eq!( + awaited_states, + vec!['Z'], + "the fallback must observe the exact zombie once before the window expires" + ); + let stat = read_proc_stat(zombie_pid) + .expect("the zombie must stay unreaped when the fallback returns at the deadline"); + assert_eq!( + stat.state, 'Z', + "the exact child must still be terminal-but-unreaped after the refused wait" + ); + assert!( + Path::new(&format!("/proc/{zombie_pid}")).exists(), + "the expired fallback must not reap the zombie it had not yet waited for (pid {zombie_pid})" + ); + let status = zombie_child + .try_wait() + .expect("the retained owner must still be able to reap its zombie") + .expect("the zombie must still be held by its owner"); + assert!( + status.success(), + "the helper exits cleanly on stdin EOF: {status}" + ); + assert!( + !Path::new(&format!("/proc/{zombie_pid}")).exists(), + "owner reclamation must remove the wait-only child (pid {zombie_pid})" + ); +} + +/// `/health/detailed` publishes `{"source": {"kind", "hash", +/// "deprecated_override"}}` from the installed runner's native metadata. Both +/// real processes must report the bundled kind they actually compiled. +fn assert_bundled_source(health: &Value, which: &str) { + let source = health.get("source").unwrap_or_else(|| { + panic!("the {which} Gateway health must publish source facts: {health}") + }); + assert_eq!( + source["kind"], + json!("bundled"), + "the {which} Gateway must run the embedded bundled RSS resource: {health}" + ); + assert!( + source["hash"].as_str().is_some_and(|hash| !hash.is_empty()), + "the {which} Gateway must report the installed runner snapshot digest: {health}" + ); + assert_eq!( + source["deprecated_override"], + json!(false), + "the bundled selection must not be a deprecated override: {health}" + ); +} + +fn assert_persisted_workspace(session: &Value, fixture: &GatewayFixture) { + let workspace = &session["session"]["workspace"]; + assert_eq!( + workspace["selector"], + json!("name:project"), + "the trusted workspace binding must survive the restart: {session}" + ); + let canonical = workspace["canonical_path"] + .as_str() + .expect("persisted canonical workspace path"); + assert_eq!( + Path::new(canonical), + fixture.workspace.as_path(), + "the reopened binding must resolve to the same trusted workspace" + ); +} + +#[cfg(target_os = "linux")] +fn latest_peer_pid(fixture: &GatewayFixture) -> u64 { + peer_events(fixture) + .iter() + .rev() + .find(|event| event["event"] == "process/spawn") + .and_then(|event| event["data"]["pid"].as_u64()) + .expect("observed real ACP peer PID") +} + +#[cfg(target_os = "linux")] +fn assert_latest_peer_reaped(fixture: &GatewayFixture) { + let pid = latest_peer_pid(fixture); + assert!( + !Path::new(&format!("/proc/{pid}")).exists(), + "ACP peer still exists after the result" + ); +} + +#[cfg(target_os = "linux")] +async fn exercise_acp_controls( + gateway: &mut GatewayProcess, + fixture: &GatewayFixture, + session: &str, + fresh_session: &str, + controls: &[FixtureRun; 5], + invalid: &FixtureRun, +) { + gateway.install_run_provider(&controls[0].key).await; + let denied = admit_run(gateway, session, "Deny this call at the human challenge").await; + decide_delegation(gateway, fixture, &denied, &controls[0], 3, "denied", true).await; + let terminal = gateway.observe_terminal(&denied, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.completed"); + assert_eq!(terminal.output, "runner saw denied: "); + assert_eq!(peer_spawns(fixture), 3); + + gateway.install_run_provider(&invalid.key).await; + let wrong = admit_run(gateway, session, "Send an additional untrusted argument").await; + let terminal = gateway.observe_terminal(&wrong, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.failed"); + assert!( + terminal.error.contains("acp_arguments_invalid"), + "wrong rejection: {}", + terminal.error + ); + assert_eq!(peer_spawns(fixture), 3); + + fs::write(fixture.root.join("caps"), "load").expect("select fixture load-only capability"); + gateway.install_run_provider(&controls[1].key).await; + let loaded = admit_run(gateway, session, "Continue with load-only capability").await; + decide_delegation(gateway, fixture, &loaded, &controls[1], 3, "approved", true).await; + let terminal = gateway.observe_terminal(&loaded, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.completed"); + assert_eq!( + terminal.output, + "runner saw completed: ctx=3;reply=external-reply" + ); + let loaded_requests = transcript_requests(fixture, "second", &controls[1].key); + let result = acp_result( + &loaded_requests[1]["request"], + controls[1].acp_call.as_ref().unwrap()["id"] + .as_str() + .unwrap(), + ); + assert!(!result.to_string().contains("history-replay-excluded")); + assert_eq!( + peer_events(fixture) + .iter() + .filter(|event| event["event"] == "session/load") + .count(), + 1 + ); + assert_latest_peer_reaped(fixture); + + gateway.install_run_provider(&controls[2].key).await; + let stopped = admit_run(gateway, session, "Stop a pending external prompt").await; + decide_delegation( + gateway, + fixture, + &stopped, + &controls[2], + 4, + "approved", + true, + ) + .await; + let deadline = Instant::now() + Duration::from_secs(15); + loop { + if peer_events(fixture).iter().any(|event| { + event["event"] == "session/prompt" + && event["data"]["prompt"][0]["text"] == "hold this prompt" + }) { + break; + } + assert!( + Instant::now() < deadline, + "peer never reached the held prompt" + ); + tokio::time::sleep(Duration::from_millis(30)).await; + } + let pid = latest_peer_pid(fixture); + assert!( + Path::new(&format!("/proc/{pid}")).exists(), + "stopped peer must actually be alive" + ); + let (status, _) = gateway + .request("POST", &format!("/v1/runs/{stopped}/stop"), None) + .await + .expect("stop live parent run"); + assert_eq!(status, 200); + assert_eq!( + gateway.observe_terminal(&stopped, HTTP_BUDGET).await.event, + "run.cancelled" + ); + assert_latest_peer_reaped(fixture); + assert_eq!(peer_spawns(fixture), 5); + + gateway.install_run_provider(&controls[3].key).await; + let fenced = admit_run(gateway, session, "Refuse reuse of the interrupted pin").await; + decide_delegation(gateway, fixture, &fenced, &controls[3], 5, "approved", true).await; + let terminal = gateway.observe_terminal(&fenced, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.completed"); + let requests = transcript_requests(fixture, "second", &controls[3].key); + let block = acp_result( + &requests[1]["request"], + controls[3].acp_call.as_ref().unwrap()["id"] + .as_str() + .unwrap(), + ); + assert_eq!(block["error"]["code"], "acp_session_indeterminate"); + assert_eq!(peer_spawns(fixture), 5); + + create_session(gateway, fresh_session).await; + bind_workspace(gateway, fresh_session).await; + gateway.install_run_provider(&controls[4].key).await; + let fresh = admit_run(gateway, fresh_session, "Use a clean main session").await; + decide_delegation(gateway, fixture, &fresh, &controls[4], 5, "approved", false).await; + let terminal = gateway.observe_terminal(&fresh, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.completed"); + assert_eq!( + terminal.output, + "runner saw completed: ctx=0;reply=external-reply" + ); + assert_eq!(peer_spawns(fixture), 6); + assert_latest_peer_reaped(fixture); + println!( + "ACP controls: denied_zero_spawn=true extra_argument_rejected=true load_replay_excluded=true stopped_peer_reaped=true interrupted_pin_fenced=true fresh_session_completed=true" + ); +} + +#[cfg(target_os = "linux")] +async fn exercise_acp_budgets( + gateway: &mut GatewayProcess, + fixture: &GatewayFixture, + session: &str, + runs: &[FixtureRun; 3], +) { + for (index, turn) in runs.iter().enumerate() { + let prior_spawns = 6 + index.saturating_sub(1); + gateway.install_run_provider(&turn.key).await; + let run_id = admit_run(gateway, session, "Exercise the admitted result budget").await; + if index == 0 { + let terminal = gateway.observe_terminal(&run_id, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.failed"); + assert!(terminal.error.contains("acp_delegation_budget")); + assert_eq!(peer_spawns(fixture), prior_spawns); + continue; + } + decide_delegation( + gateway, + fixture, + &run_id, + turn, + prior_spawns, + "approved", + true, + ) + .await; + let terminal = gateway.observe_terminal(&run_id, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.completed"); + let requests = transcript_requests(fixture, "second", &turn.key); + let block = acp_result( + &requests[1]["request"], + turn.acp_call.as_ref().unwrap()["id"].as_str().unwrap(), + ); + assert!(block.to_string().len() <= turn.output_budget.unwrap() as usize); + assert_eq!(block["result"]["text"], if index == 1 { "" } else { "ct" }); + assert_eq!(block["result"]["truncated"], true); + assert_eq!(peer_spawns(fixture), prior_spawns + 1); + assert_latest_peer_reaped(fixture); + } + println!( + "ACP result budgets: below_minimum_zero_spawn=true minimum_empty_prefix=true above_minimum_bounded_prefix=true" + ); +} diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs new file mode 100644 index 00000000..f98fe855 --- /dev/null +++ b/tests/acp_delegation_policy_tests.rs @@ -0,0 +1,4061 @@ +//! ACP delegation policy contract: launch table, approval binding, durable +//! session pinning, cancellation and call settlement. +//! +//! Every test drives the real [`AcpDelegationPolicy`] against the real gateway +//! durable store, a real admitted RSS run, the production manual approval +//! endpoint and the independent `tests/fixtures/acp_policy` stdio harness. No +//! approval row is resolved through storage directly: the fixture waits for the +//! pending row, then calls the same `resolve_pending_approval` entry point the +//! HTTP and Telegram decision endpoints use, with an authenticated resolver. +//! Spawn counts come from the harness' own append-only spawn log. + +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use rustscript_agent::acp::AcpStopReason; +use rustscript_agent::config::AgentGatewayConfig; +use rustscript_agent::config_file::ConfigFile; +use rustscript_agent::gateway::AgentGatewayState; +use rustscript_agent::gateway::build_agent_gateway_app; +use rustscript_agent::gateway::store::GatewayPersistence; +use rustscript_agent::service::acp_session_pins::{ + AcpApprovalWitness, AcpDelegationPolicy, AcpDelegationRequest, AcpDelegationResult, + AcpDelegationScope, AcpDelegationStatus, +}; +use rustscript_agent::service::{AgentService, TelegramApprovalPicker}; +use rustscript_agent::{AdmitRunRequest, AdmittedRun, CancellationReason}; +use serde_json::{Value, json}; + +#[path = "fixtures/acp_policy/build.rs"] +mod fixture_build; + +static NEXT_TEST: AtomicU64 = AtomicU64::new(0); + +struct Env { + root: PathBuf, + workspace: PathBuf, + home: PathBuf, + binary: PathBuf, +} + +impl Env { + fn new(label: &str) -> Self { + let sequence = NEXT_TEST.fetch_add(1, Ordering::Relaxed); + let base = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .or_else(|| std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMPDIR")) + .or_else(|| std::env::var_os("TMPDIR")) + .map(PathBuf::from) + .expect("policy tests require an assigned temporary directory"); + let root = base.join(format!( + "acp-policy-{label}-{}-{sequence}", + std::process::id() + )); + fs::create_dir_all(&root).expect("create policy test root"); + let workspace = root.join("workspace"); + let home = root.join("home"); + fs::create_dir_all(&workspace).expect("create policy workspace"); + fs::create_dir_all(&home).expect("create policy home"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + for path in [&root, &workspace, &home] { + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + .expect("restrict policy fixture directory"); + } + } + let workspace = fs::canonicalize(&workspace).expect("canonical workspace"); + let binary = binary_path(); + Self { + root, + workspace, + home, + binary, + } + } + + fn spawn_log(&self) -> PathBuf { + self.root.join("spawn.log") + } + + fn events(&self) -> PathBuf { + self.root.join("events.jsonl") + } + + fn store(&self) -> PathBuf { + self.root.join("sessions.txt") + } + + fn caps(&self) -> PathBuf { + self.root.join("caps.txt") + } + + fn db(&self) -> PathBuf { + self.root.join("gateway.sqlite") + } + + fn spawn_count(&self) -> usize { + fs::read_to_string(self.spawn_log()) + .map(|contents| contents.lines().filter(|line| *line == "spawn").count()) + .unwrap_or(0) + } + + fn set_caps(&self, caps: &str) { + fs::write(self.caps(), caps).expect("write caps file"); + } + + fn recorded(&self, event: &str) -> usize { + fs::read_to_string(self.events()) + .map(|contents| { + contents + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|value| value.get("event").and_then(Value::as_str) == Some(event)) + .count() + }) + .unwrap_or(0) + } + + fn config(&self, harness_id: &str, extra_args: &[&str]) -> ConfigFile { + self.config_multi(&[(harness_id, extra_args)]) + } + + fn config_limited( + &self, + output_bytes: usize, + harness_id: &str, + extra_args: &[&str], + ) -> ConfigFile { + let mut yaml = String::from("version: 1\n"); + yaml.push_str(&format!( + "agent:\n max_tool_output_bytes: {output_bytes}\n" + )); + yaml.push_str("workspaces:\n allowed_roots:\n"); + yaml.push_str(&format!(" - '{}'\n", self.workspace.display())); + yaml.push_str("acp_harnesses:\n"); + yaml.push_str(&format!(" - id: {harness_id}\n")); + yaml.push_str(&format!(" command: '{}'\n", self.binary.display())); + yaml.push_str(" args:\n"); + let base_args = [ + "--spawn-log".to_string(), + self.spawn_log().display().to_string(), + "--events".to_string(), + self.events().display().to_string(), + "--store".to_string(), + self.store().display().to_string(), + "--caps".to_string(), + self.caps().display().to_string(), + ]; + for arg in base_args + .iter() + .cloned() + .chain(extra_args.iter().map(|arg| arg.to_string())) + { + yaml.push_str(&format!(" - '{arg}'\n")); + } + ConfigFile::from_str(&yaml).expect("limited policy config parses") + } + + fn config_multi(&self, entries: &[(&str, &[&str])]) -> ConfigFile { + let base_args = [ + "--spawn-log".to_string(), + self.spawn_log().display().to_string(), + "--events".to_string(), + self.events().display().to_string(), + "--store".to_string(), + self.store().display().to_string(), + "--caps".to_string(), + self.caps().display().to_string(), + ]; + let mut yaml = String::from("version: 1\n"); + yaml.push_str("workspaces:\n allowed_roots:\n"); + yaml.push_str(&format!(" - '{}'\n", self.workspace.display())); + yaml.push_str("acp_harnesses:\n"); + for (harness_id, extra_args) in entries { + yaml.push_str(&format!(" - id: {harness_id}\n")); + yaml.push_str(&format!(" command: '{}'\n", self.binary.display())); + yaml.push_str(" args:\n"); + for arg in base_args + .iter() + .cloned() + .chain(extra_args.iter().map(|arg| arg.to_string())) + { + yaml.push_str(&format!(" - '{arg}'\n")); + } + } + ConfigFile::from_str(&yaml).expect("policy config parses") + } +} + +fn assigned_tmp_binary() -> PathBuf { + let base = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .or_else(|| std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMPDIR")) + .or_else(|| std::env::var_os("TMPDIR")) + .map(PathBuf::from) + .expect("policy tests require an assigned temporary directory"); + base.join(format!("acp-policy-agent-{}", std::process::id())) +} + +fn binary_path() -> PathBuf { + static BINARY: OnceLock = OnceLock::new(); + BINARY + .get_or_init(|| { + let path = assigned_tmp_binary(); + fixture_build::compile_policy_agent(&path); + path + }) + .clone() +} + +fn write_policy_home(env: &Env, reviewer: &str) { + fs::write( + env.home.join("config.yaml"), + format!( + "version: 1\nmodel:\n provider: local-test\n model: synthetic\nproviders:\n local-test:\n protocol: codex-responses\n base_url: https://127.0.0.1:1\nworkspaces:\n allowed_roots:\n - '{}'\n default: '{}'\napprovals:\n reviewer: {reviewer}\n", + env.workspace.display(), + env.workspace.display() + ), + ) + .expect("write policy home config"); +} + +/// One real gateway, one admitted-run factory and the installed policy. +struct Runtime<'a> { + #[allow(dead_code)] + env: &'a Env, + state: AgentGatewayState, + service: Arc, + policy: AcpDelegationPolicy, +} + +impl<'a> Runtime<'a> { + fn open(env: &'a Env) -> Self { + Self::open_with(env, env.config("fixture", &[]), "user") + } + + fn open_with(env: &'a Env, config: ConfigFile, reviewer: &str) -> Self { + write_policy_home(env, reviewer); + let mut gateway_config = AgentGatewayConfig::default(); + gateway_config.approvals.reviewer = Some(reviewer.to_string()); + let state = AgentGatewayState::with_sqlite_path(gateway_config, env.db()) + .expect("open isolated gateway state") + .with_workspace_home(&env.home); + let service = state.service(); + let persistence = state.persistence().expect("persistence"); + let policy = AcpDelegationPolicy::install(&config, persistence, service.clone()) + .expect("install policy") + .expect("configured policy"); + Self { + env, + state, + service, + policy, + } + } + + async fn open_run(&self, session: Option<&str>) -> AdmittedRun { + self.service + .admit_external_with_workspace_selector( + AdmitRunRequest { + input: json!({"message": "delegation policy fixture"}), + session_id: session.map(str::to_string), + ..Default::default() + }, + None, + ) + .await + .expect("admit live fixture run") + } + + fn persistence(&self) -> Arc { + self.state.persistence().expect("persistence") + } + + /// A state that also exposes the real bearer-authenticated HTTP API. + fn open_http(env: &'a Env, reviewer: &str, token: &str) -> (Self, String) { + write_policy_home(env, reviewer); + let mut gateway_config = AgentGatewayConfig::default(); + gateway_config.approvals.reviewer = Some(reviewer.to_string()); + gateway_config.bearer_token = Some(token.to_string()); + let state = AgentGatewayState::with_sqlite_path(gateway_config, env.db()) + .expect("open isolated gateway state") + .with_workspace_home(&env.home); + let service = state.service(); + let persistence = state.persistence().expect("persistence"); + let policy = + AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence, service.clone()) + .expect("install policy") + .expect("configured policy"); + let app = build_agent_gateway_app(state.clone()); + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("http listener"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let address = listener.local_addr().expect("http address"); + let runtime = tokio::runtime::Handle::current(); + std::thread::spawn(move || { + runtime.block_on(async move { + let listener = tokio::net::TcpListener::from_std(listener).expect("tokio listener"); + axum::serve(listener, app).await.expect("serve policy api"); + }); + }); + ( + Self { + env, + state, + service, + policy, + }, + address.to_string(), + ) + } + + async fn finish(&self, run: &AdmittedRun) { + self.persistence() + .run_transition(&json!({ + "run_id": run.run_id, + "from_status": "running", + "to_status": "completed", + "error_code": "", + "error_message": "", + "recovery_reason": "", + "now_ms": now_ms(), + })) + .expect("settle fixture run"); + self.service.mark_terminal(&run.run_id); + } + + async fn challenge( + &self, + run: &AdmittedRun, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + ) -> rustscript_agent::service::acp_session_pins::AcpApprovalChallenge { + let challenge = self + .policy + .request_approval(scope, request) + .await + .expect("approval challenge"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + let rows = self + .service + .pending_approvals(&run.run_id, Some(&run.session_id)) + .expect("pending approvals"); + if rows + .iter() + .any(|row| row["approval_id"].as_str() == Some(challenge.approval_id.as_str())) + { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "the manual approval surface never published the pending row" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + challenge + } + + async fn approve( + &self, + run: &AdmittedRun, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + ) -> AcpApprovalWitness { + let challenge = self.challenge(run, scope, request).await; + self.service + .resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "http-bearer", + Some(&run.session_id), + ) + .expect("real manual approval entry"); + AcpApprovalWitness::new(challenge.approval_id) + } + + async fn delegate_approved( + &self, + run: &AdmittedRun, + call_id: &str, + task: &str, + ) -> AcpDelegationResult { + let scope = scope(run, call_id); + let request = request("fixture", task); + let witness = self.approve(run, &scope, &request).await; + self.policy.delegate(&scope, &request, &witness).await + } +} + +// Run only fixture-owned SQL against the gateway's actual SQLite database, +// through the same SQLite host used by storage.rss. +#[cfg(feature = "workspace-io-fault")] +fn fixture_sql(env: &Env, sql: &str) { + fixture_sql_at(&env.root, sql); +} + +#[cfg(feature = "workspace-io-fault")] +fn fixture_sql_at(root: &std::path::Path, sql: &str) { + use rustscript_agent::runtime::{AgentConfig, AgentRunner}; + let source = format!( + r#" +use sqlite; +pub fn run(input: int) -> bool {{ + let opts: SqliteOpenOptions = {{ path: Some("gateway.sqlite"), mode: Some("read_write") }}; + let db = sqlite::open(opts); + sqlite::execute(&db, {}, []); + sqlite::close(db); + true +}} +"#, + serde_json::to_string(sql).expect("quote fixture SQL") + ); + let runner = AgentRunner::from_source(&source, AgentConfig::default().with_sqlite_root(root)) + .expect("fixture SQL compiles"); + runner + .run_with_context(rustscript_vm::Value::Int(0)) + .expect("fixture SQL succeeds"); +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis() as i64) + .unwrap_or_default() +} + +fn scope(run: &AdmittedRun, call_id: &str) -> AcpDelegationScope { + AcpDelegationScope { + run_id: run.run_id.clone(), + session_id: run.session_id.clone(), + tool_call_id: call_id.to_string(), + } +} + +fn request(harness_id: &str, task: &str) -> AcpDelegationRequest { + AcpDelegationRequest { + harness_id: harness_id.to_string(), + task: task.to_string(), + } +} + +fn pin_document(persistence: &GatewayPersistence, session_id: &str) -> Value { + let rows = persistence.session_get(session_id).expect("session read"); + let row = rows["rows"][0].as_array().expect("session row"); + let metadata = row + .get(13) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + serde_json::from_str::(&metadata) + .ok() + .and_then(|value| value.get("acp_delegation").cloned()) + .unwrap_or(Value::Null) +} + +fn approval_row(persistence: &GatewayPersistence, approval_id: &str) -> Vec { + persistence + .approval_get(approval_id) + .expect("approval row read") + .get("rows") + .and_then(Value::as_array) + .and_then(|rows| rows.first()) + .and_then(Value::as_array) + .cloned() + .expect("approval row") +} + +async fn wait_for(mut condition: impl FnMut() -> bool, label: &str) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + while !condition() { + assert!( + tokio::time::Instant::now() < deadline, + "timed out waiting for {label}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +fn session_row(persistence: &GatewayPersistence, session_id: &str) -> Vec { + persistence + .session_get(session_id) + .expect("session read") + .get("rows") + .and_then(Value::as_array) + .and_then(|rows| rows.first()) + .and_then(Value::as_array) + .cloned() + .expect("session row") +} + +fn edit_fixture_pin( + persistence: &GatewayPersistence, + session_id: &str, + edit: impl FnOnce(&mut Value), +) { + let row = session_row(persistence, session_id); + let mut doc = pin_document(persistence, session_id); + let expected_version = doc["version"].as_i64().expect("document version"); + let pin = &mut doc["pins"]["fixture"]; + assert_eq!(pin["phase"], "bound"); + assert!(pin["active"].is_null()); + edit(pin); + doc["version"] = json!(expected_version + 1); + let cas = persistence + .session_acp_delegation_cas(&json!({ + "session_id": session_id, + "owner": row[6], + "created_at_ms": row[15], + "expected_version": expected_version, + "lease_path": "", + "lease_call": "", + "document_json": serde_json::to_string(&doc).expect("document"), + "now_ms": now_ms(), + })) + .expect("edit fixture pin through the durable store"); + assert_eq!(cas["applied"], true); +} + +/// Delete and recreate the same session id with the same owner but a new +/// durable creation identity. +fn replace_session(persistence: &GatewayPersistence, session_id: &str) { + let row = session_row(persistence, session_id); + let text = |index: usize| row[index].as_str().unwrap_or_default().to_string(); + let created_at_ms = row[15].as_i64().unwrap_or_default(); + persistence + .session_delete(session_id) + .expect("delete original session"); + persistence + .session_create(&json!({ + "id": session_id, + "profile": text(1), + "platform": text(2), + "account_id": text(3), + "chat_id": text(4), + "thread_id": text(5), + "user_id": text(6), + "generation": 1, + "system_prompt": "", + "model": "", + "provider": "", + "toolset_hash": "", + "metadata_json": "{}", + "title": "", + "end_reason": "", + "now_ms": created_at_ms + 1, + })) + .expect("recreate session with a new identity"); +} + +/// Change the durable owner of an already admitted session without changing its +/// id, so the in-memory admission state still knows the session. +fn reown_session(persistence: &GatewayPersistence, session_id: &str, owner: &str) { + let row = session_row(persistence, session_id); + let text = |index: usize| row[index].as_str().unwrap_or_default().to_string(); + let created_at_ms = row[15].as_i64().unwrap_or_default(); + persistence + .session_delete(session_id) + .expect("delete session for reown"); + persistence + .session_create(&json!({ + "id": session_id, + "profile": text(1), + "platform": text(2), + "account_id": text(3), + "chat_id": text(4), + "thread_id": text(5), + "user_id": owner, + "generation": 1, + "system_prompt": "", + "model": "", + "provider": "", + "toolset_hash": "", + "metadata_json": "{}", + "title": "", + "end_reason": "", + "now_ms": created_at_ms + 1, + })) + .expect("reown session"); +} + +async fn raw_http( + address: &str, + method: &str, + path: &str, + token: Option<&str>, + body: &str, +) -> (u16, String) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut stream = tokio::net::TcpStream::connect(address) + .await + .expect("connect policy api"); + let authorization = token + .map(|token| format!("Authorization: Bearer {token}\r\n")) + .unwrap_or_default(); + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: {address}\r\n{authorization}\ + Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + stream + .write_all(request.as_bytes()) + .await + .expect("write policy api request"); + let mut response = Vec::new(); + stream + .read_to_end(&mut response) + .await + .expect("read policy api response"); + let response = String::from_utf8_lossy(&response).to_string(); + let status = response + .split_whitespace() + .nth(1) + .and_then(|code| code.parse().ok()) + .unwrap_or_default(); + (status, response) +} + +#[tokio::test] +async fn default_config_installs_no_policy_and_unknown_ids_never_spawn() { + let env = Env::new("default-off"); + let plain = ConfigFile::from_str("version: 1\n").expect("default config"); + let state = AgentGatewayState::with_sqlite_path(AgentGatewayConfig::default(), env.db()) + .expect("open isolated gateway state"); + let service = state.service(); + let persistence = state.persistence().expect("persistence"); + assert!( + AcpDelegationPolicy::install(&plain, persistence.clone(), service.clone()) + .expect("install default") + .is_none(), + "an empty table must leave the capability disabled" + ); + assert!( + service.acp_delegation().is_none(), + "the default capability is not installed" + ); + drop(state); + + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let unknown = runtime + .policy + .delegate( + &scope(&run, "call-1"), + &request("missing", "task"), + &AcpApprovalWitness::new("approval"), + ) + .await; + assert_eq!(unknown.status, AcpDelegationStatus::Denied); + assert_eq!(unknown.code, Some("acp_harness_unknown")); + assert_eq!(env.spawn_count(), 0, "no refusal may spawn a harness"); +} + +#[tokio::test] +async fn unapproved_denied_and_unbound_calls_never_spawn() { + let env = Env::new("refusals"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + + // Pending (never resolved) approval, created through the real surface. + let pending_scope = scope(&run, "call-pending"); + let challenge = runtime + .challenge(&run, &pending_scope, &request("fixture", "pending task")) + .await; + let pending = runtime + .policy + .delegate( + &pending_scope, + &request("fixture", "pending task"), + &AcpApprovalWitness::new(challenge.approval_id.clone()), + ) + .await; + assert_eq!(pending.status, AcpDelegationStatus::Denied); + assert_eq!(pending.code, Some("acp_approval_mismatch")); + runtime + .service + .resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "denied", + "http-bearer", + Some(&run.session_id), + ) + .expect("close the pending row before the next decision"); + + // Explicitly denied through the real decision endpoint. + let denied_scope = scope(&run, "call-denied"); + let challenge = runtime + .challenge(&run, &denied_scope, &request("fixture", "denied task")) + .await; + runtime + .service + .resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "denied", + "http-bearer", + Some(&run.session_id), + ) + .expect("deny through the manual surface"); + let denied = runtime + .policy + .delegate( + &denied_scope, + &request("fixture", "denied task"), + &AcpApprovalWitness::new(challenge.approval_id), + ) + .await; + assert_eq!(denied.status, AcpDelegationStatus::Denied); + assert_eq!(denied.code, Some("acp_approval_mismatch")); + + // An unknown run has no authoritative facts and can neither ask nor launch. + let persistence = runtime.persistence(); + persistence + .session_create(&json!({ + "id": "session-unbound", + "profile": "default", + "platform": "policy-fixture", + "account_id": "session-unbound", + "chat_id": "7", + "thread_id": "", + "user_id": "owner-1", + "generation": 1, + "system_prompt": "", + "model": "policy-model", + "provider": "policy-provider", + "toolset_hash": "policy-tools", + "metadata_json": "{}", + "title": "", + "end_reason": "", + "now_ms": 1_700_000_000_000_i64, + })) + .expect("seed unbound session"); + let unbound_scope = AcpDelegationScope { + run_id: "run-unbound".to_string(), + session_id: "session-unbound".to_string(), + tool_call_id: "call-unbound".to_string(), + }; + let refusal = runtime + .policy + .delegate( + &unbound_scope, + &request("fixture", "x"), + &AcpApprovalWitness::new("approval"), + ) + .await; + assert_eq!(refusal.status, AcpDelegationStatus::Denied); + assert_eq!(refusal.code, Some("acp_run_inactive")); + assert_eq!(env.spawn_count(), 0, "refusals must not spawn"); +} + +#[tokio::test] +async fn preview_shows_the_complete_task_or_refuses_before_approval() { + let env = Env::new("preview"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let text = "task-body-".to_string() + &"x".repeat(200); + let challenge = runtime + .challenge( + &run, + &scope(&run, "call-preview"), + &request("fixture", &text), + ) + .await; + assert!( + challenge.preview.contains(&text), + "the preview must repeat every submitted byte: {challenge:?}" + ); + assert!(challenge.preview.contains("create a new external session")); + assert!(challenge.preview.contains("does not sandbox")); + + // A task that cannot fit the bounded approval preview is refused before a + // row exists, never approved over a truncated body. + let oversized = "y".repeat(2500); + let refusal = runtime + .policy + .request_approval( + &scope(&run, "call-oversized"), + &request("fixture", &oversized), + ) + .await + .expect_err("truncated previews must be refused"); + assert_eq!(refusal.code(), "acp_approval_preview_unavailable"); + let rows = runtime + .service + .pending_approvals(&run.run_id, Some(&run.session_id)) + .expect("pending approvals"); + assert_eq!(rows.len(), 1, "only the complete preview produced a row"); + assert_eq!(env.spawn_count(), 0); +} + +#[tokio::test] +async fn first_call_creates_and_later_calls_restore_the_same_session() { + let env = Env::new("create-restore"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let first_witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "first")) + .await; + let first = runtime + .policy + .delegate(&first_scope, &request("fixture", "first"), &first_witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed, "{first:?}"); + assert_eq!(first.text, "ctx=0;reply=policy-reply"); + assert_eq!( + first.stop_reason, + Some(rustscript_agent::acp::AcpStopReason::EndTurn) + ); + assert!(!first.replayed); + + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &first_run.session_id); + let pin = &doc["pins"]["fixture"]; + let bound_id = pin["external_session_id"].as_str().expect("bound id"); + assert!(!bound_id.is_empty()); + assert_eq!(pin["phase"], "bound"); + assert!(pin["active"].is_null()); + runtime.finish(&first_run).await; + + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let second_witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "second")) + .await; + let second = runtime + .policy + .delegate( + &second_scope, + &request("fixture", "second"), + &second_witness, + ) + .await; + assert_eq!(second.status, AcpDelegationStatus::Completed, "{second:?}"); + assert_eq!( + second.text, "ctx=1;reply=policy-reply", + "the restored session must see the earlier task" + ); + assert_eq!(env.spawn_count(), 2); + assert_eq!(env.recorded("session/new"), 1); + assert_eq!(env.recorded("session/resume"), 1); + let doc = pin_document(&persistence, &first_run.session_id); + assert_eq!( + doc["pins"]["fixture"]["external_session_id"].as_str(), + Some(bound_id), + "the same external ID must be reused" + ); +} + +#[tokio::test] +async fn settled_call_replays_only_the_identical_request_without_spawning() { + let env = Env::new("replay"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "once")) + .await; + let first = runtime + .policy + .delegate(&call_scope, &request("fixture", "once"), &witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed); + assert_eq!( + runtime + .policy + .call_settlement(&run.session_id, "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Settled + ); + assert_eq!( + runtime + .policy + .call_settlement(&run.session_id, "never-used") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::NotStarted + ); + let spawns = env.spawn_count(); + let replay = runtime + .policy + .delegate(&call_scope, &request("fixture", "once"), &witness) + .await; + assert!(replay.replayed); + assert_eq!(replay.status, first.status); + assert_eq!(replay.text, first.text); + + // A different task or approval identity is not a replay and is never + // re-executed under the old call identity. + let mismatch = runtime + .policy + .delegate(&call_scope, &request("fixture", "different"), &witness) + .await; + assert_eq!(mismatch.status, AcpDelegationStatus::Denied); + assert_eq!(mismatch.code, Some("acp_call_mismatch")); + assert_eq!( + env.spawn_count(), + spawns, + "a settled call must never re-spawn" + ); +} + +#[tokio::test] +async fn gateway_restart_restores_the_durable_binding() { + let env = Env::new("restart"); + let first_session; + { + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + first_session = run.session_id.clone(); + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "before")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "before"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed); + } + let runtime = Runtime::open(&env); + // A fresh admitted run in the same RSS session must restore the persisted + // external ID; process identity and any in-memory sequence are irrelevant. + let run = runtime.open_run(Some(&first_session)).await; + let call_scope = scope(&run, "call-2"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "after")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "after"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(result.text, "ctx=1;reply=policy-reply"); + assert_eq!(env.recorded("session/new"), 1); + assert_eq!(env.recorded("session/resume"), 1); +} + +#[tokio::test] +async fn restore_failure_never_creates_a_new_session() { + let env = Env::new("restore-failure"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + // Forget the peer session: the restore request is now rejected. + fs::write(env.store(), "").expect("clear peer store"); + runtime.finish(&first_run).await; + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "b")) + .await; + let result = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Failed); + assert_eq!(result.code, Some("acp_session_restore_failed")); + assert_eq!(env.recorded("session/new"), 1, "no silent new session"); + assert_eq!(env.recorded("session/load"), 0, "no silent load fallback"); +} + +#[tokio::test] +async fn missing_restore_capability_reports_unsupported_without_new_session() { + let env = Env::new("no-restore"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + env.set_caps("none"); + runtime.finish(&first_run).await; + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "b")) + .await; + let result = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Failed); + assert_eq!(result.code, Some("acp_session_restore_unsupported")); + assert_eq!(env.recorded("session/new"), 1); +} + +#[tokio::test] +async fn load_only_restore_uses_load_and_never_mixes_replayed_text() { + let env = Env::new("load-only"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + env.set_caps("load"); + runtime.finish(&first_run).await; + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "b")) + .await; + let result = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(result.text, "ctx=1;reply=policy-reply"); + assert!(!result.text.contains("REPLAY"), "{:?}", result.text); + assert_eq!(env.recorded("session/load"), 1); + assert_eq!(env.recorded("session/resume"), 0); +} + +#[tokio::test] +async fn workspace_change_refuses_the_old_binding() { + let env = Env::new("workspace-change"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + runtime.finish(&first_run).await; + + // Simulate a workspace relocation recorded durably after the binding: the + // old pin still names the previous directory. This writes the private + // document through the product CAS, not through an approval. + let persistence = runtime.persistence(); + edit_fixture_pin(&persistence, &first_run.session_id, |pin| { + pin["workspace"] = json!(env.workspace.join("relocated")); + }); + + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "b")) + .await; + let result = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Denied); + assert_eq!(result.code, Some("acp_binding_mismatch")); + assert_eq!(env.spawn_count(), 1, "the mismatched call must not spawn"); +} + +#[tokio::test] +async fn durable_pin_rejects_a_different_owner() { + let env = Env::new("pin-owner"); + let runtime = Runtime::open(&env); + let first = runtime.open_run(None).await; + let result = runtime.delegate_approved(&first, "call-1", "first").await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + runtime.finish(&first).await; + assert_eq!(env.spawn_count(), 1); + assert_eq!(env.recorded("session/prompt"), 1); + + let persistence = runtime.persistence(); + let original = pin_document(&persistence, &first.session_id)["pins"]["fixture"].clone(); + assert!(original["external_session_id"].is_string()); + assert!(original["owner"].is_string()); + assert!(original["owner"] == session_row(&persistence, &first.session_id)[6]); + + // Change only the old pin's owner. The live session row and the next + // run's approval remain valid for the current principal. + let mut mismatched = original.clone(); + mismatched["owner"] = json!("synthetic-previous-owner"); + assert!(mismatched["owner"] != original["owner"]); + edit_fixture_pin(&persistence, &first.session_id, |pin| { + pin["owner"] = mismatched["owner"].clone(); + }); + let next = runtime.open_run(Some(&first.session_id)).await; + let scope = scope(&next, "call-2"); + let request = request("fixture", "follow-up"); + let witness = runtime.approve(&next, &scope, &request).await; + let before = pin_document(&persistence, &next.session_id); + assert!(before["pins"]["fixture"] == mismatched); + assert!(session_row(&persistence, &next.session_id)[6] == original["owner"]); + + let denied = runtime.policy.delegate(&scope, &request, &witness).await; + assert_eq!(denied.status, AcpDelegationStatus::Denied, "{denied:?}"); + assert_eq!(denied.code, Some("acp_binding_mismatch")); + assert_eq!(env.spawn_count(), 1); + assert_eq!(env.recorded("session/prompt"), 1); + assert!(pin_document(&persistence, &next.session_id) == before); + + // Repair just the pin owner. The same call and approval can now resume. + edit_fixture_pin(&persistence, &next.session_id, |pin| { + pin["owner"] = original["owner"].clone(); + }); + let restored = runtime.policy.delegate(&scope, &request, &witness).await; + assert_eq!( + restored.status, + AcpDelegationStatus::Completed, + "{restored:?}" + ); + assert_eq!(restored.text, "ctx=1;reply=policy-reply"); + assert_eq!(env.recorded("session/new"), 1); + assert_eq!(env.recorded("session/resume"), 1); +} + +#[tokio::test] +async fn durable_pins_isolate_two_live_main_sessions_for_the_same_owner_and_harness() { + let env = Env::new("pin-main-sessions"); + let runtime = Runtime::open(&env); + let first = runtime.open_run(None).await; + let second = runtime.open_run(None).await; + let persistence = runtime.persistence(); + assert!(first.session_id != second.session_id); + let owner = session_row(&persistence, &first.session_id)[6].clone(); + assert!(owner.is_string()); + assert!(session_row(&persistence, &second.session_id)[6] == owner); + + let first_result = runtime + .delegate_approved(&first, "call-1", "first session") + .await; + let second_result = runtime + .delegate_approved(&second, "call-1", "second session") + .await; + for result in [first_result, second_result] { + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(result.text, "ctx=0;reply=policy-reply"); + assert!(!result.replayed); + } + assert_eq!(env.spawn_count(), 2); + assert_eq!(env.recorded("session/resume"), 0); + assert_eq!(env.recorded("session/load"), 0); + + let first_doc = pin_document(&persistence, &first.session_id); + let second_doc = pin_document(&persistence, &second.session_id); + let pin_id = |doc: &Value| { + let pin = &doc["pins"]["fixture"]; + assert_eq!(pin["phase"], "bound"); + assert!(pin["owner"] == owner); + let id = pin["external_session_id"] + .as_str() + .expect("bound external ID"); + assert!(!id.is_empty()); + id.to_owned() + }; + let first_id = pin_id(&first_doc); + let second_id = pin_id(&second_doc); + assert!( + first_id != second_id, + "each main session must have its own pin" + ); + + let trace = fs::read_to_string(env.events()).expect("read ACP fixture trace"); + let events: Vec = trace + .lines() + .map(|line| serde_json::from_str(line).expect("parse ACP fixture event")) + .collect(); + let created: Vec<_> = events + .iter() + .filter(|event| event["event"] == "session/new") + .collect(); + let prompts: Vec<_> = events + .iter() + .filter(|event| event["event"] == "session/prompt") + .collect(); + assert_eq!(created.len(), 2); + assert_eq!(prompts.len(), 2); + for ((created, prompt), (id, task)) in created.into_iter().zip(prompts).zip([ + (first_id.as_str(), "first session"), + (second_id.as_str(), "second session"), + ]) { + assert!(created["data"]["sessionId"].as_str() == Some(id)); + assert!( + prompt["data"]["sessionId"].as_str() == Some(id), + "prompt must use its main session's pin" + ); + assert_eq!(prompt["data"]["prompt"][0]["text"], task); + } +} + +#[tokio::test] +async fn durable_pin_rejects_changed_launch_arguments_after_restart() { + let env = Env::new("pin-launch"); + let (session_id, original_pin) = { + let runtime = Runtime::open(&env); + let first = runtime.open_run(None).await; + let result = runtime.delegate_approved(&first, "call-1", "first").await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + let doc = pin_document(&runtime.persistence(), &first.session_id); + let pin = &doc["pins"]["fixture"]; + assert_eq!(pin["phase"], "bound"); + assert!(pin["external_session_id"].is_string()); + runtime.finish(&first).await; + (first.session_id, pin.clone()) + }; + assert_eq!(env.spawn_count(), 1); + assert_eq!(env.recorded("session/prompt"), 1); + + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--reply", "changed-args"]), + "user", + ); + let next = runtime.open_run(Some(&session_id)).await; + let scope = scope(&next, "call-2"); + let request = request("fixture", "follow-up"); + let witness = runtime.approve(&next, &scope, &request).await; + let persistence = runtime.persistence(); + let before = pin_document(&persistence, &session_id); + assert!(before["pins"]["fixture"] == original_pin); + + let denied = runtime.policy.delegate(&scope, &request, &witness).await; + assert_eq!(denied.status, AcpDelegationStatus::Denied, "{denied:?}"); + assert_eq!(denied.code, Some("acp_binding_mismatch")); + assert_eq!(env.spawn_count(), 1); + assert_eq!(env.recorded("session/prompt"), 1); + assert!(pin_document(&persistence, &session_id) == before); + + // The changed definition still launches for a main session without a pin. + let fresh = runtime.open_run(None).await; + let allowed = runtime + .delegate_approved(&fresh, "call-1", "fresh session") + .await; + assert_eq!( + allowed.status, + AcpDelegationStatus::Completed, + "{allowed:?}" + ); + assert_eq!(allowed.text, "ctx=0;reply=changed-args"); + assert_eq!(env.spawn_count(), 2); + assert_eq!(env.recorded("session/new"), 2); + assert_eq!(env.recorded("session/prompt"), 2); + assert_eq!(env.recorded("session/resume"), 0); + assert_eq!(env.recorded("session/load"), 0); +} + +#[tokio::test] +async fn approval_is_bound_to_the_exact_task_and_pin_version() { + let env = Env::new("approval-binding"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "approved task")) + .await; + let stale = runtime + .policy + .delegate(&call_scope, &request("fixture", "different task"), &witness) + .await; + assert_eq!(stale.status, AcpDelegationStatus::Denied); + assert_eq!(stale.code, Some("acp_approval_stale")); + assert_eq!(env.spawn_count(), 0); +} + +#[tokio::test] +async fn automatic_reviewer_reaches_real_human_pending_then_executes() { + let env = Env::new("auto-human"); + let runtime = Runtime::open_with(&env, env.config("fixture", &[]), "auto"); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "auto task"); + let challenge = runtime.challenge(&run, &call_scope, &request).await; + + // The automatic reviewer produces the same durable human wait the manual + // surface lists and resolves; it is not a Guardian auto-approval. + let row = approval_row(&runtime.persistence(), &challenge.approval_id); + assert_eq!(row[7].as_str(), Some("pending")); + assert_eq!(row[8].as_str(), Some("human_pending")); + let pending = runtime + .service + .pending_approvals(&run.run_id, Some(&run.session_id)) + .expect("real pending approval surface"); + assert!( + pending + .iter() + .any(|item| item["approval_id"].as_str() == Some(&challenge.approval_id)), + "the automatic run's human wait must be visible: {pending:?}" + ); + // A Guardian-style automatic decision is not a legal resolver at all. + assert_eq!( + runtime.service.resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "guardian", + Some(&run.session_id), + ), + Err("resolver_invalid") + ); + assert_eq!(env.spawn_count(), 0, "no automatic decision may start it"); + + // The same real endpoint, with an authenticated human resolver, approves + // exactly this call. + runtime + .service + .resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "http-bearer", + Some(&run.session_id), + ) + .expect("manual approval through the real endpoint"); + assert_eq!( + approval_row(&runtime.persistence(), &challenge.approval_id)[13].as_str(), + Some("http-bearer"), + "the human decision is recorded with its resolver" + ); + let result = runtime + .policy + .delegate( + &call_scope, + &request, + &AcpApprovalWitness::new(challenge.approval_id), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(env.spawn_count(), 1, "the approved call really runs"); + assert_eq!(env.recorded("session/new"), 1); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn automatic_guardian_resolution_never_starts_a_delegation() { + let env = Env::new("auto-guardian"); + let runtime = Runtime::open_with(&env, env.config("fixture", &[]), "auto"); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "auto task"); + let challenge = runtime.challenge(&run, &call_scope, &request).await; + + // Resolve the real pending row exactly as Guardian's automatic path does. + let resolution = runtime + .persistence() + .approval_resolve(&json!({ + "id": challenge.approval_id, + "run_id": run.run_id, + "state": "approved", + "resolver": "guardian", + "decision_reason": "guardian_allowed", + "resolved_at_ms": now_ms(), + })) + .expect("guardian resolution"); + assert_eq!(resolution["rows_affected"], 1); + assert_eq!( + approval_row(&runtime.persistence(), &challenge.approval_id)[13].as_str(), + Some("guardian") + ); + + let result = runtime + .policy + .delegate( + &call_scope, + &request, + &AcpApprovalWitness::new(challenge.approval_id), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Denied, "{result:?}"); + assert_eq!(result.code, Some("acp_approval_not_user")); + assert_eq!( + env.spawn_count(), + 0, + "an automatic allow can never authorize the external process" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn prepared_call_is_indeterminate_and_never_restarted() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cut-prepare"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "a")) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::AfterPrepareBeforeSpawn); + let cut = runtime + .policy + .delegate(&call_scope, &request("fixture", "a"), &witness) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + assert_eq!(cut.code, Some("acp_session_indeterminate")); + assert_eq!(env.spawn_count(), 0); + assert_eq!( + runtime + .policy + .call_settlement(&run.session_id, "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Indeterminate, + "a durable prepare is never reported as not started" + ); + assert_eq!(runtime.policy.quarantined_slots(), 1); + let session_id = run.session_id.clone(); + drop(runtime); + let runtime = Runtime::open(&env); + let doc = pin_document(&runtime.persistence(), &session_id); + assert_eq!(doc["calls"]["call-1"]["phase"], "prepared"); + assert_eq!(doc["pins"]["fixture"]["active"]["call_id"], "call-1"); + assert_eq!( + runtime + .policy + .call_settlement(&session_id, "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Indeterminate + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn crash_after_session_create_is_indeterminate_and_never_recreated() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cut-create"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let first_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &first_scope, &request("fixture", "a")) + .await; + runtime.policy.arm_fault(AcpPolicyFault::AfterSessionCreate); + let cut = runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + assert_eq!(cut.code, Some("acp_session_indeterminate")); + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &run.session_id); + assert_eq!(doc["pins"]["fixture"]["phase"], "creating"); + assert!(doc["pins"]["fixture"]["external_session_id"].is_null()); + assert_eq!(doc["calls"]["call-1"]["phase"], "creating"); + assert_eq!( + runtime + .policy + .call_settlement(&run.session_id, "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Indeterminate, + "a prepared/creating call is never reported as not started" + ); + + let spawns = env.spawn_count(); + let session_id = run.session_id.clone(); + drop(runtime); + let runtime = Runtime::open(&env); + let run = runtime.open_run(Some(&session_id)).await; + let second_scope = scope(&run, "call-2"); + let witness = runtime + .approve(&run, &second_scope, &request("fixture", "b")) + .await; + let blocked = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(blocked.status, AcpDelegationStatus::Failed); + assert_eq!(blocked.code, Some("acp_session_indeterminate")); + assert_eq!( + env.spawn_count(), + spawns, + "unknown create state must not re-spawn" + ); + assert_eq!(env.recorded("session/new"), 1); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn crash_after_id_persisted_blocks_the_old_call_but_allows_a_new_one() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cut-persist"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let first_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::AfterSessionPersisted); + let session_id = run.session_id.clone(); + let cut = runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + // Close the official store and reopen it before proving the cut. + drop(runtime); + let runtime = Runtime::open(&env); + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &session_id); + assert_eq!(doc["pins"]["fixture"]["phase"], "bound"); + assert!(doc["pins"]["fixture"]["external_session_id"].is_string()); + assert_eq!(doc["calls"]["call-1"]["phase"], "session_bound"); + let run = runtime.open_run(Some(&session_id)).await; + let first_scope = scope(&run, "call-1"); + + // The original call can never be restarted. + let spawns = env.spawn_count(); + let restart = runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + assert_eq!(restart.status, AcpDelegationStatus::Denied); + assert_eq!(restart.code, Some("acp_call_indeterminate")); + assert_eq!(env.spawn_count(), spawns); + + // A newly approved call may resume the persisted ID. + let second_scope = scope(&run, "call-2"); + let witness = runtime + .approve(&run, &second_scope, &request("fixture", "b")) + .await; + let resumed = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!( + resumed.status, + AcpDelegationStatus::Completed, + "{resumed:?}" + ); + assert_eq!(env.recorded("session/new"), 1); + assert_eq!(env.recorded("session/resume"), 1); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn crash_after_prompt_publication_blocks_the_binding() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cut-prompt"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let first_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::AfterPromptPublished); + let session_id = run.session_id.clone(); + let cut = runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + drop(runtime); + let runtime = Runtime::open(&env); + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &session_id); + assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); + assert_eq!(doc["calls"]["call-1"]["phase"], "prompt_intent"); + let run = runtime.open_run(Some(&session_id)).await; + + let spawns = env.spawn_count(); + let session_id = run.session_id.clone(); + drop(runtime); + let runtime = Runtime::open(&env); + let run = runtime.open_run(Some(&session_id)).await; + let second_scope = scope(&run, "call-2"); + let witness = runtime + .approve(&run, &second_scope, &request("fixture", "b")) + .await; + let blocked = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(blocked.status, AcpDelegationStatus::Failed); + assert_eq!(blocked.code, Some("acp_session_indeterminate")); + assert_eq!( + env.spawn_count(), + spawns, + "unknown prompt state must not re-run" + ); +} + +#[tokio::test] +async fn concurrent_calls_on_one_pin_have_one_winner() { + let env = Env::new("single-winner"); + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--delay-ms", "15000"]), + "user", + ); + let first_run = runtime.open_run(None).await; + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let first_scope = scope(&first_run, "call-1"); + let second_scope = scope(&second_run, "call-2"); + let first_witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + let second_witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "b")) + .await; + let policy = runtime.policy.clone(); + let first = tokio::spawn(async move { + policy + .delegate(&first_scope, &request("fixture", "a"), &first_witness) + .await + }); + wait_for(|| env.spawn_count() == 1, "the first delegation to spawn").await; + let second = runtime + .policy + .delegate(&second_scope, &request("fixture", "b"), &second_witness) + .await; + assert_eq!(second.status, AcpDelegationStatus::Busy, "{second:?}"); + assert_eq!(second.code, Some("acp_delegation_busy")); + let first = first.await.expect("first delegation task"); + assert_eq!(first.status, AcpDelegationStatus::Completed, "{first:?}"); + assert_eq!(env.spawn_count(), 1, "the loser must not spawn"); +} + +#[tokio::test] +async fn two_harnesses_in_one_session_keep_both_pin_updates() { + let env = Env::new("two-harnesses"); + let runtime = Runtime::open_with( + &env, + env.config_multi(&[ + ("fixture", &["--delay-ms", "1500"]), + ("other", &["--delay-ms", "1500"]), + ]), + "user", + ); + let first_run = runtime.open_run(None).await; + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let first_scope = scope(&first_run, "call-1"); + let second_scope = scope(&second_run, "call-2"); + let first_witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + let second_witness = runtime + .approve(&second_run, &second_scope, &request("other", "b")) + .await; + let policy = runtime.policy.clone(); + let first = tokio::spawn(async move { + policy + .delegate(&first_scope, &request("fixture", "a"), &first_witness) + .await + }); + wait_for(|| env.spawn_count() == 1, "first harness spawn").await; + let second = runtime + .policy + .delegate(&second_scope, &request("other", "b"), &second_witness) + .await; + assert_eq!(second.status, AcpDelegationStatus::Completed, "{second:?}"); + assert_eq!( + first.await.expect("first delegation").status, + AcpDelegationStatus::Completed + ); + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &first_run.session_id); + let fixture_id = doc["pins"]["fixture"]["external_session_id"] + .as_str() + .expect("the concurrent other-harness write must not erase the fixture pin"); + let other_id = doc["pins"]["other"]["external_session_id"] + .as_str() + .expect("the other harness must keep its pin"); + assert!( + fixture_id != other_id, + "the harnesses must have distinct external IDs" + ); + assert_eq!(env.recorded("session/new"), 2); +} + +#[tokio::test] +async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { + let env = Env::new("quota"); + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--delay-ms", "30000"]), + "user", + ); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let first_witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + let policy = runtime.policy.clone(); + let first = tokio::spawn(async move { + policy + .delegate(&first_scope, &request("fixture", "a"), &first_witness) + .await + }); + wait_for(|| env.spawn_count() == 1, "first spawn").await; + // Same run: refused before any read or spawn. + let same_run_scope = scope(&first_run, "call-2"); + let witness = runtime + .approve(&first_run, &same_run_scope, &request("fixture", "b")) + .await; + let same_run = runtime + .policy + .delegate(&same_run_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(same_run.status, AcpDelegationStatus::Busy); + assert_eq!(same_run.code, Some("acp_delegation_busy")); + + // Fill the remaining three service slots, then expect a typed refusal. + let mut handles = Vec::new(); + for index in 2..=4 { + let run = runtime.open_run(None).await; + let call_scope = scope(&run, &format!("call-{index}")); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "fill")) + .await; + let policy = runtime.policy.clone(); + handles.push(tokio::spawn(async move { + policy + .delegate(&call_scope, &request("fixture", "fill"), &witness) + .await + })); + } + wait_for(|| env.spawn_count() == 4, "the quota to fill").await; + assert_eq!(runtime.policy.available_processes(), 0); + let overflow_run = runtime.open_run(None).await; + let overflow_scope = scope(&overflow_run, "call-5"); + let witness = runtime + .approve( + &overflow_run, + &overflow_scope, + &request("fixture", "overflow"), + ) + .await; + let overflow = runtime + .policy + .delegate(&overflow_scope, &request("fixture", "overflow"), &witness) + .await; + assert_eq!(overflow.status, AcpDelegationStatus::Busy); + assert_eq!(overflow.code, Some("acp_delegation_capacity")); + assert_eq!( + first.await.expect("first task").status, + AcpDelegationStatus::Completed + ); + for handle in handles { + let result = handle.await.expect("quota task"); + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + } + assert_eq!(runtime.policy.available_processes(), 4); + assert_eq!(env.spawn_count(), 4, "the refused call must not spawn"); +} + +#[tokio::test] +async fn session_delete_clears_the_local_binding() { + let env = Env::new("delete"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "a")) + .await; + runtime + .policy + .delegate(&first_scope, &request("fixture", "a"), &witness) + .await; + runtime.finish(&first_run).await; + runtime + .persistence() + .session_delete(&first_run.session_id) + .expect("delete session"); + + // A fresh main session cannot see the deleted binding. + let new_run = runtime.open_run(None).await; + let new_scope = scope(&new_run, "call-2"); + let witness = runtime + .approve(&new_run, &new_scope, &request("fixture", "b")) + .await; + let result = runtime + .policy + .delegate(&new_scope, &request("fixture", "b"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed); + assert_eq!( + result.text, "ctx=0;reply=policy-reply", + "deleted binding must not resume" + ); + assert_eq!(env.recorded("session/new"), 2); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cleanup-unconfirmed"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + runtime.policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Indeterminate); + assert_eq!(result.code, Some("acp_cleanup_unverified")); + assert!( + result.text.is_empty(), + "an unsettled prompt has no result text" + ); + assert!( + !result.replayed, + "the original delivery is not a replay of a success" + ); + + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!(runtime.policy.quarantined_slots(), 1); + assert_eq!( + runtime.policy.quarantined_calls(), + vec![(format!("{}:fixture", run.session_id), "call-1".to_string())] + ); + + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &run.session_id); + assert_eq!(doc["pins"]["fixture"]["phase"], "cleanup_pending"); + assert_eq!(doc["pins"]["fixture"]["active"]["call_id"], "call-1"); + assert_eq!(doc["pins"]["fixture"]["cleanup_pending"], true); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + assert_eq!( + runtime + .policy + .call_settlement(&run.session_id, "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Settled + ); + + let spawns = env.spawn_count(); + let replay = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert!(replay.replayed); + assert_eq!(replay.status, AcpDelegationStatus::Indeterminate); + assert_eq!(replay.code, Some("acp_cleanup_unverified")); + assert_eq!(env.spawn_count(), spawns); + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!(runtime.policy.quarantined_slots(), 1); + + let next_run = runtime.open_run(Some(&run.session_id)).await; + let next_scope = scope(&next_run, "call-2"); + let witness = runtime + .approve(&next_run, &next_scope, &request("fixture", "next")) + .await; + let next = runtime + .policy + .delegate(&next_scope, &request("fixture", "next"), &witness) + .await; + assert_eq!(next.status, AcpDelegationStatus::Failed); + assert_eq!(next.code, Some("acp_session_indeterminate")); + assert_eq!(env.spawn_count(), spawns); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn lost_cleanup_observer_keeps_capacity() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cleanup-lost"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::CleanupObserverLost); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Indeterminate); + assert_eq!(result.code, Some("acp_cleanup_unverified")); + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!(runtime.policy.quarantined_slots(), 1); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn stale_settlement_never_clears_a_newer_owner() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("stale-settlement"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + runtime.policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); + runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + let persistence = runtime.persistence(); + let before = pin_document(&persistence, &run.session_id); + runtime + .policy + .settle_stale_cleanup_for_test(&call_scope, "fixture", 0) + .await; + let after = pin_document(&persistence, &run.session_id); + assert_eq!(before, after); + assert_eq!(after["pins"]["fixture"]["phase"], "cleanup_pending"); +} + +#[tokio::test] +async fn cancelled_before_spawn_creates_no_process() { + let env = Env::new("cancel-pre-spawn"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + runtime + .service + .handle(&run.run_id) + .expect("live run handle") + .cancellation() + .request(CancellationReason::Requested); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Denied); + assert_eq!(result.code, Some("acp_delegation_cancelled")); + assert_eq!(env.spawn_count(), 0, "cancelled approval must not spawn"); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn cancellation_after_prepare_but_before_spawn_is_zero_spawn() { + let env = Env::new("cancel-after-prepare"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + let signal = runtime + .service + .handle(&run.run_id) + .expect("live run handle") + .cancellation() + .clone(); + runtime.policy.arm_pre_spawn_hook(move || { + signal.request(CancellationReason::Requested); + }); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Cancelled); + assert_eq!(result.code, Some("acp_delegation_cancelled")); + assert_eq!(env.spawn_count(), 0, "the last boundary refuses to spawn"); + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + assert!(doc["pins"]["fixture"]["active"].is_null()); +} + +#[tokio::test] +async fn cancellation_during_setup_closes_without_prompting() { + let env = Env::new("cancel-setup"); + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--init-delay-ms", "3000"]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + let signal = runtime + .service + .handle(&run.run_id) + .expect("live run handle") + .cancellation() + .clone(); + let policy = runtime.policy.clone(); + let scope_for_task = call_scope.clone(); + let request_for_task = request("fixture", "task"); + let witness_for_task = witness.clone(); + let task = tokio::spawn(async move { + policy + .delegate(&scope_for_task, &request_for_task, &witness_for_task) + .await + }); + wait_for(|| env.spawn_count() == 1, "the setup harness to spawn").await; + tokio::time::sleep(Duration::from_millis(150)).await; + signal.request(CancellationReason::Requested); + let result = tokio::time::timeout(Duration::from_secs(15), task) + .await + .expect("setup cancellation must finish") + .expect("delegation task"); + assert_eq!(result.status, AcpDelegationStatus::Cancelled, "{result:?}"); + assert_eq!(env.recorded("session/prompt"), 0, "no prompt was published"); + assert_eq!( + runtime + .policy + .call_settlement(&run.session_id, "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Settled + ); +} + +#[tokio::test] +async fn cancellation_after_prompt_is_observable_and_never_reports_success() { + let env = Env::new("cancel-after-send"); + let runtime = Runtime::open_with(&env, env.config("fixture", &["--hold"]), "user"); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + let signal = runtime + .service + .handle(&run.run_id) + .expect("live run handle") + .cancellation() + .clone(); + let policy = runtime.policy.clone(); + let scope_for_task = call_scope.clone(); + let request_for_task = request("fixture", "task"); + let task = tokio::spawn(async move { + policy + .delegate(&scope_for_task, &request_for_task, &witness) + .await + }); + wait_for( + || env.recorded("session/prompt") == 1, + "the prompt to publish", + ) + .await; + signal.request(CancellationReason::Requested); + let result = tokio::time::timeout(Duration::from_secs(15), task) + .await + .expect("prompt cancellation must finish") + .expect("delegation task"); + assert_eq!(result.status, AcpDelegationStatus::Cancelled, "{result:?}"); + assert!(!result.replayed); + assert_eq!( + result.text, "", + "a cancelled prompt never reports a partial success" + ); + assert_eq!(env.recorded("session/cancel"), 1, "the peer is cancelled"); + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!( + doc["pins"]["fixture"]["phase"], "unknown", + "a possibly delivered prompt blocks reuse" + ); +} + +#[tokio::test] +async fn stale_cas_from_two_store_connections_is_not_committed() { + let env = Env::new("cas-stale"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let session_id = run.session_id.clone(); + let first = runtime.persistence(); + let second = GatewayPersistence::open(&AgentGatewayConfig::default(), &env.db()) + .expect("second product store connection"); + let row = |persistence: &GatewayPersistence| { + let value = persistence.session_get(&session_id).expect("session"); + let row = value["rows"][0].as_array().expect("row").clone(); + let owner = row[6].as_str().unwrap_or_default().to_string(); + let created = row[15].as_i64().unwrap_or_default(); + (owner, created) + }; + let (owner, created) = row(&first); + let cas = |persistence: &GatewayPersistence, expected: i64, value: Value| { + persistence + .session_acp_delegation_cas(&json!({ + "session_id": session_id, + "owner": owner, + "created_at_ms": created, + "expected_version": expected, + "lease_path": "", + "lease_call": "", + "document_json": serde_json::to_string(&value).expect("document"), + "now_ms": 1, + })) + .expect("cas") + }; + let winner = cas(&second, -1, json!({"version": 0, "pins": {"a": 1}})); + assert_eq!(winner["applied"], true); + let stale = cas(&first, -1, json!({"version": 0, "pins": {"b": 2}})); + assert_eq!( + stale["applied"], false, + "a stale version from another product connection must not commit" + ); + let doc = pin_document(&first, &session_id); + assert!( + doc["pins"]["a"].is_number(), + "the winner is preserved: {doc}" + ); + assert!(doc["pins"].get("b").is_none(), "{doc}"); + + // Retrying from the observed version is the only way to commit. + let retry = cas(&first, 0, json!({"version": 1, "pins": {"a": 1, "b": 2}})); + assert_eq!(retry["applied"], true); + let doc = pin_document(&first, &session_id); + assert_eq!(doc["pins"]["a"], 1); + assert_eq!(doc["pins"]["b"], 2); +} + +#[tokio::test] +async fn delete_race_and_recreated_session_reject_the_old_identity() { + let env = Env::new("cas-delete"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let session_id = run.session_id.clone(); + let persistence = runtime.persistence(); + let value = persistence.session_get(&session_id).expect("session"); + let row = value["rows"][0].as_array().expect("row").clone(); + let owner = row[6].as_str().unwrap_or_default().to_string(); + let created = row[15].as_i64().unwrap_or_default(); + let cas = |expected: i64, value: Value| { + persistence + .session_acp_delegation_cas(&json!({ + "session_id": session_id, + "owner": owner, + "created_at_ms": created, + "expected_version": expected, + "lease_path": "", + "lease_call": "", + "document_json": serde_json::to_string(&value).expect("document"), + "now_ms": 1, + })) + .expect("cas") + }; + persistence + .session_delete(&session_id) + .expect("delete session"); + let raced = cas(-1, json!({"version": 0, "pins": {"a": 1}})); + assert_eq!( + raced["applied"], false, + "a delete race must be an explicit not-committed result" + ); + assert!( + persistence.session_get(&session_id).expect("read")["rows"] + .as_array() + .is_none_or(|rows| rows.is_empty()), + "the deleted session is not resurrected" + ); + + // Recreate the same session id with a new durable identity; the old CAS + // expectation still names the deleted row and cannot write into it. + let recreated_at = now_ms() + 1; + persistence + .session_create(&json!({ + "id": session_id, + "profile": "default", + "platform": "policy-fixture", + "account_id": session_id, + "chat_id": "7", + "thread_id": "", + "user_id": owner, + "generation": 1, + "system_prompt": "", + "model": "policy-model", + "provider": "policy-provider", + "toolset_hash": "policy-tools", + "metadata_json": "{}", + "title": "", + "end_reason": "", + "now_ms": recreated_at, + })) + .expect("recreate the same session id with a new identity"); + let old = cas(-1, json!({"version": 0, "pins": {"old": true}})); + assert_eq!(old["applied"], false, "the old owner must not write again"); + let current = persistence.session_get(&session_id).expect("session"); + assert_eq!(current["rows"][0][15].as_i64(), Some(recreated_at)); + assert!( + current["rows"][0][13] + .as_str() + .unwrap_or_default() + .find("acp_delegation") + .is_none(), + "the old owner did not write into the recreated row" + ); +} + +#[tokio::test] +async fn non_executable_launch_definition_blocks_install_before_startup() { + let env = Env::new("bad-launch"); + let target = env.root.join("not-executable"); + fs::write(&target, "#!/bin/sh\nexit 0\n").expect("write non-executable launch"); + let yaml = format!( + "version: 1\nworkspaces:\n allowed_roots:\n - '{}'\nacp_harnesses:\n - id: bad\n command: '{}'\n", + env.workspace.display(), + target.display() + ); + let config = ConfigFile::from_str(&yaml).expect("structurally valid config"); + let state = AgentGatewayState::with_sqlite_path(AgentGatewayConfig::default(), env.db()) + .expect("open isolated gateway state"); + let service = state.service(); + let persistence = state.persistence().expect("persistence"); + let error = match AcpDelegationPolicy::install(&config, persistence, service) { + Ok(_) => panic!("a command that cannot be executed must fail startup"), + Err(error) => error, + }; + assert!(error.contains("executable"), "{error}"); +} + +#[tokio::test] +async fn result_envelope_obeys_the_run_output_budget_with_utf8_truncation() { + let env = Env::new("envelope-budget"); + let long_reply = "é".repeat(3000); + let budget = 640usize; + let runtime = Runtime::open_with( + &env, + env.config_limited(budget, "fixture", &["--reply", &long_reply]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "budget")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "budget"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert!(result.truncated, "the text must be truncated"); + assert!(result.text.len() < long_reply.len()); + assert!( + result.text.is_char_boundary(result.text.len()), + "truncation keeps valid UTF-8" + ); + let envelope = serde_json::to_vec(&result.to_json()).expect("envelope"); + assert!( + envelope.len() <= budget, + "the whole serialized envelope must fit the run budget: {} > {budget}", + envelope.len() + ); +} + +#[tokio::test] +async fn cancellation_during_restore_closes_without_prompting() { + let env = Env::new("cancel-restore"); + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--restore-delay-ms", "3000"]), + "user", + ); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "first")) + .await; + let first = runtime + .policy + .delegate(&first_scope, &request("fixture", "first"), &witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed); + runtime.finish(&first_run).await; + + let second_run = runtime.open_run(Some(&first_run.session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "second")) + .await; + let signal = runtime + .service + .handle(&second_run.run_id) + .expect("live run handle") + .cancellation() + .clone(); + let policy = runtime.policy.clone(); + let scope_for_task = second_scope.clone(); + let request_for_task = request("fixture", "second"); + let task = tokio::spawn(async move { + policy + .delegate(&scope_for_task, &request_for_task, &witness) + .await + }); + wait_for( + || env.recorded("session/resume") == 1, + "the restore request to reach the peer", + ) + .await; + signal.request(CancellationReason::Requested); + let result = tokio::time::timeout(Duration::from_secs(15), task) + .await + .expect("restore cancellation must finish") + .expect("delegation task"); + assert_eq!(result.status, AcpDelegationStatus::Cancelled, "{result:?}"); + assert_eq!( + env.recorded("session/prompt"), + 1, + "only the first call published a prompt" + ); + let doc = pin_document(&runtime.persistence(), &first_run.session_id); + assert_eq!( + doc["pins"]["fixture"]["phase"], "bound", + "a cancelled restore never spoils the known binding" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn real_cleanup_observer_settles_the_lost_prompt_once() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("observer-real"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "observed")) + .await; + runtime.policy.arm_fault(AcpPolicyFault::DeferToObserver); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "observed"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Indeterminate); + assert_eq!(result.code, Some("acp_cleanup_unconfirmed")); + // The real supervisor observer resolves cleanup and commits one + // indeterminate settlement without turning it into a success. + wait_for( + || runtime.policy.available_processes() == 4, + "the real observer to release the slot", + ) + .await; + assert_eq!(runtime.policy.quarantined_slots(), 0); + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + if runtime + .policy + .call_settlement(&run.session_id, "call-1") + .await + .expect("settlement") + == rustscript_agent::effects::DelegationSettlement::Settled + { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "the real observer must settle the lost prompt" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); + assert_eq!(doc["calls"]["call-1"]["outcome"]["status"], "indeterminate"); +} + +fn minimal_success_envelope(harness_id: &str) -> usize { + let result = AcpDelegationResult { + harness_id: harness_id.to_string(), + status: AcpDelegationStatus::Completed, + text: String::new(), + stop_reason: Some(AcpStopReason::EndTurn), + truncated: false, + code: None, + replayed: false, + }; + serde_json::to_vec(&result.to_json()) + .expect("envelope") + .len() +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn stop_observed_at_the_spawn_barrier_is_zero_spawn() { + let env = Env::new("barrier-stop"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + let service = runtime.service.clone(); + let run_id = run.run_id.clone(); + runtime.policy.arm_pre_spawn_hook(move || { + service.stop(&run_id); + }); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Cancelled, "{result:?}"); + assert_eq!(result.code, Some("acp_delegation_cancelled")); + assert_eq!( + env.spawn_count(), + 0, + "a stop seen before spawn never spawns" + ); + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + assert!(doc["pins"]["fixture"]["active"].is_null()); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn workspace_revocation_observed_at_the_spawn_barrier_is_zero_spawn() { + let env = Env::new("barrier-revoke"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + let service = runtime.service.clone(); + let run_id = run.run_id.clone(); + runtime.policy.arm_pre_spawn_hook(move || { + assert!( + service.revoke_run_workspace_authority(&run_id), + "the retained authority must be revocable" + ); + }); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Denied, "{result:?}"); + assert_eq!(result.code, Some("acp_workspace_invalid")); + assert_eq!( + env.spawn_count(), + 0, + "a revoked workspace authority never spawns" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn expired_run_clock_observed_at_the_spawn_barrier_is_zero_spawn() { + let env = Env::new("barrier-deadline"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "task")) + .await; + runtime.service.set_context_deadline_at_ms(&run.run_id, 1); + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "task"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Timeout, "{result:?}"); + assert_eq!(result.code, Some("acp_delegation_deadline")); + assert_eq!(env.spawn_count(), 0, "an elapsed clock never spawns"); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn cleanup_in_progress_keeps_the_pin_and_blocks_a_second_spawn() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("observer-hold"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let first_scope = scope(&run, "call-1"); + let first_witness = runtime + .approve(&run, &first_scope, &request("fixture", "first")) + .await; + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + runtime + .policy + .arm_cleanup_hold(entered.clone(), release.clone()); + runtime.policy.arm_fault(AcpPolicyFault::DeferToObserver); + let first = runtime + .policy + .delegate(&first_scope, &request("fixture", "first"), &first_witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Indeterminate); + entered.notified().await; + assert_eq!( + runtime.policy.available_processes(), + 3, + "the observer still owns the charged slot" + ); + + // The same pin must not start a second process while the real observer + // still holds its ownership. A new run in the same session proves the + // durable pin block; the original run still holds its per-run admission. + let next_run = runtime.open_run(Some(&run.session_id)).await; + let second_scope = scope(&next_run, "call-2"); + let second_witness = runtime + .approve(&next_run, &second_scope, &request("fixture", "second")) + .await; + let second = runtime + .policy + .delegate( + &second_scope, + &request("fixture", "second"), + &second_witness, + ) + .await; + assert_eq!(second.status, AcpDelegationStatus::Failed, "{second:?}"); + assert_eq!(second.code, Some("acp_session_indeterminate")); + assert_eq!( + env.spawn_count(), + 1, + "no second process while cleanup holds" + ); + + release.notify_one(); + wait_for( + || runtime.policy.available_processes() == 4, + "the held observer to settle and release", + ) + .await; +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn idle_local_gate_never_reclaims_a_live_call() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("live-lease"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let first_scope = scope(&run, "call-1"); + let first_witness = runtime + .approve(&run, &first_scope, &request("fixture", "first")) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::AfterSessionPersisted); + let first = runtime + .policy + .delegate(&first_scope, &request("fixture", "first"), &first_witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Failed); + let spawns = env.spawn_count(); + assert_eq!(spawns, 1); + + // The in-process pin gate is free and the call is recoverable in shape, but + // its owning run is still live: no local lock can prove the owner is gone. + let second_scope = scope(&run, "call-2"); + let second_witness = runtime + .approve(&run, &second_scope, &request("fixture", "second")) + .await; + let second = runtime + .policy + .delegate( + &second_scope, + &request("fixture", "second"), + &second_witness, + ) + .await; + assert_eq!(second.status, AcpDelegationStatus::Failed, "{second:?}"); + assert_eq!(second.code, Some("acp_session_indeterminate")); + assert_eq!(env.spawn_count(), spawns, "the live owner keeps the lease"); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn restore_interrupted_before_intent_recovers_after_reopen() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("restore-recovery"); + let runtime = Runtime::open(&env); + let first_run = runtime.open_run(None).await; + let first_scope = scope(&first_run, "call-1"); + let first_witness = runtime + .approve(&first_run, &first_scope, &request("fixture", "first")) + .await; + let first = runtime + .policy + .delegate(&first_scope, &request("fixture", "first"), &first_witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed, "{first:?}"); + runtime.finish(&first_run).await; + let session_id = first_run.session_id.clone(); + + let second_run = runtime.open_run(Some(&session_id)).await; + let second_scope = scope(&second_run, "call-2"); + let second_witness = runtime + .approve(&second_run, &second_scope, &request("fixture", "second")) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::AfterRestoreBeforeIntent); + let cut = runtime + .policy + .delegate( + &second_scope, + &request("fixture", "second"), + &second_witness, + ) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed, "{cut:?}"); + assert_eq!( + env.recorded("session/prompt"), + 1, + "the second prompt never ran" + ); + let doc = pin_document(&runtime.persistence(), &session_id); + assert_eq!(doc["calls"]["call-2"]["phase"], "restoring"); + assert_eq!(doc["pins"]["fixture"]["active"]["call_id"], "call-2"); + + drop(runtime); + let runtime = Runtime::open(&env); + let third_run = runtime.open_run(Some(&session_id)).await; + let third_scope = scope(&third_run, "call-3"); + let third_witness = runtime + .approve(&third_run, &third_scope, &request("fixture", "third")) + .await; + let third = runtime + .policy + .delegate(&third_scope, &request("fixture", "third"), &third_witness) + .await; + assert_eq!(third.status, AcpDelegationStatus::Completed, "{third:?}"); + assert_eq!(third.text, "ctx=1;reply=policy-reply"); + let doc = pin_document(&runtime.persistence(), &session_id); + assert_eq!(doc["calls"]["call-2"]["phase"], "settled"); + assert_eq!( + doc["calls"]["call-2"]["outcome"]["code"], "acp_call_interrupted", + "taking over the lease settles the old call in the same write" + ); + assert!(doc["pins"]["fixture"]["active"].is_null()); + assert_eq!(doc["calls"]["call-3"]["phase"], "settled"); + assert_eq!(env.recorded("session/resume"), 2); + assert_eq!(env.recorded("session/new"), 1); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn cas_retry_recomputes_on_the_same_original_row() { + let env = Env::new("cas-retry"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let persistence = runtime.persistence(); + let session_id = run.session_id.clone(); + let writer = persistence.clone(); + let writer_session = session_id.clone(); + runtime.policy.arm_cas_hook(move || { + let value = writer.session_get(&writer_session).expect("session"); + let row = value["rows"][0].as_array().expect("row").clone(); + let mut delegation = row[13] + .as_str() + .and_then(|metadata| serde_json::from_str::(metadata).ok()) + .and_then(|metadata| metadata.get("acp_delegation").cloned()) + .unwrap_or_else( + || json!({"version": -1, "pins": {}, "calls": {}, "pending_approvals": {}}), + ); + let expected = delegation["version"].as_i64().unwrap_or(-1); + delegation["version"] = json!(expected + 1); + let cas = writer + .session_acp_delegation_cas(&json!({ + "session_id": writer_session, + "owner": row[6], + "created_at_ms": row[15], + "expected_version": expected, + "lease_path": "", + "lease_call": "", + "document_json": serde_json::to_string(&delegation).expect("document"), + "now_ms": now_ms(), + })) + .expect("revision writer"); + assert_eq!(cas["applied"], true); + }); + let challenge = runtime + .policy + .request_approval(&call_scope, &request("fixture", "task")) + .await + .expect("the same-row conflict is retried"); + let doc = pin_document(&persistence, &session_id); + assert_eq!(doc["version"], 1, "hook wrote generation 0, policy wrote 1"); + assert_eq!( + doc["pending_approvals"][challenge.approval_id.clone()]["task"], + "task" + ); + assert_eq!(env.spawn_count(), 0); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn session_replacement_between_read_and_cas_is_refused() { + let env = Env::new("cas-identity"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let persistence = runtime.persistence(); + let session_id = run.session_id.clone(); + let writer = persistence.clone(); + let writer_session = session_id.clone(); + runtime.policy.arm_cas_hook(move || { + writer + .session_delete(&writer_session) + .expect("delete the original session"); + writer + .session_create(&json!({ + "id": writer_session, + "profile": "default", + "platform": "policy-fixture", + "account_id": writer_session, + "chat_id": "7", + "thread_id": "", + "user_id": "replacement-owner", + "generation": 1, + "system_prompt": "", + "model": "policy-model", + "provider": "policy-provider", + "toolset_hash": "policy-tools", + "metadata_json": "{}", + "title": "", + "end_reason": "", + "now_ms": now_ms() + 1, + })) + .expect("recreate the session with a new identity"); + }); + let refusal = runtime + .policy + .request_approval(&call_scope, &request("fixture", "task")) + .await + .expect_err("the new session row must not inherit the old document"); + assert_eq!(refusal.code(), "acp_session_identity_changed"); + let value = persistence.session_get(&session_id).expect("session"); + assert!( + value["rows"][0][13] + .as_str() + .unwrap_or_default() + .find("acp_delegation") + .is_none(), + "no approval or lease leaked into the recreated row" + ); + assert_eq!(env.spawn_count(), 0); +} + +#[tokio::test] +async fn budget_below_the_minimal_envelope_is_refused_before_spawn() { + let env = Env::new("budget-below"); + let minimal = minimal_success_envelope("fixture"); + let runtime = Runtime::open_with( + &env, + env.config_limited(minimal - 1, "fixture", &[]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let refusal = runtime + .policy + .request_approval(&call_scope, &request("fixture", "task")) + .await + .expect_err("an impossible budget must not create an approval"); + assert_eq!(refusal.code(), "acp_delegation_budget"); + let pending = runtime + .service + .pending_approvals(&run.run_id, Some(&run.session_id)) + .expect("pending approvals"); + assert!(pending.is_empty()); + + let result = runtime + .policy + .delegate( + &call_scope, + &request("fixture", "task"), + &AcpApprovalWitness::new("not-an-approval"), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Failed); + assert_eq!(result.code, Some("acp_delegation_budget")); + assert_eq!(env.spawn_count(), 0, "no impossible call may spawn"); +} + +#[tokio::test] +async fn budget_equal_to_the_minimal_envelope_delivers_the_complete_result() { + let env = Env::new("budget-equal"); + let minimal = minimal_success_envelope("fixture"); + let reply = "abcd"; + let budget = minimal + "ctx=0;reply=".len() + reply.len(); + let runtime = Runtime::open_with( + &env, + env.config_limited(budget, "fixture", &["--reply", reply]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "budget")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "budget"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(result.text, format!("ctx=0;reply={reply}")); + assert!(!result.truncated); + let envelope = serde_json::to_vec(&result.to_json()).expect("envelope"); + assert_eq!(envelope.len(), budget, "the exact minimal budget is enough"); +} + +#[tokio::test] +async fn budget_above_the_minimal_envelope_keeps_a_longer_reply() { + let env = Env::new("budget-above"); + let minimal = minimal_success_envelope("fixture"); + let reply = "0123456789abcdefghij"; + let budget = minimal + "ctx=0;reply=".len() + reply.len(); + let runtime = Runtime::open_with( + &env, + env.config_limited(budget, "fixture", &["--reply", reply]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "budget")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "budget"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(result.text, format!("ctx=0;reply={reply}")); + assert!(!result.truncated); + assert!( + serde_json::to_vec(&result.to_json()) + .expect("envelope") + .len() + <= budget + ); +} + +#[tokio::test] +async fn budget_truncation_stays_on_a_utf8_boundary() { + let env = Env::new("budget-utf8"); + let minimal = minimal_success_envelope("fixture"); + // One byte short of the two-byte `é`: the full text cannot be delivered, + // and the chosen prefix must stop at the preceding character boundary. + let budget = minimal + "ctx=0;reply=".len() + 1; + let runtime = Runtime::open_with( + &env, + env.config_limited(budget, "fixture", &["--reply", "é"]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "budget")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "budget"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert!(result.truncated); + assert_eq!(result.text, "ctx=0;reply="); + assert!(result.text.is_char_boundary(result.text.len())); + assert!( + serde_json::to_vec(&result.to_json()) + .expect("envelope") + .len() + <= budget + ); +} + +fn refusal_envelope_bytes(harness_id: &str) -> usize { + AcpDelegationResult { + harness_id: harness_id.to_string(), + status: AcpDelegationStatus::Failed, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_delegation_budget"), + replayed: false, + } + .serialized_envelope_bytes() +} + +fn success_envelope_bytes(harness_id: &str) -> usize { + AcpDelegationResult { + harness_id: harness_id.to_string(), + status: AcpDelegationStatus::Completed, + text: String::new(), + stop_reason: Some(AcpStopReason::EndTurn), + truncated: false, + code: None, + replayed: false, + } + .serialized_envelope_bytes() +} + +fn minimum_deliverable_bytes(harness_id: &str) -> usize { + refusal_envelope_bytes(harness_id).max(success_envelope_bytes(harness_id)) +} + +#[tokio::test] +async fn guardian_reviewer_reaches_real_human_pending_then_executes() { + let env = Env::new("guardian-human"); + let runtime = Runtime::open_with(&env, env.config("fixture", &[]), "guardian"); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "guardian task"); + let challenge = runtime.challenge(&run, &call_scope, &request).await; + let row = approval_row(&runtime.persistence(), &challenge.approval_id); + assert_eq!(row[8].as_str(), Some("human_pending")); + assert_eq!( + runtime.service.resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "guardian", + Some(&run.session_id), + ), + Err("resolver_invalid") + ); + runtime + .service + .resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "http-bearer", + Some(&run.session_id), + ) + .expect("the real manual resolver"); + let result = runtime + .policy + .delegate( + &call_scope, + &request, + &AcpApprovalWitness::new(challenge.approval_id), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(env.spawn_count(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn telegram_adapter_publishes_and_resolves_real_delegation_approvals() { + use axum::{ + Json, Router, + extract::Path, + routing::{get, post}, + }; + use rustscript_agent::{TelegramConfig, gateway::telegram::spawn_telegram_adapter}; + use std::collections::VecDeque; + use std::sync::Mutex; + use tokio::sync::{Notify, oneshot}; + + for (reviewer, chat, chat_kind, thread) in [ + ("auto", 101, "private", None), + ("guardian", -102, "supergroup", Some(17)), + ] { + let env = Env::new("telegram-adapter-policy"); + write_policy_home(&env, reviewer); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let arrivals = Arc::new(Notify::new()); + let unpark = Arc::new(Notify::new()); + let updates = Arc::new(Mutex::new(VecDeque::::new())); + let sent = Arc::new(Mutex::new(Vec::<(String, Value)>::new())); + let bot_updates = updates.clone(); + let bot_sent = sent.clone(); + let worker_arrivals = arrivals.clone(); + let worker_release = unpark.clone(); + let app = Router::new() + .route("/hold", get(move || { + let (arrivals, unpark) = (worker_arrivals.clone(), worker_release.clone()); + async move { arrivals.notify_one(); unpark.notified().await; "done" } + })) + .route("/{bot}/{method}", post(move |Path((_, method)): Path<(String, String)>, bytes: axum::body::Bytes| { + let body: Value = if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap() }; + let (updates, sent) = (bot_updates.clone(), bot_sent.clone()); + async move { + let result = match method.as_str() { + "getMe" => json!({"id": 900, "is_bot": true, "first_name": "Fixture", "username": "fixture_bot"}), + "getUpdates" => { + tokio::time::sleep(Duration::from_millis(25)).await; + json!(updates.lock().unwrap().drain(..).collect::>()) + } + "sendMessage" => { + let mut sent = sent.lock().unwrap(); + sent.push((method, body)); + json!({"message_id": 4000 + sent.iter().filter(|(m, _)| m == "sendMessage").count() as i64}) + } + _ => { sent.lock().unwrap().push((method, body)); json!(true) } + }; + Json(json!({"ok": true, "result": result})) + } + })); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let source = format!( + r#" +use http; +pub fn run(input: map) -> map {{ + let request = http::request::new("GET", "http://{address}/hold"); + let response = http::client::request(request); + {{kind: "run.completed", answer: "done"}} +}} +"# + ); + let mut gateway_config = AgentGatewayConfig { + http: rustscript_vm::HttpConfig { + allowed_hosts: vec!["127.0.0.1".into()], + allowed_schemes: vec!["http".into()], + allowed_ports: vec![address.port()], + allow_private_ips: true, + ..Default::default() + }, + ..Default::default() + }; + if reviewer == "guardian" { + gateway_config.approvals.reviewer = Some(reviewer.into()); + } + let state = + AgentGatewayState::with_agent_source_and_sqlite(gateway_config, source, env.db()) + .expect("start Telegram test gateway") + .with_workspace_home(&env.home); + let service = state.service(); + let persistence = state.persistence().unwrap(); + let policy = AcpDelegationPolicy::install( + &env.config("fixture", &[]), + persistence.clone(), + service.clone(), + ) + .unwrap() + .unwrap(); + let (send_run, receive_run) = oneshot::channel(); + persistence.inject_admission_precommit_hook(move |payload| { + send_run + .send( + payload["run_id"] + .as_str() + .expect("admission run id") + .to_string(), + ) + .unwrap(); + }); + let adapter = spawn_telegram_adapter( + state, + TelegramConfig { + bot_token: "synthetic-telegram-fixture".into(), + api_base: format!("http://{address}"), + allow_insecure_localhost: true, + allowed_accounts: vec!["fixture_bot".into()], + allowed_chats: vec![chat, -103], + allowed_users: vec![101, 202], + drop_pending_updates: false, + max_edit_interval: Duration::from_millis(50), + ..Default::default() + }, + ) + .await + .expect("start production Telegram adapter"); + let message = |update, actor, dst, text: &str| { + json!({"update_id":update, "message":{ + "message_id":update, "date":0, "chat":{"id":dst,"type":chat_kind}, + "message_thread_id":thread, "from":{"id":actor,"is_bot":false,"first_name":"Actor"}, "text":text + }}) + }; + updates + .lock() + .unwrap() + .push_back(message(1, 101, chat, "review fixture")); + let run_id = tokio::time::timeout(Duration::from_secs(300), receive_run) + .await + .unwrap_or_else(|_| { + panic!( + "Telegram admission did not reach commit; bot sends: {:?}", + *sent.lock().unwrap() + ) + }) + .unwrap(); + tokio::time::timeout(Duration::from_secs(300), arrivals.notified()) + .await + .expect("production worker parked"); + let thread_text = thread.map_or_else(String::new, |id| id.to_string()); + let session_id = format!("telegram:fixture_bot:{chat}:{thread_text}"); + let call = |tool_call_id: &str| AcpDelegationScope { + run_id: run_id.clone(), + session_id: session_id.clone(), + tool_call_id: tool_call_id.into(), + }; + let req = request("fixture", "benign complete fixture task"); + let issued = policy + .request_approval(&call("accept"), &req) + .await + .unwrap(); + assert_eq!( + approval_row(&persistence, &issued.approval_id)[8], + "human_pending" + ); + wait_for( + || { + sent.lock().unwrap().iter().any(|(m, body)| { + m == "sendMessage" + && body["text"].as_str().is_some_and(|text| { + text.starts_with("ACP delegation approval\n") + && text.contains(&req.task) + }) + }) + }, + "the production delegation approval card", + ) + .await; + let (card_id, card) = { + let sent = sent.lock().unwrap(); + let (index, (_, body)) = sent + .iter() + .enumerate() + .find(|(_, (m, body))| { + m == "sendMessage" + && body["text"] + .as_str() + .is_some_and(|text| text.starts_with("ACP delegation approval\n")) + }) + .unwrap(); + let id = 4000 + + sent[..=index] + .iter() + .filter(|(m, _)| m == "sendMessage") + .count() as i64; + (id, body.clone()) + }; + assert_eq!(card["reply_markup"].is_object(), thread.is_none()); + let approve = format!("/approve {}", issued.approval_id); + let callback_data = card["reply_markup"]["inline_keyboard"][0][0]["callback_data"].as_str(); + let decide = |update, actor, dst, msg_id| match callback_data { + Some(data) => json!({"update_id":update, "callback_query":{ + "id": format!("cb-{update}"), "data":data, "from":{"id":actor,"is_bot":false,"first_name":"Actor"}, + "message":{"message_id":msg_id,"date":0,"chat":{"id":dst,"type":chat_kind},"message_thread_id":thread} + }}), + None => message(update, actor, dst, &approve), + }; + if thread.is_none() { + wait_for( + || service.telegram_approval_picker(chat, card_id).is_some(), + "the exact picker binding", + ) + .await; + let picker = service.telegram_approval_picker(chat, card_id).unwrap(); + assert_eq!(picker.approval_id, issued.approval_id); + assert_eq!(picker.owner_user_id, "101"); + } + updates + .lock() + .unwrap() + .extend([decide(2, 202, chat, card_id), decide(3, 101, -103, card_id)]); + wait_for( + || adapter.processed_updates() >= 3, + "wrong actor and wrong chat decisions", + ) + .await; + assert_eq!( + approval_row(&persistence, &issued.approval_id)[7], + "pending" + ); + assert_eq!(env.spawn_count(), 0); + updates + .lock() + .unwrap() + .push_back(decide(4, 101, chat, card_id)); + wait_for(|| adapter.processed_updates() >= 4, "owner decision").await; + assert_eq!( + approval_row(&persistence, &issued.approval_id)[13], + "telegram:101" + ); + let witness = AcpApprovalWitness::new(issued.approval_id); + let result = policy.delegate(&call("accept"), &req, &witness).await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert!( + policy + .delegate(&call("accept"), &req, &witness) + .await + .replayed + ); + let declined = policy + .request_approval(&call("decline"), &req) + .await + .unwrap(); + updates.lock().unwrap().push_back(message( + 5, + 101, + chat, + &format!("/deny {}", declined.approval_id), + )); + wait_for(|| adapter.processed_updates() >= 5, "owner command denial").await; + assert_eq!( + approval_row(&persistence, &declined.approval_id)[7], + "denied" + ); + assert_eq!( + policy + .delegate( + &call("decline"), + &req, + &AcpApprovalWitness::new(declined.approval_id) + ) + .await + .status, + AcpDelegationStatus::Denied + ); + assert_eq!(env.spawn_count(), 1); + assert_eq!(env.recorded("session/prompt"), 1); + unpark.notify_one(); + wait_for( + || { + service + .handle(&run_id) + .is_some_and(|handle| handle.is_terminal()) + }, + "fixture worker exit", + ) + .await; + adapter.shutdown().await; + server.abort(); + let _ = server.await; + } +} + +#[tokio::test] +async fn telegram_route_authorizes_only_the_bound_owner_and_row() { + let env = Env::new("telegram-route"); + let runtime = Runtime::open_with(&env, env.config("fixture", &[]), "guardian"); + let _temp = runtime.open_run(None).await; + let session_id = _temp.session_id.clone(); + reown_session(&runtime.persistence(), &session_id, "101"); + let run = runtime.open_run(Some(&session_id)).await; + assert_eq!(run.session_id, session_id); + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "telegram task"); + let challenge = runtime.challenge(&run, &call_scope, &request).await; + + let picker = |owner: &str| TelegramApprovalPicker { + run_id: run.run_id.clone(), + approval_id: challenge.approval_id.clone(), + message_id: 42, + account: "fixture".to_string(), + session_id: session_id.to_string(), + chat_id: 101, + thread_id: None, + owner_user_id: owner.to_string(), + }; + assert_eq!( + runtime + .service + .bind_telegram_approval_picker(&picker("202")), + Err("approval_owner_mismatch"), + "another Telegram actor cannot bind this row" + ); + runtime + .service + .bind_telegram_approval_picker(&picker("101")) + .expect("the owner's real Telegram picker binds"); + assert_eq!( + runtime.service.resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "telegram:202", + Some(&session_id), + ), + Err("approval_owner_mismatch"), + "another actor cannot decide the bound row" + ); + runtime + .service + .resolve_pending_approval( + &run.run_id, + &challenge.approval_id, + "approved", + "telegram:101", + Some(&session_id), + ) + .expect("the production Telegram decision path"); + let result = runtime + .policy + .delegate( + &call_scope, + &request, + &AcpApprovalWitness::new(challenge.approval_id), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(env.spawn_count(), 1); +} + +#[tokio::test] +async fn http_route_authorizes_only_the_bound_delegation() { + let env = Env::new("http-route"); + let (runtime, address) = Runtime::open_http(&env, "user", "policy-test-token"); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "http task"); + let challenge = runtime.challenge(&run, &call_scope, &request).await; + let path = format!( + "/v1/runs/{}/approvals/{}", + run.run_id, challenge.approval_id + ); + let body = json!({ "decision": "approved" }).to_string(); + let (status, _) = raw_http(&address, "POST", &path, None, &body).await; + assert_eq!(status, 401, "the real HTTP entry requires the bearer token"); + let (status, _) = raw_http( + &address, + "POST", + &format!("/v1/runs/{}/approvals/not-a-row", run.run_id), + Some("policy-test-token"), + &body, + ) + .await; + assert_eq!(status, 404, "an unrelated approval id is not resolvable"); + let (status, _) = raw_http(&address, "POST", &path, Some("policy-test-token"), &body).await; + assert_eq!(status, 200, "the bound row resolves through the real API"); + assert_eq!( + approval_row(&runtime.persistence(), &challenge.approval_id)[13].as_str(), + Some("http-bearer") + ); + let result = runtime + .policy + .delegate( + &call_scope, + &request, + &AcpApprovalWitness::new(challenge.approval_id), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(env.spawn_count(), 1); +} + +#[tokio::test] +async fn same_owner_session_replacement_before_the_first_read_is_zero_write() { + let env = Env::new("replace-before-read"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "task"); + let witness = runtime.approve(&run, &call_scope, &request).await; + replace_session(&runtime.persistence(), &run.session_id); + let result = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert!( + matches!( + result.status, + AcpDelegationStatus::Denied | AcpDelegationStatus::Failed + ), + "{result:?}" + ); + assert_eq!(env.spawn_count(), 0); + assert_eq!( + pin_document(&runtime.persistence(), &run.session_id), + Value::Null, + "a replacement row never inherits an approval, lease or call" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn session_replacement_during_observer_settlement_is_zero_write() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("replace-observer"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "task"); + let witness = runtime.approve(&run, &call_scope, &request).await; + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + runtime + .policy + .arm_cleanup_hold(entered.clone(), release.clone()); + runtime.policy.arm_fault(AcpPolicyFault::DeferToObserver); + let result = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Indeterminate); + entered.notified().await; + replace_session(&runtime.persistence(), &run.session_id); + release.notify_one(); + wait_for( + || runtime.policy.quarantined_slots() == 1, + "replacement leaves the charged slot quarantined", + ) + .await; + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!( + pin_document(&runtime.persistence(), &run.session_id), + Value::Null, + "the observer's write never lands on the replacement row" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn known_id_prepared_call_is_not_taken_over() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("prepared-known-id"); + let runtime = Runtime::open(&env); + let first = runtime.open_run(None).await; + let first_scope = scope(&first, "call-1"); + let first_request = request("fixture", "first"); + let first_witness = runtime.approve(&first, &first_scope, &first_request).await; + let first_result = runtime + .policy + .delegate(&first_scope, &first_request, &first_witness) + .await; + assert_eq!(first_result.status, AcpDelegationStatus::Completed); + let known_id = pin_document(&runtime.persistence(), &first.session_id)["pins"]["fixture"] + ["external_session_id"] + .as_str() + .expect("bound id") + .to_string(); + assert!(!known_id.is_empty()); + + let second = runtime.open_run(Some(&first.session_id)).await; + let second_scope = scope(&second, "call-2"); + let second_request = request("fixture", "second"); + let second_witness = runtime + .approve(&second, &second_scope, &second_request) + .await; + runtime + .policy + .arm_fault(AcpPolicyFault::AfterPrepareBeforeSpawn); + let second_result = runtime + .policy + .delegate(&second_scope, &second_request, &second_witness) + .await; + assert_eq!( + second_result.status, + AcpDelegationStatus::Failed, + "{second_result:?}" + ); + runtime.finish(&second).await; + + let third = runtime.open_run(Some(&first.session_id)).await; + let third_scope = scope(&third, "call-3"); + let third_request = request("fixture", "third"); + let third_witness = runtime.approve(&third, &third_scope, &third_request).await; + let third_result = runtime + .policy + .delegate(&third_scope, &third_request, &third_witness) + .await; + assert_eq!(third_result.status, AcpDelegationStatus::Failed); + assert_eq!(third_result.code, Some("acp_session_indeterminate")); + assert_eq!( + env.spawn_count(), + 1, + "a Prepared call with a known id is never taken over" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn cleanup_pending_blocks_another_harness_until_a_new_prompt() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("other-harness-hold"); + let config = env.config_multi(&[("fixture", &[]), ("fixture2", &[])]); + let runtime = Runtime::open_with(&env, config, "user"); + let run = runtime.open_run(None).await; + let first_scope = scope(&run, "call-1"); + let first_request = request("fixture", "first"); + let first_witness = runtime.approve(&run, &first_scope, &first_request).await; + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + runtime + .policy + .arm_cleanup_hold(entered.clone(), release.clone()); + runtime.policy.arm_fault(AcpPolicyFault::DeferToObserver); + let first = runtime + .policy + .delegate(&first_scope, &first_request, &first_witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Indeterminate); + entered.notified().await; + + // The same pin cannot take over while the old process may still be alive. + let second = runtime.open_run(Some(&run.session_id)).await; + let second_scope = scope(&second, "call-2"); + let second_request = request("fixture", "second"); + let second_witness = runtime + .approve(&second, &second_scope, &second_request) + .await; + let blocked = runtime + .policy + .delegate(&second_scope, &second_request, &second_witness) + .await; + assert_eq!(blocked.status, AcpDelegationStatus::Failed); + assert_eq!(blocked.code, Some("acp_session_indeterminate")); + assert_eq!( + env.spawn_count(), + 1, + "no second process while cleanup is pending" + ); + + release.notify_one(); + wait_for( + || runtime.policy.quarantined_slots() == 0, + "confirmed cleanup releases the first slot", + ) + .await; + let third = runtime.open_run(Some(&run.session_id)).await; + let third_scope = scope(&third, "call-3"); + let third_request = request("fixture2", "third"); + let third_witness = runtime.approve(&third, &third_scope, &third_request).await; + let third_result = runtime + .policy + .delegate(&third_scope, &third_request, &third_witness) + .await; + assert_eq!( + third_result.status, + AcpDelegationStatus::Completed, + "{third_result:?}" + ); + assert_eq!( + env.spawn_count(), + 2, + "exactly one new prompt after confirmed cleanup" + ); + assert_eq!(env.recorded("session/new"), 2); + assert_eq!(env.recorded("session/prompt"), 2); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn stop_at_the_final_commit_point_is_zero_spawn() { + let env = Env::new("commit-stop"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "task"); + let witness = runtime.approve(&run, &call_scope, &request).await; + let service = runtime.service.clone(); + let run_id = run.run_id.clone(); + runtime.policy.arm_commit_hook(move || { + service.stop(&run_id); + }); + let result = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Cancelled, "{result:?}"); + assert_eq!(env.spawn_count(), 0); + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn revoke_at_the_final_commit_point_is_zero_spawn() { + let env = Env::new("commit-revoke"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "task"); + let witness = runtime.approve(&run, &call_scope, &request).await; + let service = runtime.service.clone(); + let run_id = run.run_id.clone(); + runtime.policy.arm_commit_hook(move || { + assert!(service.revoke_run_workspace_authority(&run_id)); + }); + let result = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Denied, "{result:?}"); + assert_eq!(result.code, Some("acp_workspace_invalid")); + assert_eq!(env.spawn_count(), 0); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn concurrent_stop_losing_the_spawn_race_is_cancelled_after_start() { + let env = Env::new("fence-stop-loser"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "task"); + let witness = runtime.approve(&run, &call_scope, &request).await; + let service = runtime.service.clone(); + let run_id = run.run_id.clone(); + runtime.policy.arm_fence_hook(move || { + let service = service.clone(); + let run_id = run_id.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + service.stop(&run_id); + }); + std::thread::sleep(Duration::from_millis(60)); + }); + let result = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Cancelled, "{result:?}"); + assert_eq!( + env.spawn_count(), + 1, + "the loser in the race started and was then cancelled normally" + ); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn approval_expiring_inside_spawn_fence_refuses_to_start() { + let env = Env::new("approval-at-spawn"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call = scope(&run, "expiry-call"); + let req = request("fixture", "task"); + let witness = runtime.approve(&run, &call, &req).await; + let expires = Arc::new(std::sync::atomic::AtomicI64::new(0)); + let expiry_for_commit = expires.clone(); + let root = env.root.clone(); + runtime.policy.arm_commit_hook(move || { + let expiration = now_ms() + 3000; + fixture_sql_at(&root, &format!("UPDATE approvals SET expires_at_ms = {expiration} WHERE tool_call_id = 'expiry-call'")); + expiry_for_commit.store(expiration, Ordering::Release); + }); + runtime.policy.arm_fence_hook(move || { + let expiry = expires.load(Ordering::Acquire); + assert!( + expiry > now_ms(), + "approval must be live on entering the fence" + ); + while now_ms() < expiry { + std::thread::sleep(Duration::from_millis(5)); + } + }); + let result = runtime.policy.delegate(&call, &req, &witness).await; + assert_eq!(result.status, AcpDelegationStatus::Denied, "{result:?}"); + assert_eq!(result.code, Some("acp_approval_expired")); + assert!( + runtime + .service + .handle(&run.run_id) + .unwrap() + .cancellation() + .requested() + .is_none() + ); + assert_eq!(env.spawn_count(), 0); + assert_eq!(runtime.policy.available_processes(), 4); + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["expiry-call"]["phase"], "settled"); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn run_deadline_expiring_inside_spawn_fence_refuses_to_start() { + let env = Env::new("run-deadline-at-spawn"); + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let call = scope(&run, "deadline-call"); + let req = request("fixture", "task"); + let witness = runtime.approve(&run, &call, &req).await; + let expiry = now_ms() + 2500; + runtime + .service + .set_context_deadline_at_ms(&run.run_id, expiry as u64); + runtime.policy.arm_fence_hook(move || { + assert!(now_ms() < expiry, "run must be live on entering the fence"); + while now_ms() <= expiry + 10 { + std::thread::sleep(Duration::from_millis(5)); + } + }); + let result = runtime.policy.delegate(&call, &req, &witness).await; + assert_eq!(result.status, AcpDelegationStatus::Timeout, "{result:?}"); + assert_eq!(result.code, Some("acp_delegation_deadline")); + assert_eq!(env.spawn_count(), 0); + assert_eq!(runtime.policy.available_processes(), 4); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn dropped_caller_cannot_release_the_spawn_fence_owner() { + let env = Env::new("drop-at-spawn"); + let runtime = Runtime::open_with( + &env, + env.config_multi(&[("fixture", &[]), ("other", &[])]), + "user", + ); + let run = runtime.open_run(None).await; + let call = scope(&run, "abandoned"); + let req = request("fixture", "held task"); + let witness = runtime.approve(&run, &call, &req).await; + let next = scope(&run, "next"); + let next_req = request("other", "next task"); + let next_witness = runtime.approve(&run, &next, &next_req).await; + let (entered, wait_entered) = tokio::sync::oneshot::channel(); + let (release, wait_release) = tokio::sync::oneshot::channel(); + let once = std::sync::Mutex::new(Some((entered, wait_release))); + runtime.policy.arm_fence_hook(move || { + let (entered, wait_release) = once.lock().unwrap().take().unwrap(); + entered.send(()).unwrap(); + let _ = wait_release.blocking_recv(); + }); + let policy = runtime.policy.clone(); + let task = tokio::spawn(async move { policy.delegate(&call, &req, &witness).await }); + tokio::time::timeout(Duration::from_secs(10), wait_entered) + .await + .unwrap() + .unwrap(); + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + assert_eq!(runtime.policy.available_processes(), 3); + let competing_policy = runtime.policy.clone(); + let (competing_scope, competing_req, competing_witness) = + (next.clone(), next_req.clone(), next_witness.clone()); + let mut competing = tokio::spawn(async move { + competing_policy + .delegate(&competing_scope, &competing_req, &competing_witness) + .await + }); + let busy = tokio::time::timeout(Duration::from_secs(10), &mut competing).await; + release.send(()).unwrap(); + let busy = busy + .expect("a competing caller must not wait on the spawn fence") + .unwrap(); + assert_eq!(busy.code, Some("acp_delegation_busy"), "{busy:?}"); + wait_for( + || runtime.policy.available_processes() == 4, + "zero-spawn settlement", + ) + .await; + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["abandoned"]["outcome"]["status"], "cancelled"); + assert_eq!(env.spawn_count(), 0); + let resumed = runtime + .policy + .delegate(&next, &next_req, &next_witness) + .await; + assert_eq!( + resumed.status, + AcpDelegationStatus::Completed, + "{resumed:?}" + ); + assert_eq!(env.spawn_count(), 1); +} + +#[tokio::test] +async fn dropped_caller_keeps_the_running_child_charged_until_reap() { + let env = Env::new("drop-running-owner"); + let release = env.root.join("exit-release"); + let runtime = Runtime::open_with( + &env, + env.config_multi(&[ + ( + "fixture", + &["--hold", "--eof-release", release.to_str().unwrap()], + ), + ("other", &[]), + ]), + "user", + ); + let run = runtime.open_run(None).await; + let call = scope(&run, "dropped-running"); + let req = request("fixture", "held task"); + let witness = runtime.approve(&run, &call, &req).await; + let next = scope(&run, "next"); + let next_req = request("other", "next task"); + let next_witness = runtime.approve(&run, &next, &next_req).await; + let policy = runtime.policy.clone(); + let task = tokio::spawn(async move { policy.delegate(&call, &req, &witness).await }); + wait_for(|| env.recorded("session/prompt") == 1, "held child prompt").await; + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + assert_eq!(runtime.policy.available_processes(), 3); + let busy = runtime + .policy + .delegate(&next, &next_req, &next_witness) + .await; + assert_eq!(busy.code, Some("acp_delegation_busy"), "{busy:?}"); + runtime + .service + .handle(&run.run_id) + .unwrap() + .cancellation() + .request(CancellationReason::Requested); + wait_for(|| env.recorded("stdin/eof") == 1, "child saw EOF").await; + assert_eq!( + runtime.policy.available_processes(), + 3, + "EOF does not prove exit or reap" + ); + fs::write(release, "exit").unwrap(); + wait_for( + || runtime.policy.available_processes() == 4, + "child reaped and durable settlement", + ) + .await; + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["dropped-running"]["cleanup_confirmed"], true); + assert_eq!( + doc["calls"]["dropped-running"]["outcome"]["status"], + "cancelled" + ); + assert_eq!(env.spawn_count(), 1); +} + +#[tokio::test] +async fn workspace_revocation_stops_only_its_running_delegation() { + let env = Env::new("revoke-after-prompt"); + let runtime = Runtime::open_with( + &env, + env.config_multi(&[("fixture", &["--hold"]), ("other", &[])]), + "user", + ); + let run = runtime.open_run(None).await; + let other = runtime.open_run(None).await; + let call = scope(&run, "revoked-call"); + let req = request("fixture", "held task"); + let witness = runtime.approve(&run, &call, &req).await; + let policy = runtime.policy.clone(); + let task = tokio::spawn(async move { policy.delegate(&call, &req, &witness).await }); + wait_for(|| env.recorded("session/prompt") == 1, "held prompt").await; + assert!(runtime.service.revoke_run_workspace_authority(&run.run_id)); + let result = tokio::time::timeout(Duration::from_secs(8), task) + .await + .expect("revocation must wake the owner") + .expect("delegation task"); + assert_eq!(result.status, AcpDelegationStatus::Denied, "{result:?}"); + assert_eq!(result.code, Some("acp_workspace_invalid")); + assert_eq!(runtime.policy.available_processes(), 4); + let doc = pin_document(&runtime.persistence(), &run.session_id); + assert_eq!(doc["calls"]["revoked-call"]["cleanup_confirmed"], true); + assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); + let call = scope(&other, "other-call"); + let req = request("other", "independent task"); + let witness = runtime.approve(&other, &call, &req).await; + let result = runtime.policy.delegate(&call, &req, &witness).await; + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + assert_eq!(env.spawn_count(), 2); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn failed_restore_phase_write_preserves_the_known_id_after_cleanup() { + let env = Env::new("known-id-write-failure"); + let runtime = Runtime::open(&env); + let first = runtime.open_run(None).await; + for (call_id, text) in [ + ("first", "first task"), + ("second", "never sent"), + ("third", "third task"), + ] { + let run = if call_id == "first" { + first.clone() + } else { + runtime.open_run(Some(&first.session_id)).await + }; + let call = scope(&run, call_id); + let req = request("fixture", text); + let witness = runtime.approve(&run, &call, &req).await; + if call_id == "second" { + fixture_sql( + &env, + "CREATE TRIGGER refuse_restore BEFORE UPDATE OF metadata_json ON sessions WHEN json_extract(NEW.metadata_json, '$.acp_delegation.calls.second.phase') = 'restoring' BEGIN SELECT RAISE(ABORT, 'fixture restore write rejected'); END", + ); + } + let result = runtime.policy.delegate(&call, &req, &witness).await; + if call_id == "second" { + assert_eq!(result.code, Some("acp_storage_not_committed"), "{result:?}"); + assert_eq!(runtime.policy.available_processes(), 4); + let doc = pin_document(&runtime.persistence(), &first.session_id); + assert_eq!(doc["calls"]["second"]["cleanup_confirmed"], true); + assert_eq!(doc["pins"]["fixture"]["phase"], "bound"); + let replay = runtime.policy.delegate(&call, &req, &witness).await; + assert!(replay.replayed, "{replay:?}"); + assert_eq!(env.spawn_count(), 2); + } else { + assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); + } + } + assert_eq!(env.spawn_count(), 3); + assert_eq!(env.recorded("session/new"), 1); + assert_eq!(env.recorded("session/resume"), 1); + assert_eq!(env.recorded("session/prompt"), 2); + fixture_sql(&env, "DROP TRIGGER refuse_restore"); + let events = fs::read_to_string(env.events()).expect("harness trace"); + assert!(events.contains("first task") && events.contains("third task")); + assert!(!events.contains("never sent")); +} + +#[tokio::test] +async fn budget_below_the_minimum_refusal_emits_no_acp_json() { + let env = Env::new("budget-below-refusal"); + let harness = "fixture"; + let minimum = minimum_deliverable_bytes(harness); + let runtime = Runtime::open_with(&env, env.config_limited(minimum - 1, harness, &[]), "user"); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let refusal = runtime + .policy + .request_approval(&call_scope, &request(harness, "task")) + .await + .expect_err("a budget below the typed refusal cannot be approved"); + assert_eq!(refusal.code(), "acp_delegation_budget"); + let result = runtime + .policy + .delegate( + &call_scope, + &request(harness, "task"), + &AcpApprovalWitness::new("not-an-approval"), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Failed); + assert_eq!(result.code, Some("acp_delegation_budget")); + assert!( + result.to_json_within(minimum - 1).is_none(), + "no over-limit ACP JSON may be emitted" + ); + assert_eq!(env.spawn_count(), 0); +} + +#[tokio::test] +async fn budget_at_the_minimum_deliverable_returns_the_typed_refusal() { + let env = Env::new("budget-equal-refusal"); + let budget = minimum_deliverable_bytes("fixture"); + let runtime = Runtime::open_with( + &env, + env.config_limited( + budget, + "fixture", + &[ + "--reply", + "a-long-reply", + "--stop-reason", + "max_turn_requests", + ], + ), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "budget")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "budget"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Failed, "{result:?}"); + assert_eq!(result.code, Some("acp_delegation_budget")); + assert!(result.text.is_empty()); + assert_eq!( + result.serialized_envelope_bytes(), + budget, + "the typed refusal fits the minimum safe budget exactly" + ); + assert_eq!( + env.spawn_count(), + 1, + "the call ran before its outcome had to be refused" + ); +} + +#[tokio::test] +async fn budget_long_stop_reason_failure_and_json_escaping_stay_bounded() { + let env = Env::new("budget-stop-escape"); + let failure = AcpDelegationResult { + harness_id: "fixture".to_string(), + status: AcpDelegationStatus::Failed, + text: String::new(), + stop_reason: Some(AcpStopReason::MaxTurnRequests), + truncated: false, + code: Some("acp_stop_reason"), + replayed: false, + }; + let budget = failure.serialized_envelope_bytes(); + let reply = "quote\" back\\slash tab\t é😀"; + let runtime = Runtime::open_with( + &env, + env.config_limited( + budget, + "fixture", + &["--reply", reply, "--stop-reason", "max_turn_requests"], + ), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let witness = runtime + .approve(&run, &call_scope, &request("fixture", "escape")) + .await; + let result = runtime + .policy + .delegate(&call_scope, &request("fixture", "escape"), &witness) + .await; + assert_eq!(result.status, AcpDelegationStatus::Failed, "{result:?}"); + assert_eq!(result.stop_reason, Some(AcpStopReason::MaxTurnRequests)); + assert_eq!(result.code, Some("acp_stop_reason")); + assert!( + result.serialized_envelope_bytes() <= budget, + "the escaped envelope never exceeds the public budget" + ); +} + +#[tokio::test] +async fn replayed_result_obeys_the_same_public_budget() { + let env = Env::new("budget-replay"); + let _minimal = AcpDelegationResult { + harness_id: "fixture".to_string(), + status: AcpDelegationStatus::Completed, + text: String::new(), + stop_reason: Some(AcpStopReason::EndTurn), + truncated: false, + code: None, + replayed: false, + } + .serialized_envelope_bytes(); + let budget = minimum_deliverable_bytes("fixture") + 4; + let runtime = Runtime::open_with( + &env, + env.config_limited(budget, "fixture", &["--reply", "0123456789abcdef"]), + "user", + ); + let run = runtime.open_run(None).await; + let call_scope = scope(&run, "call-1"); + let request = request("fixture", "replay"); + let witness = runtime.approve(&run, &call_scope, &request).await; + let first = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed, "{first:?}"); + assert!(first.truncated); + assert!(first.serialized_envelope_bytes() <= budget); + let replay = runtime + .policy + .delegate(&call_scope, &request, &witness) + .await; + assert!(replay.replayed); + assert_eq!(replay.status, AcpDelegationStatus::Completed); + assert!( + replay.serialized_envelope_bytes() <= budget, + "a durable replay is measured at the same public boundary" + ); + assert_eq!(env.spawn_count(), 1); +} diff --git a/tests/config_file_tests.rs b/tests/config_file_tests.rs index 85c31ba3..6b1c31a1 100644 --- a/tests/config_file_tests.rs +++ b/tests/config_file_tests.rs @@ -801,3 +801,105 @@ fn invalid_home_inputs_fail_closed() { environment.set("RUSTSCRIPT_AGENT_HOME", ""); assert!(AgentPaths::resolve().is_err()); } + +const ACP_HARNESS_SENTINEL: &str = "--policy-argv-sentinel"; + +fn config_with_harnesses(entries: &str) -> String { + format!( + "{}acp_harnesses:\n{entries}", + valid_config("synthetic-credential") + ) +} + +#[test] +fn acp_harness_table_loads_through_the_existing_entry_and_stays_host_private() { + let config = ConfigFile::from_str(&config_with_harnesses(&format!( + " - id: opencode\n command: /opt/bin/opencode\n args: [acp, {ACP_HARNESS_SENTINEL}]\n" + ))) + .expect("configured harness table parses"); + let harness = config + .acp_harness("opencode") + .expect("configured harness resolves"); + assert_eq!(harness.command, PathBuf::from("/opt/bin/opencode")); + assert_eq!( + harness.args, + vec!["acp".to_string(), ACP_HARNESS_SENTINEL.to_string()] + ); + assert!(config.acp_harness("missing").is_none()); + + // The public config snapshot must keep every existing field and never + // project the launch definition or its argv. + let public = serde_json::to_value(&config).expect("public projection"); + assert!(public.get("acp_harnesses").is_none()); + assert!(!public.to_string().contains(ACP_HARNESS_SENTINEL)); + assert!(!public.to_string().contains("/opt/bin/opencode")); + assert_eq!(public["model"]["provider"], "openai-codex"); + assert!(public["workspaces"]["allowed_roots"].is_array()); + + // Defaults keep the capability off. + assert!( + ConfigFile::from_str("version: 1\n") + .expect("default config") + .acp_harnesses + .is_empty() + ); +} + +#[test] +fn acp_harness_table_rejects_entries_that_cannot_launch_as_an_exact_argv() { + let cases = [ + ( + " - id: dup\n command: /bin/a\n - id: dup\n command: /bin/b\n", + "acp_harnesses[1].id", + ), + ( + " - id: rel\n command: bin/a\n", + "acp_harnesses[0].command", + ), + ( + " - id: bad id\n command: /bin/a\n", + "acp_harnesses[0].id", + ), + ( + " - id: ok\n command: /bin/a\n env: {A: B}\n", + "acp_harnesses[0].env", + ), + ]; + for (entries, field) in cases { + let error = ConfigFile::from_str(&config_with_harnesses(entries)) + .expect_err("invalid harness table must be refused"); + match error { + ConfigFileError::InvalidValue { field: actual, .. } => { + assert_eq!(actual, field) + } + ConfigFileError::UnknownKey { path, .. } => assert_eq!(path, field), + other => panic!("unexpected error for {field}: {other:?}"), + } + } + + // Nine entries exceed the table bound. + let mut many = String::new(); + for index in 0..9 { + many.push_str(&format!(" - id: h{index}\n command: /bin/h\n")); + } + assert!(ConfigFile::from_str(&config_with_harnesses(&many)).is_err()); + + // Thirty-three arguments exceed the per-harness bound. + let args = (0..33).map(|index| format!("a{index}")).collect::>(); + let too_many = format!( + " - id: many\n command: /bin/a\n args: [{}]\n", + args.join(", ") + ); + assert!(ConfigFile::from_str(&config_with_harnesses(&too_many)).is_err()); + + // An argument vector above 8 KiB is refused. + let huge = "x".repeat(8 * 1024 + 1); + let oversized = format!(" - id: huge\n command: /bin/a\n args: ['{huge}']\n"); + assert!(ConfigFile::from_str(&config_with_harnesses(&oversized)).is_err()); + + // A non-sequence argument list is a shape error. + let shape = ConfigFile::from_str(&config_with_harnesses( + " - id: bad\n command: /bin/a\n args: nope\n", + )); + assert!(shape.is_err()); +} diff --git a/tests/fixtures/acp/build.rs b/tests/fixtures/acp/build.rs index 56e78e58..fd4f1a9d 100644 --- a/tests/fixtures/acp/build.rs +++ b/tests/fixtures/acp/build.rs @@ -1,35 +1,6 @@ -use std::{fs, path::Path, process::Command}; +include!("compile.rs"); /// Compile the same fake peer for the packaged ACP transport and MCP tests. pub fn compile_fake_agent(binary: &Path) { - let current = std::env::current_exe().expect("resolve current test executable"); - let deps = current.parent().expect("cargo deps directory"); - let serde_json = fs::read_dir(deps) - .expect("read cargo deps directory") - .filter_map(Result::ok) - .map(|entry| entry.path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("libserde_json-") && name.ends_with(".rlib")) - }) - .min() - .expect("cargo built a serde_json rlib for this test profile"); - let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); - let output = Command::new(rustc) - .arg("--edition=2021") - .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/acp/fake_agent.rs")) - .arg("--extern") - .arg(format!("serde_json={}", serde_json.display())) - .arg("-L") - .arg(format!("dependency={}", deps.display())) - .arg("-o") - .arg(binary) - .output() - .expect("run rustc for the ACP fixture harness"); - assert!( - output.status.success(), - "fixture harness did not compile: {}", - String::from_utf8_lossy(&output.stderr) - ); + compile_fixture("fake_agent.rs", "2021", binary); } diff --git a/tests/fixtures/acp/compile.rs b/tests/fixtures/acp/compile.rs new file mode 100644 index 00000000..a0e6675d --- /dev/null +++ b/tests/fixtures/acp/compile.rs @@ -0,0 +1,38 @@ +use std::{fs, path::Path, process::Command}; + +fn compile_fixture(source: &str, edition: &str, binary: &Path) { + let current = std::env::current_exe().expect("resolve current test executable"); + let deps = current.parent().expect("cargo deps directory"); + let serde_json = fs::read_dir(deps) + .expect("read cargo deps directory") + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("libserde_json-") && name.ends_with(".rlib")) + }) + .min() + .expect("cargo built a serde_json rlib for this test profile"); + let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let output = Command::new(rustc) + .arg(format!("--edition={edition}")) + .arg( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/acp") + .join(source), + ) + .arg("--extern") + .arg(format!("serde_json={}", serde_json.display())) + .arg("-L") + .arg(format!("dependency={}", deps.display())) + .arg("-o") + .arg(binary) + .output() + .expect("run rustc for the ACP fixture harness"); + assert!( + output.status.success(), + "fixture harness did not compile: {}", + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/tests/fixtures/acp/delegation_agent.rs b/tests/fixtures/acp/delegation_agent.rs new file mode 100644 index 00000000..d9a150ad --- /dev/null +++ b/tests/fixtures/acp/delegation_agent.rs @@ -0,0 +1,765 @@ +//! Deterministic ACP v1 harness for delegated-client tests. +//! +//! Compiled by `tests/acp_delegation_client_tests.rs` with `rustc`. It speaks +//! newline-delimited JSON-RPC over stdio and records every request in a JSONL +//! event log. Configuration is argv-only; no environment variable is needed. +//! +//! Modes: +//! - `normal`: both `resume` and `load` are advertised. +//! - `load_only`: only `loadSession` is advertised. +//! - `resume_only`: only `sessionCapabilities.resume` is advertised. +//! - `no_restore`: neither restore method is advertised. +//! - `reject_restore`: advertise restore but reject the restore request. +//! - `permission`: ask for permission before answering the prompt. +//! - `unsupported`: call `fs/read_text_file` before answering the prompt. +//! - `flood`: stream a configured number of updates before answering. +//! - `stubborn`: hold the prompt and ignore cancellation and stdin EOF. +//! - `crash`: exit while the prompt is pending. +//! - `late`: send an update after the prompt response. +//! - `decoy`: send a mismatched response and updates before the real response. +//! - `bad-update`: send wrong-session and schema-invalid updates first. +//! - `terminal`: request a terminal callback before answering. +//! - `permission-flood`: send many permission requests before answering. +//! - `exit-after-prompt`: answer once and exit, so the leader dies first. +//! - `group-helper`: keep a signal-ignoring helper in the same process group. +//! - `hang-setup`: record `session/new` and never answer it. +//! - `reject-first-new`: answer the first `session/new` with a protocol error +//! after the `--fence` file appears, then behave normally. +//! +//! Sessions are remembered in `--store` so a fresh child process can restore +//! an ID created by an earlier child. + +use std::collections::HashMap; +use std::env; +use std::fs::{File, OpenOptions}; +use std::io::{self, BufRead, Write}; +use std::path::PathBuf; + +use serde_json::{Value, json}; + +#[derive(Clone)] +struct Config { + events: Option, + mode: String, + store: Option, + reply: String, + replay: String, + stop_reason: String, + descendant: bool, + permission: bool, + unsupported: bool, + flood: usize, + flood_bytes: usize, + stubborn: bool, + late: Option, + crash: bool, + reject_restore: bool, + big_frame: bool, + utf8_cut: bool, + sentinel: Option, + protocol_version: u64, + decoy: bool, + bad_update: bool, + terminal: bool, + permission_flood: usize, + exit_after_prompt: bool, + group_helper_seconds: Option, + helper_marker: Option, + hang_setup: bool, + reject_first_new: bool, + fence: Option, +} + +impl Default for Config { + fn default() -> Self { + Self { + events: None, + mode: "normal".to_owned(), + store: None, + reply: "delegated-reply".to_owned(), + replay: "REPLAY-SHOULD-NOT-APPEAR".to_owned(), + stop_reason: "end_turn".to_owned(), + descendant: false, + permission: false, + unsupported: false, + flood: 0, + flood_bytes: 0, + stubborn: false, + late: None, + crash: false, + reject_restore: false, + big_frame: false, + utf8_cut: false, + sentinel: None, + protocol_version: 1, + decoy: false, + bad_update: false, + terminal: false, + permission_flood: 0, + exit_after_prompt: false, + group_helper_seconds: None, + helper_marker: None, + hang_setup: false, + reject_first_new: false, + fence: None, + } + } +} + +struct Pending { + session_id: String, + prompt_id: Value, +} + +struct Harness { + config: Config, + events: Option, + out: io::Stdout, + sessions: HashMap, + flood: Option<(Value, String)>, + flood_remaining: usize, + next_session: u64, + next_request: u64, + new_requests: u64, +} + +impl Harness { + fn record(&mut self, event: &str, data: Value) { + if let Some(file) = self.events.as_mut() { + let _ = writeln!(file, "{}", json!({ "event": event, "data": data })); + let _ = file.flush(); + } + } + + fn send(&mut self, message: Value) { + let line = serde_json::to_string(&message).expect("fixture message serializes"); + let _ = self + .out + .write_all(format!("{line}\n").as_bytes()) + .and_then(|()| self.out.flush()); + } + + fn respond(&mut self, id: &Value, result: Value) { + self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result })); + } + + fn respond_error(&mut self, id: &Value, code: i64, message: &str) { + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "error": { "code": code, "message": message } + })); + } + + fn update(&mut self, session_id: &str, update: Value) { + self.send(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { "sessionId": session_id, "update": update } + })); + } + + fn agent_text(&mut self, session_id: &str, text: &str) { + self.update( + session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": text } + }), + ); + } + + fn initialize(&mut self, id: &Value, params: &Value) { + self.record("initialize", params.clone()); + if self.config.big_frame { + let padding = "x".repeat(1024 * 1024 + 256); + let _ = self.out.write_all(padding.as_bytes()); + let _ = self.out.write_all(b"\n"); + let _ = self.out.flush(); + return; + } + let (load, resume) = match self.config.mode.as_str() { + "load_only" => (true, None), + "resume_only" => (false, Some(json!({}))), + "no_restore" => (false, None), + _ => (true, Some(json!({}))), + }; + let session_capabilities = match resume { + Some(resume) => json!({ "resume": resume }), + None => json!({}), + }; + self.respond( + id, + json!({ + "protocolVersion": self.config.protocol_version, + "agentCapabilities": { + "loadSession": load, + "sessionCapabilities": session_capabilities, + "promptCapabilities": { + "image": false, + "audio": false, + "embeddedContext": false + } + }, + "agentInfo": { + "name": "delegation-fixture", + "title": "Delegation Fixture", + "version": "0.1.0" + } + }), + ); + } + + fn remember(&mut self, session_id: &str) { + if let Some(path) = self.config.store.as_ref() + && let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) + { + let _ = writeln!(file, "{session_id}"); + } + } + + fn known(&self, session_id: &str) -> bool { + self.config.store.as_ref().is_none_or(|path| { + std::fs::read_to_string(path).is_ok_and(|contents| { + contents.lines().any(|line| line.trim() == session_id) + }) + }) + } + + fn new_session(&mut self, id: &Value, params: &Value) { + self.new_requests += 1; + if self.config.hang_setup { + // Observation fence for the client-side shutdown test: the request + // is on the wire and will never be answered. + self.record( + "session/new", + json!({ "params": params, "attempt": self.new_requests }), + ); + return; + } + if self.config.reject_first_new && self.new_requests == 1 { + self.record( + "session/new", + json!({ "params": params, "attempt": self.new_requests }), + ); + // Wait for the test's fence file so the caller can abandon its wait + // before this protocol error is produced. + if let Some(fence) = self.config.fence.clone() { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while !fence.exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + self.respond_error(id, -32000, "first session/new rejected"); + return; + } + self.next_session += 1; + let session_id = format!("fixture-session-{}-{}", std::process::id(), self.next_session); + self.remember(&session_id); + self.record( + "session/new", + json!({ "params": params, "sessionId": session_id }), + ); + self.respond(id, json!({ "sessionId": session_id })); + } + + fn restore(&mut self, method: &str, id: &Value, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + self.record( + method, + json!({ "params": params, "sessionId": session_id }), + ); + let allowed = match (self.config.mode.as_str(), method) { + ("no_restore", _) => false, + ("load_only", "session/resume") => false, + ("resume_only", "session/load") => false, + _ => true, + }; + if self.config.reject_restore + || self.config.mode == "reject_restore" + || !allowed + || !self.known(&session_id) + { + self.respond_error(id, -32000, "restore rejected"); + return; + } + if method == "session/load" && !self.config.replay.is_empty() { + // Replay must be written before the load response. The client's + // phase boundary drops it from the next prompt result. + let replay = format!("REPLAY:{}:END", self.config.replay); + self.agent_text(&session_id, &replay); + } + self.respond(id, json!({})); + self.record("setup_responded", json!({ "method": method })); + } + + fn prompt(&mut self, id: &Value, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + self.record("session/prompt", params.clone()); + if self.config.crash { + std::process::exit(3); + } + if self.config.permission_flood > 0 { + self.flood = Some((id.clone(), session_id.clone())); + self.flood_remaining = self.config.permission_flood; + for index in 0..self.config.permission_flood { + let request_id = json!(format!("fixture-permission-flood-{index}")); + self.record( + "permission_request", + json!({ "id": request_id, "sessionId": session_id }), + ); + self.send(json!({ + "jsonrpc": "2.0", + "id": request_id, + "method": "session/request_permission", + "params": { + "sessionId": session_id, + "toolCall": { + "toolCallId": format!("fixture-flood-call-{index}"), + "title": "Fixture flood read", + "kind": "read", + "status": "pending" + }, + "options": [ + { "optionId": "allow", "name": "Allow", "kind": "allow_once" }, + { "optionId": "deny", "name": "Deny", "kind": "reject_once" } + ] + } + })); + } + return; + } + if self.config.terminal { + self.next_request += 1; + let request_id = json!(format!("fixture-terminal-{}", self.next_request)); + self.record( + "terminal_request", + json!({ "id": request_id, "sessionId": session_id }), + ); + self.sessions.insert( + request_id.to_string(), + Pending { + session_id, + prompt_id: id.clone(), + }, + ); + self.send(json!({ + "jsonrpc": "2.0", + "id": request_id, + "method": "terminal/create", + "params": { + "sessionId": params.get("sessionId").cloned().unwrap_or(Value::Null), + "command": "sh", + "args": ["-c", "echo opened > \"$1\"", "sh", self.config.sentinel] + } + })); + return; + } + if self.config.bad_update { + // A well-formed update for a session this client does not own. + self.update( + "fixture-session-other", + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "WRONG-SESSION" } + }), + ); + // Unknown update kind: typed SessionNotification parsing must fail. + self.send(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": session_id, + "update": { "sessionUpdate": "bogus_update" } + } + })); + // Known kind with a content block missing its required field. + self.send(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": session_id, + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text" } + } + } + })); + self.agent_text(&session_id, "VALID-"); + } + if self.config.decoy { + // A response-shaped frame whose id is the prompt id encoded as a + // JSON string. It must not close the prompt text phase. + let decoy_id = match id { + Value::Number(number) => json!(number.to_string()), + Value::String(text) => json!(format!("{text}-decoy")), + _ => json!("decoy"), + }; + self.record("decoy_response", json!({ "id": decoy_id })); + self.respond(&decoy_id, json!({ "stopReason": "end_turn" })); + self.agent_text(&session_id, "P-"); + // An unrelated response id must be dropped as well. + self.respond( + &json!("unrelated-response"), + json!({ "stopReason": "end_turn" }), + ); + self.agent_text(&session_id, "S-"); + } + if self.config.flood > 0 { + for index in 0..self.config.flood { + let prefix = format!("flood-{index:03}-"); + let size = self.config.flood_bytes.saturating_sub(prefix.len()); + self.agent_text(&session_id, &format!("{prefix}{}", "x".repeat(size))); + } + self.respond(id, json!({ "stopReason": "end_turn" })); + return; + } + if self.config.unsupported { + self.next_request += 1; + let request_id = json!(format!("fixture-fs-{}", self.next_request)); + self.record( + "unsupported_request", + json!({ "id": request_id, "path": self.config.sentinel }), + ); + self.sessions.insert( + request_id.to_string(), + Pending { + session_id, + prompt_id: id.clone(), + }, + ); + self.send(json!({ + "jsonrpc": "2.0", + "id": request_id, + "method": "fs/read_text_file", + "params": { + "sessionId": params.get("sessionId").cloned().unwrap_or(Value::Null), + "path": self.config.sentinel + } + })); + return; + } + if self.config.permission { + self.next_request += 1; + let request_id = json!(format!("fixture-permission-{}", self.next_request)); + self.record( + "permission_request", + json!({ "id": request_id, "sessionId": session_id }), + ); + self.agent_text(&session_id, "working"); + self.sessions.insert( + request_id.to_string(), + Pending { + session_id, + prompt_id: id.clone(), + }, + ); + self.send(json!({ + "jsonrpc": "2.0", + "id": request_id, + "method": "session/request_permission", + "params": { + "sessionId": params.get("sessionId").cloned().unwrap_or(Value::Null), + "toolCall": { + "toolCallId": "fixture-call-1", + "title": "Fixture read", + "kind": "read", + "status": "pending" + }, + "options": [ + { "optionId": "allow", "name": "Allow", "kind": "allow_once" }, + { "optionId": "deny", "name": "Deny", "kind": "reject_once" } + ] + } + })); + return; + } + if self.config.stubborn { + self.agent_text(&session_id, "working"); + self.sessions.insert( + format!("prompt:{id}"), + Pending { + session_id, + prompt_id: id.clone(), + }, + ); + return; + } + self.finish_prompt(id, &session_id); + if self.config.exit_after_prompt { + std::process::exit(0); + } + } + + fn finish_prompt(&mut self, id: &Value, session_id: &str) { + self.update( + session_id, + json!({ + "sessionUpdate": "agent_thought_chunk", + "content": { "type": "text", "text": "THOUGHT-SHOULD-NOT-APPEAR" } + }), + ); + self.update( + session_id, + json!({ + "sessionUpdate": "tool_call", + "toolCallId": "fixture-call-1", + "title": "Fixture read", + "kind": "read", + "status": "pending" + }), + ); + if self.config.utf8_cut { + let mut text = "a".repeat(32_766); + text.push('€'); + self.agent_text(session_id, &text); + } else { + let reply = self.config.reply.clone(); + self.agent_text(session_id, &reply); + } + self.respond(id, json!({ "stopReason": self.config.stop_reason })); + if let Some(late) = self.config.late.clone() { + self.agent_text(session_id, &late); + } + } + + fn cancel(&mut self, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + self.record("session/cancel", params.clone()); + if self.config.stubborn { + return; + } + let key = self + .sessions + .iter() + .find(|(_, pending)| pending.session_id == session_id) + .map(|(key, _)| key.clone()); + if let Some(key) = key { + if let Some(pending) = self.sessions.remove(&key) { + self.respond(&pending.prompt_id, json!({ "stopReason": "cancelled" })); + } + } + } + + fn response(&mut self, id: &Value, message: &Value) { + if id + .as_str() + .is_some_and(|id| id.starts_with("fixture-permission-flood-")) + { + self.record( + "permission_response", + json!({ "result": message.get("result"), "error": message.get("error") }), + ); + self.flood_remaining = self.flood_remaining.saturating_sub(1); + if self.flood_remaining == 0 + && let Some((prompt_id, session_id)) = self.flood.take() + { + self.finish_prompt(&prompt_id, &session_id); + } + return; + } + let Some(pending) = self.sessions.remove(&id.to_string()) else { + self.record("unmatched_response", message.clone()); + return; + }; + if id + .as_str() + .is_some_and(|id| id.starts_with("fixture-terminal-")) + { + self.record( + "terminal_response", + json!({ "result": message.get("result"), "error": message.get("error") }), + ); + } else if id.as_str().is_some_and(|id| id.starts_with("fixture-permission-")) { + self.record( + "permission_response", + json!({ "result": message.get("result"), "error": message.get("error") }), + ); + } else { + self.record( + "unsupported_response", + json!({ "result": message.get("result"), "error": message.get("error") }), + ); + } + self.finish_prompt(&pending.prompt_id, &pending.session_id); + } +} + +fn parse_args() -> Config { + let mut config = Config::default(); + let mut args = env::args().skip(1); + while let Some(argument) = args.next() { + let mut value = |name: &str| { + args.next() + .unwrap_or_else(|| panic!("missing value for {name}")) + }; + match argument.as_str() { + "--events" => config.events = Some(PathBuf::from(value("--events"))), + "--mode" => config.mode = value("--mode"), + "--store" => config.store = Some(PathBuf::from(value("--store"))), + "--reply" => config.reply = value("--reply"), + "--replay" => config.replay = value("--replay"), + "--stop-reason" => config.stop_reason = value("--stop-reason"), + "--late" => config.late = Some(value("--late")), + "--flood" => config.flood = value("--flood").parse().expect("flood count"), + "--flood-bytes" => { + config.flood_bytes = value("--flood-bytes").parse().expect("flood bytes") + } + "--sentinel" => config.sentinel = Some(PathBuf::from(value("--sentinel"))), + "--descendant" => config.descendant = true, + "--permission" => config.permission = true, + "--unsupported" => config.unsupported = true, + "--stubborn" => config.stubborn = true, + "--crash" => config.crash = true, + "--reject-restore" => config.reject_restore = true, + "--big-frame" => config.big_frame = true, + "--utf8-cut" => config.utf8_cut = true, + "--protocol-version" => { + config.protocol_version = value("--protocol-version") + .parse() + .expect("protocol version") + } + "--decoy" => config.decoy = true, + "--bad-update" => config.bad_update = true, + "--terminal" => config.terminal = true, + "--permission-flood" => { + config.permission_flood = value("--permission-flood") + .parse() + .expect("permission flood count") + } + "--exit-after-prompt" => config.exit_after_prompt = true, + "--group-helper" => config.group_helper_seconds = Some(value("--group-helper")), + "--helper-marker" => config.helper_marker = Some(PathBuf::from(value("--helper-marker"))), + "--hang-setup" => config.hang_setup = true, + "--reject-first-new" => config.reject_first_new = true, + "--fence" => config.fence = Some(PathBuf::from(value("--fence"))), + other => panic!("unsupported fixture argument: {other}"), + } + } + config +} + +fn main() { + let config = parse_args(); + let events = config + .events + .as_ref() + .and_then(|path| OpenOptions::new().create(true).append(true).open(path).ok()); + let mut harness = Harness { + config, + events, + out: io::stdout(), + sessions: HashMap::new(), + flood: None, + flood_remaining: 0, + next_session: 0, + next_request: 0, + new_requests: 0, + }; + harness.record( + "start", + json!({ "pid": std::process::id(), "args": env::args().skip(1).collect::>() }), + ); + if harness.config.descendant { + match std::process::Command::new("sleep").arg("120").spawn() { + Ok(child) => harness.record("descendant", json!({ "pid": child.id() })), + Err(error) => harness.record("descendant_error", json!(error.to_string())), + } + } + if let Some(seconds) = harness.config.group_helper_seconds.clone() { + // Stays in the harness process group, ignores SIGTERM, optionally + // writes a marker after its own delay and then exits. + let mut helper = std::process::Command::new("sh"); + helper + .arg("-c") + .arg("trap '' TERM; sleep \"$1\"; if [ -n \"$2\" ]; then : > \"$2\"; fi") + .arg("sh") + .arg(&seconds) + .arg( + harness + .config + .helper_marker + .as_ref() + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_default(), + ); + match helper.spawn() { + Ok(child) => harness.record("group_helper", json!({ "pid": child.id() })), + Err(error) => harness.record("group_helper_error", json!(error.to_string())), + } + } + + let stdin = io::stdin(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let message: Value = match serde_json::from_str(&line) { + Ok(message) => message, + Err(error) => { + harness.record("parse_error", json!(error.to_string())); + continue; + } + }; + let method = message.get("method").and_then(Value::as_str); + let id = message.get("id"); + match method { + Some("initialize") => { + if let Some(id) = id { + harness.initialize(id, message.get("params").unwrap_or(&Value::Null)); + } + } + Some("session/new") => { + if let Some(id) = id { + harness.new_session(id, message.get("params").unwrap_or(&Value::Null)); + } + } + Some(method @ ("session/load" | "session/resume")) => { + if let Some(id) = id { + harness.restore(method, id, message.get("params").unwrap_or(&Value::Null)); + } + } + Some("session/prompt") => { + if let Some(id) = id { + harness.prompt(id, message.get("params").unwrap_or(&Value::Null)); + } + } + Some("session/cancel") => { + harness.cancel(message.get("params").unwrap_or(&Value::Null)); + } + Some(method) => { + harness.record( + "unsupported_request", + json!({ "method": method, "id": id, "params": message.get("params") }), + ); + if let Some(id) = id { + harness.respond_error(id, -32601, "method not found"); + } + } + None => { + if let Some(id) = id { + harness.response(id, &message); + } + } + } + } + harness.record("stdin_eof", json!({})); + if harness.config.stubborn { + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } +} diff --git a/tests/fixtures/acp/delegation_build.rs b/tests/fixtures/acp/delegation_build.rs new file mode 100644 index 00000000..e45d0e4e --- /dev/null +++ b/tests/fixtures/acp/delegation_build.rs @@ -0,0 +1,6 @@ +include!("compile.rs"); + +/// Compile the harness used by the delegated ACP client tests. +pub fn compile_delegation_agent(binary: &Path) { + compile_fixture("delegation_agent.rs", "2024", binary); +} diff --git a/tests/fixtures/acp_policy/build.rs b/tests/fixtures/acp_policy/build.rs new file mode 100644 index 00000000..a274cdb8 --- /dev/null +++ b/tests/fixtures/acp_policy/build.rs @@ -0,0 +1,40 @@ +use std::{fs, path::Path, process::Command}; + +/// Compiles the policy fixture harness with the `serde_json` rlib already built +/// for this test profile. The fixture is independent of the task-1 ACP +/// fixtures, so policy tests never touch their source. +#[allow(dead_code)] +pub fn compile_policy_agent(binary: &Path) { + let current = std::env::current_exe().expect("resolve current test executable"); + let deps = current.parent().expect("cargo deps directory"); + let serde_json = fs::read_dir(deps) + .expect("read cargo deps directory") + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("libserde_json-") && name.ends_with(".rlib")) + }) + .min() + .expect("cargo built a serde_json rlib for this test profile"); + let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let output = Command::new(rustc) + .arg("--edition=2024") + .arg( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/acp_policy/policy_agent.rs"), + ) + .arg("--extern") + .arg(format!("serde_json={}", serde_json.display())) + .arg("-L") + .arg(format!("dependency={}", deps.display())) + .arg("-o") + .arg(binary) + .output() + .expect("run rustc for the policy fixture harness"); + assert!( + output.status.success(), + "policy fixture did not compile: {}", + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/tests/fixtures/acp_policy/policy_agent.rs b/tests/fixtures/acp_policy/policy_agent.rs new file mode 100644 index 00000000..3086c6c0 --- /dev/null +++ b/tests/fixtures/acp_policy/policy_agent.rs @@ -0,0 +1,418 @@ +//! Deterministic ACP v1 harness for the delegation policy tests. +//! +//! Independent of the task-1 fixture: it keeps a per-session prompt history so +//! a restored connection can prove it sees the earlier context, and it appends +//! one line to `--spawn-log` at process start. The spawn log is the only +//! process-count evidence the policy tests use. +//! +//! Capabilities are read from `--caps` on every `initialize`, so a test can +//! change them without changing the configured argv (which is part of the +//! durable binding identity): +//! +//! - `resume+load` (default): both restore methods are advertised; +//! - `load`: only `loadSession` is advertised; +//! - `none`: no restore method is advertised. + +use std::collections::HashMap; +use std::fs::OpenOptions; +use std::io::{self, BufRead, Write}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::{Value, json}; + +#[derive(Clone, Default)] +struct Config { + spawn_log: Option, + events: Option, + store: Option, + caps: Option, + reply: String, + replay: String, + stop_reason: String, + delay_ms: u64, + init_delay_ms: u64, + restore_delay_ms: u64, + hold: bool, + hold_task: Option, +} + +struct Harness { + config: Config, + out: Arc>, + pending: Arc>>, + next_session: AtomicU64, +} + +impl Harness { + fn record(&self, event: &str, data: Value) { + if let Some(path) = self.config.events.as_ref() + && let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) + { + let _ = writeln!(file, "{}", json!({ "event": event, "data": data })); + } + } + + fn send(&self, message: Value) { + let line = serde_json::to_string(&message).expect("fixture message"); + let mut out = self.out.lock().expect("fixture stdout"); + let _ = out.write_all(format!("{line}\n").as_bytes()); + let _ = out.flush(); + } + + fn respond(&self, id: &Value, result: Value) { + self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result })); + } + + fn respond_error(&self, id: &Value, message: &str) { + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "error": { "code": -32000, "message": message } + })); + } + + fn update(&self, session_id: &str, update: Value) { + self.send(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { "sessionId": session_id, "update": update } + })); + } + + fn agent_text(&self, session_id: &str, text: &str) { + self.update( + session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": text } + }), + ); + } + + fn capabilities(&self) -> (bool, Option) { + let mode = self + .config + .caps + .as_ref() + .and_then(|path| std::fs::read_to_string(path).ok()) + .map(|text| text.trim().to_string()) + .unwrap_or_else(|| "resume+load".to_string()); + match mode.as_str() { + "load" => (true, None), + "none" => (false, None), + _ => (true, Some(json!({}))), + } + } + + fn initialize(&self, id: &Value, params: &Value) { + self.record("initialize", params.clone()); + if self.config.init_delay_ms > 0 { + std::thread::sleep(Duration::from_millis(self.config.init_delay_ms)); + } + let (load, resume) = self.capabilities(); + let session_capabilities = match resume { + Some(resume) => json!({ "resume": resume }), + None => json!({}), + }; + self.respond( + id, + json!({ + "protocolVersion": 1, + "agentCapabilities": { + "loadSession": load, + "sessionCapabilities": session_capabilities, + "promptCapabilities": { + "image": false, + "audio": false, + "embeddedContext": false + } + }, + "agentInfo": { "name": "policy-fixture", "version": "0.1.0" } + }), + ); + } + + fn history_len(&self, session_id: &str) -> usize { + self.config + .store + .as_ref() + .and_then(|path| std::fs::read_to_string(path).ok()) + .map(|contents| { + contents + .lines() + .filter(|line| { + let mut fields = line.split('\t'); + fields.next() == Some(session_id) + && fields.next().is_some_and(|task| task != "") + }) + .count() + }) + .unwrap_or(0) + } + + fn remember(&self, session_id: &str, task: &str) { + if let Some(path) = self.config.store.as_ref() + && let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) + { + let _ = writeln!(file, "{session_id}\t{task}"); + } + } + + fn known(&self, session_id: &str) -> bool { + self.config + .store + .as_ref() + .and_then(|path| std::fs::read_to_string(path).ok()) + .is_some_and(|contents| { + contents + .lines() + .any(|line| line.split('\t').next() == Some(session_id)) + }) + } + + fn new_session(&self, id: &Value, params: &Value) { + let ordinal = self.next_session.fetch_add(1, Ordering::Relaxed) + 1; + let session_id = format!("policy-session-{}-{ordinal}", std::process::id()); + self.record("session/new", json!({ "params": params, "sessionId": session_id })); + // A created session exists even before its first prompt. + if let Some(path) = self.config.store.as_ref() + && let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) + { + let _ = writeln!(file, "{session_id}\t"); + } + self.respond(id, json!({ "sessionId": session_id })); + } + + fn restore(&self, method: &str, id: &Value, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + self.record(method, json!({ "params": params })); + if self.config.restore_delay_ms > 0 { + std::thread::sleep(Duration::from_millis(self.config.restore_delay_ms)); + } + let (load, resume) = self.capabilities(); + let allowed = match method { + "session/load" => load, + "session/resume" => resume.is_some(), + _ => false, + }; + if !allowed || !self.known(&session_id) { + self.respond_error(id, "restore rejected"); + return; + } + if method == "session/load" && !self.config.replay.is_empty() { + // Replay arrives before the load response and must never be part of + // the next prompt's result. + self.agent_text(&session_id, &format!("REPLAY:{}:END", self.config.replay)); + } + self.respond(id, json!({})); + self.record("setup_responded", json!({ "method": method })); + } + + fn prompt(&self, id: &Value, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let task = params + .get("prompt") + .and_then(Value::as_array) + .and_then(|blocks| blocks.first()) + .and_then(|block| block.get("text")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + self.record("session/prompt", params.clone()); + let prior = self.history_len(&session_id); + self.remember(&session_id, &task); + if self.config.hold || self.config.hold_task.as_deref() == Some(task.as_str()) { + self.pending + .lock() + .expect("fixture pending") + .insert(session_id, id.clone()); + return; + } + let harness = FixtureHandle { + out: Arc::clone(&self.out), + pending: Arc::clone(&self.pending), + }; + let reply = format!("ctx={prior};reply={}", self.config.reply); + let stop_reason = self.config.stop_reason.clone(); + let delay = self.config.delay_ms; + let prompt_id = id.clone(); + std::thread::spawn(move || { + if delay > 0 { + std::thread::sleep(Duration::from_millis(delay)); + } + harness.agent_text(&session_id, &reply); + harness.respond_end_turn(&session_id, &prompt_id, &stop_reason); + }); + } + + fn cancel(&self, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + self.record("session/cancel", params.clone()); + let pending = self + .pending + .lock() + .expect("fixture pending") + .remove(&session_id); + if let Some(prompt_id) = pending { + self.respond(&prompt_id, json!({ "stopReason": "cancelled" })); + } + } +} + +struct FixtureHandle { + out: Arc>, + pending: Arc>>, +} + +impl FixtureHandle { + fn send(&self, message: Value) { + let line = serde_json::to_string(&message).expect("fixture message"); + let mut out = self.out.lock().expect("fixture stdout"); + let _ = out.write_all(format!("{line}\n").as_bytes()); + let _ = out.flush(); + } + + fn agent_text(&self, session_id: &str, text: &str) { + self.send(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": session_id, + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": text } + } + } + })); + } + + fn respond_end_turn(&self, session_id: &str, id: &Value, stop_reason: &str) { + self.pending + .lock() + .expect("fixture pending") + .remove(session_id); + self.send( + json!({ "jsonrpc": "2.0", "id": id, "result": { "stopReason": stop_reason } }), + ); + } +} + +fn argument(args: &[String], name: &str) -> Option { + args.iter() + .position(|arg| arg == name) + .and_then(|index| args.get(index + 1)) + .map(PathBuf::from) +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let config = Config { + spawn_log: argument(&args, "--spawn-log"), + events: argument(&args, "--events"), + store: argument(&args, "--store"), + caps: argument(&args, "--caps"), + reply: args + .iter() + .position(|arg| arg == "--reply") + .and_then(|index| args.get(index + 1)) + .cloned() + .unwrap_or_else(|| "policy-reply".to_string()), + replay: args + .iter() + .position(|arg| arg == "--replay") + .and_then(|index| args.get(index + 1)) + .cloned() + .unwrap_or_else(|| "REPLAY-SHOULD-NOT-APPEAR".to_string()), + stop_reason: args + .iter() + .position(|arg| arg == "--stop-reason") + .and_then(|index| args.get(index + 1)) + .cloned() + .unwrap_or_else(|| "end_turn".to_string()), + delay_ms: args + .iter() + .position(|arg| arg == "--delay-ms") + .and_then(|index| args.get(index + 1)) + .and_then(|value| value.parse::().ok()) + .unwrap_or(0), + init_delay_ms: args + .iter() + .position(|arg| arg == "--init-delay-ms") + .and_then(|index| args.get(index + 1)) + .and_then(|value| value.parse::().ok()) + .unwrap_or(0), + restore_delay_ms: args + .iter() + .position(|arg| arg == "--restore-delay-ms") + .and_then(|index| args.get(index + 1)) + .and_then(|value| value.parse::().ok()) + .unwrap_or(0), + hold: args.iter().any(|arg| arg == "--hold"), + hold_task: args.windows(2).find(|pair| pair[0] == "--hold-task").map(|pair| pair[1].clone()), + }; + if let Some(path) = config.spawn_log.as_ref() + && let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) + { + let _ = writeln!(file, "spawn"); + } + + let harness = Harness { + config, + out: Arc::new(Mutex::new(io::stdout())), + pending: Arc::new(Mutex::new(HashMap::new())), + next_session: AtomicU64::new(0), + }; + harness.record("process/spawn", json!({"pid": std::process::id()})); + let stdin = io::stdin(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + let Ok(message) = serde_json::from_str::(&line) else { + continue; + }; + match message.get("method").and_then(Value::as_str) { + Some("initialize") => harness.initialize( + message.get("id").unwrap_or(&Value::Null), + message.get("params").unwrap_or(&Value::Null), + ), + Some("session/new") => harness.new_session( + message.get("id").unwrap_or(&Value::Null), + message.get("params").unwrap_or(&Value::Null), + ), + Some(method @ ("session/load" | "session/resume")) => harness.restore( + method, + message.get("id").unwrap_or(&Value::Null), + message.get("params").unwrap_or(&Value::Null), + ), + Some("session/prompt") => harness.prompt( + message.get("id").unwrap_or(&Value::Null), + message.get("params").unwrap_or(&Value::Null), + ), + Some("session/cancel") => { + harness.cancel(message.get("params").unwrap_or(&Value::Null)) + } + _ => {} + } + } + harness.record("stdin/eof", json!({"pid": std::process::id()})); + if let Some(release) = argument(&args, "--eof-release") { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); + while !release.exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } +} diff --git a/tests/mcp_catalog_tests.rs b/tests/mcp_catalog_tests.rs index 255533aa..2e415c70 100644 --- a/tests/mcp_catalog_tests.rs +++ b/tests/mcp_catalog_tests.rs @@ -94,6 +94,23 @@ fn catalog_matches_the_registry_exactly_in_deterministic_order() { } } +#[test] +fn mixed_gateway_catalog_does_not_export_delegate_acp() { + let default = snapshot(); + let mut descriptors = default.descriptors().to_vec(); + descriptors.push(descriptor("delegate_acp", "execute", Toolset::PROCESS)); + let mixed = rustscript_agent::registry::ToolRegistry::from_descriptors(descriptors) + .expect("mixed registry") + .snapshot(); + assert!(mixed.descriptor("delegate_acp").is_some()); + for profile in [ToolProfile::Coding, ToolProfile::ReadOnly] { + assert_eq!( + serde_json::to_value(catalog_from_registry(&mixed, profile).unwrap()).unwrap(), + serde_json::to_value(catalog_from_registry(&default, profile).unwrap()).unwrap(), + ); + } +} + #[test] fn read_only_catalog_exports_only_the_two_read_tools() { let catalog = diff --git a/tests/provider_durable_replay_loop_tests.rs b/tests/provider_durable_replay_loop_tests.rs index 4d35883f..64522c00 100644 --- a/tests/provider_durable_replay_loop_tests.rs +++ b/tests/provider_durable_replay_loop_tests.rs @@ -12,7 +12,7 @@ use std::fs; use std::io::Write; use std::path::PathBuf; use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Barrier, Mutex}; +use std::sync::{Arc, Condvar, Mutex}; use std::time::Duration; use axum::{ @@ -11614,13 +11614,22 @@ fn auto_concurrent_http_approve_grants_once() { .telegram_picker_message_for_approval(&opened.approval_id) .is_some() ); - let entered = Arc::new(Barrier::new(2)); + let entered = Arc::new((Mutex::new(0), Condvar::new())); opened .persistence() .inject_approval_resolve_gate(&opened.run_id, &opened.approval_id, { let entered = Arc::clone(&entered); move || { - entered.wait(); + let (arrivals, changed) = &*entered; + let mut count = arrivals.lock().expect("approval arrivals"); + *count += 1; + changed.notify_all(); + let (count, _) = changed + .wait_timeout_while(count, Duration::from_secs(15), |count| *count < 2) + .expect("approval rendezvous"); + let observed = *count; + drop(count); + assert_eq!(observed, 2, "both approvals must reach the resolve gate"); } }); let app = build_agent_gateway_app(opened.state.clone()); diff --git a/tests/release_packaging_tests.rs b/tests/release_packaging_tests.rs index 91798ff2..0e83644e 100644 --- a/tests/release_packaging_tests.rs +++ b/tests/release_packaging_tests.rs @@ -321,7 +321,7 @@ fn expected_file_bytes(binary_dir: &Path) -> BTreeMap> { fn explicit_release_classification_is_complete_and_import_closed() { let rss_production = plain_inventory("rss-production.txt"); let rss_support = plain_inventory("rss-support.txt"); - assert_eq!(rss_production.len(), 82, "production RSS count changed"); + assert_eq!(rss_production.len(), 83, "production RSS count changed"); assert_eq!( rss_support, BTreeSet::from([