diff --git a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs index 232f498047..03fc0e4086 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs @@ -85,11 +85,12 @@ async fn pending_mcp_action_uses_the_configured_reviewer( "I understand the release risk. I explicitly approve this release action."; const FINAL_REVOCATION: &str = "Stop the release again. Do not deploy."; const FIRST_DENIAL_REASON: &str = "The user explicitly stopped this deployment."; + const UNRELATED_GOAL: &str = "Write release notes in French."; const PENDING_CALL: &str = "release-pending"; let next_call = Arc::new(Mutex::new(None)); let actor_call = Arc::clone(&next_call); - let stale_allow_url = Arc::new(Mutex::new(None::)); - let redirect = Arc::clone(&stale_allow_url); + let held_allow_url = Arc::new(Mutex::new(None::)); + let redirect = Arc::clone(&held_allow_url); let ask_to_subscribe = AtomicBool::new(uses_board); let deny_first_reapproval = AtomicBool::new(reconsider); let first_final_sample = AtomicBool::new(true); @@ -130,7 +131,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer( responses::ev_completed("subscribe"), ])); } - if let Some(url) = redirect.lock().expect("stale allow URL").take() { + if let Some(url) = redirect.lock().expect("held allow URL").take() { return wiremock::ResponseTemplate::new(/*s*/ 307).insert_header("location", url); } let final_revocation = received_user_instruction(&request, FINAL_REVOCATION); @@ -284,7 +285,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer( turns.push(( PENDING_CALL, "Proceed with the release.", - GuardianApprovalReviewStatus::Denied, + GuardianApprovalReviewStatus::Approved, )); } let mut previous_reviewer = None; @@ -310,7 +311,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer( body: assistant_response(r#"{"outcome":"allow","rationale":"Release approved."}"#)?, }]]) .await; - *stale_allow_url.lock().expect("stale allow URL") = + *held_allow_url.lock().expect("held allow URL") = Some(format!("{}/v1/responses", stream.uri())); Some((stream, release)) } else { @@ -337,12 +338,12 @@ async fn pending_mcp_action_uses_the_configured_reviewer( "thread/goal/set", Some(json!({ "threadId": thread.id, "origin": "user", - "status": "paused", "objective": FINAL_REVOCATION, + "status": "paused", "objective": UNRELATED_GOAL, })), ) .await?; let _: ThreadGoalSetResponse = timeout(TIMEOUT, app.read_response(id)).await??; - release.send(()).expect("release stale allow"); + release.send(()).expect("release allow"); } if let Some(gate) = gate { app.wait_for_matching_json_log_event( @@ -419,21 +420,11 @@ async fn pending_mcp_action_uses_the_configured_reviewer( denied_turns.push(review.turn_id); } if call_id == PENDING_CALL { - let [stale, retry] = assessments.as_slice() else { - anyhow::bail!("expected a stale allow and one retry for {call_id}"); + let [allow] = assessments.as_slice() else { + anyhow::bail!("an unrouted goal should not invalidate the verdict for {call_id}"); }; - assert!(!received_user_instruction(stale, FINAL_REVOCATION)); - assert!(received_user_instruction(retry, FINAL_REVOCATION)); + assert!(!received_user_instruction(allow, UNRELATED_GOAL)); assert_eq!(review.target_item_id.as_deref(), Some(call_id)); - let denied = wait_for_mcp_tool_call_completed(&mut app, call_id).await?; - assert!(matches!( - denied.item.payload, - ThreadItemPayload::McpToolCall { - status: McpToolCallStatus::Failed, error: Some(error), .. - } if error.message.contains(FIRST_DENIAL_REASON) - )); - // Core discards the stale session, so the reuse assertions below don't apply. - continue; } if prompt == FINAL_REVOCATION { assert_eq!( diff --git a/codex-rs/core/src/guardian/attached_review.rs b/codex-rs/core/src/guardian/attached_review.rs index 3facee72de..738db485f6 100644 --- a/codex-rs/core/src/guardian/attached_review.rs +++ b/codex-rs/core/src/guardian/attached_review.rs @@ -1,8 +1,7 @@ -//! Holds one action's prepared reviewer and its pre-capture authorization revision. +//! Holds the attached reviewer through the verdict. New evidence can wait for the next review. //! Native retries take a new reservation under the original verdict deadline. use super::super::*; use super::PreparedApproval; -use super::ReviewAuthorization; use crate::guardian::input_budget::PendingReviewContext; use crate::guardian::review_session::PreparedVerdictTurn; use crate::guardian::review_session::ensure_guardian_followup_reminder; @@ -21,13 +20,12 @@ use tokio::sync::Mutex; pub(super) struct AttachedApproval { provider: BoundReviewer, config: GuardianReviewSessionConfig, - first: Mutex)>>, + first: Mutex>>, } impl AttachedApproval { pub async fn prepare( provider: BoundReviewer, - authorization: ReviewAuthorization, parent: &Arc, context: &GuardianReviewContext, deadline: ReviewDeadline, @@ -42,7 +40,7 @@ impl AttachedApproval { Ok(Self { provider, config, - first: Mutex::new(Some((authorization, reserved))), + first: Mutex::new(Some(reserved)), }) }; tokio::select! { @@ -77,7 +75,6 @@ impl AttachedApproval { parent: &Arc, approval: &PreparedApproval, reasons: &ApprovalRequestReasons, - authorization: ReviewAuthorization, deadline: ReviewDeadline, cancel: &CancellationToken, ) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) { @@ -86,20 +83,17 @@ impl AttachedApproval { let mut usage_at_start = None; let prepare = async { let first = self.first.lock().await.take(); - let (authorization, model) = match first { + let model = match first { Some(first) => first, - None => ( - authorization, - Self::reserve( - &self.provider, - &self.config, - parent, - &approval.context, - cancel, - ) - .await - .map_err(|err| GuardianReviewSessionOutcome::PromptBuildFailed(err.into()))?, - ), + None => Self::reserve( + &self.provider, + &self.config, + parent, + &approval.context, + cancel, + ) + .await + .map_err(|err| GuardianReviewSessionOutcome::PromptBuildFailed(err.into()))?, }; let model = reservation.insert(model); let config = &self.config; @@ -112,10 +106,6 @@ impl AttachedApproval { kind, matches!(kind, GuardianReviewSessionKind::TrunkReused), ); - if let Some(stale) = authorization.invalidation(parent, Some(cancel)).await { - analytics.context_changed = stale.context_changed; - return Err(stale.outcome); - } let action = codex_guardian_reviewer::build_guardian_planned_action( &approval.request, reasons.retry.clone().or_else(|| reasons.approval.clone()), @@ -166,11 +156,11 @@ impl AttachedApproval { ) .await .map_err(GuardianReviewSessionOutcome::PromptBuildFailed)?; - Ok((runtime, authorization, turn)) + Ok((runtime, turn)) }; let prepared = run_before_review_deadline(deadline, Some(cancel), prepare).await; let result = async { - let (runtime, authorization, turn) = prepared??; + let (runtime, turn) = prepared??; // Let the runner interrupt and drain the turn before it finalizes a provisional denial. let (turn, _) = runtime .run_sync_verdict( @@ -181,20 +171,23 @@ impl AttachedApproval { &mut analytics, ) .await?; - let stale = tokio::select! { + tokio::select! { biased; _ = cancel.cancelled() => return Err(GuardianReviewSessionOutcome::Aborted), _ = deadline.wait() => { if !turn.outcome.is_recovered_denial() { return Err(GuardianReviewSessionOutcome::TimedOut); } - None } - stale = authorization.invalidation(parent, Some(cancel)) => stale, - }; - if let Some(stale) = stale { - analytics.context_changed |= stale.context_changed; - return Err(stale.outcome); + root = parent.guardian_root_snapshot() => { + let root = root.map_err(|error| match error.details() { + super::CodexErrorDetails::Timeout => GuardianReviewSessionOutcome::TimedOut, + _ => GuardianReviewSessionOutcome::Aborted, + })?; + if approval.root_history != root.as_ref().map(super::root_history_key) { + return Err(GuardianReviewSessionOutcome::Aborted); + } + } } Ok((turn.outcome, turn.disposition)) } diff --git a/codex-rs/core/src/guardian/review_request.rs b/codex-rs/core/src/guardian/review_request.rs index b6bc9e4897..24c136ca8c 100644 --- a/codex-rs/core/src/guardian/review_request.rs +++ b/codex-rs/core/src/guardian/review_request.rs @@ -235,18 +235,6 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { .map_err(|error| ReviewDecision::denied(error.to_string()))?; let root_history = root.as_ref().map(root_history_key); let attached = if let Some(provider) = attached_reviewer { - let history = session.conversation_history_snapshot().await; - let authorization = ReviewAuthorization { - user_message_revision: history.user_message_revision(), - review_context_revision: history.guardian_review_context_revision(), - root_history, - root_authorization_version: root.as_ref().map(|root| root.authorization_version), - root_review_context_revision: root - .as_ref() - .map(|root| root.review_context_revision), - history_reset: self.history_reset.clone(), - }; - drop(history); let started = Instant::now(); tracing::info!( %review_id, @@ -258,15 +246,9 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { }, "Guardian V3 review preparation started" ); - let result = AttachedApproval::prepare( - provider, - authorization, - &session, - &context, - deadline, - cancellation, - ) - .await; + let result = + AttachedApproval::prepare(provider, &session, &context, deadline, cancellation) + .await; let result = if cancellation.is_cancelled() { Err(ReviewPreparationError::Cancelled) } else { @@ -358,26 +340,19 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { root_versions, }); drop(history); - let authorization = ReviewAuthorization { - user_message_revision, - review_context_revision, - root_history: prepared.root_history, - root_authorization_version, - root_review_context_revision, - history_reset: self.history_reset.clone(), - }; let (outcome, analytics) = if let Some(attached) = &prepared.attached { attached - .attempt( - session, - prepared, - &self.reasons, - authorization, - deadline, - cancellation, - ) + .attempt(session, prepared, &self.reasons, deadline, cancellation) .await } else { + let authorization = ReviewAuthorization { + user_message_revision, + review_context_revision, + root_history: prepared.root_history, + root_authorization_version, + root_review_context_revision, + history_reset: self.history_reset.clone(), + }; run_guardian_review_session_before_deadline( Arc::clone(&self.session), prepared.context.clone(), diff --git a/codex-rs/core/src/guardian_review.rs b/codex-rs/core/src/guardian_review.rs index 54b80d6c90..978131b5ea 100644 --- a/codex-rs/core/src/guardian_review.rs +++ b/codex-rs/core/src/guardian_review.rs @@ -146,7 +146,7 @@ pub enum ReviewPreparationError { } /// Reserve the actor's reviewer after routing and delivery have covered this attempt. -/// A retry must cover authorization changes since the previous attempt. +/// Each attempt admits evidence available to that reviewer. pub trait ReviewerPreparation: Send + Sync { fn prepare<'a>( &'a self, @@ -158,7 +158,7 @@ pub trait ReviewerPreparation: Send + Sync { >; } -/// Holds the model session until the host finishes validating the original authority. +/// Holds the model session until the host accepts or discards its verdict. /// Dropping an interrupted reservation discards its partially admitted conversation. pub trait PreparedAssessment: Send + Sync { fn runtime(&self) -> &GuardianReviewSession; diff --git a/codex-rs/ext/guardian-v3/src/actor.rs b/codex-rs/ext/guardian-v3/src/actor.rs index 72cb47b086..6f479d096b 100644 --- a/codex-rs/ext/guardian-v3/src/actor.rs +++ b/codex-rs/ext/guardian-v3/src/actor.rs @@ -265,7 +265,7 @@ impl ActorReviewer { } /// The first attempt uses the request-time position. Every later attempt flushes and -/// captures again after core has sampled its new authorization revision. +/// captures again before draining newly delivered evidence. struct BoundActorReview { actor: Arc, initial: Mutex>>,