From e3d083936f2929d86b43f3215ae37bb00b021b89 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 05:38:47 +0800 Subject: [PATCH 01/27] feat(acp): add supervised delegated session client Expose explicit initialize, session setup, prompt and close phases over a bounded ACP v1 stdio child. The caller receives the peer session id before any prompt is sent, so the durable scope can persist the binding and send intent first. Prefer session/resume when advertised, use session/load only when solely advertised, and reject restore failures without creating a new session. Discard load replay at the serialized ingress boundary, cancel permission requests, and keep prompt text bounded to 32 KiB. The owned supervisor enforces the 1 MiB frame limit, 64-notification and 4 MiB notification budgets, absolute deadlines, and process-group cleanup on explicit close or drop. --- src/acp/delegated_client.rs | 1150 ++++++++++++++++++++++++ src/acp/mod.rs | 9 + tests/acp_delegation_client_tests.rs | 675 ++++++++++++++ tests/fixtures/acp/build.rs | 18 +- tests/fixtures/acp/delegation_agent.rs | 528 +++++++++++ 5 files changed, 2378 insertions(+), 2 deletions(-) create mode 100644 src/acp/delegated_client.rs create mode 100644 tests/acp_delegation_client_tests.rs create mode 100644 tests/fixtures/acp/delegation_agent.rs diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs new file mode 100644 index 0000000..0f32568 --- /dev/null +++ b/src/acp/delegated_client.rs @@ -0,0 +1,1150 @@ +//! 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 and is reaped on explicit close, +//! on drop, or by the owned supervisor after cancellation; +//! - each inbound line is limited to 1 MiB; a turn is cut off after 64 +//! notifications or 4 MiB, whichever comes first; +//! - only typed `agent_message_chunk` text is captured, capped at 32 KiB on a +//! UTF-8 boundary with an explicit truncation bit. +//! +//! The SDK still owns JSON-RPC framing, IDs, request correlation and dispatch. +//! Session updates are observed through the SDK's ordered notification handler. +//! That ordering is the phase boundary used to discard `session/load` replay: +//! replay notifications are dispatched 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}; +use std::time::Duration; + +use agent_client_protocol::v1::schema::{ + CancelNotification, ContentBlock, Implementation, InitializeRequest, LoadSessionRequest, + NewSessionRequest, PromptRequest, RequestPermissionOutcome, RequestPermissionRequest, + RequestPermissionResponse, ResumeSessionRequest, SessionId, +}; +use agent_client_protocol::{Agent, Client, Error as SdkError, Lines, schema::ProtocolVersion}; +use futures_util::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +use futures_util::{Sink, Stream, sink, stream}; +use serde_json::Value; +use tokio::io::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 notifications processed for one connection before cutoff. +pub const MAX_TURN_NOTIFICATIONS: usize = 64; +/// Maximum notification bytes processed for one connection before cutoff. +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); +/// Time allowed for the SDK connection to drain accepted output before its +/// future is dropped and the child group is terminated. +const CONNECTION_DRAIN_BUDGET: Duration = Duration::from_secs(1); +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, + 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::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)] +pub struct AcpCleanupReport { + pub direct_child_reaped: bool, + pub exit_status: Option, + pub group_signal_sent: bool, + pub forced: bool, + pub cleanup_confirmed: bool, +} + +/// 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>, + pid: u32, + deadline: Instant, + active: Arc, + shared: Arc, + initialized: bool, + session_id: Option, + prompted: bool, + closed: bool, +} + +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 { + if Instant::now() >= deadline { + return Err(AcpDelegationError::DeadlineExceeded); + } + let mut child = OwnedChild::spawn(&launch).map_err(|_| AcpDelegationError::SpawnFailed)?; + let pid = child.pid(); + let (stdin, stdout) = child + .take_pipes() + .map_err(|_| AcpDelegationError::SpawnFailed)?; + + let shared = Arc::new(Shared::default()); + let transport = bounded_lines(stdin, stdout, shared.clone()); + let shared_for_client = shared.clone(); + let (command_tx, command_rx) = mpsc::channel(1); + let (shutdown_tx, shutdown_rx) = watch::channel(false); + 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 supervisor = tokio::spawn(async move { + let mut connection = Box::pin( + Client + .v1() + .name("rustscript-agent-delegation") + .on_receive_request( + { + let shared = shared.clone(); + async move |_request: RequestPermissionRequest, responder, _cx| { + shared.permissions.fetch_add(1, Ordering::Relaxed); + responder.respond(RequestPermissionResponse::new( + RequestPermissionOutcome::Cancelled, + ))?; + Ok(()) + } + }, + agent_client_protocol::on_receive_request!(), + ) + .connect_with(transport, { + let shared = shared.clone(); + async move |connection| { + run_actor(connection, command_rx, shared, cwd, deadline, shutdown_rx) + .await + } + }), + ); + let _connection_result = tokio::select! { + result = &mut connection => Some(result), + _ = supervisor_shutdown.changed() => { + timeout(CONNECTION_DRAIN_BUDGET, &mut connection).await.ok() + } + }; + drop(connection); + let cleanup = child.terminate(CLEANUP_BUDGET).await; + supervisor_active.store(0, Ordering::Release); + SupervisorReport { cleanup } + }); + + Ok(Self { + commands: Some(command_tx), + shutdown: shutdown_tx, + supervisor: Some(supervisor), + 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`. + pub fn active_count(&self) -> usize { + self.active.load(Ordering::Acquire) + } + + /// 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; + self.exchange( + |reply| ActorCommand::Prompt { + session_id: session_id.to_owned(), + task: task.to_owned(), + reply, + }, + AcpDelegationError::PromptFailed, + ) + .await + } + + /// Request shutdown and wait for the owned supervisor's cleanup evidence. + /// + /// If the supervisor cannot be confirmed within the cleanup budget plus one + /// drain allowance, the supervisor remains alive with its capacity until it + /// completes; this call returns unconfirmed evidence. + pub async fn close(mut self) -> AcpCleanupReport { + self.closed = true; + let _ = self.shutdown.send(true); + self.commands.take(); + let Some(supervisor) = self.supervisor.take() else { + return AcpCleanupReport::unconfirmed(); + }; + match timeout(CLEANUP_BUDGET + CONNECTION_DRAIN_BUDGET, 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)?; + 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) + } + } + } +} + +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, + 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, + cwd: PathBuf, + deadline: Instant, + initialized: bool, + capabilities: AcpAgentCapabilities, + session_id: Option, + prompted: bool, +} + +async fn run_actor( + connection: agent_client_protocol::v1::ConnectionTo, + mut commands: mpsc::Receiver, + shared: Arc, + cwd: PathBuf, + deadline: Instant, + mut shutdown: watch::Receiver, +) -> Result<(), SdkError> { + let mut actor = Actor { + connection, + shared, + cwd, + deadline, + initialized: false, + capabilities: AcpAgentCapabilities { + resume: false, + load: false, + }, + session_id: None, + prompted: false, + }; + loop { + tokio::select! { + _ = shutdown.changed() => return Ok(()), + _ = sleep_until(deadline) => return Ok(()), + command = commands.recv() => match command { + Some(ActorCommand::Initialize { reply }) => { + if actor.initialized { + let _ = reply.send(Err(AcpDelegationError::InvalidPhase)); + continue; + } + let result = actor.initialize().await; + if result.is_ok() { + actor.initialized = true; + } + let _ = reply.send(result); + } + Some(ActorCommand::NewSession { reply }) => { + let result = actor.new_session().await; + let _ = reply.send(result); + } + Some(ActorCommand::RestoreSession { session_id, reply }) => { + let result = actor.restore_session(session_id).await; + let _ = reply.send(result); + } + Some(ActorCommand::Prompt { + session_id, + task, + reply, + }) => { + let result = actor.prompt(&session_id, &task, &mut shutdown).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 response = timeout_at( + self.deadline, + self.connection.send_request(request).block_task(), + ) + .await + .map_err(|_| AcpDelegationError::DeadlineExceeded)? + .map_err(|_| self.failure(AcpDelegationError::InitializeFailed))?; + 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 response = timeout_at( + self.deadline, + self.connection.send_request(request).block_task(), + ) + .await + .map_err(|_| AcpDelegationError::DeadlineExceeded)? + .map_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()); + let response = match method { + AcpRestoreMethod::Resume => { + let request = ResumeSessionRequest::new(session, &self.cwd).mcp_servers(Vec::new()); + timeout_at( + self.deadline, + self.connection.send_request(request).block_task(), + ) + .await + .map_err(|_| AcpDelegationError::DeadlineExceeded)? + .map(|_| ()) + } + AcpRestoreMethod::Load => { + let request = LoadSessionRequest::new(session, &self.cwd).mcp_servers(Vec::new()); + timeout_at( + self.deadline, + self.connection.send_request(request).block_task(), + ) + .await + .map_err(|_| AcpDelegationError::DeadlineExceeded)? + .map(|_| ()) + } + }; + response.map_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, + ) -> 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; + self.shared.begin_prompt(session_id); + let request = PromptRequest::new( + SessionId::from(session_id.to_owned()), + vec![ContentBlock::from(task.to_owned())], + ); + let response = tokio::select! { + _ = shutdown.changed() => { + self.cancel(session_id); + self.shared.finish_prompt(); + return Err(AcpDelegationError::Cancelled); + } + result = timeout_at(self.deadline, self.connection.send_request(request).block_task()) => { + match result { + Err(_) => { + self.cancel(session_id); + self.shared.finish_prompt(); + return Err(AcpDelegationError::DeadlineExceeded); + } + Ok(response) => response, + } + } + }; + let response = match response { + Ok(response) => response, + Err(_) => { + self.shared.finish_prompt(); + return Err(self.failure(AcpDelegationError::PromptFailed)); + } + }; + 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() + }; + Ok(AcpPromptResult { + text, + truncated, + stop_reason: map_stop_reason(response.stop_reason), + }) + } + + fn cancel(&self, session_id: &str) { + let _ = self + .connection + .send_notification(CancelNotification::new(SessionId::from( + session_id.to_owned(), + ))); + } + + fn failure(&self, fallback: AcpDelegationError) -> AcpDelegationError { + self.shared.fatal().unwrap_or(fallback) + } +} + +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; + +#[derive(Default)] +struct Shared { + phase: AtomicU8, + session: Mutex>, + text: Mutex, + truncated: AtomicBool, + notifications: AtomicUsize, + notification_bytes: AtomicUsize, + fatal: Mutex>, + permissions: AtomicUsize, +} + +impl Shared { + 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) { + self.text.lock().unwrap().clear(); + self.truncated.store(false, Ordering::Release); + *self.session.lock().unwrap() = Some(session_id.to_owned()); + self.phase.store(PHASE_PROMPT, Ordering::Release); + } + + 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); + } + } + + fn ingest(&self, line: &str) -> Result<(), io::Error> { + let Ok(Value::Object(message)) = serde_json::from_str::(line) else { + return Ok(()); + }; + if message.get("method").and_then(Value::as_str) != Some("session/update") { + return Ok(()); + } + let count = self.notifications.fetch_add(1, Ordering::AcqRel) + 1; + let total = self + .notification_bytes + .fetch_add(line.len(), Ordering::AcqRel) + .saturating_add(line.len()); + if count > MAX_TURN_NOTIFICATIONS || total > MAX_TURN_NOTIFICATION_BYTES { + self.set_fatal(AcpDelegationError::NotificationFlood); + return Err(io::Error::other("acp notification rate exceeds limit")); + } + if self.phase.load(Ordering::Acquire) != PHASE_PROMPT { + return Ok(()); + } + let Some(params) = message.get("params").and_then(Value::as_object) else { + return Ok(()); + }; + if params.get("sessionId").and_then(Value::as_str) + != self.session.lock().unwrap().as_deref() + { + return Ok(()); + } + let Some(update) = params.get("update").and_then(Value::as_object) else { + return Ok(()); + }; + if update.get("sessionUpdate").and_then(Value::as_str) != Some("agent_message_chunk") { + return Ok(()); + } + let Some(content) = update.get("content").and_then(Value::as_object) else { + return Ok(()); + }; + if content.get("type").and_then(Value::as_str) != Some("text") { + return Ok(()); + } + if let Some(text) = content.get("text").and_then(Value::as_str) { + self.append_text(text); + } + Ok(()) + } + + 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); + } +} + +fn bounded_lines( + stdin: ChildStdin, + stdout: ChildStdout, + shared: Arc, +) -> Lines< + impl Sink + Send + 'static, + impl Stream> + Send + 'static, +> { + let incoming = stream::try_unfold(BufReader::new(ChildIo(stdout)), move |mut reader| { + let shared = shared.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; + } + // Serialized ingress boundary: while a prompt is active, the + // first JSON-RPC response on the wire is its response. Seal the + // text phase before the SDK dispatches it, so a notification + // the peer writes after the response can never join the result. + if shared.phase.load(Ordering::Acquire) == PHASE_PROMPT { + if looks_like_response(&line) { + shared.finish_prompt(); + } else { + shared.ingest(&line)?; + } + } + return Ok(Some((line, reader))); + } + } + }); + let outgoing = sink::unfold(ChildIo(stdin), |mut writer, line: String| async move { + writer.write_all(line.as_bytes()).await?; + writer.write_all(b"\n").await?; + writer.flush().await?; + Ok::<_, io::Error>(writer) + }); + Lines::new(outgoing, incoming) +} + +fn looks_like_response(line: &str) -> bool { + let Ok(Value::Object(object)) = serde_json::from_str::(line) else { + return false; + }; + object.contains_key("id") + && !object.contains_key("method") + && (object.contains_key("result") || object.contains_key("error")) +} + +/// `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, +} + +impl OwnedChild { + fn spawn(launch: &AcpDelegationLaunch) -> io::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); + let child = command.spawn()?; + let pid = child + .id() + .ok_or_else(|| io::Error::other("harness pid unavailable"))?; + Ok(Self { child, pid }) + } + + 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)) + } + + async fn terminate(mut self, budget: Duration) -> AcpCleanupReport { + let deadline = Instant::now() + budget; + let mut status = None; + let natural_deadline = (Instant::now() + Duration::from_millis(300)).min(deadline); + loop { + match self.child.try_wait() { + Ok(Some(exit)) => { + status = Some(exit); + break; + } + Ok(None) => {} + Err(_) => break, + } + if Instant::now() >= natural_deadline { + break; + } + sleep(Duration::from_millis(10)).await; + } + + let mut group_signal_sent = false; + let mut forced = false; + if status.is_none() { + group_signal_sent |= signal_group(self.pid, libc::SIGTERM); + let term_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline); + loop { + match self.child.try_wait() { + Ok(Some(exit)) => { + status = Some(exit); + break; + } + Ok(None) => {} + Err(_) => break, + } + if Instant::now() >= term_deadline { + break; + } + sleep(Duration::from_millis(10)).await; + } + } + if status.is_none() { + group_signal_sent |= signal_group(self.pid, libc::SIGKILL); + forced = true; + let _ = self.child.start_kill(); + if let Ok(Ok(exit)) = timeout_at(deadline, self.child.wait()).await { + status = Some(exit); + } + } + // The direct child may have exited while a descendant kept the group + // alive. Signal the owned group again while its identity is known. + group_signal_sent |= signal_group(self.pid, libc::SIGKILL); + let direct_child_reaped = status.is_some(); + AcpCleanupReport { + direct_child_reaped, + exit_status: status, + group_signal_sent, + forced, + cleanup_confirmed: direct_child_reaped, + } + } +} + +impl Drop for OwnedChild { + fn drop(&mut self) { + // Cancellation cannot await. Tokio owns the direct-child reap; signal + // the group while the unreaped leader identity still exists. + signal_group(self.pid, libc::SIGKILL); + let _ = self.child.start_kill(); + } +} + +#[cfg(unix)] +fn signal_group(pid: u32, signal: libc::c_int) -> bool { + // SAFETY: the group was created at spawn. The negative PID targets only the + // owned process group, never an unrelated process. + unsafe { libc::kill(-(pid as libc::pid_t), signal) == 0 } +} + +#[cfg(not(unix))] +fn signal_group(_pid: u32, _signal: libc::c_int) -> bool { + false +} diff --git a/src/acp/mod.rs b/src/acp/mod.rs index 0fffe94..3006249 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, AcpCleanupReport, AcpDelegationError, AcpDelegationLaunch, + AcpPromptResult, AcpRestoreMethod, AcpStopReason, DelegatedAcpClient, +}; pub use proxy::{AcpProxyError, ProxyDisposition, run_proxy}; diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs new file mode 100644 index 0000000..901b508 --- /dev/null +++ b/tests/acp_delegation_client_tests.rs @@ -0,0 +1,675 @@ +//! 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/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 { + let contents = fs::read_to_string(path).unwrap_or_default(); + contents + .lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).expect("fixture event is JSON")) + .collect() +} + +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() +} + +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"); +} + +#[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); + + 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); + 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 notification_flood_terminates_the_connection() { + let root = TestRoot::new("flood"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--flood", "96", "--flood-bytes", "16384"], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + assert_eq!( + client.prompt(&session_id, "flood").await, + Err(AcpDelegationError::NotificationFlood) + ); + 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 prompt = client.prompt(&session_id, "hold until cancellation"); + tokio::pin!(prompt); + tokio::select! { + result = &mut prompt => panic!("stubborn prompt unexpectedly completed: {result:?}"), + _ = tokio::time::sleep(Duration::from_millis(250)) => {} + } + } + 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; + 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); + let events = read_events(&root.record_path()); + let descendant = named(&events, "descendant")[0]["data"]["pid"] + .as_u64() + .expect("descendant pid") as u32; + wait_pid_gone(descendant).await; +} + +#[tokio::test] +async fn notification_byte_flood_terminates_the_connection() { + let root = TestRoot::new("byte-flood"); + let mut client = connect( + &root, + with_extra( + &root, + "normal", + &["--flood", "6", "--flood-bytes", "800000"], + ), + OPERATION_BOUND, + ) + .await; + client.initialize().await.expect("initialize"); + let session_id = client.new_session().await.expect("session/new"); + assert_eq!( + client.prompt(&session_id, "byte flood").await, + Err(AcpDelegationError::NotificationFlood) + ); + let cleanup = client.close().await; + assert!(cleanup.cleanup_confirmed); +} diff --git a/tests/fixtures/acp/build.rs b/tests/fixtures/acp/build.rs index 56e78e5..ab01d7e 100644 --- a/tests/fixtures/acp/build.rs +++ b/tests/fixtures/acp/build.rs @@ -1,7 +1,17 @@ use std::{fs, path::Path, process::Command}; /// Compile the same fake peer for the packaged ACP transport and MCP tests. +#[allow(dead_code)] pub fn compile_fake_agent(binary: &Path) { + compile_fixture("fake_agent.rs", "2021", binary); +} + +/// Compile the delegated-client harness used by the task-1 client tests. +pub fn compile_delegation_agent(binary: &Path) { + compile_fixture("delegation_agent.rs", "2024", binary); +} + +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) @@ -17,8 +27,12 @@ pub fn compile_fake_agent(binary: &Path) { .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(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") diff --git a/tests/fixtures/acp/delegation_agent.rs b/tests/fixtures/acp/delegation_agent.rs new file mode 100644 index 0000000..8d46982 --- /dev/null +++ b/tests/fixtures/acp/delegation_agent.rs @@ -0,0 +1,528 @@ +//! 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. +//! +//! 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, +} + +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, + } + } +} + +struct Pending { + session_id: String, + prompt_id: Value, +} + +struct Harness { + config: Config, + events: Option, + out: io::Stdout, + sessions: HashMap, + next_session: u64, + next_request: 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": 1, + "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.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.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); + } + + 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) { + 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-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, + 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(), + next_session: 0, + next_request: 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())), + } + } + + 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)); + } + } +} From c395465a4c2c87fd7f99af8ed168d28f525467a7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 06:03:44 +0800 Subject: [PATCH 02/27] fix(acp): bind delegation ingress and cleanup to owned state Classify every inbound line before it reaches the SDK transport: only the response carrying the exact prompt request ID is forwarded, so text after the matching response and unrelated frames never affect the result. Validate session updates with the locked SDK schema, answer peer requests inline, and charge only frames that are actually unconsumed. Keep the direct leader unreaped while terminating and confirming the owned process group, then reap it; share one absolute cleanup budget with connection draining and never signal a cached PID after reaping. Release capacity only after cleanup is proven. Extend the ACP fixture and client tests for decoy responses, non-v1 handshakes, malformed updates, inline request bursts, long ready streams, terminal callbacks and leader-exit-first group cleanup. --- src/acp/delegated_client.rs | 640 ++++++++++++++++++------- tests/acp_delegation_client_tests.rs | 341 ++++++++++++- tests/fixtures/acp/delegation_agent.rs | 201 +++++++- 3 files changed, 997 insertions(+), 185 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 0f32568..247761b 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -11,18 +11,28 @@ //! 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 and is reaped on explicit close, -//! on drop, or by the owned supervisor after cancellation; -//! - each inbound line is limited to 1 MiB; a turn is cut off after 64 -//! notifications or 4 MiB, whichever comes first; +//! - the child runs in its own process group. While the direct leader is still +//! owned and unreaped, the supervisor terminates the whole group and confirms +//! that no live member remains; only then is the leader reaped. A cached PID +//! is never signalled after the leader has been reaped; +//! - 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. //! //! The SDK still owns JSON-RPC framing, IDs, request correlation and dispatch. -//! Session updates are observed through the SDK's ordered notification handler. -//! That ordering is the phase boundary used to discard `session/load` replay: -//! replay notifications are dispatched before the load response, while the -//! collector only admits text after this client has begun its single prompt. +//! 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 @@ -42,14 +52,17 @@ use std::time::Duration; use agent_client_protocol::v1::schema::{ CancelNotification, ContentBlock, Implementation, InitializeRequest, LoadSessionRequest, - NewSessionRequest, PromptRequest, RequestPermissionOutcome, RequestPermissionRequest, - RequestPermissionResponse, ResumeSessionRequest, SessionId, + NewSessionRequest, PromptRequest, RequestPermissionOutcome, RequestPermissionResponse, + ResumeSessionRequest, SessionId, SessionNotification, SessionUpdate, }; -use agent_client_protocol::{Agent, Client, Error as SdkError, Lines, schema::ProtocolVersion}; -use futures_util::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +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::ReadBuf; +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}; @@ -57,9 +70,9 @@ 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 notifications processed for one connection before cutoff. +/// Maximum frames forwarded to the SDK but not yet consumed. pub const MAX_TURN_NOTIFICATIONS: usize = 64; -/// Maximum notification bytes processed for one connection before cutoff. +/// 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; @@ -67,9 +80,11 @@ pub const MAX_RESULT_TEXT_BYTES: usize = 32 * 1024; pub const MAX_TASK_BYTES: usize = 8 * 1024; /// Separate absolute process-cleanup budget. pub const CLEANUP_BUDGET: Duration = Duration::from_secs(5); -/// Time allowed for the SDK connection to drain accepted output before its -/// future is dropped and the child group is terminated. -const CONNECTION_DRAIN_BUDGET: Duration = Duration::from_secs(1); +/// 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; @@ -244,6 +259,9 @@ pub struct AcpCleanupReport { pub exit_status: Option, pub group_signal_sent: bool, pub forced: bool, + /// The owned process group had no live, non-zombie member at the final + /// check, taken while the direct leader was still unreaped. + pub group_clear: bool, pub cleanup_confirmed: bool, } @@ -286,7 +304,8 @@ impl DelegatedAcpClient { .map_err(|_| AcpDelegationError::SpawnFailed)?; let shared = Arc::new(Shared::default()); - let transport = bounded_lines(stdin, stdout, shared.clone()); + let wire = Arc::new(Wire::new(stdin)); + let transport = bounded_lines(stdout, wire.clone(), shared.clone()); let shared_for_client = shared.clone(); let (command_tx, command_rx) = mpsc::channel(1); let (shutdown_tx, shutdown_rx) = watch::channel(false); @@ -295,24 +314,12 @@ impl DelegatedAcpClient { 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") - .on_receive_request( - { - let shared = shared.clone(); - async move |_request: RequestPermissionRequest, responder, _cx| { - shared.permissions.fetch_add(1, Ordering::Relaxed); - responder.respond(RequestPermissionResponse::new( - RequestPermissionOutcome::Cancelled, - ))?; - Ok(()) - } - }, - agent_client_protocol::on_receive_request!(), - ) .connect_with(transport, { let shared = shared.clone(); async move |connection| { @@ -321,16 +328,29 @@ impl DelegatedAcpClient { } }), ); - let _connection_result = tokio::select! { - result = &mut connection => Some(result), + // One absolute cleanup budget covers draining accepted output and + // terminating the owned process group; they do not add up. + let cleanup_deadline = tokio::select! { + _result = &mut connection => Instant::now() + CLEANUP_BUDGET, _ = supervisor_shutdown.changed() => { - timeout(CONNECTION_DRAIN_BUDGET, &mut connection).await.ok() + let deadline = Instant::now() + CLEANUP_BUDGET; + let _ = timeout_at(deadline, &mut connection).await; + deadline } }; drop(connection); - let cleanup = child.terminate(CLEANUP_BUDGET).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; + } supervisor_active.store(0, Ordering::Release); - SupervisorReport { cleanup } + SupervisorReport { cleanup: report } }); Ok(Self { @@ -358,6 +378,19 @@ impl DelegatedAcpClient { self.active.load(Ordering::Acquire) } + /// 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), + ) + } + /// Send `initialize`. No file-system or terminal client capability is /// advertised. pub async fn initialize(&mut self) -> Result { @@ -456,9 +489,9 @@ impl DelegatedAcpClient { /// Request shutdown and wait for the owned supervisor's cleanup evidence. /// - /// If the supervisor cannot be confirmed within the cleanup budget plus one - /// drain allowance, the supervisor remains alive with its capacity until it - /// completes; this call returns unconfirmed 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(mut self) -> AcpCleanupReport { self.closed = true; let _ = self.shutdown.send(true); @@ -466,7 +499,7 @@ impl DelegatedAcpClient { let Some(supervisor) = self.supervisor.take() else { return AcpCleanupReport::unconfirmed(); }; - match timeout(CLEANUP_BUDGET + CONNECTION_DRAIN_BUDGET, supervisor).await { + match timeout(CLEANUP_BUDGET + CLOSE_SCHEDULING_SLACK, supervisor).await { Ok(Ok(report)) => report.cleanup, Ok(Err(_)) | Err(_) => AcpCleanupReport::unconfirmed(), } @@ -483,7 +516,7 @@ impl DelegatedAcpClient { .send(build(reply_tx)) .await .map_err(|_| AcpDelegationError::Closed)?; - match timeout_at(self.deadline + CLEANUP_BUDGET, reply_rx).await { + let outcome = match timeout_at(self.deadline + CLEANUP_BUDGET, reply_rx).await { Ok(Ok(result)) => result, Ok(Err(_)) => { if Instant::now() >= self.deadline { @@ -496,7 +529,11 @@ impl DelegatedAcpClient { let _ = self.shutdown.send(true); Err(AcpDelegationError::DeadlineExceeded) } - } + }; + // The forwarded response (if any) has now been consumed by the SDK or + // was never forwarded; either way it no longer occupies ingress quota. + self.shared.release_forwarded(); + outcome } } @@ -520,6 +557,7 @@ impl AcpCleanupReport { exit_status: None, group_signal_sent: false, forced: false, + group_clear: false, cleanup_confirmed: false, } } @@ -626,13 +664,16 @@ impl Actor { "rustscript-agent", env!("CARGO_PKG_VERSION"), )); - let response = timeout_at( - self.deadline, - self.connection.send_request(request).block_task(), - ) - .await - .map_err(|_| AcpDelegationError::DeadlineExceeded)? - .map_err(|_| self.failure(AcpDelegationError::InitializeFailed))?; + 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); + 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); } @@ -656,13 +697,16 @@ impl Actor { return Err(AcpDelegationError::InvalidPhase); } let request = NewSessionRequest::new(&self.cwd).mcp_servers(Vec::new()); - let response = timeout_at( - self.deadline, - self.connection.send_request(request).block_task(), - ) - .await - .map_err(|_| AcpDelegationError::DeadlineExceeded)? - .map_err(|_| self.failure(AcpDelegationError::SessionCreateFailed))?; + 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); + 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()); @@ -684,29 +728,34 @@ impl Actor { .restore_method() .ok_or(AcpDelegationError::RestoreUnsupported)?; let session = SessionId::from(session_id.clone()); - let response = match method { + match method { AcpRestoreMethod::Resume => { let request = ResumeSessionRequest::new(session, &self.cwd).mcp_servers(Vec::new()); - timeout_at( - self.deadline, - self.connection.send_request(request).block_task(), - ) - .await - .map_err(|_| AcpDelegationError::DeadlineExceeded)? - .map(|_| ()) + 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); + 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()); - timeout_at( - self.deadline, - self.connection.send_request(request).block_task(), - ) - .await - .map_err(|_| AcpDelegationError::DeadlineExceeded)? - .map(|_| ()) + 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); + match outcome { + Err(_) => return Err(AcpDelegationError::DeadlineExceeded), + Ok(Ok(_)) => {} + Ok(Err(_)) => return Err(self.failure(AcpDelegationError::RestoreFailed)), + } } - }; - response.map_err(|_| self.failure(AcpDelegationError::RestoreFailed))?; + } self.shared.set_session(&session_id); self.session_id = Some(session_id); Ok(method) @@ -728,21 +777,28 @@ impl Actor { return Err(AcpDelegationError::SessionMismatch); } self.prompted = true; - self.shared.begin_prompt(session_id); 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(); + // Bind the text phase to the exact JSON-RPC ID reserved for this + // prompt before publishing it. The serial ingress forwards only the + // response with this ID and seals the text phase at that point. + self.shared.begin_prompt(session_id, request_id.clone()); let response = tokio::select! { _ = shutdown.changed() => { self.cancel(session_id); + self.shared.clear_expected(&request_id); self.shared.finish_prompt(); return Err(AcpDelegationError::Cancelled); } - result = timeout_at(self.deadline, self.connection.send_request(request).block_task()) => { + result = timeout_at(self.deadline, prepared.block_task()) => { match result { Err(_) => { self.cancel(session_id); + self.shared.clear_expected(&request_id); self.shared.finish_prompt(); return Err(AcpDelegationError::DeadlineExceeded); } @@ -750,6 +806,7 @@ impl Actor { } } }; + self.shared.clear_expected(&request_id); let response = match response { Ok(response) => response, Err(_) => { @@ -781,6 +838,22 @@ impl Actor { 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 { @@ -799,16 +872,27 @@ const PHASE_SETUP: u8 = 0; const PHASE_PROMPT: u8 = 1; const PHASE_DONE: u8 = 2; +/// Frames handed to the SDK but not yet consumed by it. +#[derive(Default)] +struct ForwardedBudget { + messages: usize, + bytes: usize, + peak: usize, + outstanding: Vec, +} + #[derive(Default)] struct Shared { phase: AtomicU8, + expected: Mutex>, session: Mutex>, text: Mutex, truncated: AtomicBool, - notifications: AtomicUsize, - notification_bytes: AtomicUsize, + forwarded: Mutex, fatal: Mutex>, permissions: AtomicUsize, + rejected_requests: AtomicUsize, + ignored_updates: AtomicUsize, } impl Shared { @@ -817,13 +901,39 @@ impl Shared { self.phase.store(PHASE_SETUP, Ordering::Release); } - fn begin_prompt(&self, session_id: &str) { + 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()); + // Reserving the exact response ID before publication means a matching + // response cannot be observed without an armed expected ID. + *self.expected.lock().unwrap() = Some(request_id); self.phase.store(PHASE_PROMPT, Ordering::Release); } + fn expect_response(&self, request_id: RawJsonRpcId) { + *self.expected.lock().unwrap() = Some(request_id); + } + + fn clear_expected(&self, request_id: &RawJsonRpcId) { + let mut expected = self.expected.lock().unwrap(); + if expected.as_ref() == Some(request_id) { + *expected = None; + } + } + + /// Claim the expected response ID. Only the first response with exactly + /// this typed ID (string and number forms differ) is forwarded. + fn take_expected(&self, request_id: &RawJsonRpcId) -> bool { + let mut expected = self.expected.lock().unwrap(); + if expected.as_ref() == Some(request_id) { + *expected = None; + true + } else { + false + } + } + fn finish_prompt(&self) { self.phase.store(PHASE_DONE, Ordering::Release); } @@ -846,49 +956,124 @@ impl Shared { } } - fn ingest(&self, line: &str) -> Result<(), io::Error> { - let Ok(Value::Object(message)) = serde_json::from_str::(line) else { - return Ok(()); - }; - if message.get("method").and_then(Value::as_str) != Some("session/update") { - return Ok(()); - } - let count = self.notifications.fetch_add(1, Ordering::AcqRel) + 1; - let total = self - .notification_bytes - .fetch_add(line.len(), Ordering::AcqRel) - .saturating_add(line.len()); - if count > MAX_TURN_NOTIFICATIONS || total > MAX_TURN_NOTIFICATION_BYTES { + /// Charge a frame that is about to enter the SDK transport. The charge is + /// released by [`Self::release_forwarded`] once its response consumer runs. + fn admit_forward(&self, 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 notification rate exceeds limit")); + return Err(io::Error::other("acp ingress quota exceeded")); + } + forwarded.messages += 1; + forwarded.bytes += bytes; + forwarded.outstanding.push(bytes); + forwarded.peak = forwarded.peak.max(forwarded.messages); + Ok(()) + } + + fn release_forwarded(&self) { + let mut forwarded = self.forwarded.lock().unwrap(); + if let Some(bytes) = forwarded.outstanding.pop() { + 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 Ok(()); + return; } - let Some(params) = message.get("params").and_then(Value::as_object) else { - return Ok(()); + 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 params.get("sessionId").and_then(Value::as_str) - != self.session.lock().unwrap().as_deref() + 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 { - return Ok(()); + self.append_text(&content.text); } - let Some(update) = params.get("update").and_then(Value::as_object) else { - return Ok(()); + } + + /// 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()), + ) }; - if update.get("sessionUpdate").and_then(Value::as_str) != Some("agent_message_chunk") { - return Ok(()); - } - let Some(content) = update.get("content").and_then(Value::as_object) else { - return Ok(()); + 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); }; - if content.get("type").and_then(Value::as_str) != Some("text") { - return Ok(()); - } - if let Some(text) = content.get("text").and_then(Value::as_str) { - self.append_text(text); + 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(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) + } } - Ok(()) } fn append_text(&self, text: &str) { @@ -910,16 +1095,41 @@ impl Shared { } } +/// 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. Peer text is never echoed. +struct Wire { + stdin: tokio::sync::Mutex, +} + +impl Wire { + fn new(stdin: ChildStdin) -> Self { + Self { + stdin: tokio::sync::Mutex::new(stdin), + } + } + + async fn write_line(&self, line: &str) -> io::Result<()> { + let mut stdin = self.stdin.lock().await; + stdin.write_all(line.as_bytes()).await?; + stdin.write_all(b"\n").await?; + stdin.flush().await + } +} + fn bounded_lines( - stdin: ChildStdin, 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(); @@ -950,39 +1160,20 @@ fn bounded_lines( if line.trim().is_empty() { continue; } - // Serialized ingress boundary: while a prompt is active, the - // first JSON-RPC response on the wire is its response. Seal the - // text phase before the SDK dispatches it, so a notification - // the peer writes after the response can never join the result. - if shared.phase.load(Ordering::Acquire) == PHASE_PROMPT { - if looks_like_response(&line) { - shared.finish_prompt(); - } else { - shared.ingest(&line)?; - } + if shared.classify(&line, &wire).await? { + return Ok(Some((line, reader))); } - return Ok(Some((line, reader))); + // Fully consumed inline; continue without yielding. } } }); - let outgoing = sink::unfold(ChildIo(stdin), |mut writer, line: String| async move { - writer.write_all(line.as_bytes()).await?; - writer.write_all(b"\n").await?; - writer.flush().await?; - Ok::<_, io::Error>(writer) + let outgoing = sink::unfold(wire, |wire: Arc, line: String| async move { + wire.write_line(&line).await?; + Ok::<_, io::Error>(wire) }); Lines::new(outgoing, incoming) } -fn looks_like_response(line: &str) -> bool { - let Ok(Value::Object(object)) = serde_json::from_str::(line) else { - return false; - }; - object.contains_key("id") - && !object.contains_key("method") - && (object.contains_key("result") || object.contains_key("error")) -} - /// `Lines` uses futures I/O; the owned child uses Tokio I/O. struct ChildIo(T); @@ -1019,6 +1210,7 @@ impl AsyncWrite for ChildIo { struct OwnedChild { child: Child, pid: u32, + reaped: bool, } impl OwnedChild { @@ -1046,7 +1238,11 @@ impl OwnedChild { let pid = child .id() .ok_or_else(|| io::Error::other("harness pid unavailable"))?; - Ok(Self { child, pid }) + Ok(Self { + child, + pid, + reaped: false, + }) } fn pid(&self) -> u32 { @@ -1067,76 +1263,176 @@ impl OwnedChild { Ok((stdin, stdout)) } - async fn terminate(mut self, budget: Duration) -> AcpCleanupReport { - let deadline = Instant::now() + budget; - let mut status = None; + /// Terminate the owned process group and confirm it is empty before the + /// direct leader is reaped. + /// + /// The unreaped leader pins both the PID and the process-group identity, so + /// every group signal in this method targets the group this client created. + /// Once the leader has been reaped this method never signals again. + async fn terminate(&mut self, deadline: Instant) -> AcpCleanupReport { + let mut group_signal_sent = false; + let mut forced = false; + + // Give a harness that closes stdio a short window to exit on its own. let natural_deadline = (Instant::now() + Duration::from_millis(300)).min(deadline); - loop { - match self.child.try_wait() { - Ok(Some(exit)) => { - status = Some(exit); + while Instant::now() < natural_deadline && !leader_exited(self.pid) { + sleep(Duration::from_millis(10)).await; + } + + // Members that outlive the leader are still in the owned group while the + // leader is unreaped, so the group identity is safe to use. + let mut group = group_members(self.pid); + if !matches!(group, Ok(0)) { + group_signal_sent |= signal_group(self.pid, libc::SIGTERM); + let term_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline); + loop { + group = group_members(self.pid); + if matches!(group, Ok(0)) || Instant::now() >= term_deadline { break; } - Ok(None) => {} - Err(_) => break, + sleep(Duration::from_millis(10)).await; } - if Instant::now() >= natural_deadline { - break; + } + if !matches!(group, Ok(0)) { + group_signal_sent |= signal_group(self.pid, libc::SIGKILL); + forced = true; + loop { + group = group_members(self.pid); + if matches!(group, Ok(0)) || Instant::now() >= deadline { + break; + } + sleep(Duration::from_millis(10)).await; } - sleep(Duration::from_millis(10)).await; } - let mut group_signal_sent = false; - let mut forced = false; - if status.is_none() { - group_signal_sent |= signal_group(self.pid, libc::SIGTERM); - let term_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline); + let group_clear = matches!(group, Ok(0)); + // Reap only after the group is proven empty. Until then the unreaped + // leader is retained as the group identity anchor for a later retry. + let mut status = None; + if group_clear { loop { match self.child.try_wait() { Ok(Some(exit)) => { status = Some(exit); + self.reaped = true; break; } Ok(None) => {} Err(_) => break, } - if Instant::now() >= term_deadline { + if Instant::now() >= deadline { break; } - sleep(Duration::from_millis(10)).await; + sleep(Duration::from_millis(5)).await; } } - if status.is_none() { - group_signal_sent |= signal_group(self.pid, libc::SIGKILL); - forced = true; - let _ = self.child.start_kill(); - if let Ok(Ok(exit)) = timeout_at(deadline, self.child.wait()).await { - status = Some(exit); - } - } - // The direct child may have exited while a descendant kept the group - // alive. Signal the owned group again while its identity is known. - group_signal_sent |= signal_group(self.pid, libc::SIGKILL); let direct_child_reaped = status.is_some(); AcpCleanupReport { direct_child_reaped, exit_status: status, group_signal_sent, forced, - cleanup_confirmed: direct_child_reaped, + group_clear, + cleanup_confirmed: group_clear && direct_child_reaped, } } } impl Drop for OwnedChild { fn drop(&mut self) { - // Cancellation cannot await. Tokio owns the direct-child reap; signal - // the group while the unreaped leader identity still exists. + if self.reaped { + return; + } + // Cancellation cannot await. The leader is still unreaped here, so its + // cached PID still pins the group identity; this is the last safe point + // to signal the whole group. signal_group(self.pid, libc::SIGKILL); let _ = self.child.start_kill(); } } +/// Whether the direct leader has exited, without reaping it. +/// +/// `WNOWAIT` keeps the zombie in place so the PID and process-group identity +/// stay anchored to this client until [`OwnedChild::terminate`] has confirmed +/// that no live group member remains. +#[cfg(unix)] +fn leader_exited(pid: u32) -> bool { + // SAFETY: `waitid` writes to the provided `siginfo_t`; it is zeroed first + // and only read through the documented accessor. + unsafe { + let mut info: libc::siginfo_t = std::mem::zeroed(); + let result = libc::waitid( + libc::P_PID, + pid as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ); + result == 0 && info.si_pid() != 0 + } +} + +#[cfg(not(unix))] +fn leader_exited(_pid: u32) -> bool { + false +} + +/// Number of live (non-zombie) processes in `pgid`. +/// +/// Linux is checked through `/proc`, which distinguishes a zombie from a live +/// member. Elsewhere signal 0 only proves that some member is still signalable; +/// zombies may keep that true, which fails closed rather than reporting a +/// cleanup that was not observed. +#[cfg(target_os = "linux")] +fn group_members(pgid: u32) -> io::Result { + let mut live = 0; + for entry in std::fs::read_dir("/proc")? { + let entry = entry?; + let Some(pid) = entry + .file_name() + .to_str() + .and_then(|name| name.parse::().ok()) + else { + continue; + }; + let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else { + continue; + }; + let Some(close) = stat.rfind(')') else { + continue; + }; + let mut fields = stat[close + 1..].split_whitespace(); + let state = fields.next(); + let _parent = fields.next(); + let group = fields.next().and_then(|value| value.parse::().ok()); + if state != Some("Z") && group == Some(pgid) { + live += 1; + } + } + Ok(live) +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn group_members(pgid: u32) -> io::Result { + // SAFETY: signal 0 only performs an existence/permission check. + let result = unsafe { libc::kill(-(pgid as libc::pid_t), 0) }; + if result == 0 { + Ok(1) + } else { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::ESRCH) { + Ok(0) + } else { + Err(error) + } + } +} + +#[cfg(not(unix))] +fn group_members(_pgid: u32) -> io::Result { + Ok(0) +} + #[cfg(unix)] fn signal_group(pid: u32, signal: libc::c_int) -> bool { // SAFETY: the group was created at spawn. The negative PID targets only the diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs index 901b508..96bca07 100644 --- a/tests/acp_delegation_client_tests.rs +++ b/tests/acp_delegation_client_tests.rs @@ -156,6 +156,45 @@ async fn wait_pid_gone(pid: u32) { assert!(!pid_alive(pid), "fixture process {pid} was not reaped"); } +/// Live (non-zombie) processes whose process group is `pgid`. +fn live_group_members(pgid: u32) -> Vec { + let Ok(entries) = fs::read_dir("/proc") else { + return Vec::new(); + }; + let mut members = Vec::new(); + for entry in entries.flatten() { + let Some(pid) = entry + .file_name() + .to_str() + .and_then(|name| name.parse::().ok()) + else { + continue; + }; + let Some(stat) = fs::read_to_string(format!("/proc/{pid}/stat")).ok() else { + continue; + }; + let Some(close) = stat.rfind(')') else { + continue; + }; + let fields: Vec<&str> = stat[close + 1..].split_whitespace().collect(); + let (Some(state), Some(group)) = (fields.first(), fields.get(2)) else { + continue; + }; + if *state != "Z" && group.parse::().ok() == Some(pgid) { + members.push(pid); + } + } + members +} + +fn assert_group_clear(pgid: u32) { + let members = live_group_members(pgid); + assert!( + members.is_empty(), + "process group {pgid} still has live members at cleanup return: {members:?}" + ); +} + #[tokio::test] async fn new_session_returns_peer_id_and_one_new_request() { let root = TestRoot::new("new"); @@ -463,23 +502,31 @@ async fn late_update_after_prompt_response_is_not_collected() { } #[tokio::test] -async fn notification_flood_terminates_the_connection() { - let root = TestRoot::new("flood"); +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", "96", "--flood-bytes", "16384"], + &["--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!( - client.prompt(&session_id, "flood").await, - Err(AcpDelegationError::NotificationFlood) + peak, 1, + "only the matching response is ever handed to the SDK unconsumed" ); let cleanup = client.close().await; assert!(cleanup.cleanup_confirmed); @@ -636,6 +683,7 @@ async fn process_group_descendant_is_terminated() { OPERATION_BOUND, ) .await; + let pgid = client.pid(); client.initialize().await.expect("initialize"); let session_id = client.new_session().await.expect("session/new"); client @@ -644,32 +692,303 @@ async fn process_group_descendant_is_terminated() { .expect("prompt"); let cleanup = client.close().await; assert!(cleanup.cleanup_confirmed); + assert_group_clear(pgid); let events = read_events(&root.record_path()); let descendant = named(&events, "descendant")[0]["data"]["pid"] .as_u64() .expect("descendant pid") as u32; - wait_pid_gone(descendant).await; + assert!( + !live_group_members(pgid).contains(&descendant), + "the descendant is gone when cleanup returns" + ); +} + +#[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 notification_byte_flood_terminates_the_connection() { - let root = TestRoot::new("byte-flood"); +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", - &["--flood", "6", "--flood-bytes", "800000"], + &[ + "--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!( - client.prompt(&session_id, "byte flood").await, - Err(AcpDelegationError::NotificationFlood) + 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 pgid = client.pid(); + 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_group_clear(pgid); + 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 pgid = client.pid(); + 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); + assert_group_clear(pgid); + assert!( + marker.exists(), + "the leader-exit-first path must not force-kill a member inside its TERM grace" + ); +} diff --git a/tests/fixtures/acp/delegation_agent.rs b/tests/fixtures/acp/delegation_agent.rs index 8d46982..71c3409 100644 --- a/tests/fixtures/acp/delegation_agent.rs +++ b/tests/fixtures/acp/delegation_agent.rs @@ -16,6 +16,12 @@ //! - `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. //! //! Sessions are remembered in `--store` so a fresh child process can restore //! an ID created by an earlier child. @@ -48,6 +54,14 @@ struct Config { 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, } impl Default for Config { @@ -71,6 +85,14 @@ impl Default for Config { 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, } } } @@ -85,6 +107,8 @@ struct Harness { events: Option, out: io::Stdout, sessions: HashMap, + flood: Option<(Value, String)>, + flood_remaining: usize, next_session: u64, next_request: u64, } @@ -157,7 +181,7 @@ impl Harness { self.respond( id, json!({ - "protocolVersion": 1, + "protocolVersion": self.config.protocol_version, "agentCapabilities": { "loadSession": load, "sessionCapabilities": session_capabilities, @@ -247,6 +271,112 @@ impl Harness { 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}-"); @@ -328,6 +458,9 @@ impl Harness { 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) { @@ -385,11 +518,35 @@ impl Harness { } 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-permission-")) { + 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") }), @@ -433,6 +590,22 @@ fn parse_args() -> Config { "--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"))), other => panic!("unsupported fixture argument: {other}"), } } @@ -450,6 +623,8 @@ fn main() { events, out: io::stdout(), sessions: HashMap::new(), + flood: None, + flood_remaining: 0, next_session: 0, next_request: 0, }; @@ -463,6 +638,28 @@ fn main() { 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() { From 5b25c2c055c673c858a5931b6da2f017c6c007ca Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 06:32:25 +0800 Subject: [PATCH 03/27] fix(acp): confirm delegated cleanup and release consumed replies Byte-parse /proc stat for live group membership so a non-UTF-8 name or an unreadable/unparsable entry cannot look like an empty group; only a vanished entry counts as absence and cleanup stays unconfirmed otherwise. Group tests observe members by PID and kernel start time instead of reusing the same /proc group scan as the oracle. Close now interrupts pending initialize/new/restore requests inside the single absolute cleanup budget, with only a small drain slice before process reaping, and only a published prompt attempts session/cancel. The supervisor publishes typed final cleanup evidence through a caller-held observer before releasing its process slot, so a timed-out close or a drop cannot hand unverified capacity to the next delegation. Ingress quota is released by the actor branch that consumes the matching response, so abandoning the caller's wait no longer leaks a forwarded frame. --- src/acp/delegated_client.rs | 325 +++++++++++++++++++++--- src/acp/mod.rs | 4 +- tests/acp_delegation_client_tests.rs | 329 +++++++++++++++++++++---- tests/fixtures/acp/delegation_agent.rs | 40 +++ 4 files changed, 607 insertions(+), 91 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 247761b..25507db 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -24,6 +24,15 @@ //! 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. Only a prompt that was actually published attempts `session/cancel`. +//! 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 @@ -80,6 +89,10 @@ pub const MAX_RESULT_TEXT_BYTES: usize = 32 * 1024; 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 @@ -253,7 +266,7 @@ impl AcpPromptResult { } /// Evidence from terminating the owned direct child and its process group. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct AcpCleanupReport { pub direct_child_reaped: bool, pub exit_status: Option, @@ -265,6 +278,46 @@ pub struct AcpCleanupReport { 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 remains the owner of the +/// process slot and publishes this report only after cleanup is proven; the +/// observer resolves later even when `close` returned unconfirmed or the client +/// was dropped. A service layer can therefore hand the caller an unconfirmed +/// result and release capacity later, in the background, 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. + pub fn latest(&self) -> Option { + self.report.borrow().clone() + } + + /// Process slots still charged to this supervisor (`1` until the cleanup + /// report is published, then `0`). + pub fn active(&self) -> usize { + self.active.load(Ordering::Acquire) + } + + /// Wait until the supervisor has published final cleanup evidence and has + /// released its slot. + /// + /// Returns `None` only if the supervisor ended without a report (a panic). + /// Because the report is published after the capacity decision but before + /// the task exits, a `Some` value here is ordered after that decision. + 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 @@ -274,6 +327,7 @@ pub struct DelegatedAcpClient { commands: Option>, shutdown: watch::Sender, supervisor: Option>, + proof: watch::Receiver>, pid: u32, deadline: Instant, active: Arc, @@ -309,6 +363,7 @@ impl DelegatedAcpClient { let shared_for_client = shared.clone(); let (command_tx, command_rx) = mpsc::channel(1); let (shutdown_tx, shutdown_rx) = watch::channel(false); + 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(); @@ -328,17 +383,21 @@ impl DelegatedAcpClient { } }), ); - // One absolute cleanup budget covers draining accepted output and - // terminating the owned process group; they do not add up. - let cleanup_deadline = tokio::select! { - _result = &mut connection => Instant::now() + CLEANUP_BUDGET, + // One absolute cleanup budget starts at the first cleanup step. + // A shutdown gets a small drain slice so group termination and + // reaping keep the remaining time in the same budget. + let cleanup_start = tokio::select! { + _result = &mut connection => Instant::now(), _ = supervisor_shutdown.changed() => { - let deadline = Instant::now() + CLEANUP_BUDGET; - let _ = timeout_at(deadline, &mut connection).await; - deadline + let start = Instant::now(); + let drain_deadline = + (start + PROTOCOL_DRAIN_BUDGET).min(start + CLEANUP_BUDGET); + let _ = timeout_at(drain_deadline, &mut connection).await; + start } }; drop(connection); + let cleanup_deadline = cleanup_start + CLEANUP_BUDGET; 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 @@ -349,7 +408,11 @@ impl DelegatedAcpClient { .terminate(Instant::now() + Duration::from_secs(1)) .await; } + // Release the slot only once the final report exists, then publish + // it. Any observer that sees a report is therefore guaranteed to + // see the released counter when the supervisor exits. supervisor_active.store(0, Ordering::Release); + let _ = proof_tx.send(Some(report.clone())); SupervisorReport { cleanup: report } }); @@ -357,6 +420,7 @@ impl DelegatedAcpClient { commands: Some(command_tx), shutdown: shutdown_tx, supervisor: Some(supervisor), + proof: proof_rx, pid, deadline, active, @@ -374,10 +438,25 @@ impl DelegatedAcpClient { } /// `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(), + } + } + /// 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. @@ -530,9 +609,9 @@ impl DelegatedAcpClient { Err(AcpDelegationError::DeadlineExceeded) } }; - // The forwarded response (if any) has now been consumed by the SDK or - // was never forwarded; either way it no longer occupies ingress quota. - self.shared.release_forwarded(); + // 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 } } @@ -627,18 +706,39 @@ async fn run_actor( let _ = reply.send(Err(AcpDelegationError::InvalidPhase)); continue; } - let result = actor.initialize().await; + // 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 = actor.new_session().await; + 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 = actor.restore_session(session_id).await; + 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 { @@ -669,6 +769,7 @@ impl Actor { 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, @@ -702,6 +803,7 @@ impl Actor { 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, @@ -736,6 +838,7 @@ impl Actor { 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(_)) => {} @@ -749,6 +852,7 @@ impl Actor { 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(_)) => {} @@ -791,6 +895,7 @@ impl Actor { _ = shutdown.changed() => { self.cancel(session_id); self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); self.shared.finish_prompt(); return Err(AcpDelegationError::Cancelled); } @@ -799,6 +904,7 @@ impl Actor { Err(_) => { self.cancel(session_id); self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); self.shared.finish_prompt(); return Err(AcpDelegationError::DeadlineExceeded); } @@ -807,6 +913,7 @@ impl Actor { } }; self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); let response = match response { Ok(response) => response, Err(_) => { @@ -878,7 +985,10 @@ struct ForwardedBudget { messages: usize, bytes: usize, peak: usize, - outstanding: Vec, + /// 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)>, } #[derive(Default)] @@ -957,8 +1067,9 @@ impl Shared { } /// Charge a frame that is about to enter the SDK transport. The charge is - /// released by [`Self::release_forwarded`] once its response consumer runs. - fn admit_forward(&self, bytes: usize) -> Result<(), io::Error> { + /// 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 @@ -969,17 +1080,26 @@ impl Shared { } forwarded.messages += 1; forwarded.bytes += bytes; - forwarded.outstanding.push(bytes); + forwarded.outstanding.push((request_id.clone(), bytes)); forwarded.peak = forwarded.peak.max(forwarded.messages); Ok(()) } - fn release_forwarded(&self) { + /// 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(); - if let Some(bytes) = forwarded.outstanding.pop() { - forwarded.messages -= 1; - forwarded.bytes -= bytes; - } + 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 { @@ -1059,7 +1179,7 @@ impl Shared { if self.phase.load(Ordering::Acquire) == PHASE_PROMPT { self.finish_prompt(); } - self.admit_forward(line.len())?; + self.admit_forward(response.id(), line.len())?; Ok(true) } RawJsonRpcMessage::Request(request) => { @@ -1380,9 +1500,16 @@ fn leader_exited(_pid: u32) -> bool { /// Number of live (non-zombie) processes in `pgid`. /// /// Linux is checked through `/proc`, which distinguishes a zombie from a live -/// member. Elsewhere signal 0 only proves that some member is still signalable; -/// zombies may keep that true, which fails closed rather than reporting a -/// cleanup that was not observed. +/// member. A vanished entry is the only read failure that proves the process is +/// outside the group; an unreadable or unparsable entry is an error, so an +/// unknown member can never be mistaken for an empty group. Elsewhere signal 0 +/// only proves that some member is still signalable; zombies may keep that true, +/// which fails closed rather than reporting a cleanup that was not observed. +/// +/// Boundary: under a `hidepid=` mount that hides other processes, or across user +/// namespaces, `/proc` may not expose every member of the owned group. In that +/// case this function reports an error, cleanup stays unconfirmed and the +/// supervisor keeps the slot instead of claiming a group is empty. #[cfg(target_os = "linux")] fn group_members(pgid: u32) -> io::Result { let mut live = 0; @@ -1395,23 +1522,91 @@ fn group_members(pgid: u32) -> io::Result { else { continue; }; - let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else { - continue; - }; - let Some(close) = stat.rfind(')') else { - continue; - }; - let mut fields = stat[close + 1..].split_whitespace(); - let state = fields.next(); - let _parent = fields.next(); - let group = fields.next().and_then(|value| value.parse::().ok()); - if state != Some("Z") && group == Some(pgid) { + if member_of(std::fs::read(format!("/proc/{pid}/stat")), pgid)? { live += 1; } } Ok(live) } +/// Narrow classification of one `/proc//stat` read against `pgid`. +/// +/// Only `NotFound` (which includes `ESRCH` for a PID that vanished between the +/// directory scan and the read) proves the process is not a member. Every other +/// read error and every malformed stat is returned as an error. +#[cfg(target_os = "linux")] +fn member_of(stat: io::Result>, pgid: u32) -> io::Result { + match stat { + Ok(bytes) => match parse_proc_stat(&bytes) { + ProcStat::Live(group) => Ok(group == pgid), + ProcStat::Zombie => Ok(false), + ProcStat::Malformed => Err(io::Error::new( + io::ErrorKind::InvalidData, + "unparsable /proc stat", + )), + }, + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Fields needed from `/proc//stat`, parsed from raw bytes. +#[cfg(target_os = "linux")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ProcStat { + /// Field 5 (`pgrp`) of a live task. + Live(u32), + /// State `Z` (zombie) or `X` (dead): present in `/proc` but not a live + /// member of any group. + Zombie, + /// The line does not have the documented `pid (comm) state ppid pgrp` + /// prefix. This is never treated as "not a member". + Malformed, +} + +/// Parse the state and `pgrp` fields from raw `/proc//stat` bytes. +/// +/// `comm` is arbitrary bytes (non-UTF-8 and embedded `)` are both legal), so +/// the name is delimited by the first `(` and the last `)` and the remainder is +/// split as ASCII. A non-UTF-8 process name must not hide a live group member. +#[cfg(target_os = "linux")] +fn parse_proc_stat(bytes: &[u8]) -> ProcStat { + let Some(open) = bytes.iter().position(|byte| *byte == b'(') else { + return ProcStat::Malformed; + }; + let Some(close) = bytes.iter().rposition(|byte| *byte == b')') else { + return ProcStat::Malformed; + }; + if close <= open { + return ProcStat::Malformed; + } + let mut fields = bytes[close + 1..] + .split(|byte| byte.is_ascii_whitespace()) + .filter(|field| !field.is_empty()); + let Some(state) = fields.next() else { + return ProcStat::Malformed; + }; + if state.len() != 1 || !state[0].is_ascii_alphabetic() { + return ProcStat::Malformed; + } + let Some(_parent) = fields.next() else { + return ProcStat::Malformed; + }; + let Some(group) = fields.next() else { + return ProcStat::Malformed; + }; + let Some(group) = std::str::from_utf8(group) + .ok() + .and_then(|group| group.parse::().ok()) + else { + return ProcStat::Malformed; + }; + match state[0] { + b'Z' | b'X' => ProcStat::Zombie, + _ => ProcStat::Live(group), + } +} + #[cfg(all(unix, not(target_os = "linux")))] fn group_members(pgid: u32) -> io::Result { // SAFETY: signal 0 only performs an existence/permission check. @@ -1444,3 +1639,57 @@ fn signal_group(pid: u32, signal: libc::c_int) -> bool { fn signal_group(_pid: u32, _signal: libc::c_int) -> bool { false } + +/// Synthetic `/proc//stat` bytes and read-failure classification. +/// +/// These are pure byte-level checks: no process is spawned and no `/proc` write +/// is attempted. They pin the two properties cleanup depends on: a non-UTF-8 +/// `comm` cannot hide a live member, and only a vanished entry may look absent. +#[cfg(all(test, target_os = "linux"))] +mod proc_stat_tests { + use super::{ProcStat, member_of, parse_proc_stat}; + use std::io; + + #[test] + fn non_utf8_comm_is_still_a_live_member() { + let stat = b"4242 (na\xff\xfeme) S 1 4242 4242 0 -1 4194304".to_vec(); + assert_eq!(parse_proc_stat(&stat), ProcStat::Live(4242)); + assert_eq!(member_of(Ok(stat.clone()), 4242).ok(), Some(true)); + assert_eq!(member_of(Ok(stat), 7).ok(), Some(false)); + } + + #[test] + fn comm_with_parentheses_uses_the_last_delimiter() { + assert_eq!( + parse_proc_stat(b"11 (a) b) R 1 11 11 0 -1"), + ProcStat::Live(11) + ); + } + + #[test] + fn zombie_and_dead_states_are_not_live_members() { + assert_eq!(parse_proc_stat(b"9 (z) Z 1 9 9"), ProcStat::Zombie); + assert_eq!(parse_proc_stat(b"9 (x) X 1 9 9"), ProcStat::Zombie); + assert_eq!( + member_of(Ok(b"9 (z) Z 1 9 9".to_vec()), 9).ok(), + Some(false) + ); + } + + #[test] + fn vanished_entry_proves_absence() { + assert_eq!( + member_of(Err(io::Error::from(io::ErrorKind::NotFound)), 3).ok(), + Some(false) + ); + } + + #[test] + fn unreadable_or_unparsable_entry_is_unknown_not_empty() { + assert!(member_of(Err(io::Error::from(io::ErrorKind::PermissionDenied)), 3).is_err()); + assert!(member_of(Ok(b"3 (truncated".to_vec()), 3).is_err()); + assert!(member_of(Ok(b"3 (name) S 1 not-a-pid".to_vec()), 3).is_err()); + assert!(member_of(Ok(b"".to_vec()), 3).is_err()); + assert!(member_of(Ok(b"3 (name) $ 1 3 3".to_vec()), 3).is_err()); + } +} diff --git a/src/acp/mod.rs b/src/acp/mod.rs index 3006249..f0f0742 100644 --- a/src/acp/mod.rs +++ b/src/acp/mod.rs @@ -16,7 +16,7 @@ pub mod proxy; pub use config::{AcpConfigError, AcpProxyConfig}; pub use delegated_client::{ - AcpAgentCapabilities, AcpCleanupReport, AcpDelegationError, AcpDelegationLaunch, - AcpPromptResult, AcpRestoreMethod, AcpStopReason, DelegatedAcpClient, + AcpAgentCapabilities, AcpCleanupObserver, AcpCleanupReport, AcpDelegationError, + AcpDelegationLaunch, AcpPromptResult, AcpRestoreMethod, AcpStopReason, DelegatedAcpClient, }; pub use proxy::{AcpProxyError, ProxyDisposition, run_proxy}; diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs index 96bca07..e17b3e5 100644 --- a/tests/acp_delegation_client_tests.rs +++ b/tests/acp_delegation_client_tests.rs @@ -121,12 +121,18 @@ async fn connect(root: &TestRoot, args: Vec, budget: Duration) -> Dele } fn read_events(path: &Path) -> Vec { - let contents = fs::read_to_string(path).unwrap_or_default(); - contents - .lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).expect("fixture event is JSON")) - .collect() + // 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> { @@ -156,45 +162,93 @@ async fn wait_pid_gone(pid: u32) { assert!(!pid_alive(pid), "fixture process {pid} was not reaped"); } -/// Live (non-zombie) processes whose process group is `pgid`. -fn live_group_members(pgid: u32) -> Vec { - let Ok(entries) = fs::read_dir("/proc") else { - return Vec::new(); - }; - let mut members = Vec::new(); - for entry in entries.flatten() { - let Some(pid) = entry - .file_name() - .to_str() - .and_then(|name| name.parse::().ok()) - else { - continue; - }; - let Some(stat) = fs::read_to_string(format!("/proc/{pid}/stat")).ok() else { - continue; - }; - let Some(close) = stat.rfind(')') else { - continue; - }; - let fields: Vec<&str> = stat[close + 1..].split_whitespace().collect(); - let (Some(state), Some(group)) = (fields.first(), fields.get(2)) else { - continue; +/// 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; }; - if *state != "Z" && group.parse::().ok() == Some(pgid) { - members.push(pid); - } + 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" } - members } -fn assert_group_clear(pgid: u32) { - let members = live_group_members(pgid); +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!( - members.is_empty(), - "process group {pgid} still has live members at cleanup return: {members:?}" + !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"); @@ -683,7 +737,14 @@ async fn process_group_descendant_is_terminated() { OPERATION_BOUND, ) .await; - let pgid = client.pid(); + 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 @@ -692,15 +753,8 @@ async fn process_group_descendant_is_terminated() { .expect("prompt"); let cleanup = client.close().await; assert!(cleanup.cleanup_confirmed); - assert_group_clear(pgid); - let events = read_events(&root.record_path()); - let descendant = named(&events, "descendant")[0]["data"]["pid"] - .as_u64() - .expect("descendant pid") as u32; - assert!( - !live_group_members(pgid).contains(&descendant), - "the descendant is gone when cleanup returns" - ); + wait_identity_gone(descendant).await; + wait_identity_gone(leader).await; } #[tokio::test] @@ -932,7 +986,13 @@ async fn leader_exit_first_and_lingering_group_member_is_force_terminated() { OPERATION_BOUND, ) .await; - let pgid = client.pid(); + 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 @@ -950,7 +1010,11 @@ async fn leader_exit_first_and_lingering_group_member_is_force_terminated() { cleanup.forced, "a member that ignores TERM requires the forced group termination path" ); - assert_group_clear(pgid); + 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" @@ -977,7 +1041,12 @@ async fn self_exiting_group_member_is_given_a_term_grace() { OPERATION_BOUND, ) .await; - let pgid = client.pid(); + 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 @@ -986,9 +1055,167 @@ async fn self_exiting_group_member_is_given_a_term_grace() { .expect("prompt"); let cleanup = client.close().await; assert!(cleanup.cleanup_confirmed); - assert_group_clear(pgid); + 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); +} diff --git a/tests/fixtures/acp/delegation_agent.rs b/tests/fixtures/acp/delegation_agent.rs index 71c3409..d9a150a 100644 --- a/tests/fixtures/acp/delegation_agent.rs +++ b/tests/fixtures/acp/delegation_agent.rs @@ -22,6 +22,9 @@ //! - `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. @@ -62,6 +65,9 @@ struct Config { exit_after_prompt: bool, group_helper_seconds: Option, helper_marker: Option, + hang_setup: bool, + reject_first_new: bool, + fence: Option, } impl Default for Config { @@ -93,6 +99,9 @@ impl Default for Config { exit_after_prompt: false, group_helper_seconds: None, helper_marker: None, + hang_setup: false, + reject_first_new: false, + fence: None, } } } @@ -111,6 +120,7 @@ struct Harness { flood_remaining: usize, next_session: u64, next_request: u64, + new_requests: u64, } impl Harness { @@ -217,6 +227,32 @@ impl Harness { } 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); @@ -606,6 +642,9 @@ fn parse_args() -> Config { "--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}"), } } @@ -627,6 +666,7 @@ fn main() { flood_remaining: 0, next_session: 0, next_request: 0, + new_requests: 0, }; harness.record( "start", From ee2bb9213489cd78b1cb17d3f3ccda2d0ef37016 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 07:16:20 +0800 Subject: [PATCH 04/27] fix(acp): require trusted group evidence and linearize prompt publication Verify the procfs view before spawning a delegated harness: the single full procfs mount at /proc must be unrestricted (no nonzero hidepid), the process must not span nested PID namespaces, and the same mount identity plus the self PID/PGID anchor are rechecked before every group measurement. An unavailable, replaced or ambiguous view is an error, never an empty group, and delegation is refused before spawn when the view is known inadequate. Treat a Z/X thread-group leader as terminal only when the kernel reports a single thread. A top-level /proc scan lists only leaders, so a zombie leader with live siblings previously looked absent, leaving the group unkilled while cleanup kept its slot. Preserve the PGID for dead entries and never count a parsing or visibility ambiguity as nonmembership. Make prompt publication an explicit gate. Decide shutdown, the absolute deadline and a withdrawn caller wait before PreparedRequest::block_task, which enqueues synchronously: a stop that wins before publication sends neither the wire prompt nor session/cancel. After publication, claim_cancel atomically checks the serialized ingress for the matching response, so a response already claimed cannot be followed by a late cancel. Track the actual pipe writer and report written, partial, failed and merely-enqueued states separately. Align the cleanup observer contract with the supervisor: publish the confirmed report, then release the slot before task exit, and have wait_for_cleanup fence on exit. Add deterministic gates for a pre-publication stop and deadline, one cancel for an outstanding published prompt, no cancel after a claimed response, and an unconfirmed bounded close whose observer confirms later without changing the production budget. --- src/acp/delegated_client.rs | 1017 ++++++++++++++++++++++---- tests/acp_delegation_client_tests.rs | 169 ++++- 2 files changed, 1035 insertions(+), 151 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 25507db..419f3d7 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -61,8 +61,8 @@ use std::time::Duration; use agent_client_protocol::v1::schema::{ CancelNotification, ContentBlock, Implementation, InitializeRequest, LoadSessionRequest, - NewSessionRequest, PromptRequest, RequestPermissionOutcome, RequestPermissionResponse, - ResumeSessionRequest, SessionId, SessionNotification, SessionUpdate, + NewSessionRequest, PromptRequest, PromptResponse, RequestPermissionOutcome, + RequestPermissionResponse, ResumeSessionRequest, SessionId, SessionNotification, SessionUpdate, }; use agent_client_protocol::{ Agent, Client, Error as SdkError, Lines, RawJsonRpcId, RawJsonRpcMessage, RawJsonRpcParams, @@ -106,6 +106,10 @@ const MAX_HARNESS_ARGUMENT_BYTES: usize = 8 * 1024; pub enum AcpDelegationError { InvalidLaunch, SpawnFailed, + /// The kernel does not expose a procfs view that can prove the owned + /// process group is empty. Cleanup cannot be verified, so delegation is + /// refused before a child is started. + ProcfsUnsupported, DeadlineExceeded, NotInitialized, InvalidPhase, @@ -130,6 +134,7 @@ impl AcpDelegationError { match self { Self::InvalidLaunch => "acp_delegation_invalid_launch", Self::SpawnFailed => "acp_delegation_spawn_failed", + Self::ProcfsUnsupported => "acp_delegation_procfs_unsupported", Self::DeadlineExceeded => "acp_delegation_deadline", Self::NotInitialized => "acp_delegation_not_initialized", Self::InvalidPhase => "acp_delegation_invalid_phase", @@ -281,11 +286,12 @@ pub struct AcpCleanupReport { /// 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 remains the owner of the -/// process slot and publishes this report only after cleanup is proven; the -/// observer resolves later even when `close` returned unconfirmed or the client -/// was dropped. A service layer can therefore hand the caller an unconfirmed -/// result and release capacity later, in the background, from this proof. +/// `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>, @@ -294,22 +300,26 @@ pub struct AcpCleanupObserver { 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 the cleanup - /// report is published, then `0`). + /// 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 and has - /// released its slot. + /// 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). - /// Because the report is published after the capacity decision but before - /// the task exits, a `Some` value here is ordered after that decision. + /// 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. @@ -351,14 +361,20 @@ impl DelegatedAcpClient { if Instant::now() >= deadline { return Err(AcpDelegationError::DeadlineExceeded); } - let mut child = OwnedChild::spawn(&launch).map_err(|_| AcpDelegationError::SpawnFailed)?; + // Prove up front that this host exposes a procfs view capable of + // enumerating the group we are about to create. Without it cleanup can + // never be verified, so refuse to spawn rather than leak an unowned + // process tree later. + let view = ProcfsView::validate().map_err(|_| AcpDelegationError::ProcfsUnsupported)?; + let mut child = + OwnedChild::spawn(&launch, view).map_err(|_| AcpDelegationError::SpawnFailed)?; let pid = child.pid(); let (stdin, stdout) = child .take_pipes() .map_err(|_| AcpDelegationError::SpawnFailed)?; let shared = Arc::new(Shared::default()); - let wire = Arc::new(Wire::new(stdin)); + let wire = Arc::new(Wire::new(stdin, shared.clone())); let transport = bounded_lines(stdout, wire.clone(), shared.clone()); let shared_for_client = shared.clone(); let (command_tx, command_rx) = mpsc::channel(1); @@ -408,11 +424,12 @@ impl DelegatedAcpClient { .terminate(Instant::now() + Duration::from_secs(1)) .await; } - // Release the slot only once the final report exists, then publish - // it. Any observer that sees a report is therefore guaranteed to - // see the released counter when the supervisor exits. - supervisor_active.store(0, Ordering::Release); + // 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 } }); @@ -457,6 +474,16 @@ impl DelegatedAcpClient { } } + /// 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. @@ -470,6 +497,19 @@ impl DelegatedAcpClient { ) } + /// Actual pipe-writer evidence for the one prompt: `"pending"`, + /// `"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::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 { @@ -571,14 +611,27 @@ impl DelegatedAcpClient { /// 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(mut self) -> AcpCleanupReport { + 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(CLEANUP_BUDGET + CLOSE_SCHEDULING_SLACK, supervisor).await { + match timeout(wait, supervisor).await { Ok(Ok(report)) => report.cleanup, Ok(Err(_)) | Err(_) => AcpCleanupReport::unconfirmed(), } @@ -746,7 +799,9 @@ async fn run_actor( task, reply, }) => { - let result = actor.prompt(&session_id, &task, &mut shutdown).await; + let result = actor + .prompt(&session_id, &task, &mut shutdown, &reply) + .await; let _ = reply.send(result); // One prompt per connection. The supervisor now closes // stdio and verifies process cleanup. @@ -870,6 +925,7 @@ impl Actor { session_id: &str, task: &str, shutdown: &mut watch::Receiver, + reply: &oneshot::Sender>, ) -> Result { if !self.initialized { return Err(AcpDelegationError::NotInitialized); @@ -887,51 +943,95 @@ impl Actor { ); let prepared = self.connection.prepare_request(request); let request_id = prepared.raw_id().clone(); - // Bind the text phase to the exact JSON-RPC ID reserved for this - // prompt before publishing it. The serial ingress forwards only the + // Arm the exact response ID and the writer expectation while the + // request is still unpublished. The serial ingress forwards only the // response with this ID and seals the text phase at that point. self.shared.begin_prompt(session_id, request_id.clone()); - let response = tokio::select! { - _ = shutdown.changed() => { - self.cancel(session_id); + + // Publication gate (linearization point). `block_task` publishes + // synchronously: calling it enqueues the frame, so the decision to + // send must be made here, before it is called. A stop already decided, + // an expired absolute deadline, or a withdrawn caller wait forbids the + // wire prompt and therefore forbids session/cancel as well. + let expired = Instant::now() >= self.deadline; + let withdrawn = reply.is_closed(); + if expired || withdrawn || *shutdown.borrow() { + self.shared.abort_prompt(&request_id); + return Err(if expired { + AcpDelegationError::DeadlineExceeded + } else { + AcpDelegationError::Cancelled + }); + } + let mut response = Box::pin(prepared.block_task()); + // Poll once so a publication failure, which settles the response + // channel inside `block_task`, is observed before the prompt is treated + // as published. `Pending` means the frame was enqueued; the SDK's + // outgoing queue writes it before any cancel enqueued later. + let first = std::future::poll_fn(|cx| Poll::Ready(response.as_mut().poll(cx))).await; + match first { + Poll::Ready(result) => { + // Publication failed, or a response was already available. + // Either way nothing is outstanding and no cancel may follow. self.shared.clear_expected(&request_id); self.shared.release_forwarded(&request_id); self.shared.finish_prompt(); - return Err(AcpDelegationError::Cancelled); + return match result { + Ok(response) => Ok(self.finish_prompt_response(response)), + Err(_) => Err(self.failure(AcpDelegationError::PromptFailed)), + }; } - result = timeout_at(self.deadline, prepared.block_task()) => { + Poll::Pending => self.shared.mark_prompt_published(&request_id), + } + + // Post-publication arbitration. Only a prompt that won publication and + // is still outstanding at the serialized ingress may send cancel. + let outcome = tokio::select! { + _ = shutdown.changed() => Err(AcpDelegationError::Cancelled), + result = timeout_at(self.deadline, &mut response) => { match result { - Err(_) => { - self.cancel(session_id); - self.shared.clear_expected(&request_id); - self.shared.release_forwarded(&request_id); - self.shared.finish_prompt(); - return Err(AcpDelegationError::DeadlineExceeded); - } - Ok(response) => response, + Err(_) => Err(AcpDelegationError::DeadlineExceeded), + Ok(Ok(response)) => Ok(response), + Ok(Err(_)) => Err(self.failure(AcpDelegationError::PromptFailed)), } } }; - self.shared.clear_expected(&request_id); - self.shared.release_forwarded(&request_id); - let response = match response { - Ok(response) => response, - Err(_) => { + match outcome { + Ok(response) => { + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); + Ok(self.finish_prompt_response(response)) + } + Err(error @ (AcpDelegationError::Cancelled | AcpDelegationError::DeadlineExceeded)) => { + if self.shared.claim_cancel(&request_id) { + self.cancel(session_id); + } + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); self.shared.finish_prompt(); - return Err(self.failure(AcpDelegationError::PromptFailed)); + Err(error) } - }; + Err(error) => { + self.shared.clear_expected(&request_id); + self.shared.release_forwarded(&request_id); + self.shared.finish_prompt(); + Err(error) + } + } + } + + 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() }; - Ok(AcpPromptResult { + AcpPromptResult { text, truncated, stop_reason: map_stop_reason(response.stop_reason), - }) + } } fn cancel(&self, session_id: &str) { @@ -979,6 +1079,60 @@ 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 +/// that is merely enqueued from one the pipe writer fully committed, and a +/// partial/failed write from a delivered prompt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PromptWire { + /// Armed, but no outgoing `session/prompt` line has been observed yet. + Pending, + /// 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, +} + +/// Per-prompt arbitration record. `id` is the exact JSON-RPC ID reserved for +/// the one prompt, so correlation is preserved across ingress and writer. +struct PromptGate { + id: RawJsonRpcId, + /// Set only once `block_task` has published the request (it enqueues + /// synchronously). A stop that wins before this forbids the prompt. + published: bool, + /// Cleared exactly once, under this same lock, either when the serial + /// ingress claims the matching response or when this client claims the + /// right to send `session/cancel`. + outstanding: bool, + wire: PromptWire, +} + +impl PromptGate { + fn new(id: RawJsonRpcId) -> Self { + Self { + id, + published: false, + outstanding: true, + wire: PromptWire::Pending, + } + } +} + +/// Serialized ingress state: the single response ID currently forwarded to the +/// SDK plus the prompt arbitration record. Keeping both under one lock makes +/// "matching response already arrived" and "cancel may be sent" a single +/// linearizable decision instead of two racing observations. +#[derive(Default)] +struct Ingress { + expected: Option, + prompt: Option, +} + /// Frames handed to the SDK but not yet consumed by it. #[derive(Default)] struct ForwardedBudget { @@ -994,7 +1148,7 @@ struct ForwardedBudget { #[derive(Default)] struct Shared { phase: AtomicU8, - expected: Mutex>, + ingress: Mutex, session: Mutex>, text: Mutex, truncated: AtomicBool, @@ -1015,33 +1169,115 @@ impl Shared { self.text.lock().unwrap().clear(); self.truncated.store(false, Ordering::Release); *self.session.lock().unwrap() = Some(session_id.to_owned()); - // Reserving the exact response ID before publication means a matching - // response cannot be observed without an armed expected ID. - *self.expected.lock().unwrap() = Some(request_id); + let mut ingress = self.ingress.lock().unwrap(); + // Arm the exact response ID and the writer expectation 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(request_id)); self.phase.store(PHASE_PROMPT, Ordering::Release); } fn expect_response(&self, request_id: RawJsonRpcId) { - *self.expected.lock().unwrap() = Some(request_id); + self.ingress.lock().unwrap().expected = Some(request_id); } fn clear_expected(&self, request_id: &RawJsonRpcId) { - let mut expected = self.expected.lock().unwrap(); - if expected.as_ref() == Some(request_id) { - *expected = None; + let mut ingress = self.ingress.lock().unwrap(); + if ingress.expected.as_ref() == Some(request_id) { + ingress.expected = None; + } + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + { + prompt.outstanding = false; + } + } + + /// Abandon a prompt that was armed but never published. No response can + /// match it and no `session/cancel` may be sent for it. + fn abort_prompt(&self, request_id: &RawJsonRpcId) { + let mut ingress = self.ingress.lock().unwrap(); + if ingress.expected.as_ref() == Some(request_id) { + ingress.expected = None; + } + if ingress + .prompt + .as_ref() + .is_some_and(|prompt| prompt.id == *request_id) + { + ingress.prompt = None; } } + /// Publication linearization point: `block_task` has enqueued the request. + fn mark_prompt_published(&self, request_id: &RawJsonRpcId) { + let mut ingress = self.ingress.lock().unwrap(); + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + { + prompt.published = true; + } + } + + /// Record what the actual pipe writer did with the prompt frame. + fn note_prompt_wire(&self, request_id: &RawJsonRpcId, wire: PromptWire) { + let mut ingress = self.ingress.lock().unwrap(); + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + { + prompt.wire = wire; + } + } + + /// Atomically claim the right to send `session/cancel`. + /// + /// The claim wins only when publication already committed, the matching + /// response has not been claimed by the serial ingress, and the writer did + /// not report a partial/failed frame. Clearing `expected` here means a + /// response that arrives after the claim is discarded rather than mistaken + /// for a result of this cancelled turn. + fn claim_cancel(&self, request_id: &RawJsonRpcId) -> bool { + let mut ingress = self.ingress.lock().unwrap(); + let Some(prompt) = ingress.prompt.as_mut() else { + return false; + }; + if prompt.id != *request_id || !prompt.published || !prompt.outstanding { + return false; + } + if matches!(prompt.wire, PromptWire::Partial | PromptWire::Failed) { + return false; + } + prompt.outstanding = false; + ingress.expected = None; + true + } + + fn prompt_wire(&self) -> Option { + self.ingress + .lock() + .unwrap() + .prompt + .as_ref() + .map(|prompt| prompt.wire) + } + /// Claim the expected response ID. Only the first response with exactly - /// this typed ID (string and number forms differ) is forwarded. + /// 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. fn take_expected(&self, request_id: &RawJsonRpcId) -> bool { - let mut expected = self.expected.lock().unwrap(); - if expected.as_ref() == Some(request_id) { - *expected = None; - true - } else { - false + let mut ingress = self.ingress.lock().unwrap(); + if ingress.expected.as_ref() != Some(request_id) { + return false; + } + ingress.expected = None; + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id + { + prompt.outstanding = false; } + true } fn finish_prompt(&self) { @@ -1219,22 +1455,94 @@ impl Shared { /// /// Whole lines are written under one lock so protocol responses authored at the /// ingress boundary never interleave with SDK frames. Peer text is never echoed. +/// The writer also reports the actual prompt frame outcome, because SDK +/// publication only enqueues a request and is not proof that its bytes reached +/// the child. struct Wire { stdin: tokio::sync::Mutex, + shared: Arc, } impl Wire { - fn new(stdin: ChildStdin) -> Self { + fn new(stdin: ChildStdin, shared: Arc) -> Self { Self { stdin: tokio::sync::Mutex::new(stdin), + shared, } } async fn write_line(&self, line: &str) -> io::Result<()> { + let prompt_id = prompt_request_id(line); let mut stdin = self.stdin.lock().await; - stdin.write_all(line.as_bytes()).await?; - stdin.write_all(b"\n").await?; - stdin.flush().await + let (result, wire) = if prompt_id.is_some() { + write_prompt_frame(&mut stdin, line).await + } else { + let result = match stdin.write_all(line.as_bytes()).await { + Ok(()) => match stdin.write_all(b"\n").await { + Ok(()) => stdin.flush().await, + Err(error) => Err(error), + }, + Err(error) => Err(error), + }; + (result, PromptWire::Pending) + }; + drop(stdin); + if let Some(request_id) = prompt_id.as_ref() { + self.shared.note_prompt_wire(request_id, wire); + } + result + } +} + +/// The prompt request carried by an already-serialized outgoing line, if any. +fn prompt_request_id(line: &str) -> Option { + match serde_json::from_str::(line) { + Ok(RawJsonRpcMessage::Request(request)) if request.method.as_ref() == "session/prompt" => { + Some(request.id) + } + _ => None, + } +} + +/// Write one prompt frame while counting how much of the line reached the pipe. +/// +/// `write_all` cannot distinguish a failed first write from a truncated one, so +/// this loop keeps the byte count and reports partial vs no-send separately. +async fn write_prompt_frame(stdin: &mut ChildStdin, line: &str) -> (io::Result<()>, PromptWire) { + let bytes = line.as_bytes(); + let mut written = 0usize; + while written < bytes.len() { + match stdin.write(&bytes[written..]).await { + Ok(0) => { + return ( + Err(io::Error::from(io::ErrorKind::WriteZero)), + if written == 0 { + PromptWire::Failed + } else { + PromptWire::Partial + }, + ); + } + Ok(count) => written += count, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => { + return ( + Err(error), + if written == 0 { + PromptWire::Failed + } else { + PromptWire::Partial + }, + ); + } + } + } + if let Err(error) = stdin.write_all(b"\n").await { + return (Err(error), PromptWire::Partial); + } + match stdin.flush().await { + Ok(()) => (Ok(()), PromptWire::Written), + Err(error) => (Err(error), PromptWire::Partial), } } @@ -1331,10 +1639,13 @@ struct OwnedChild { child: Child, pid: u32, reaped: bool, + /// The procfs view admitted before spawn and rechecked before every group + /// measurement and before cleanup is claimed. + view: ProcfsView, } impl OwnedChild { - fn spawn(launch: &AcpDelegationLaunch) -> io::Result { + fn spawn(launch: &AcpDelegationLaunch, view: ProcfsView) -> io::Result { let mut command = Command::new(launch.command()); command .args(launch.arguments()) @@ -1362,6 +1673,7 @@ impl OwnedChild { child, pid, reaped: false, + view, }) } @@ -1400,13 +1712,15 @@ impl OwnedChild { } // Members that outlive the leader are still in the owned group while the - // leader is unreaped, so the group identity is safe to use. - let mut group = group_members(self.pid); + // leader is unreaped, so the group identity is safe to use. Every + // measurement revalidates the procfs view first; an unknown view is an + // error, never "empty". + let mut group = group_members(self.pid, &self.view); if !matches!(group, Ok(0)) { group_signal_sent |= signal_group(self.pid, libc::SIGTERM); let term_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline); loop { - group = group_members(self.pid); + group = group_members(self.pid, &self.view); if matches!(group, Ok(0)) || Instant::now() >= term_deadline { break; } @@ -1417,7 +1731,7 @@ impl OwnedChild { group_signal_sent |= signal_group(self.pid, libc::SIGKILL); forced = true; loop { - group = group_members(self.pid); + group = group_members(self.pid, &self.view); if matches!(group, Ok(0)) || Instant::now() >= deadline { break; } @@ -1425,6 +1739,9 @@ impl OwnedChild { } } + // The final empty reading already revalidated the same view that was + // admitted before spawn. A view that changed underneath us reports an + // error and keeps cleanup unconfirmed. let group_clear = matches!(group, Ok(0)); // Reap only after the group is proven empty. Until then the unreaped // leader is retained as the group identity anchor for a later retry. @@ -1497,22 +1814,183 @@ fn leader_exited(_pid: u32) -> bool { false } -/// Number of live (non-zombie) processes in `pgid`. +/// Verified, reusable view of the procfs mount used for group enumeration. /// -/// Linux is checked through `/proc`, which distinguishes a zombie from a live -/// member. A vanished entry is the only read failure that proves the process is -/// outside the group; an unreadable or unparsable entry is an error, so an -/// unknown member can never be mistaken for an empty group. Elsewhere signal 0 -/// only proves that some member is still signalable; zombies may keep that true, -/// which fails closed rather than reporting a cleanup that was not observed. +/// A procfs mount can fail to show every member of the group we own: `hidepid=` +/// can hide processes that changed credentials, and a procfs mounted from a +/// different PID namespace reports that namespace's PID/PGID values. An absent +/// `/proc/` entry therefore only proves absence when the same, verified +/// view was used for the directory scan and for reading each entry. /// -/// Boundary: under a `hidepid=` mount that hides other processes, or across user -/// namespaces, `/proc` may not expose every member of the owned group. In that -/// case this function reports an error, cleanup stays unconfirmed and the -/// supervisor keeps the slot instead of claiming a group is empty. +/// `validate` is called before spawn so an unsuitable host is rejected before +/// any process exists. `revalidate` runs before every measurement and before +/// cleanup is claimed, and also pins the mount identity (`major:minor` and mount +/// ID) so a mount replaced underneath us is an error, never an empty group. +#[derive(Debug, Clone)] +struct ProcfsView { + #[cfg(target_os = "linux")] + anchor: ProcMountAnchor, +} + +impl ProcfsView { + #[cfg(target_os = "linux")] + fn validate() -> io::Result { + let mountinfo = std::fs::read("/proc/self/mountinfo")?; + let anchor = parse_proc_mountinfo(&mountinfo)?; + let status = std::fs::read("/proc/self/status")?; + if parse_nspid_status(&status)? != 1 { + return Err(io::Error::other("procfs view spans nested pid namespaces")); + } + check_self_anchor()?; + Ok(Self { anchor }) + } + + #[cfg(not(target_os = "linux"))] + fn validate() -> io::Result { + Ok(Self {}) + } + + #[cfg(target_os = "linux")] + fn revalidate(&self) -> io::Result<()> { + let mountinfo = std::fs::read("/proc/self/mountinfo")?; + let current = parse_proc_mountinfo(&mountinfo)?; + if current != self.anchor { + return Err(io::Error::other("procfs mount changed during ownership")); + } + let status = std::fs::read("/proc/self/status")?; + if parse_nspid_status(&status)? != 1 { + return Err(io::Error::other("procfs view spans nested pid namespaces")); + } + check_self_anchor() + } + + #[cfg(not(target_os = "linux"))] + fn revalidate(&self) -> io::Result<()> { + Ok(()) + } +} + +/// Mount identity admitted before spawn. `mount_id` and `device` make a +/// replacement or bind mount of another procfs visible to `revalidate`. #[cfg(target_os = "linux")] -fn group_members(pgid: u32) -> io::Result { - let mut live = 0; +#[derive(Debug, Clone, PartialEq, Eq)] +struct ProcMountAnchor { + mount_id: u64, + device: String, +} + +/// Locate the single full procfs mount at `/proc` and reject any visibility +/// restriction. Parses `/proc/self/mountinfo` bytes directly so the same logic +/// is exercised by synthetic unit tests. +#[cfg(target_os = "linux")] +fn parse_proc_mountinfo(bytes: &[u8]) -> io::Result { + let text = std::str::from_utf8(bytes).map_err(|_| io::Error::other("mountinfo encoding"))?; + let mut found: Option = None; + for line in text.lines() { + let fields: Vec<&str> = line.split(' ').collect(); + if fields.len() < 10 { + continue; + } + // mountinfo: id parent major:minor root mount-point options ... - fstype source super-options + if fields[4] != "/proc" || fields[3] != "/" { + continue; + } + let Some(dash) = fields.iter().position(|field| *field == "-") else { + return Err(io::Error::other("mountinfo separator")); + }; + if dash + 3 >= fields.len() { + return Err(io::Error::other("mountinfo fields")); + } + if fields[dash + 1] != "proc" { + return Err(io::Error::other("not a procfs mount at /proc")); + } + if !hidepid_unrestricted(fields[5]) || !hidepid_unrestricted(fields[dash + 3]) { + return Err(io::Error::other("procfs visibility is restricted")); + } + let mount_id = fields[0] + .parse::() + .map_err(|_| io::Error::other("mountinfo id"))?; + let device = fields[2].to_owned(); + if found.is_some() { + return Err(io::Error::other("ambiguous /proc mount")); + } + found = Some(ProcMountAnchor { mount_id, device }); + } + found.ok_or_else(|| io::Error::other("no procfs mount at /proc")) +} + +#[cfg(target_os = "linux")] +fn hidepid_unrestricted(options: &str) -> bool { + for option in options.split(',') { + if let Some(value) = option.strip_prefix("hidepid=") + && value != "0" + { + return false; + } + } + true +} + +/// Number of PIDs listed by `/proc/self/status`'s `NSpid` field. One value +/// means this process is not a member of any namespace nested below the procfs +/// mount's namespace, so the same view enumerates children we spawn without +/// privileges beyond reading our own status. +#[cfg(target_os = "linux")] +fn parse_nspid_status(bytes: &[u8]) -> io::Result { + let text = std::str::from_utf8(bytes).map_err(|_| io::Error::other("status encoding"))?; + for line in text.lines() { + let Some(rest) = line.strip_prefix("NSpid:") else { + continue; + }; + let mut count = 0; + for value in rest.split_whitespace() { + value + .parse::() + .map_err(|_| io::Error::other("NSpid value"))?; + count += 1; + } + if count == 0 { + return Err(io::Error::other("empty NSpid")); + } + return Ok(count); + } + Err(io::Error::other("missing NSpid")) +} + +/// Confirm the selected `/proc` view sees this process with the PID and PGID +/// the kernel reports to us. This rejects a procfs mounted from a different +/// namespace even when NSpid alone is inconclusive. +#[cfg(target_os = "linux")] +fn check_self_anchor() -> io::Result<()> { + let stat = std::fs::read("/proc/self/stat")?; + let fields = + parse_stat_fields(&stat).ok_or_else(|| io::Error::other("unparsable self stat"))?; + if fields.pid != std::process::id() { + return Err(io::Error::other("procfs pid namespace mismatch")); + } + // SAFETY: `getpgrp` has no preconditions and only reads process state. + let pgrp = unsafe { libc::getpgrp() }; + if fields.pgrp != pgrp as u32 { + return Err(io::Error::other("procfs process-group mismatch")); + } + Ok(()) +} + +/// Number of group members that can still run. +/// +/// Linux is checked through the verified procfs view. A `Z`/`X` thread-group +/// leader counts as present while the kernel reports more than one thread in +/// its group: the leader can be a zombie while sibling threads are still live, +/// and a top-level `/proc` scan only lists leaders. A vanished entry is the +/// only read failure that proves the process is outside the group; unreadable, +/// restricted or unparsable entries are errors, so an unknown member is never +/// mistaken for an empty group. Elsewhere signal 0 only proves that some member +/// is still signalable; zombies may keep that true, which fails closed rather +/// than reporting a cleanup that was not observed. +#[cfg(target_os = "linux")] +fn group_members(pgid: u32, view: &ProcfsView) -> io::Result { + view.revalidate()?; + let mut present = 0; for entry in std::fs::read_dir("/proc")? { let entry = entry?; let Some(pid) = entry @@ -1523,10 +2001,14 @@ fn group_members(pgid: u32) -> io::Result { continue; }; if member_of(std::fs::read(format!("/proc/{pid}/stat")), pgid)? { - live += 1; + present += 1; } } - Ok(live) + // Fence the scan: a mount replaced between the directory read and the + // entry reads must invalidate the count instead of reporting an empty + // group. The same verified view has to be in effect for the whole scan. + view.revalidate()?; + Ok(present) } /// Narrow classification of one `/proc//stat` read against `pgid`. @@ -1537,78 +2019,92 @@ fn group_members(pgid: u32) -> io::Result { #[cfg(target_os = "linux")] fn member_of(stat: io::Result>, pgid: u32) -> io::Result { match stat { - Ok(bytes) => match parse_proc_stat(&bytes) { - ProcStat::Live(group) => Ok(group == pgid), - ProcStat::Zombie => Ok(false), - ProcStat::Malformed => Err(io::Error::new( - io::ErrorKind::InvalidData, - "unparsable /proc stat", - )), - }, + Ok(bytes) => { + let Some(fields) = parse_stat_fields(&bytes) else { + return Err(io::Error::other("unparsable /proc stat")); + }; + Ok(counts_as_present(fields, pgid)) + } Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), Err(error) => Err(error), } } +#[cfg(target_os = "linux")] +fn counts_as_present(fields: StatFields, pgid: u32) -> bool { + if fields.pgrp != pgid { + return false; + } + match fields.state { + // Terminal only when the leader is the last thread left. + b'Z' | b'X' => fields.num_threads > 1, + _ => true, + } +} + /// Fields needed from `/proc//stat`, parsed from raw bytes. #[cfg(target_os = "linux")] #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ProcStat { - /// Field 5 (`pgrp`) of a live task. - Live(u32), - /// State `Z` (zombie) or `X` (dead): present in `/proc` but not a live - /// member of any group. - Zombie, - /// The line does not have the documented `pid (comm) state ppid pgrp` - /// prefix. This is never treated as "not a member". - Malformed, +struct StatFields { + pid: u32, + state: u8, + /// Field 5 (`pgrp`), preserved for `Z`/`X` entries. + pgrp: u32, + /// Field 20 (`num_threads`); counts every thread in the group, including a + /// zombie leader, so `1` means no sibling threads remain. + num_threads: u32, } -/// Parse the state and `pgrp` fields from raw `/proc//stat` bytes. +/// Parse `/proc//stat` from raw bytes. /// /// `comm` is arbitrary bytes (non-UTF-8 and embedded `)` are both legal), so /// the name is delimited by the first `(` and the last `)` and the remainder is -/// split as ASCII. A non-UTF-8 process name must not hide a live group member. +/// split as ASCII. A non-UTF-8 process name must not hide a live group member, +/// and a truncated line is malformed rather than absent. #[cfg(target_os = "linux")] -fn parse_proc_stat(bytes: &[u8]) -> ProcStat { - let Some(open) = bytes.iter().position(|byte| *byte == b'(') else { - return ProcStat::Malformed; - }; - let Some(close) = bytes.iter().rposition(|byte| *byte == b')') else { - return ProcStat::Malformed; - }; +fn parse_stat_fields(bytes: &[u8]) -> Option { + let open = bytes.iter().position(|byte| *byte == b'(')?; + let close = bytes.iter().rposition(|byte| *byte == b')')?; if close <= open { - return ProcStat::Malformed; + return None; } + let pid = std::str::from_utf8(&bytes[..open]) + .ok()? + .trim() + .parse::() + .ok()?; let mut fields = bytes[close + 1..] .split(|byte| byte.is_ascii_whitespace()) .filter(|field| !field.is_empty()); - let Some(state) = fields.next() else { - return ProcStat::Malformed; - }; + let state = fields.next()?; if state.len() != 1 || !state[0].is_ascii_alphabetic() { - return ProcStat::Malformed; - } - let Some(_parent) = fields.next() else { - return ProcStat::Malformed; - }; - let Some(group) = fields.next() else { - return ProcStat::Malformed; - }; - let Some(group) = std::str::from_utf8(group) - .ok() - .and_then(|group| group.parse::().ok()) - else { - return ProcStat::Malformed; - }; - match state[0] { - b'Z' | b'X' => ProcStat::Zombie, - _ => ProcStat::Live(group), - } + return None; + } + let _parent = fields.next()?; + let pgrp = parse_stat_u32(fields.next()?)?; + // Fields 6..=19 (session .. nice); field 20 is num_threads. + for _ in 0..14 { + fields.next()?; + } + let num_threads = parse_stat_u32(fields.next()?)?; + if num_threads == 0 { + return None; + } + Some(StatFields { + pid, + state: state[0], + pgrp, + num_threads, + }) +} + +#[cfg(target_os = "linux")] +fn parse_stat_u32(field: &[u8]) -> Option { + std::str::from_utf8(field).ok()?.parse::().ok() } #[cfg(all(unix, not(target_os = "linux")))] -fn group_members(pgid: u32) -> io::Result { +fn group_members(pgid: u32, _view: &ProcfsView) -> io::Result { // SAFETY: signal 0 only performs an existence/permission check. let result = unsafe { libc::kill(-(pgid as libc::pid_t), 0) }; if result == 0 { @@ -1624,7 +2120,7 @@ fn group_members(pgid: u32) -> io::Result { } #[cfg(not(unix))] -fn group_members(_pgid: u32) -> io::Result { +fn group_members(_pgid: u32, _view: &ProcfsView) -> io::Result { Ok(0) } @@ -1640,42 +2136,121 @@ fn signal_group(_pid: u32, _signal: libc::c_int) -> bool { false } -/// Synthetic `/proc//stat` bytes and read-failure classification. +/// Synthetic procfs bytes and the per-prompt arbitration state machine. /// -/// These are pure byte-level checks: no process is spawned and no `/proc` write -/// is attempted. They pin the two properties cleanup depends on: a non-UTF-8 -/// `comm` cannot hide a live member, and only a vanished entry may look absent. +/// These are pure byte/state checks: no process is spawned and no `/proc` write +/// is attempted. They pin what cleanup and cancellation depend on: only an +/// admitted, trusted view may report an empty group; a zombie leader is terminal +/// only when its thread group has no siblings left; and a matching response that +/// already reached the serial ingress forbids a late `session/cancel`. #[cfg(all(test, target_os = "linux"))] -mod proc_stat_tests { - use super::{ProcStat, member_of, parse_proc_stat}; +mod linux_evidence_tests { + use super::{ + ProcMountAnchor, PromptWire, Shared, StatFields, counts_as_present, member_of, + parse_nspid_status, parse_proc_mountinfo, parse_stat_fields, + }; + use agent_client_protocol::RawJsonRpcId; use std::io; + /// Fields after `comm`: state, ppid, pgrp, fields 6..=19, then num_threads. + fn tail(state: u8, pgrp: u32, threads: u32) -> String { + let mut fields = vec![ + (state as char).to_string(), + "1".to_owned(), + pgrp.to_string(), + ]; + for _ in 0..14 { + fields.push("0".to_owned()); + } + fields.push(threads.to_string()); + fields.push("0".to_owned()); + fields.join(" ") + } + + fn stat_line(pid: u32, comm: &str, state: u8, pgrp: u32, threads: u32) -> Vec { + format!("{pid} ({comm}) {}", tail(state, pgrp, threads)).into_bytes() + } + #[test] fn non_utf8_comm_is_still_a_live_member() { - let stat = b"4242 (na\xff\xfeme) S 1 4242 4242 0 -1 4194304".to_vec(); - assert_eq!(parse_proc_stat(&stat), ProcStat::Live(4242)); + let mut stat = b"4242 (na".to_vec(); + stat.extend_from_slice(b"\xff\xfe"); + stat.extend_from_slice(b"me) "); + stat.extend_from_slice(tail(b'S', 4242, 1).as_bytes()); + assert_eq!( + parse_stat_fields(&stat), + Some(StatFields { + pid: 4242, + state: b'S', + pgrp: 4242, + num_threads: 1, + }) + ); assert_eq!(member_of(Ok(stat.clone()), 4242).ok(), Some(true)); assert_eq!(member_of(Ok(stat), 7).ok(), Some(false)); } #[test] fn comm_with_parentheses_uses_the_last_delimiter() { + let stat = format!("11 (a) b) {}", tail(b'R', 11, 1)).into_bytes(); + assert_eq!(parse_stat_fields(&stat).map(|fields| fields.pgrp), Some(11)); + } + + #[test] + fn zombie_leader_with_sibling_threads_is_retained() { + // A top-level /proc scan only lists thread-group leaders. A zombie + // leader with num_threads > 1 still has live siblings in the group. + for state in [b'Z', b'X'] { + assert!( + member_of(Ok(stat_line(9, "leader", state, 9, 2)), 9).ok() == Some(true), + "state {} with siblings must keep the group non-empty", + state as char + ); + } + } + + #[test] + fn zombie_leader_alone_is_terminal() { + for state in [b'Z', b'X'] { + assert_eq!( + member_of(Ok(stat_line(9, "leader", state, 9, 1)), 9).ok(), + Some(false) + ); + } + } + + #[test] + fn zombie_leader_of_another_group_is_not_counted() { assert_eq!( - parse_proc_stat(b"11 (a) b) R 1 11 11 0 -1"), - ProcStat::Live(11) + member_of(Ok(stat_line(9, "leader", b'Z', 4, 5)), 9).ok(), + Some(false) ); } #[test] - fn zombie_and_dead_states_are_not_live_members() { - assert_eq!(parse_proc_stat(b"9 (z) Z 1 9 9"), ProcStat::Zombie); - assert_eq!(parse_proc_stat(b"9 (x) X 1 9 9"), ProcStat::Zombie); + fn live_leader_is_member_regardless_of_threads() { assert_eq!( - member_of(Ok(b"9 (z) Z 1 9 9".to_vec()), 9).ok(), + member_of(Ok(stat_line(9, "live", b'S', 9, 5)), 9).ok(), + Some(true) + ); + assert_eq!( + member_of(Ok(stat_line(9, "live", b'S', 7, 5)), 9).ok(), Some(false) ); } + #[test] + fn counts_as_present_preserves_pgid_for_dead_entries() { + let fields = StatFields { + pid: 9, + state: b'Z', + pgrp: 9, + num_threads: 3, + }; + assert!(counts_as_present(fields, 9)); + assert!(!counts_as_present(fields, 8)); + } + #[test] fn vanished_entry_proves_absence() { assert_eq!( @@ -1689,7 +2264,149 @@ mod proc_stat_tests { assert!(member_of(Err(io::Error::from(io::ErrorKind::PermissionDenied)), 3).is_err()); assert!(member_of(Ok(b"3 (truncated".to_vec()), 3).is_err()); assert!(member_of(Ok(b"3 (name) S 1 not-a-pid".to_vec()), 3).is_err()); - assert!(member_of(Ok(b"".to_vec()), 3).is_err()); + assert!(member_of(Ok(Vec::new()), 3).is_err()); assert!(member_of(Ok(b"3 (name) $ 1 3 3".to_vec()), 3).is_err()); + // A real /proc stat always has field 20; a short line is ambiguous, + // never "not a member". + assert!(member_of(Ok(b"3 (name) S 1 3 3".to_vec()), 3).is_err()); + assert!(member_of(Ok(stat_line(3, "name", b'Z', 3, 0)), 3).is_err()); + } + + fn mount_line(id: u64, root: &str, options: &str, fstype: &str, super_options: &str) -> String { + format!("{id} 29 0:23 {root} /proc {options} shared:12 - {fstype} proc {super_options}") + } + + #[test] + fn unrestricted_proc_mount_is_admitted() { + let bytes = mount_line(25, "/", "rw,nosuid,nodev,noexec,relatime", "proc", "rw"); + assert_eq!( + parse_proc_mountinfo(bytes.as_bytes()).ok(), + Some(ProcMountAnchor { + mount_id: 25, + device: "0:23".to_owned(), + }) + ); + let explicit_zero = mount_line(25, "/", "rw", "proc", "rw,hidepid=0"); + assert!(parse_proc_mountinfo(explicit_zero.as_bytes()).is_ok()); + } + + #[test] + fn restriction_anywhere_is_rejected() { + for line in [ + mount_line(25, "/", "rw,hidepid=2", "proc", "rw"), + mount_line(25, "/", "rw", "proc", "rw,hidepid=1"), + mount_line(25, "/", "rw", "proc", "rw,hidepid=invisible"), + ] { + assert!( + parse_proc_mountinfo(line.as_bytes()).is_err(), + "restricted mount must be rejected: {line}" + ); + } + } + + #[test] + fn non_procfs_subtree_or_missing_mount_is_rejected() { + assert!(parse_proc_mountinfo(mount_line(25, "/", "rw", "tmpfs", "rw").as_bytes()).is_err()); + assert!( + parse_proc_mountinfo(mount_line(25, "/sub", "rw", "proc", "rw").as_bytes()).is_err() + ); + assert!(parse_proc_mountinfo(b"25 29 0:23 / /proc/sys rw - proc proc rw\n").is_err()); + } + + #[test] + fn ambiguous_duplicate_proc_mounts_are_rejected() { + let mut bytes = mount_line(25, "/", "rw", "proc", "rw"); + bytes.push('\n'); + bytes.push_str(&mount_line(26, "/", "rw", "proc", "rw")); + assert!(parse_proc_mountinfo(bytes.as_bytes()).is_err()); + } + + #[test] + fn single_level_nspid_is_admitted() { + assert_eq!( + parse_nspid_status(b"Name:\tfixture\nNSpid:\t123\n").ok(), + Some(1) + ); + } + + #[test] + fn nested_or_invalid_nspid_is_rejected() { + assert_eq!(parse_nspid_status(b"NSpid:\t123\t45\n").ok(), Some(2)); + assert!(parse_nspid_status(b"NSpid:\n").is_err()); + assert!(parse_nspid_status(b"NSpid:\tabc\n").is_err()); + assert!(parse_nspid_status(b"Name:\tfixture\n").is_err()); + } + + fn prompt_id() -> RawJsonRpcId { + RawJsonRpcId::Number(7) + } + + #[test] + fn cancel_requires_publication_and_stays_single_use() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + assert!( + !shared.claim_cancel(&id), + "unpublished prompt cannot cancel" + ); + shared.mark_prompt_published(&id); + assert!( + shared.claim_cancel(&id), + "published outstanding prompt may cancel" + ); + assert!( + !shared.claim_cancel(&id), + "a cancel is claimed at most once" + ); + } + + #[test] + fn matching_response_claimed_before_cancel_refuses_late_cancel() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + shared.mark_prompt_published(&id); + assert!( + shared.take_expected(&id), + "the ingress claims the response id" + ); + assert!( + !shared.claim_cancel(&id), + "a response already claimed by the serial ingress forbids session/cancel" + ); + } + + #[test] + fn partial_or_failed_write_refuses_cancel() { + for wire in [PromptWire::Partial, PromptWire::Failed] { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + shared.mark_prompt_published(&id); + shared.note_prompt_wire(&id, wire); + assert!( + !shared.claim_cancel(&id), + "a frame that did not fully reach the pipe cannot be cancelled" + ); + } + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + shared.mark_prompt_published(&id); + shared.note_prompt_wire(&id, PromptWire::Written); + assert!(shared.claim_cancel(&id)); + } + + #[test] + fn aborted_prompt_never_cancels() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + shared.abort_prompt(&id); + assert!(!shared.claim_cancel(&id)); + // Even a stray publication mark cannot revive an aborted prompt. + shared.mark_prompt_published(&id); + assert!(!shared.claim_cancel(&id)); } } diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs index e17b3e5..68bc803 100644 --- a/tests/acp_delegation_client_tests.rs +++ b/tests/acp_delegation_client_tests.rs @@ -272,6 +272,11 @@ async fn new_session_returns_peer_id_and_one_new_request() { 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"); @@ -288,6 +293,11 @@ async fn new_session_returns_peer_id_and_one_new_request() { 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!( @@ -641,12 +651,15 @@ async fn dropping_the_client_hands_cleanup_to_the_owned_supervisor() { 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:?}"), - _ = tokio::time::sleep(Duration::from_millis(250)) => {} + // 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); @@ -1219,3 +1232,157 @@ async fn abandoned_setup_wait_does_not_leak_ingress_quota() { 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" + ); +} + +#[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; +} From 9d5bea9486546bbb615d1b52f302854fbcf7f108 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 08:14:08 +0800 Subject: [PATCH 05/27] fix(acp): prove group absence in the kernel and arbitrate prompts at the wire Replace the procfs group census with a waitid(WNOWAIT) proof: signal the owned group only while the direct leader is still our unreaped child, reap exactly that child, and confirm absence only when signal 0 reports ESRCH for the original group. A lagging member or a reused group number keeps capacity retained, and a host with untrustworthy waitid/kill semantics is rejected before spawn. Move prompt publication to the bounded stdio writer. One arbitration record orders shutdown, the deadline, caller withdrawal, the first written byte, the completed frame and the matching ingress response. A frame discarded before any byte sends neither cancellation method; a complete outstanding prompt gets at most one session/cancel; a partial line poisons the connection; and the SDK's deferred $/cancel_request for the reserved prompt id is suppressed at the wire. --- src/acp/delegated_client.rs | 1904 +++++++++++++++----------- tests/acp_delegation_client_tests.rs | 15 + 2 files changed, 1112 insertions(+), 807 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 419f3d7..1b30b07 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -11,10 +11,16 @@ //! 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. While the direct leader is still -//! owned and unreaped, the supervisor terminates the whole group and confirms -//! that no live member remains; only then is the leader reaped. A cached PID -//! is never signalled after the leader has been reaped; +//! - 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 @@ -26,9 +32,13 @@ //! 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. Only a prompt that was actually published attempts `session/cancel`. -//! Protocol draining gets a small slice of the single absolute cleanup budget -//! so process reaping keeps the remainder; +//! 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` @@ -106,10 +116,10 @@ const MAX_HARNESS_ARGUMENT_BYTES: usize = 8 * 1024; pub enum AcpDelegationError { InvalidLaunch, SpawnFailed, - /// The kernel does not expose a procfs view that can prove the owned - /// process group is empty. Cleanup cannot be verified, so delegation is - /// refused before a child is started. - ProcfsUnsupported, + /// 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, @@ -134,7 +144,7 @@ impl AcpDelegationError { match self { Self::InvalidLaunch => "acp_delegation_invalid_launch", Self::SpawnFailed => "acp_delegation_spawn_failed", - Self::ProcfsUnsupported => "acp_delegation_procfs_unsupported", + Self::CleanupUnsupported => "acp_delegation_cleanup_unsupported", Self::DeadlineExceeded => "acp_delegation_deadline", Self::NotInitialized => "acp_delegation_not_initialized", Self::InvalidPhase => "acp_delegation_invalid_phase", @@ -276,9 +286,12 @@ 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 had no live, non-zombie member at the final - /// check, taken while the direct leader was still unreaped. + /// 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, } @@ -361,24 +374,25 @@ impl DelegatedAcpClient { if Instant::now() >= deadline { return Err(AcpDelegationError::DeadlineExceeded); } - // Prove up front that this host exposes a procfs view capable of - // enumerating the group we are about to create. Without it cleanup can - // never be verified, so refuse to spawn rather than leak an unowned - // process tree later. - let view = ProcfsView::validate().map_err(|_| AcpDelegationError::ProcfsUnsupported)?; - let mut child = - OwnedChild::spawn(&launch, view).map_err(|_| AcpDelegationError::SpawnFailed)?; + // 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(AcpDelegationError::CleanupUnsupported); + } + let mut child = OwnedChild::spawn(&launch).map_err(|_| AcpDelegationError::SpawnFailed)?; let pid = child.pid(); let (stdin, stdout) = child .take_pipes() .map_err(|_| AcpDelegationError::SpawnFailed)?; - let shared = Arc::new(Shared::default()); + 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(stdin, shared.clone())); let transport = bounded_lines(stdout, wire.clone(), shared.clone()); let shared_for_client = shared.clone(); - let (command_tx, command_rx) = mpsc::channel(1); - let (shutdown_tx, shutdown_rx) = watch::channel(false); let (proof_tx, proof_rx) = watch::channel(None); let active = Arc::new(AtomicUsize::new(1)); let supervisor_active = active.clone(); @@ -393,9 +407,18 @@ impl DelegatedAcpClient { .name("rustscript-agent-delegation") .connect_with(transport, { let shared = shared.clone(); + let wire = wire.clone(); async move |connection| { - run_actor(connection, command_rx, shared, cwd, deadline, shutdown_rx) - .await + run_actor( + connection, + command_rx, + shared, + wire, + cwd, + deadline, + shutdown_rx, + ) + .await } }), ); @@ -498,12 +521,13 @@ impl DelegatedAcpClient { } /// Actual pipe-writer evidence for the one prompt: `"pending"`, - /// `"written"`, `"partial"`, `"failed"`, or `None` when no prompt was - /// armed. SDK publication alone is never reported as `"written"`. + /// `"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", @@ -720,6 +744,7 @@ enum ActorCommand { struct Actor { connection: agent_client_protocol::v1::ConnectionTo, shared: Arc, + wire: Arc, cwd: PathBuf, deadline: Instant, initialized: bool, @@ -732,6 +757,7 @@ async fn run_actor( connection: agent_client_protocol::v1::ConnectionTo, mut commands: mpsc::Receiver, shared: Arc, + wire: Arc, cwd: PathBuf, deadline: Instant, mut shutdown: watch::Receiver, @@ -739,6 +765,7 @@ async fn run_actor( let mut actor = Actor { connection, shared, + wire, cwd, deadline, initialized: false, @@ -937,85 +964,94 @@ impl Actor { return Err(AcpDelegationError::SessionMismatch); } self.prompted = true; - 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 expectation while the - // request is still unpublished. The serial ingress forwards only the - // response with this ID and seals the text phase at that point. - self.shared.begin_prompt(session_id, request_id.clone()); - // Publication gate (linearization point). `block_task` publishes - // synchronously: calling it enqueues the frame, so the decision to - // send must be made here, before it is called. A stop already decided, - // an expired absolute deadline, or a withdrawn caller wait forbids the - // wire prompt and therefore forbids session/cancel as well. + // 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() { - self.shared.abort_prompt(&request_id); 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()); - // Poll once so a publication failure, which settles the response - // channel inside `block_task`, is observed before the prompt is treated - // as published. `Pending` means the frame was enqueued; the SDK's - // outgoing queue writes it before any cancel enqueued later. - let first = std::future::poll_fn(|cx| Poll::Ready(response.as_mut().poll(cx))).await; - match first { - Poll::Ready(result) => { - // Publication failed, or a response was already available. - // Either way nothing is outstanding and no cancel may follow. - self.shared.clear_expected(&request_id); - self.shared.release_forwarded(&request_id); - self.shared.finish_prompt(); - return match result { - Ok(response) => Ok(self.finish_prompt_response(response)), - Err(_) => Err(self.failure(AcpDelegationError::PromptFailed)), - }; - } - Poll::Pending => self.shared.mark_prompt_published(&request_id), - } - - // Post-publication arbitration. Only a prompt that won publication and - // is still outstanding at the serialized ingress may send cancel. - let outcome = tokio::select! { - _ = shutdown.changed() => Err(AcpDelegationError::Cancelled), - result = timeout_at(self.deadline, &mut response) => { - match result { - Err(_) => Err(AcpDelegationError::DeadlineExceeded), - Ok(Ok(response)) => Ok(response), - Ok(Err(_)) => Err(self.failure(AcpDelegationError::PromptFailed)), + + enum Stopped { + Shutdown, + Withdrawn, + Deadline, + Failed, + } + + let outcome = loop { + tokio::select! { + _ = shutdown.changed() => break Err(Stopped::Shutdown), + _ = sleep(Duration::from_millis(10)) => { + if reply.is_closed() { + break Err(Stopped::Withdrawn); + } + } + result = timeout_at(self.deadline, &mut response) => { + match result { + Err(_) => break Err(Stopped::Deadline), + Ok(Ok(response)) => break Ok(response), + Ok(Err(_)) => break Err(Stopped::Failed), + } } } }; + match outcome { Ok(response) => { - self.shared.clear_expected(&request_id); self.shared.release_forwarded(&request_id); Ok(self.finish_prompt_response(response)) } - Err(error @ (AcpDelegationError::Cancelled | AcpDelegationError::DeadlineExceeded)) => { - if self.shared.claim_cancel(&request_id) { - self.cancel(session_id); - } - self.shared.clear_expected(&request_id); + 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); - self.shared.finish_prompt(); - Err(error) + Err(self.failure(AcpDelegationError::PromptFailed)) } - Err(error) => { - self.shared.clear_expected(&request_id); + Err(stop) => { + match self.shared.request_prompt_cancel(&request_id) { + CancelAction::SendNow => { + let _ = self.wire.write_session_cancel(&request_id).await; + } + CancelAction::Deferred => { + // Give the writer one bounded chance to finish its own + // transition. It either discards the frame before any + // byte or completes it and writes the single cancel. + let _ = timeout( + Duration::from_millis(250), + self.shared.wait_prompt_settled(&request_id), + ) + .await; + } + CancelAction::None => {} + } self.shared.release_forwarded(&request_id); - self.shared.finish_prompt(); - Err(error) + Err(match stop { + Stopped::Deadline => AcpDelegationError::DeadlineExceeded, + _ => AcpDelegationError::Cancelled, + }) } } } @@ -1034,14 +1070,6 @@ impl Actor { } } - fn cancel(&self, session_id: &str) { - let _ = self - .connection - .send_notification(CancelNotification::new(SessionId::from( - session_id.to_owned(), - ))); - } - fn failure(&self, fallback: AcpDelegationError) -> AcpDelegationError { self.shared.fatal().unwrap_or(fallback) } @@ -1083,12 +1111,15 @@ const PHASE_DONE: u8 = 2; /// /// SDK publication (`PreparedRequest::block_task`) only enqueues the frame; it /// does not prove the bytes reached the child. These states distinguish a frame -/// that is merely enqueued from one the pipe writer fully committed, and a -/// partial/failed write from a delivered prompt. +/// 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 no outgoing `session/prompt` line has been observed yet. + /// 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 @@ -1098,35 +1129,77 @@ enum PromptWire { Failed, } -/// Per-prompt arbitration record. `id` is the exact JSON-RPC ID reserved for -/// the one prompt, so correlation is preserved across ingress and writer. +/// Writer transition for the one prompt. `Writing` is set under the arbitration +/// lock immediately before the first write attempt and is the publication +/// linearization point. A stop that acquires the lock earlier transitions +/// `Armed` to `Discarded`, and the writer writes nothing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PromptState { + Armed, + 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, - /// Set only once `block_task` has published the request (it enqueues - /// synchronously). A stop that wins before this forbids the prompt. - published: bool, - /// Cleared exactly once, under this same lock, either when the serial - /// ingress claims the matching response or when this client claims the - /// right to send `session/cancel`. - outstanding: bool, - wire: PromptWire, + 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(id: RawJsonRpcId) -> Self { + fn new(session: &str, id: RawJsonRpcId) -> Self { Self { id, - published: false, - outstanding: true, - wire: PromptWire::Pending, + session: session.to_owned(), + state: PromptState::Armed, + outcome: PromptOutcome::Outstanding, + cancel_requested: false, + cancel_claimed: false, + cancel_done: false, } } } -/// Serialized ingress state: the single response ID currently forwarded to the -/// SDK plus the prompt arbitration record. Keeping both under one lock makes -/// "matching response already arrived" and "cancel may be sent" a single -/// linearizable decision instead of two racing observations. +/// 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, @@ -1145,6 +1218,18 @@ struct ForwardedBudget { 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, @@ -1157,9 +1242,20 @@ struct Shared { permissions: AtomicUsize, rejected_requests: AtomicUsize, ignored_updates: AtomicUsize, + /// `None` in unit tests that do not model a live connection. + stop: Option, + /// 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); @@ -1170,11 +1266,11 @@ impl Shared { 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 expectation before the - // request can be published, so neither the ingress nor the pipe writer - // can observe this prompt without the arbitration record in place. + // 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(request_id)); + ingress.prompt = Some(PromptGate::new(session_id, request_id)); self.phase.store(PHASE_PROMPT, Ordering::Release); } @@ -1187,97 +1283,204 @@ impl Shared { if ingress.expected.as_ref() == Some(request_id) { ingress.expected = None; } - if let Some(prompt) = ingress.prompt.as_mut() - && prompt.id == *request_id - { - prompt.outstanding = false; - } } - /// Abandon a prompt that was armed but never published. No response can - /// match it and no `session/cancel` may be sent for it. - fn abort_prompt(&self, request_id: &RawJsonRpcId) { + /// Writer decision taken under the arbitration lock immediately before the + /// first write attempt. Returns `false` when the frame must be discarded + /// without touching the pipe. + fn begin_prompt_write(&self, request_id: &RawJsonRpcId) -> bool { + let stop = self.stop.as_ref().is_some_and(Stop::tripped); let mut ingress = self.ingress.lock().unwrap(); - if ingress.expected.as_ref() == Some(request_id) { + let Some(prompt) = ingress.prompt.as_mut() else { + return false; + }; + if prompt.id != *request_id || prompt.state != PromptState::Armed { + return false; + } + if prompt.cancel_requested || stop { + prompt.state = PromptState::Discarded; ingress.expected = None; + return false; } - if ingress - .prompt - .as_ref() - .is_some_and(|prompt| prompt.id == *request_id) + prompt.state = PromptState::Writing; + true + } + + /// 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 stop = self.stop.as_ref().is_some_and(Stop::tripped); + let mut ingress = self.ingress.lock().unwrap(); + 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 + } + + fn partial_prompt_write(&self, request_id: &RawJsonRpcId) { + let mut ingress = self.ingress.lock().unwrap(); + if let Some(prompt) = ingress.prompt.as_mut() + && prompt.id == *request_id { - ingress.prompt = None; + prompt.state = PromptState::Partial; + ingress.expected = None; } } - /// Publication linearization point: `block_task` has enqueued the request. - fn mark_prompt_published(&self, request_id: &RawJsonRpcId) { + fn failed_prompt_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.state == PromptState::Writing { - prompt.published = true; + prompt.state = PromptState::FailedNoBytes; + ingress.expected = None; } } - /// Record what the actual pipe writer did with the prompt frame. - fn note_prompt_wire(&self, request_id: &RawJsonRpcId, wire: PromptWire) { + /// 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.wire = wire; + prompt.state = PromptState::Discarded; + ingress.expected = None; } } - /// Atomically claim the right to send `session/cancel`. - /// - /// The claim wins only when publication already committed, the matching - /// response has not been claimed by the serial ingress, and the writer did - /// not report a partial/failed frame. Clearing `expected` here means a - /// response that arrives after the claim is discarded rather than mistaken - /// for a result of this cancelled turn. - fn claim_cancel(&self, request_id: &RawJsonRpcId) -> bool { + /// Record an actor-observed stop. The writer, not this call, decides whether + /// any byte was exposed. + fn request_prompt_cancel(&self, request_id: &RawJsonRpcId) -> CancelAction { let mut ingress = self.ingress.lock().unwrap(); let Some(prompt) = ingress.prompt.as_mut() else { - return false; + return CancelAction::None; }; - if prompt.id != *request_id || !prompt.published || !prompt.outstanding { - return false; + if prompt.id != *request_id { + return CancelAction::None; } - if matches!(prompt.wire, PromptWire::Partial | PromptWire::Failed) { - return false; + match prompt.state { + PromptState::Armed | PromptState::Writing => { + if prompt.outcome != PromptOutcome::Outstanding { + return CancelAction::None; + } + 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 + } } - prompt.outstanding = false; - ingress.expected = None; - true } - fn prompt_wire(&self) -> Option { - self.ingress - .lock() - .unwrap() - .prompt - .as_ref() - .map(|prompt| prompt.wire) + /// 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()) } - /// 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. - fn take_expected(&self, request_id: &RawJsonRpcId) -> bool { + /// 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 ingress.expected.as_ref() != Some(request_id) { - return false; - } - ingress.expected = None; if let Some(prompt) = ingress.prompt.as_mut() && prompt.id == *request_id { - prompt.outstanding = false; + 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 + } + + /// 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) { @@ -1432,6 +1635,43 @@ impl Shared { } } + /// 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 begun the + /// frame. A response that arrives while the prompt is still `Armed` cannot + /// come from a peer that received the request, so it 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::Writing | PromptState::Complete => { + prompt.state = PromptState::Complete; + if prompt.outcome == PromptOutcome::Outstanding { + prompt.outcome = PromptOutcome::Answered; + } + prompt.cancel_requested = false; + } + PromptState::Armed + | 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; @@ -1454,13 +1694,17 @@ impl Shared { /// 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. Peer text is never echoed. -/// The writer also reports the actual prompt frame outcome, because SDK -/// publication only enqueues a request and is not proof that its bytes reached -/// the child. +/// 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 { 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 { @@ -1468,47 +1712,151 @@ impl Wire { Self { stdin: tokio::sync::Mutex::new(stdin), shared, + poisoned: AtomicBool::new(false), } } async fn write_line(&self, line: &str) -> io::Result<()> { - let prompt_id = prompt_request_id(line); + 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(()); + } + match frame { + OutgoingFrame::Prompt(id) => { + if !self.shared.begin_prompt_write(&id) { + self.shared.settle_prompt(); + return Ok(()); + } + let (result, wire) = write_prompt_frame(&mut *stdin, line).await; + match wire { + PromptWire::Written => { + if self.shared.complete_prompt_write(&id) { + let _ = self.write_cancel_locked(&mut 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.poisoned.store(true, Ordering::Release); + self.shared.partial_prompt_write(&id); + } + PromptWire::Failed => { + self.shared.failed_prompt_write(&id); + } + PromptWire::Pending | PromptWire::Discarded => {} + } + self.shared.settle_prompt(); + result + } + _ => write_plain_line(&mut *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, wire) = if prompt_id.is_some() { - write_prompt_frame(&mut stdin, line).await + let result = if self.poisoned.load(Ordering::Acquire) { + Ok(()) } else { - let result = match stdin.write_all(line.as_bytes()).await { - Ok(()) => match stdin.write_all(b"\n").await { - Ok(()) => stdin.flush().await, - Err(error) => Err(error), - }, - Err(error) => Err(error), - }; - (result, PromptWire::Pending) + write_cancel_line(&mut *stdin, &session).await }; drop(stdin); - if let Some(request_id) = prompt_id.as_ref() { - self.shared.note_prompt_wire(request_id, wire); - } + 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 ChildStdin, + request_id: &RawJsonRpcId, + ) -> io::Result<()> { + 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, } -/// The prompt request carried by an already-serialized outgoing line, if any. -fn prompt_request_id(line: &str) -> Option { - match serde_json::from_str::(line) { - Ok(RawJsonRpcMessage::Request(request)) if request.method.as_ref() == "session/prompt" => { - Some(request.id) +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, } - _ => None, } } +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 prompt frame while counting how much of the line reached the pipe. /// /// `write_all` cannot distinguish a failed first write from a truncated one, so /// this loop keeps the byte count and reports partial vs no-send separately. -async fn write_prompt_frame(stdin: &mut ChildStdin, line: &str) -> (io::Result<()>, PromptWire) { +async fn write_prompt_frame(stdin: &mut W, line: &str) -> (io::Result<()>, PromptWire) +where + W: tokio::io::AsyncWrite + Unpin, +{ let bytes = line.as_bytes(); let mut written = 0usize; while written < bytes.len() { @@ -1546,6 +1894,22 @@ async fn write_prompt_frame(stdin: &mut ChildStdin, line: &str) -> (io::Result<( } } +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, @@ -1639,13 +2003,150 @@ struct OwnedChild { child: Child, pid: u32, reaped: bool, - /// The procfs view admitted before spawn and rechecked before every group - /// measurement and before cleanup is claimed. - view: ProcfsView, + 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 } impl OwnedChild { - fn spawn(launch: &AcpDelegationLaunch, view: ProcfsView) -> io::Result { + fn spawn(launch: &AcpDelegationLaunch) -> io::Result { let mut command = Command::new(launch.command()); command .args(launch.arguments()) @@ -1673,7 +2174,9 @@ impl OwnedChild { child, pid, reaped: false, - view, + exit_status: None, + group_signal_sent: false, + forced: false, }) } @@ -1695,82 +2198,109 @@ impl OwnedChild { Ok((stdin, stdout)) } - /// Terminate the owned process group and confirm it is empty before the - /// direct leader is reaped. + /// Terminate the owned process group while the direct leader still pins its + /// identity, then reap that exact child and prove the original group absent. /// - /// The unreaped leader pins both the PID and the process-group identity, so - /// every group signal in this method targets the group this client created. - /// Once the leader has been reaped this method never signals again. + /// 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 { - let mut group_signal_sent = false; - let mut forced = false; - - // Give a harness that closes stdio a short window to exit on its own. - let natural_deadline = (Instant::now() + Duration::from_millis(300)).min(deadline); - while Instant::now() < natural_deadline && !leader_exited(self.pid) { - sleep(Duration::from_millis(10)).await; - } - - // Members that outlive the leader are still in the owned group while the - // leader is unreaped, so the group identity is safe to use. Every - // measurement revalidates the procfs view first; an unknown view is an - // error, never "empty". - let mut group = group_members(self.pid, &self.view); - if !matches!(group, Ok(0)) { - group_signal_sent |= signal_group(self.pid, libc::SIGTERM); - let term_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline); + 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 { - group = group_members(self.pid, &self.view); - if matches!(group, Ok(0)) || Instant::now() >= term_deadline { - break; + 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, + }; + } } - sleep(Duration::from_millis(10)).await; } - } - if !matches!(group, Ok(0)) { - group_signal_sent |= signal_group(self.pid, libc::SIGKILL); - forced = true; - loop { - group = group_members(self.pid, &self.view); - if matches!(group, Ok(0)) || Instant::now() >= deadline { - break; + + // 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; + } + } } - sleep(Duration::from_millis(10)).await; } - } - // The final empty reading already revalidated the same view that was - // admitted before spawn. A view that changed underneath us reports an - // error and keeps cleanup unconfirmed. - let group_clear = matches!(group, Ok(0)); - // Reap only after the group is proven empty. Until then the unreaped - // leader is retained as the group identity anchor for a later retry. - let mut status = None; - if group_clear { + // 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(exit)) => { - status = Some(exit); + Ok(Some(status)) => { self.reaped = true; + self.exit_status = Some(status); break; } - Ok(None) => {} + Ok(None) => { + if Instant::now() >= reap_deadline { + break; + } + sleep(Duration::from_millis(5)).await; + } Err(_) => break, } - if Instant::now() >= deadline { - break; - } - sleep(Duration::from_millis(5)).await; } } - let direct_child_reaped = status.is_some(); + + // 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, - exit_status: status, - group_signal_sent, - forced, + direct_child_reaped: self.reaped, + exit_status: self.exit_status, + group_signal_sent: self.group_signal_sent, + forced: self.forced, group_clear, - cleanup_confirmed: group_clear && direct_child_reaped, + cleanup_confirmed: self.reaped && group_clear, } } } @@ -1780,355 +2310,28 @@ impl Drop for OwnedChild { if self.reaped { return; } - // Cancellation cannot await. The leader is still unreaped here, so its - // cached PID still pins the group identity; this is the last safe point - // to signal the whole group. - signal_group(self.pid, libc::SIGKILL); - let _ = self.child.start_kill(); - } -} - -/// Whether the direct leader has exited, without reaping it. -/// -/// `WNOWAIT` keeps the zombie in place so the PID and process-group identity -/// stay anchored to this client until [`OwnedChild::terminate`] has confirmed -/// that no live group member remains. -#[cfg(unix)] -fn leader_exited(pid: u32) -> bool { - // SAFETY: `waitid` writes to the provided `siginfo_t`; it is zeroed first - // and only read through the documented accessor. - unsafe { - let mut info: libc::siginfo_t = std::mem::zeroed(); - let result = libc::waitid( - libc::P_PID, - pid as libc::id_t, - &mut info, - libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, - ); - result == 0 && info.si_pid() != 0 - } -} - -#[cfg(not(unix))] -fn leader_exited(_pid: u32) -> bool { - false -} - -/// Verified, reusable view of the procfs mount used for group enumeration. -/// -/// A procfs mount can fail to show every member of the group we own: `hidepid=` -/// can hide processes that changed credentials, and a procfs mounted from a -/// different PID namespace reports that namespace's PID/PGID values. An absent -/// `/proc/` entry therefore only proves absence when the same, verified -/// view was used for the directory scan and for reading each entry. -/// -/// `validate` is called before spawn so an unsuitable host is rejected before -/// any process exists. `revalidate` runs before every measurement and before -/// cleanup is claimed, and also pins the mount identity (`major:minor` and mount -/// ID) so a mount replaced underneath us is an error, never an empty group. -#[derive(Debug, Clone)] -struct ProcfsView { - #[cfg(target_os = "linux")] - anchor: ProcMountAnchor, -} - -impl ProcfsView { - #[cfg(target_os = "linux")] - fn validate() -> io::Result { - let mountinfo = std::fs::read("/proc/self/mountinfo")?; - let anchor = parse_proc_mountinfo(&mountinfo)?; - let status = std::fs::read("/proc/self/status")?; - if parse_nspid_status(&status)? != 1 { - return Err(io::Error::other("procfs view spans nested pid namespaces")); - } - check_self_anchor()?; - Ok(Self { anchor }) - } - - #[cfg(not(target_os = "linux"))] - fn validate() -> io::Result { - Ok(Self {}) - } - - #[cfg(target_os = "linux")] - fn revalidate(&self) -> io::Result<()> { - let mountinfo = std::fs::read("/proc/self/mountinfo")?; - let current = parse_proc_mountinfo(&mountinfo)?; - if current != self.anchor { - return Err(io::Error::other("procfs mount changed during ownership")); - } - let status = std::fs::read("/proc/self/status")?; - if parse_nspid_status(&status)? != 1 { - return Err(io::Error::other("procfs view spans nested pid namespaces")); - } - check_self_anchor() - } - - #[cfg(not(target_os = "linux"))] - fn revalidate(&self) -> io::Result<()> { - Ok(()) - } -} - -/// Mount identity admitted before spawn. `mount_id` and `device` make a -/// replacement or bind mount of another procfs visible to `revalidate`. -#[cfg(target_os = "linux")] -#[derive(Debug, Clone, PartialEq, Eq)] -struct ProcMountAnchor { - mount_id: u64, - device: String, -} - -/// Locate the single full procfs mount at `/proc` and reject any visibility -/// restriction. Parses `/proc/self/mountinfo` bytes directly so the same logic -/// is exercised by synthetic unit tests. -#[cfg(target_os = "linux")] -fn parse_proc_mountinfo(bytes: &[u8]) -> io::Result { - let text = std::str::from_utf8(bytes).map_err(|_| io::Error::other("mountinfo encoding"))?; - let mut found: Option = None; - for line in text.lines() { - let fields: Vec<&str> = line.split(' ').collect(); - if fields.len() < 10 { - continue; - } - // mountinfo: id parent major:minor root mount-point options ... - fstype source super-options - if fields[4] != "/proc" || fields[3] != "/" { - continue; - } - let Some(dash) = fields.iter().position(|field| *field == "-") else { - return Err(io::Error::other("mountinfo separator")); - }; - if dash + 3 >= fields.len() { - return Err(io::Error::other("mountinfo fields")); - } - if fields[dash + 1] != "proc" { - return Err(io::Error::other("not a procfs mount at /proc")); - } - if !hidepid_unrestricted(fields[5]) || !hidepid_unrestricted(fields[dash + 3]) { - return Err(io::Error::other("procfs visibility is restricted")); - } - let mount_id = fields[0] - .parse::() - .map_err(|_| io::Error::other("mountinfo id"))?; - let device = fields[2].to_owned(); - if found.is_some() { - return Err(io::Error::other("ambiguous /proc mount")); - } - found = Some(ProcMountAnchor { mount_id, device }); - } - found.ok_or_else(|| io::Error::other("no procfs mount at /proc")) -} - -#[cfg(target_os = "linux")] -fn hidepid_unrestricted(options: &str) -> bool { - for option in options.split(',') { - if let Some(value) = option.strip_prefix("hidepid=") - && value != "0" - { - return false; - } - } - true -} - -/// Number of PIDs listed by `/proc/self/status`'s `NSpid` field. One value -/// means this process is not a member of any namespace nested below the procfs -/// mount's namespace, so the same view enumerates children we spawn without -/// privileges beyond reading our own status. -#[cfg(target_os = "linux")] -fn parse_nspid_status(bytes: &[u8]) -> io::Result { - let text = std::str::from_utf8(bytes).map_err(|_| io::Error::other("status encoding"))?; - for line in text.lines() { - let Some(rest) = line.strip_prefix("NSpid:") else { - continue; - }; - let mut count = 0; - for value in rest.split_whitespace() { - value - .parse::() - .map_err(|_| io::Error::other("NSpid value"))?; - count += 1; - } - if count == 0 { - return Err(io::Error::other("empty NSpid")); - } - return Ok(count); - } - Err(io::Error::other("missing NSpid")) -} - -/// Confirm the selected `/proc` view sees this process with the PID and PGID -/// the kernel reports to us. This rejects a procfs mounted from a different -/// namespace even when NSpid alone is inconclusive. -#[cfg(target_os = "linux")] -fn check_self_anchor() -> io::Result<()> { - let stat = std::fs::read("/proc/self/stat")?; - let fields = - parse_stat_fields(&stat).ok_or_else(|| io::Error::other("unparsable self stat"))?; - if fields.pid != std::process::id() { - return Err(io::Error::other("procfs pid namespace mismatch")); - } - // SAFETY: `getpgrp` has no preconditions and only reads process state. - let pgrp = unsafe { libc::getpgrp() }; - if fields.pgrp != pgrp as u32 { - return Err(io::Error::other("procfs process-group mismatch")); - } - Ok(()) -} - -/// Number of group members that can still run. -/// -/// Linux is checked through the verified procfs view. A `Z`/`X` thread-group -/// leader counts as present while the kernel reports more than one thread in -/// its group: the leader can be a zombie while sibling threads are still live, -/// and a top-level `/proc` scan only lists leaders. A vanished entry is the -/// only read failure that proves the process is outside the group; unreadable, -/// restricted or unparsable entries are errors, so an unknown member is never -/// mistaken for an empty group. Elsewhere signal 0 only proves that some member -/// is still signalable; zombies may keep that true, which fails closed rather -/// than reporting a cleanup that was not observed. -#[cfg(target_os = "linux")] -fn group_members(pgid: u32, view: &ProcfsView) -> io::Result { - view.revalidate()?; - let mut present = 0; - for entry in std::fs::read_dir("/proc")? { - let entry = entry?; - let Some(pid) = entry - .file_name() - .to_str() - .and_then(|name| name.parse::().ok()) - else { - continue; - }; - if member_of(std::fs::read(format!("/proc/{pid}/stat")), pgid)? { - present += 1; - } - } - // Fence the scan: a mount replaced between the directory read and the - // entry reads must invalidate the count instead of reporting an empty - // group. The same verified view has to be in effect for the whole scan. - view.revalidate()?; - Ok(present) -} - -/// Narrow classification of one `/proc//stat` read against `pgid`. -/// -/// Only `NotFound` (which includes `ESRCH` for a PID that vanished between the -/// directory scan and the read) proves the process is not a member. Every other -/// read error and every malformed stat is returned as an error. -#[cfg(target_os = "linux")] -fn member_of(stat: io::Result>, pgid: u32) -> io::Result { - match stat { - Ok(bytes) => { - let Some(fields) = parse_stat_fields(&bytes) else { - return Err(io::Error::other("unparsable /proc stat")); - }; - Ok(counts_as_present(fields, pgid)) - } - Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), - Err(error) => Err(error), - } -} - -#[cfg(target_os = "linux")] -fn counts_as_present(fields: StatFields, pgid: u32) -> bool { - if fields.pgrp != pgid { - return false; - } - match fields.state { - // Terminal only when the leader is the last thread left. - b'Z' | b'X' => fields.num_threads > 1, - _ => true, - } -} - -/// Fields needed from `/proc//stat`, parsed from raw bytes. -#[cfg(target_os = "linux")] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct StatFields { - pid: u32, - state: u8, - /// Field 5 (`pgrp`), preserved for `Z`/`X` entries. - pgrp: u32, - /// Field 20 (`num_threads`); counts every thread in the group, including a - /// zombie leader, so `1` means no sibling threads remain. - num_threads: u32, -} - -/// Parse `/proc//stat` from raw bytes. -/// -/// `comm` is arbitrary bytes (non-UTF-8 and embedded `)` are both legal), so -/// the name is delimited by the first `(` and the last `)` and the remainder is -/// split as ASCII. A non-UTF-8 process name must not hide a live group member, -/// and a truncated line is malformed rather than absent. -#[cfg(target_os = "linux")] -fn parse_stat_fields(bytes: &[u8]) -> Option { - let open = bytes.iter().position(|byte| *byte == b'(')?; - let close = bytes.iter().rposition(|byte| *byte == b')')?; - if close <= open { - return None; - } - let pid = std::str::from_utf8(&bytes[..open]) - .ok()? - .trim() - .parse::() - .ok()?; - let mut fields = bytes[close + 1..] - .split(|byte| byte.is_ascii_whitespace()) - .filter(|field| !field.is_empty()); - let state = fields.next()?; - if state.len() != 1 || !state[0].is_ascii_alphabetic() { - return None; - } - let _parent = fields.next()?; - let pgrp = parse_stat_u32(fields.next()?)?; - // Fields 6..=19 (session .. nice); field 20 is num_threads. - for _ in 0..14 { - fields.next()?; - } - let num_threads = parse_stat_u32(fields.next()?)?; - if num_threads == 0 { - return None; - } - Some(StatFields { - pid, - state: state[0], - pgrp, - num_threads, - }) -} - -#[cfg(target_os = "linux")] -fn parse_stat_u32(field: &[u8]) -> Option { - std::str::from_utf8(field).ok()?.parse::().ok() -} - -#[cfg(all(unix, not(target_os = "linux")))] -fn group_members(pgid: u32, _view: &ProcfsView) -> io::Result { - // SAFETY: signal 0 only performs an existence/permission check. - let result = unsafe { libc::kill(-(pgid as libc::pid_t), 0) }; - if result == 0 { - Ok(1) - } else { - let error = io::Error::last_os_error(); - if error.raw_os_error() == Some(libc::ESRCH) { - Ok(0) - } else { - Err(error) + // 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(not(unix))] -fn group_members(_pgid: u32, _view: &ProcfsView) -> io::Result { - Ok(0) -} - #[cfg(unix)] fn signal_group(pid: u32, signal: libc::c_int) -> bool { - // SAFETY: the group was created at spawn. The negative PID targets only the - // owned process group, never an unrelated process. - unsafe { libc::kill(-(pid as libc::pid_t), signal) == 0 } + 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))] @@ -2136,277 +2339,364 @@ fn signal_group(_pid: u32, _signal: libc::c_int) -> bool { false } -/// Synthetic procfs bytes and the per-prompt arbitration state machine. +/// Kernel-backed group-presence proof and prompt-arbitration unit tests. /// -/// These are pure byte/state checks: no process is spawned and no `/proc` write -/// is attempted. They pin what cleanup and cancellation depend on: only an -/// admitted, trusted view may report an empty group; a zombie leader is terminal -/// only when its thread group has no siblings left; and a matching response that -/// already reached the serial ingress forbids a late `session/cancel`. -#[cfg(all(test, target_os = "linux"))] -mod linux_evidence_tests { - use super::{ - ProcMountAnchor, PromptWire, Shared, StatFields, counts_as_present, member_of, - parse_nspid_status, parse_proc_mountinfo, parse_stat_fields, - }; - use agent_client_protocol::RawJsonRpcId; +/// 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; - - /// Fields after `comm`: state, ppid, pgrp, fields 6..=19, then num_threads. - fn tail(state: u8, pgrp: u32, threads: u32) -> String { - let mut fields = vec![ - (state as char).to_string(), - "1".to_owned(), - pgrp.to_string(), - ]; - for _ in 0..14 { - fields.push("0".to_owned()); - } - fields.push(threads.to_string()); - fields.push("0".to_owned()); - fields.join(" ") - } - - fn stat_line(pid: u32, comm: &str, state: u8, pgrp: u32, threads: u32) -> Vec { - format!("{pid} ({comm}) {}", tail(state, pgrp, threads)).into_bytes() - } + use std::time::{Duration, Instant}; #[test] - fn non_utf8_comm_is_still_a_live_member() { - let mut stat = b"4242 (na".to_vec(); - stat.extend_from_slice(b"\xff\xfe"); - stat.extend_from_slice(b"me) "); - stat.extend_from_slice(tail(b'S', 4242, 1).as_bytes()); + fn group_query_is_absent_only_on_esrch() { + assert_eq!(classify_group_query(0, None), GroupPresence::Present); assert_eq!( - parse_stat_fields(&stat), - Some(StatFields { - pid: 4242, - state: b'S', - pgrp: 4242, - num_threads: 1, - }) + classify_group_query(-1, Some(libc::ESRCH)), + GroupPresence::Absent ); - assert_eq!(member_of(Ok(stat.clone()), 4242).ok(), Some(true)); - assert_eq!(member_of(Ok(stat), 7).ok(), Some(false)); - } - - #[test] - fn comm_with_parentheses_uses_the_last_delimiter() { - let stat = format!("11 (a) b) {}", tail(b'R', 11, 1)).into_bytes(); - assert_eq!(parse_stat_fields(&stat).map(|fields| fields.pgrp), Some(11)); + 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 zombie_leader_with_sibling_threads_is_retained() { - // A top-level /proc scan only lists thread-group leaders. A zombie - // leader with num_threads > 1 still has live siblings in the group. - for state in [b'Z', b'X'] { - assert!( - member_of(Ok(stat_line(9, "leader", state, 9, 2)), 9).ok() == Some(true), - "state {} with siblings must keep the group non-empty", - state as char - ); - } - } - + 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 zombie_leader_alone_is_terminal() { - for state in [b'Z', b'X'] { - assert_eq!( - member_of(Ok(stat_line(9, "leader", state, 9, 1)), 9).ok(), - Some(false) - ); + 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)); } - } - #[test] - fn zombie_leader_of_another_group_is_not_counted() { + // 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!( - member_of(Ok(stat_line(9, "leader", b'Z', 4, 5)), 9).ok(), - Some(false) + present, 0, + "the kernel retains the owned group while the leader is waitable" ); - } - #[test] - fn live_leader_is_member_regardless_of_threads() { - assert_eq!( - member_of(Ok(stat_line(9, "live", b'S', 9, 5)), 9).ok(), - Some(true) - ); + 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!( - member_of(Ok(stat_line(9, "live", b'S', 7, 5)), 9).ok(), - Some(false) + io::Error::last_os_error().raw_os_error(), + Some(libc::ESRCH), + "after the exact reap the original group is gone" ); } +} - #[test] - fn counts_as_present_preserves_pgid_for_dead_entries() { - let fields = StatFields { - pid: 9, - state: b'Z', - pgrp: 9, - num_threads: 3, - }; - assert!(counts_as_present(fields, 9)); - assert!(!counts_as_present(fields, 8)); +#[cfg(test)] +mod prompt_arbitration_tests { + use super::{CancelAction, PromptWire, Shared}; + use agent_client_protocol::RawJsonRpcId; + use std::time::Duration; + + fn prompt_id() -> RawJsonRpcId { + RawJsonRpcId::Number(7) } #[test] - fn vanished_entry_proves_absence() { + 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_eq!( - member_of(Err(io::Error::from(io::ErrorKind::NotFound)), 3).ok(), - Some(false) + shared.request_prompt_cancel(&id), + CancelAction::Deferred, + "the actor records the stop before the writer decides" + ); + assert!( + !shared.begin_prompt_write(&id), + "the writer discards the scheduled frame before any byte" ); + 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)); } #[test] - fn unreadable_or_unparsable_entry_is_unknown_not_empty() { - assert!(member_of(Err(io::Error::from(io::ErrorKind::PermissionDenied)), 3).is_err()); - assert!(member_of(Ok(b"3 (truncated".to_vec()), 3).is_err()); - assert!(member_of(Ok(b"3 (name) S 1 not-a-pid".to_vec()), 3).is_err()); - assert!(member_of(Ok(Vec::new()), 3).is_err()); - assert!(member_of(Ok(b"3 (name) $ 1 3 3".to_vec()), 3).is_err()); - // A real /proc stat always has field 20; a short line is ambiguous, - // never "not a member". - assert!(member_of(Ok(b"3 (name) S 1 3 3".to_vec()), 3).is_err()); - assert!(member_of(Ok(stat_line(3, "name", b'Z', 3, 0)), 3).is_err()); - } + fn writer_consults_shutdown_and_deadline_before_the_first_byte() { + let (_shutdown, shutdown_rx) = tokio::sync::watch::channel(true); + 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()); + assert!(!shared.begin_prompt_write(&id)); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); - fn mount_line(id: u64, root: &str, options: &str, fstype: &str, super_options: &str) -> String { - format!("{id} 29 0:23 {root} /proc {options} shared:12 - {fstype} proc {super_options}") + let (_shutdown, shutdown_rx) = tokio::sync::watch::channel(false); + let past = tokio::time::Instant::now() - Duration::from_millis(1); + let shared = Shared::new(shutdown_rx, past); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + assert!(!shared.begin_prompt_write(&id)); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); } #[test] - fn unrestricted_proc_mount_is_admitted() { - let bytes = mount_line(25, "/", "rw,nosuid,nodev,noexec,relatime", "proc", "rw"); + fn complete_frame_yields_exactly_one_cancel() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + assert!(shared.begin_prompt_write(&id)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::Deferred); + assert!( + shared.complete_prompt_write(&id), + "a complete frame with a pending stop owes one cancel" + ); assert_eq!( - parse_proc_mountinfo(bytes.as_bytes()).ok(), - Some(ProcMountAnchor { - mount_id: 25, - device: "0:23".to_owned(), - }) + shared.request_prompt_cancel(&id), + CancelAction::Deferred, + "the writer owns the cancel until its line is written" ); - let explicit_zero = mount_line(25, "/", "rw", "proc", "rw,hidepid=0"); - assert!(parse_proc_mountinfo(explicit_zero.as_bytes()).is_ok()); + 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); } #[test] - fn restriction_anywhere_is_rejected() { - for line in [ - mount_line(25, "/", "rw,hidepid=2", "proc", "rw"), - mount_line(25, "/", "rw", "proc", "rw,hidepid=1"), - mount_line(25, "/", "rw", "proc", "rw,hidepid=invisible"), - ] { - assert!( - parse_proc_mountinfo(line.as_bytes()).is_err(), - "restricted mount must be rejected: {line}" - ); - } + fn complete_frame_then_cancel_claims_one_send_now() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + assert!(shared.begin_prompt_write(&id)); + 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); } #[test] - fn non_procfs_subtree_or_missing_mount_is_rejected() { - assert!(parse_proc_mountinfo(mount_line(25, "/", "rw", "tmpfs", "rw").as_bytes()).is_err()); + fn matching_response_wins_over_later_cancel() { + let shared = Shared::default(); + let id = prompt_id(); + shared.begin_prompt("fixture-session", id.clone()); + assert!(shared.begin_prompt_write(&id)); assert!( - parse_proc_mountinfo(mount_line(25, "/sub", "rw", "proc", "rw").as_bytes()).is_err() + shared.take_expected(&id), + "the ingress claims the exact prompt response" ); - assert!(parse_proc_mountinfo(b"25 29 0:23 / /proc/sys rw - proc proc rw\n").is_err()); - } - - #[test] - fn ambiguous_duplicate_proc_mounts_are_rejected() { - let mut bytes = mount_line(25, "/", "rw", "proc", "rw"); - bytes.push('\n'); - bytes.push_str(&mount_line(26, "/", "rw", "proc", "rw")); - assert!(parse_proc_mountinfo(bytes.as_bytes()).is_err()); - } - - #[test] - fn single_level_nspid_is_admitted() { + assert!(shared.is_reserved_prompt_id(&id)); assert_eq!( - parse_nspid_status(b"Name:\tfixture\nNSpid:\t123\n").ok(), - Some(1) + 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 nested_or_invalid_nspid_is_rejected() { - assert_eq!(parse_nspid_status(b"NSpid:\t123\t45\n").ok(), Some(2)); - assert!(parse_nspid_status(b"NSpid:\n").is_err()); - assert!(parse_nspid_status(b"NSpid:\tabc\n").is_err()); - assert!(parse_nspid_status(b"Name:\tfixture\n").is_err()); - } - - fn prompt_id() -> RawJsonRpcId { - RawJsonRpcId::Number(7) - } - - #[test] - fn cancel_requires_publication_and_stays_single_use() { + fn response_before_any_prompt_byte_is_not_accepted() { let shared = Shared::default(); let id = prompt_id(); shared.begin_prompt("fixture-session", id.clone()); - assert!( - !shared.claim_cancel(&id), - "unpublished prompt cannot cancel" - ); - shared.mark_prompt_published(&id); - assert!( - shared.claim_cancel(&id), - "published outstanding prompt may cancel" - ); - assert!( - !shared.claim_cancel(&id), - "a cancel is claimed at most once" - ); + assert!(!shared.take_expected(&id)); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Pending)); } #[test] - fn matching_response_claimed_before_cancel_refuses_late_cancel() { + fn partial_write_refuses_cancel_and_blocks_follow_on_lines() { let shared = Shared::default(); let id = prompt_id(); shared.begin_prompt("fixture-session", id.clone()); - shared.mark_prompt_published(&id); - assert!( - shared.take_expected(&id), - "the ingress claims the response id" - ); - assert!( - !shared.claim_cancel(&id), - "a response already claimed by the serial ingress forbids session/cancel" - ); + assert!(shared.begin_prompt_write(&id)); + shared.partial_prompt_write(&id); + 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)); } #[test] - fn partial_or_failed_write_refuses_cancel() { - for wire in [PromptWire::Partial, PromptWire::Failed] { - let shared = Shared::default(); - let id = prompt_id(); - shared.begin_prompt("fixture-session", id.clone()); - shared.mark_prompt_published(&id); - shared.note_prompt_wire(&id, wire); - assert!( - !shared.claim_cancel(&id), - "a frame that did not fully reach the pipe cannot be cancelled" - ); - } + fn zero_byte_write_sends_nothing() { let shared = Shared::default(); let id = prompt_id(); shared.begin_prompt("fixture-session", id.clone()); - shared.mark_prompt_published(&id); - shared.note_prompt_wire(&id, PromptWire::Written); - assert!(shared.claim_cancel(&id)); + assert!(shared.begin_prompt_write(&id)); + shared.failed_prompt_write(&id); + 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); } #[test] - fn aborted_prompt_never_cancels() { + 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.abort_prompt(&id); - assert!(!shared.claim_cancel(&id)); - // Even a stray publication mark cannot revive an aborted prompt. - shared.mark_prompt_published(&id); - assert!(!shared.claim_cancel(&id)); + shared.abandon_unwritten_prompt(&id); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); + assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); + } +} + +#[cfg(test)] +mod writer_outcome_tests { + use super::{OutgoingFrame, PromptWire, session_cancel_frame, write_prompt_frame}; + use agent_client_protocol::RawJsonRpcId; + use std::io; + use std::pin::Pin; + use std::task::{Context, Poll}; + + struct ScriptedWriter { + allow: usize, + written: Vec, + } + + impl tokio::io::AsyncWrite for ScriptedWriter { + fn poll_write( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let remaining = self.allow.saturating_sub(self.written.len()); + if remaining == 0 { + return Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe))); + } + let take = remaining.min(buf.len()); + self.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(())) + } + } + + #[tokio::test] + async fn complete_line_is_reported_written() { + let mut writer = ScriptedWriter { + allow: usize::MAX, + written: Vec::new(), + }; + let (result, wire) = write_prompt_frame(&mut writer, "{\"x\":1}").await; + assert!(result.is_ok()); + assert_eq!(wire, PromptWire::Written); + assert_eq!(writer.written.as_slice(), b"{\"x\":1}\n"); + } + + #[tokio::test] + async fn failure_before_any_byte_is_not_a_delivery() { + let mut writer = ScriptedWriter { + allow: 0, + written: Vec::new(), + }; + let (result, wire) = write_prompt_frame(&mut writer, "{\"x\":1}").await; + assert!(result.is_err()); + assert_eq!(wire, PromptWire::Failed); + assert!(writer.written.is_empty()); + } + + #[tokio::test] + async fn truncated_line_is_reported_partial() { + let mut writer = ScriptedWriter { + allow: 5, + written: Vec::new(), + }; + let (result, wire) = write_prompt_frame(&mut writer, "{\"x\":1}").await; + assert!(result.is_err()); + assert_eq!(wire, PromptWire::Partial); + assert_eq!(writer.written.as_slice(), b"{\"x\":"); + } + + #[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"), + } } } diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs index 68bc803..be22123 100644 --- a/tests/acp_delegation_client_tests.rs +++ b/tests/acp_delegation_client_tests.rs @@ -146,6 +146,16 @@ 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 } @@ -1331,6 +1341,11 @@ async fn published_prompt_still_outstanding_sends_exactly_one_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] From 14b33ec71fb9203be6d9e44d99254b0b9b6ccc6e Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 08:06:34 +0800 Subject: [PATCH 06/27] feat(acp): add durable delegation policy and session pins Wire the operator-owned `acp_harnesses` table through the existing `config.yaml` loader and keep its argv host-private, so the public config snapshot never projects a launch definition and an invalid table fails startup before the listener binds. Add the durable delegation policy: a user approval bound to the run, the call, the admitted workspace, the launch definition and the pin version; a private session pin created once and restored afterwards; a separate durable prompt-send intent; and one settlement write that also releases the pin lease. A pin whose remote state is unknown is never rebuilt or continued automatically. The policy is installed only when the table is non-empty, refuses every call before the spawn point when approval, workspace, harness, binding or capacity is missing, and reports `completed` only after `end_turn` and confirmed process cleanup. --- src/bin/rustscript-agent-gateway.rs | 21 + src/config_file.rs | 167 ++ src/effects/mod.rs | 11 +- src/effects/types.rs | 15 + src/lib.rs | 4 +- src/service.rs | 67 + src/service/acp_session_pins.rs | 1834 +++++++++++++++++++++ tests/acp_delegation_policy_tests.rs | 1808 ++++++++++++++++++++ tests/config_file_tests.rs | 102 ++ tests/fixtures/acp_policy/build.rs | 40 + tests/fixtures/acp_policy/policy_agent.rs | 378 +++++ 11 files changed, 4440 insertions(+), 7 deletions(-) create mode 100644 src/service/acp_session_pins.rs create mode 100644 tests/acp_delegation_policy_tests.rs create mode 100644 tests/fixtures/acp_policy/build.rs create mode 100644 tests/fixtures/acp_policy/policy_agent.rs diff --git a/src/bin/rustscript-agent-gateway.rs b/src/bin/rustscript-agent-gateway.rs index f656b48..a1ce42a 100644 --- a/src/bin/rustscript-agent-gateway.rs +++ b/src/bin/rustscript-agent-gateway.rs @@ -223,6 +223,27 @@ 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, + ) + .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 0ef901e..2c5bc47 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/mod.rs b/src/effects/mod.rs index 1f70887..1d073df 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 47e4a65..e2a5b79 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/lib.rs b/src/lib.rs index 0fbef5e..c18eb5e 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/service.rs b/src/service.rs index 6c3a8bb..c2615a3 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, @@ -1750,6 +1754,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), @@ -6485,6 +6490,68 @@ impl AgentService { self.inner.persistence.clone() } + /// Installs the optional ACP delegation policy built from the existing + /// `config.yaml` launch table. + /// + /// Installing twice replaces the table for later calls only; an already + /// admitted call keeps the policy it started with. A `None` policy leaves + /// the capability disabled, which is the default. + 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(), + ); + } + *self + .inner + .acp_delegation + .lock() + .expect("acp delegation policy") = policy; + Ok(()) + } + + /// 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, + cancellation: &RunCancellation, + ) -> 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, cancellation) + .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( diff --git a/src/service/acp_session_pins.rs b/src/service/acp_session_pins.rs new file mode 100644 index 0000000..3292901 --- /dev/null +++ b/src/service/acp_session_pins.rs @@ -0,0 +1,1834 @@ +//! 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 user approval bound to the run, the call, the +//! admitted workspace, the current launch definition and the current pin +//! version, and revalidates that witness after the approval; +//! - it keeps the peer-assigned external session ID and every call phase 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; +//! - it separates the durable "prompt send intent" write from the result +//! settlement, so a crash can never silently re-run a prompt; +//! - it releases the pin lease in the same durable write that settles the call; +//! - 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: `session.touch` is one atomic JSON merge but not a +//! compare-and-swap. Ownership is therefore decided by the in-process per-pin +//! gate (`try_lock`, so a conflicting call is refused immediately instead of +//! queued), recorded durably as a lease next to the call phase, and verified by +//! a read-back fence before the process is spawned. The durable lease is what +//! carries "one active call per pin" across runs and restarts; two gateway +//! processes must not share one database, which is the product's existing +//! single-writer deployment constraint. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::OsString; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, 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 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; +/// Task excerpt carried by the approval preview. +const PREVIEW_TASK_BYTES: usize = 1024; +/// Metadata key owning every private delegation record in one session. +const METADATA_KEY: &str = "acp_delegation"; + +/// 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, + }) + } +} + +/// 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(), + } + } +} + +/// 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, + /// Optional absolute wall-clock run deadline; the effective deadline is + /// always the earlier of this and [`DELEGATION_DEADLINE_MS`] from now. + pub run_deadline_ms: Option, +} + +/// Why a delegation was refused before any process existed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AcpPolicyRefusal { + Denied(&'static str), + Busy(&'static str), + Failed(&'static str), +} + +impl AcpPolicyRefusal { + pub fn status(self) -> AcpDelegationStatus { + match self { + Self::Denied(_) => AcpDelegationStatus::Denied, + Self::Busy(_) => AcpDelegationStatus::Busy, + Self::Failed(_) => AcpDelegationStatus::Failed, + } + } + + pub fn code(self) -> &'static str { + match self { + Self::Denied(code) | Self::Busy(code) | Self::Failed(code) => code, + } + } +} + +/// Test-only fault cut driven at the three recovery boundaries. The policy +/// closes the child and then returns an indeterminate result without writing +/// the later phase, exactly like a crash at that point. +#[cfg(feature = "workspace-io-fault")] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AcpPolicyFault { + #[default] + None, + /// `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, + /// The prompt may have run; no settlement was written. + AfterPromptPublished, + /// `close` returned unconfirmed, but the supervisor will publish a positive + /// cleanup report. + DeferredCleanupConfirmed, + /// 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, + harnesses: BTreeMap, + /// Monotonic identity of this immutable launch table. + config_version: u64, + 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: Mutex>, + gates: Mutex>>>, + #[cfg(feature = "workspace-io-fault")] + fault: Mutex, +} + +/// Installed delegation policy. Cloning shares the same durable gates. +#[derive(Clone)] +pub struct AcpDelegationPolicy { + inner: Arc, +} + +static CONFIG_VERSION_SEQUENCE: AtomicU64 = AtomicU64::new(1); + +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. + pub fn install( + config: &ConfigFile, + persistence: 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 config_version = CONFIG_VERSION_SEQUENCE.fetch_add(1, Ordering::Relaxed); + 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, + harnesses, + config_version, + 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: Mutex::new(HashSet::new()), + gates: Mutex::new(HashMap::new()), + #[cfg(feature = "workspace-io-fault")] + fault: Mutex::new(AcpPolicyFault::None), + }), + })) + } + + /// Configured logical IDs, in stable order. + pub fn harness_ids(&self) -> Vec { + self.inner.harnesses.keys().cloned().collect() + } + + /// Monotonic identity of this immutable launch table. + pub fn config_version(&self) -> u64 { + self.inner.config_version + } + + /// Free process slots of the service-wide delegation quota. + pub fn available_processes(&self) -> usize { + self.inner.quota.available_permits() + } + + #[cfg(feature = "workspace-io-fault")] + pub fn arm_fault(&self, fault: AcpPolicyFault) { + *self.inner.fault.lock().expect("acp policy fault") = fault; + } + + #[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::DeferredCleanupConfirmed + | 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 + } + } + + /// Durable settlement classification of one call. + /// + /// `NotStarted` means no process was ever prepared for that exact call and a + /// fresh approved call may start; `Indeterminate` means the call may have + /// produced an external effect and must never be re-executed; `Settled` + /// means its 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. + /// + /// The preview names the harness, the admitted workspace, whether the call + /// creates or continues a session, the task and the external program's + /// authority. An insufficient preview is refused instead of approved. + pub async fn request_approval( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + ) -> Result { + validate_request(request)?; + if !self.inner.harnesses.contains_key(&request.harness_id) { + return Err(AcpPolicyRefusal::Denied("acp_harness_unknown")); + } + let snapshot = self.read_session(&scope.session_id).await?; + let workspace = admitted_workspace(&snapshot, &self.inner.allowed_roots)?; + let doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let pin_version = doc + .pins + .get(&request.harness_id) + .map(|pin| pin.version) + .unwrap_or(0); + let new_session = doc + .pins + .get(&request.harness_id) + .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(scope.run_deadline_ms, now_ms); + if expires_at_ms <= now_ms { + return Err(AcpPolicyRefusal::Denied("acp_delegation_deadline")); + } + let arguments = ApprovalArguments { + harness_id: request.harness_id.clone(), + task: request.task.clone(), + config_version: self.inner.config_version, + pin_version, + workspace: workspace.path.clone(), + owner: snapshot.owner.clone(), + new_session, + }; + let arguments_json = serde_json::to_string(&arguments) + .map_err(|_| AcpPolicyRefusal::Failed("acp_approval_invalid"))?; + let preview = build_preview( + &request.harness_id, + &workspace.path, + new_session, + &request.task, + )?; + let payload = json!({ + "id": approval_id, + "run_id": scope.run_id, + "session_id": scope.session_id, + "tool_call_id": scope.tool_call_id, + "tool_name": DELEGATION_TOOL_NAME, + "arguments_json": arguments_json, + "risk_class": "execute", + "decision_scope": "", + "one_time": 1, + "requested_at_ms": now_ms, + "expires_at_ms": expires_at_ms, + }); + let persistence = self.inner.persistence.clone(); + let result = blocking(move || persistence.approval_request(&payload)).await?; + let row = first_row(&result).ok_or(AcpPolicyRefusal::Failed("acp_approval_unavailable"))?; + if row.first().and_then(Value::as_str) != Some(approval_id.as_str()) { + return Err(AcpPolicyRefusal::Failed("acp_approval_unavailable")); + } + Ok(AcpApprovalChallenge { + approval_id, + preview, + expires_at_ms, + }) + } + + /// Executes one approved delegation. + /// + /// Every refusal before the spawn point returns without creating a process. + pub async fn delegate( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + witness: &AcpApprovalWitness, + cancellation: &RunCancellation, + ) -> AcpDelegationResult { + let harness_id = request.harness_id.clone(); + match self + .delegate_inner(scope, request, witness, cancellation) + .await + { + Ok(result) => result, + Err(refusal) => { + AcpDelegationResult::refusal(&harness_id, refusal.status(), refusal.code()) + } + } + } + + async fn delegate_inner( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + witness: &AcpApprovalWitness, + cancellation: &RunCancellation, + ) -> Result { + validate_request(request)?; + let Some(launch) = self.inner.harnesses.get(&request.harness_id) else { + return Err(AcpPolicyRefusal::Denied("acp_harness_unknown")); + }; + if cancellation.requested().is_some() { + return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")); + } + 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 { + policy: &self.inner, + run_id: scope.run_id.clone(), + }; + + let mut snapshot = self.read_session(&scope.session_id).await?; + let workspace = admitted_workspace(&snapshot, &self.inner.allowed_roots)?; + let mut 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"))?; + 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); + let mut reclaim_lease = false; + 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() { + // The in-process pin gate is free here, so any visible lease + // belongs to an interrupted call. It may be reclaimed only when + // that call never published a prompt: the remote session state + // is still known. + let interrupted = doc + .calls + .get(&lease.call_id) + .map(|call| matches!(call.phase, CallPhase::Prepared | CallPhase::SessionBound)) + .unwrap_or(true); + if lease.call_id == scope.tool_call_id || !interrupted { + return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + } + reclaim_lease = true; + } + } + + // 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, &workspace, pin_version) + .await?; + + let deadline = effective_deadline(scope.run_deadline_ms); + if Instant::now() >= deadline { + return Err(AcpPolicyRefusal::Failed("acp_delegation_deadline")); + } + let permit = self + .inner + .quota + .clone() + .try_acquire_owned() + .map_err(|_| AcpPolicyRefusal::Busy("acp_delegation_capacity"))?; + + // Durable preparation before any process exists. + let call = AcpCallRecord { + call_id: scope.tool_call_id.clone(), + run_id: scope.run_id.clone(), + harness_id: request.harness_id.clone(), + approval_id: witness.approval_id.clone(), + phase: CallPhase::Prepared, + outcome: None, + prompt_intent_at_ms: 0, + }; + doc.calls.insert(scope.tool_call_id.clone(), call); + { + let pin = doc + .pins + .entry(request.harness_id.clone()) + .or_insert_with(|| { + AcpPin::new( + snapshot.owner.clone(), + &workspace, + launch.fingerprint.clone(), + ) + }); + if pin.active.is_some() && !reclaim_lease { + return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + } + pin.active = Some(ActiveLease { + call_id: scope.tool_call_id.clone(), + run_id: scope.run_id.clone(), + expires_at_ms: crate::domain::timestamp() + DELEGATION_DEADLINE_MS, + }); + pin.version += 1; + } + self.write_session(&mut snapshot, &doc).await?; + // Read-back fence: the durable lease must name this exact call. + // `session.touch` is not a compare-and-swap, so the in-process per-pin + // gate is the serialization point and this check refuses to proceed on + // a document that does not contain our own preparation. + { + let current = self.read_session(&scope.session_id).await?; + let current_doc = PinDocument::from_metadata(current.metadata.as_deref()); + let owned = current_doc + .pins + .get(&request.harness_id) + .and_then(|pin| pin.active.as_ref()) + .is_some_and(|lease| lease.call_id == scope.tool_call_id); + if !owned { + return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + } + snapshot.metadata = current.metadata; + } + + let launch_handle = AcpDelegationLaunch::new( + launch.command.clone(), + launch.arguments.clone(), + workspace.path.clone(), + ) + .map_err(|_| AcpPolicyRefusal::Failed("acp_delegation_invalid_launch"))?; + + let outcome = self + .run_call( + scope, + request, + launch_handle, + deadline, + cancellation, + &mut snapshot, + permit, + ) + .await?; + Ok(outcome) + } + + /// Drives one connection from spawn to settlement. + #[allow(clippy::too_many_arguments)] + async fn run_call( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + launch: AcpDelegationLaunch, + deadline: Instant, + cancellation: &RunCancellation, + snapshot: &mut SessionSnapshot, + permit: tokio::sync::OwnedSemaphorePermit, + ) -> Result { + let mut client = match DelegatedAcpClient::connect(launch, deadline).await { + Ok(client) => client, + Err(error) => { + return self + .settle_failed(scope, request, snapshot, error.code()) + .await; + } + }; + let observer = client.cleanup_observer(); + + let capabilities = match client.initialize().await { + Ok(capabilities) => capabilities, + Err(error) => { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, observer, permit) + .await; + } + return self + .settle_failed(scope, request, snapshot, error.code()) + .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() { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, observer, permit) + .await; + } + return self + .settle_failed(scope, request, snapshot, "acp_session_restore_unsupported") + .await; + } + match client.restore_session(existing.clone()).await { + Ok(_) => existing, + Err(error) => { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, observer, permit) + .await; + } + // A failed restore never falls back to `session/new`. + return self + .settle_failed(scope, request, snapshot, error.code()) + .await; + } + } + } + None => { + // Record that a remote session may exist before requesting it. + { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let pin = doc + .pins + .get_mut(&request.harness_id) + .ok_or(AcpPolicyRefusal::Failed("acp_pin_missing"))?; + pin.phase = PinPhase::Creating; + pin.version += 1; + self.write_session(snapshot, &doc).await?; + } + let created = match client.new_session().await { + Ok(created) => created, + Err(error) => { + let report = client.close().await; + // The peer may have created a session we cannot name. + let _ = self.mark_pin_unknown(scope, request, snapshot).await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, observer, permit) + .await; + } + return self + .settle_failed(scope, request, snapshot, error.code()) + .await; + } + }; + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterSessionCreate) { + let _ = client.close().await; + // The pin stays `Creating`: the ID was never persisted. + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + if created.is_empty() || created.len() > MAX_EXTERNAL_SESSION_ID_BYTES { + let _ = client.close().await; + let _ = self.mark_pin_unknown(scope, request, snapshot).await; + return Err(AcpPolicyRefusal::Failed("acp_session_create_failed")); + } + // Persist the peer ID *before* any prompt can be sent. + { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let pin = doc + .pins + .get_mut(&request.harness_id) + .ok_or(AcpPolicyRefusal::Failed("acp_pin_missing"))?; + pin.phase = PinPhase::Bound; + pin.external_session_id = Some(created.clone()); + pin.version += 1; + let call = doc + .calls + .get_mut(&scope.tool_call_id) + .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; + call.phase = CallPhase::SessionBound; + self.write_session(snapshot, &doc).await?; + } + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterSessionPersisted) { + let _ = client.close().await; + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + created + } + }; + + if cancellation.requested().is_some() { + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, observer, permit) + .await; + } + // No prompt was sent: the pin keeps its known session. + return self + .settle_outcome( + scope, + request, + snapshot, + SettledOutcome { + status: AcpDelegationStatus::Cancelled, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_delegation_cancelled".to_string()), + }, + true, + ) + .await; + } + + // Durable prompt-send intent, strictly after the bound ID write. + { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let call = doc + .calls + .get_mut(&scope.tool_call_id) + .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; + call.phase = CallPhase::PromptIntent; + call.prompt_intent_at_ms = crate::domain::timestamp(); + if let Some(pin) = doc.pins.get_mut(&request.harness_id) { + pin.phase = PinPhase::Bound; + pin.version += 1; + } + self.write_session(snapshot, &doc).await?; + } + + // The in-flight prompt future borrows the client, so it is dropped + // before the client is consumed by `close`. + let prompt_outcome = { + let prompt = client.prompt(&session_id, &request.task); + tokio::pin!(prompt); + loop { + tokio::select! { + result = &mut prompt => break result, + _ = tokio::time::sleep(Duration::from_millis(20)) => { + if cancellation.requested().is_some() { + break Err(AcpDelegationError::Cancelled); + } + if Instant::now() >= deadline { + break Err(AcpDelegationError::DeadlineExceeded); + } + } + } + } + }; + + 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::DeferredCleanupConfirmed => ( + CleanupProof::Confirmed(crate::acp::AcpCleanupReport { + direct_child_reaped: true, + exit_status: None, + group_signal_sent: true, + forced: true, + group_clear: true, + cleanup_confirmed: true, + }), + "acp_prompt_unsettled", + ), + AcpPolicyFault::CleanupObserverLost => { + (CleanupProof::Lost, "acp_cleanup_unverified") + } + _ => ( + CleanupProof::Unconfirmed(unconfirmed_report()), + "acp_cleanup_unverified", + ), + }; + self.settle_after_cleanup( + scope, + &request.harness_id, + proof, + Some(permit), + expected_version, + ) + .await; + return Ok(AcpDelegationResult::refusal( + &request.harness_id, + AcpDelegationStatus::Indeterminate, + code, + )); + } + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, observer, permit) + .await; + } + + let (settled, keeps_binding) = match prompt_outcome { + Ok(result) => { + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterPromptPublished) { + let _ = self.mark_pin_unknown(scope, request, snapshot).await; + 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, + ) + } + Err(AcpDelegationError::DeadlineExceeded) => ( + SettledOutcome { + status: AcpDelegationStatus::Timeout, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some("acp_delegation_deadline".to_string()), + }, + false, + ), + Err(AcpDelegationError::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, + ), + Err(error) => ( + SettledOutcome { + status: AcpDelegationStatus::Failed, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(error.code().to_string()), + }, + false, + ), + }; + self.settle_outcome(scope, request, snapshot, settled, keeps_binding) + .await + } + + /// Settles a call that never published a prompt. The pin keeps its durable + /// binding, so a later approved call can restore the same external session. + async fn settle_failed( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &mut SessionSnapshot, + code: &'static str, + ) -> Result { + self.settle_outcome( + scope, + request, + snapshot, + SettledOutcome { + status: AcpDelegationStatus::Failed, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code.to_string()), + }, + true, + ) + .await + } + + /// One durable write settles the outcome and releases the pin lease. + /// + /// `keeps_binding` distinguishes a call that never published a prompt (the + /// external session is still valid) from one whose remote effect is + /// unknown (the pin must not be reused). + async fn settle_outcome( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &mut SessionSnapshot, + outcome: SettledOutcome, + keeps_binding: bool, + ) -> Result { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let call = doc + .calls + .get_mut(&scope.tool_call_id) + .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; + call.phase = CallPhase::Settled; + call.outcome = Some(outcome.clone()); + if let Some(pin) = doc.pins.get_mut(&request.harness_id) { + pin.active = None; + if !keeps_binding { + pin.phase = PinPhase::Unknown; + } + pin.version += 1; + } + doc.prune(); + self.write_session(snapshot, &doc).await?; + Ok(outcome.to_result(&request.harness_id, false)) + } + + /// Marks the pin as un-reusable after an unknown remote effect. + async fn mark_pin_unknown( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + if let Some(pin) = doc.pins.get_mut(&request.harness_id) { + pin.phase = PinPhase::Unknown; + pin.active = None; + pin.version += 1; + } + if let Some(call) = doc.calls.get_mut(&scope.tool_call_id) + && call.phase != CallPhase::Settled + { + call.phase = CallPhase::PromptIntent; + } + let _ = request; + self.write_session(snapshot, &doc).await + } + + /// 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() + } + + /// 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 charged slot + /// to [`Self::settle_after_cleanup`] once the proof resolves. + async fn hold_until_cleanup( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + observer: crate::acp::AcpCleanupObserver, + permit: tokio::sync::OwnedSemaphorePermit, + ) -> Result { + let policy = self.clone(); + let scope = scope.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); + tokio::spawn(async move { + 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, 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. + /// + /// Only a positive proof (`cleanup_confirmed`) releases the charged slot, + /// exactly once. A lost observer or an explicitly unconfirmed report keeps + /// the slot in an explicit quarantine entry for the rest of the service + /// lifetime, and leaves the durable pin indeterminate. The call itself is + /// never rewritten as a success and its recorded outcome can only be + /// replayed as `indeterminate`. + /// + /// The pin is only cleared when it still carries this exact call and the + /// version this policy last wrote, so a later owner can never be cleared by + /// an old settlement. + async fn settle_after_cleanup( + &self, + scope: &AcpDelegationScope, + harness_id: &str, + proof: CleanupProof, + permit: Option, + expected_version: u64, + ) { + 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" + }; + if let Ok(mut snapshot) = self.read_session(&scope.session_id).await { + let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + let mut changed = false; + if let Some(call) = doc.calls.get_mut(&scope.tool_call_id) + && call.phase != CallPhase::Settled + { + call.phase = CallPhase::Settled; + call.outcome = Some(SettledOutcome { + status: AcpDelegationStatus::Indeterminate, + text: String::new(), + stop_reason: None, + truncated: false, + code: Some(code.to_string()), + }); + changed = true; + } + let owns_pin = doc.pins.get(harness_id).is_some_and(|pin| { + pin.version == expected_version + && pin.active.as_ref().is_some_and(|lease| { + lease.call_id == scope.tool_call_id && lease.run_id == scope.run_id + }) + }); + if owns_pin { + let pin = doc.pins.get_mut(harness_id).expect("pin checked above"); + pin.phase = if confirmed { + PinPhase::Bound + } else { + PinPhase::Unknown + }; + pin.active = None; + pin.version += 1; + changed = true; + } + if changed { + let _ = self.write_session(&mut snapshot, &doc).await; + } + } + match (confirmed, permit) { + // The single proven release: the supervisor proved that no owned + // process remains. + (true, Some(permit)) => drop(permit), + // Unproven cleanup keeps the real capacity charged. The permit is + // parked in an explicit service-lifetime quarantine entry instead + // of being forgotten or transferred to a new delegation. + (false, Some(permit)) => { + self.inner + .quarantine + .lock() + .expect("acp quarantine") + .push(QuarantinedSlot { + pin_key: format!("{}:{}", scope.session_id, harness_id), + call_id: scope.tool_call_id.clone(), + _permit: permit, + }); + } + (_, None) => {} + } + } + + /// 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, + ) { + self.settle_after_cleanup( + scope, + harness_id, + CleanupProof::Unconfirmed(unconfirmed_report()), + None, + expected_version, + ) + .await; + } + + async fn validate_witness( + &self, + witness: &AcpApprovalWitness, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &SessionSnapshot, + workspace: &AdmittedWorkspace, + pin_version: u64, + ) -> Result<(), AcpPolicyRefusal> { + 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")); + } + // A delegated external process always needs a human decision: the + // automatic reviewer path may never produce a usable witness. + if field(13) != Some("user") { + return Err(AcpPolicyRefusal::Denied("acp_approval_not_user")); + } + 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")); + } + let arguments = field(5).ok_or(AcpPolicyRefusal::Denied("acp_approval_mismatch"))?; + let arguments: ApprovalArguments = serde_json::from_str(arguments) + .map_err(|_| AcpPolicyRefusal::Denied("acp_approval_mismatch"))?; + let expected = ApprovalArguments { + harness_id: request.harness_id.clone(), + task: request.task.clone(), + config_version: self.inner.config_version, + pin_version, + workspace: workspace.path.clone(), + owner: snapshot.owner.clone(), + new_session: pin_version == 0, + }; + if arguments != expected { + return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); + } + Ok(()) + } + + 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")) + } + + /// Merges one private delegation document into the session metadata. + /// + /// `session.touch` is a single atomic `json_patch` of the top-level key, so + /// callers see either the previous or the new document, never a fragment. + async fn write_session( + &self, + snapshot: &mut SessionSnapshot, + doc: &PinDocument, + ) -> Result<(), AcpPolicyRefusal> { + let persistence = self.inner.persistence.clone(); + let payload = snapshot.touch_payload(doc)?; + let merged = serde_json::to_string(&json!({ METADATA_KEY: doc })) + .map_err(|_| AcpPolicyRefusal::Failed("acp_pin_invalid"))?; + let result = blocking(move || persistence.session_touch(&payload)).await?; + snapshot.metadata = first_row(&result) + .and_then(SessionSnapshot::from_row) + .and_then(|fresh| fresh.metadata) + .or(Some(merged)); + Ok(()) + } + + 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() + } +} + +/// A report that explicitly did not prove cleanup. +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, + _permit: tokio::sync::OwnedSemaphorePermit, +} + +struct RunGate<'a> { + policy: &'a PolicyInner, + run_id: String, +} + +impl Drop for RunGate<'_> { + fn drop(&mut self) { + self.policy + .per_run + .lock() + .expect("acp per-run gate") + .remove(&self.run_id); + } +} + +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(); + 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 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}")) +} + +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 effective_deadline(run_deadline_ms: Option) -> Instant { + let now_ms = crate::domain::timestamp(); + let deadline_ms = effective_deadline_ms(run_deadline_ms, now_ms); + let remaining = deadline_ms.saturating_sub(now_ms); + Instant::now() + Duration::from_millis(remaining) +} + +fn build_preview( + harness_id: &str, + workspace: &str, + new_session: bool, + task: &str, +) -> Result { + let mode = if new_session { + "a new external session" + } else { + "the bound external session" + }; + let (excerpt, extra) = if task.len() > PREVIEW_TASK_BYTES { + let mut end = PREVIEW_TASK_BYTES; + while !task.is_char_boundary(end) { + end -= 1; + } + (&task[..end], task.len() - end) + } else { + (task, 0) + }; + let mut preview = format!( + "Delegate to ACP harness `{harness_id}` in workspace `{workspace}` using {mode}.\n\ + Task: {excerpt}" + ); + if extra > 0 { + preview.push_str(&format!("\n({extra} more task bytes not shown)")); + } + preview.push_str( + "\nThe 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.", + ); + 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; +} + +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")), + } +} + +fn first_row(value: &Value) -> Option> { + sqlite_storage_first_row(value) +} + +/// Admitted workspace resolved from the session's authoritative binding. +struct AdmittedWorkspace { + path: String, + generation: u64, +} + +fn admitted_workspace( + snapshot: &SessionSnapshot, + allowed_roots: &[PathBuf], +) -> Result { + let workspace = snapshot + .metadata + .as_deref() + .and_then(|metadata| serde_json::from_str::(metadata).ok()) + .and_then(|metadata| metadata.get("workspace").cloned()) + .and_then(|workspace| serde_json::from_value::(workspace).ok()) + .ok_or(AcpPolicyRefusal::Denied("acp_workspace_unbound"))?; + let path = PathBuf::from(&workspace.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: workspace.canonical_path, + generation: workspace.generation, + }) +} + +#[derive(Clone, Debug, Deserialize)] +struct BoundWorkspace { + canonical_path: String, + #[serde(default)] + #[allow(dead_code)] + selector: String, + #[serde(default)] + generation: u64, +} + +/// Durable session columns echoed back by `session.touch`. +struct SessionSnapshot { + session_id: String, + owner: String, + status: String, + system_prompt: String, + model: String, + provider: String, + toolset_hash: String, + title: String, + end_reason: String, + metadata: Option, +} + +impl SessionSnapshot { + fn from_row(row: Vec) -> Option { + let text = |index: usize| { + row.get(index) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + Some(Self { + session_id: row.first()?.as_str()?.to_string(), + owner: text(6), + status: text(8), + system_prompt: text(9), + model: text(10), + provider: text(11), + toolset_hash: text(12), + metadata: row.get(13).and_then(Value::as_str).map(str::to_string), + title: text(17), + end_reason: text(18), + }) + } + + fn touch_payload(&self, doc: &PinDocument) -> Result { + let metadata = serde_json::to_string(&json!({ METADATA_KEY: doc })) + .map_err(|_| AcpPolicyRefusal::Failed("acp_pin_invalid"))?; + Ok(json!({ + "session_id": self.session_id, + "status": self.status, + "generation": 1, + "system_prompt": self.system_prompt, + "model": self.model, + "provider": self.provider, + "toolset_hash": self.toolset_hash, + "metadata_json": metadata, + "title": self.title, + "end_reason": self.end_reason, + "now_ms": crate::domain::timestamp(), + })) + } +} + +/// Private durable delegation document kept under `$.acp_delegation`. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +struct PinDocument { + #[serde(default)] + version: u64, + #[serde(default)] + pins: BTreeMap, + #[serde(default)] + calls: BTreeMap, +} + +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(); + }; + value + .get(METADATA_KEY) + .cloned() + .and_then(|value| serde_json::from_value(value).ok()) + .unwrap_or_default() + } + + /// Keeps the record bounded: the newest [`MAX_BINDINGS_PER_SESSION`] pins + /// and the newest 32 settled calls survive. + fn prune(&mut self) { + while self.pins.len() > MAX_BINDINGS_PER_SESSION { + let victim = self + .pins + .iter() + .filter(|(_, pin)| pin.active.is_none()) + .min_by_key(|(_, pin)| pin.version) + .map(|(key, _)| key.clone()); + match victim { + Some(key) => { + self.pins.remove(&key); + } + None => break, + } + } + while self.calls.len() > 32 { + let victim = self + .calls + .iter() + .filter(|(_, call)| call.phase == CallPhase::Settled) + .map(|(key, _)| key.clone()) + .next(); + match victim { + Some(key) => { + self.calls.remove(&key); + } + None => break, + } + } + } +} + +#[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, +} + +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, + 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, + 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. + Prepared, + /// The peer session ID is durable; no prompt intent was written. + SessionBound, + /// 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::Prepared => crate::effects::DelegationSettlement::NotStarted, + Self::SessionBound | Self::PromptIntent => { + crate::effects::DelegationSettlement::Indeterminate + } + Self::Settled => crate::effects::DelegationSettlement::Settled, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct AcpCallRecord { + call_id: String, + run_id: String, + harness_id: String, + approval_id: String, + phase: CallPhase, + #[serde(default)] + outcome: Option, + #[serde(default)] + prompt_intent_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_pin_invalid", + "acp_call_missing", + "acp_pin_missing", + "acp_call_record_invalid", + ]; + CODES.iter().copied().find(|known| *known == code) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct ApprovalArguments { + harness_id: String, + task: String, + config_version: u64, + pin_version: u64, + workspace: String, + owner: String, + new_session: bool, +} diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs new file mode 100644 index 0000000..17fe6ad --- /dev/null +++ b/tests/acp_delegation_policy_tests.rs @@ -0,0 +1,1808 @@ +//! ACP delegation policy contract: launch table, approval binding, durable +//! session pinning and call settlement. +//! +//! Every test drives the real [`AcpDelegationPolicy`] against the real gateway +//! durable store on an isolated fixture database and the independent +//! `tests/fixtures/acp_policy` stdio harness. Spawn counts come from the +//! harness' own append-only spawn log, so a refusal that never spawned a +//! process is observable rather than inferred. No model, provider, credential +//! or network path is involved. + +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::config::AgentGatewayConfig; +use rustscript_agent::config_file::ConfigFile; +use rustscript_agent::gateway::AgentGatewayState; +use rustscript_agent::gateway::store::GatewayPersistence; +use rustscript_agent::runtime::rss_runner::RunCancellation; +use rustscript_agent::service::acp_session_pins::{ + AcpApprovalWitness, AcpDelegationPolicy, AcpDelegationRequest, AcpDelegationScope, + AcpDelegationStatus, +}; +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, + 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"); + fs::create_dir_all(&workspace).expect("create policy workspace"); + let workspace = fs::canonicalize(&workspace).expect("canonical workspace"); + let binary = binary_path(); + Self { + root, + workspace, + 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_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 open_state(env: &Env) -> AgentGatewayState { + AgentGatewayState::with_sqlite_path(AgentGatewayConfig::default(), env.db()) + .expect("open isolated gateway state") +} + +fn seed( + persistence: &GatewayPersistence, + session_id: &str, + run_id: &str, + owner: &str, + workspace: &Path, +) { + let metadata = serde_json::to_string(&json!({ + "workspace": { + "selector": "name:policy", + "canonical_path": workspace.display().to_string(), + "selected_name": "policy", + "generation": 1 + } + })) + .expect("workspace metadata"); + 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": metadata, + "title": "", + "end_reason": "", + "now_ms": 1_700_000_000_000_i64, + })) + .expect("seed policy session"); + persistence + .run_create(&json!({ + "id": run_id, + "session_id": session_id, + "parent_run_id": "", + "input_json": "{}", + "provider": "policy-provider", + "model": "policy-model", + "script_hash": "policy-script", + "idempotency_scope": "", + "idempotency_key": "", + "now_ms": 1_700_000_000_000_i64, + })) + .expect("seed policy run"); + persistence + .run_transition(&json!({ + "run_id": run_id, + "from_status": "queued", + "to_status": "running", + "error_code": "", + "error_message": "", + "recovery_reason": "", + "now_ms": 1_700_000_000_001_i64, + })) + .expect("start policy run"); +} + +fn scope(run_id: &str, session_id: &str, call_id: &str) -> AcpDelegationScope { + AcpDelegationScope { + run_id: run_id.to_string(), + session_id: session_id.to_string(), + tool_call_id: call_id.to_string(), + run_deadline_ms: None, + } +} + +fn request(harness_id: &str, task: &str) -> AcpDelegationRequest { + AcpDelegationRequest { + harness_id: harness_id.to_string(), + task: task.to_string(), + } +} + +async fn approve( + policy: &AcpDelegationPolicy, + persistence: &GatewayPersistence, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, +) -> AcpApprovalWitness { + let challenge = policy + .request_approval(scope, request) + .await + .expect("approval challenge"); + persistence + .approval_resolve(&json!({ + "id": challenge.approval_id, + "run_id": scope.run_id, + "state": "approved", + "resolver": "user", + "decision_reason": "policy fixture approval", + "resolved_at_ms": 1, + })) + .expect("resolve approval"); + AcpApprovalWitness::new(challenge.approval_id) +} + +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) +} + +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; + } +} + +#[tokio::test] +async fn default_config_installs_no_policy_and_unknown_ids_never_spawn() { + let env = Env::new("default-off"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + let plain = ConfigFile::from_str("version: 1\n").expect("default config"); + assert!( + AcpDelegationPolicy::install(&plain, persistence.clone()) + .expect("install default") + .is_none(), + "an empty table must leave the capability disabled" + ); + let disabled = state + .service() + .delegate_acp( + scope("run-1", "session-1", "call-1"), + request("fixture", "task"), + AcpApprovalWitness::new("approval"), + &RunCancellation::new(), + ) + .await; + assert_eq!(disabled.status, AcpDelegationStatus::Denied); + assert_eq!(disabled.code, Some("acp_delegation_disabled")); + + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install policy") + .expect("configured policy"); + let unknown = policy + .delegate( + &scope("run-1", "session-1", "call-1"), + &request("missing", "task"), + &AcpApprovalWitness::new("approval"), + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + + // Pending (never resolved) approval. + let pending_scope = scope("run-1", "session-1", "call-pending"); + let challenge = policy + .request_approval(&pending_scope, &request("fixture", "pending task")) + .await + .expect("challenge"); + let pending = policy + .delegate( + &pending_scope, + &request("fixture", "pending task"), + &AcpApprovalWitness::new(challenge.approval_id), + &RunCancellation::new(), + ) + .await; + assert_eq!(pending.status, AcpDelegationStatus::Denied); + assert_eq!(pending.code, Some("acp_approval_mismatch")); + + // Explicitly denied approval. + let denied_scope = scope("run-1", "session-1", "call-denied"); + let challenge = policy + .request_approval(&denied_scope, &request("fixture", "denied task")) + .await + .expect("challenge"); + persistence + .approval_resolve(&json!({ + "id": challenge.approval_id, + "run_id": "run-1", + "state": "denied", + "resolver": "user", + "decision_reason": "no", + "resolved_at_ms": 2, + })) + .expect("deny approval"); + let denied = policy + .delegate( + &denied_scope, + &request("fixture", "denied task"), + &AcpApprovalWitness::new(challenge.approval_id), + &RunCancellation::new(), + ) + .await; + assert_eq!(denied.status, AcpDelegationStatus::Denied); + assert_eq!(denied.code, Some("acp_approval_mismatch")); + + // No workspace binding at all on the session. + persistence + .session_create(&json!({ + "id": "session-3", + "profile": "default", + "platform": "policy-fixture", + "account_id": "session-3", + "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"); + persistence + .run_create(&json!({ + "id": "run-3", + "session_id": "session-3", + "parent_run_id": "", + "input_json": "{}", + "provider": "policy-provider", + "model": "policy-model", + "script_hash": "policy-script", + "idempotency_scope": "", + "idempotency_key": "", + "now_ms": 1_700_000_000_000_i64, + })) + .expect("seed unbound run"); + persistence + .run_transition(&json!({ + "run_id": "run-3", + "from_status": "queued", + "to_status": "running", + "error_code": "", + "error_message": "", + "recovery_reason": "", + "now_ms": 1_700_000_000_001_i64, + })) + .expect("start unbound run"); + let unbound_scope = scope("run-3", "session-3", "call-unbound"); + let refusal = policy + .request_approval(&unbound_scope, &request("fixture", "x")) + .await + .expect_err("a session without an admitted workspace cannot even ask"); + assert_eq!(refusal.code(), "acp_workspace_unbound"); + assert_eq!(env.spawn_count(), 0, "refusals must not spawn"); +} + +#[tokio::test] +async fn first_call_creates_and_later_calls_restore_the_same_session() { + let env = Env::new("create-restore"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + + let first_scope = scope("run-1", "session-1", "call-1"); + let first_witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "first"), + ) + .await; + let first = policy + .delegate( + &first_scope, + &request("fixture", "first"), + &first_witness, + &RunCancellation::new(), + ) + .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 doc = pin_document(&persistence, "session-1"); + 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()); + + seed( + &persistence, + "session-1", + "run-2", + "owner-1", + &env.workspace, + ); + let second_scope = scope("run-2", "session-1", "call-2"); + let second_witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "second"), + ) + .await; + let second = policy + .delegate( + &second_scope, + &request("fixture", "second"), + &second_witness, + &RunCancellation::new(), + ) + .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, "session-1"); + 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_the_durable_result_without_spawning() { + let env = Env::new("replay"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "once"), + ) + .await; + let first = policy + .delegate( + &call_scope, + &request("fixture", "once"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed); + assert_eq!( + policy + .call_settlement("session-1", "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Settled + ); + assert_eq!( + policy + .call_settlement("session-1", "never-used") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::NotStarted + ); + let spawns = env.spawn_count(); + let replay = policy + .delegate( + &call_scope, + &request("fixture", "once"), + &witness, + &RunCancellation::new(), + ) + .await; + assert!(replay.replayed); + assert_eq!(replay.status, first.status); + assert_eq!(replay.text, first.text); + 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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "before"), + ) + .await; + let result = policy + .delegate( + &call_scope, + &request("fixture", "before"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Completed); + } + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + // Restart recovery terminates the previously active run; a fresh admitted + // run in the same RSS session is what needs the durable binding. + seed( + &persistence, + "session-1", + "run-2", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-2", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "after"), + ) + .await; + let result = policy + .delegate( + &call_scope, + &request("fixture", "after"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + // Forget the peer session: the restore request is now rejected. + fs::write(env.store(), "").expect("clear peer store"); + let second_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let result = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + env.set_caps("none"); + let second_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let result = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + env.set_caps("load"); + let second_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let result = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + + persistence + .run_transition(&json!({ + "run_id": "run-1", + "from_status": "running", + "to_status": "completed", + "error_code": "", + "error_message": "", + "recovery_reason": "", + "now_ms": 1_700_000_000_002_i64, + })) + .expect("close first run"); + // A second admitted workspace inside the configured root. + let other = env.workspace.join("other-workspace"); + fs::create_dir_all(&other).expect("second workspace"); + let other = fs::canonicalize(&other).expect("canonical second workspace"); + persistence + .session_workspace_bind( + "session-1", + &json!({ + "selector": "name:other", + "canonical_path": other.display().to_string(), + "selected_name": "other", + "generation": 2 + }), + ) + .expect("rebind workspace"); + + seed(&persistence, "session-1", "run-2", "owner-1", &other); + let second_scope = scope("run-2", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let result = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 approval_is_bound_to_the_exact_task_and_pin_version() { + let env = Env::new("approval-binding"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "approved task"), + ) + .await; + let stale = policy + .delegate( + &call_scope, + &request("fixture", "different task"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(stale.status, AcpDelegationStatus::Denied); + assert_eq!(stale.code, Some("acp_approval_stale")); + assert_eq!(env.spawn_count(), 0); +} + +#[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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy.arm_fault(AcpPolicyFault::AfterSessionCreate); + let cut = policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + assert_eq!(cut.code, Some("acp_session_indeterminate")); + let doc = pin_document(&persistence, "session-1"); + assert_eq!(doc["pins"]["fixture"]["phase"], "creating"); + assert!(doc["pins"]["fixture"]["external_session_id"].is_null()); + + let spawns = env.spawn_count(); + let second_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let blocked = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy.arm_fault(AcpPolicyFault::AfterSessionPersisted); + let cut = policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + let doc = pin_document(&persistence, "session-1"); + 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"); + + // The original call can never be restarted. + let spawns = env.spawn_count(); + let restart = policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .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-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let resumed = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy.arm_fault(AcpPolicyFault::AfterPromptPublished); + let cut = policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(cut.status, AcpDelegationStatus::Failed); + let doc = pin_document(&persistence, "session-1"); + assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); + assert_eq!(doc["calls"]["call-1"]["phase"], "prompt_intent"); + + let spawns = env.spawn_count(); + let second_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let blocked = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + seed( + &persistence, + "session-1", + "run-2", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install( + &env.config("fixture", &["--delay-ms", "5000"]), + persistence.clone(), + ) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let second_scope = scope("run-2", "session-1", "call-2"); + let first_witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + let second_witness = approve( + &policy, + &persistence, + &second_scope, + &request("fixture", "b"), + ) + .await; + let first_policy = policy.clone(); + let first = tokio::spawn(async move { + first_policy + .delegate( + &first_scope, + &request("fixture", "a"), + &first_witness, + &RunCancellation::new(), + ) + .await + }); + wait_for(|| env.spawn_count() == 1, "the first delegation to spawn").await; + let second = policy + .delegate( + &second_scope, + &request("fixture", "b"), + &second_witness, + &RunCancellation::new(), + ) + .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 per_run_gate_and_service_quota_refuse_instead_of_queueing() { + let env = Env::new("quota"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install( + &env.config("fixture", &["--delay-ms", "8000"]), + persistence.clone(), + ) + .expect("install") + .expect("policy"); + + let first_scope = scope("run-1", "session-1", "call-1"); + let first_witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + let first_policy = policy.clone(); + let first = tokio::spawn(async move { + first_policy + .delegate( + &first_scope, + &request("fixture", "a"), + &first_witness, + &RunCancellation::new(), + ) + .await + }); + wait_for(|| env.spawn_count() == 1, "first spawn").await; + // Same run: refused before any read or spawn. + let same_run_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &same_run_scope, + &request("fixture", "b"), + ) + .await; + let same_run = policy + .delegate( + &same_run_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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 session = format!("session-{index}"); + let run = format!("run-{index}"); + seed(&persistence, &session, &run, "owner-1", &env.workspace); + let call_scope = scope(&run, &session, &format!("call-{index}")); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "fill"), + ) + .await; + let policy = policy.clone(); + handles.push(tokio::spawn(async move { + policy + .delegate( + &call_scope, + &request("fixture", "fill"), + &witness, + &RunCancellation::new(), + ) + .await + })); + } + wait_for(|| policy.available_processes() == 0, "the quota to fill").await; + seed( + &persistence, + "session-5", + "run-5", + "owner-1", + &env.workspace, + ); + let overflow_scope = scope("run-5", "session-5", "call-5"); + let witness = approve( + &policy, + &persistence, + &overflow_scope, + &request("fixture", "overflow"), + ) + .await; + let overflow = policy + .delegate( + &overflow_scope, + &request("fixture", "overflow"), + &witness, + &RunCancellation::new(), + ) + .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!(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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + persistence + .session_delete("session-1") + .expect("delete session"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let new_scope = scope("run-1", "session-1", "call-2"); + let witness = approve(&policy, &persistence, &new_scope, &request("fixture", "b")).await; + let result = policy + .delegate( + &new_scope, + &request("fixture", "b"), + &witness, + &RunCancellation::new(), + ) + .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); +} + +#[tokio::test] +async fn automatic_reviewer_approval_is_never_accepted() { + let env = Env::new("auto-approval"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let challenge = policy + .request_approval(&call_scope, &request("fixture", "task")) + .await + .expect("challenge"); + persistence + .approval_resolve(&json!({ + "id": challenge.approval_id, + "run_id": "run-1", + "state": "approved", + "resolver": "guardian", + "decision_reason": "automatic", + "resolved_at_ms": 1, + })) + .expect("resolve approval"); + let result = policy + .delegate( + &call_scope, + &request("fixture", "task"), + &AcpApprovalWitness::new(challenge.approval_id), + &RunCancellation::new(), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Denied); + assert_eq!(result.code, Some("acp_approval_not_user")); + assert_eq!(env.spawn_count(), 0, "an automatic approval must not spawn"); +} + +#[tokio::test] +async fn distinct_harnesses_keep_distinct_sessions() { + let env = Env::new("harness-isolation"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install( + &env.config_multi(&[("fixture", &[]), ("other", &[])]), + persistence.clone(), + ) + .expect("install") + .expect("policy"); + + let first_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &first_scope, + &request("fixture", "a"), + ) + .await; + let first = policy + .delegate( + &first_scope, + &request("fixture", "a"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(first.status, AcpDelegationStatus::Completed); + + let second_scope = scope("run-1", "session-1", "call-2"); + let witness = approve(&policy, &persistence, &second_scope, &request("other", "b")).await; + let second = policy + .delegate( + &second_scope, + &request("other", "b"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(second.status, AcpDelegationStatus::Completed, "{second:?}"); + assert_eq!( + second.text, "ctx=0;reply=policy-reply", + "the second harness must not share the first harness' history" + ); + let doc = pin_document(&persistence, "session-1"); + let first_id = doc["pins"]["fixture"]["external_session_id"] + .as_str() + .expect("fixture id") + .to_string(); + let second_id = doc["pins"]["other"]["external_session_id"] + .as_str() + .expect("other id") + .to_string(); + assert_ne!(first_id, second_id); + assert_eq!(env.recorded("session/new"), 2); + assert_eq!(env.spawn_count(), 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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "task"), + ) + .await; + policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); + let result = policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &RunCancellation::new(), + ) + .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" + ); + + // Negative control: the charged slot is not released, and it is held by an + // explicit quarantine entry rather than being dropped. + assert_eq!(policy.available_processes(), 3); + assert_eq!(policy.quarantined_slots(), 1); + assert_eq!( + policy.quarantined_calls(), + vec![("session-1:fixture".to_string(), "call-1".to_string())] + ); + + let doc = pin_document(&persistence, "session-1"); + assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); + assert!(doc["pins"]["fixture"]["active"].is_null()); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + assert_eq!( + policy + .call_settlement("session-1", "call-1") + .await + .expect("settlement"), + rustscript_agent::effects::DelegationSettlement::Settled + ); + + // The recorded outcome replays as indeterminate: no success, no re-run and + // no second release. + let spawns = env.spawn_count(); + let replay = policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &RunCancellation::new(), + ) + .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!(policy.available_processes(), 3); + assert_eq!(policy.quarantined_slots(), 1); + + // The pin is indeterminate, so no later call may take it over. + let next_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &next_scope, + &request("fixture", "next"), + ) + .await; + let next = policy + .delegate( + &next_scope, + &request("fixture", "next"), + &witness, + &RunCancellation::new(), + ) + .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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "task"), + ) + .await; + policy.arm_fault(AcpPolicyFault::CleanupObserverLost); + let result = policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Indeterminate); + assert_eq!(result.code, Some("acp_cleanup_unverified")); + assert_eq!(policy.available_processes(), 3); + assert_eq!(policy.quarantined_slots(), 1); + let doc = pin_document(&persistence, "session-1"); + assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); +} + +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn confirmed_deferred_cleanup_releases_once_without_turning_it_into_success() { + use rustscript_agent::service::acp_session_pins::AcpPolicyFault; + + let env = Env::new("cleanup-confirmed"); + let state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "task"), + ) + .await; + policy.arm_fault(AcpPolicyFault::DeferredCleanupConfirmed); + let result = policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(result.status, AcpDelegationStatus::Indeterminate); + assert_eq!(result.code, Some("acp_prompt_unsettled")); + // Positive control: the proven cleanup releases the slot exactly once. + assert_eq!(policy.available_processes(), 4); + assert_eq!(policy.quarantined_slots(), 0); + + let doc = pin_document(&persistence, "session-1"); + assert_eq!(doc["pins"]["fixture"]["phase"], "bound"); + assert!(doc["pins"]["fixture"]["active"].is_null()); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + assert_eq!( + doc["calls"]["call-1"]["outcome"]["status"], "indeterminate", + "a cleanup success must not be rewritten as a prompt success" + ); + + let replay = policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &RunCancellation::new(), + ) + .await; + assert!(replay.replayed); + assert_eq!(replay.status, AcpDelegationStatus::Indeterminate); + assert_eq!(policy.available_processes(), 4, "the slot is released once"); + + // The binding itself is still known-good, so a newly approved call may + // resume it; that is a new call, not a replay of the lost prompt. + let next_scope = scope("run-1", "session-1", "call-2"); + let witness = approve( + &policy, + &persistence, + &next_scope, + &request("fixture", "next"), + ) + .await; + let next = policy + .delegate( + &next_scope, + &request("fixture", "next"), + &witness, + &RunCancellation::new(), + ) + .await; + assert_eq!(next.status, AcpDelegationStatus::Completed, "{next:?}"); + assert_eq!(env.recorded("session/new"), 1); + assert_eq!(env.recorded("session/resume"), 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 state = open_state(&env); + let persistence = state.persistence().expect("persistence"); + seed( + &persistence, + "session-1", + "run-1", + "owner-1", + &env.workspace, + ); + let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) + .expect("install") + .expect("policy"); + let call_scope = scope("run-1", "session-1", "call-1"); + let witness = approve( + &policy, + &persistence, + &call_scope, + &request("fixture", "task"), + ) + .await; + policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); + policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &RunCancellation::new(), + ) + .await; + let before = pin_document(&persistence, "session-1"); + // The old settlement is replayed with a stale version. It must not touch + // the current pin document. + policy + .settle_stale_cleanup_for_test(&call_scope, "fixture", 0) + .await; + let after = pin_document(&persistence, "session-1"); + assert_eq!(before, after); + assert_eq!(after["pins"]["fixture"]["phase"], "unknown"); +} diff --git a/tests/config_file_tests.rs b/tests/config_file_tests.rs index 85c31ba..6b1c31a 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_policy/build.rs b/tests/fixtures/acp_policy/build.rs new file mode 100644 index 0000000..a274cdb --- /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 0000000..d1d98b5 --- /dev/null +++ b/tests/fixtures/acp_policy/policy_agent.rs @@ -0,0 +1,378 @@ +//! 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, + delay_ms: u64, + hold: bool, +} + +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()); + 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 })); + 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.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 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); + }); + } + + 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) { + self.pending + .lock() + .expect("fixture pending") + .remove(session_id); + self.send(json!({ "jsonrpc": "2.0", "id": id, "result": { "stopReason": "end_turn" } })); + } +} + +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()), + 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), + hold: args.iter().any(|arg| arg == "--hold"), + }; + 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), + }; + 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)) + } + _ => {} + } + } +} From b207daedb645afaaaff819dd053efb8d6682773a Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 08:42:52 +0800 Subject: [PATCH 07/27] fix(acp): re-arbitrate parked prompt writes and close stdin on cleanup Re-check the recorded stop on every poll_write, so a frame parked before its first byte stays revocable and a partial frame is never appended to or followed by a cancel notification. Ingress only claims a response after the writer proved a complete frame. Take the child's stdin out of the shared wire and drop it after the connection is discarded, so a benign harness observes a real EOF and can exit before any group signal instead of being force-terminated. Anchor one absolute cleanup budget at the first observed stop and bound cancel-lock acquisition and cancel-line serialization to its drain slice, so blocked IO cannot delay group termination or reaping. --- src/acp/delegated_client.rs | 883 +++++++++++++++++++-------- tests/acp_delegation_client_tests.rs | 43 ++ 2 files changed, 684 insertions(+), 242 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 1b30b07..9aba76c 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -66,7 +66,7 @@ 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}; +use std::task::{Context, Poll, Waker}; use std::time::Duration; use agent_client_protocol::v1::schema::{ @@ -392,6 +392,13 @@ impl DelegatedAcpClient { let shared = Arc::new(Shared::new(shutdown_tx.subscribe(), deadline)); let wire = Arc::new(Wire::new(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)); @@ -407,7 +414,7 @@ impl DelegatedAcpClient { .name("rustscript-agent-delegation") .connect_with(transport, { let shared = shared.clone(); - let wire = wire.clone(); + let wire = actor_wire; async move |connection| { run_actor( connection, @@ -422,13 +429,14 @@ impl DelegatedAcpClient { } }), ); - // One absolute cleanup budget starts at the first cleanup step. - // A shutdown gets a small drain slice so group termination and - // reaping keep the remaining time in the same budget. + // One absolute cleanup budget is anchored at the first observed + // stop (shutdown, run deadline or caller withdrawal). A pending + // connection gets a bounded drain slice; group termination and + // reaping keep the remainder of the same budget. let cleanup_start = tokio::select! { - _result = &mut connection => Instant::now(), + _result = &mut connection => shared.mark_cleanup_start(), _ = supervisor_shutdown.changed() => { - let start = Instant::now(); + let start = shared.mark_cleanup_start(); let drain_deadline = (start + PROTOCOL_DRAIN_BUDGET).min(start + CLEANUP_BUDGET); let _ = timeout_at(drain_deadline, &mut connection).await; @@ -436,7 +444,14 @@ impl DelegatedAcpClient { } }; drop(connection); - let cleanup_deadline = cleanup_start + CLEANUP_BUDGET; + let cleanup_deadline = shared.cleanup_deadline(); + debug_assert_eq!(cleanup_start + CLEANUP_BUDGET, cleanup_deadline); + // 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 close_deadline = (cleanup_start + PROTOCOL_DRAIN_BUDGET).min(cleanup_deadline); + let _ = timeout_at(close_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 @@ -778,8 +793,14 @@ async fn run_actor( }; loop { tokio::select! { - _ = shutdown.changed() => return Ok(()), - _ = sleep_until(deadline) => return Ok(()), + _ = 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 { @@ -826,8 +847,9 @@ async fn run_actor( task, reply, }) => { + let mut reply = reply; let result = actor - .prompt(&session_id, &task, &mut shutdown, &reply) + .prompt(&session_id, &task, &mut shutdown, &mut reply) .await; let _ = reply.send(result); // One prompt per connection. The supervisor now closes @@ -952,7 +974,7 @@ impl Actor { session_id: &str, task: &str, shutdown: &mut watch::Receiver, - reply: &oneshot::Sender>, + reply: &mut oneshot::Sender>, ) -> Result { if !self.initialized { return Err(AcpDelegationError::NotInitialized); @@ -999,20 +1021,19 @@ impl Actor { Failed, } - let outcome = loop { - tokio::select! { - _ = shutdown.changed() => break Err(Stopped::Shutdown), - _ = sleep(Duration::from_millis(10)) => { - if reply.is_closed() { - break Err(Stopped::Withdrawn); - } - } - result = timeout_at(self.deadline, &mut response) => { - match result { - Err(_) => break Err(Stopped::Deadline), - Ok(Ok(response)) => break Ok(response), - Ok(Err(_)) => break Err(Stopped::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), } } }; @@ -1031,16 +1052,33 @@ impl Actor { 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 => { - let _ = self.wire.write_session_cancel(&request_id).await; + 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. It either discards the frame before any - // byte or completes it and writes the single cancel. - let _ = timeout( - Duration::from_millis(250), + // 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; @@ -1129,13 +1167,19 @@ enum PromptWire { Failed, } -/// Writer transition for the one prompt. `Writing` is set under the arbitration -/// lock immediately before the first write attempt and is the publication -/// linearization point. A stop that acquires the lock earlier transitions -/// `Armed` to `Discarded`, and the writer writes nothing. +/// 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, @@ -1204,6 +1248,10 @@ impl PromptGate { 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, } /// Frames handed to the SDK but not yet consumed by it. @@ -1244,6 +1292,10 @@ struct Shared { 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>, /// Wakes an actor waiting for the writer's terminal transition. settled: tokio::sync::Notify, } @@ -1285,25 +1337,36 @@ impl Shared { } } - /// Writer decision taken under the arbitration lock immediately before the - /// first write attempt. Returns `false` when the frame must be discarded - /// without touching the pipe. - fn begin_prompt_write(&self, request_id: &RawJsonRpcId) -> bool { - let stop = self.stop.as_ref().is_some_and(Stop::tripped); - let mut ingress = self.ingress.lock().unwrap(); - let Some(prompt) = ingress.prompt.as_mut() else { - return false; - }; - if prompt.id != *request_id || prompt.state != PromptState::Armed { - return false; - } - if prompt.cancel_requested || stop { - prompt.state = PromptState::Discarded; - ingress.expected = None; - return false; - } - prompt.state = PromptState::Writing; - true + fn stop_tripped(&self) -> bool { + self.stop.as_ref().is_some_and(Stop::tripped) + } + + /// 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 mut start = self.cleanup_start.lock().unwrap(); + *start.get_or_insert_with(Instant::now) + } + + 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 @@ -1325,27 +1388,6 @@ impl Shared { false } - fn partial_prompt_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.state = PromptState::Partial; - ingress.expected = None; - } - } - - fn failed_prompt_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.state == PromptState::Writing - { - prompt.state = PromptState::FailedNoBytes; - ingress.expected = None; - } - } - /// 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) { @@ -1360,39 +1402,49 @@ impl Shared { } /// Record an actor-observed stop. The writer, not this call, decides whether - /// any byte was exposed. + /// 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 Some(prompt) = ingress.prompt.as_mut() else { - return CancelAction::None; - }; - if prompt.id != *request_id { - return CancelAction::None; - } - match prompt.state { - PromptState::Armed | PromptState::Writing => { - if prompt.outcome != PromptOutcome::Outstanding { - return CancelAction::None; + 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 + } } - prompt.cancel_requested = true; - CancelAction::Deferred - } - PromptState::Complete => match prompt.outcome { - PromptOutcome::Outstanding => { - prompt.outcome = PromptOutcome::CancelClaimed; - CancelAction::SendNow + 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 } - // 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 @@ -1640,9 +1692,10 @@ impl Shared { /// 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 begun the - /// frame. A response that arrives while the prompt is still `Armed` cannot - /// come from a peer that received the request, so it is dropped. + /// 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) { @@ -1653,14 +1706,14 @@ impl Shared { && prompt.id == *request_id { match prompt.state { - PromptState::Writing | PromptState::Complete => { - prompt.state = PromptState::Complete; + 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, @@ -1700,7 +1753,11 @@ impl Shared { /// the single intentional `session/cancel`, and suppresses the SDK's deferred /// automatic `$/cancel_request` for the reserved prompt id. struct Wire { - stdin: tokio::sync::Mutex, + /// 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. @@ -1710,12 +1767,23 @@ struct Wire { impl Wire { fn new(stdin: ChildStdin, shared: Arc) -> Self { Self { - stdin: tokio::sync::Mutex::new(stdin), + 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(()); @@ -1733,35 +1801,30 @@ impl Wire { if self.poisoned.load(Ordering::Acquire) { return Ok(()); } + let Some(stdin) = stdin.as_mut() else { + return Ok(()); + }; match frame { OutgoingFrame::Prompt(id) => { - if !self.shared.begin_prompt_write(&id) { - self.shared.settle_prompt(); - return Ok(()); - } - let (result, wire) = write_prompt_frame(&mut *stdin, line).await; + 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(&mut stdin, &id).await; + 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.poisoned.store(true, Ordering::Release); - self.shared.partial_prompt_write(&id); + self.poison(); } - PromptWire::Failed => { - self.shared.failed_prompt_write(&id); - } - PromptWire::Pending | PromptWire::Discarded => {} + PromptWire::Failed | PromptWire::Pending | PromptWire::Discarded => {} } self.shared.settle_prompt(); result } - _ => write_plain_line(&mut *stdin, line).await, + _ => write_plain_line(stdin, line).await, } } @@ -1776,10 +1839,11 @@ impl Wire { return Ok(()); }; let mut stdin = self.stdin.lock().await; - let result = if self.poisoned.load(Ordering::Acquire) { - Ok(()) - } else { - write_cancel_line(&mut *stdin, &session).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); @@ -1849,49 +1913,147 @@ where stdin.flush().await } -/// Write one prompt frame while counting how much of the line reached the pipe. +/// Write one whole prompt frame under the arbitration lock. /// -/// `write_all` cannot distinguish a failed first write from a truncated one, so -/// this loop keeps the byte count and reports partial vs no-send separately. -async fn write_prompt_frame(stdin: &mut W, line: &str) -> (io::Result<()>, PromptWire) +/// 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 bytes = line.as_bytes(); + 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; - while written < bytes.len() { - match stdin.write(&bytes[written..]).await { - Ok(0) => { - return ( - Err(io::Error::from(io::ErrorKind::WriteZero)), - if written == 0 { + + std::future::poll_fn(|cx| { + let stop = shared.stop_tripped(); + let mut ingress = shared.ingress.lock().unwrap(); + // 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 || 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 - }, - ); - } - Ok(count) => written += count, - Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, - Err(error) => { - return ( - Err(error), - if written == 0 { + }; + 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)); + } } } - } - if let Err(error) = stdin.write_all(b"\n").await { - return (Err(error), PromptWire::Partial); - } - match stdin.flush().await { - Ok(()) => (Ok(()), PromptWire::Written), - Err(error) => (Err(error), PromptWire::Partial), - } + 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 { @@ -2438,62 +2600,63 @@ mod cleanup_proof_tests { #[cfg(test)] mod prompt_arbitration_tests { - use super::{CancelAction, PromptWire, Shared}; + 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 decides" - ); - assert!( - !shared.begin_prompt_write(&id), - "the writer discards the scheduled frame before any byte" + "the actor records the stop before the writer runs" ); - 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)); } - #[test] - fn writer_consults_shutdown_and_deadline_before_the_first_byte() { - let (_shutdown, shutdown_rx) = tokio::sync::watch::channel(true); + #[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()); - assert!(!shared.begin_prompt_write(&id)); - assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); - - let (_shutdown, shutdown_rx) = tokio::sync::watch::channel(false); - let past = tokio::time::Instant::now() - Duration::from_millis(1); - let shared = Shared::new(shutdown_rx, past); - let id = prompt_id(); - shared.begin_prompt("fixture-session", id.clone()); - assert!(!shared.begin_prompt_write(&id)); - assert_eq!(shared.prompt_wire(), Some(PromptWire::Discarded)); - } + 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)); - #[test] - fn complete_frame_yields_exactly_one_cancel() { - let shared = Shared::default(); - let id = prompt_id(); - shared.begin_prompt("fixture-session", id.clone()); - assert!(shared.begin_prompt_write(&id)); - assert_eq!(shared.request_prompt_cancel(&id), CancelAction::Deferred); + // 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" @@ -2516,12 +2679,16 @@ mod prompt_arbitration_tests { assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); } - #[test] - fn complete_frame_then_cancel_claims_one_send_now() { + #[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()); - assert!(shared.begin_prompt_write(&id)); + 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!( @@ -2535,15 +2702,19 @@ mod prompt_arbitration_tests { assert_eq!(shared.request_prompt_cancel(&id), CancelAction::None); } - #[test] - fn matching_response_wins_over_later_cancel() { + #[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()); - assert!(shared.begin_prompt_write(&id)); + 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 exact prompt response" + "the ingress claims the response only after a complete frame" ); assert!(shared.is_reserved_prompt_id(&id)); assert_eq!( @@ -2556,76 +2727,260 @@ mod prompt_arbitration_tests { } #[test] - fn response_before_any_prompt_byte_is_not_accepted() { + 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()); - assert!(!shared.take_expected(&id)); - assert_eq!(shared.prompt_wire(), Some(PromptWire::Pending)); + 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 partial_write_refuses_cancel_and_blocks_follow_on_lines() { + 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()); - assert!(shared.begin_prompt_write(&id)); - shared.partial_prompt_write(&id); - assert_eq!(shared.prompt_wire(), Some(PromptWire::Partial)); + 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 zero_byte_write_sends_nothing() { + 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()); - assert!(shared.begin_prompt_write(&id)); - shared.failed_prompt_write(&id); - assert_eq!(shared.prompt_wire(), Some(PromptWire::Failed)); + 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 sdk_failure_before_the_writer_discards_the_armed_prompt() { - let shared = Shared::default(); + 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()); - shared.abandon_unwritten_prompt(&id); + 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 writer_outcome_tests { - use super::{OutgoingFrame, PromptWire, session_cancel_frame, write_prompt_frame}; - use agent_client_protocol::RawJsonRpcId; +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}; - struct ScriptedWriter { - allow: usize, - written: Vec, + 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 tokio::io::AsyncWrite for ScriptedWriter { + impl GateWriter { + pub fn new(state: Arc) -> Self { + Self { state } + } + } + + impl tokio::io::AsyncWrite for GateWriter { fn poll_write( - mut self: Pin<&mut Self>, + self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { - let remaining = self.allow.saturating_sub(self.written.len()); - if remaining == 0 { - return Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe))); + 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)) + } } - let take = remaining.min(buf.len()); - self.written.extend_from_slice(&buf[..take]); - Poll::Ready(Ok(take)) } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { @@ -2636,41 +2991,73 @@ mod writer_outcome_tests { 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 mut writer = ScriptedWriter { - allow: usize::MAX, - written: Vec::new(), - }; - let (result, wire) = write_prompt_frame(&mut writer, "{\"x\":1}").await; + 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); - assert_eq!(writer.written.as_slice(), b"{\"x\":1}\n"); + 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 mut writer = ScriptedWriter { - allow: 0, - written: Vec::new(), - }; - let (result, wire) = write_prompt_frame(&mut writer, "{\"x\":1}").await; + 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!(writer.written.is_empty()); + assert!(state.bytes().is_empty()); + assert_eq!(shared.prompt_wire(), Some(PromptWire::Failed)); } #[tokio::test] async fn truncated_line_is_reported_partial() { - let mut writer = ScriptedWriter { - allow: 5, - written: Vec::new(), - }; - let (result, wire) = write_prompt_frame(&mut writer, "{\"x\":1}").await; - assert!(result.is_err()); - assert_eq!(wire, PromptWire::Partial); - assert_eq!(writer.written.as_slice(), b"{\"x\":"); + 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] @@ -2699,4 +3086,16 @@ mod writer_outcome_tests { _ => 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); + } } diff --git a/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs index be22123..8d3cc1b 100644 --- a/tests/acp_delegation_client_tests.rs +++ b/tests/acp_delegation_client_tests.rs @@ -1401,3 +1401,46 @@ async fn unconfirmed_bounded_close_completes_through_the_observer() { 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" + ); +} From 3cbacf2e75b4244ee72537aaaf0a094d8286c9cf Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 09:09:46 +0800 Subject: [PATCH 08/27] fix(acp): arbitrate caller withdrawal before the first prompt byte Record caller withdrawal synchronously under the ingress lock when the prompt future is dropped, and re-read shutdown, the absolute deadline and that withdrawal after taking the same lock on every write attempt. A parked first byte can no longer be published when the SDK polls its transport before the actor; the guard is disarmed only after a completed exchange, so a finished prompt is unaffected. Already-sent and partial frames keep their existing transitions. Let the supervisor anchor cleanup from the original run deadline and the first cleanup-start notification instead of waiting for the SDK connection to finish. Every path into cleanup shares the existing 500 ms drain slice of the one absolute 5 s budget, so a connection stuck in an inline reply or a physical writer drain cannot hold the process slot or delay reaping. --- src/acp/delegated_client.rs | 570 +++++++++++++++++++++++++++++++++--- 1 file changed, 537 insertions(+), 33 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 9aba76c..962f81b 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -370,6 +370,20 @@ impl DelegatedAcpClient { pub async fn connect( launch: AcpDelegationLaunch, deadline: Instant, + ) -> Result { + Self::connect_with_stdin(launch, deadline, |stdin| Box::new(stdin)).await + } + + /// 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 { if Instant::now() >= deadline { return Err(AcpDelegationError::DeadlineExceeded); @@ -390,7 +404,7 @@ impl DelegatedAcpClient { 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(stdin, shared.clone())); + 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 @@ -430,28 +444,38 @@ impl DelegatedAcpClient { }), ); // One absolute cleanup budget is anchored at the first observed - // stop (shutdown, run deadline or caller withdrawal). A pending - // connection gets a bounded drain slice; group termination and - // reaping keep the remainder of the same budget. + // 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 => shared.mark_cleanup_start(), - _ = supervisor_shutdown.changed() => { - let start = shared.mark_cleanup_start(); - let drain_deadline = - (start + PROTOCOL_DRAIN_BUDGET).min(start + CLEANUP_BUDGET); - let _ = timeout_at(drain_deadline, &mut connection).await; - start + _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(), }; - drop(connection); 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 close_deadline = (cleanup_start + PROTOCOL_DRAIN_BUDGET).min(cleanup_deadline); - let _ = timeout_at(close_deadline, supervisor_wire.close_stdin()).await; + 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 @@ -634,15 +658,23 @@ impl DelegatedAcpClient { return Err(AcpDelegationError::SessionMismatch); } self.prompted = true; - self.exchange( - |reply| ActorCommand::Prompt { - session_id: session_id.to_owned(), - task: task.to_owned(), - reply, - }, - AcpDelegationError::PromptFailed, - ) - .await + // 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. @@ -1252,6 +1284,10 @@ struct Ingress { /// 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. @@ -1296,6 +1332,11 @@ struct Shared { /// 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, } @@ -1341,12 +1382,52 @@ impl Shared { 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 mut start = self.cleanup_start.lock().unwrap(); - *start.get_or_insert_with(Instant::now) + 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 { @@ -1372,8 +1453,8 @@ impl Shared { /// 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 stop = self.stop.as_ref().is_some_and(Stop::tripped); 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; }; @@ -1744,6 +1825,35 @@ impl Shared { } } +/// 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 @@ -1757,7 +1867,7 @@ struct Wire { /// 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>, + 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. @@ -1765,7 +1875,7 @@ struct Wire { } impl Wire { - fn new(stdin: ChildStdin, shared: Arc) -> Self { + fn new(stdin: StdinWriter, shared: Arc) -> Self { Self { stdin: tokio::sync::Mutex::new(Some(stdin)), shared, @@ -1852,11 +1962,14 @@ impl Wire { /// 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( + async fn write_cancel_locked( &self, - stdin: &mut ChildStdin, + stdin: &mut W, request_id: &RawJsonRpcId, - ) -> io::Result<()> { + ) -> io::Result<()> + where + W: tokio::io::AsyncWrite + Unpin, + { let Some(session) = self.shared.begin_cancel_write(request_id) else { return Ok(()); }; @@ -1939,8 +2052,12 @@ where let mut written = 0usize; std::future::poll_fn(|cx| { - let stop = shared.stop_tripped(); 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. @@ -1956,7 +2073,7 @@ where } // 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 || stop { + if cancel_requested || withdrawn || stop { if written == 0 { if let Some(prompt) = ingress.prompt.as_mut() { prompt.state = PromptState::Discarded; @@ -3099,3 +3216,390 @@ mod writer_outcome_tests { 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"); + } +} From db4833dea6fe05eca700813430693898821f0883 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 09:38:23 +0800 Subject: [PATCH 09/27] fix(acp): notify supervised cleanup when the actor exits Publish the idempotent cleanup anchor at the actor's single common exit instead of scattering the notification across individual stop branches. The ACP SDK keeps the physical transport draining after the foreground task returns, so the connection future is a late termination signal that the supervisor may otherwise only observe at the run deadline. Clean prompt completion, early setup errors, caller withdrawal before the prompt is armed and command EOF now all notify the supervisor, while the earliest stop still anchors first before any cancellable IO. Add regressions over the real SDK and a real child harness. One holds the transport close so the connection future cannot resolve and proves the anchor is published while it is still pending. The other withdraws the prompt before arming, never closes or requests shutdown, and requires confirmed cleanup, an exact reap and an empty post-handshake wire within the bounded drain. --- src/acp/delegated_client.rs | 484 ++++++++++++++++++++++++++++++++++++ 1 file changed, 484 insertions(+) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 962f81b..997da42 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -801,6 +801,28 @@ struct Actor { } 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, @@ -3603,3 +3625,465 @@ mod supervisor_deadline_tests { 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/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; + } +} From 93979e929322059b9d2efdb481342183cabea6ab Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 10:47:07 +0800 Subject: [PATCH 10/27] fix(acp): bind manual delegation approvals and durable CAS Route delegate_acp approvals through the gateway's real manual approval surface, bind the private launch definition, workspace, pin version, task and expiry durably, and refuse automatic reviewers or previews that cannot show the complete task. Replace the unconditional session metadata merge with a database-enforced compare-and-swap on owner, durable session identity, document version and the exact lease call. Settlement and lease release share one write, prepared/creating calls are indeterminate, and settled replays require the identical request and authenticated approval identity. Wake setup and prompt cancellation from the run cancellation watch, recheck the run, approval and same absolute deadline at the last pre-spawn boundary, and confine every post-spawn early return to confirmed cleanup or an explicit quarantine. Bound the serialized result envelope to the run output budget with UTF-8 truncation. --- rss/storage/debug.rss | 2 + rss/storage/main.rss | 2 + rss/storage/sessions.rss | 49 + src/bin/rustscript-agent-gateway.rs | 1 + src/gateway/store.rs | 10 + src/runtime/rss_runner.rs | 28 + src/service.rs | 126 ++ src/service/acp_session_pins.rs | 1882 ++++++++++++----- tests/acp_delegation_policy_tests.rs | 2271 ++++++++++++--------- tests/fixtures/acp_policy/policy_agent.rs | 20 + 10 files changed, 2918 insertions(+), 1473 deletions(-) diff --git a/rss/storage/debug.rss b/rss/storage/debug.rss index 56fffa0..78d7579 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 425b616..94da089 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 232da49..3c8d9ba 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/src/bin/rustscript-agent-gateway.rs b/src/bin/rustscript-agent-gateway.rs index a1ce42a..ee3e182 100644 --- a/src/bin/rustscript-agent-gateway.rs +++ b/src/bin/rustscript-agent-gateway.rs @@ -236,6 +236,7 @@ async fn main() -> Result<(), Box> { 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); diff --git a/src/gateway/store.rs b/src/gateway/store.rs index 8787070..b079ef3 100644 --- a/src/gateway/store.rs +++ b/src/gateway/store.rs @@ -4443,6 +4443,16 @@ 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 { + self.command_data("session.acp_delegation_cas", payload) + } + /// Atomically binds trusted workspace display metadata to an idle session /// through the RSS session command, preserving unrelated metadata keys. pub fn session_workspace_bind( diff --git a/src/runtime/rss_runner.rs b/src/runtime/rss_runner.rs index e8496f4..e70ac66 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 @@ -839,6 +842,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 +916,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 +981,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), ), diff --git a/src/service.rs b/src/service.rs index c2615a3..6339e2e 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1655,6 +1655,132 @@ 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 is a forced human decision. A run + // sealed for the automatic reviewer can never create one. + if !self.sealed_user_reviewer(&request.run_id) { + 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 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": "single_call", + "one_time": 1, + "requested_at_ms": timestamp(), + "expires_at_ms": request.expires_at_ms, + }); + persistence + .approval_request(&payload) + .map_err(|_| "acp_storage_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(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, 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()) + } +} + impl AgentService { pub(crate) fn new( config: Arc, diff --git a/src/service/acp_session_pins.rs b/src/service/acp_session_pins.rs index 3292901..873ba70 100644 --- a/src/service/acp_session_pins.rs +++ b/src/service/acp_session_pins.rs @@ -4,15 +4,23 @@ //! `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 user approval bound to the run, the call, the -//! admitted workspace, the current launch definition and the current pin -//! version, and revalidates that witness after the approval; -//! - it keeps the peer-assigned external session ID and every call phase 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; +//! - 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 releases the pin lease in the same durable write that settles the call; +//! - 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. //! @@ -21,19 +29,15 @@ //! have run without a persisted ID, or a prompt that may have run without a //! settlement) is never rebuilt or continued automatically. //! -//! Concurrency: `session.touch` is one atomic JSON merge but not a -//! compare-and-swap. Ownership is therefore decided by the in-process per-pin -//! gate (`try_lock`, so a conflicting call is refused immediately instead of -//! queued), recorded durably as a lease next to the call phase, and verified by -//! a read-back fence before the process is spawned. The durable lease is what -//! carries "one active call per pin" across runs and restarts; two gateway -//! processes must not share one database, which is the product's existing -//! single-writer deployment constraint. +//! 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. use std::collections::{BTreeMap, HashMap, HashSet}; use std::ffi::OsString; use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -59,16 +63,23 @@ pub const MAX_TASK_BYTES: usize = 8 * 1024; 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; -/// Task excerpt carried by the approval preview. -const PREVIEW_TASK_BYTES: usize = 1024; /// 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)] @@ -190,6 +201,38 @@ impl AcpApprovalWitness { } } +/// 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; +} + /// Exact durable identity of one delegation. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AcpDelegationScope { @@ -201,7 +244,7 @@ pub struct AcpDelegationScope { pub run_deadline_ms: Option, } -/// Why a delegation was refused before any process existed. +/// Why a delegation was refused before any successful settlement. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AcpPolicyRefusal { Denied(&'static str), @@ -225,20 +268,24 @@ impl AcpPolicyRefusal { } } -/// Test-only fault cut driven at the three recovery boundaries. The policy -/// closes the child and then returns an indeterminate result without writing -/// the later phase, exactly like a crash at that point. +/// 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, /// 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, /// `close` returned unconfirmed, but the supervisor will publish a positive /// cleanup report. DeferredCleanupConfirmed, @@ -257,9 +304,8 @@ struct HarnessLaunch { struct PolicyInner { persistence: Arc, + gateway: Arc, harnesses: BTreeMap, - /// Monotonic identity of this immutable launch table. - config_version: u64, allowed_roots: Vec, max_result_bytes: usize, quota: Arc, @@ -270,6 +316,8 @@ struct PolicyInner { gates: Mutex>>>, #[cfg(feature = "workspace-io-fault")] fault: Mutex, + #[cfg(feature = "workspace-io-fault")] + pre_spawn_hook: Mutex>>, } /// Installed delegation policy. Cloning shares the same durable gates. @@ -278,16 +326,16 @@ pub struct AcpDelegationPolicy { inner: Arc, } -static CONFIG_VERSION_SEQUENCE: AtomicU64 = AtomicU64::new(1); - 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. + /// 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); @@ -300,7 +348,6 @@ impl AcpDelegationPolicy { let launch = build_launch(harness)?; harnesses.insert(harness.id.clone(), launch); } - let config_version = CONFIG_VERSION_SEQUENCE.fetch_add(1, Ordering::Relaxed); let max_result_bytes = config .agent .max_tool_output_bytes @@ -308,8 +355,8 @@ impl AcpDelegationPolicy { Ok(Some(Self { inner: Arc::new(PolicyInner { persistence, + gateway, harnesses, - config_version, allowed_roots: config.workspaces.allowed_roots.clone(), max_result_bytes, quota: Arc::new(Semaphore::new(MAX_ACTIVE_PROCESSES)), @@ -318,6 +365,8 @@ impl AcpDelegationPolicy { 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), }), })) } @@ -327,11 +376,6 @@ impl AcpDelegationPolicy { self.inner.harnesses.keys().cloned().collect() } - /// Monotonic identity of this immutable launch table. - pub fn config_version(&self) -> u64 { - self.inner.config_version - } - /// Free process slots of the service-wide delegation quota. pub fn available_processes(&self) -> usize { self.inner.quota.available_permits() @@ -342,6 +386,18 @@ impl AcpDelegationPolicy { *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)); + } + #[cfg(feature = "workspace-io-fault")] fn take_cleanup_fault(&self) -> Option { let mut fault = self.inner.fault.lock().expect("acp policy fault"); @@ -368,12 +424,25 @@ impl AcpDelegationPolicy { } } + #[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(); + } + } + /// Durable settlement classification of one call. /// - /// `NotStarted` means no process was ever prepared for that exact call and a - /// fresh approved call may start; `Indeterminate` means the call may have - /// produced an external effect and must never be re-executed; `Settled` - /// means its recorded outcome is authoritative. + /// `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, @@ -388,31 +457,30 @@ impl AcpDelegationPolicy { .unwrap_or(crate::effects::DelegationSettlement::NotStarted)) } - /// Creates the durable pending approval for one exact delegation. + /// Creates the durable pending approval for one exact delegation through + /// the gateway's real manual approval surface. /// - /// The preview names the harness, the admitted workspace, whether the call - /// creates or continues a session, the task and the external program's - /// authority. An insufficient preview is refused instead of approved. + /// 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)?; - if !self.inner.harnesses.contains_key(&request.harness_id) { + let Some(launch) = self.inner.harnesses.get(&request.harness_id) else { return Err(AcpPolicyRefusal::Denied("acp_harness_unknown")); + }; + 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(&snapshot, &self.inner.allowed_roots)?; let doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - let pin_version = doc - .pins - .get(&request.harness_id) - .map(|pin| pin.version) - .unwrap_or(0); - let new_session = doc - .pins - .get(&request.harness_id) + 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)?; @@ -421,47 +489,65 @@ impl AcpDelegationPolicy { if expires_at_ms <= now_ms { return Err(AcpPolicyRefusal::Denied("acp_delegation_deadline")); } - let arguments = ApprovalArguments { - harness_id: request.harness_id.clone(), - task: request.task.clone(), - config_version: self.inner.config_version, - pin_version, - workspace: workspace.path.clone(), - owner: snapshot.owner.clone(), - new_session, - }; - let arguments_json = serde_json::to_string(&arguments) - .map_err(|_| AcpPolicyRefusal::Failed("acp_approval_invalid"))?; let preview = build_preview( &request.harness_id, &workspace.path, new_session, &request.task, )?; - let payload = json!({ - "id": approval_id, - "run_id": scope.run_id, - "session_id": scope.session_id, - "tool_call_id": scope.tool_call_id, - "tool_name": DELEGATION_TOOL_NAME, - "arguments_json": arguments_json, - "risk_class": "execute", - "decision_scope": "", - "one_time": 1, - "requested_at_ms": now_ms, - "expires_at_ms": expires_at_ms, - }); - let persistence = self.inner.persistence.clone(); - let result = blocking(move || persistence.approval_request(&payload)).await?; - let row = first_row(&result).ok_or(AcpPolicyRefusal::Failed("acp_approval_unavailable"))?; - if row.first().and_then(Value::as_str) != Some(approval_id.as_str()) { - return Err(AcpPolicyRefusal::Failed("acp_approval_unavailable")); - } - Ok(AcpApprovalChallenge { - approval_id, - preview, + let binding = ApprovalBinding { + run_id: scope.run_id.clone(), + session_id: scope.session_id.clone(), + 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(); + self.mutate(&scope.session_id, move |doc, snapshot| { + if snapshot.owner != stored.owner { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + 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. @@ -475,7 +561,7 @@ impl AcpDelegationPolicy { cancellation: &RunCancellation, ) -> AcpDelegationResult { let harness_id = request.harness_id.clone(); - match self + let result = match self .delegate_inner(scope, request, witness, cancellation) .await { @@ -483,7 +569,8 @@ impl AcpDelegationPolicy { Err(refusal) => { AcpDelegationResult::refusal(&harness_id, refusal.status(), refusal.code()) } - } + }; + bounded_result(result, self.inner.max_result_bytes) } async fn delegate_inner( @@ -520,7 +607,7 @@ impl AcpDelegationPolicy { let mut snapshot = self.read_session(&scope.session_id).await?; let workspace = admitted_workspace(&snapshot, &self.inner.allowed_roots)?; - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); + 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 { @@ -528,6 +615,10 @@ impl AcpDelegationPolicy { .outcome .clone() .ok_or(AcpPolicyRefusal::Failed("acp_call_record_invalid"))?; + self.verify_replay( + existing, scope, request, witness, &snapshot, &workspace, launch, + ) + .await?; return Ok(outcome.to_result(&request.harness_id, true)); } // The exact call already reached an unrecoverable phase: never @@ -540,7 +631,6 @@ impl AcpDelegationPolicy { .get(&request.harness_id) .map(|pin| pin.version) .unwrap_or(0); - let mut reclaim_lease = false; if let Some(pin) = doc.pins.get(&request.harness_id) { if pin.owner != snapshot.owner || pin.workspace != workspace.path @@ -554,26 +644,34 @@ impl AcpDelegationPolicy { } if let Some(lease) = pin.active.as_ref() { // The in-process pin gate is free here, so any visible lease - // belongs to an interrupted call. It may be reclaimed only when - // that call never published a prompt: the remote session state - // is still known. - let interrupted = doc + // belongs to an interrupted call. Only the middle cut (peer ID + // durable, prompt intent never written) may be reclaimed. + if lease.call_id == scope.tool_call_id { + return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + } + let reclaimable = doc .calls .get(&lease.call_id) - .map(|call| matches!(call.phase, CallPhase::Prepared | CallPhase::SessionBound)) - .unwrap_or(true); - if lease.call_id == scope.tool_call_id || !interrupted { - return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); + .is_some_and(|call| call.phase == CallPhase::SessionBound); + if !reclaimable { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } - reclaim_lease = true; } } // 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, &workspace, pin_version) + self.validate_witness(witness, scope, request, &snapshot, &workspace) .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 = effective_deadline(scope.run_deadline_ms); if Instant::now() >= deadline { return Err(AcpPolicyRefusal::Failed("acp_delegation_deadline")); @@ -585,56 +683,233 @@ impl AcpDelegationPolicy { .try_acquire_owned() .map_err(|_| AcpPolicyRefusal::Busy("acp_delegation_capacity"))?; - // Durable preparation before any process exists. + // Waiting for 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?; + let workspace = admitted_workspace(&snapshot, &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 facts = self + .validate_witness(witness, scope, request, &snapshot, &workspace) + .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(), + 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: 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(), harness_id: request.harness_id.clone(), approval_id: witness.approval_id.clone(), + approval_resolver: Some(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, outcome: None, prompt_intent_at_ms: 0, }; - doc.calls.insert(scope.tool_call_id.clone(), call); - { - let pin = doc - .pins - .entry(request.harness_id.clone()) - .or_insert_with(|| { + 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 (prepared_snapshot, _) = self + .mutate(&scope.session_id, move |doc, snapshot| { + if snapshot.owner != owner { + return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); + } + 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( - snapshot.owner.clone(), - &workspace, + owner.clone(), + &prepare_workspace, launch.fingerprint.clone(), ) }); - if pin.active.is_some() && !reclaim_lease { - return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); - } - pin.active = Some(ActiveLease { - call_id: scope.tool_call_id.clone(), - run_id: scope.run_id.clone(), - expires_at_ms: crate::domain::timestamp() + DELEGATION_DEADLINE_MS, - }); - pin.version += 1; + 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; + if let Some(active) = pin.active.clone() { + let reclaimable = doc + .calls + .get(&active.call_id) + .is_some_and(|call| call.phase == CallPhase::SessionBound); + if !reclaimable { + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + lease_guard = Some((harness_id.clone(), active.call_id.clone())); + } + 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.version += 1; + Ok(lease_guard) + }) + .await?; + snapshot = prepared_snapshot; + + #[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_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + 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")); } - self.write_session(&mut snapshot, &doc).await?; - // Read-back fence: the durable lease must name this exact call. - // `session.touch` is not a compare-and-swap, so the in-process per-pin - // gate is the serialization point and this check refuses to proceed on - // a document that does not contain our own preparation. + + // Last boundary before spawn: cancellation, run liveness, approval, + // workspace and the absolute deadline are checked after every wait. + #[cfg(feature = "workspace-io-fault")] + self.run_pre_spawn_hook(); + if cancellation.requested().is_some() { + return self + .abort_pre_spawn( + scope, + request, + snapshot, + permit, + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + ) + .await; + } + if Instant::now() >= deadline { + return self + .abort_pre_spawn( + scope, + request, + snapshot, + permit, + AcpDelegationStatus::Timeout, + "acp_delegation_deadline", + ) + .await; + } + if !self.inner.gateway.run_active(&scope.run_id) { + return self + .abort_pre_spawn( + scope, + request, + snapshot, + permit, + AcpDelegationStatus::Denied, + "acp_run_inactive", + ) + .await; + } + let fresh = self.read_session(&scope.session_id).await?; + let fresh_workspace = admitted_workspace(&fresh, &self.inner.allowed_roots)?; + if fresh_workspace.path != workspace.path + || fresh_workspace.generation != workspace.generation + || fresh.owner != snapshot.owner { - let current = self.read_session(&scope.session_id).await?; - let current_doc = PinDocument::from_metadata(current.metadata.as_deref()); - let owned = current_doc - .pins - .get(&request.harness_id) - .and_then(|pin| pin.active.as_ref()) - .is_some_and(|lease| lease.call_id == scope.tool_call_id); - if !owned { - return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); - } - snapshot.metadata = current.metadata; + return self + .abort_pre_spawn( + scope, + request, + snapshot, + permit, + AcpDelegationStatus::Denied, + "acp_binding_mismatch", + ) + .await; + } + if let Err(refusal) = self + .validate_witness(witness, scope, request, &fresh, &fresh_workspace) + .await + { + return self + .abort_pre_spawn( + scope, + request, + snapshot, + permit, + refusal.status(), + refusal.code(), + ) + .await; } + snapshot = fresh; let launch_handle = AcpDelegationLaunch::new( launch.command.clone(), @@ -643,18 +918,54 @@ impl AcpDelegationPolicy { ) .map_err(|_| AcpPolicyRefusal::Failed("acp_delegation_invalid_launch"))?; - let outcome = self - .run_call( - scope, - request, - launch_handle, - deadline, - cancellation, - &mut snapshot, - permit, - ) - .await?; - Ok(outcome) + self.run_call( + scope, + request, + launch_handle, + deadline, + cancellation, + &mut snapshot, + permit, + ) + .await + } + + /// Settles a prepared call that never spawned a process. + #[allow(clippy::too_many_arguments)] + async fn abort_pre_spawn( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: SessionSnapshot, + permit: tokio::sync::OwnedSemaphorePermit, + 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, &mut snapshot, outcome, true) + .await + { + Ok(result) => { + drop(permit); + Ok(result) + } + Err(_) => { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } } /// Drives one connection from spawn to settlement. @@ -669,30 +980,84 @@ impl AcpDelegationPolicy { snapshot: &mut SessionSnapshot, permit: tokio::sync::OwnedSemaphorePermit, ) -> Result { + if cancellation.requested().is_some() || Instant::now() >= deadline { + let timed_out = Instant::now() >= deadline; + let (status, code) = if timed_out { + (AcpDelegationStatus::Timeout, "acp_delegation_deadline") + } else { + (AcpDelegationStatus::Cancelled, "acp_delegation_cancelled") + }; + return self + .abort_pre_spawn(scope, request, snapshot.clone(), permit, status, code) + .await; + } let mut client = match DelegatedAcpClient::connect(launch, deadline).await { Ok(client) => client, Err(error) => { - return self + let result = self .settle_failed(scope, request, snapshot, error.code()) .await; + return match result { + Ok(result) => { + drop(permit); + Ok(result) + } + Err(_) => { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + }; } }; let observer = client.cleanup_observer(); - let capabilities = match client.initialize().await { - Ok(capabilities) => capabilities, - Err(error) => { - let report = client.close().await; - if !report.cleanup_confirmed { - return self - .hold_until_cleanup(scope, request, observer, permit) - .await; - } + let capabilities = { + let future = client.initialize(); + tokio::pin!(future); + tokio::select! { + biased; + _ = cancellation.cancelled() => None, + result = &mut future => Some(result), + } + }; + let capabilities = match capabilities { + None => { return self - .settle_failed(scope, request, snapshot, error.code()) + .unsent_close( + scope, + request, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + true, + ) + .await; + } + Some(Ok(capabilities)) => capabilities, + Some(Err(error)) => { + return self + .unsent_close( + scope, + request, + 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) @@ -701,91 +1066,149 @@ impl AcpDelegationPolicy { let session_id = match bound_id { Some(existing) => { if capabilities.restore_method().is_none() { - let report = client.close().await; - if !report.cleanup_confirmed { - return self - .hold_until_cleanup(scope, request, observer, permit) - .await; - } return self - .settle_failed(scope, request, snapshot, "acp_session_restore_unsupported") + .unsent_close( + scope, + request, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + "acp_session_restore_unsupported", + true, + ) .await; } - match client.restore_session(existing.clone()).await { - Ok(_) => existing, - Err(error) => { - let report = client.close().await; - if !report.cleanup_confirmed { - return self - .hold_until_cleanup(scope, request, observer, permit) - .await; - } + let restored = { + let future = client.restore_session(existing.clone()); + tokio::pin!(future); + tokio::select! { + biased; + _ = cancellation.cancelled() => None, + result = &mut future => Some(result), + } + }; + match restored { + None => { + return self + .unsent_close( + scope, + request, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + true, + ) + .await; + } + Some(Err(error)) => { // A failed restore never falls back to `session/new`. return self - .settle_failed(scope, request, snapshot, error.code()) + .unsent_close( + scope, + request, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + error.code(), + true, + ) .await; } + Some(Ok(_)) => existing, } } None => { - // Record that a remote session may exist before requesting it. - { - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - let pin = doc - .pins - .get_mut(&request.harness_id) - .ok_or(AcpPolicyRefusal::Failed("acp_pin_missing"))?; - pin.phase = PinPhase::Creating; - pin.version += 1; - self.write_session(snapshot, &doc).await?; + let marked = self.mark_session_creating(scope, request, snapshot).await; + if marked.is_err() { + return self + .abort_unknown_state(scope, request, snapshot, client, observer, permit) + .await; } - let created = match client.new_session().await { - Ok(created) => created, - Err(error) => { - let report = client.close().await; - // The peer may have created a session we cannot name. - let _ = self.mark_pin_unknown(scope, request, snapshot).await; - if !report.cleanup_confirmed { - return self - .hold_until_cleanup(scope, request, observer, permit) - .await; - } + let created = { + let future = client.new_session(); + tokio::pin!(future); + tokio::select! { + biased; + _ = cancellation.cancelled() => None, + result = &mut future => Some(result), + } + }; + let created = match created { + None => { + return self + .unsent_close( + scope, + request, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + false, + ) + .await; + } + Some(Ok(created)) => created, + Some(Err(error)) => { return self - .settle_failed(scope, request, snapshot, error.code()) + .fail_created_unknown( + scope, + request, + snapshot, + client, + observer, + permit, + error.code(), + ) .await; } }; #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::AfterSessionCreate) { let _ = client.close().await; - // The pin stays `Creating`: the ID was never persisted. + // The pin and call stay `creating`: the ID was never + // persisted. The permit stays charged because cleanup was + // not observed here. + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } if created.is_empty() || created.len() > MAX_EXTERNAL_SESSION_ID_BYTES { - let _ = client.close().await; - let _ = self.mark_pin_unknown(scope, request, snapshot).await; - return Err(AcpPolicyRefusal::Failed("acp_session_create_failed")); + return self + .reject_external_id(scope, request, snapshot, client, observer, permit) + .await; } - // Persist the peer ID *before* any prompt can be sent. + if let Err(_error) = self + .persist_bound_id(scope, request, snapshot, &created) + .await { - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - let pin = doc - .pins - .get_mut(&request.harness_id) - .ok_or(AcpPolicyRefusal::Failed("acp_pin_missing"))?; - pin.phase = PinPhase::Bound; - pin.external_session_id = Some(created.clone()); - pin.version += 1; - let call = doc - .calls - .get_mut(&scope.tool_call_id) - .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; - call.phase = CallPhase::SessionBound; - self.write_session(snapshot, &doc).await?; + return self + .abort_unknown_state(scope, request, snapshot, client, observer, permit) + .await; } #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::AfterSessionPersisted) { - let _ = client.close().await; + let report = client.close().await; + if report.cleanup_confirmed { + drop(permit); + } else { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + } return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } created @@ -793,63 +1216,62 @@ impl AcpDelegationPolicy { }; if cancellation.requested().is_some() { - let report = client.close().await; - if !report.cleanup_confirmed { - return self - .hold_until_cleanup(scope, request, observer, permit) - .await; - } - // No prompt was sent: the pin keeps its known session. return self - .settle_outcome( + .unsent_close( scope, request, snapshot, - SettledOutcome { - status: AcpDelegationStatus::Cancelled, - text: String::new(), - stop_reason: None, - truncated: false, - code: Some("acp_delegation_cancelled".to_string()), - }, + client, + observer, + permit, + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", true, ) .await; } // Durable prompt-send intent, strictly after the bound ID write. - { - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - let call = doc - .calls - .get_mut(&scope.tool_call_id) - .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; - call.phase = CallPhase::PromptIntent; - call.prompt_intent_at_ms = crate::domain::timestamp(); - if let Some(pin) = doc.pins.get_mut(&request.harness_id) { - pin.phase = PinPhase::Bound; - pin.version += 1; - } - self.write_session(snapshot, &doc).await?; + if let Err(_error) = self.write_prompt_intent(scope, request, snapshot).await { + return self + .unsent_close( + scope, + request, + 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 cancellation.requested().is_some() { + return self + .unsent_close( + scope, + request, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + false, + ) + .await; } - // The in-flight prompt future borrows the client, so it is dropped - // before the client is consumed by `close`. let prompt_outcome = { let prompt = client.prompt(&session_id, &request.task); tokio::pin!(prompt); - loop { - tokio::select! { - result = &mut prompt => break result, - _ = tokio::time::sleep(Duration::from_millis(20)) => { - if cancellation.requested().is_some() { - break Err(AcpDelegationError::Cancelled); - } - if Instant::now() >= deadline { - break Err(AcpDelegationError::DeadlineExceeded); - } - } - } + tokio::select! { + biased; + _ = cancellation.cancelled() => PromptWait::Cancelled, + result = &mut prompt => PromptWait::Done(result), } }; @@ -882,20 +1304,28 @@ impl AcpDelegationPolicy { "acp_cleanup_unverified", ), }; - self.settle_after_cleanup( - scope, - &request.harness_id, - proof, - Some(permit), - expected_version, - ) - .await; + let released = self + .settle_after_cleanup( + scope, + &request.harness_id, + 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, observer, permit) + .await; + } if !report.cleanup_confirmed { return self .hold_until_cleanup(scope, request, observer, permit) @@ -903,10 +1333,11 @@ impl AcpDelegationPolicy { } let (settled, keeps_binding) = match prompt_outcome { - Ok(result) => { + PromptWait::Done(Ok(result)) => { #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::AfterPromptPublished) { let _ = self.mark_pin_unknown(scope, request, snapshot).await; + drop(permit); return Err(AcpPolicyRefusal::Failed("acp_prompt_indeterminate")); } let mut text = result.text; @@ -931,7 +1362,7 @@ impl AcpDelegationPolicy { true, ) } - Err(AcpDelegationError::DeadlineExceeded) => ( + PromptWait::Done(Err(AcpDelegationError::DeadlineExceeded)) => ( SettledOutcome { status: AcpDelegationStatus::Timeout, text: String::new(), @@ -941,7 +1372,7 @@ impl AcpDelegationPolicy { }, false, ), - Err(AcpDelegationError::Cancelled) => ( + PromptWait::Done(Err(AcpDelegationError::Cancelled)) | PromptWait::Cancelled => ( SettledOutcome { status: AcpDelegationStatus::Cancelled, text: String::new(), @@ -951,7 +1382,7 @@ impl AcpDelegationPolicy { }, false, ), - Err(error) => ( + PromptWait::Done(Err(error)) => ( SettledOutcome { status: AcpDelegationStatus::Failed, text: String::new(), @@ -962,8 +1393,161 @@ impl AcpDelegationPolicy { false, ), }; - self.settle_outcome(scope, request, snapshot, settled, keeps_binding) + match self + .settle_outcome(scope, request, snapshot, settled, keeps_binding) .await + { + Ok(result) => { + drop(permit); + Ok(result) + } + Err(_) => { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + 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, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: tokio::sync::OwnedSemaphorePermit, + 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, 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, snapshot, outcome, keeps_binding) + .await + { + Ok(result) => { + drop(permit); + Ok(result) + } + Err(_) => { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + 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, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: tokio::sync::OwnedSemaphorePermit, + code: &'static str, + ) -> Result { + let _ = self.mark_pin_unknown(scope, request, snapshot).await; + let report = client.close().await; + if !report.cleanup_confirmed { + return self + .hold_until_cleanup(scope, request, 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, snapshot, outcome, false) + .await + { + Ok(result) => { + drop(permit); + Ok(result) + } + Err(_) => { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } + } + } + + /// A remote session may exist but the peer ID is empty or oversized. + async fn reject_external_id( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: tokio::sync::OwnedSemaphorePermit, + ) -> Result { + self.fail_created_unknown( + scope, + request, + snapshot, + client, + observer, + permit, + "acp_session_create_failed", + ) + .await + } + + /// Durable writes failed after the spawn: leave the durable phase exactly + /// where it was and keep the capacity charged until cleanup is proven. + async fn abort_unknown_state( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + _snapshot: &mut SessionSnapshot, + client: DelegatedAcpClient, + observer: crate::acp::AcpCleanupObserver, + permit: tokio::sync::OwnedSemaphorePermit, + ) -> Result { + let report = client.close().await; + if report.cleanup_confirmed { + drop(permit); + } else { + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + let _ = observer; + } + Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")) } /// Settles a call that never published a prompt. The pin keeps its durable @@ -991,11 +1575,9 @@ impl AcpDelegationPolicy { .await } - /// One durable write settles the outcome and releases the pin lease. - /// - /// `keeps_binding` distinguishes a call that never published a prompt (the - /// external session is still valid) from one whose remote effect is - /// unknown (the pin must not be reused). + /// One durable conditional write settles the outcome and releases the pin + /// lease. The storage predicate still names this exact call as the lease + /// owner, so a stale settlement cannot clear a newer owner. async fn settle_outcome( &self, scope: &AcpDelegationScope, @@ -1004,22 +1586,39 @@ impl AcpDelegationPolicy { outcome: SettledOutcome, keeps_binding: bool, ) -> Result { - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - let call = doc - .calls - .get_mut(&scope.tool_call_id) - .ok_or(AcpPolicyRefusal::Failed("acp_call_missing"))?; - call.phase = CallPhase::Settled; - call.outcome = Some(outcome.clone()); - if let Some(pin) = doc.pins.get_mut(&request.harness_id) { - pin.active = None; - if !keeps_binding { - pin.phase = PinPhase::Unknown; - } - pin.version += 1; - } - doc.prune(); - self.write_session(snapshot, &doc).await?; + 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, move |doc, _snapshot| { + 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.phase = CallPhase::Settled; + call.outcome = Some(settle.clone()); + let mut lease_guard = None; + if let Some(pin) = doc.pins.get_mut(&harness_id) { + let owns = pin + .active + .as_ref() + .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id); + if owns { + pin.active = None; + if !keeps_binding { + pin.phase = PinPhase::Unknown; + } + pin.version += 1; + lease_guard = Some((harness_id.clone(), call_id.clone())); + } + } + Ok(lease_guard) + }) + .await?; + *snapshot = fresh; Ok(outcome.to_result(&request.harness_id, false)) } @@ -1030,19 +1629,153 @@ impl AcpDelegationPolicy { request: &AcpDelegationRequest, snapshot: &mut SessionSnapshot, ) -> Result<(), AcpPolicyRefusal> { - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - if let Some(pin) = doc.pins.get_mut(&request.harness_id) { - pin.phase = PinPhase::Unknown; - pin.active = None; - pin.version += 1; + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, move |doc, _snapshot| { + let mut lease_guard = None; + if let Some(pin) = doc.pins.get_mut(&harness_id) { + pin.phase = PinPhase::Unknown; + pin.active = None; + pin.version += 1; + lease_guard = Some((harness_id.clone(), call_id.clone())); + } + Ok(lease_guard) + }) + .await?; + *snapshot = fresh; + Ok(()) + } + + async fn mark_session_creating( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, move |doc, _snapshot| { + let Some(pin) = doc.pins.get_mut(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + let Some(call) = doc.calls.get_mut(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + pin.phase = PinPhase::Creating; + 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 persist_bound_id( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + 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 external = external_session_id.to_string(); + let (fresh, _) = self + .mutate(&scope.session_id, move |doc, _snapshot| { + let Some(pin) = doc.pins.get_mut(&harness_id) else { + return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); + }; + let Some(call) = doc.calls.get_mut(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + pin.phase = PinPhase::Bound; + pin.external_session_id = Some(external.clone()); + pin.version += 1; + 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, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, move |doc, _snapshot| { + let Some(call) = doc.calls.get_mut(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + call.phase = CallPhase::PromptIntent; + call.prompt_intent_at_ms = crate::domain::timestamp(); + if let Some(pin) = doc.pins.get_mut(&harness_id) { + 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, + workspace: &AdmittedWorkspace, + launch: &HarnessLaunch, + ) -> Result<(), AcpPolicyRefusal> { + if call.call_id != scope.tool_call_id + || call.run_id != scope.run_id + || call.harness_id != request.harness_id + || call.task != request.task + || call.launch != launch.fingerprint + || call.workspace != workspace.path + || call.workspace_generation != workspace.generation + || call.owner != snapshot.owner + || call.toolset_hash != snapshot.toolset_hash + || call.approval_id != witness.approval_id + { + return Err(AcpPolicyRefusal::Denied("acp_call_mismatch")); } - if let Some(call) = doc.calls.get_mut(&scope.tool_call_id) - && call.phase != CallPhase::Settled + 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) { - call.phase = CallPhase::PromptIntent; + return Err(AcpPolicyRefusal::Denied("acp_call_mismatch")); } - let _ = request; - self.write_session(snapshot, &doc).await + Ok(()) } /// Pins that could not prove cleanup and therefore keep their process slot. @@ -1061,6 +1794,23 @@ impl AcpDelegationPolicy { .collect() } + fn quarantine_permit( + &self, + permit: tokio::sync::OwnedSemaphorePermit, + pin_key: String, + call_id: String, + ) { + self.inner + .quarantine + .lock() + .expect("acp quarantine") + .push(QuarantinedSlot { + pin_key, + call_id, + _permit: 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()?; @@ -1105,16 +1855,11 @@ impl AcpDelegationPolicy { /// Settles a call whose prompt outcome was lost, using the cleanup proof. /// - /// Only a positive proof (`cleanup_confirmed`) releases the charged slot, - /// exactly once. A lost observer or an explicitly unconfirmed report keeps - /// the slot in an explicit quarantine entry for the rest of the service - /// lifetime, and leaves the durable pin indeterminate. The call itself is - /// never rewritten as a success and its recorded outcome can only be - /// replayed as `indeterminate`. - /// - /// The pin is only cleared when it still carries this exact call and the - /// version this policy last wrote, so a later owner can never be cleared by - /// an old settlement. + /// The slot is released exactly once and only when the settlement itself + /// committed and cleanup was proven; otherwise the permit is parked in the + /// explicit 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, @@ -1122,7 +1867,7 @@ impl AcpDelegationPolicy { proof: CleanupProof, permit: Option, expected_version: u64, - ) { + ) -> bool { let confirmed = match &proof { CleanupProof::Confirmed(report) => report.cleanup_confirmed, CleanupProof::Unconfirmed(report) => report.cleanup_confirmed, @@ -1133,12 +1878,19 @@ impl AcpDelegationPolicy { } else { "acp_cleanup_unverified" }; - if let Ok(mut snapshot) = self.read_session(&scope.session_id).await { - let mut doc = PinDocument::from_metadata(snapshot.metadata.as_deref()); - let mut changed = false; - if let Some(call) = doc.calls.get_mut(&scope.tool_call_id) - && call.phase != CallPhase::Settled - { + 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, move |doc, _snapshot| { + 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")); + } + let had_intent = + call.phase == CallPhase::PromptIntent || call.phase == CallPhase::Creating; call.phase = CallPhase::Settled; call.outcome = Some(SettledOutcome { status: AcpDelegationStatus::Indeterminate, @@ -1147,49 +1899,39 @@ impl AcpDelegationPolicy { truncated: false, code: Some(code.to_string()), }); - changed = true; - } - let owns_pin = doc.pins.get(harness_id).is_some_and(|pin| { - pin.version == expected_version - && pin.active.as_ref().is_some_and(|lease| { - lease.call_id == scope.tool_call_id && lease.run_id == scope.run_id - }) - }); - if owns_pin { - let pin = doc.pins.get_mut(harness_id).expect("pin checked above"); - pin.phase = if confirmed { - PinPhase::Bound - } else { - PinPhase::Unknown - }; - pin.active = None; - pin.version += 1; - changed = true; - } - if changed { - let _ = self.write_session(&mut snapshot, &doc).await; - } - } - match (confirmed, permit) { - // The single proven release: the supervisor proved that no owned - // process remains. - (true, Some(permit)) => drop(permit), - // Unproven cleanup keeps the real capacity charged. The permit is - // parked in an explicit service-lifetime quarantine entry instead - // of being forgotten or transferred to a new delegation. - (false, Some(permit)) => { - self.inner - .quarantine - .lock() - .expect("acp quarantine") - .push(QuarantinedSlot { - pin_key: format!("{}:{}", scope.session_id, harness_id), - call_id: scope.tool_call_id.clone(), - _permit: permit, - }); - } - (_, None) => {} + let mut lease_guard = None; + if let Some(pin) = doc.pins.get_mut(&harness_id_owned) { + 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 { + pin.active = None; + pin.phase = if had_intent { + PinPhase::Unknown + } else { + PinPhase::Bound + }; + pin.version += 1; + lease_guard = Some((harness_id_owned.clone(), call_id.clone())); + } + } + Ok(lease_guard) + }) + .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)) => drop(permit), + (_, _, Some(permit)) => self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, harness_id), + scope.tool_call_id.clone(), + ), + (_, _, None) => {} } + committed && confirmed } /// Test-only entry that settles with a stale version and no charged slot, @@ -1212,6 +1954,7 @@ impl AcpDelegationPolicy { .await; } + /// Re-reads and revalidates the durable manual approval. async fn validate_witness( &self, witness: &AcpApprovalWitness, @@ -1219,8 +1962,7 @@ impl AcpDelegationPolicy { request: &AcpDelegationRequest, snapshot: &SessionSnapshot, workspace: &AdmittedWorkspace, - pin_version: u64, - ) -> Result<(), AcpPolicyRefusal> { + ) -> Result { let persistence = self.inner.persistence.clone(); let id = witness.approval_id.clone(); let result = blocking(move || persistence.approval_get(&id)).await?; @@ -1235,10 +1977,10 @@ impl AcpDelegationPolicy { { return Err(AcpPolicyRefusal::Denied("acp_approval_mismatch")); } - // A delegated external process always needs a human decision: the - // automatic reviewer path may never produce a usable witness. - if field(13) != Some("user") { - return Err(AcpPolicyRefusal::Denied("acp_approval_not_user")); + // 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")); @@ -1255,22 +1997,19 @@ impl AcpDelegationPolicy { if !matches!(risk, "execute" | "privileged") { return Err(AcpPolicyRefusal::Denied("acp_approval_risk")); } - let arguments = field(5).ok_or(AcpPolicyRefusal::Denied("acp_approval_mismatch"))?; - let arguments: ApprovalArguments = serde_json::from_str(arguments) - .map_err(|_| AcpPolicyRefusal::Denied("acp_approval_mismatch"))?; - let expected = ApprovalArguments { - harness_id: request.harness_id.clone(), - task: request.task.clone(), - config_version: self.inner.config_version, - pin_version, - workspace: workspace.path.clone(), - owner: snapshot.owner.clone(), - new_session: pin_version == 0, - }; - if arguments != expected { - return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); - } - Ok(()) + let _ = (snapshot, workspace, 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 { @@ -1281,25 +2020,73 @@ impl AcpDelegationPolicy { SessionSnapshot::from_row(row).ok_or(AcpPolicyRefusal::Denied("acp_session_unknown")) } - /// Merges one private delegation document into the session metadata. + /// Applies one mutation to the authoritative document through the storage + /// compare-and-swap, retrying from the returned document on conflict. /// - /// `session.touch` is a single atomic `json_patch` of the top-level key, so - /// callers see either the previous or the new document, never a fragment. - async fn write_session( + /// 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, - snapshot: &mut SessionSnapshot, - doc: &PinDocument, - ) -> Result<(), AcpPolicyRefusal> { - let persistence = self.inner.persistence.clone(); - let payload = snapshot.touch_payload(doc)?; - let merged = serde_json::to_string(&json!({ METADATA_KEY: doc })) - .map_err(|_| AcpPolicyRefusal::Failed("acp_pin_invalid"))?; - let result = blocking(move || persistence.session_touch(&payload)).await?; - snapshot.metadata = first_row(&result) - .and_then(SessionSnapshot::from_row) - .and_then(|fresh| fresh.metadata) - .or(Some(merged)); - Ok(()) + session_id: &str, + mut apply: F, + ) -> Result<(SessionSnapshot, PinDocument), AcpPolicyRefusal> + where + F: FnMut( + &mut PinDocument, + &SessionSnapshot, + ) -> Result, AcpPolicyRefusal>, + { + let mut snapshot = self.read_session(session_id).await?; + 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": snapshot.owner, + "created_at_ms": snapshot.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"))?; + snapshot = SessionSnapshot::from_row(row) + .ok_or(AcpPolicyRefusal::Failed("acp_session_unknown"))?; + 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> { @@ -1312,7 +2099,6 @@ impl AcpDelegationPolicy { } } -/// A report that explicitly did not prove cleanup. fn unconfirmed_report() -> crate::acp::AcpCleanupReport { crate::acp::AcpCleanupReport { direct_child_reaped: false, @@ -1354,6 +2140,11 @@ impl Drop for RunGate<'_> { } } +enum PromptWait { + Done(Result), + Cancelled, +} + fn build_launch(harness: &AcpHarnessSettings) -> Result { if harness.args.len() > MAX_ACP_HARNESS_ARGUMENTS || harness.argument_bytes() > MAX_ACP_HARNESS_ARGUMENT_BYTES @@ -1365,6 +2156,16 @@ fn build_launch(harness: &AcpHarnessSettings) -> Result { .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, @@ -1377,6 +2178,19 @@ fn build_launch(harness: &AcpHarnessSettings) -> Result { }) } +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")); @@ -1423,29 +2237,18 @@ fn build_preview( task: &str, ) -> Result { let mode = if new_session { - "a new external session" - } else { - "the bound external session" - }; - let (excerpt, extra) = if task.len() > PREVIEW_TASK_BYTES { - let mut end = PREVIEW_TASK_BYTES; - while !task.is_char_boundary(end) { - end -= 1; - } - (&task[..end], task.len() - end) + "create a new external session" } else { - (task, 0) + "continue the bound external session" }; - let mut preview = format!( - "Delegate to ACP harness `{harness_id}` in workspace `{workspace}` using {mode}.\n\ - Task: {excerpt}" - ); - if extra > 0 { - preview.push_str(&format!("\n({extra} more task bytes not shown)")); - } - preview.push_str( - "\nThe 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.", + // 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")); @@ -1488,6 +2291,48 @@ fn clamp_text(text: &mut String, budget: usize, truncated: &mut bool) { *truncated = true; } +/// Shrinks the text until the whole serialized result envelope fits the run's +/// tool-output budget, preserving UTF-8 boundaries. +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; + } + result +} + +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, @@ -1499,11 +2344,24 @@ where } } +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, @@ -1553,18 +2411,13 @@ struct BoundWorkspace { generation: u64, } -/// Durable session columns echoed back by `session.touch`. +/// Durable session columns read by the policy. +#[derive(Clone)] struct SessionSnapshot { - session_id: String, owner: String, - status: String, - system_prompt: String, - model: String, - provider: String, toolset_hash: String, - title: String, - end_reason: String, metadata: Option, + created_at_ms: i64, } impl SessionSnapshot { @@ -1575,48 +2428,38 @@ impl SessionSnapshot { .unwrap_or_default() .to_string() }; + row.first()?.as_str()?; Some(Self { - session_id: row.first()?.as_str()?.to_string(), owner: text(6), - status: text(8), - system_prompt: text(9), - model: text(10), - provider: text(11), toolset_hash: text(12), metadata: row.get(13).and_then(Value::as_str).map(str::to_string), - title: text(17), - end_reason: text(18), + created_at_ms: row.get(15).and_then(Value::as_i64).unwrap_or_default(), }) } - - fn touch_payload(&self, doc: &PinDocument) -> Result { - let metadata = serde_json::to_string(&json!({ METADATA_KEY: doc })) - .map_err(|_| AcpPolicyRefusal::Failed("acp_pin_invalid"))?; - Ok(json!({ - "session_id": self.session_id, - "status": self.status, - "generation": 1, - "system_prompt": self.system_prompt, - "model": self.model, - "provider": self.provider, - "toolset_hash": self.toolset_hash, - "metadata_json": metadata, - "title": self.title, - "end_reason": self.end_reason, - "now_ms": crate::domain::timestamp(), - })) - } } /// Private durable delegation document kept under `$.acp_delegation`. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] struct PinDocument { #[serde(default)] - version: u64, + 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 { @@ -1627,44 +2470,22 @@ impl PinDocument { let Ok(value) = serde_json::from_str::(metadata) else { return Self::default(); }; - value - .get(METADATA_KEY) - .cloned() - .and_then(|value| serde_json::from_value(value).ok()) - .unwrap_or_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() } - /// Keeps the record bounded: the newest [`MAX_BINDINGS_PER_SESSION`] pins - /// and the newest 32 settled calls survive. - fn prune(&mut self) { - while self.pins.len() > MAX_BINDINGS_PER_SESSION { - let victim = self - .pins - .iter() - .filter(|(_, pin)| pin.active.is_none()) - .min_by_key(|(_, pin)| pin.version) - .map(|(key, _)| key.clone()); - match victim { - Some(key) => { - self.pins.remove(&key); - } - None => break, - } - } - while self.calls.len() > 32 { - let victim = self - .calls - .iter() - .filter(|(_, call)| call.phase == CallPhase::Settled) - .map(|(key, _)| key.clone()) - .next(); - match victim { - Some(key) => { - self.calls.remove(&key); - } - None => break, - } - } + fn expire_approvals(&mut self, now_ms: u64) { + self.pending_approvals + .retain(|_, binding| binding.expires_at_ms > now_ms); } } @@ -1726,8 +2547,11 @@ struct ActiveLease { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub(crate) enum CallPhase { - /// Durable preparation before any process exists. + /// 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, /// The prompt send intent is durable; no settlement exists. @@ -1740,11 +2564,10 @@ impl CallPhase { /// Durable settlement classification shared with the effect vocabulary. fn settlement(self) -> crate::effects::DelegationSettlement { match self { - Self::Prepared => crate::effects::DelegationSettlement::NotStarted, - Self::SessionBound | Self::PromptIntent => { + Self::Settled => crate::effects::DelegationSettlement::Settled, + Self::Prepared | Self::Creating | Self::SessionBound | Self::PromptIntent => { crate::effects::DelegationSettlement::Indeterminate } - Self::Settled => crate::effects::DelegationSettlement::Settled, } } } @@ -1755,6 +2578,16 @@ struct AcpCallRecord { run_id: String, 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, #[serde(default)] outcome: Option, @@ -1762,6 +2595,28 @@ struct AcpCallRecord { prompt_intent_at_ms: u64, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct ApprovalBinding { + run_id: String, + session_id: String, + 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, @@ -1814,21 +2669,34 @@ fn known_code(code: &str) -> Option<&'static str> { "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_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) } - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct ApprovalArguments { - harness_id: String, - task: String, - config_version: u64, - pin_version: u64, - workspace: String, - owner: String, - new_session: bool, -} diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs index 17fe6ad..dea2c75 100644 --- a/tests/acp_delegation_policy_tests.rs +++ b/tests/acp_delegation_policy_tests.rs @@ -1,28 +1,31 @@ //! ACP delegation policy contract: launch table, approval binding, durable -//! session pinning and call settlement. +//! session pinning, cancellation and call settlement. //! //! Every test drives the real [`AcpDelegationPolicy`] against the real gateway -//! durable store on an isolated fixture database and the independent -//! `tests/fixtures/acp_policy` stdio harness. Spawn counts come from the -//! harness' own append-only spawn log, so a refusal that never spawned a -//! process is observable rather than inferred. No model, provider, credential -//! or network path is involved. +//! 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::{Path, PathBuf}; -use std::sync::OnceLock; +use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Duration; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use rustscript_agent::config::AgentGatewayConfig; use rustscript_agent::config_file::ConfigFile; use rustscript_agent::gateway::AgentGatewayState; use rustscript_agent::gateway::store::GatewayPersistence; use rustscript_agent::runtime::rss_runner::RunCancellation; +use rustscript_agent::service::AgentService; use rustscript_agent::service::acp_session_pins::{ AcpApprovalWitness, AcpDelegationPolicy, AcpDelegationRequest, AcpDelegationScope, AcpDelegationStatus, }; +use rustscript_agent::{AdmitRunRequest, AdmittedRun, CancellationReason}; use serde_json::{Value, json}; #[path = "fixtures/acp_policy/build.rs"] @@ -33,6 +36,7 @@ static NEXT_TEST: AtomicU64 = AtomicU64::new(0); struct Env { root: PathBuf, workspace: PathBuf, + home: PathBuf, binary: PathBuf, } @@ -50,12 +54,23 @@ impl Env { )); 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, } } @@ -106,6 +121,42 @@ impl Env { 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(), @@ -157,78 +208,144 @@ fn binary_path() -> PathBuf { .clone() } -fn open_state(env: &Env) -> AgentGatewayState { - AgentGatewayState::with_sqlite_path(AgentGatewayConfig::default(), env.db()) - .expect("open isolated gateway state") +/// 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, } -fn seed( - persistence: &GatewayPersistence, - session_id: &str, - run_id: &str, - owner: &str, - workspace: &Path, -) { - let metadata = serde_json::to_string(&json!({ - "workspace": { - "selector": "name:policy", - "canonical_path": workspace.display().to_string(), - "selected_name": "policy", - "generation": 1 +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 { + 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"); + 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, } - })) - .expect("workspace metadata"); - 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": metadata, - "title": "", - "end_reason": "", - "now_ms": 1_700_000_000_000_i64, - })) - .expect("seed policy session"); - persistence - .run_create(&json!({ - "id": run_id, - "session_id": session_id, - "parent_run_id": "", - "input_json": "{}", - "provider": "policy-provider", - "model": "policy-model", - "script_hash": "policy-script", - "idempotency_scope": "", - "idempotency_key": "", - "now_ms": 1_700_000_000_000_i64, - })) - .expect("seed policy run"); - persistence - .run_transition(&json!({ - "run_id": run_id, - "from_status": "queued", - "to_status": "running", - "error_code": "", - "error_message": "", - "recovery_reason": "", - "now_ms": 1_700_000_000_001_i64, - })) - .expect("start policy run"); + } + + 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") + } + + 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) + } +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis() as i64) + .unwrap_or_default() } -fn scope(run_id: &str, session_id: &str, call_id: &str) -> AcpDelegationScope { +fn scope(run: &AdmittedRun, call_id: &str) -> AcpDelegationScope { AcpDelegationScope { - run_id: run_id.to_string(), - session_id: session_id.to_string(), + run_id: run.run_id.clone(), + session_id: run.session_id.clone(), tool_call_id: call_id.to_string(), run_deadline_ms: None, } @@ -241,29 +358,6 @@ fn request(harness_id: &str, task: &str) -> AcpDelegationRequest { } } -async fn approve( - policy: &AcpDelegationPolicy, - persistence: &GatewayPersistence, - scope: &AcpDelegationScope, - request: &AcpDelegationRequest, -) -> AcpApprovalWitness { - let challenge = policy - .request_approval(scope, request) - .await - .expect("approval challenge"); - persistence - .approval_resolve(&json!({ - "id": challenge.approval_id, - "run_id": scope.run_id, - "state": "approved", - "resolver": "user", - "decision_reason": "policy fixture approval", - "resolved_at_ms": 1, - })) - .expect("resolve approval"); - AcpApprovalWitness::new(challenge.approval_id) -} - 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"); @@ -292,40 +386,29 @@ async fn wait_for(mut condition: impl FnMut() -> bool, label: &str) { #[tokio::test] async fn default_config_installs_no_policy_and_unknown_ids_never_spawn() { let env = Env::new("default-off"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); 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()) + AcpDelegationPolicy::install(&plain, persistence.clone(), service.clone()) .expect("install default") .is_none(), "an empty table must leave the capability disabled" ); - let disabled = state - .service() - .delegate_acp( - scope("run-1", "session-1", "call-1"), - request("fixture", "task"), - AcpApprovalWitness::new("approval"), - &RunCancellation::new(), - ) - .await; - assert_eq!(disabled.status, AcpDelegationStatus::Denied); - assert_eq!(disabled.code, Some("acp_delegation_disabled")); - - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, + assert!( + service.acp_delegation().is_none(), + "the default capability is not installed" ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install policy") - .expect("configured policy"); - let unknown = policy + drop(state); + + let runtime = Runtime::open(&env); + let run = runtime.open_run(None).await; + let unknown = runtime + .policy .delegate( - &scope("run-1", "session-1", "call-1"), + &scope(&run, "call-1"), &request("missing", "task"), &AcpApprovalWitness::new("approval"), &RunCancellation::new(), @@ -339,53 +422,53 @@ async fn default_config_installs_no_policy_and_unknown_ids_never_spawn() { #[tokio::test] async fn unapproved_denied_and_unbound_calls_never_spawn() { let env = Env::new("refusals"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - - // Pending (never resolved) approval. - let pending_scope = scope("run-1", "session-1", "call-pending"); - let challenge = policy - .request_approval(&pending_scope, &request("fixture", "pending task")) - .await - .expect("challenge"); - let pending = policy + 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), + &AcpApprovalWitness::new(challenge.approval_id.clone()), &RunCancellation::new(), ) .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 approval. - let denied_scope = scope("run-1", "session-1", "call-denied"); - let challenge = policy - .request_approval(&denied_scope, &request("fixture", "denied task")) - .await - .expect("challenge"); - persistence - .approval_resolve(&json!({ - "id": challenge.approval_id, - "run_id": "run-1", - "state": "denied", - "resolver": "user", - "decision_reason": "no", - "resolved_at_ms": 2, - })) - .expect("deny approval"); - let denied = policy + // 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"), @@ -396,13 +479,14 @@ async fn unapproved_denied_and_unbound_calls_never_spawn() { assert_eq!(denied.status, AcpDelegationStatus::Denied); assert_eq!(denied.code, Some("acp_approval_mismatch")); - // No workspace binding at all on the session. + // A session without an admitted workspace can neither ask nor launch. + let persistence = runtime.persistence(); persistence .session_create(&json!({ - "id": "session-3", + "id": "session-unbound", "profile": "default", "platform": "policy-fixture", - "account_id": "session-3", + "account_id": "session-unbound", "chat_id": "7", "thread_id": "", "user_id": "owner-1", @@ -417,65 +501,77 @@ async fn unapproved_denied_and_unbound_calls_never_spawn() { "now_ms": 1_700_000_000_000_i64, })) .expect("seed unbound session"); - persistence - .run_create(&json!({ - "id": "run-3", - "session_id": "session-3", - "parent_run_id": "", - "input_json": "{}", - "provider": "policy-provider", - "model": "policy-model", - "script_hash": "policy-script", - "idempotency_scope": "", - "idempotency_key": "", - "now_ms": 1_700_000_000_000_i64, - })) - .expect("seed unbound run"); - persistence - .run_transition(&json!({ - "run_id": "run-3", - "from_status": "queued", - "to_status": "running", - "error_code": "", - "error_message": "", - "recovery_reason": "", - "now_ms": 1_700_000_000_001_i64, - })) - .expect("start unbound run"); - let unbound_scope = scope("run-3", "session-3", "call-unbound"); - let refusal = policy - .request_approval(&unbound_scope, &request("fixture", "x")) - .await - .expect_err("a session without an admitted workspace cannot even ask"); - assert_eq!(refusal.code(), "acp_workspace_unbound"); + let unbound_scope = AcpDelegationScope { + run_id: "run-unbound".to_string(), + session_id: "session-unbound".to_string(), + tool_call_id: "call-unbound".to_string(), + run_deadline_ms: None, + }; + let refusal = runtime + .policy + .delegate( + &unbound_scope, + &request("fixture", "x"), + &AcpApprovalWitness::new("approval"), + &RunCancellation::new(), + ) + .await; + assert_eq!(refusal.status, AcpDelegationStatus::Denied); + assert_eq!(refusal.code, Some("acp_workspace_unbound")); 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 state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - - let first_scope = scope("run-1", "session-1", "call-1"); - let first_witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "first"), - ) - .await; - let first = policy + 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"), @@ -491,29 +587,22 @@ async fn first_call_creates_and_later_calls_restore_the_same_session() { ); assert!(!first.replayed); - let doc = pin_document(&persistence, "session-1"); + 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; - seed( - &persistence, - "session-1", - "run-2", - "owner-1", - &env.workspace, - ); - let second_scope = scope("run-2", "session-1", "call-2"); - let second_witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "second"), - ) - .await; - let second = policy + 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"), @@ -529,7 +618,7 @@ async fn first_call_creates_and_later_calls_restore_the_same_session() { 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, "session-1"); + let doc = pin_document(&persistence, &first_run.session_id); assert_eq!( doc["pins"]["fixture"]["external_session_id"].as_str(), Some(bound_id), @@ -538,29 +627,16 @@ async fn first_call_creates_and_later_calls_restore_the_same_session() { } #[tokio::test] -async fn settled_call_replays_the_durable_result_without_spawning() { +async fn settled_call_replays_only_the_identical_request_without_spawning() { let env = Env::new("replay"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "once"), - ) - .await; - let first = policy + 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"), @@ -570,21 +646,24 @@ async fn settled_call_replays_the_durable_result_without_spawning() { .await; assert_eq!(first.status, AcpDelegationStatus::Completed); assert_eq!( - policy - .call_settlement("session-1", "call-1") + runtime + .policy + .call_settlement(&run.session_id, "call-1") .await .expect("settlement"), rustscript_agent::effects::DelegationSettlement::Settled ); assert_eq!( - policy - .call_settlement("session-1", "never-used") + runtime + .policy + .call_settlement(&run.session_id, "never-used") .await .expect("settlement"), rustscript_agent::effects::DelegationSettlement::NotStarted ); let spawns = env.spawn_count(); - let replay = policy + let replay = runtime + .policy .delegate( &call_scope, &request("fixture", "once"), @@ -595,6 +674,20 @@ async fn settled_call_replays_the_durable_result_without_spawning() { 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, + &RunCancellation::new(), + ) + .await; + assert_eq!(mismatch.status, AcpDelegationStatus::Denied); + assert_eq!(mismatch.code, Some("acp_call_mismatch")); assert_eq!( env.spawn_count(), spawns, @@ -605,28 +698,17 @@ async fn settled_call_replays_the_durable_result_without_spawning() { #[tokio::test] async fn gateway_restart_restores_the_durable_binding() { let env = Env::new("restart"); + let first_session; { - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "before"), - ) - .await; - let result = policy + 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"), @@ -636,29 +718,16 @@ async fn gateway_restart_restores_the_durable_binding() { .await; assert_eq!(result.status, AcpDelegationStatus::Completed); } - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - // Restart recovery terminates the previously active run; a fresh admitted - // run in the same RSS session is what needs the durable binding. - seed( - &persistence, - "session-1", - "run-2", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-2", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "after"), - ) - .await; - let result = policy + 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"), @@ -675,27 +744,14 @@ async fn gateway_restart_restores_the_durable_binding() { #[tokio::test] async fn restore_failure_never_creates_a_new_session() { let env = Env::new("restore-failure"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy + 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"), @@ -705,15 +761,14 @@ async fn restore_failure_never_creates_a_new_session() { .await; // Forget the peer session: the restore request is now rejected. fs::write(env.store(), "").expect("clear peer store"); - let second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let result = policy + 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"), @@ -730,27 +785,14 @@ async fn restore_failure_never_creates_a_new_session() { #[tokio::test] async fn missing_restore_capability_reports_unsupported_without_new_session() { let env = Env::new("no-restore"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy + 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"), @@ -759,15 +801,14 @@ async fn missing_restore_capability_reports_unsupported_without_new_session() { ) .await; env.set_caps("none"); - let second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let result = policy + 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"), @@ -783,27 +824,14 @@ async fn missing_restore_capability_reports_unsupported_without_new_session() { #[tokio::test] async fn load_only_restore_uses_load_and_never_mixes_replayed_text() { let env = Env::new("load-only"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy + 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"), @@ -812,15 +840,14 @@ async fn load_only_restore_uses_load_and_never_mixes_replayed_text() { ) .await; env.set_caps("load"); - let second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let result = policy + 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"), @@ -838,27 +865,14 @@ async fn load_only_restore_uses_load_and_never_mixes_replayed_text() { #[tokio::test] async fn workspace_change_refuses_the_old_binding() { let env = Env::new("workspace-change"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy + 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"), @@ -866,44 +880,41 @@ async fn workspace_change_refuses_the_old_binding() { &RunCancellation::new(), ) .await; - - persistence - .run_transition(&json!({ - "run_id": "run-1", - "from_status": "running", - "to_status": "completed", - "error_code": "", - "error_message": "", - "recovery_reason": "", - "now_ms": 1_700_000_000_002_i64, + 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(); + let mut doc = pin_document(&persistence, &first_run.session_id); + let expected_version = doc["version"].as_i64().unwrap_or(-1); + doc["version"] = json!(expected_version + 1); + doc["pins"]["fixture"]["workspace"] = json!(env.workspace.join("relocated")); + let value = persistence + .session_get(&first_run.session_id) + .expect("session"); + let row = value["rows"][0].as_array().expect("row").clone(); + let cas = persistence + .session_acp_delegation_cas(&json!({ + "session_id": first_run.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("close first run"); - // A second admitted workspace inside the configured root. - let other = env.workspace.join("other-workspace"); - fs::create_dir_all(&other).expect("second workspace"); - let other = fs::canonicalize(&other).expect("canonical second workspace"); - persistence - .session_workspace_bind( - "session-1", - &json!({ - "selector": "name:other", - "canonical_path": other.display().to_string(), - "selected_name": "other", - "generation": 2 - }), - ) - .expect("rebind workspace"); - - seed(&persistence, "session-1", "run-2", "owner-1", &other); - let second_scope = scope("run-2", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let result = policy + .expect("relocate pin workspace"); + assert_eq!(cas["applied"], true); + + 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"), @@ -919,27 +930,14 @@ async fn workspace_change_refuses_the_old_binding() { #[tokio::test] async fn approval_is_bound_to_the_exact_task_and_pin_version() { let env = Env::new("approval-binding"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "approved task"), - ) - .await; - let stale = policy + 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"), @@ -952,34 +950,89 @@ async fn approval_is_bound_to_the_exact_task_and_pin_version() { assert_eq!(env.spawn_count(), 0); } +#[tokio::test] +async fn automatic_reviewer_cannot_create_a_manual_approval() { + let env = Env::new("auto-approval"); + 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 refusal = runtime + .policy + .request_approval(&call_scope, &request("fixture", "task")) + .await + .expect_err("an automatic reviewer run must not create a manual row"); + assert_eq!(refusal.code(), "acp_human_review_required"); + assert_eq!(env.spawn_count(), 0); +} + +#[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, + &RunCancellation::new(), + ) + .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 state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy.arm_fault(AcpPolicyFault::AfterSessionCreate); - let cut = policy + 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"), @@ -989,20 +1042,32 @@ async fn crash_after_session_create_is_indeterminate_and_never_recreated() { .await; assert_eq!(cut.status, AcpDelegationStatus::Failed); assert_eq!(cut.code, Some("acp_session_indeterminate")); - let doc = pin_document(&persistence, "session-1"); + 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 second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let blocked = policy + 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"), @@ -1026,28 +1091,18 @@ 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 state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy.arm_fault(AcpPolicyFault::AfterSessionPersisted); - let cut = policy + 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"), @@ -1056,14 +1111,21 @@ async fn crash_after_id_persisted_blocks_the_old_call_but_allows_a_new_one() { ) .await; assert_eq!(cut.status, AcpDelegationStatus::Failed); - let doc = pin_document(&persistence, "session-1"); + // 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 = policy + let restart = runtime + .policy .delegate( &first_scope, &request("fixture", "a"), @@ -1076,15 +1138,12 @@ async fn crash_after_id_persisted_blocks_the_old_call_but_allows_a_new_one() { assert_eq!(env.spawn_count(), spawns); // A newly approved call may resume the persisted ID. - let second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let resumed = policy + 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"), @@ -1107,28 +1166,18 @@ async fn crash_after_prompt_publication_blocks_the_binding() { use rustscript_agent::service::acp_session_pins::AcpPolicyFault; let env = Env::new("cut-prompt"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy.arm_fault(AcpPolicyFault::AfterPromptPublished); - let cut = policy + 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"), @@ -1137,20 +1186,25 @@ async fn crash_after_prompt_publication_blocks_the_binding() { ) .await; assert_eq!(cut.status, AcpDelegationStatus::Failed); - let doc = pin_document(&persistence, "session-1"); + 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 second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let blocked = policy + 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"), @@ -1170,47 +1224,24 @@ async fn crash_after_prompt_publication_blocks_the_binding() { #[tokio::test] async fn concurrent_calls_on_one_pin_have_one_winner() { let env = Env::new("single-winner"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - seed( - &persistence, - "session-1", - "run-2", - "owner-1", - &env.workspace, + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--delay-ms", "15000"]), + "user", ); - let policy = AcpDelegationPolicy::install( - &env.config("fixture", &["--delay-ms", "5000"]), - persistence.clone(), - ) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let second_scope = scope("run-2", "session-1", "call-2"); - let first_witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - let second_witness = approve( - &policy, - &persistence, - &second_scope, - &request("fixture", "b"), - ) - .await; - let first_policy = policy.clone(); + 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 { - first_policy + policy .delegate( &first_scope, &request("fixture", "a"), @@ -1220,7 +1251,8 @@ async fn concurrent_calls_on_one_pin_have_one_winner() { .await }); wait_for(|| env.spawn_count() == 1, "the first delegation to spawn").await; - let second = policy + let second = runtime + .policy .delegate( &second_scope, &request("fixture", "b"), @@ -1235,36 +1267,79 @@ async fn concurrent_calls_on_one_pin_have_one_winner() { 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, + &RunCancellation::new(), + ) + .await + }); + wait_for(|| env.spawn_count() == 1, "first harness spawn").await; + let second = runtime + .policy + .delegate( + &second_scope, + &request("other", "b"), + &second_witness, + &RunCancellation::new(), + ) + .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); + assert!( + doc["pins"]["fixture"]["external_session_id"].is_string(), + "the concurrent other-harness write must not erase the fixture pin: {doc}" + ); + assert!(doc["pins"]["other"]["external_session_id"].is_string()); + 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 state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, + let runtime = Runtime::open_with( + &env, + env.config("fixture", &["--delay-ms", "30000"]), + "user", ); - let policy = AcpDelegationPolicy::install( - &env.config("fixture", &["--delay-ms", "8000"]), - persistence.clone(), - ) - .expect("install") - .expect("policy"); - - let first_scope = scope("run-1", "session-1", "call-1"); - let first_witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - let first_policy = policy.clone(); + 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 { - first_policy + policy .delegate( &first_scope, &request("fixture", "a"), @@ -1275,15 +1350,12 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { }); wait_for(|| env.spawn_count() == 1, "first spawn").await; // Same run: refused before any read or spawn. - let same_run_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &same_run_scope, - &request("fixture", "b"), - ) - .await; - let same_run = policy + 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"), @@ -1297,18 +1369,12 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { // Fill the remaining three service slots, then expect a typed refusal. let mut handles = Vec::new(); for index in 2..=4 { - let session = format!("session-{index}"); - let run = format!("run-{index}"); - seed(&persistence, &session, &run, "owner-1", &env.workspace); - let call_scope = scope(&run, &session, &format!("call-{index}")); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "fill"), - ) - .await; - let policy = policy.clone(); + 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( @@ -1320,23 +1386,19 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { .await })); } - wait_for(|| policy.available_processes() == 0, "the quota to fill").await; - seed( - &persistence, - "session-5", - "run-5", - "owner-1", - &env.workspace, - ); - let overflow_scope = scope("run-5", "session-5", "call-5"); - let witness = approve( - &policy, - &persistence, - &overflow_scope, - &request("fixture", "overflow"), - ) - .await; - let overflow = policy + 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"), @@ -1354,34 +1416,21 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { let result = handle.await.expect("quota task"); assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); } - assert_eq!(policy.available_processes(), 4); + 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 state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - policy + 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"), @@ -1389,19 +1438,20 @@ async fn session_delete_clears_the_local_binding() { &RunCancellation::new(), ) .await; - persistence - .session_delete("session-1") + runtime.finish(&first_run).await; + runtime + .persistence() + .session_delete(&first_run.session_id) .expect("delete session"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let new_scope = scope("run-1", "session-1", "call-2"); - let witness = approve(&policy, &persistence, &new_scope, &request("fixture", "b")).await; - let result = policy + + // 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"), @@ -1417,143 +1467,21 @@ async fn session_delete_clears_the_local_binding() { assert_eq!(env.recorded("session/new"), 2); } -#[tokio::test] -async fn automatic_reviewer_approval_is_never_accepted() { - let env = Env::new("auto-approval"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let challenge = policy - .request_approval(&call_scope, &request("fixture", "task")) - .await - .expect("challenge"); - persistence - .approval_resolve(&json!({ - "id": challenge.approval_id, - "run_id": "run-1", - "state": "approved", - "resolver": "guardian", - "decision_reason": "automatic", - "resolved_at_ms": 1, - })) - .expect("resolve approval"); - let result = policy - .delegate( - &call_scope, - &request("fixture", "task"), - &AcpApprovalWitness::new(challenge.approval_id), - &RunCancellation::new(), - ) - .await; - assert_eq!(result.status, AcpDelegationStatus::Denied); - assert_eq!(result.code, Some("acp_approval_not_user")); - assert_eq!(env.spawn_count(), 0, "an automatic approval must not spawn"); -} - -#[tokio::test] -async fn distinct_harnesses_keep_distinct_sessions() { - let env = Env::new("harness-isolation"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install( - &env.config_multi(&[("fixture", &[]), ("other", &[])]), - persistence.clone(), - ) - .expect("install") - .expect("policy"); - - let first_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &first_scope, - &request("fixture", "a"), - ) - .await; - let first = policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) - .await; - assert_eq!(first.status, AcpDelegationStatus::Completed); - - let second_scope = scope("run-1", "session-1", "call-2"); - let witness = approve(&policy, &persistence, &second_scope, &request("other", "b")).await; - let second = policy - .delegate( - &second_scope, - &request("other", "b"), - &witness, - &RunCancellation::new(), - ) - .await; - assert_eq!(second.status, AcpDelegationStatus::Completed, "{second:?}"); - assert_eq!( - second.text, "ctx=0;reply=policy-reply", - "the second harness must not share the first harness' history" - ); - let doc = pin_document(&persistence, "session-1"); - let first_id = doc["pins"]["fixture"]["external_session_id"] - .as_str() - .expect("fixture id") - .to_string(); - let second_id = doc["pins"]["other"]["external_session_id"] - .as_str() - .expect("other id") - .to_string(); - assert_ne!(first_id, second_id); - assert_eq!(env.recorded("session/new"), 2); - assert_eq!(env.spawn_count(), 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 state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "task"), - ) - .await; - policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); - let result = policy + 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"), @@ -1572,31 +1500,30 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { "the original delivery is not a replay of a success" ); - // Negative control: the charged slot is not released, and it is held by an - // explicit quarantine entry rather than being dropped. - assert_eq!(policy.available_processes(), 3); - assert_eq!(policy.quarantined_slots(), 1); + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!(runtime.policy.quarantined_slots(), 1); assert_eq!( - policy.quarantined_calls(), - vec![("session-1:fixture".to_string(), "call-1".to_string())] + runtime.policy.quarantined_calls(), + vec![(format!("{}:fixture", run.session_id), "call-1".to_string())] ); - let doc = pin_document(&persistence, "session-1"); + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &run.session_id); assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); assert!(doc["pins"]["fixture"]["active"].is_null()); assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); assert_eq!( - policy - .call_settlement("session-1", "call-1") + runtime + .policy + .call_settlement(&run.session_id, "call-1") .await .expect("settlement"), rustscript_agent::effects::DelegationSettlement::Settled ); - // The recorded outcome replays as indeterminate: no success, no re-run and - // no second release. let spawns = env.spawn_count(); - let replay = policy + let replay = runtime + .policy .delegate( &call_scope, &request("fixture", "task"), @@ -1608,19 +1535,15 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { assert_eq!(replay.status, AcpDelegationStatus::Indeterminate); assert_eq!(replay.code, Some("acp_cleanup_unverified")); assert_eq!(env.spawn_count(), spawns); - assert_eq!(policy.available_processes(), 3); - assert_eq!(policy.quarantined_slots(), 1); - - // The pin is indeterminate, so no later call may take it over. - let next_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &next_scope, - &request("fixture", "next"), - ) - .await; - let next = policy + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!(runtime.policy.quarantined_slots(), 1); + + let next_scope = scope(&run, "call-2"); + let witness = runtime + .approve(&run, &next_scope, &request("fixture", "next")) + .await; + let next = runtime + .policy .delegate( &next_scope, &request("fixture", "next"), @@ -1639,28 +1562,17 @@ async fn lost_cleanup_observer_keeps_capacity() { use rustscript_agent::service::acp_session_pins::AcpPolicyFault; let env = Env::new("cleanup-lost"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "task"), - ) - .await; - policy.arm_fault(AcpPolicyFault::CleanupObserverLost); - let result = policy + 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"), @@ -1670,10 +1582,8 @@ async fn lost_cleanup_observer_keeps_capacity() { .await; assert_eq!(result.status, AcpDelegationStatus::Indeterminate); assert_eq!(result.code, Some("acp_cleanup_unverified")); - assert_eq!(policy.available_processes(), 3); - assert_eq!(policy.quarantined_slots(), 1); - let doc = pin_document(&persistence, "session-1"); - assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); + assert_eq!(runtime.policy.available_processes(), 3); + assert_eq!(runtime.policy.quarantined_slots(), 1); } #[cfg(feature = "workspace-io-fault")] @@ -1682,28 +1592,17 @@ async fn confirmed_deferred_cleanup_releases_once_without_turning_it_into_succes use rustscript_agent::service::acp_session_pins::AcpPolicyFault; let env = Env::new("cleanup-confirmed"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "task"), - ) - .await; - policy.arm_fault(AcpPolicyFault::DeferredCleanupConfirmed); - let result = policy + 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::DeferredCleanupConfirmed); + let result = runtime + .policy .delegate( &call_scope, &request("fixture", "task"), @@ -1714,19 +1613,21 @@ async fn confirmed_deferred_cleanup_releases_once_without_turning_it_into_succes assert_eq!(result.status, AcpDelegationStatus::Indeterminate); assert_eq!(result.code, Some("acp_prompt_unsettled")); // Positive control: the proven cleanup releases the slot exactly once. - assert_eq!(policy.available_processes(), 4); - assert_eq!(policy.quarantined_slots(), 0); + assert_eq!(runtime.policy.available_processes(), 4); + assert_eq!(runtime.policy.quarantined_slots(), 0); - let doc = pin_document(&persistence, "session-1"); - assert_eq!(doc["pins"]["fixture"]["phase"], "bound"); - assert!(doc["pins"]["fixture"]["active"].is_null()); - assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + let persistence = runtime.persistence(); + let doc = pin_document(&persistence, &run.session_id); assert_eq!( - doc["calls"]["call-1"]["outcome"]["status"], "indeterminate", - "a cleanup success must not be rewritten as a prompt success" + doc["pins"]["fixture"]["phase"], "unknown", + "a prompt intent without settlement must never turn back into bound" ); + assert!(doc["pins"]["fixture"]["active"].is_null()); + assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); + assert_eq!(doc["calls"]["call-1"]["outcome"]["status"], "indeterminate"); - let replay = policy + let replay = runtime + .policy .delegate( &call_scope, &request("fixture", "task"), @@ -1736,19 +1637,15 @@ async fn confirmed_deferred_cleanup_releases_once_without_turning_it_into_succes .await; assert!(replay.replayed); assert_eq!(replay.status, AcpDelegationStatus::Indeterminate); - assert_eq!(policy.available_processes(), 4, "the slot is released once"); - - // The binding itself is still known-good, so a newly approved call may - // resume it; that is a new call, not a replay of the lost prompt. - let next_scope = scope("run-1", "session-1", "call-2"); - let witness = approve( - &policy, - &persistence, - &next_scope, - &request("fixture", "next"), - ) - .await; - let next = policy + assert_eq!(runtime.policy.available_processes(), 4, "released once"); + + // The pin is indeterminate: no later call may take it over. + let next_scope = scope(&run, "call-2"); + let witness = runtime + .approve(&run, &next_scope, &request("fixture", "next")) + .await; + let next = runtime + .policy .delegate( &next_scope, &request("fixture", "next"), @@ -1756,9 +1653,8 @@ async fn confirmed_deferred_cleanup_releases_once_without_turning_it_into_succes &RunCancellation::new(), ) .await; - assert_eq!(next.status, AcpDelegationStatus::Completed, "{next:?}"); - assert_eq!(env.recorded("session/new"), 1); - assert_eq!(env.recorded("session/resume"), 1); + assert_eq!(next.status, AcpDelegationStatus::Failed); + assert_eq!(next.code, Some("acp_session_indeterminate")); } #[cfg(feature = "workspace-io-fault")] @@ -1767,28 +1663,15 @@ async fn stale_settlement_never_clears_a_newer_owner() { use rustscript_agent::service::acp_session_pins::AcpPolicyFault; let env = Env::new("stale-settlement"); - let state = open_state(&env); - let persistence = state.persistence().expect("persistence"); - seed( - &persistence, - "session-1", - "run-1", - "owner-1", - &env.workspace, - ); - let policy = AcpDelegationPolicy::install(&env.config("fixture", &[]), persistence.clone()) - .expect("install") - .expect("policy"); - let call_scope = scope("run-1", "session-1", "call-1"); - let witness = approve( - &policy, - &persistence, - &call_scope, - &request("fixture", "task"), - ) - .await; - policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); - policy + 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"), @@ -1796,13 +1679,469 @@ async fn stale_settlement_never_clears_a_newer_owner() { &RunCancellation::new(), ) .await; - let before = pin_document(&persistence, "session-1"); - // The old settlement is replayed with a stale version. It must not touch - // the current pin document. - policy + 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, "session-1"); + let after = pin_document(&persistence, &run.session_id); assert_eq!(before, after); assert_eq!(after["pins"]["fixture"]["phase"], "unknown"); } + +#[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; + let cancellation = RunCancellation::new(); + cancellation.request(CancellationReason::Requested); + let result = runtime + .policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &cancellation, + ) + .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 cancellation = RunCancellation::new(); + let signal = cancellation.clone(); + runtime.policy.arm_pre_spawn_hook(move || { + signal.request(CancellationReason::Requested); + }); + let result = runtime + .policy + .delegate( + &call_scope, + &request("fixture", "task"), + &witness, + &cancellation, + ) + .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 cancellation = RunCancellation::new(); + let signal = 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, + &cancellation, + ) + .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 cancellation = RunCancellation::new(); + let signal = 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, &cancellation) + .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, + &RunCancellation::new(), + ) + .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, + &RunCancellation::new(), + ) + .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 cancellation = RunCancellation::new(); + let signal = 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, &cancellation) + .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, + &RunCancellation::new(), + ) + .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"); +} diff --git a/tests/fixtures/acp_policy/policy_agent.rs b/tests/fixtures/acp_policy/policy_agent.rs index d1d98b5..fc9e449 100644 --- a/tests/fixtures/acp_policy/policy_agent.rs +++ b/tests/fixtures/acp_policy/policy_agent.rs @@ -32,6 +32,8 @@ struct Config { reply: String, replay: String, delay_ms: u64, + init_delay_ms: u64, + restore_delay_ms: u64, hold: bool, } @@ -105,6 +107,9 @@ impl Harness { 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 }), @@ -186,6 +191,9 @@ impl Harness { .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, @@ -331,6 +339,18 @@ fn main() { .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"), }; if let Some(path) = config.spawn_log.as_ref() From d35be5bf676fb1f3df54953f5f6881749175cb98 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 11:23:29 +0800 Subject: [PATCH 11/27] docs(acp): add ACP harness delegation documentation Add docs/acp-delegation.md and update docs/acp-mode.md, docs/configuration.md and docs/status.md to describe the acp_harnesses startup entry, the delegate_acp tool contract, durable session pin binding and resume across gateway restarts, and the failure table for approvals, cancellation, timeouts and lost external sessions. Documentation only: no code, schema or configuration changes, and no new test coverage. --- docs/acp-delegation.md | 355 +++++++++++++++++++++++++++++++++++++++++ docs/acp-mode.md | 20 +++ docs/configuration.md | 40 +++++ docs/status.md | 1 + 4 files changed, 416 insertions(+) create mode 100644 docs/acp-delegation.md diff --git a/docs/acp-delegation.md b/docs/acp-delegation.md new file mode 100644 index 0000000..1609203 --- /dev/null +++ b/docs/acp-delegation.md @@ -0,0 +1,355 @@ +# 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. + +> **Status on this branch.** The delegation capability is a feature-branch +> candidate. The `docs/` text below is the agreed contract for that feature; +> this checkout's default tool registry, `ConfigFile` loader, gateway +> assembly, and MCP six-tool surface are unchanged, and an `acp_harnesses` +> key is rejected by the current loader until the implementing change lands. +> Nothing in this page is part of the v0.1.0 product claim. + +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 does. + +## 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 687d724..ebec3f2 100644 --- a/docs/acp-mode.md +++ b/docs/acp-mode.md @@ -121,6 +121,26 @@ 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: in the agreed contract, a normal 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. + +**Staged on this branch.** This checkout does not yet wire delegation into the +gateway: `delegate_acp` is absent from the current tool registry, the current +configuration loader rejects `acp_harnesses`, and the RSS runtime has no +delegation entry. This page is a feature-branch candidate whose documentation +states the agreed contract; this section will be adjusted after the combined +gateway, RSS, and real-harness end-to-end run passes. + ## Troubleshooting | Symptom | What to check | diff --git a/docs/configuration.md b/docs/configuration.md index da36abb..3084ba6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -271,6 +271,46 @@ 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`) + +**Feature-branch candidate, not part of this checkout.** The `acp_harnesses` +table below is the agreed opt-in contract for the `delegate_acp` gateway tool. +The current loader has no such field, so adding it to `config.yaml` is rejected +as an unknown key until the implementing change lands. It is documented here +because it reuses this same document and the existing agent-home +`ConfigFile::load` path; it introduces no new file, flag, or environment +variable. Until that change is present, the default tool table, the ACP proxy, +and the MCP six-tool list are exactly as described elsewhere on this page. + +```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/status.md b/docs/status.md index edc70d3..937fd8c 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`) | Feature-branch candidate, **not enabled in this checkout**: the default tool registry, the ACP proxy, and the MCP six-tool list are unchanged. The agreed opt-in contract (config table, tool input, approvals, durable session pin, resume, restart and unknown-state rules) is documented in [ACP delegation](acp-delegation.md). A standalone protocol pre-verification on OpenCode 1.19.6 with a scripted loopback model covered two separate processes resuming one external session ID with context carried from the first turn. Gateway end-to-end acceptance, approval binding, crash points, quotas, and cleanup evidence remain open. | ## Plugin graphs and state From fd1725f333ea871d5d863ca9cbddd0ea416ac104 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 13:09:02 +0800 Subject: [PATCH 12/27] test(acp): add two-process gateway restart harness Spawn the integration-test executable as a real Gateway child process with the production router, durable store, and bundled RSS loop; then stop and reap it and start a second OS process on the same private home and database. The control admits a plain run over HTTP in each process and proves the second process's actual model input contains the first turn's durable session record. --- tests/acp_delegation_e2e_tests.rs | 768 ++++++++++++++++++++++++++++++ 1 file changed, 768 insertions(+) create mode 100644 tests/acp_delegation_e2e_tests.rs diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs new file mode 100644 index 0000000..e906305 --- /dev/null +++ b/tests/acp_delegation_e2e_tests.rs @@ -0,0 +1,768 @@ +//! 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: run 1 is admitted +//! over real HTTP, completed, and persisted; the Gateway is stopped and reaped +//! and its listener is closed; a second Gateway process on the same private +//! home/store admits a distinct run on the same RSS session, and its actual +//! model input contains the first turn's durable record. + +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::str::FromStr; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use axum::serve; +use rustscript_agent::config::ProviderProfile; +use rustscript_agent::{ + AgentGatewayConfig, AgentGatewayState, AgentProviderHost, 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 READY_BUDGET: Duration = Duration::from_secs(300); +const RUN_BUDGET: Duration = Duration::from_secs(120); +const HTTP_BUDGET: Duration = Duration::from_secs(240); +const REAP_BUDGET: Duration = Duration::from_secs(30); + +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" + }) +} + +/// 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, + 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"); + } + self.inner.call(request, cancellation) + } +} + +/// 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) { + if std::thread::panicking() { + eprintln!( + "preserving failing Gateway fixture for diagnosis: {}", + self.root.display() + ); + return; + } + let _ = fs::remove_dir_all(&self.root); + } +} + +/// 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: Child, + address: SocketAddr, + token: String, + stdout_path: PathBuf, + stderr_path: PathBuf, + reaped: bool, +} + +impl GatewayProcess { + fn start(fixture: &GatewayFixture, label: &str, responses: &[Value]) -> Self { + let ready_path = fixture.root.join(format!("ready-{label}.json")); + let transcript_path = fixture.root.join(format!("transcript-{label}.jsonl")); + let spec_path = fixture.root.join(format!("spec-{label}.json")); + fs::write( + &spec_path, + json!({ + "db_path": fixture.db_path.to_string_lossy(), + "workspace_home": fixture.home.to_string_lossy(), + "ready_path": ready_path.to_string_lossy(), + "transcript_path": transcript_path.to_string_lossy(), + "responses": responses, + "run_timeout_ms": RUN_BUDGET.as_millis() as u64, + }) + .to_string(), + ) + .expect("write child Gateway spec"); + + let token = format!("rss-acp-e2e-{}", uuid::Uuid::new_v4().simple()); + let stdout_path = fixture.root.join(format!("stdout-{label}.log")); + let stderr_path = fixture.root.join(format!("stderr-{label}.log")); + let stdout = fs::File::create(&stdout_path).expect("create child stdout 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::from(stdout)) + .stderr(Stdio::from(stderr)); + let mut child = command.spawn().expect("Gateway harness child must spawn"); + + let deadline = Instant::now() + READY_BUDGET; + loop { + if let Ok(Some(status)) = child.try_wait() { + panic!( + "Gateway harness child exited before readiness ({status}): {}", + fs::read_to_string(&stderr_path).unwrap_or_default() + ); + } + 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 address = SocketAddr::from_str(address).expect("child listener address"); + return Self { + child, + address, + token, + stdout_path, + stderr_path, + reaped: false, + }; + } + assert!( + Instant::now() < deadline, + "Gateway harness child did not become ready: {}", + fs::read_to_string(&stderr_path).unwrap_or_default() + ); + 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)) + } + + /// Reads one run's SSE stream until the named event is observed. Reconnects + /// and replays from the beginning because a subscription made before the + /// live sender exists may end after partial history. + async fn await_event(&self, run_id: &str, event: &str) -> String { + let deadline = Instant::now() + RUN_BUDGET; + let needle = format!("\"event\":\"{event}\""); + let mut collected = String::new(); + loop { + if collected.contains(&needle) { + return collected; + } + assert!( + Instant::now() < deadline, + "run {run_id} did not emit {event}: {collected}\nstderr: {}", + self.stderr() + ); + let attempt_deadline = (Instant::now() + Duration::from_secs(4)).min(deadline); + if let Ok(Ok(mut stream)) = + tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(self.address)).await + { + let request = format!( + "GET /v1/runs/{run_id}/events HTTP/1.1\r\nHost: {}\r\nAuthorization: Bearer {}\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n", + self.address, self.token + ); + if stream.write_all(request.as_bytes()).await.is_ok() { + loop { + if collected.contains(&needle) || Instant::now() >= attempt_deadline { + break; + } + let mut chunk = [0_u8; 4096]; + match tokio::time::timeout( + Duration::from_millis(200), + stream.read(&mut chunk), + ) + .await + { + Ok(Ok(0)) => break, + Ok(Ok(read)) => { + collected.extend(String::from_utf8_lossy(&chunk[..read]).chars()) + } + Ok(Err(_)) => break, + Err(_) => {} + } + } + } + } + if !collected.contains(&needle) { + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + } + + /// 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.as_mut().expect("child stdin"); + writeln!(stdin, "shutdown").expect("send shutdown to the Gateway harness"); + stdin.flush().expect("flush shutdown"); + } + drop(self.child.stdin.take()); + + let deadline = Instant::now() + REAP_BUDGET; + loop { + match self.child.try_wait().expect("poll Gateway harness") { + Some(status) => { + assert!( + status.success(), + "Gateway harness did not exit cleanly ({status}): {}\n{}", + self.stderr(), + fs::read_to_string(&self.stdout_path).unwrap_or_default() + ); + break; + } + None => { + assert!( + Instant::now() < deadline, + "Gateway harness did not stop within {REAP_BUDGET:?}: {}", + self.stderr() + ); + std::thread::sleep(Duration::from_millis(25)); + } + } + } + self.reaped = true; + + 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)); + } + } +} + +impl Drop for GatewayProcess { + fn drop(&mut self) { + if !self.reaped { + let _ = self.child.kill(); + let _ = self.child.wait(); + self.reaped = true; + } + } +} + +fn transcript_requests(fixture: &GatewayFixture, label: &str) -> Vec { + let path = fixture.root.join(format!("transcript-{label}.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 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(" ") +} + +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 transcript_path = spec["transcript_path"] + .as_str() + .expect("child transcript path"); + let run_timeout_ms = spec["run_timeout_ms"].as_u64().unwrap_or(90_000); + + let config = AgentGatewayConfig { + bearer_token: Some(token), + run_timeout: Duration::from_millis(run_timeout_ms), + ..AgentGatewayConfig::default() + }; + let state = AgentGatewayState::with_agent_file_and_sqlite( + config, + rustscript_agent::bundled_agent_main_path(), + db_path, + ) + .expect("bundled RSS agent must compile against the durable store") + .with_workspace_home(workspace_home); + state + .service() + .set_provider_profile(ProviderProfile::builtin("local-agent").expect("local-agent profile")) + .expect("install the local-agent provider profile"); + + let scripted = ScriptedProvider::new(); + if let Some(responses) = spec["responses"].as_array() { + for response in responses { + scripted.push_ok(response.clone()); + } + } + let recorder = RecordingProvider { + inner: scripted, + transcript: Mutex::new( + fs::File::create(transcript_path).expect("create provider transcript"), + ), + }; + state + .service() + .inject_provider_host(std::sync::Arc::new(recorder)); + + 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"); + 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::<()>(); + 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(_) if line.trim() == "shutdown" => { + let _ = shutdown_tx.send(()); + return; + } + Ok(_) => {} + 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"); + + // The production SIGINT path: stop admission, wake the idle janitor, then + // join the owned service/storage workers before the process exits. The + // terminal event is observable slightly before the run worker drops its + // occupancy, so a bounded retry waits out that hand-off instead of racing + // the production shutdown contract. + 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); +} + +#[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() + ); + + // ---- First Gateway OS process: create/bind the session and run turn 1. ---- + let first = GatewayProcess::start(&fixture, "first", &[text_response(FIRST_ANSWER_MARKER)]); + let (status, health) = first.health().await; + assert_eq!(status, 200, "first Gateway health: {health}"); + assert_eq!(health["status"], json!("ok")); + + create_session(&first, &session_id).await; + bind_workspace(&first, &session_id).await; + let first_prompt = format!("{FIRST_PROMPT_MARKER}: note the durable first turn."); + let first_run = admit_run(&first, &session_id, &first_prompt).await; + let first_events = first.await_event(&first_run, "run.completed").await; + assert!( + first_events.contains("run.completed") && first_events.contains(FIRST_ANSWER_MARKER), + "first turn must complete with the fixture answer: {first_events}" + ); + + // The first process's real model input and the durable user record. + let first_requests = transcript_requests(&fixture, "first"); + assert_eq!( + first_requests.len(), + 1, + "one plain Q&A turn must make exactly one provider call: {first_requests:?}" + ); + let first_request = &first_requests[0]["request"]; + assert_eq!(first_request["provider"], json!("local-agent")); + assert!( + first_request.to_string().contains(FIRST_PROMPT_MARKER), + "the first model input must carry the first prompt: {first_request}" + ); + let (status, messages) = first + .request("GET", &format!("/api/sessions/{session_id}/messages"), None) + .await + .expect("first Gateway session messages"); + assert_eq!(status, 200, "first session messages: {messages}"); + let user_messages: Vec = messages["data"] + .as_array() + .expect("session message list") + .iter() + .filter(|message| message["role"] == json!("user")) + .cloned() + .collect(); + assert_eq!( + user_messages.len(), + 1, + "first turn user message: {messages}" + ); + assert!( + message_text(&user_messages[0]).contains(FIRST_PROMPT_MARKER), + "the first user turn must be durably recorded: {messages}" + ); + + // 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 second = GatewayProcess::start(&fixture, "second", &[text_response(SECOND_ANSWER_MARKER)]); + let (status, health) = second.health().await; + assert_eq!(status, 200, "second Gateway health: {health}"); + + 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); + + // Run 1's durable terminal record is readable from the fresh process. + let persisted_events = second.await_event(&first_run, "run.completed").await; + assert!( + persisted_events.contains(FIRST_ANSWER_MARKER), + "the first turn output must survive the process restart: {persisted_events}" + ); + + let second_prompt = format!("{SECOND_PROMPT_MARKER}: continue from the durable session."); + let second_run = admit_run(&second, &session_id, &second_prompt).await; + let second_events = second.await_event(&second_run, "run.completed").await; + assert!( + second_events.contains(SECOND_ANSWER_MARKER), + "second turn must complete with its own fixture answer: {second_events}" + ); + + // The decisive control: the second OS process's actual model input contains + // the first turn's durable record and the new prompt, and nothing from the + // second answer script leaks backwards. + let second_requests = transcript_requests(&fixture, "second"); + assert_eq!( + second_requests.len(), + 1, + "the second plain turn must make exactly one provider call: {second_requests:?}" + ); + let second_request = &second_requests[0]["request"]; + let wire = second_request.to_string(); + assert!( + wire.contains(FIRST_PROMPT_MARKER), + "the restarted Gateway model input must include the first turn record: {second_request}" + ); + assert!( + wire.contains(SECOND_PROMPT_MARKER), + "the restarted Gateway model input must include the new prompt: {second_request}" + ); + assert!( + !wire.contains(SECOND_ANSWER_MARKER), + "the model input must not already contain its own future answer: {second_request}" + ); + let wire_messages = second_request["messages"] + .as_array() + .expect("model input messages"); + let wire_user_texts: Vec = wire_messages + .iter() + .filter(|message| message["role"] == json!("user")) + .map(message_text) + .collect(); + assert_eq!( + wire_user_texts.len(), + 2, + "two persisted user turns must reach the second model call: {second_request}" + ); + assert!(wire_user_texts[0].contains(FIRST_PROMPT_MARKER)); + assert!(wire_user_texts[1].contains(SECOND_PROMPT_MARKER)); + + 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 roles: Vec<&str> = messages["data"] + .as_array() + .expect("session message list") + .iter() + .filter_map(|message| message["role"].as_str()) + .collect(); + assert_eq!( + roles.iter().filter(|role| **role == "user").count(), + 2, + "both user turns must be persisted: {messages}" + ); + + second.stop_and_reap(); +} + +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" + ); +} From 73bd8f5debdba7fdc428daec0c72b1d584b52a44 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 13:20:47 +0800 Subject: [PATCH 13/27] fix(acp): bind delegation approval and settlement to the live gateway run - Route automatic and guardian-sealed runs through a real durable human_pending approval row instead of refusing the tool outright; only an authenticated manual resolver can authorize the external process. - Read workspace authority, cancellation root, sealed reviewer and the admitted deadline from the live run, and revalidate them in a synchronous barrier immediately before spawn. A stop, revocation, elapsed clock, inactive run or stale approval fails with zero spawns. - Pin CAS retries to the original session row identity, so a recreated session never inherits an approval, lease or outcome. A stale lease is reclaimed only when the store proves its owning run terminal, and the takeover settles the interrupted call in the same durable write. - Keep pin ownership and the process slot charged until a real terminal cleanup report exists; an interrupted restore before the prompt send intent stays recoverable and is never replayed as a prompt. - Refuse a run output budget below the minimal result envelope before any approval or process exists, and drop the diagnostic code before falling back to a bounded refusal so a legal budget always carries a complete or explicitly truncated envelope. --- src/service.rs | 160 +++- src/service/acp_session_pins.rs | 624 ++++++++++++--- tests/acp_delegation_policy_tests.rs | 1078 +++++++++++++++++--------- 3 files changed, 1352 insertions(+), 510 deletions(-) diff --git a/src/service.rs b/src/service.rs index 6339e2e..6010f1c 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1664,11 +1664,16 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { if handle.is_terminal() || handle.cancel.requested().is_some() { return Err("acp_run_inactive"); } - // Delegated external execution is a forced human decision. A run - // sealed for the automatic reviewer can never create one. - if !self.sealed_user_reviewer(&request.run_id) { - return Err("acp_human_review_required"); - } + // 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 @@ -1681,6 +1686,11 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { 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, @@ -1689,7 +1699,7 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { "tool_name": acp_session_pins::DELEGATION_TOOL_NAME, "arguments_json": "{}", "risk_class": "execute", - "decision_scope": "single_call", + "decision_scope": request_scope, "one_time": 1, "requested_at_ms": timestamp(), "expires_at_ms": request.expires_at_ms, @@ -1697,6 +1707,24 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { 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")?; @@ -1715,6 +1743,7 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { || 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"); @@ -1765,7 +1794,7 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { 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, scope) { + 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(); @@ -1779,6 +1808,79 @@ impl acp_session_pins::AcpApprovalGateway for AgentService { 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() + } +} + +/// 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 { @@ -6191,7 +6293,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( @@ -6265,15 +6367,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, } } @@ -6538,7 +6652,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); @@ -6659,7 +6774,6 @@ impl AgentService { scope: acp_session_pins::AcpDelegationScope, request: acp_session_pins::AcpDelegationRequest, witness: acp_session_pins::AcpApprovalWitness, - cancellation: &RunCancellation, ) -> acp_session_pins::AcpDelegationResult { let harness_id = request.harness_id.clone(); let Some(policy) = self.acp_delegation() else { @@ -6673,9 +6787,7 @@ impl AgentService { replayed: false, }; }; - policy - .delegate(&scope, &request, &witness, cancellation) - .await + policy.delegate(&scope, &request, &witness).await } /// Resolves and durably changes a session workspace through the shared RSS @@ -9441,6 +9553,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. diff --git a/src/service/acp_session_pins.rs b/src/service/acp_session_pins.rs index 873ba70..3e690d7 100644 --- a/src/service/acp_session_pins.rs +++ b/src/service/acp_session_pins.rs @@ -34,6 +34,14 @@ //! 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; @@ -201,6 +209,34 @@ impl AcpApprovalWitness { } } +/// 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; +} + +/// 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. @@ -231,6 +267,15 @@ pub trait AcpApprovalGateway: Send + Sync { ) -> 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. @@ -239,9 +284,6 @@ pub struct AcpDelegationScope { pub run_id: String, pub session_id: String, pub tool_call_id: String, - /// Optional absolute wall-clock run deadline; the effective deadline is - /// always the earlier of this and [`DELEGATION_DEADLINE_MS`] from now. - pub run_deadline_ms: Option, } /// Why a delegation was refused before any successful settlement. @@ -281,14 +323,14 @@ pub enum AcpPolicyFault { 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, - /// `close` returned unconfirmed, but the supervisor will publish a positive - /// cleanup report. - DeferredCleanupConfirmed, /// The cleanup observer ended without any report. CleanupObserverLost, /// The cleanup report arrived explicitly unconfirmed. @@ -318,6 +360,14 @@ struct PolicyInner { fault: Mutex, #[cfg(feature = "workspace-io-fault")] pre_spawn_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. @@ -367,6 +417,10 @@ impl AcpDelegationPolicy { fault: Mutex::new(AcpPolicyFault::None), #[cfg(feature = "workspace-io-fault")] pre_spawn_hook: Mutex::new(None), + #[cfg(feature = "workspace-io-fault")] + cas_hook: Mutex::new(None), + #[cfg(feature = "workspace-io-fault")] + cleanup_hold: Mutex::new(None), }), })) } @@ -381,6 +435,16 @@ impl AcpDelegationPolicy { self.inner.quota.available_permits() } + /// A call whose smallest successful envelope cannot fit the run's + /// tool-output budget can never deliver a result; it is refused before an + /// approval row or a process exists. + fn require_deliverable_budget(&self, harness_id: &str) -> Result<(), AcpPolicyRefusal> { + if minimal_success_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; @@ -398,13 +462,38 @@ impl AcpDelegationPolicy { .expect("acp pre-spawn 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::DeferredCleanupConfirmed - | AcpPolicyFault::CleanupObserverLost - | AcpPolicyFault::CleanupUnconfirmed => { + AcpPolicyFault::CleanupObserverLost | AcpPolicyFault::CleanupUnconfirmed => { let taken = *fault; *fault = AcpPolicyFault::None; Some(taken) @@ -472,11 +561,23 @@ impl AcpDelegationPolicy { 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(&snapshot, &self.inner.allowed_roots)?; + 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); @@ -485,7 +586,7 @@ impl AcpDelegationPolicy { .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(scope.run_deadline_ms, now_ms); + 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")); } @@ -558,13 +659,16 @@ impl AcpDelegationPolicy { scope: &AcpDelegationScope, request: &AcpDelegationRequest, witness: &AcpApprovalWitness, - cancellation: &RunCancellation, ) -> AcpDelegationResult { let harness_id = request.harness_id.clone(); - let result = match self - .delegate_inner(scope, request, witness, cancellation) - .await - { + if self.require_deliverable_budget(&harness_id).is_err() { + return AcpDelegationResult::refusal( + &harness_id, + AcpDelegationStatus::Failed, + "acp_delegation_budget", + ); + } + let result = match self.delegate_inner(scope, request, witness).await { Ok(result) => result, Err(refusal) => { AcpDelegationResult::refusal(&harness_id, refusal.status(), refusal.code()) @@ -578,15 +682,27 @@ impl AcpDelegationPolicy { scope: &AcpDelegationScope, request: &AcpDelegationRequest, witness: &AcpApprovalWitness, - cancellation: &RunCancellation, ) -> Result { validate_request(request)?; let Some(launch) = self.inner.harnesses.get(&request.harness_id) else { return Err(AcpPolicyRefusal::Denied("acp_harness_unknown")); }; - if cancellation.requested().is_some() { + 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 cancellation = facts.cancellation.clone(); 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() { @@ -606,7 +722,8 @@ impl AcpDelegationPolicy { }; let mut snapshot = self.read_session(&scope.session_id).await?; - let workspace = admitted_workspace(&snapshot, &self.inner.allowed_roots)?; + let original_identity = snapshot.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) { @@ -615,10 +732,8 @@ impl AcpDelegationPolicy { .outcome .clone() .ok_or(AcpPolicyRefusal::Failed("acp_call_record_invalid"))?; - self.verify_replay( - existing, scope, request, witness, &snapshot, &workspace, launch, - ) - .await?; + 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 @@ -631,6 +746,7 @@ impl AcpDelegationPolicy { .get(&request.harness_id) .map(|pin| pin.version) .unwrap_or(0); + 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 @@ -643,25 +759,34 @@ impl AcpDelegationPolicy { return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } if let Some(lease) = pin.active.as_ref() { - // The in-process pin gate is free here, so any visible lease - // belongs to an interrupted call. Only the middle cut (peer ID - // durable, prompt intent never written) may be reclaimed. + // 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 = doc - .calls - .get(&lease.call_id) - .is_some_and(|call| call.phase == CallPhase::SessionBound); + let reclaimable = !pin.cleanup_pending + && doc.calls.get(&lease.call_id).is_some_and(|call| { + 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, &workspace) + self.validate_witness(witness, scope, request, &snapshot, &facts) .await?; if pin_version != doc @@ -672,7 +797,7 @@ impl AcpDelegationPolicy { { return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); } - let deadline = effective_deadline(scope.run_deadline_ms); + let deadline = effective_deadline(run_deadline_ms(&facts)); if Instant::now() >= deadline { return Err(AcpPolicyRefusal::Failed("acp_delegation_deadline")); } @@ -683,11 +808,14 @@ impl AcpDelegationPolicy { .try_acquire_owned() .map_err(|_| AcpPolicyRefusal::Busy("acp_delegation_capacity"))?; - // Waiting for the permit is a real boundary: re-read the authoritative + // 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?; - let workspace = admitted_workspace(&snapshot, &self.inner.allowed_roots)?; + 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 @@ -703,8 +831,8 @@ impl AcpDelegationPolicy { if cancellation.requested().is_some() { return Err(AcpPolicyRefusal::Denied("acp_delegation_cancelled")); } - let facts = self - .validate_witness(witness, scope, request, &snapshot, &workspace) + let witness_facts = self + .validate_witness(witness, scope, request, &snapshot, &facts) .await?; if Instant::now() >= deadline { return Err(AcpPolicyRefusal::Failed("acp_delegation_deadline")); @@ -727,7 +855,7 @@ impl AcpDelegationPolicy { .get(&request.harness_id) .and_then(|pin| pin.external_session_id.as_ref()) .is_none(), - expires_at_ms: facts.expires_at_ms, + expires_at_ms: witness_facts.expires_at_ms, }; // Durable preparation: consume the approval binding, insert the @@ -737,7 +865,7 @@ impl AcpDelegationPolicy { run_id: scope.run_id.clone(), harness_id: request.harness_id.clone(), approval_id: witness.approval_id.clone(), - approval_resolver: Some(facts.resolver.clone()), + approval_resolver: Some(witness_facts.resolver.clone()), task: request.task.clone(), launch: launch.fingerprint.clone(), workspace: workspace.path.clone(), @@ -786,15 +914,36 @@ impl AcpDelegationPolicy { 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() { - let reclaimable = doc - .calls - .get(&active.call_id) - .is_some_and(|call| call.phase == CallPhase::SessionBound); - if !reclaimable { + // 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")); @@ -807,12 +956,13 @@ impl AcpDelegationPolicy { } // Consumption and preparation are the same durable write. doc.pending_approvals.remove(&approval_key); - doc.calls.insert(call_id.clone(), call.clone()); + 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) }) @@ -837,80 +987,96 @@ impl AcpDelegationPolicy { return Err(AcpPolicyRefusal::Failed("acp_storage_conflict")); } - // Last boundary before spawn: cancellation, run liveness, approval, - // workspace and the absolute deadline are checked after every wait. + // 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(); - if cancellation.requested().is_some() { + + // 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, - snapshot, + fresh, permit, - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", + AcpDelegationStatus::Denied, + "acp_session_identity_changed", ) .await; } - if Instant::now() >= deadline { + if !self.lease_names(&fresh, &request.harness_id, &scope.tool_call_id) { return self .abort_pre_spawn( scope, request, - snapshot, + fresh, permit, - AcpDelegationStatus::Timeout, - "acp_delegation_deadline", + AcpDelegationStatus::Failed, + "acp_storage_conflict", ) .await; } - if !self.inner.gateway.run_active(&scope.run_id) { + if let Err(refusal) = self + .validate_witness(witness, scope, request, &fresh, &facts) + .await + { return self .abort_pre_spawn( scope, request, - snapshot, + fresh, permit, - AcpDelegationStatus::Denied, - "acp_run_inactive", + refusal.status(), + refusal.code(), ) .await; } - let fresh = self.read_session(&scope.session_id).await?; - let fresh_workspace = admitted_workspace(&fresh, &self.inner.allowed_roots)?; - if fresh_workspace.path != workspace.path - || fresh_workspace.generation != workspace.generation - || fresh.owner != snapshot.owner - { + // 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, - snapshot, + fresh, permit, AcpDelegationStatus::Denied, - "acp_binding_mismatch", + "acp_run_inactive", ) .await; - } - if let Err(refusal) = self - .validate_witness(witness, scope, request, &fresh, &fresh_workspace) - .await - { + }; + if live.session_id != facts.session_id || live.reviewer != facts.reviewer { return self .abort_pre_spawn( scope, request, - snapshot, + fresh, permit, - refusal.status(), - refusal.code(), + AcpDelegationStatus::Denied, + "acp_binding_mismatch", ) .await; } + let deadline = effective_deadline(run_deadline_ms(&live)); snapshot = fresh; + // Synchronous arbitration, in this order: stop, elapsed deadline, run + // liveness, then workspace revocation and identity. Nothing is awaited + // between this barrier and the process spawn; an event observed here + // is a pre-spawn event and produces zero spawns. + if let PreSpawnBarrier::Refuse(status, code) = + self.pre_spawn_barrier(scope, &live, &workspace, deadline) + { + return self + .abort_pre_spawn(scope, request, snapshot, permit, status, code) + .await; + } + let launch_handle = AcpDelegationLaunch::new( launch.command.clone(), launch.arguments.clone(), @@ -923,13 +1089,55 @@ impl AcpDelegationPolicy { request, launch_handle, deadline, - cancellation, + &live, + &workspace, &mut snapshot, permit, ) .await } + /// One synchronous pre-spawn decision. + /// + /// The order is fixed: the run's stop/revocation root first, then the + /// admitted absolute deadline, then run liveness, then the retained + /// workspace authority. Whoever wins here is a pre-spawn event. + fn pre_spawn_barrier( + &self, + scope: &AcpDelegationScope, + facts: &AcpRunFacts, + workspace: &AdmittedWorkspace, + deadline: Instant, + ) -> PreSpawnBarrier { + if facts.cancellation.requested().is_some() { + return PreSpawnBarrier::Refuse( + AcpDelegationStatus::Cancelled, + "acp_delegation_cancelled", + ); + } + if Instant::now() >= deadline { + return PreSpawnBarrier::Refuse( + AcpDelegationStatus::Timeout, + "acp_delegation_deadline", + ); + } + if !self.inner.gateway.run_active(&scope.run_id) { + return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_run_inactive"); + } + let Some(authority) = facts.workspace.as_ref() else { + return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_workspace_unbound"); + }; + if authority.revoked() || authority.check().is_err() { + return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_workspace_invalid"); + } + if authority.canonical_path() != workspace.path + || authority.generation() != workspace.generation + { + return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_binding_mismatch"); + } + PreSpawnBarrier::Proceed + } + /// Settles a prepared call that never spawned a process. #[allow(clippy::too_many_arguments)] async fn abort_pre_spawn( @@ -976,10 +1184,21 @@ impl AcpDelegationPolicy { request: &AcpDelegationRequest, launch: AcpDelegationLaunch, deadline: Instant, - cancellation: &RunCancellation, + facts: &AcpRunFacts, + workspace: &AdmittedWorkspace, snapshot: &mut SessionSnapshot, permit: tokio::sync::OwnedSemaphorePermit, ) -> Result { + // The final synchronous decision sits immediately before `connect`, + // which creates the process. No await separates them. + if let PreSpawnBarrier::Refuse(status, code) = + self.pre_spawn_barrier(scope, facts, workspace, deadline) + { + return self + .abort_pre_spawn(scope, request, snapshot.clone(), permit, status, code) + .await; + } + let cancellation = &facts.cancellation; if cancellation.requested().is_some() || Instant::now() >= deadline { let timed_out = Instant::now() >= deadline; let (status, code) = if timed_out { @@ -1080,6 +1299,18 @@ impl AcpDelegationPolicy { ) .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, snapshot) + .await + .is_err() + { + return self + .abort_unknown_state(scope, request, snapshot, client, observer, permit) + .await; + } let restored = { let future = client.restore_session(existing.clone()); tokio::pin!(future); @@ -1121,7 +1352,22 @@ impl AcpDelegationPolicy { ) .await; } - Some(Ok(_)) => existing, + Some(Ok(_)) => { + #[cfg(feature = "workspace-io-fault")] + if self.take_fault(AcpPolicyFault::AfterRestoreBeforeIntent) { + let _ = client.close().await; + // The call stays `restoring` with its lease: a + // later call may reclaim it after the store proves + // this run terminal, and then restore the same ID. + self.quarantine_permit( + permit, + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + } + existing + } } } None => { @@ -1285,17 +1531,6 @@ impl AcpDelegationPolicy { .await .unwrap_or(u64::MAX); let (proof, code) = match fault { - AcpPolicyFault::DeferredCleanupConfirmed => ( - CleanupProof::Confirmed(crate::acp::AcpCleanupReport { - direct_child_reaped: true, - exit_status: None, - group_signal_sent: true, - forced: true, - group_clear: true, - cleanup_confirmed: true, - }), - "acp_prompt_unsettled", - ), AcpPolicyFault::CleanupObserverLost => { (CleanupProof::Lost, "acp_cleanup_unverified") } @@ -1470,7 +1705,6 @@ impl AcpDelegationPolicy { permit: tokio::sync::OwnedSemaphorePermit, code: &'static str, ) -> Result { - let _ = self.mark_pin_unknown(scope, request, snapshot).await; let report = client.close().await; if !report.cleanup_confirmed { return self @@ -1675,6 +1909,34 @@ impl AcpDelegationPolicy { Ok(()) } + async fn mark_session_restoring( + &self, + scope: &AcpDelegationScope, + request: &AcpDelegationRequest, + snapshot: &mut SessionSnapshot, + ) -> Result<(), AcpPolicyRefusal> { + let harness_id = request.harness_id.clone(); + let call_id = scope.tool_call_id.clone(); + let (fresh, _) = self + .mutate(&scope.session_id, move |doc, _snapshot| { + let Some(call) = doc.calls.get_mut(&call_id) else { + return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + }; + if call.phase != CallPhase::Prepared { + return Err(AcpPolicyRefusal::Failed("acp_call_record_invalid")); + } + call.phase = CallPhase::Restoring; + if let Some(pin) = doc.pins.get_mut(&harness_id) { + 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, @@ -1742,16 +2004,19 @@ impl AcpDelegationPolicy { request: &AcpDelegationRequest, witness: &AcpApprovalWitness, snapshot: &SessionSnapshot, - workspace: &AdmittedWorkspace, + 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.harness_id != request.harness_id || call.task != request.task || call.launch != launch.fingerprint - || call.workspace != workspace.path - || call.workspace_generation != workspace.generation + || 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 @@ -1836,7 +2101,19 @@ impl AcpDelegationPolicy { .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), @@ -1905,8 +2182,17 @@ impl AcpDelegationPolicy { && pin.active.as_ref().is_some_and(|lease| { lease.call_id == call_id && lease.run_id == run_id }); - if owns { + if owns && !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; + pin.version += 1; + lease_guard = Some((harness_id_owned.clone(), call_id.clone())); + } else if owns { pin.active = None; + pin.cleanup_pending = false; pin.phase = if had_intent { PinPhase::Unknown } else { @@ -1961,7 +2247,7 @@ impl AcpDelegationPolicy { scope: &AcpDelegationScope, request: &AcpDelegationRequest, snapshot: &SessionSnapshot, - workspace: &AdmittedWorkspace, + facts: &AcpRunFacts, ) -> Result { let persistence = self.inner.persistence.clone(); let id = witness.approval_id.clone(); @@ -1997,7 +2283,20 @@ impl AcpDelegationPolicy { if !matches!(risk, "execute" | "privileged") { return Err(AcpPolicyRefusal::Denied("acp_approval_risk")); } - let _ = (snapshot, workspace, request); + // 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(); @@ -2038,6 +2337,13 @@ impl AcpDelegationPolicy { ) -> 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. + let identity = snapshot.identity(); + #[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; @@ -2054,8 +2360,8 @@ impl AcpDelegationPolicy { }; let payload = json!({ "session_id": session_id, - "owner": snapshot.owner, - "created_at_ms": snapshot.created_at_ms, + "owner": identity.0, + "created_at_ms": identity.1, "expected_version": expected_version, "lease_path": lease_path, "lease_call": lease_call, @@ -2072,8 +2378,12 @@ impl AcpDelegationPolicy { .and_then(Value::as_array) .cloned() .ok_or(AcpPolicyRefusal::Failed("acp_session_unknown"))?; - snapshot = SessionSnapshot::from_row(row) + 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)); } @@ -2145,6 +2455,12 @@ enum PromptWait { Cancelled, } +/// Outcome of the synchronous decision immediately before process creation. +enum PreSpawnBarrier { + Proceed, + Refuse(AcpDelegationStatus, &'static str), +} + fn build_launch(harness: &AcpHarnessSettings) -> Result { if harness.args.len() > MAX_ACP_HARNESS_ARGUMENTS || harness.argument_bytes() > MAX_ACP_HARNESS_ARGUMENT_BYTES @@ -2215,6 +2531,11 @@ fn approval_id(run_id: &str, call_id: &str) -> Result 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 { @@ -2293,6 +2614,11 @@ fn clamp_text(text: &mut String, budget: usize, truncated: &mut bool) { /// 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 at least a minimal successful +/// envelope fits. If an outcome is still too large with empty text, its static +/// diagnostic code is dropped first; the last resort is the minimal bounded +/// refusal, never an oversized result. fn bounded_result(mut result: AcpDelegationResult, budget: usize) -> AcpDelegationResult { if envelope_len(&result) <= budget { return result; @@ -2313,7 +2639,44 @@ fn bounded_result(mut result: AcpDelegationResult, budget: usize) -> AcpDelegati if chosen < source.len() { result.truncated = true; } - result + if envelope_len(&result) <= budget { + return result; + } + result.code = None; + result.truncated = true; + if envelope_len(&result) <= budget { + return result; + } + budget_refusal_result(&result.harness_id, result.replayed) +} + +/// Smallest successful typed envelope for one harness: empty text, end turn, +/// and no diagnostic code. +fn minimal_success_envelope_bytes(harness_id: &str) -> usize { + let result = AcpDelegationResult::settled( + harness_id, + AcpDelegationStatus::Completed, + String::new(), + Some(AcpStopReason::EndTurn), + false, + None, + false, + ); + envelope_len(&result) +} + +/// 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 { @@ -2368,17 +2731,19 @@ struct AdmittedWorkspace { } fn admitted_workspace( - snapshot: &SessionSnapshot, + facts: &AcpRunFacts, allowed_roots: &[PathBuf], ) -> Result { - let workspace = snapshot - .metadata - .as_deref() - .and_then(|metadata| serde_json::from_str::(metadata).ok()) - .and_then(|metadata| metadata.get("workspace").cloned()) - .and_then(|workspace| serde_json::from_value::(workspace).ok()) - .ok_or(AcpPolicyRefusal::Denied("acp_workspace_unbound"))?; - let path = PathBuf::from(&workspace.canonical_path); + 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() @@ -2396,21 +2761,11 @@ fn admitted_workspace( return Err(AcpPolicyRefusal::Denied("acp_workspace_invalid")); } Ok(AdmittedWorkspace { - path: workspace.canonical_path, - generation: workspace.generation, + path: authority.canonical_path().to_string(), + generation: authority.generation(), }) } -#[derive(Clone, Debug, Deserialize)] -struct BoundWorkspace { - canonical_path: String, - #[serde(default)] - #[allow(dead_code)] - selector: String, - #[serde(default)] - generation: u64, -} - /// Durable session columns read by the policy. #[derive(Clone)] struct SessionSnapshot { @@ -2421,6 +2776,13 @@ struct SessionSnapshot { } 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) -> (String, i64) { + (self.owner.clone(), self.created_at_ms) + } + fn from_row(row: Vec) -> Option { let text = |index: usize| { row.get(index) @@ -2499,6 +2861,9 @@ enum PinPhase { 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 { @@ -2519,6 +2884,10 @@ struct AcpPin { 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, } @@ -2532,6 +2901,7 @@ impl AcpPin { phase: PinPhase::Bound, external_session_id: None, active: None, + cleanup_pending: false, version: 0, } } @@ -2554,6 +2924,9 @@ pub(crate) enum CallPhase { 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. @@ -2565,9 +2938,11 @@ impl CallPhase { fn settlement(self) -> crate::effects::DelegationSettlement { match self { Self::Settled => crate::effects::DelegationSettlement::Settled, - Self::Prepared | Self::Creating | Self::SessionBound | Self::PromptIntent => { - crate::effects::DelegationSettlement::Indeterminate - } + Self::Prepared + | Self::Creating + | Self::SessionBound + | Self::Restoring + | Self::PromptIntent => crate::effects::DelegationSettlement::Indeterminate, } } } @@ -2677,6 +3052,9 @@ fn known_code(code: &str) -> Option<&'static str> { "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", diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs index dea2c75..dc0b1fd 100644 --- a/tests/acp_delegation_policy_tests.rs +++ b/tests/acp_delegation_policy_tests.rs @@ -15,15 +15,15 @@ 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::store::GatewayPersistence; -use rustscript_agent::runtime::rss_runner::RunCancellation; use rustscript_agent::service::AgentService; use rustscript_agent::service::acp_session_pins::{ - AcpApprovalWitness, AcpDelegationPolicy, AcpDelegationRequest, AcpDelegationScope, - AcpDelegationStatus, + AcpApprovalWitness, AcpDelegationPolicy, AcpDelegationRequest, AcpDelegationResult, + AcpDelegationScope, AcpDelegationStatus, }; use rustscript_agent::{AdmitRunRequest, AdmittedRun, CancellationReason}; use serde_json::{Value, json}; @@ -347,7 +347,6 @@ fn scope(run: &AdmittedRun, call_id: &str) -> AcpDelegationScope { run_id: run.run_id.clone(), session_id: run.session_id.clone(), tool_call_id: call_id.to_string(), - run_deadline_ms: None, } } @@ -372,6 +371,18 @@ fn pin_document(persistence: &GatewayPersistence, session_id: &str) -> Value { .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() { @@ -411,7 +422,6 @@ async fn default_config_installs_no_policy_and_unknown_ids_never_spawn() { &scope(&run, "call-1"), &request("missing", "task"), &AcpApprovalWitness::new("approval"), - &RunCancellation::new(), ) .await; assert_eq!(unknown.status, AcpDelegationStatus::Denied); @@ -436,7 +446,6 @@ async fn unapproved_denied_and_unbound_calls_never_spawn() { &pending_scope, &request("fixture", "pending task"), &AcpApprovalWitness::new(challenge.approval_id.clone()), - &RunCancellation::new(), ) .await; assert_eq!(pending.status, AcpDelegationStatus::Denied); @@ -473,13 +482,12 @@ async fn unapproved_denied_and_unbound_calls_never_spawn() { &denied_scope, &request("fixture", "denied task"), &AcpApprovalWitness::new(challenge.approval_id), - &RunCancellation::new(), ) .await; assert_eq!(denied.status, AcpDelegationStatus::Denied); assert_eq!(denied.code, Some("acp_approval_mismatch")); - // A session without an admitted workspace can neither ask nor launch. + // An unknown run has no authoritative facts and can neither ask nor launch. let persistence = runtime.persistence(); persistence .session_create(&json!({ @@ -505,7 +513,6 @@ async fn unapproved_denied_and_unbound_calls_never_spawn() { run_id: "run-unbound".to_string(), session_id: "session-unbound".to_string(), tool_call_id: "call-unbound".to_string(), - run_deadline_ms: None, }; let refusal = runtime .policy @@ -513,11 +520,10 @@ async fn unapproved_denied_and_unbound_calls_never_spawn() { &unbound_scope, &request("fixture", "x"), &AcpApprovalWitness::new("approval"), - &RunCancellation::new(), ) .await; assert_eq!(refusal.status, AcpDelegationStatus::Denied); - assert_eq!(refusal.code, Some("acp_workspace_unbound")); + assert_eq!(refusal.code, Some("acp_run_inactive")); assert_eq!(env.spawn_count(), 0, "refusals must not spawn"); } @@ -572,12 +578,7 @@ async fn first_call_creates_and_later_calls_restore_the_same_session() { .await; let first = runtime .policy - .delegate( - &first_scope, - &request("fixture", "first"), - &first_witness, - &RunCancellation::new(), - ) + .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"); @@ -607,7 +608,6 @@ async fn first_call_creates_and_later_calls_restore_the_same_session() { &second_scope, &request("fixture", "second"), &second_witness, - &RunCancellation::new(), ) .await; assert_eq!(second.status, AcpDelegationStatus::Completed, "{second:?}"); @@ -637,12 +637,7 @@ async fn settled_call_replays_only_the_identical_request_without_spawning() { .await; let first = runtime .policy - .delegate( - &call_scope, - &request("fixture", "once"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "once"), &witness) .await; assert_eq!(first.status, AcpDelegationStatus::Completed); assert_eq!( @@ -664,12 +659,7 @@ async fn settled_call_replays_only_the_identical_request_without_spawning() { let spawns = env.spawn_count(); let replay = runtime .policy - .delegate( - &call_scope, - &request("fixture", "once"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "once"), &witness) .await; assert!(replay.replayed); assert_eq!(replay.status, first.status); @@ -679,12 +669,7 @@ async fn settled_call_replays_only_the_identical_request_without_spawning() { // re-executed under the old call identity. let mismatch = runtime .policy - .delegate( - &call_scope, - &request("fixture", "different"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "different"), &witness) .await; assert_eq!(mismatch.status, AcpDelegationStatus::Denied); assert_eq!(mismatch.code, Some("acp_call_mismatch")); @@ -709,12 +694,7 @@ async fn gateway_restart_restores_the_durable_binding() { .await; let result = runtime .policy - .delegate( - &call_scope, - &request("fixture", "before"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "before"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Completed); } @@ -728,12 +708,7 @@ async fn gateway_restart_restores_the_durable_binding() { .await; let result = runtime .policy - .delegate( - &call_scope, - &request("fixture", "after"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "after"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); assert_eq!(result.text, "ctx=1;reply=policy-reply"); @@ -752,12 +727,7 @@ async fn restore_failure_never_creates_a_new_session() { .await; runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .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"); @@ -769,12 +739,7 @@ async fn restore_failure_never_creates_a_new_session() { .await; let result = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Failed); assert_eq!(result.code, Some("acp_session_restore_failed")); @@ -793,12 +758,7 @@ async fn missing_restore_capability_reports_unsupported_without_new_session() { .await; runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; env.set_caps("none"); runtime.finish(&first_run).await; @@ -809,12 +769,7 @@ async fn missing_restore_capability_reports_unsupported_without_new_session() { .await; let result = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Failed); assert_eq!(result.code, Some("acp_session_restore_unsupported")); @@ -832,12 +787,7 @@ async fn load_only_restore_uses_load_and_never_mixes_replayed_text() { .await; runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; env.set_caps("load"); runtime.finish(&first_run).await; @@ -848,12 +798,7 @@ async fn load_only_restore_uses_load_and_never_mixes_replayed_text() { .await; let result = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); assert_eq!(result.text, "ctx=1;reply=policy-reply"); @@ -873,12 +818,7 @@ async fn workspace_change_refuses_the_old_binding() { .await; runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; runtime.finish(&first_run).await; @@ -915,12 +855,7 @@ async fn workspace_change_refuses_the_old_binding() { .await; let result = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Denied); assert_eq!(result.code, Some("acp_binding_mismatch")); @@ -938,12 +873,7 @@ async fn approval_is_bound_to_the_exact_task_and_pin_version() { .await; let stale = runtime .policy - .delegate( - &call_scope, - &request("fixture", "different task"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "different task"), &witness) .await; assert_eq!(stale.status, AcpDelegationStatus::Denied); assert_eq!(stale.code, Some("acp_approval_stale")); @@ -951,18 +881,115 @@ async fn approval_is_bound_to_the_exact_task_and_pin_version() { } #[tokio::test] -async fn automatic_reviewer_cannot_create_a_manual_approval() { - let env = Env::new("auto-approval"); +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 refusal = runtime + 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 - .request_approval(&call_scope, &request("fixture", "task")) - .await - .expect_err("an automatic reviewer run must not create a manual row"); - assert_eq!(refusal.code(), "acp_human_review_required"); - assert_eq!(env.spawn_count(), 0); + .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")] @@ -982,12 +1009,7 @@ async fn prepared_call_is_indeterminate_and_never_restarted() { .arm_fault(AcpPolicyFault::AfterPrepareBeforeSpawn); let cut = runtime .policy - .delegate( - &call_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "a"), &witness) .await; assert_eq!(cut.status, AcpDelegationStatus::Failed); assert_eq!(cut.code, Some("acp_session_indeterminate")); @@ -1033,12 +1055,7 @@ async fn crash_after_session_create_is_indeterminate_and_never_recreated() { runtime.policy.arm_fault(AcpPolicyFault::AfterSessionCreate); let cut = runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; assert_eq!(cut.status, AcpDelegationStatus::Failed); assert_eq!(cut.code, Some("acp_session_indeterminate")); @@ -1068,12 +1085,7 @@ async fn crash_after_session_create_is_indeterminate_and_never_recreated() { .await; let blocked = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!(blocked.status, AcpDelegationStatus::Failed); assert_eq!(blocked.code, Some("acp_session_indeterminate")); @@ -1103,12 +1115,7 @@ async fn crash_after_id_persisted_blocks_the_old_call_but_allows_a_new_one() { let session_id = run.session_id.clone(); let cut = runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .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. @@ -1126,12 +1133,7 @@ async fn crash_after_id_persisted_blocks_the_old_call_but_allows_a_new_one() { let spawns = env.spawn_count(); let restart = runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; assert_eq!(restart.status, AcpDelegationStatus::Denied); assert_eq!(restart.code, Some("acp_call_indeterminate")); @@ -1144,12 +1146,7 @@ async fn crash_after_id_persisted_blocks_the_old_call_but_allows_a_new_one() { .await; let resumed = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!( resumed.status, @@ -1178,12 +1175,7 @@ async fn crash_after_prompt_publication_blocks_the_binding() { let session_id = run.session_id.clone(); let cut = runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; assert_eq!(cut.status, AcpDelegationStatus::Failed); drop(runtime); @@ -1205,12 +1197,7 @@ async fn crash_after_prompt_publication_blocks_the_binding() { .await; let blocked = runtime .policy - .delegate( - &second_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &witness) .await; assert_eq!(blocked.status, AcpDelegationStatus::Failed); assert_eq!(blocked.code, Some("acp_session_indeterminate")); @@ -1242,23 +1229,13 @@ async fn concurrent_calls_on_one_pin_have_one_winner() { let policy = runtime.policy.clone(); let first = tokio::spawn(async move { policy - .delegate( - &first_scope, - &request("fixture", "a"), - &first_witness, - &RunCancellation::new(), - ) + .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, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("fixture", "b"), &second_witness) .await; assert_eq!(second.status, AcpDelegationStatus::Busy, "{second:?}"); assert_eq!(second.code, Some("acp_delegation_busy")); @@ -1291,23 +1268,13 @@ async fn two_harnesses_in_one_session_keep_both_pin_updates() { let policy = runtime.policy.clone(); let first = tokio::spawn(async move { policy - .delegate( - &first_scope, - &request("fixture", "a"), - &first_witness, - &RunCancellation::new(), - ) + .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, - &RunCancellation::new(), - ) + .delegate(&second_scope, &request("other", "b"), &second_witness) .await; assert_eq!(second.status, AcpDelegationStatus::Completed, "{second:?}"); assert_eq!( @@ -1340,12 +1307,7 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { let policy = runtime.policy.clone(); let first = tokio::spawn(async move { policy - .delegate( - &first_scope, - &request("fixture", "a"), - &first_witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &first_witness) .await }); wait_for(|| env.spawn_count() == 1, "first spawn").await; @@ -1356,12 +1318,7 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { .await; let same_run = runtime .policy - .delegate( - &same_run_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .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")); @@ -1377,12 +1334,7 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { let policy = runtime.policy.clone(); handles.push(tokio::spawn(async move { policy - .delegate( - &call_scope, - &request("fixture", "fill"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "fill"), &witness) .await })); } @@ -1399,12 +1351,7 @@ async fn per_run_gate_and_service_quota_refuse_instead_of_queueing() { .await; let overflow = runtime .policy - .delegate( - &overflow_scope, - &request("fixture", "overflow"), - &witness, - &RunCancellation::new(), - ) + .delegate(&overflow_scope, &request("fixture", "overflow"), &witness) .await; assert_eq!(overflow.status, AcpDelegationStatus::Busy); assert_eq!(overflow.code, Some("acp_delegation_capacity")); @@ -1431,12 +1378,7 @@ async fn session_delete_clears_the_local_binding() { .await; runtime .policy - .delegate( - &first_scope, - &request("fixture", "a"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "a"), &witness) .await; runtime.finish(&first_run).await; runtime @@ -1452,12 +1394,7 @@ async fn session_delete_clears_the_local_binding() { .await; let result = runtime .policy - .delegate( - &new_scope, - &request("fixture", "b"), - &witness, - &RunCancellation::new(), - ) + .delegate(&new_scope, &request("fixture", "b"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Completed); assert_eq!( @@ -1482,12 +1419,7 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { runtime.policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); let result = runtime .policy - .delegate( - &call_scope, - &request("fixture", "task"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "task"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Indeterminate); assert_eq!(result.code, Some("acp_cleanup_unverified")); @@ -1509,8 +1441,9 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { let persistence = runtime.persistence(); let doc = pin_document(&persistence, &run.session_id); - assert_eq!(doc["pins"]["fixture"]["phase"], "unknown"); - assert!(doc["pins"]["fixture"]["active"].is_null()); + 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 @@ -1524,12 +1457,7 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { let spawns = env.spawn_count(); let replay = runtime .policy - .delegate( - &call_scope, - &request("fixture", "task"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "task"), &witness) .await; assert!(replay.replayed); assert_eq!(replay.status, AcpDelegationStatus::Indeterminate); @@ -1544,12 +1472,7 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { .await; let next = runtime .policy - .delegate( - &next_scope, - &request("fixture", "next"), - &witness, - &RunCancellation::new(), - ) + .delegate(&next_scope, &request("fixture", "next"), &witness) .await; assert_eq!(next.status, AcpDelegationStatus::Failed); assert_eq!(next.code, Some("acp_session_indeterminate")); @@ -1573,12 +1496,7 @@ async fn lost_cleanup_observer_keeps_capacity() { .arm_fault(AcpPolicyFault::CleanupObserverLost); let result = runtime .policy - .delegate( - &call_scope, - &request("fixture", "task"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "task"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Indeterminate); assert_eq!(result.code, Some("acp_cleanup_unverified")); @@ -1586,77 +1504,6 @@ async fn lost_cleanup_observer_keeps_capacity() { assert_eq!(runtime.policy.quarantined_slots(), 1); } -#[cfg(feature = "workspace-io-fault")] -#[tokio::test] -async fn confirmed_deferred_cleanup_releases_once_without_turning_it_into_success() { - use rustscript_agent::service::acp_session_pins::AcpPolicyFault; - - let env = Env::new("cleanup-confirmed"); - 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::DeferredCleanupConfirmed); - let result = runtime - .policy - .delegate( - &call_scope, - &request("fixture", "task"), - &witness, - &RunCancellation::new(), - ) - .await; - assert_eq!(result.status, AcpDelegationStatus::Indeterminate); - assert_eq!(result.code, Some("acp_prompt_unsettled")); - // Positive control: the proven cleanup releases the slot exactly once. - assert_eq!(runtime.policy.available_processes(), 4); - assert_eq!(runtime.policy.quarantined_slots(), 0); - - let persistence = runtime.persistence(); - let doc = pin_document(&persistence, &run.session_id); - assert_eq!( - doc["pins"]["fixture"]["phase"], "unknown", - "a prompt intent without settlement must never turn back into bound" - ); - assert!(doc["pins"]["fixture"]["active"].is_null()); - assert_eq!(doc["calls"]["call-1"]["phase"], "settled"); - assert_eq!(doc["calls"]["call-1"]["outcome"]["status"], "indeterminate"); - - let replay = runtime - .policy - .delegate( - &call_scope, - &request("fixture", "task"), - &witness, - &RunCancellation::new(), - ) - .await; - assert!(replay.replayed); - assert_eq!(replay.status, AcpDelegationStatus::Indeterminate); - assert_eq!(runtime.policy.available_processes(), 4, "released once"); - - // The pin is indeterminate: no later call may take it over. - let next_scope = scope(&run, "call-2"); - let witness = runtime - .approve(&run, &next_scope, &request("fixture", "next")) - .await; - let next = runtime - .policy - .delegate( - &next_scope, - &request("fixture", "next"), - &witness, - &RunCancellation::new(), - ) - .await; - assert_eq!(next.status, AcpDelegationStatus::Failed); - assert_eq!(next.code, Some("acp_session_indeterminate")); -} - #[cfg(feature = "workspace-io-fault")] #[tokio::test] async fn stale_settlement_never_clears_a_newer_owner() { @@ -1672,12 +1519,7 @@ async fn stale_settlement_never_clears_a_newer_owner() { runtime.policy.arm_fault(AcpPolicyFault::CleanupUnconfirmed); runtime .policy - .delegate( - &call_scope, - &request("fixture", "task"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "task"), &witness) .await; let persistence = runtime.persistence(); let before = pin_document(&persistence, &run.session_id); @@ -1687,7 +1529,7 @@ async fn stale_settlement_never_clears_a_newer_owner() { .await; let after = pin_document(&persistence, &run.session_id); assert_eq!(before, after); - assert_eq!(after["pins"]["fixture"]["phase"], "unknown"); + assert_eq!(after["pins"]["fixture"]["phase"], "cleanup_pending"); } #[tokio::test] @@ -1699,16 +1541,15 @@ async fn cancelled_before_spawn_creates_no_process() { let witness = runtime .approve(&run, &call_scope, &request("fixture", "task")) .await; - let cancellation = RunCancellation::new(); - cancellation.request(CancellationReason::Requested); + 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, - &cancellation, - ) + .delegate(&call_scope, &request("fixture", "task"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Denied); assert_eq!(result.code, Some("acp_delegation_cancelled")); @@ -1725,19 +1566,18 @@ async fn cancellation_after_prepare_but_before_spawn_is_zero_spawn() { let witness = runtime .approve(&run, &call_scope, &request("fixture", "task")) .await; - let cancellation = RunCancellation::new(); - let signal = cancellation.clone(); + 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, - &cancellation, - ) + .delegate(&call_scope, &request("fixture", "task"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Cancelled); assert_eq!(result.code, Some("acp_delegation_cancelled")); @@ -1760,20 +1600,19 @@ async fn cancellation_during_setup_closes_without_prompting() { let witness = runtime .approve(&run, &call_scope, &request("fixture", "task")) .await; - let cancellation = RunCancellation::new(); - let signal = cancellation.clone(); + 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, - &cancellation, - ) + .delegate(&scope_for_task, &request_for_task, &witness_for_task) .await }); wait_for(|| env.spawn_count() == 1, "the setup harness to spawn").await; @@ -1804,14 +1643,18 @@ async fn cancellation_after_prompt_is_observable_and_never_reports_success() { let witness = runtime .approve(&run, &call_scope, &request("fixture", "task")) .await; - let cancellation = RunCancellation::new(); - let signal = cancellation.clone(); + 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, &cancellation) + .delegate(&scope_for_task, &request_for_task, &witness) .await }); wait_for( @@ -2007,12 +1850,7 @@ async fn result_envelope_obeys_the_run_output_budget_with_utf8_truncation() { .await; let result = runtime .policy - .delegate( - &call_scope, - &request("fixture", "budget"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "budget"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Completed, "{result:?}"); assert!(result.truncated, "the text must be truncated"); @@ -2044,12 +1882,7 @@ async fn cancellation_during_restore_closes_without_prompting() { .await; let first = runtime .policy - .delegate( - &first_scope, - &request("fixture", "first"), - &witness, - &RunCancellation::new(), - ) + .delegate(&first_scope, &request("fixture", "first"), &witness) .await; assert_eq!(first.status, AcpDelegationStatus::Completed); runtime.finish(&first_run).await; @@ -2059,14 +1892,18 @@ async fn cancellation_during_restore_closes_without_prompting() { let witness = runtime .approve(&second_run, &second_scope, &request("fixture", "second")) .await; - let cancellation = RunCancellation::new(); - let signal = cancellation.clone(); + 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, &cancellation) + .delegate(&scope_for_task, &request_for_task, &witness) .await }); wait_for( @@ -2107,12 +1944,7 @@ async fn real_cleanup_observer_settles_the_lost_prompt_once() { runtime.policy.arm_fault(AcpPolicyFault::DeferToObserver); let result = runtime .policy - .delegate( - &call_scope, - &request("fixture", "observed"), - &witness, - &RunCancellation::new(), - ) + .delegate(&call_scope, &request("fixture", "observed"), &witness) .await; assert_eq!(result.status, AcpDelegationStatus::Indeterminate); assert_eq!(result.code, Some("acp_cleanup_unconfirmed")); @@ -2145,3 +1977,509 @@ async fn real_cleanup_observer_settles_the_lost_prompt_once() { 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; + let service = runtime.service.clone(); + let run_id = run.run_id.clone(); + runtime.policy.arm_pre_spawn_hook(move || { + service.set_context_deadline_at_ms(&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. + 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(), + 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 + ); +} From cd676c075338ad1fd1d53fd6ec6078aa75464add Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 13:47:09 +0800 Subject: [PATCH 14/27] Fix ACP gateway harness source selection and startup reclamation - Boot each child through the production with_agent_selection_and_compaction path with the gateway's default home selection request, and assert that both real health responses report source.kind == bundled. - Hand the spawned Child to an owning guard immediately so every startup failure kills and reaps the exact process instead of orphaning it. - Add a startup-failure control covering live-but-unready children and invalid readiness, plus a distinct run_id assertion on restart. --- tests/acp_delegation_e2e_tests.rs | 548 +++++++++++++++++++++++++----- 1 file changed, 462 insertions(+), 86 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index e906305..933fa48 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -19,16 +19,17 @@ use std::fs; use std::io::{BufRead, BufReader, Write}; use std::net::SocketAddr; use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Stdio}; +use std::process::{Child, Command, ExitStatus, Stdio}; use std::str::FromStr; use std::sync::Mutex; use std::time::{Duration, Instant}; use axum::serve; use rustscript_agent::config::ProviderProfile; +use rustscript_agent::config_file::{AgentPaths, ConfigFileError}; use rustscript_agent::{ - AgentGatewayConfig, AgentGatewayState, AgentProviderHost, RunCancellation, ScriptedProvider, - build_agent_gateway_app, + AgentGatewayConfig, AgentGatewayState, AgentProviderHost, ConfigFile, RunCancellation, + ScriptedProvider, build_agent_gateway_app, }; use serde_json::{Value, json}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -47,6 +48,9 @@ const READY_BUDGET: Duration = Duration::from_secs(300); const RUN_BUDGET: Duration = Duration::from_secs(120); const HTTP_BUDGET: Duration = Duration::from_secs(240); const REAP_BUDGET: Duration = Duration::from_secs(30); +// 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") @@ -153,91 +157,300 @@ impl Drop for GatewayFixture { } } +/// 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 kills and waits for the exact process instead of +/// leaving an orphan Gateway holding its listener. +struct ChildGuard { + child: Option, + reaped: bool, +} + +impl ChildGuard { + fn new(child: Child) -> Self { + Self { + child: Some(child), + reaped: false, + } + } + + fn pid(&self) -> u32 { + self.child.as_ref().expect("owned child handle").id() + } + + fn stdin_mut(&mut self) -> &mut std::process::ChildStdin { + self.child + .as_mut() + .expect("owned child handle") + .stdin + .as_mut() + .expect("child stdin") + } + + fn take_stdin(&mut self) -> Option { + self.child + .as_mut() + .expect("owned child handle") + .stdin + .take() + } + + /// Polls without taking ownership; an observed exit was already reaped by + /// `try_wait`, so the guard must never signal that pid again. + fn try_wait(&mut self) -> std::io::Result> { + let status = self + .child + .as_mut() + .expect("owned child handle") + .try_wait()?; + if status.is_some() { + self.reaped = true; + } + Ok(status) + } + + fn is_running(&mut self) -> bool { + matches!(self.try_wait(), Ok(None)) + } + + /// Kills and waits for the exact owned child, returning its terminal + /// status. `None` means it had already exited and been reaped. + fn terminate(&mut self) -> Option { + let mut child = self.child.take()?; + if self.reaped { + return None; + } + let _ = child.kill(); + let status = child.wait().ok(); + self.reaped = true; + status + } +} + +impl Drop for ChildGuard { + fn drop(&mut self) { + if !self.reaped { + let _ = self.terminate(); + } + } +} + +/// 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, + stdout_path: PathBuf, + stderr_path: PathBuf, +} + +fn spawn_harness_child( + fixture: &GatewayFixture, + label: &str, + db_path: &Path, + ready_path: &Path, + responses: &[Value], + hold_before_ready_ms: u64, +) -> HarnessChild { + let transcript_path = fixture.root.join(format!("transcript-{label}.jsonl")); + 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(), + "transcript_path": transcript_path.to_string_lossy(), + "responses": responses, + "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 stdout_path = fixture.root.join(format!("stdout-{label}.log")); + let stderr_path = fixture.root.join(format!("stderr-{label}.log")); + let stdout = fs::File::create(&stdout_path).expect("create child stdout 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::from(stdout)) + .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. + HarnessChild { + guard: ChildGuard::new(child), + token, + ready_path: ready_path.to_path_buf(), + stdout_path, + stderr_path, + } +} + +/// A startup that never produced a usable listener. The guard is returned to +/// the caller so the exact child is inspected and reclaimed by the parent. +struct StartFailure { + reason: String, + pid: u32, + status: Option, + ready_path: PathBuf, + stderr_path: PathBuf, + guard: ChildGuard, +} + +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: Child, + child: ChildGuard, address: SocketAddr, token: String, stdout_path: PathBuf, stderr_path: PathBuf, - reaped: bool, +} + +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, responses: &[Value]) -> Self { let ready_path = fixture.root.join(format!("ready-{label}.json")); - let transcript_path = fixture.root.join(format!("transcript-{label}.jsonl")); - let spec_path = fixture.root.join(format!("spec-{label}.json")); - fs::write( - &spec_path, - json!({ - "db_path": fixture.db_path.to_string_lossy(), - "workspace_home": fixture.home.to_string_lossy(), - "ready_path": ready_path.to_string_lossy(), - "transcript_path": transcript_path.to_string_lossy(), - "responses": responses, - "run_timeout_ms": RUN_BUDGET.as_millis() as u64, - }) - .to_string(), - ) - .expect("write child Gateway spec"); - - let token = format!("rss-acp-e2e-{}", uuid::Uuid::new_v4().simple()); - let stdout_path = fixture.root.join(format!("stdout-{label}.log")); - let stderr_path = fixture.root.join(format!("stderr-{label}.log")); - let stdout = fs::File::create(&stdout_path).expect("create child stdout 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::from(stdout)) - .stderr(Stdio::from(stderr)); - let mut child = command.spawn().expect("Gateway harness child must spawn"); + match Self::start_with_budget_at( + fixture, + label, + responses, + ready_path, + fixture.db_path.clone(), + READY_BUDGET, + 0, + ) { + Ok(process) => process, + Err(failure) => panic!("{failure}"), + } + } - let deadline = Instant::now() + READY_BUDGET; + /// Bounded readiness wait used by the ordinary tests and by the startup + /// failure control. The returned guard always owns the exact child; on + /// failure the caller can inspect and reclaim it instead of losing it to + /// a panic. + fn start_with_budget_at( + fixture: &GatewayFixture, + label: &str, + responses: &[Value], + 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, + responses, + hold_before_ready_ms, + ); + let HarnessChild { + mut guard, + token, + ready_path, + stdout_path, + stderr_path, + } = launch; + let pid = guard.pid(); + let deadline = Instant::now() + budget; loop { - if let Ok(Some(status)) = child.try_wait() { - panic!( - "Gateway harness child exited before readiness ({status}): {}", - fs::read_to_string(&stderr_path).unwrap_or_default() - ); + 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, + }); + } + Ok(None) => {} + Err(error) => { + return Err(StartFailure { + reason: format!("could not poll the child: {error}"), + pid, + status: None, + ready_path, + stderr_path, + 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) { - let address = SocketAddr::from_str(address).expect("child listener address"); - return Self { - child, + return Ok(Self { + child: guard, address, token, stdout_path, stderr_path, - reaped: false, - }; + }); + } + if Instant::now() >= deadline { + return Err(StartFailure { + reason: format!("published no usable readiness within {budget:?}"), + pid, + status: None, + ready_path, + stderr_path, + guard, + }); } - assert!( - Instant::now() < deadline, - "Gateway harness child did not become ready: {}", - fs::read_to_string(&stderr_path).unwrap_or_default() - ); std::thread::sleep(Duration::from_millis(25)); } } @@ -361,11 +574,11 @@ impl GatewayProcess { /// and an explicit proof that the process is gone and its listener closed. fn stop_and_reap(mut self) { { - let stdin = self.child.stdin.as_mut().expect("child stdin"); + let stdin = self.child.stdin_mut(); writeln!(stdin, "shutdown").expect("send shutdown to the Gateway harness"); stdin.flush().expect("flush shutdown"); } - drop(self.child.stdin.take()); + drop(self.child.take_stdin()); let deadline = Instant::now() + REAP_BUDGET; loop { @@ -389,7 +602,6 @@ impl GatewayProcess { } } } - self.reaped = true; let listener_deadline = Instant::now() + Duration::from_secs(5); loop { @@ -409,16 +621,6 @@ impl GatewayProcess { } } -impl Drop for GatewayProcess { - fn drop(&mut self) { - if !self.reaped { - let _ = self.child.kill(); - let _ = self.child.wait(); - self.reaped = true; - } - } -} - fn transcript_requests(fixture: &GatewayFixture, label: &str) -> Vec { let path = fixture.root.join(format!("transcript-{label}.jsonl")); let file = fs::File::open(&path).expect("provider transcript must exist"); @@ -503,18 +705,52 @@ async fn gateway_harness_child_entry() { .as_str() .expect("child transcript path"); 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 config = AgentGatewayConfig { bearer_token: Some(token), run_timeout: Duration::from_millis(run_timeout_ms), ..AgentGatewayConfig::default() }; - let state = AgentGatewayState::with_agent_file_and_sqlite( + // 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"), + }; + 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, - rustscript_agent::bundled_agent_main_path(), - db_path, + Value::Object(selection), + Some(Path::new(db_path)), + compaction_settings, ) - .expect("bundled RSS agent must compile against the durable store") + .expect("the production bundled RSS selection must compile against the durable store") .with_workspace_home(workspace_home); state .service() @@ -533,6 +769,9 @@ async fn gateway_harness_child_entry() { fs::File::create(transcript_path).expect("create provider transcript"), ), }; + // This provider override is one-shot per process: a future test that runs + // two main-model turns in one Gateway process must supply a new host + // instead of assuming this injected one is reused. state .service() .inject_provider_host(std::sync::Arc::new(recorder)); @@ -541,6 +780,9 @@ async fn gateway_harness_child_entry() { .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(), @@ -581,11 +823,11 @@ async fn gateway_harness_child_entry() { .await .expect("real Gateway router must serve until shutdown"); - // The production SIGINT path: stop admission, wake the idle janitor, then - // join the owned service/storage workers before the process exits. The - // terminal event is observable slightly before the run worker drops its - // occupancy, so a bounded retry waits out that hand-off instead of racing - // the production shutdown contract. + // 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 { @@ -615,6 +857,7 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { 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; @@ -668,6 +911,7 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { let second = GatewayProcess::start(&fixture, "second", &[text_response(SECOND_ANSWER_MARKER)]); 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) @@ -685,6 +929,10 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { let second_prompt = format!("{SECOND_PROMPT_MARKER}: continue from the durable session."); let second_run = admit_run(&second, &session_id, &second_prompt).await; + assert_ne!( + first_run, second_run, + "the restarted Gateway must admit a distinct real run id" + ); let second_events = second.await_event(&second_run, "run.completed").await; assert!( second_events.contains(SECOND_ANSWER_MARKER), @@ -750,6 +998,134 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { second.stop_and_reap(); } +/// Startup failure control: a real child that never publishes usable +/// readiness must still be killed and reaped by its owner. The parent does +/// not close stdin, does not wait for the child to exit on its own, and does +/// not treat a temp file as reclamation evidence: it inspects the exact pid, +/// kills it through the owning guard, and waits until that pid disappears. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn gateway_startup_failure_reclaims_the_real_child() { + let fixture = GatewayFixture::new("startup-failure"); + let pid_marker = lease_tmp().join("acp-delegation-negative-control-child.pid"); + + // ---- Case 1: live child, no readiness published. ---- + // + // The child is still before readiness: it is either compiling the + // embedded bundled entry or holding after binding its real listener. In + // both positions no stdin control thread exists yet, so closing stdin + // could not stop it; the hold outlives the short observation clock and + // keeps the live-but-unready window deterministic. Only owner + // reclamation proves the exact process is gone. + let blocked_ready = fixture.root.join("ready-blocked.json"); + let observe = Duration::from_secs(5); + let started = Instant::now(); + let mut failure = GatewayProcess::start_with_budget_at( + &fixture, + "blocked", + &[], + blocked_ready.clone(), + fixture.db_path.clone(), + observe, + 120_000, + ) + .expect_err("a child that never publishes readiness must not be admitted"); + assert!( + started.elapsed() >= observe, + "the observation clock must actually elapse before startup is rejected" + ); + // Persist the exact pid before any assertion so an outer negative-control + // run can reclaim a child abandoned by a regressed owner. + fs::write(&pid_marker, failure.pid.to_string()).expect("record the exact child pid"); + assert_eq!( + failure.status, None, + "the blocked child must still be alive at the observation deadline" + ); + assert!( + failure.guard.is_running(), + "the blocked child must be running when the parent reclaims it" + ); + let killed = failure + .guard + .terminate() + .expect("the owning parent must observe the blocked child's exit"); + assert!( + !killed.success(), + "a blocked child must not report success after owner reclamation: {killed}" + ); + assert!( + !Path::new(&format!("/proc/{}", failure.pid)).exists(), + "the exact child pid {} must be gone after the parent waited for it", + failure.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 exit and reaps it. + 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"); + 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" + ); +} + +/// `/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!( From e8d890f9aebd223112377453c694f989f488a5a4 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 14:33:23 +0800 Subject: [PATCH 15/27] Bound ACP harness child reclamation and drive the startup-failure Drop path - Replace the unbounded kill/wait (which dropped the kill error and marked the child reaped even when wait failed) with one absolute 5 s reclamation window: finite try_wait observation of the exact owned child, EINTR treated as retryable, and the guard marked reaped only after a real terminal state was observed and the process reaped. Failures keep the handle and report the signal/poll reason instead of pretending success. - Share that single window between the startup timeout and the normal stop timeout, and share one per-guard deadline between explicit calls and Drop so reclamation windows never stack. - Exercise the real negative control through the ordinary GatewayProcess::start failure wrapper: the child is alive and unready when the short observation clock expires, only ChildGuard::drop reclaims it during unwinding, and a spawn identity witness plus /proc proves the exact pid was reaped inside the total budget. An identity-checked outer reclaimer only acts if the owner regression leaked the child. The finite-deadline and EINTR error paths use a test double; both real-child cases remain. --- tests/acp_delegation_e2e_tests.rs | 562 ++++++++++++++++++++++++------ 1 file changed, 457 insertions(+), 105 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index 933fa48..d4e50c5 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -48,6 +48,13 @@ const READY_BUDGET: Duration = Duration::from_secs(300); const RUN_BUDGET: Duration = Duration::from_secs(120); const HTTP_BUDGET: Duration = Duration::from_secs(240); const REAP_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. +const RECLAIM_BUDGET: Duration = Duration::from_secs(5); +const RECLAIM_POLL: Duration = Duration::from_millis(25); + // 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. @@ -159,78 +166,301 @@ impl Drop for GatewayFixture { /// 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 kills and waits for the exact process instead of -/// leaving an orphan Gateway holding its listener. +/// 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: Option, - reaped: bool, + child: Child, + pid: u32, + reaped: Option, + /// One absolute cleanup deadline per guard: an explicit reclamation and a + /// later `Drop` fallback share it instead of stacking fresh windows. + cleanup_deadline: Option, } impl ChildGuard { fn new(child: Child) -> Self { Self { - child: Some(child), - reaped: false, + pid: child.id(), + child, + reaped: None, + cleanup_deadline: None, } } fn pid(&self) -> u32 { - self.child.as_ref().expect("owned child handle").id() + self.pid } fn stdin_mut(&mut self) -> &mut std::process::ChildStdin { - self.child - .as_mut() - .expect("owned child handle") - .stdin - .as_mut() - .expect("child stdin") + self.child.stdin.as_mut().expect("child stdin") } fn take_stdin(&mut self) -> Option { - self.child - .as_mut() - .expect("owned child handle") - .stdin - .take() + self.child.stdin.take() } - /// Polls without taking ownership; an observed exit was already reaped by - /// `try_wait`, so the guard must never signal that pid again. + /// 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> { - let status = self - .child - .as_mut() - .expect("owned child handle") - .try_wait()?; - if status.is_some() { - self.reaped = true; + 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) } - fn is_running(&mut self) -> bool { - matches!(self.try_wait(), Ok(None)) + /// 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. + 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 deadline = *self + .cleanup_deadline + .get_or_insert_with(|| Instant::now() + RECLAIM_BUDGET); + let signal_error = self.child.kill().err(); + let status = match reclaim_until_terminal(pid, deadline, || self.child.try_wait()) { + Ok(status) => status, + Err(mut error) => { + error.signal_error = signal_error; + return Err(error); + } + }; + self.reaped = Some(status); + Ok(Reclaim::Signalled { + status, + signal_error, + }) } +} - /// Kills and waits for the exact owned child, returning its terminal - /// status. `None` means it had already exited and been reaped. - fn terminate(&mut self) -> Option { - let mut child = self.child.take()?; - if self.reaped { - return None; +/// 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, + }); } - let _ = child.kill(); - let status = child.wait().ok(); - self.reaped = true; - status + std::thread::sleep(RECLAIM_POLL.min(deadline - now)); } } impl Drop for ChildGuard { fn drop(&mut self) { - if !self.reaped { - let _ = self.terminate(); + if self.reaped.is_some() { + return; + } + if let Err(error) = self.terminate() { + // Never panic while unwinding, and never mark an unreclaimed child + // as reaped: the bounded failure is reported instead. + eprintln!("harness child was not reclaimed: {error}"); + } + } +} + +/// 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 { + 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 start_time = rest.split_whitespace().nth(19)?.parse().ok()?; + Some(Self { 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()?, + }) + } + + /// True only while `/proc` still shows this exact process as our direct + /// child with the start time captured at spawn. + fn still_exact(&self) -> bool { + let Ok(stat) = fs::read_to_string(format!("/proc/{}/stat", self.pid)) else { + return false; + }; + let Some((_, rest)) = stat.rsplit_once(')') else { + return false; + }; + let fields: Vec<&str> = rest.split_whitespace().collect(); + if fields.len() < 20 { + return false; + } + let (Ok(ppid), Ok(start_time)) = (fields[1].parse::(), fields[19].parse::()) + else { + return false; + }; + if ppid != std::process::id() || start_time != self.start_time { + return false; + } + // A zombie has already terminated and is the only case where the + // command line is gone; it still has to be awaited, so accept it. + if fields[0] == "Z" { + return true; + } + fs::read(format!("/proc/{}/cmdline", self.pid)) + .map(|cmdline| String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY)) + .unwrap_or(false) + } + + /// Independent outer safety net for the negative control. Only a process + /// still proven to be the exact spawned child may be signalled, and it is + /// waited for as well, so a deliberately disabled owner cannot leak it. + fn reclaim_if_exact(&self) { + if !self.still_exact() { + return; + } + let pid = self.pid as libc::pid_t; + // The identity check above (pid, spawn start time, parent, and child + // entry) is what makes this signal safe; a bare cached pid is not. + unsafe { + libc::kill(pid, libc::SIGKILL); + } + let deadline = Instant::now() + RECLAIM_BUDGET; + loop { + let mut status = 0; + let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) }; + if waited == pid { + return; + } + if waited < 0 + && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted + { + continue; + } + if Instant::now() >= deadline { + return; + } + std::thread::sleep(RECLAIM_POLL); } } } @@ -298,8 +528,17 @@ fn spawn_harness_child( .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: ChildGuard::new(child), + guard, token, ready_path: ready_path.to_path_buf(), stdout_path, @@ -307,15 +546,18 @@ fn spawn_harness_child( } } -/// A startup that never produced a usable listener. The guard is returned to -/// the caller so the exact child is inspected and reclaimed by the parent. +/// 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, - guard: ChildGuard, + /// 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 { @@ -359,6 +601,21 @@ impl std::fmt::Debug for GatewayProcess { impl GatewayProcess { fn start(fixture: &GatewayFixture, label: &str, responses: &[Value]) -> Self { + Self::start_bounded(fixture, label, responses, 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, + responses: &[Value], + 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, @@ -366,8 +623,8 @@ impl GatewayProcess { responses, ready_path, fixture.db_path.clone(), - READY_BUDGET, - 0, + budget, + hold_before_ready_ms, ) { Ok(process) => process, Err(failure) => panic!("{failure}"), @@ -375,9 +632,8 @@ impl GatewayProcess { } /// Bounded readiness wait used by the ordinary tests and by the startup - /// failure control. The returned guard always owns the exact child; on - /// failure the caller can inspect and reclaim it instead of losing it to - /// a panic. + /// 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, @@ -413,10 +669,13 @@ impl GatewayProcess { status: Some(status), ready_path, stderr_path, - guard, + 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}"), @@ -424,7 +683,7 @@ impl GatewayProcess { status: None, ready_path, stderr_path, - guard, + guard: Box::new(guard), }); } } @@ -448,7 +707,7 @@ impl GatewayProcess { status: None, ready_path, stderr_path, - guard, + guard: Box::new(guard), }); } std::thread::sleep(Duration::from_millis(25)); @@ -582,8 +841,8 @@ impl GatewayProcess { let deadline = Instant::now() + REAP_BUDGET; loop { - match self.child.try_wait().expect("poll Gateway harness") { - Some(status) => { + match self.child.try_wait() { + Ok(Some(status)) => { assert!( status.success(), "Gateway harness did not exit cleanly ({status}): {}\n{}", @@ -592,15 +851,26 @@ impl GatewayProcess { ); break; } - None => { - assert!( - Instant::now() < deadline, - "Gateway harness did not stop within {REAP_BUDGET:?}: {}", - self.stderr() - ); - std::thread::sleep(Duration::from_millis(25)); - } + 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); @@ -998,65 +1268,95 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { 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 killed and reaped by its owner. The parent does -/// not close stdin, does not wait for the child to exit on its own, and does -/// not treat a temp file as reclamation evidence: it inspects the exact pid, -/// kills it through the owning guard, and waits until that pid disappears. +/// 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"); - let pid_marker = lease_tmp().join("acp-delegation-negative-control-child.pid"); - // ---- Case 1: live child, no readiness published. ---- + // ---- Case 1: owner-driven reclamation through the startup wrapper. ---- // - // The child is still before readiness: it is either compiling the - // embedded bundled entry or holding after binding its real listener. In - // both positions no stdin control thread exists yet, so closing stdin - // could not stop it; the hold outlives the short observation clock and - // keeps the live-but-unready window deterministic. Only owner - // reclamation proves the exact process is gone. + // 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 mut failure = GatewayProcess::start_with_budget_at( - &fixture, - "blocked", - &[], - blocked_ready.clone(), - fixture.db_path.clone(), - observe, - 120_000, - ) - .expect_err("a child that never publishes readiness must not be admitted"); + 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!( - started.elapsed() >= observe, - "the observation clock must actually elapse before startup is rejected" + failure.contains("published no usable readiness"), + "the observation clock, not an early exit, must reject startup: {failure}" ); - // Persist the exact pid before any assertion so an outer negative-control - // run can reclaim a child abandoned by a regressed owner. - fs::write(&pid_marker, failure.pid.to_string()).expect("record the exact child pid"); - assert_eq!( - failure.status, None, - "the blocked child must still be alive at the observation deadline" + assert!( + failure.contains("still running"), + "the unready child must still be alive at the startup deadline: {failure}" ); assert!( - failure.guard.is_running(), - "the blocked child must be running when the parent reclaims it" + elapsed >= observe, + "the observation clock must actually elapse before startup is rejected" ); - let killed = failure - .guard - .terminate() - .expect("the owning parent must observe the blocked child's exit"); assert!( - !killed.success(), - "a blocked child must not report success after owner reclamation: {killed}" + 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/{}", failure.pid)).exists(), - "the exact child pid {} must be gone after the parent waited for it", - failure.pid + !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(), @@ -1067,7 +1367,8 @@ async fn gateway_startup_failure_reclaims_the_real_child() { // // 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 exit and reaps it. + // 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"); @@ -1084,6 +1385,11 @@ async fn gateway_startup_failure_reclaims_the_real_child() { 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"); @@ -1101,6 +1407,52 @@ async fn gateway_startup_failure_reclaims_the_real_child() { 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" + ); } /// `/health/detailed` publishes `{"source": {"kind", "hash", From b6a9e295cd8983fc9d502ffe3c6fb2cfee4573cf Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 15:10:07 +0800 Subject: [PATCH 16/27] Bound ACP test-child reclamation to one window and one signal Keep the guard's single absolute reclamation window and record its one forced signal attempt, so an explicit stop that runs out of budget cannot be followed by a second SIGKILL from Drop. A repeated entry only observes what is left of the original deadline. Drop implementations no longer write diagnostics while unwinding. The outer safety net re-reads the exact child identity and reaps an already-exited child without signalling it; every WNOHANG/EINTR path shares one bounded deadline. Add the failing-window test double and the real killed-child reap case, and keep the existing real startup-failure controls unchanged. --- tests/acp_delegation_e2e_tests.rs | 284 ++++++++++++++++++++++++------ 1 file changed, 229 insertions(+), 55 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index d4e50c5..61fa6ab 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -51,7 +51,7 @@ const REAP_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. +/// 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); @@ -153,11 +153,9 @@ impl GatewayFixture { 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() { - eprintln!( - "preserving failing Gateway fixture for diagnosis: {}", - self.root.display() - ); return; } let _ = fs::remove_dir_all(&self.root); @@ -172,9 +170,10 @@ struct ChildGuard { child: Child, pid: u32, reaped: Option, - /// One absolute cleanup deadline per guard: an explicit reclamation and a - /// later `Drop` fallback share it instead of stacking fresh windows. - cleanup_deadline: 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 { @@ -183,7 +182,7 @@ impl ChildGuard { pid: child.id(), child, reaped: None, - cleanup_deadline: None, + reclaim: None, } } @@ -221,7 +220,8 @@ impl ChildGuard { /// 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. + /// 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)); @@ -244,25 +244,90 @@ impl ChildGuard { } } let pid = self.pid; - let deadline = *self - .cleanup_deadline - .get_or_insert_with(|| Instant::now() + RECLAIM_BUDGET); - let signal_error = self.child.kill().err(); - let status = match reclaim_until_terminal(pid, deadline, || self.child.try_wait()) { + 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); } }; - self.reaped = Some(status); - Ok(Reclaim::Signalled { - status, - signal_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)] @@ -356,11 +421,10 @@ impl Drop for ChildGuard { if self.reaped.is_some() { return; } - if let Err(error) = self.terminate() { - // Never panic while unwinding, and never mark an unreclaimed child - // as reaped: the bounded failure is reported instead. - eprintln!("harness child was not reclaimed: {error}"); - } + // 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(); } } @@ -402,48 +466,54 @@ impl ChildIdentity { }) } - /// True only while `/proc` still shows this exact process as our direct - /// child with the start time captured at spawn. - fn still_exact(&self) -> bool { - let Ok(stat) = fs::read_to_string(format!("/proc/{}/stat", self.pid)) else { - return false; - }; - let Some((_, rest)) = stat.rsplit_once(')') else { - return false; - }; + /// One `/proc` observation of this exact child. `None` when the pid is gone + /// or no longer provably this child (`pid`, spawn start time, and parent + /// must all still match); otherwise `Some(is_zombie)`. A zombie has + /// already terminated, so it only needs to be reaped, never signalled. + fn exact_state(&self) -> Option { + let stat = fs::read_to_string(format!("/proc/{}/stat", self.pid)).ok()?; + let (_, rest) = stat.rsplit_once(')')?; let fields: Vec<&str> = rest.split_whitespace().collect(); if fields.len() < 20 { - return false; + return None; } let (Ok(ppid), Ok(start_time)) = (fields[1].parse::(), fields[19].parse::()) else { - return false; + return None; }; if ppid != std::process::id() || start_time != self.start_time { - return false; + return None; } // A zombie has already terminated and is the only case where the // command line is gone; it still has to be awaited, so accept it. if fields[0] == "Z" { - return true; + return Some(true); } - fs::read(format!("/proc/{}/cmdline", self.pid)) - .map(|cmdline| String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY)) - .unwrap_or(false) + let cmdline = fs::read(format!("/proc/{}/cmdline", self.pid)).ok()?; + if !String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY) { + return None; + } + Some(false) } - /// Independent outer safety net for the negative control. Only a process - /// still proven to be the exact spawned child may be signalled, and it is - /// waited for as well, so a deliberately disabled owner cannot leak it. + /// Independent outer safety net for the negative control. The single + /// identity observation decides both safety and whether a signal is + /// needed: only a still-running exact child is signalled, while an exact + /// child that already exited (zombie) is only reaped. Anything that lost + /// the identity proof is left untouched. All `WNOHANG`/`EINTR` paths share + /// one deadline and never sleep past it. fn reclaim_if_exact(&self) { - if !self.still_exact() { + let Some(zombie) = self.exact_state() else { return; - } + }; let pid = self.pid as libc::pid_t; - // The identity check above (pid, spawn start time, parent, and child - // entry) is what makes this signal safe; a bare cached pid is not. - unsafe { - libc::kill(pid, libc::SIGKILL); + if !zombie { + // The identity observation above (pid, spawn start time, parent, + // and child entry) is what makes this signal safe; a bare cached + // pid is not. + unsafe { + libc::kill(pid, libc::SIGKILL); + } } let deadline = Instant::now() + RECLAIM_BUDGET; loop { @@ -452,15 +522,21 @@ impl ChildIdentity { if waited == pid { return; } - if waited < 0 - && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted - { - continue; + 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; + } } - if Instant::now() >= deadline { + let now = Instant::now(); + if now >= deadline { return; } - std::thread::sleep(RECLAIM_POLL); + std::thread::sleep(RECLAIM_POLL.min(deadline - now)); } } } @@ -1453,6 +1529,104 @@ async fn gateway_startup_failure_reclaims_the_real_child() { 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() != Some(true) { + 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" + ); } /// `/health/detailed` publishes `{"source": {"kind", "hash", From f7067cab24eddf48a6d0e3c285e9fb5babece7cc Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 15:26:26 +0800 Subject: [PATCH 17/27] test(acp-e2e): reap an exact child that exits during the identity probe The outer safety net read a live /proc stat and only then the command line. A child that exited in between had an empty cmdline while the stat snapshot still looked alive, so the net refused the identity and skipped waitpid, leaving a zombie behind. After an empty cmdline, re-read the same stat a bounded number of times, re-validating parent and spawn start time, and accept only the terminal zombie state so the existing bounded waitpid reaps that exact child without a signal. The observation is injectable through a test-only hook: the regression makes the exact child exit exactly between the two reads and proves it is waited for without a signal, while a mismatched witness control proves the net still refuses. --- tests/acp_delegation_e2e_tests.rs | 269 ++++++++++++++++++++++++++---- 1 file changed, 234 insertions(+), 35 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index 61fa6ab..b4b2721 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -54,6 +54,12 @@ const REAP_BUDGET: Duration = Duration::from_secs(30); /// 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); +/// Bounded re-reads of `/proc//stat` when a live identity observation is +/// followed by an empty command line. The kernel drops `cmdline` before the +/// process becomes a zombie, so the next stat of the same exact child must show +/// the terminal state instead of the exit race being mistaken for a lost +/// identity. +const 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 @@ -428,6 +434,35 @@ impl Drop for ChildGuard { } } +/// 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()?, + }) +} + /// 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 @@ -442,12 +477,10 @@ struct ChildIdentity { #[cfg(unix)] impl ChildIdentity { fn capture(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 start_time = rest.split_whitespace().nth(19)?.parse().ok()?; - Some(Self { pid, start_time }) + Some(Self { + pid, + start_time: read_proc_stat(pid)?.start_time, + }) } fn write_witness(&self, path: &Path) { @@ -466,44 +499,74 @@ impl ChildIdentity { }) } - /// One `/proc` observation of this exact child. `None` when the pid is gone - /// or no longer provably this child (`pid`, spawn start time, and parent - /// must all still match); otherwise `Some(is_zombie)`. A zombie has - /// already terminated, so it only needs to be reaped, never signalled. + /// This exact child's state, accepted only while the observation is + /// provably this child (`pid`, spawn start time, and parent must all + /// match). `None` when the pid is gone or the identity proof is lost; + /// otherwise `Some(is_zombie)`. A zombie has already terminated, so it only + /// needs to be reaped, never signalled. fn exact_state(&self) -> Option { - let stat = fs::read_to_string(format!("/proc/{}/stat", self.pid)).ok()?; - let (_, rest) = stat.rsplit_once(')')?; - let fields: Vec<&str> = rest.split_whitespace().collect(); - if fields.len() < 20 { - return None; - } - let (Ok(ppid), Ok(start_time)) = (fields[1].parse::(), fields[19].parse::()) - else { - return None; - }; - if ppid != std::process::id() || start_time != self.start_time { - return None; - } - // A zombie has already terminated and is the only case where the - // command line is gone; it still has to be awaited, so accept it. - if fields[0] == "Z" { + 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()) -> Option { + let stat = self.matching_stat()?; + after_first_stat(); + if stat.state == 'Z' { return Some(true); } let cmdline = fs::read(format!("/proc/{}/cmdline", self.pid)).ok()?; - if !String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY) { + if String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY) { + return Some(false); + } + if !cmdline.is_empty() { + // A readable command line naming another program means this pid is + // no longer the harness child; only an empty one means it is + // exiting. return None; } - Some(false) + // The child began exiting between the identity stat and the + // command-line read. Re-read the same stat a bounded number of times, + // re-validating parent and spawn time, and accept only the terminal + // zombie state so this exact child is reaped instead of skipped. + for _ in 0..EXIT_RACE_REREADS { + std::thread::yield_now(); + let stat = self.matching_stat()?; + if stat.state == 'Z' { + return Some(true); + } + } + None + } + + /// 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 single - /// identity observation decides both safety and whether a signal is - /// needed: only a still-running exact child is signalled, while an exact - /// child that already exited (zombie) is only reaped. Anything that lost - /// the identity proof is left untouched. All `WNOHANG`/`EINTR` paths share - /// one deadline and never sleep past it. + /// 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 is signalled, while an exact child that + /// already exited (zombie) is only reaped. Anything that lost the identity + /// proof is left untouched. All `WNOHANG`/`EINTR` paths share one deadline + /// and never sleep past it. fn reclaim_if_exact(&self) { - let Some(zombie) = self.exact_state() else { + self.reclaim_if_exact_observed(&mut || {}, &mut |_| {}); + } + + /// `reclaim_if_exact` with the test-only observation hook and a callback + /// that records every signal attempt, so a regression can prove an exited + /// child was reaped without one. + fn reclaim_if_exact_observed( + &self, + after_first_stat: &mut dyn FnMut(), + record_signal: &mut dyn FnMut(libc::pid_t), + ) { + let Some(zombie) = self.exact_state_observed(after_first_stat) else { return; }; let pid = self.pid as libc::pid_t; @@ -511,6 +574,7 @@ impl ChildIdentity { // The identity observation above (pid, spawn start time, parent, // and child entry) is what makes this signal safe; a bare cached // pid is not. + record_signal(pid); unsafe { libc::kill(pid, libc::SIGKILL); } @@ -1627,6 +1691,141 @@ async fn gateway_startup_failure_reclaims_the_real_child() { 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; + exiting_identity.reclaim_if_exact_observed(&mut after_first_stat, &mut record_signal); + 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; + wrong_identity.reclaim_if_exact_observed(&mut after_first_stat, &mut record_signal); + 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!( + 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" + ); } /// `/health/detailed` publishes `{"source": {"kind", "hash", From c8472d91a99f55fe5d63d354606425df45fdd9e5 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 15:58:49 +0800 Subject: [PATCH 18/27] test(acp-e2e): wait for an exiting child under the shared reclaim deadline The fixture fallback abandoned an exact child whose /proc command line had already gone once eight stat re-reads were spent. Linux clears the argument vector in exit_mm and only later publishes Z in exit_notify, so that fixed count can run out while the child is still alive, and the unreaped zombie was left behind. Observe once and keep one boundary for everything after it: - A lost identity still returns with zero operations. - A matching Z, or a matching child with no command-line text, goes straight into the bounded waitpid(WNOHANG) loop and is never signalled. - Only a matching child that still shows the harness command line in its command line may make the one existing signal attempt. - Every wait iteration re-proves parent and spawn start time first, and the loop sleeps only the remaining time of the same absolute RECLAIM_BUDGET deadline, so EINTR and a never-terminating child both end at the original window instead of opening a second one. The regression holds the transient open deterministically: a real child replaces itself with a program that has an empty argument vector and then blocks on its stdin pipe, so /proc reports a live non-Z child with no command-line text for as long as the test keeps the pipe open. The fallback must keep waiting past the removed eight-read budget, signal nothing, reap that exact child once the pipe closes, and return at the original deadline for a matching child that never terminates. --- tests/acp_delegation_e2e_tests.rs | 375 +++++++++++++++++++++++++----- 1 file changed, 321 insertions(+), 54 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index b4b2721..b80c172 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -36,6 +36,10 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; const CHILD_ENTRY: &str = "gateway_harness_child_entry"; +/// The helper child entry that replaces itself with a process whose argument +/// vector is empty, so `/proc//cmdline` carries no text while the process +/// is still alive. +const EMPTY_CMDLINE_ENTRY: &str = "empty_cmdline_helper_entry"; const SPEC_ENV: &str = "RSS_ACP_DELEGATION_E2E_CHILD_SPEC"; const TOKEN_ENV: &str = "RSS_ACP_DELEGATION_E2E_CHILD_TOKEN"; @@ -54,12 +58,14 @@ const REAP_BUDGET: Duration = Duration::from_secs(30); /// 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); -/// Bounded re-reads of `/proc//stat` when a live identity observation is -/// followed by an empty command line. The kernel drops `cmdline` before the -/// process becomes a zombie, so the next stat of the same exact child must show -/// the terminal state instead of the exit race being mistaken for a lost -/// identity. -const EXIT_RACE_REREADS: usize = 8; +/// 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 @@ -463,6 +469,24 @@ fn read_proc_stat(pid: u32) -> Option { }) } +/// 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 @@ -501,44 +525,38 @@ impl ChildIdentity { /// This exact child's state, accepted only while the observation is /// provably this child (`pid`, spawn start time, and parent must all - /// match). `None` when the pid is gone or the identity proof is lost; - /// otherwise `Some(is_zombie)`. A zombie has already terminated, so it only - /// needs to be reaped, never signalled. - fn exact_state(&self) -> Option { + /// 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()) -> Option { - let stat = self.matching_stat()?; + 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 Some(true); + return ExactChild::Zombie; } - let cmdline = fs::read(format!("/proc/{}/cmdline", self.pid)).ok()?; + let Ok(cmdline) = fs::read(format!("/proc/{}/cmdline", self.pid)) else { + return ExactChild::Lost; + }; if String::from_utf8_lossy(&cmdline).contains(CHILD_ENTRY) { - return Some(false); + return ExactChild::Live; } - if !cmdline.is_empty() { - // A readable command line naming another program means this pid is - // no longer the harness child; only an empty one means it is - // exiting. - return None; + 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; } - // The child began exiting between the identity stat and the - // command-line read. Re-read the same stat a bounded number of times, - // re-validating parent and spawn time, and accept only the terminal - // zombie state so this exact child is reaped instead of skipped. - for _ in 0..EXIT_RACE_REREADS { - std::thread::yield_now(); - let stat = self.matching_stat()?; - if stat.state == 'Z' { - return Some(true); - } - } - None + // 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 @@ -550,37 +568,55 @@ impl ChildIdentity { /// 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 is signalled, while an exact child that - /// already exited (zombie) is only reaped. Anything that lost the identity - /// proof is left untouched. All `WNOHANG`/`EINTR` paths share one deadline - /// and never sleep past it. + /// 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 |_| {}); + self.reclaim_if_exact_observed(&mut || {}, &mut |_| {}, &mut |_| {}); } - /// `reclaim_if_exact` with the test-only observation hook and a callback - /// that records every signal attempt, so a regression can prove an exited - /// child was reaped without one. + /// `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, and that it ends at the one + /// deadline when the exact child never terminates. 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), ) { - let Some(zombie) = self.exact_state_observed(after_first_stat) else { - return; - }; let pid = self.pid as libc::pid_t; - if !zombie { - // The identity observation above (pid, spawn start time, parent, - // and child entry) is what makes this signal safe; a bare cached - // pid is not. - record_signal(pid); - unsafe { - libc::kill(pid, libc::SIGKILL); + // Opened before the identity observation, so the observation and every + // wait below share one window instead of stacking fresh ones. + let deadline = Instant::now() + RECLAIM_BUDGET; + match self.exact_state_observed(after_first_stat) { + 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); + unsafe { + libc::kill(pid, libc::SIGKILL); + } } } - let deadline = Instant::now() + RECLAIM_BUDGET; loop { + // 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); let mut status = 0; let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) }; if waited == pid { @@ -686,6 +722,78 @@ fn spawn_harness_child( } } +/// Spawns the empty-command-line helper as a real OS child of this test. The +/// child entry replaces itself with a program that has no argument vector and +/// then blocks on the piped stdin, so `/proc//cmdline` carries no text +/// while the process is still running. That is the same kernel observation +/// `exit_mm` produces for an exiting child, but it can be held open +/// deterministically until this test closes the pipe. +#[cfg(unix)] +fn spawn_empty_cmdline_child(fixture: &GatewayFixture, label: &str) -> (ChildGuard, ChildIdentity) { + let assigned_tmp = lease_tmp(); + let log_path = fixture.root.join(format!("empty-cmdline-{label}.log")); + let stdout = fs::File::create(&log_path).expect("create empty-command-line child log"); + let stderr = stdout + .try_clone() + .expect("clone empty-command-line child log"); + let exe = std::env::current_exe().expect("current test executable"); + let mut command = Command::new(exe); + command + .args(["--exact", EMPTY_CMDLINE_ENTRY, "--ignored", "--nocapture"]) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .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::from(stdout)) + .stderr(Stdio::from(stderr)); + let child = command + .spawn() + .expect("the empty-command-line helper must spawn"); + // Ownership moves to the guard before any readiness work can fail. + let guard = ChildGuard::new(child); + let identity = ChildIdentity::capture(guard.pid()) + .expect("the empty-command-line helper must have a spawn identity"); + (guard, identity) +} + +/// Waits until the helper is provably this exact child, still running (`Z` is +/// never acceptable), with an argument vector that carries no text at all. +#[cfg(unix)] +fn await_no_command_line(identity: &ChildIdentity, label: &str) { + let deadline = Instant::now() + RECLAIM_BUDGET; + loop { + let stat = read_proc_stat(identity.pid); + let cmdline = fs::read(format!("/proc/{}/cmdline", identity.pid)).ok(); + let alive = stat.is_some_and(|stat| { + stat.state != 'Z' + && stat.ppid == std::process::id() + && stat.start_time == identity.start_time + }); + let no_text = cmdline + .as_ref() + .is_some_and(|cmdline| cmdline.iter().all(|byte| *byte == 0)); + if alive && no_text { + return; + } + assert!( + !stat.is_some_and(|stat| stat.state == 'Z'), + "{label} exited before it ever showed an empty command line; the helper could not replace itself" + ); + assert!( + Instant::now() < deadline, + "{label} must become a live exact child without command-line text; last stat {stat:?}, command-line length {:?}", + cmdline.as_ref().map(Vec::len) + ); + std::thread::sleep(Duration::from_millis(2)); + } +} + /// 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. @@ -1438,6 +1546,29 @@ fn panic_text(payload: Box) -> String { } } +/// Helper process for the empty-command-line regression. It replaces itself +/// with `cat` whose argument vector is empty (`argc == 0`) and whose +/// environment is empty, so `/proc//cmdline` carries no text while the +/// process stays alive blocked on its stdin pipe. The parent closes that pipe +/// when it wants the exact child to exit, which makes the "command line is +/// already gone, terminal state is not published yet" transient reproducible +/// without depending on kernel scheduling after a signal. +#[cfg(unix)] +#[test] +#[ignore = "helper process launched by the empty-command-line regression"] +fn empty_cmdline_helper_entry() { + // Only `/bin/cat` and `/usr/bin/cat` are tried; either one blocks reading + // stdin with no file operands and exits 0 on EOF. + let argv: [*const libc::c_char; 1] = [std::ptr::null()]; + let envp: [*const libc::c_char; 1] = [std::ptr::null()]; + for program in ["/bin/cat\0", "/usr/bin/cat\0"] { + unsafe { + libc::execve(program.as_ptr().cast(), argv.as_ptr(), envp.as_ptr()); + } + } + std::process::exit(127); +} + /// 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 @@ -1669,7 +1800,7 @@ async fn gateway_startup_failure_reclaims_the_real_child() { libc::kill(zombie_pid, libc::SIGKILL); } let zombie_deadline = Instant::now() + RECLAIM_BUDGET; - while zombie_identity.exact_state() != Some(true) { + while zombie_identity.exact_state() != ExactChild::Zombie { assert!( Instant::now() < zombie_deadline, "the killed child must become a zombie of this parent" @@ -1750,7 +1881,17 @@ async fn gateway_startup_failure_reclaims_the_real_child() { }; let mut signalled = 0usize; let mut record_signal = |_pid: libc::pid_t| signalled += 1; - exiting_identity.reclaim_if_exact_observed(&mut after_first_stat, &mut record_signal); + 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" @@ -1802,12 +1943,22 @@ async fn gateway_startup_failure_reclaims_the_real_child() { let mut after_first_stat = || reached_cmdline = true; let mut signalled = 0usize; let mut record_signal = |_pid: libc::pid_t| signalled += 1; - wrong_identity.reclaim_if_exact_observed(&mut after_first_stat, &mut record_signal); + 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" @@ -1826,6 +1977,122 @@ async fn gateway_startup_failure_reclaims_the_real_child() { !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 replaces itself with a program that has + // an empty argument vector and then 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, "no-command-line"); + let free_pid = free_child.pid(); + assert_eq!( + free_identity.pid, free_pid, + "the witness must describe the exact spawned child" + ); + await_no_command_line(&free_identity, "the empty-command-line child"); + assert_eq!( + free_identity.exact_state(), + ExactChild::NoCommandLine, + "the fallback's own first observation must be a live, non-`Z` child without command-line text" + ); + 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, "no-command-line-stuck"); + let stuck_pid = stuck_child.pid(); + await_no_command_line(&stuck_identity, "the stuck empty-command-line child"); + 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" + ); } /// `/health/detailed` publishes `{"source": {"kind", "hash", From a4050a2924255d9b96de99a3d77b554e88b70f8b Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 17:02:11 +0800 Subject: [PATCH 19/27] test(acp-e2e): refuse fallback side effects once the window is spent Check the single reclamation deadline after the identity observation and again immediately before the kill, and before every waitpid after an observation. Once the window is spent, no signal, identity re-read, poll, or wait may start; sleep and EINTR still consume the original remainder. Two deterministic controls advance a test-only clock to exactly the entry deadline: a real /bin/sleep child carrying the harness entry in argv[0] must stay alive and owned instead of being signalled, and a real zombie must stay unreaped under /proc until its exact owner collects it. --- tests/acp_delegation_e2e_tests.rs | 216 +++++++++++++++++++++++++++++- 1 file changed, 211 insertions(+), 5 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index b80c172..3ab17ca 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -581,19 +581,45 @@ impl ChildIdentity { /// 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, and that it ends at the one - /// deadline when the exact child never terminates. + /// 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 = Instant::now() + RECLAIM_BUDGET; - match self.exact_state_observed(after_first_stat) { + 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 => { @@ -602,12 +628,22 @@ impl ChildIdentity { // 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 @@ -617,6 +653,11 @@ impl ChildIdentity { 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 { @@ -632,7 +673,7 @@ impl ChildIdentity { return; } } - let now = Instant::now(); + let now = clock(); if now >= deadline { return; } @@ -2095,6 +2136,171 @@ async fn gateway_startup_failure_reclaims_the_real_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, "wait-only-deadline"); + let zombie_pid = zombie_child.pid(); + await_no_command_line(&zombie_identity, "the deadline wait-only child"); + 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. From 755342d446056c78b68eb7bbe1b3686d38d8863f Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 17:30:48 +0800 Subject: [PATCH 20/27] fix(acp): unify delegation approval, spawn and process ownership - Route automatic, guardian and unset reviewer runs through a real durable human_pending row; the production Telegram picker and /approve /deny paths accept a delegation id as syntax only and authorize strictly from the bound run, session, owner, picker, pending state and expiry. - Freeze one absolute delegation deadline, then perform the only process creation under a single synchronous fence shared with the real writers: the persistence session fence used by CAS/delete/approval resolve, the RunCancellation mutex used by request, and the workspace authority revoke mutex. A stop, revoke, replacement or expired approval observed there is zero spawn; one that loses the race is cancelled normally. - Carry the original session identity through every phase write, abort and asynchronous settlement, and re-check the original pin lease in each mutation. A replacement row is never inherited, even with the same owner. - Give one cleanup owner the call identity, observer, service permit and per-run admission. Only confirmed cleanup settles and releases; unknown or lost cleanup stays charged in quarantine. A stale lease is reclaimable only after a durable terminal run and recorded confirmed cleanup. - Measure the result budget at the public JSON boundary, add the typed refusal minimum, and drop the unvalidated code-dropping fallback. --- src/acp/delegated_client.rs | 21 + src/gateway/store.rs | 26 + src/gateway/telegram.rs | 45 +- src/runtime/rss_runner.rs | 41 + src/service.rs | 12 +- src/service/acp_session_pins.rs | 1272 ++++++++++++++------- tests/acp_delegation_policy_tests.rs | 795 ++++++++++++- tests/fixtures/acp_policy/policy_agent.rs | 16 +- 8 files changed, 1805 insertions(+), 423 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 997da42..7fc01dc 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -374,6 +374,19 @@ impl DelegatedAcpClient { 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 { + Self::spawn_with_stdin(launch, deadline, |stdin| Box::new(stdin)) + } + /// 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 @@ -384,6 +397,14 @@ impl DelegatedAcpClient { launch: AcpDelegationLaunch, deadline: Instant, wrap_stdin: impl FnOnce(ChildStdin) -> StdinWriter, + ) -> Result { + Self::spawn_with_stdin(launch, deadline, wrap_stdin) + } + + fn spawn_with_stdin( + launch: AcpDelegationLaunch, + deadline: Instant, + wrap_stdin: impl FnOnce(ChildStdin) -> StdinWriter, ) -> Result { if Instant::now() >= deadline { return Err(AcpDelegationError::DeadlineExceeded); diff --git a/src/gateway/store.rs b/src/gateway/store.rs index b079ef3..a9924cc 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, @@ -4450,9 +4458,19 @@ impl GatewayPersistence { /// 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( @@ -4478,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 })) } @@ -4943,6 +4965,10 @@ impl GatewayPersistence { } pub fn approval_resolve(&self, payload: &Value) -> Result { + let _fence = self + .session_fence + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); #[cfg(feature = "config-fixture")] { let gate = self diff --git a/src/gateway/telegram.rs b/src/gateway/telegram.rs index 2cd02f4..8f33f84 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; }; @@ -3406,6 +3418,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/runtime/rss_runner.rs b/src/runtime/rss_runner.rs index e70ac66..116752f 100644 --- a/src/runtime/rss_runner.rs +++ b/src/runtime/rss_runner.rs @@ -815,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) } @@ -1106,6 +1134,9 @@ 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>, } impl WorkspaceAuthority { @@ -1133,10 +1164,19 @@ 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.binding.host.revoke(); } + /// Arbitration shared with the delegation spawn commit. + pub(crate) fn spawn_gate(&self) -> Arc> { + Arc::clone(&self.spawn_gate) + } + /// 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. @@ -1554,6 +1594,7 @@ impl AgentRunner { binding, grant, explicitly_revoked: AtomicBool::new(false), + spawn_gate: Arc::new(std::sync::Mutex::new(())), })), (Some(_), None) => { return Err(RunError::Setup(VmError::HostError( diff --git a/src/service.rs b/src/service.rs index 6010f1c..4f8b6e2 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1873,6 +1873,10 @@ impl acp_session_pins::AcpWorkspaceAuthority for RunWorkspaceAuthority { fn generation(&self) -> u64 { self.0.generation() } + + fn spawn_gate(&self) -> Arc> { + self.0.spawn_gate() + } } /// Admission metadata stores the deadline either as a JSON number or, after a @@ -6414,10 +6418,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, diff --git a/src/service/acp_session_pins.rs b/src/service/acp_session_pins.rs index 3e690d7..8d28ae9 100644 --- a/src/service/acp_session_pins.rs +++ b/src/service/acp_session_pins.rs @@ -182,6 +182,17 @@ impl AcpDelegationResult { "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. @@ -218,6 +229,9 @@ pub trait AcpWorkspaceAuthority: Send + Sync { 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>; } /// Authoritative facts of one live run, read from the gateway's admitted run. @@ -292,6 +306,7 @@ pub enum AcpPolicyRefusal { Denied(&'static str), Busy(&'static str), Failed(&'static str), + TimedOut(&'static str), } impl AcpPolicyRefusal { @@ -300,12 +315,15 @@ impl AcpPolicyRefusal { 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) => code, + Self::Denied(code) | Self::Busy(code) | Self::Failed(code) | Self::TimedOut(code) => { + code + } } } } @@ -355,11 +373,22 @@ struct PolicyInner { /// of the service lifetime; the entry owns the permit explicitly. quarantine: Mutex>, per_run: Mutex>, + /// Runs whose per-run admission was handed to a cleanup owner (or to + /// quarantine). `RunGate::drop` must not release those. + per_run_handoff: Mutex>, 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>>, @@ -412,12 +441,17 @@ impl AcpDelegationPolicy { quota: Arc::new(Semaphore::new(MAX_ACTIVE_PROCESSES)), quarantine: Mutex::new(Vec::new()), per_run: Mutex::new(HashSet::new()), + per_run_handoff: 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), @@ -435,11 +469,12 @@ impl AcpDelegationPolicy { self.inner.quota.available_permits() } - /// A call whose smallest successful envelope cannot fit the run's - /// tool-output budget can never deliver a result; it is refused before an - /// approval row or a process exists. + /// 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 minimal_success_envelope_bytes(harness_id) > self.inner.max_result_bytes { + if minimum_deliverable_envelope_bytes(harness_id) > self.inner.max_result_bytes { return Err(AcpPolicyRefusal::Failed("acp_delegation_budget")); } Ok(()) @@ -462,6 +497,20 @@ impl AcpDelegationPolicy { .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")] @@ -526,6 +575,24 @@ impl AcpDelegationPolicy { } } + #[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 @@ -599,6 +666,7 @@ impl AcpDelegationPolicy { 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(), @@ -613,24 +681,32 @@ impl AcpDelegationPolicy { }; let key = approval_id.clone(); let stored = binding.clone(); - self.mutate(&scope.session_id, move |doc, snapshot| { - if snapshot.owner != stored.owner { - return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); - } - 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) - }) + 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 { @@ -703,6 +779,24 @@ impl AcpDelegationPolicy { return Err(AcpPolicyRefusal::Denied("acp_run_inactive")); } let cancellation = facts.cancellation.clone(); + // 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.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() { @@ -716,13 +810,13 @@ impl AcpDelegationPolicy { return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); } } - let _run_guard = RunGate { - policy: &self.inner, - run_id: scope.run_id.clone(), - }; + let _run_guard = RunGate::new(Arc::clone(&self.inner), scope.run_id.clone()); let mut snapshot = self.read_session(&scope.session_id).await?; - let original_identity = snapshot.identity(); + 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()); @@ -746,6 +840,8 @@ impl AcpDelegationPolicy { .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 @@ -768,7 +864,8 @@ impl AcpDelegationPolicy { } let reclaimable = !pin.cleanup_pending && doc.calls.get(&lease.call_id).is_some_and(|call| { - matches!(call.phase, CallPhase::SessionBound | CallPhase::Restoring) + call.cleanup_confirmed + && matches!(call.phase, CallPhase::SessionBound | CallPhase::Restoring) }); if !reclaimable { return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); @@ -797,9 +894,9 @@ impl AcpDelegationPolicy { { return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); } - let deadline = effective_deadline(run_deadline_ms(&facts)); + let deadline = frozen_deadline(&facts); if Instant::now() >= deadline { - return Err(AcpPolicyRefusal::Failed("acp_delegation_deadline")); + return Err(AcpPolicyRefusal::TimedOut("acp_delegation_deadline")); } let permit = self .inner @@ -841,6 +938,7 @@ impl AcpDelegationPolicy { 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(), @@ -863,6 +961,7 @@ impl AcpDelegationPolicy { 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()), @@ -874,6 +973,7 @@ impl AcpDelegationPolicy { 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, }; @@ -884,88 +984,98 @@ impl AcpDelegationPolicy { 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, move |doc, snapshot| { - if snapshot.owner != owner { - return Err(AcpPolicyRefusal::Denied("acp_binding_mismatch")); - } - 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 + .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 Some(interrupted) = doc_calls.get_mut(&active.call_id) else { + 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 !matches!( - interrupted.phase, - CallPhase::SessionBound | CallPhase::Restoring - ) { - return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); + if binding != &expected_binding || binding.pin_version != pin.version { + return Err(AcpPolicyRefusal::Denied("acp_approval_stale")); } - // 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()), + 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, }); - 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) - }) + pin.cleanup_pending = false; + pin.version += 1; + Ok(lease_guard) + }, + ) .await?; snapshot = prepared_snapshot; @@ -973,8 +1083,9 @@ impl AcpDelegationPolicy { 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_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1001,6 +1112,7 @@ impl AcpDelegationPolicy { .abort_pre_spawn( scope, request, + &original_identity, fresh, permit, AcpDelegationStatus::Denied, @@ -1013,6 +1125,7 @@ impl AcpDelegationPolicy { .abort_pre_spawn( scope, request, + &original_identity, fresh, permit, AcpDelegationStatus::Failed, @@ -1028,6 +1141,7 @@ impl AcpDelegationPolicy { .abort_pre_spawn( scope, request, + &original_identity, fresh, permit, refusal.status(), @@ -1043,6 +1157,7 @@ impl AcpDelegationPolicy { .abort_pre_spawn( scope, request, + &original_identity, fresh, permit, AcpDelegationStatus::Denied, @@ -1055,6 +1170,7 @@ impl AcpDelegationPolicy { .abort_pre_spawn( scope, request, + &original_identity, fresh, permit, AcpDelegationStatus::Denied, @@ -1062,20 +1178,14 @@ impl AcpDelegationPolicy { ) .await; } - let deadline = effective_deadline(run_deadline_ms(&live)); + // The frozen deadline stays authoritative: the live read above can + // never extend it. snapshot = fresh; - // Synchronous arbitration, in this order: stop, elapsed deadline, run - // liveness, then workspace revocation and identity. Nothing is awaited - // between this barrier and the process spawn; an event observed here - // is a pre-spawn event and produces zero spawns. - if let PreSpawnBarrier::Refuse(status, code) = - self.pre_spawn_barrier(scope, &live, &workspace, deadline) - { - return self - .abort_pre_spawn(scope, request, snapshot, permit, status, code) - .await; - } + // 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(), @@ -1084,58 +1194,197 @@ impl AcpDelegationPolicy { ) .map_err(|_| AcpPolicyRefusal::Failed("acp_delegation_invalid_launch"))?; + let spawned = match self + .commit_spawn( + scope, + request, + witness, + &original_identity, + &facts, + &workspace, + launch_handle, + deadline, + ) + .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, - launch_handle, - deadline, - &live, - &workspace, + &original_identity, + spawned, + cancellation.clone(), &mut snapshot, permit, ) .await } - /// One synchronous pre-spawn decision. + /// The single synchronous spawn commit. /// - /// The order is fixed: the run's stop/revocation root first, then the - /// admitted absolute deadline, then run liveness, then the retained - /// workspace authority. Whoever wins here is a pre-spawn event. - fn pre_spawn_barrier( + /// 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, - ) -> PreSpawnBarrier { - if facts.cancellation.requested().is_some() { - return PreSpawnBarrier::Refuse( - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", - ); - } - if Instant::now() >= deadline { - return PreSpawnBarrier::Refuse( - AcpDelegationStatus::Timeout, - "acp_delegation_deadline", - ); - } - if !self.inner.gateway.run_active(&scope.run_id) { - return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_run_inactive"); - } - let Some(authority) = facts.workspace.as_ref() else { - return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_workspace_unbound"); - }; - if authority.revoked() || authority.check().is_err() { - return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_workspace_invalid"); - } - if authority.canonical_path() != workspace.path - || authority.generation() != workspace.generation - { - return PreSpawnBarrier::Refuse(AcpDelegationStatus::Denied, "acp_binding_mismatch"); - } - PreSpawnBarrier::Proceed + ) -> 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(); + } + match crate::acp::DelegatedAcpClient::spawn(launch, deadline) { + Ok(client) => Ok(Ok(client)), + Err(error) => Ok(Err((AcpDelegationStatus::Failed, error.code()))), + } + }) + .await + .map_err(|_| AcpPolicyRefusal::Failed("acp_delegation_spawn_failed"))?; + joined.map_err(AcpPolicyRefusal::Failed) } /// Settles a prepared call that never spawned a process. @@ -1144,6 +1393,7 @@ impl AcpDelegationPolicy { &self, scope: &AcpDelegationScope, request: &AcpDelegationRequest, + identity: &SessionIdentity, snapshot: SessionSnapshot, permit: tokio::sync::OwnedSemaphorePermit, status: AcpDelegationStatus, @@ -1158,7 +1408,7 @@ impl AcpDelegationPolicy { code: Some(code.to_string()), }; match self - .settle_outcome(scope, request, &mut snapshot, outcome, true) + .settle_outcome(scope, request, identity, &mut snapshot, outcome, true, true) .await { Ok(result) => { @@ -1166,8 +1416,9 @@ impl AcpDelegationPolicy { Ok(result) } Err(_) => { - self.quarantine_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1176,62 +1427,18 @@ impl AcpDelegationPolicy { } } - /// Drives one connection from spawn to settlement. + /// Drives one already-spawned connection from handshake to settlement. #[allow(clippy::too_many_arguments)] async fn run_call( &self, scope: &AcpDelegationScope, request: &AcpDelegationRequest, - launch: AcpDelegationLaunch, - deadline: Instant, - facts: &AcpRunFacts, - workspace: &AdmittedWorkspace, + identity: &SessionIdentity, + mut client: DelegatedAcpClient, + cancellation: crate::runtime::rss_runner::RunCancellation, snapshot: &mut SessionSnapshot, permit: tokio::sync::OwnedSemaphorePermit, ) -> Result { - // The final synchronous decision sits immediately before `connect`, - // which creates the process. No await separates them. - if let PreSpawnBarrier::Refuse(status, code) = - self.pre_spawn_barrier(scope, facts, workspace, deadline) - { - return self - .abort_pre_spawn(scope, request, snapshot.clone(), permit, status, code) - .await; - } - let cancellation = &facts.cancellation; - if cancellation.requested().is_some() || Instant::now() >= deadline { - let timed_out = Instant::now() >= deadline; - let (status, code) = if timed_out { - (AcpDelegationStatus::Timeout, "acp_delegation_deadline") - } else { - (AcpDelegationStatus::Cancelled, "acp_delegation_cancelled") - }; - return self - .abort_pre_spawn(scope, request, snapshot.clone(), permit, status, code) - .await; - } - let mut client = match DelegatedAcpClient::connect(launch, deadline).await { - Ok(client) => client, - Err(error) => { - let result = self - .settle_failed(scope, request, snapshot, error.code()) - .await; - return match result { - Ok(result) => { - drop(permit); - Ok(result) - } - Err(_) => { - self.quarantine_permit( - permit, - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); - Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) - } - }; - } - }; let observer = client.cleanup_observer(); let capabilities = { @@ -1249,6 +1456,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1265,6 +1473,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1289,6 +1498,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1303,12 +1513,14 @@ impl AcpDelegationPolicy { // interruption here is an explicit recoverable state, distinct // from an unknown `session/new`. if self - .mark_session_restoring(scope, request, snapshot) + .mark_session_restoring(scope, request, identity, snapshot) .await .is_err() { return self - .abort_unknown_state(scope, request, snapshot, client, observer, permit) + .abort_unknown_state( + scope, request, identity, snapshot, client, observer, permit, + ) .await; } let restored = { @@ -1326,6 +1538,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1342,6 +1555,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1355,15 +1569,22 @@ impl AcpDelegationPolicy { Some(Ok(_)) => { #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::AfterRestoreBeforeIntent) { - let _ = client.close().await; - // The call stays `restoring` with its lease: a - // later call may reclaim it after the store proves - // this run terminal, and then restore the same ID. - self.quarantine_permit( - permit, - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + let report = client.close().await; + if report.cleanup_confirmed + && self + .mark_cleanup_confirmed(scope, request, identity, snapshot) + .await + .is_ok() + { + drop(permit); + } else { + self.quarantine_ownership( + permit, + scope.run_id.clone(), + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + } return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } existing @@ -1371,10 +1592,14 @@ impl AcpDelegationPolicy { } } None => { - let marked = self.mark_session_creating(scope, request, snapshot).await; + let marked = self + .mark_session_creating(scope, request, identity, snapshot) + .await; if marked.is_err() { return self - .abort_unknown_state(scope, request, snapshot, client, observer, permit) + .abort_unknown_state( + scope, request, identity, snapshot, client, observer, permit, + ) .await; } let created = { @@ -1392,6 +1617,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1408,6 +1634,7 @@ impl AcpDelegationPolicy { .fail_created_unknown( scope, request, + identity, snapshot, client, observer, @@ -1423,8 +1650,9 @@ impl AcpDelegationPolicy { // The pin and call stay `creating`: the ID was never // persisted. The permit stays charged because cleanup was // not observed here. - self.quarantine_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1432,25 +1660,35 @@ impl AcpDelegationPolicy { } if created.is_empty() || created.len() > MAX_EXTERNAL_SESSION_ID_BYTES { return self - .reject_external_id(scope, request, snapshot, client, observer, permit) + .reject_external_id( + scope, request, identity, snapshot, client, observer, permit, + ) .await; } if let Err(_error) = self - .persist_bound_id(scope, request, snapshot, &created) + .persist_bound_id(scope, request, identity, snapshot, &created) .await { return self - .abort_unknown_state(scope, request, snapshot, client, observer, permit) + .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 { + if report.cleanup_confirmed + && self + .mark_cleanup_confirmed(scope, request, identity, snapshot) + .await + .is_ok() + { drop(permit); } else { - self.quarantine_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1466,6 +1704,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1478,11 +1717,15 @@ impl AcpDelegationPolicy { } // Durable prompt-send intent, strictly after the bound ID write. - if let Err(_error) = self.write_prompt_intent(scope, request, snapshot).await { + if let Err(_error) = self + .write_prompt_intent(scope, request, identity, snapshot) + .await + { return self .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1500,6 +1743,7 @@ impl AcpDelegationPolicy { .unsent_close( scope, request, + identity, snapshot, client, observer, @@ -1543,6 +1787,7 @@ impl AcpDelegationPolicy { .settle_after_cleanup( scope, &request.harness_id, + identity, proof, Some(permit), expected_version, @@ -1558,12 +1803,12 @@ impl AcpDelegationPolicy { #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::DeferToObserver) { return self - .hold_until_cleanup(scope, request, observer, permit) + .hold_until_cleanup(scope, request, identity, observer, permit) .await; } if !report.cleanup_confirmed { return self - .hold_until_cleanup(scope, request, observer, permit) + .hold_until_cleanup(scope, request, identity, observer, permit) .await; } @@ -1571,7 +1816,9 @@ impl AcpDelegationPolicy { PromptWait::Done(Ok(result)) => { #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::AfterPromptPublished) { - let _ = self.mark_pin_unknown(scope, request, snapshot).await; + let _ = self + .mark_pin_unknown(scope, request, identity, snapshot) + .await; drop(permit); return Err(AcpPolicyRefusal::Failed("acp_prompt_indeterminate")); } @@ -1629,7 +1876,15 @@ impl AcpDelegationPolicy { ), }; match self - .settle_outcome(scope, request, snapshot, settled, keeps_binding) + .settle_outcome( + scope, + request, + identity, + snapshot, + settled, + keeps_binding, + true, + ) .await { Ok(result) => { @@ -1637,8 +1892,9 @@ impl AcpDelegationPolicy { Ok(result) } Err(_) => { - self.quarantine_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1653,6 +1909,7 @@ impl AcpDelegationPolicy { &self, scope: &AcpDelegationScope, request: &AcpDelegationRequest, + identity: &SessionIdentity, snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, @@ -1664,7 +1921,7 @@ impl AcpDelegationPolicy { let report = client.close().await; if !report.cleanup_confirmed { return self - .hold_until_cleanup(scope, request, observer, permit) + .hold_until_cleanup(scope, request, identity, observer, permit) .await; } let outcome = SettledOutcome { @@ -1675,7 +1932,15 @@ impl AcpDelegationPolicy { code: Some(code.to_string()), }; match self - .settle_outcome(scope, request, snapshot, outcome, keeps_binding) + .settle_outcome( + scope, + request, + identity, + snapshot, + outcome, + keeps_binding, + true, + ) .await { Ok(result) => { @@ -1683,8 +1948,9 @@ impl AcpDelegationPolicy { Ok(result) } Err(_) => { - self.quarantine_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1699,6 +1965,7 @@ impl AcpDelegationPolicy { &self, scope: &AcpDelegationScope, request: &AcpDelegationRequest, + identity: &SessionIdentity, snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, @@ -1708,7 +1975,7 @@ impl AcpDelegationPolicy { let report = client.close().await; if !report.cleanup_confirmed { return self - .hold_until_cleanup(scope, request, observer, permit) + .hold_until_cleanup(scope, request, identity, observer, permit) .await; } let outcome = SettledOutcome { @@ -1719,7 +1986,7 @@ impl AcpDelegationPolicy { code: Some(code.to_string()), }; match self - .settle_outcome(scope, request, snapshot, outcome, false) + .settle_outcome(scope, request, identity, snapshot, outcome, false, true) .await { Ok(result) => { @@ -1727,8 +1994,9 @@ impl AcpDelegationPolicy { Ok(result) } Err(_) => { - self.quarantine_permit( + self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, request.harness_id), scope.tool_call_id.clone(), ); @@ -1738,10 +2006,12 @@ impl AcpDelegationPolicy { } /// 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, @@ -1750,6 +2020,7 @@ impl AcpDelegationPolicy { self.fail_created_unknown( scope, request, + identity, snapshot, client, observer, @@ -1760,121 +2031,178 @@ impl AcpDelegationPolicy { } /// Durable writes failed after the spawn: leave the durable phase exactly - /// where it was and keep the capacity charged until cleanup is proven. + /// 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, - _snapshot: &mut SessionSnapshot, + identity: &SessionIdentity, + snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, permit: tokio::sync::OwnedSemaphorePermit, ) -> Result { let report = client.close().await; - if report.cleanup_confirmed { - drop(permit); - } else { - self.quarantine_permit( - permit, - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); - let _ = observer; + 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(_) => { + drop(permit); + Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")) + } + Err(_) => { + self.quarantine_ownership( + permit, + scope.run_id.clone(), + format!("{}:{}", scope.session_id, request.harness_id), + scope.tool_call_id.clone(), + ); + Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) + } } - Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")) - } - - /// Settles a call that never published a prompt. The pin keeps its durable - /// binding, so a later approved call can restore the same external session. - async fn settle_failed( - &self, - scope: &AcpDelegationScope, - request: &AcpDelegationRequest, - snapshot: &mut SessionSnapshot, - code: &'static str, - ) -> Result { - self.settle_outcome( - scope, - request, - snapshot, - SettledOutcome { - status: AcpDelegationStatus::Failed, - text: String::new(), - stop_reason: None, - truncated: false, - code: Some(code.to_string()), - }, - true, - ) - .await } /// One durable conditional write settles the outcome and releases the pin /// lease. The storage predicate still names this exact call as the lease - /// owner, so a stale settlement cannot clear a newer owner. + /// 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, move |doc, _snapshot| { - let Some(call) = doc.calls.get_mut(&call_id) else { + .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 mut lease_guard = None; - if let Some(pin) = doc.pins.get_mut(&harness_id) { - let owns = pin - .active - .as_ref() - .is_some_and(|lease| lease.call_id == call_id && lease.run_id == run_id); - if owns { - pin.active = None; - if !keeps_binding { - pin.phase = PinPhase::Unknown; - } - pin.version += 1; - lease_guard = Some((harness_id.clone(), call_id.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; } - Ok(lease_guard) + pin.version += 1; + Ok(Some((harness_id.clone(), call_id.clone()))) }) .await?; *snapshot = fresh; Ok(outcome.to_result(&request.harness_id, false)) } - /// Marks the pin as un-reusable after an unknown remote effect. + /// 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, move |doc, _snapshot| { - let mut lease_guard = None; - if let Some(pin) = doc.pins.get_mut(&harness_id) { - pin.phase = PinPhase::Unknown; - pin.active = None; - pin.version += 1; - lease_guard = Some((harness_id.clone(), call_id.clone())); + .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")); } - Ok(lease_guard) + 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; @@ -1885,19 +2213,30 @@ impl AcpDelegationPolicy { &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, move |doc, _snapshot| { - let Some(pin) = doc.pins.get_mut(&harness_id) else { + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); }; - let Some(call) = doc.calls.get_mut(&call_id) else { + 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; } @@ -1913,23 +2252,35 @@ impl AcpDelegationPolicy { &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, move |doc, _snapshot| { - let Some(call) = doc.calls.get_mut(&call_id) else { + .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; - if let Some(pin) = doc.pins.get_mut(&harness_id) { - pin.phase = PinPhase::Bound; - pin.version += 1; - } + 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?; @@ -1941,23 +2292,34 @@ impl AcpDelegationPolicy { &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, move |doc, _snapshot| { - let Some(pin) = doc.pins.get_mut(&harness_id) else { + .mutate(&scope.session_id, identity, move |doc, _snapshot| { + let Some(pin) = doc.pins.get(&harness_id) else { return Err(AcpPolicyRefusal::Failed("acp_pin_missing")); }; - let Some(call) = doc.calls.get_mut(&call_id) else { + 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; } @@ -1972,21 +2334,33 @@ impl AcpDelegationPolicy { &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, move |doc, _snapshot| { - let Some(call) = doc.calls.get_mut(&call_id) else { - return Err(AcpPolicyRefusal::Failed("acp_call_missing")); + .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(); - if let Some(pin) = doc.pins.get_mut(&harness_id) { - pin.phase = PinPhase::Bound; - pin.version += 1; - } + 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?; @@ -2012,6 +2386,7 @@ impl AcpDelegationPolicy { }; 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 @@ -2059,12 +2434,17 @@ impl AcpDelegationPolicy { .collect() } - fn quarantine_permit( + /// 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: tokio::sync::OwnedSemaphorePermit, + run_id: String, pin_key: String, call_id: String, ) { + self.handoff_run(&run_id); self.inner .quarantine .lock() @@ -2076,6 +2456,27 @@ impl AcpDelegationPolicy { }); } + fn handoff_run(&self, run_id: &str) { + self.inner + .per_run_handoff + .lock() + .expect("acp per-run handoff") + .insert(run_id.to_string()); + } + + fn finish_run_handoff(&self, run_id: &str) { + self.inner + .per_run_handoff + .lock() + .expect("acp per-run handoff") + .remove(run_id); + self.inner + .per_run + .lock() + .expect("acp per-run gate") + .remove(run_id); + } + /// 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()?; @@ -2085,18 +2486,21 @@ impl AcpDelegationPolicy { .map(|pin| pin.version) } - /// Waits for the supervisor's cleanup evidence and hands the charged slot - /// to [`Self::settle_after_cleanup`] once the proof resolves. + /// 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: tokio::sync::OwnedSemaphorePermit, ) -> Result { let policy = self.clone(); let scope = scope.clone(); + let identity = identity.clone(); let harness_id = request.harness_id.clone(); + self.handoff_run(&scope.run_id); let expected_version = self .current_pin_version(&scope.session_id, &harness_id) .await @@ -2120,7 +2524,14 @@ impl AcpDelegationPolicy { None => CleanupProof::Lost, }; policy - .settle_after_cleanup(&scope, &harness_id, proof, Some(permit), expected_version) + .settle_after_cleanup( + &scope, + &harness_id, + &identity, + proof, + Some(permit), + expected_version, + ) .await; }); Ok(AcpDelegationResult::refusal( @@ -2132,15 +2543,17 @@ impl AcpDelegationPolicy { /// Settles a call whose prompt outcome was lost, using the cleanup proof. /// - /// The slot is released exactly once and only when the settlement itself - /// committed and cleanup was proven; otherwise the permit is parked in the - /// explicit 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. + /// 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, @@ -2159,16 +2572,29 @@ impl AcpDelegationPolicy { let harness_id_owned = harness_id.to_string(); let run_id = scope.run_id.clone(); let settled = self - .mutate(&scope.session_id, move |doc, _snapshot| { - let Some(call) = doc.calls.get_mut(&call_id) else { + .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(), @@ -2176,42 +2602,37 @@ impl AcpDelegationPolicy { truncated: false, code: Some(code.to_string()), }); - let mut lease_guard = None; - if let Some(pin) = doc.pins.get_mut(&harness_id_owned) { - 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 && !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; - pin.version += 1; - lease_guard = Some((harness_id_owned.clone(), call_id.clone())); - } else if owns { - pin.active = None; - pin.cleanup_pending = false; - pin.phase = if had_intent { - PinPhase::Unknown - } else { - PinPhase::Bound - }; - pin.version += 1; - lease_guard = Some((harness_id_owned.clone(), call_id.clone())); - } + 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 + }; } - Ok(lease_guard) + 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)) => drop(permit), - (_, _, Some(permit)) => self.quarantine_permit( + (true, true, Some(permit)) => { + drop(permit); + self.finish_run_handoff(&scope.run_id); + } + (_, _, Some(permit)) => self.quarantine_ownership( permit, + scope.run_id.clone(), format!("{}:{}", scope.session_id, harness_id), scope.tool_call_id.clone(), ), @@ -2230,9 +2651,14 @@ impl AcpDelegationPolicy { 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, @@ -2322,12 +2748,17 @@ impl AcpDelegationPolicy { /// 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 @@ -2341,7 +2772,9 @@ impl AcpDelegationPolicy { // 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. - let identity = snapshot.identity(); + 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 { @@ -2360,8 +2793,8 @@ impl AcpDelegationPolicy { }; let payload = json!({ "session_id": session_id, - "owner": identity.0, - "created_at_ms": identity.1, + "owner": identity.owner, + "created_at_ms": identity.created_at_ms, "expected_version": expected_version, "lease_path": lease_path, "lease_call": lease_call, @@ -2380,7 +2813,7 @@ impl AcpDelegationPolicy { .ok_or(AcpPolicyRefusal::Failed("acp_session_unknown"))?; let next = SessionSnapshot::from_row(row) .ok_or(AcpPolicyRefusal::Failed("acp_session_unknown"))?; - if next.identity() != identity { + if &next.identity() != identity { return Err(AcpPolicyRefusal::Denied("acp_session_identity_changed")); } snapshot = next; @@ -2435,18 +2868,35 @@ struct QuarantinedSlot { _permit: tokio::sync::OwnedSemaphorePermit, } -struct RunGate<'a> { - policy: &'a PolicyInner, +struct RunGate { + policy: Arc, run_id: String, } -impl Drop for RunGate<'_> { +impl RunGate { + fn new(policy: Arc, run_id: String) -> Self { + Self { policy, run_id } + } +} + +impl Drop for RunGate { fn drop(&mut self) { - self.policy - .per_run + // A handed-off or quarantined call keeps this run's admission slot + // until its cleanup owner settles it. Only the ordinary return path + // releases it here. + let handed_off = self + .policy + .per_run_handoff .lock() - .expect("acp per-run gate") - .remove(&self.run_id); + .expect("acp per-run handoff") + .contains(&self.run_id); + if !handed_off { + self.policy + .per_run + .lock() + .expect("acp per-run gate") + .remove(&self.run_id); + } } } @@ -2455,12 +2905,6 @@ enum PromptWait { Cancelled, } -/// Outcome of the synchronous decision immediately before process creation. -enum PreSpawnBarrier { - Proceed, - Refuse(AcpDelegationStatus, &'static str), -} - fn build_launch(harness: &AcpHarnessSettings) -> Result { if harness.args.len() > MAX_ACP_HARNESS_ARGUMENTS || harness.argument_bytes() > MAX_ACP_HARNESS_ARGUMENT_BYTES @@ -2544,11 +2988,21 @@ fn effective_deadline_ms(run_deadline_ms: Option, now_ms: u64) -> u64 { } } -fn effective_deadline(run_deadline_ms: Option) -> Instant { +fn frozen_deadline(facts: &AcpRunFacts) -> Instant { + let now = Instant::now(); let now_ms = crate::domain::timestamp(); - let deadline_ms = effective_deadline_ms(run_deadline_ms, now_ms); - let remaining = deadline_ms.saturating_sub(now_ms); - Instant::now() + Duration::from_millis(remaining) + 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( @@ -2615,10 +3069,9 @@ fn clamp_text(text: &mut String, budget: usize, truncated: &mut bool) { /// 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 at least a minimal successful -/// envelope fits. If an outcome is still too large with empty text, its static -/// diagnostic code is dropped first; the last resort is the minimal bounded -/// refusal, never an oversized result. +/// 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; @@ -2642,17 +3095,12 @@ fn bounded_result(mut result: AcpDelegationResult, budget: usize) -> AcpDelegati if envelope_len(&result) <= budget { return result; } - result.code = None; - result.truncated = true; - if envelope_len(&result) <= budget { - return result; - } budget_refusal_result(&result.harness_id, result.replayed) } -/// Smallest successful typed envelope for one harness: empty text, end turn, -/// and no diagnostic code. -fn minimal_success_envelope_bytes(harness_id: &str) -> usize { +/// 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, @@ -2662,7 +3110,18 @@ fn minimal_success_envelope_bytes(harness_id: &str) -> usize { None, false, ); - envelope_len(&result) + 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 @@ -2766,6 +3225,15 @@ fn admitted_workspace( }) } +/// 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 { @@ -2779,8 +3247,11 @@ 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) -> (String, i64) { - (self.owner.clone(), self.created_at_ms) + fn identity(&self) -> SessionIdentity { + SessionIdentity { + owner: self.owner.clone(), + created_at_ms: self.created_at_ms, + } } fn from_row(row: Vec) -> Option { @@ -2951,6 +3422,8 @@ impl CallPhase { struct AcpCallRecord { call_id: String, run_id: String, + #[serde(default)] + session_identity: SessionIdentity, harness_id: String, approval_id: String, #[serde(default)] @@ -2964,6 +3437,11 @@ struct AcpCallRecord { 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)] @@ -2974,6 +3452,8 @@ struct AcpCallRecord { struct ApprovalBinding { run_id: String, session_id: String, + #[serde(default)] + session_identity: SessionIdentity, tool_call_id: String, harness_id: String, task: String, diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs index dc0b1fd..5d8dc74 100644 --- a/tests/acp_delegation_policy_tests.rs +++ b/tests/acp_delegation_policy_tests.rs @@ -19,12 +19,13 @@ 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::AgentService; 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}; @@ -268,6 +269,53 @@ impl<'a> Runtime<'a> { 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) { + 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"); + 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!({ @@ -394,6 +442,117 @@ async fn wait_for(mut condition: impl FnMut() -> bool, label: &str) { } } +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") +} + +/// 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"); @@ -1466,9 +1625,10 @@ async fn unproven_cleanup_keeps_capacity_and_never_reports_success() { assert_eq!(runtime.policy.available_processes(), 3); assert_eq!(runtime.policy.quarantined_slots(), 1); - let next_scope = scope(&run, "call-2"); + let next_run = runtime.open_run(Some(&run.session_id)).await; + let next_scope = scope(&next_run, "call-2"); let witness = runtime - .approve(&run, &next_scope, &request("fixture", "next")) + .approve(&next_run, &next_scope, &request("fixture", "next")) .await; let next = runtime .policy @@ -2065,11 +2225,7 @@ async fn expired_run_clock_observed_at_the_spawn_barrier_is_zero_spawn() { 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.set_context_deadline_at_ms(&run_id, 1); - }); + runtime.service.set_context_deadline_at_ms(&run.run_id, 1); let result = runtime .policy .delegate(&call_scope, &request("fixture", "task"), &witness) @@ -2110,10 +2266,12 @@ async fn cleanup_in_progress_keeps_the_pin_and_blocks_a_second_spawn() { ); // The same pin must not start a second process while the real observer - // still holds its ownership. - let second_scope = scope(&run, "call-2"); + // 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(&run, &second_scope, &request("fixture", "second")) + .approve(&next_run, &second_scope, &request("fixture", "second")) .await; let second = runtime .policy @@ -2483,3 +2641,618 @@ async fn budget_truncation_stays_on_a_utf8_boundary() { <= 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] +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" + ); +} + +#[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/fixtures/acp_policy/policy_agent.rs b/tests/fixtures/acp_policy/policy_agent.rs index fc9e449..22e13f6 100644 --- a/tests/fixtures/acp_policy/policy_agent.rs +++ b/tests/fixtures/acp_policy/policy_agent.rs @@ -31,6 +31,7 @@ struct Config { caps: Option, reply: String, replay: String, + stop_reason: String, delay_ms: u64, init_delay_ms: u64, restore_delay_ms: u64, @@ -242,6 +243,7 @@ impl Harness { 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 || { @@ -249,7 +251,7 @@ impl Harness { std::thread::sleep(Duration::from_millis(delay)); } harness.agent_text(&session_id, &reply); - harness.respond_end_turn(&session_id, &prompt_id); + harness.respond_end_turn(&session_id, &prompt_id, &stop_reason); }); } @@ -298,12 +300,14 @@ impl FixtureHandle { })); } - fn respond_end_turn(&self, session_id: &str, id: &Value) { + 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": "end_turn" } })); + self.send( + json!({ "jsonrpc": "2.0", "id": id, "result": { "stopReason": stop_reason } }), + ); } } @@ -333,6 +337,12 @@ fn main() { .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") From 1fc159d30dafec5d737a68dea650a315ba014b62 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 18:22:29 +0800 Subject: [PATCH 21/27] test(acp-e2e): exercise three ordinary RSS runs across Gateway restart --- tests/acp_delegation_e2e_tests.rs | 978 +++++++++++++++++++++--------- 1 file changed, 699 insertions(+), 279 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index 3ab17ca..f85dfa5 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -9,11 +9,16 @@ //! `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: run 1 is admitted -//! over real HTTP, completed, and persisted; the Gateway is stopped and reaped -//! and its listener is closed; a second Gateway process on the same private -//! home/store admits a distinct run on the same RSS session, and its actual -//! model input contains the first turn's durable record. +//! 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}; @@ -25,6 +30,11 @@ 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::{ @@ -36,10 +46,6 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; const CHILD_ENTRY: &str = "gateway_harness_child_entry"; -/// The helper child entry that replaces itself with a process whose argument -/// vector is empty, so `/proc//cmdline` carries no text while the process -/// is still alive. -const EMPTY_CMDLINE_ENTRY: &str = "empty_cmdline_helper_entry"; const SPEC_ENV: &str = "RSS_ACP_DELEGATION_E2E_CHILD_SPEC"; const TOKEN_ENV: &str = "RSS_ACP_DELEGATION_E2E_CHILD_TOKEN"; @@ -47,11 +53,23 @@ 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 READY_BUDGET: Duration = Duration::from_secs(300); +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`) @@ -92,6 +110,72 @@ fn text_response(text: &str) -> Value { }) } +/// 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. +struct FixtureRun { + key: String, + answer: Value, +} + +impl FixtureRun { + fn new(label: &str, answer_marker: &str) -> Self { + Self { + key: format!("{label}-{}", uuid::Uuid::new_v4().simple()), + answer: text_response(answer_marker), + } + } +} + +/// 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"); + let scripted = ScriptedProvider::new(); + scripted.push_ok(run["answer"].clone()); + let recorder = RecordingProvider { + inner: scripted, + 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 @@ -210,6 +294,10 @@ impl ChildGuard { 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 @@ -688,7 +776,6 @@ struct HarnessChild { guard: ChildGuard, token: String, ready_path: PathBuf, - stdout_path: PathBuf, stderr_path: PathBuf, } @@ -697,10 +784,22 @@ fn spawn_harness_child( label: &str, db_path: &Path, ready_path: &Path, - responses: &[Value], + runs: &[FixtureRun], hold_before_ready_ms: u64, ) -> HarnessChild { - let transcript_path = fixture.root.join(format!("transcript-{label}.jsonl")); + let run_specs: Vec = runs + .iter() + .map(|run| { + json!({ + "key": run.key, + "answer": run.answer, + "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, @@ -708,8 +807,7 @@ fn spawn_harness_child( "db_path": db_path.to_string_lossy(), "workspace_home": fixture.home.to_string_lossy(), "ready_path": ready_path.to_string_lossy(), - "transcript_path": transcript_path.to_string_lossy(), - "responses": responses, + "runs": run_specs, "run_timeout_ms": RUN_BUDGET.as_millis() as u64, "hold_before_ready_ms": hold_before_ready_ms, }) @@ -718,9 +816,7 @@ fn spawn_harness_child( .expect("write child Gateway spec"); let token = format!("rss-acp-e2e-{}", uuid::Uuid::new_v4().simple()); - let stdout_path = fixture.root.join(format!("stdout-{label}.log")); let stderr_path = fixture.root.join(format!("stderr-{label}.log")); - let stdout = fs::File::create(&stdout_path).expect("create child stdout log"); let stderr = fs::File::create(&stderr_path).expect("create child stderr log"); let assigned_tmp = lease_tmp(); @@ -741,7 +837,7 @@ fn spawn_harness_child( .env(TOKEN_ENV, &token) .current_dir(&fixture.workspace) .stdin(Stdio::piped()) - .stdout(Stdio::from(stdout)) + .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. @@ -758,31 +854,28 @@ fn spawn_harness_child( guard, token, ready_path: ready_path.to_path_buf(), - stdout_path, stderr_path, } } -/// Spawns the empty-command-line helper as a real OS child of this test. The -/// child entry replaces itself with a program that has no argument vector and -/// then blocks on the piped stdin, so `/proc//cmdline` carries no text -/// while the process is still running. That is the same kernel observation -/// `exit_mm` produces for an exiting child, but it can be held open -/// deterministically until this test closes the pipe. +/// 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, label: &str) -> (ChildGuard, ChildIdentity) { +fn spawn_empty_cmdline_child(fixture: &GatewayFixture) -> (ChildGuard, ChildIdentity) { + use std::os::unix::process::CommandExt; + let assigned_tmp = lease_tmp(); - let log_path = fixture.root.join(format!("empty-cmdline-{label}.log")); - let stdout = fs::File::create(&log_path).expect("create empty-command-line child log"); - let stderr = stdout - .try_clone() - .expect("clone empty-command-line child log"); - let exe = std::env::current_exe().expect("current test executable"); - let mut command = Command::new(exe); - command - .args(["--exact", EMPTY_CMDLINE_ENTRY, "--ignored", "--nocapture"]) + 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("PATH", std::env::var_os("PATH").unwrap_or_default()) .env("TMPDIR", &assigned_tmp) .env("TMP", &assigned_tmp) .env("TEMP", &assigned_tmp) @@ -791,47 +884,37 @@ fn spawn_empty_cmdline_child(fixture: &GatewayFixture, label: &str) -> (ChildGua .env("RUSTSCRIPT_AGENT_TEST_TMPDIR", &assigned_tmp) .current_dir(&fixture.root) .stdin(Stdio::piped()) - .stdout(Stdio::from(stdout)) - .stderr(Stdio::from(stderr)); - let child = command + .stdout(Stdio::null()) + .stderr(Stdio::null()) .spawn() .expect("the empty-command-line helper must spawn"); - // Ownership moves to the guard before any readiness work can fail. - let guard = ChildGuard::new(child); + let mut guard = ChildGuard::new(child); let identity = ChildIdentity::capture(guard.pid()) .expect("the empty-command-line helper must have a spawn identity"); - (guard, identity) -} - -/// Waits until the helper is provably this exact child, still running (`Z` is -/// never acceptable), with an argument vector that carries no text at all. -#[cfg(unix)] -fn await_no_command_line(identity: &ChildIdentity, label: &str) { + // `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 { - let stat = read_proc_stat(identity.pid); - let cmdline = fs::read(format!("/proc/{}/cmdline", identity.pid)).ok(); - let alive = stat.is_some_and(|stat| { - stat.state != 'Z' - && stat.ppid == std::process::id() - && stat.start_time == identity.start_time - }); - let no_text = cmdline - .as_ref() - .is_some_and(|cmdline| cmdline.iter().all(|byte| *byte == 0)); - if alive && no_text { - return; - } assert!( - !stat.is_some_and(|stat| stat.state == 'Z'), - "{label} exited before it ever showed an empty command line; the helper could not replace itself" + 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!( - Instant::now() < deadline, - "{label} must become a live exact child without command-line text; last stat {stat:?}, command-line length {:?}", - cmdline.as_ref().map(Vec::len) + now < deadline, + "the helper must start with no command-line text" ); - std::thread::sleep(Duration::from_millis(2)); + std::thread::sleep(RECLAIM_POLL.min(deadline - now)); } } @@ -873,8 +956,11 @@ struct GatewayProcess { child: ChildGuard, address: SocketAddr, token: String, - stdout_path: PathBuf, 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 { @@ -889,8 +975,8 @@ impl std::fmt::Debug for GatewayProcess { } impl GatewayProcess { - fn start(fixture: &GatewayFixture, label: &str, responses: &[Value]) -> Self { - Self::start_bounded(fixture, label, responses, READY_BUDGET, 0) + 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 @@ -901,7 +987,7 @@ impl GatewayProcess { fn start_bounded( fixture: &GatewayFixture, label: &str, - responses: &[Value], + runs: &[FixtureRun], budget: Duration, hold_before_ready_ms: u64, ) -> Self { @@ -909,7 +995,7 @@ impl GatewayProcess { match Self::start_with_budget_at( fixture, label, - responses, + runs, ready_path, fixture.db_path.clone(), budget, @@ -926,7 +1012,7 @@ impl GatewayProcess { fn start_with_budget_at( fixture: &GatewayFixture, label: &str, - responses: &[Value], + runs: &[FixtureRun], ready_path: PathBuf, db_path: PathBuf, budget: Duration, @@ -937,17 +1023,35 @@ impl GatewayProcess { label, &db_path, &ready_path, - responses, + runs, hold_before_ready_ms, ); let HarnessChild { mut guard, token, ready_path, - stdout_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() { @@ -985,8 +1089,8 @@ impl GatewayProcess { child: guard, address, token, - stdout_path, stderr_path, + control, }); } if Instant::now() >= deadline { @@ -1066,54 +1170,171 @@ impl GatewayProcess { Ok((status, body)) } - /// Reads one run's SSE stream until the named event is observed. Reconnects - /// and replays from the beginning because a subscription made before the - /// live sender exists may end after partial history. - async fn await_event(&self, run_id: &str, event: &str) -> String { - let deadline = Instant::now() + RUN_BUDGET; - let needle = format!("\"event\":\"{event}\""); - let mut collected = String::new(); + /// 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 { - if collected.contains(&needle) { - return collected; - } assert!( Instant::now() < deadline, - "run {run_id} did not emit {event}: {collected}\nstderr: {}", + "the child did not acknowledge provider {key} within {ACK_BUDGET:?}: {}", self.stderr() ); - let attempt_deadline = (Instant::now() + Duration::from_secs(4)).min(deadline); - if let Ok(Ok(mut stream)) = - tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(self.address)).await - { - let request = format!( - "GET /v1/runs/{run_id}/events HTTP/1.1\r\nHost: {}\r\nAuthorization: Bearer {}\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n", - self.address, self.token - ); - if stream.write_all(request.as_bytes()).await.is_ok() { - loop { - if collected.contains(&needle) || Instant::now() >= attempt_deadline { - break; - } - let mut chunk = [0_u8; 4096]; - match tokio::time::timeout( - Duration::from_millis(200), - stream.read(&mut chunk), - ) - .await - { - Ok(Ok(0)) => break, - Ok(Ok(read)) => { - collected.extend(String::from_utf8_lossy(&chunk[..read]).chars()) - } - Ok(Err(_)) => break, - Err(_) => {} + 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, } - if !collected.contains(&needle) { - tokio::time::sleep(Duration::from_millis(50)).await; + } + } + + /// 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)); + } } } } @@ -1134,9 +1355,8 @@ impl GatewayProcess { Ok(Some(status)) => { assert!( status.success(), - "Gateway harness did not exit cleanly ({status}): {}\n{}", - self.stderr(), - fs::read_to_string(&self.stdout_path).unwrap_or_default() + "Gateway harness did not exit cleanly ({status}): {}", + self.stderr() ); break; } @@ -1180,8 +1400,136 @@ impl GatewayProcess { } } -fn transcript_requests(fixture: &GatewayFixture, label: &str) -> Vec { - let path = fixture.root.join(format!("transcript-{label}.jsonl")); +/// 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() @@ -1203,6 +1551,20 @@ fn message_text(message: &Value) -> String { .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( @@ -1260,9 +1622,10 @@ async fn gateway_harness_child_entry() { 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 transcript_path = spec["transcript_path"] - .as_str() - .expect("child transcript 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 @@ -1311,30 +1674,15 @@ async fn gateway_harness_child_entry() { ) .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. state .service() .set_provider_profile(ProviderProfile::builtin("local-agent").expect("local-agent profile")) .expect("install the local-agent provider profile"); - let scripted = ScriptedProvider::new(); - if let Some(responses) = spec["responses"].as_array() { - for response in responses { - scripted.push_ok(response.clone()); - } - } - let recorder = RecordingProvider { - inner: scripted, - transcript: Mutex::new( - fs::File::create(transcript_path).expect("create provider transcript"), - ), - }; - // This provider override is one-shot per process: a future test that runs - // two main-model turns in one Gateway process must supply a new host - // instead of assuming this injected one is reused. - state - .service() - .inject_provider_host(std::sync::Arc::new(recorder)); - let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) .await .expect("bind real loopback Gateway listener"); @@ -1349,6 +1697,7 @@ async fn gateway_harness_child_entry() { .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 { @@ -1358,11 +1707,16 @@ async fn gateway_harness_child_entry() { let _ = shutdown_tx.send(()); return; } - Ok(_) if line.trim() == "shutdown" => { - 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()); + } } - Ok(_) => {} Err(_) => { let _ = shutdown_tx.send(()); return; @@ -1410,9 +1764,29 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { "acp-delegation-e2e-session-{}", uuid::Uuid::new_v4().simple() ); - - // ---- First Gateway OS process: create/bind the session and run turn 1. ---- - let first = GatewayProcess::start(&fixture, "first", &[text_response(FIRST_ANSWER_MARKER)]); + 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")); @@ -1420,54 +1794,89 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { create_session(&first, &session_id).await; bind_workspace(&first, &session_id).await; - let first_prompt = format!("{FIRST_PROMPT_MARKER}: note the durable first turn."); - let first_run = admit_run(&first, &session_id, &first_prompt).await; - let first_events = first.await_event(&first_run, "run.completed").await; - assert!( - first_events.contains("run.completed") && first_events.contains(FIRST_ANSWER_MARKER), - "first turn must complete with the fixture answer: {first_events}" - ); - // The first process's real model input and the durable user record. - let first_requests = transcript_requests(&fixture, "first"); - assert_eq!( - first_requests.len(), - 1, - "one plain Q&A turn must make exactly one provider call: {first_requests:?}" - ); - let first_request = &first_requests[0]["request"]; - assert_eq!(first_request["provider"], json!("local-agent")); - assert!( - first_request.to_string().contains(FIRST_PROMPT_MARKER), - "the first model input must carry the first prompt: {first_request}" - ); - let (status, messages) = first - .request("GET", &format!("/api/sessions/{session_id}/messages"), None) - .await - .expect("first Gateway session messages"); - assert_eq!(status, 200, "first session messages: {messages}"); - let user_messages: Vec = messages["data"] - .as_array() - .expect("session message list") - .iter() - .filter(|message| message["role"] == json!("user")) - .cloned() - .collect(); - assert_eq!( - user_messages.len(), - 1, - "first turn user message: {messages}" - ); - assert!( - message_text(&user_messages[0]).contains(FIRST_PROMPT_MARKER), - "the first user turn must be durably recorded: {messages}" - ); + 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")); + 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 second = GatewayProcess::start(&fixture, "second", &[text_response(SECOND_ANSWER_MARKER)]); + 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"); @@ -1479,80 +1888,124 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { assert_eq!(status, 200, "reopened session: {reopened_session}"); assert_persisted_workspace(&reopened_session, &fixture); - // Run 1's durable terminal record is readable from the fresh process. - let persisted_events = second.await_event(&first_run, "run.completed").await; - assert!( - persisted_events.contains(FIRST_ANSWER_MARKER), - "the first turn output must survive the process restart: {persisted_events}" - ); + // 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 + ); + } + } + } - let second_prompt = format!("{SECOND_PROMPT_MARKER}: continue from the durable session."); - let second_run = admit_run(&second, &session_id, &second_prompt).await; - assert_ne!( - first_run, second_run, + 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 second_events = second.await_event(&second_run, "run.completed").await; + 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!( - second_events.contains(SECOND_ANSWER_MARKER), - "second turn must complete with its own fixture answer: {second_events}" + 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 OS process's actual model input contains - // the first turn's durable record and the new prompt, and nothing from the - // second answer script leaks backwards. - let second_requests = transcript_requests(&fixture, "second"); + // 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!( - second_requests.len(), + third_requests.len(), 1, - "the second plain turn must make exactly one provider call: {second_requests:?}" - ); - let second_request = &second_requests[0]["request"]; - let wire = second_request.to_string(); - assert!( - wire.contains(FIRST_PROMPT_MARKER), - "the restarted Gateway model input must include the first turn record: {second_request}" + "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!( - wire.contains(SECOND_PROMPT_MARKER), - "the restarted Gateway model input must include the new prompt: {second_request}" + !third_wire.contains(THIRD_ANSWER_MARKER), + "the third model input must not already contain its own future answer: {third_request}" ); - assert!( - !wire.contains(SECOND_ANSWER_MARKER), - "the model input must not already contain its own future answer: {second_request}" - ); - let wire_messages = second_request["messages"] - .as_array() - .expect("model input messages"); - let wire_user_texts: Vec = wire_messages - .iter() - .filter(|message| message["role"] == json!("user")) - .map(message_text) - .collect(); + 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!( - wire_user_texts.len(), - 2, - "two persisted user turns must reach the second model call: {second_request}" + third_user_texts.len(), + 3, + "three persisted user turns must reach the third model call: {third_request}" ); - assert!(wire_user_texts[0].contains(FIRST_PROMPT_MARKER)); - assert!(wire_user_texts[1].contains(SECOND_PROMPT_MARKER)); + 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 roles: Vec<&str> = messages["data"] + let user_messages: Vec<&Value> = messages["data"] .as_array() .expect("session message list") .iter() - .filter_map(|message| message["role"].as_str()) + .filter(|message| message["role"] == json!("user")) .collect(); assert_eq!( - roles.iter().filter(|role| **role == "user").count(), - 2, - "both user turns must be persisted: {messages}" + 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(); } @@ -1587,29 +2040,6 @@ fn panic_text(payload: Box) -> String { } } -/// Helper process for the empty-command-line regression. It replaces itself -/// with `cat` whose argument vector is empty (`argc == 0`) and whose -/// environment is empty, so `/proc//cmdline` carries no text while the -/// process stays alive blocked on its stdin pipe. The parent closes that pipe -/// when it wants the exact child to exit, which makes the "command line is -/// already gone, terminal state is not published yet" transient reproducible -/// without depending on kernel scheduling after a signal. -#[cfg(unix)] -#[test] -#[ignore = "helper process launched by the empty-command-line regression"] -fn empty_cmdline_helper_entry() { - // Only `/bin/cat` and `/usr/bin/cat` are tried; either one blocks reading - // stdin with no file operands and exits 0 on EOF. - let argv: [*const libc::c_char; 1] = [std::ptr::null()]; - let envp: [*const libc::c_char; 1] = [std::ptr::null()]; - for program in ["/bin/cat\0", "/usr/bin/cat\0"] { - unsafe { - libc::execve(program.as_ptr().cast(), argv.as_ptr(), envp.as_ptr()); - } - } - std::process::exit(127); -} - /// 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 @@ -2026,22 +2456,16 @@ async fn gateway_startup_failure_reclaims_the_real_child() { // 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 replaces itself with a program that has - // an empty argument vector and then blocks on its stdin pipe. `/proc` + // 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, "no-command-line"); + 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" ); - await_no_command_line(&free_identity, "the empty-command-line child"); - assert_eq!( - free_identity.exact_state(), - ExactChild::NoCommandLine, - "the fallback's own first observation must be a live, non-`Z` child without command-line text" - ); let mut free_stdin = Some( free_child .take_stdin() @@ -2096,10 +2520,8 @@ async fn gateway_startup_failure_reclaims_the_real_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, "no-command-line-stuck"); + let (mut stuck_child, stuck_identity) = spawn_empty_cmdline_child(&fixture); let stuck_pid = stuck_child.pid(); - await_no_command_line(&stuck_identity, "the stuck empty-command-line child"); let mut stuck_states = 0usize; let mut on_wait = |state: char| { assert_ne!( @@ -2235,10 +2657,8 @@ fn gateway_fallback_refuses_waitpid_after_wait_only_deadline() { // 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, "wait-only-deadline"); + let (mut zombie_child, zombie_identity) = spawn_empty_cmdline_child(&fixture); let zombie_pid = zombie_child.pid(); - await_no_command_line(&zombie_identity, "the deadline wait-only child"); drop( zombie_child .take_stdin() From abb0c5bbc7f6c3e75971ce52ea12b42dc018a69e Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 18:30:35 +0800 Subject: [PATCH 22/27] fix(acp): complete gateway delegation approval and cleanup policy --- src/acp/delegated_client.rs | 101 +++- src/gateway/telegram.rs | 38 +- src/runtime/rss_runner.rs | 12 + src/service.rs | 4 + src/service/acp_session_pins.rs | 515 +++++++++++------- tests/acp_delegation_policy_tests.rs | 627 +++++++++++++++++++++- tests/fixtures/acp_policy/policy_agent.rs | 7 + 7 files changed, 1079 insertions(+), 225 deletions(-) diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 7fc01dc..946db81 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -361,6 +361,30 @@ pub struct DelegatedAcpClient { 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. /// @@ -384,7 +408,36 @@ impl DelegatedAcpClient { launch: AcpDelegationLaunch, deadline: Instant, ) -> Result { - Self::spawn_with_stdin(launch, deadline, |stdin| Box::new(stdin)) + 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. @@ -398,29 +451,40 @@ impl DelegatedAcpClient { deadline: Instant, wrap_stdin: impl FnOnce(ChildStdin) -> StdinWriter, ) -> Result { - Self::spawn_with_stdin(launch, deadline, wrap_stdin) + 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, - ) -> Result { + precondition: Option Result<(), AcpLaunchVeto> + Send>>, + ) -> Result { if Instant::now() >= deadline { - return Err(AcpDelegationError::DeadlineExceeded); + 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(AcpDelegationError::CleanupUnsupported); + return Err(SpawnFailure::Error(AcpDelegationError::CleanupUnsupported)); } - let mut child = OwnedChild::spawn(&launch).map_err(|_| AcpDelegationError::SpawnFailed)?; + 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(|_| AcpDelegationError::SpawnFailed)?; + .map_err(|_| SpawnFailure::Error(AcpDelegationError::SpawnFailed))?; let (command_tx, command_rx) = mpsc::channel(1); let (shutdown_tx, shutdown_rx) = watch::channel(false); @@ -2467,8 +2531,18 @@ 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) -> io::Result { + fn spawn( + launch: &AcpDelegationLaunch, + precondition: Option Result<(), AcpLaunchVeto> + Send>>, + ) -> Result { let mut command = Command::new(launch.command()); command .args(launch.arguments()) @@ -2488,10 +2562,13 @@ impl OwnedChild { } #[cfg(unix)] command.process_group(0); - let child = command.spawn()?; - let pid = child - .id() - .ok_or_else(|| io::Error::other("harness pid unavailable"))?; + // 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, diff --git a/src/gateway/telegram.rs b/src/gateway/telegram.rs index 8f33f84..c524434 100644 --- a/src/gateway/telegram.rs +++ b/src/gateway/telegram.rs @@ -2629,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 { @@ -2652,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 { diff --git a/src/runtime/rss_runner.rs b/src/runtime/rss_runner.rs index 116752f..c9250ec 100644 --- a/src/runtime/rss_runner.rs +++ b/src/runtime/rss_runner.rs @@ -1137,6 +1137,9 @@ pub(crate) struct WorkspaceAuthority { /// 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 { @@ -1169,6 +1172,7 @@ impl WorkspaceAuthority { .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(); } @@ -1177,6 +1181,13 @@ impl WorkspaceAuthority { 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. @@ -1595,6 +1606,7 @@ impl AgentRunner { 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( diff --git a/src/service.rs b/src/service.rs index 4f8b6e2..b2e1aa5 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1877,6 +1877,10 @@ impl acp_session_pins::AcpWorkspaceAuthority for RunWorkspaceAuthority { 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 diff --git a/src/service/acp_session_pins.rs b/src/service/acp_session_pins.rs index 8d28ae9..79bb085 100644 --- a/src/service/acp_session_pins.rs +++ b/src/service/acp_session_pins.rs @@ -46,6 +46,7 @@ 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; @@ -232,6 +233,15 @@ pub trait AcpWorkspaceAuthority: Send + Sync { /// 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. @@ -372,10 +382,7 @@ struct PolicyInner { /// 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: Mutex>, - /// Runs whose per-run admission was handed to a cleanup owner (or to - /// quarantine). `RunGate::drop` must not release those. - per_run_handoff: Mutex>, + per_run: Arc>>, gates: Mutex>>>, #[cfg(feature = "workspace-io-fault")] fault: Mutex, @@ -440,8 +447,7 @@ impl AcpDelegationPolicy { max_result_bytes, quota: Arc::new(Semaphore::new(MAX_ACTIVE_PROCESSES)), quarantine: Mutex::new(Vec::new()), - per_run: Mutex::new(HashSet::new()), - per_run_handoff: Mutex::new(HashSet::new()), + per_run: Arc::new(Mutex::new(HashSet::new())), gates: Mutex::new(HashMap::new()), #[cfg(feature = "workspace-io-fault")] fault: Mutex::new(AcpPolicyFault::None), @@ -729,6 +735,13 @@ impl AcpDelegationPolicy { /// 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, @@ -744,11 +757,32 @@ impl AcpDelegationPolicy { "acp_delegation_budget", ); } - let result = match self.delegate_inner(scope, request, witness).await { - Ok(result) => result, - Err(refusal) => { + 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) } @@ -758,6 +792,7 @@ impl AcpDelegationPolicy { scope: &AcpDelegationScope, request: &AcpDelegationRequest, witness: &AcpApprovalWitness, + abandoned: &Arc, ) -> Result { validate_request(request)?; let Some(launch) = self.inner.harnesses.get(&request.harness_id) else { @@ -772,13 +807,6 @@ impl AcpDelegationPolicy { 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 cancellation = facts.cancellation.clone(); // 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. @@ -791,6 +819,7 @@ impl AcpDelegationPolicy { .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)); @@ -810,7 +839,14 @@ impl AcpDelegationPolicy { return Err(AcpPolicyRefusal::Busy("acp_delegation_busy")); } } - let _run_guard = RunGate::new(Arc::clone(&self.inner), scope.run_id.clone()); + 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 { @@ -1078,17 +1114,19 @@ impl AcpDelegationPolicy { ) .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, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } @@ -1204,6 +1242,7 @@ impl AcpDelegationPolicy { &workspace, launch_handle, deadline, + Arc::clone(abandoned), ) .await { @@ -1230,12 +1269,27 @@ impl AcpDelegationPolicy { &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 @@ -1255,6 +1309,7 @@ impl AcpDelegationPolicy { workspace: &AdmittedWorkspace, launch: AcpDelegationLaunch, deadline: Instant, + abandoned: Arc, ) -> Result< Result, AcpPolicyRefusal, @@ -1377,9 +1432,45 @@ impl AcpDelegationPolicy { if let Some(hook) = fence_hook { hook(); } - match crate::acp::DelegatedAcpClient::spawn(launch, deadline) { + // 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(error) => Ok(Err((AcpDelegationStatus::Failed, error.code()))), + 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 @@ -1395,7 +1486,7 @@ impl AcpDelegationPolicy { request: &AcpDelegationRequest, identity: &SessionIdentity, snapshot: SessionSnapshot, - permit: tokio::sync::OwnedSemaphorePermit, + permit: CallPermit, status: AcpDelegationStatus, code: &'static str, ) -> Result { @@ -1412,16 +1503,11 @@ impl AcpDelegationPolicy { .await { Ok(result) => { - drop(permit); + permit.release(); Ok(result) } Err(_) => { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) } } @@ -1436,22 +1522,24 @@ impl AcpDelegationPolicy { identity: &SessionIdentity, mut client: DelegatedAcpClient, cancellation: crate::runtime::rss_runner::RunCancellation, + workspace: Option>, snapshot: &mut SessionSnapshot, - permit: tokio::sync::OwnedSemaphorePermit, + 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; - _ = cancellation.cancelled() => None, - result = &mut future => Some(result), + interruption = delegation_interrupted(&cancellation, &mut revocation) => Err(interruption), + result = &mut future => Ok(result), } }; let capabilities = match capabilities { - None => { + Err(interruption) => { return self .unsent_close( scope, @@ -1461,14 +1549,14 @@ impl AcpDelegationPolicy { client, observer, permit, - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", + interruption.status(), + interruption.code(), true, ) .await; } - Some(Ok(capabilities)) => capabilities, - Some(Err(error)) => { + Ok(Ok(capabilities)) => capabilities, + Ok(Err(error)) => { return self .unsent_close( scope, @@ -1517,9 +1605,20 @@ impl AcpDelegationPolicy { .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 - .abort_unknown_state( - scope, request, identity, snapshot, client, observer, permit, + .unsent_close( + scope, + request, + identity, + snapshot, + client, + observer, + permit, + AcpDelegationStatus::Failed, + "acp_storage_not_committed", + true, ) .await; } @@ -1528,12 +1627,12 @@ impl AcpDelegationPolicy { tokio::pin!(future); tokio::select! { biased; - _ = cancellation.cancelled() => None, - result = &mut future => Some(result), + interruption = delegation_interrupted(&cancellation, &mut revocation) => Err(interruption), + result = &mut future => Ok(result), } }; match restored { - None => { + Err(interruption) => { return self .unsent_close( scope, @@ -1543,13 +1642,13 @@ impl AcpDelegationPolicy { client, observer, permit, - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", + interruption.status(), + interruption.code(), true, ) .await; } - Some(Err(error)) => { + Ok(Err(error)) => { // A failed restore never falls back to `session/new`. return self .unsent_close( @@ -1566,7 +1665,7 @@ impl AcpDelegationPolicy { ) .await; } - Some(Ok(_)) => { + Ok(Ok(_)) => { #[cfg(feature = "workspace-io-fault")] if self.take_fault(AcpPolicyFault::AfterRestoreBeforeIntent) { let report = client.close().await; @@ -1576,14 +1675,9 @@ impl AcpDelegationPolicy { .await .is_ok() { - drop(permit); + permit.release(); } else { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); } return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } @@ -1607,12 +1701,12 @@ impl AcpDelegationPolicy { tokio::pin!(future); tokio::select! { biased; - _ = cancellation.cancelled() => None, - result = &mut future => Some(result), + interruption = delegation_interrupted(&cancellation, &mut revocation) => Err(interruption), + result = &mut future => Ok(result), } }; let created = match created { - None => { + Err(interruption) => { return self .unsent_close( scope, @@ -1622,14 +1716,14 @@ impl AcpDelegationPolicy { client, observer, permit, - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", + interruption.status(), + interruption.code(), false, ) .await; } - Some(Ok(created)) => created, - Some(Err(error)) => { + Ok(Ok(created)) => created, + Ok(Err(error)) => { return self .fail_created_unknown( scope, @@ -1650,12 +1744,7 @@ impl AcpDelegationPolicy { // 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, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } if created.is_empty() || created.len() > MAX_EXTERNAL_SESSION_ID_BYTES { @@ -1684,14 +1773,9 @@ impl AcpDelegationPolicy { .await .is_ok() { - drop(permit); + permit.release(); } else { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); } return Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")); } @@ -1699,7 +1783,7 @@ impl AcpDelegationPolicy { } }; - if cancellation.requested().is_some() { + if let Some(interruption) = current_interruption(&cancellation, &revocation) { return self .unsent_close( scope, @@ -1709,8 +1793,8 @@ impl AcpDelegationPolicy { client, observer, permit, - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", + interruption.status(), + interruption.code(), true, ) .await; @@ -1738,7 +1822,7 @@ impl AcpDelegationPolicy { } // 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 cancellation.requested().is_some() { + if let Some(interruption) = current_interruption(&cancellation, &revocation) { return self .unsent_close( scope, @@ -1748,8 +1832,8 @@ impl AcpDelegationPolicy { client, observer, permit, - AcpDelegationStatus::Cancelled, - "acp_delegation_cancelled", + interruption.status(), + interruption.code(), false, ) .await; @@ -1760,7 +1844,7 @@ impl AcpDelegationPolicy { tokio::pin!(prompt); tokio::select! { biased; - _ = cancellation.cancelled() => PromptWait::Cancelled, + interruption = delegation_interrupted(&cancellation, &mut revocation) => PromptWait::Interrupted(interruption), result = &mut prompt => PromptWait::Done(result), } }; @@ -1819,7 +1903,7 @@ impl AcpDelegationPolicy { let _ = self .mark_pin_unknown(scope, request, identity, snapshot) .await; - drop(permit); + permit.release(); return Err(AcpPolicyRefusal::Failed("acp_prompt_indeterminate")); } let mut text = result.text; @@ -1854,7 +1938,18 @@ impl AcpDelegationPolicy { }, false, ), - PromptWait::Done(Err(AcpDelegationError::Cancelled)) | PromptWait::Cancelled => ( + 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(), @@ -1888,16 +1983,11 @@ impl AcpDelegationPolicy { .await { Ok(result) => { - drop(permit); + permit.release(); Ok(result) } Err(_) => { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) } } @@ -1913,7 +2003,7 @@ impl AcpDelegationPolicy { snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, - permit: tokio::sync::OwnedSemaphorePermit, + permit: CallPermit, status: AcpDelegationStatus, code: &'static str, keeps_binding: bool, @@ -1944,16 +2034,11 @@ impl AcpDelegationPolicy { .await { Ok(result) => { - drop(permit); + permit.release(); Ok(result) } Err(_) => { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) } } @@ -1969,7 +2054,7 @@ impl AcpDelegationPolicy { snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, - permit: tokio::sync::OwnedSemaphorePermit, + permit: CallPermit, code: &'static str, ) -> Result { let report = client.close().await; @@ -1990,16 +2075,11 @@ impl AcpDelegationPolicy { .await { Ok(result) => { - drop(permit); + permit.release(); Ok(result) } Err(_) => { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) } } @@ -2015,7 +2095,7 @@ impl AcpDelegationPolicy { snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, - permit: tokio::sync::OwnedSemaphorePermit, + permit: CallPermit, ) -> Result { self.fail_created_unknown( scope, @@ -2044,7 +2124,7 @@ impl AcpDelegationPolicy { snapshot: &mut SessionSnapshot, client: DelegatedAcpClient, observer: crate::acp::AcpCleanupObserver, - permit: tokio::sync::OwnedSemaphorePermit, + permit: CallPermit, ) -> Result { let report = client.close().await; if !report.cleanup_confirmed { @@ -2064,16 +2144,11 @@ impl AcpDelegationPolicy { .await { Ok(_) => { - drop(permit); + permit.release(); Err(AcpPolicyRefusal::Failed("acp_session_indeterminate")) } Err(_) => { - self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, request.harness_id), - scope.tool_call_id.clone(), - ); + self.quarantine_ownership(permit); Err(AcpPolicyRefusal::Failed("acp_storage_not_committed")) } } @@ -2437,44 +2512,10 @@ impl AcpDelegationPolicy { /// 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: tokio::sync::OwnedSemaphorePermit, - run_id: String, - pin_key: String, - call_id: String, - ) { - self.handoff_run(&run_id); - self.inner - .quarantine - .lock() - .expect("acp quarantine") - .push(QuarantinedSlot { - pin_key, - call_id, - _permit: permit, - }); - } - - fn handoff_run(&self, run_id: &str) { - self.inner - .per_run_handoff - .lock() - .expect("acp per-run handoff") - .insert(run_id.to_string()); - } - - fn finish_run_handoff(&self, run_id: &str) { - self.inner - .per_run_handoff - .lock() - .expect("acp per-run handoff") - .remove(run_id); - self.inner - .per_run - .lock() - .expect("acp per-run gate") - .remove(run_id); + 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. @@ -2494,13 +2535,12 @@ impl AcpDelegationPolicy { request: &AcpDelegationRequest, identity: &SessionIdentity, observer: crate::acp::AcpCleanupObserver, - permit: tokio::sync::OwnedSemaphorePermit, + permit: CallPermit, ) -> Result { let policy = self.clone(); let scope = scope.clone(); let identity = identity.clone(); let harness_id = request.harness_id.clone(); - self.handoff_run(&scope.run_id); let expected_version = self .current_pin_version(&scope.session_id, &harness_id) .await @@ -2555,7 +2595,7 @@ impl AcpDelegationPolicy { harness_id: &str, identity: &SessionIdentity, proof: CleanupProof, - permit: Option, + permit: Option, expected_version: u64, ) -> bool { let confirmed = match &proof { @@ -2627,15 +2667,9 @@ impl AcpDelegationPolicy { // The single proven release: settlement committed and the // supervisor proved that no owned process remains. (true, true, Some(permit)) => { - drop(permit); - self.finish_run_handoff(&scope.run_id); + permit.release(); } - (_, _, Some(permit)) => self.quarantine_ownership( - permit, - scope.run_id.clone(), - format!("{}:{}", scope.session_id, harness_id), - scope.tool_call_id.clone(), - ), + (_, _, Some(permit)) => self.quarantine_ownership(permit), (_, _, None) => {} } committed && confirmed @@ -2865,44 +2899,149 @@ enum CleanupProof { struct QuarantinedSlot { pin_key: String, call_id: String, - _permit: tokio::sync::OwnedSemaphorePermit, + _admission: CallAdmission, } -struct RunGate { +/// 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, - run_id: String, + 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, + }); + } } -impl RunGate { - fn new(policy: Arc, run_id: String) -> Self { - Self { policy, run_id } +/// 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) { - // A handed-off or quarantined call keeps this run's admission slot - // until its cleanup owner settles it. Only the ordinary return path - // releases it here. - let handed_off = self - .policy - .per_run_handoff + self.runs .lock() - .expect("acp per-run handoff") - .contains(&self.run_id); - if !handed_off { - self.policy - .per_run - .lock() - .expect("acp per-run gate") - .remove(&self.run_id); + .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), - Cancelled, + Interrupted(DelegationInterruption), } fn build_launch(harness: &AcpHarnessSettings) -> Result { diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs index 5d8dc74..d623b4e 100644 --- a/tests/acp_delegation_policy_tests.rs +++ b/tests/acp_delegation_policy_tests.rs @@ -209,6 +209,18 @@ fn binary_path() -> PathBuf { .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)] @@ -224,15 +236,7 @@ impl<'a> Runtime<'a> { } fn open_with(env: &'a Env, config: ConfigFile, reviewer: &str) -> Self { - 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"); + 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()) @@ -271,15 +275,7 @@ impl<'a> Runtime<'a> { /// A state that also exposes the real bearer-authenticated HTTP API. fn open_http(env: &'a Env, reviewer: &str, token: &str) -> (Self, String) { - 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"); + 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()); @@ -383,6 +379,36 @@ impl<'a> Runtime<'a> { } } +// 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) @@ -2714,6 +2740,289 @@ async fn guardian_reviewer_reaches_real_human_pending_then_executes() { 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"); @@ -3100,6 +3409,288 @@ async fn concurrent_stop_losing_the_spawn_race_is_cancelled_after_start() { ); } +#[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"); diff --git a/tests/fixtures/acp_policy/policy_agent.rs b/tests/fixtures/acp_policy/policy_agent.rs index 22e13f6..00e5dfd 100644 --- a/tests/fixtures/acp_policy/policy_agent.rs +++ b/tests/fixtures/acp_policy/policy_agent.rs @@ -405,4 +405,11 @@ fn main() { _ => {} } } + if let Some(release) = argument(&args, "--eof-release") { + harness.record("stdin/eof", json!({"pid": std::process::id()})); + 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)); + } + } } From e8b76164fbc40c0a7b3a2934d5095eb7be089cb6 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 20:14:19 +0800 Subject: [PATCH 23/27] Wire approved ACP delegation into the bundled RSS Gateway loop --- docs/acp-delegation.md | 12 +- docs/acp-mode.md | 9 +- docs/configuration.md | 13 +- docs/deployment.md | 2 +- docs/status.md | 2 +- release/rss-production.txt | 1 + rss/agent/main.rss | 8 +- rss/tools/delegate_acp.rss | 37 ++ src/runtime/agent_host.rs | 36 +- src/runtime/rss_runner.rs | 13 + src/service.rs | 168 +++++- src/service/acp_session_pins.rs | 190 +++++++ src/tool_schema.rs | 21 +- tests/acp_delegation_e2e_tests.rs | 645 +++++++++++++++++++++- tests/fixtures/acp_policy/policy_agent.rs | 7 +- tests/mcp_catalog_tests.rs | 17 + tests/release_packaging_tests.rs | 2 +- 17 files changed, 1134 insertions(+), 49 deletions(-) create mode 100644 rss/tools/delegate_acp.rss diff --git a/docs/acp-delegation.md b/docs/acp-delegation.md index 1609203..8ec2b3c 100644 --- a/docs/acp-delegation.md +++ b/docs/acp-delegation.md @@ -13,17 +13,15 @@ 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. -> **Status on this branch.** The delegation capability is a feature-branch -> candidate. The `docs/` text below is the agreed contract for that feature; -> this checkout's default tool registry, `ConfigFile` loader, gateway -> assembly, and MCP six-tool surface are unchanged, and an `acp_harnesses` -> key is rejected by the current loader until the implementing change lands. -> Nothing in this page is part of the v0.1.0 product claim. +> **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 does. +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 diff --git a/docs/acp-mode.md b/docs/acp-mode.md index ebec3f2..423cf30 100644 --- a/docs/acp-mode.md +++ b/docs/acp-mode.md @@ -125,7 +125,7 @@ MCP stdio connections. 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: in the agreed contract, a normal gateway run can +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 @@ -134,13 +134,6 @@ this proxy, its tool profile, or the MCP six-tool list. See [ACP delegation](acp-delegation.md) for its configuration, recovery, and permission rules. -**Staged on this branch.** This checkout does not yet wire delegation into the -gateway: `delegate_acp` is absent from the current tool registry, the current -configuration loader rejects `acp_harnesses`, and the RSS runtime has no -delegation entry. This page is a feature-branch candidate whose documentation -states the agreed contract; this section will be adjusted after the combined -gateway, RSS, and real-harness end-to-end run passes. - ## Troubleshooting | Symptom | What to check | diff --git a/docs/configuration.md b/docs/configuration.md index 3084ba6..625fa9d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -273,14 +273,11 @@ compatibility, and troubleshooting. ## ACP delegation harnesses (`config.yaml`) -**Feature-branch candidate, not part of this checkout.** The `acp_harnesses` -table below is the agreed opt-in contract for the `delegate_acp` gateway tool. -The current loader has no such field, so adding it to `config.yaml` is rejected -as an unknown key until the implementing change lands. It is documented here -because it reuses this same document and the existing agent-home -`ConfigFile::load` path; it introduces no new file, flag, or environment -variable. Until that change is present, the default tool table, the ACP proxy, -and the MCP six-tool list are exactly as described elsewhere on this page. +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 diff --git a/docs/deployment.md b/docs/deployment.md index d005d97..186dff6 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 3f074b3..d256e81 100644 --- a/docs/status.md +++ b/docs/status.md @@ -48,7 +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`) | Feature-branch candidate, **not enabled in this checkout**: the default tool registry, the ACP proxy, and the MCP six-tool list are unchanged. The agreed opt-in contract (config table, tool input, approvals, durable session pin, resume, restart and unknown-state rules) is documented in [ACP delegation](acp-delegation.md). A standalone protocol pre-verification on OpenCode 1.19.6 with a scripted loopback model covered two separate processes resuming one external session ID with context carried from the first turn. Gateway end-to-end acceptance, approval binding, crash points, quotas, and cleanup evidence remain open. | +| 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 f5aa098..66b01e4 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 cbc5424..54cb05a 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/tools/delegate_acp.rss b/rss/tools/delegate_acp.rss new file mode 100644 index 0000000..b13b206 --- /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/runtime/agent_host.rs b/src/runtime/agent_host.rs index daa9ef8..c79a14d 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/rss_runner.rs b/src/runtime/rss_runner.rs index c9250ec..3d52254 100644 --- a/src/runtime/rss_runner.rs +++ b/src/runtime/rss_runner.rs @@ -1102,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>, @@ -1418,6 +1419,7 @@ impl AgentRunner { child_call: None, child_read: None, child_state: None, + acp_tool: None, }) } @@ -1502,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() @@ -1799,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(), }); @@ -2419,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, }; @@ -2460,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 b2e1aa5..c42ff51 100644 --- a/src/service.rs +++ b/src/service.rs @@ -6742,9 +6742,8 @@ impl AgentService { /// Installs the optional ACP delegation policy built from the existing /// `config.yaml` launch table. /// - /// Installing twice replaces the table for later calls only; an already - /// admitted call keeps the policy it started with. A `None` policy leaves - /// the capability disabled, which is the default. + /// 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>, @@ -6755,12 +6754,138 @@ impl AgentService { .to_string(), ); } - *self + 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 - .acp_delegation + .context_registries .lock() - .expect("acp delegation policy") = policy; - Ok(()) + .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. @@ -9978,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() @@ -12023,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 { @@ -12612,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| { @@ -12630,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 index 79bb085..647755a 100644 --- a/src/service/acp_session_pins.rs +++ b/src/service/acp_session_pins.rs @@ -3697,3 +3697,193 @@ fn known_code(code: &str) -> Option<&'static str> { ]; 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 cbf96fe..b645b20 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_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index f85dfa5..e2fa25c 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -114,9 +114,12 @@ fn text_response(text: &str) -> Value { /// 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 { @@ -124,6 +127,8 @@ impl FixtureRun { Self { key: format!("{label}-{}", uuid::Uuid::new_v4().simple()), answer: text_response(answer_marker), + acp_call: None, + output_budget: None, } } } @@ -159,10 +164,30 @@ fn install_fixture_provider(state: &AgentGatewayState, runs: &[Value], key: &str 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"), ), @@ -182,6 +207,8 @@ fn install_fixture_provider(state: &AgentGatewayState, runs: &[Value], key: &str /// process boundary as a test-owned object. struct RecordingProvider { inner: ScriptedProvider, + acp_call: Option, + turn: Mutex, transcript: Mutex, } @@ -193,7 +220,34 @@ impl AgentProviderHost for RecordingProvider { .expect("append provider transcript"); transcript.flush().expect("flush provider transcript"); } - self.inner.call(request, cancellation) + 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":{}}) } } @@ -793,6 +847,8 @@ fn spawn_harness_child( 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)) @@ -1540,6 +1596,23 @@ fn transcript_requests(fixture: &GatewayFixture, label: &str, run_key: &str) -> .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() @@ -1633,7 +1706,7 @@ async fn gateway_harness_child_entry() { // production code. let hold_before_ready_ms = spec["hold_before_ready_ms"].as_u64().unwrap_or(0); - let config = AgentGatewayConfig { + let mut config = AgentGatewayConfig { bearer_token: Some(token), run_timeout: Duration::from_millis(run_timeout_ms), ..AgentGatewayConfig::default() @@ -1653,6 +1726,9 @@ async fn gateway_harness_child_entry() { 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() @@ -1678,6 +1754,22 @@ async fn gateway_harness_child_entry() { // 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")) @@ -1757,6 +1849,361 @@ async fn gateway_harness_child_entry() { 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", "continue 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); + exercise_acp_controls(&mut gateway, &fixture, session_id, &controls, &invalid).await; + exercise_acp_budgets(&mut gateway, &fixture, session_id, &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"); @@ -1849,6 +2296,22 @@ async fn gateway_restart_preserves_session_history_for_the_next_model_turn() { ); 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]), @@ -2760,3 +3223,181 @@ fn assert_persisted_workspace(session: &Value, fixture: &GatewayFixture) { "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, + controls: &[FixtureRun; 4], + 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 reused = admit_run(gateway, session, "Use the released pin after cancellation").await; + decide_delegation(gateway, fixture, &reused, &controls[3], 5, "approved", true).await; + let terminal = gateway.observe_terminal(&reused, HTTP_BUDGET).await; + assert_eq!(terminal.event, "run.completed"); + assert_eq!( + terminal.output, + "runner saw completed: ctx=5;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 pin_reused=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/fixtures/acp_policy/policy_agent.rs b/tests/fixtures/acp_policy/policy_agent.rs index 00e5dfd..3086c6c 100644 --- a/tests/fixtures/acp_policy/policy_agent.rs +++ b/tests/fixtures/acp_policy/policy_agent.rs @@ -36,6 +36,7 @@ struct Config { init_delay_ms: u64, restore_delay_ms: u64, hold: bool, + hold_task: Option, } struct Harness { @@ -231,7 +232,7 @@ impl Harness { self.record("session/prompt", params.clone()); let prior = self.history_len(&session_id); self.remember(&session_id, &task); - if self.config.hold { + if self.config.hold || self.config.hold_task.as_deref() == Some(task.as_str()) { self.pending .lock() .expect("fixture pending") @@ -362,6 +363,7 @@ fn main() { .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) @@ -375,6 +377,7 @@ fn main() { 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 }; @@ -405,8 +408,8 @@ fn main() { _ => {} } } + harness.record("stdin/eof", json!({"pid": std::process::id()})); if let Some(release) = argument(&args, "--eof-release") { - harness.record("stdin/eof", json!({"pid": std::process::id()})); 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 255533a..2e415c7 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/release_packaging_tests.rs b/tests/release_packaging_tests.rs index 91798ff..0e83644 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([ From 8f9b6c3df935530863865a1d46ec4ff6fa7600ee Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 20:25:50 +0800 Subject: [PATCH 24/27] Verify cancellation fences the old ACP pin and permits a fresh session --- tests/acp_delegation_e2e_tests.rs | 49 +++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/tests/acp_delegation_e2e_tests.rs b/tests/acp_delegation_e2e_tests.rs index e2fa25c..a1fe3ed 100644 --- a/tests/acp_delegation_e2e_tests.rs +++ b/tests/acp_delegation_e2e_tests.rs @@ -2036,7 +2036,11 @@ async fn gateway_restarts_between_three_approved_rss_delegations() { delegation_turn("deny", "denied benign task"), delegation_turn("load", "load-only benign task"), delegation_turn("stop", "hold this prompt"), - delegation_turn("after-stop", "continue after cancellation"), + 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 = [ @@ -2128,8 +2132,17 @@ async fn gateway_restarts_between_three_approved_rss_delegations() { } if label == "second" { assert_three_peer_rounds(&fixture, tasks); - exercise_acp_controls(&mut gateway, &fixture, session_id, &controls, &invalid).await; - exercise_acp_budgets(&mut gateway, &fixture, session_id, &budgets).await; + 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(); } @@ -3248,7 +3261,8 @@ async fn exercise_acp_controls( gateway: &mut GatewayProcess, fixture: &GatewayFixture, session: &str, - controls: &[FixtureRun; 4], + fresh_session: &str, + controls: &[FixtureRun; 5], invalid: &FixtureRun, ) { gateway.install_run_provider(&controls[0].key).await; @@ -3341,18 +3355,35 @@ async fn exercise_acp_controls( assert_eq!(peer_spawns(fixture), 5); gateway.install_run_provider(&controls[3].key).await; - let reused = admit_run(gateway, session, "Use the released pin after cancellation").await; - decide_delegation(gateway, fixture, &reused, &controls[3], 5, "approved", true).await; - let terminal = gateway.observe_terminal(&reused, HTTP_BUDGET).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=5;reply=external-reply" + "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 pin_reused=true" + "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" ); } From b2c8fc19bf70b09974da83082ebf00821df15375 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 22:39:38 +0800 Subject: [PATCH 25/27] test: fix ACP fixtures for all-target Clippy --- src/acp/delegated_client.rs | 2 +- src/effects/managed_authority_tests.rs | 1 + src/runtime/agent_host/option_text_tests.rs | 2 + src/runtime/agent_host/preview_tests.rs | 2 + tests/acp_delegation_client_tests.rs | 2 +- tests/fixtures/acp/build.rs | 45 +-------------------- tests/fixtures/acp/compile.rs | 38 +++++++++++++++++ tests/fixtures/acp/delegation_build.rs | 6 +++ 8 files changed, 52 insertions(+), 46 deletions(-) create mode 100644 tests/fixtures/acp/compile.rs create mode 100644 tests/fixtures/acp/delegation_build.rs diff --git a/src/acp/delegated_client.rs b/src/acp/delegated_client.rs index 946db81..18869a0 100644 --- a/src/acp/delegated_client.rs +++ b/src/acp/delegated_client.rs @@ -3762,7 +3762,7 @@ mod sdk_actor_exit_cleanup_tests { mod fixture_build { include!(concat!( env!("CARGO_MANIFEST_DIR"), - "/tests/fixtures/acp/build.rs" + "/tests/fixtures/acp/delegation_build.rs" )); } diff --git a/src/effects/managed_authority_tests.rs b/src/effects/managed_authority_tests.rs index 1cb925f..7e4b422 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/runtime/agent_host/option_text_tests.rs b/src/runtime/agent_host/option_text_tests.rs index 66e526e..a941435 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 e111da0..0cf99fc 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/tests/acp_delegation_client_tests.rs b/tests/acp_delegation_client_tests.rs index 8d3cc1b..1db7365 100644 --- a/tests/acp_delegation_client_tests.rs +++ b/tests/acp_delegation_client_tests.rs @@ -19,7 +19,7 @@ use rustscript_agent::acp::{ use serde_json::Value; use tokio::time::{Instant, timeout}; -#[path = "fixtures/acp/build.rs"] +#[path = "fixtures/acp/delegation_build.rs"] mod fixture_build; const SETUP_BOUND: Duration = Duration::from_secs(20); diff --git a/tests/fixtures/acp/build.rs b/tests/fixtures/acp/build.rs index ab01d7e..fd4f1a9 100644 --- a/tests/fixtures/acp/build.rs +++ b/tests/fixtures/acp/build.rs @@ -1,49 +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. -#[allow(dead_code)] pub fn compile_fake_agent(binary: &Path) { compile_fixture("fake_agent.rs", "2021", binary); } - -/// Compile the delegated-client harness used by the task-1 client tests. -pub fn compile_delegation_agent(binary: &Path) { - compile_fixture("delegation_agent.rs", "2024", binary); -} - -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/compile.rs b/tests/fixtures/acp/compile.rs new file mode 100644 index 0000000..a0e6675 --- /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_build.rs b/tests/fixtures/acp/delegation_build.rs new file mode 100644 index 0000000..e45d0e4 --- /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); +} From 9ef869ce9c0e00d9bcbe965143f640fa510b3701 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 1 Dec 2026 05:48:56 +0800 Subject: [PATCH 26/27] test: rendezvous before the approval session fence --- src/gateway/store.rs | 12 ++++++------ tests/provider_durable_replay_loop_tests.rs | 15 ++++++++++++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/gateway/store.rs b/src/gateway/store.rs index a9924cc..237b5f2 100644 --- a/src/gateway/store.rs +++ b/src/gateway/store.rs @@ -4965,10 +4965,6 @@ impl GatewayPersistence { } pub fn approval_resolve(&self, payload: &Value) -> Result { - let _fence = self - .session_fence - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); #[cfg(feature = "config-fixture")] { let gate = self @@ -4986,6 +4982,10 @@ impl GatewayPersistence { } } } + let _fence = self + .session_fence + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); self.command_data("approval.resolve", payload) } @@ -5131,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/tests/provider_durable_replay_loop_tests.rs b/tests/provider_durable_replay_loop_tests.rs index 4d35883..64522c0 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()); From 4508ac6f20bf714f89a98755bfac7028adc18a54 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 1 Dec 2026 06:36:01 +0800 Subject: [PATCH 27/27] test(acp): verify durable session pin isolation --- tests/acp_delegation_policy_tests.rs | 260 ++++++++++++++++++++++++--- 1 file changed, 236 insertions(+), 24 deletions(-) diff --git a/tests/acp_delegation_policy_tests.rs b/tests/acp_delegation_policy_tests.rs index d623b4e..f98fe85 100644 --- a/tests/acp_delegation_policy_tests.rs +++ b/tests/acp_delegation_policy_tests.rs @@ -377,6 +377,18 @@ impl<'a> Runtime<'a> { .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, @@ -480,6 +492,34 @@ fn session_row(persistence: &GatewayPersistence, session_id: &str) -> Vec .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) { @@ -1011,27 +1051,9 @@ async fn workspace_change_refuses_the_old_binding() { // old pin still names the previous directory. This writes the private // document through the product CAS, not through an approval. let persistence = runtime.persistence(); - let mut doc = pin_document(&persistence, &first_run.session_id); - let expected_version = doc["version"].as_i64().unwrap_or(-1); - doc["version"] = json!(expected_version + 1); - doc["pins"]["fixture"]["workspace"] = json!(env.workspace.join("relocated")); - let value = persistence - .session_get(&first_run.session_id) - .expect("session"); - let row = value["rows"][0].as_array().expect("row").clone(); - let cas = persistence - .session_acp_delegation_cas(&json!({ - "session_id": first_run.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("relocate pin workspace"); - assert_eq!(cas["applied"], true); + 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"); @@ -1047,6 +1069,191 @@ async fn workspace_change_refuses_the_old_binding() { 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"); @@ -1468,11 +1675,16 @@ async fn two_harnesses_in_one_session_keep_both_pin_updates() { ); 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!( - doc["pins"]["fixture"]["external_session_id"].is_string(), - "the concurrent other-harness write must not erase the fixture pin: {doc}" + fixture_id != other_id, + "the harnesses must have distinct external IDs" ); - assert!(doc["pins"]["other"]["external_session_id"].is_string()); assert_eq!(env.recorded("session/new"), 2); }