mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Shadow fresh Guardian V2 approvals with Guardian V3 (#64782)
## Why Collect Guardian V3 verdicts for actions that require a fresh Guardian V2 review while keeping Guardian V2 in control of approval and tool execution. ## What changed When Guardian V3 shadowing is enabled and an enrolled reviewer is available, run a single background review for eligible fresh approvals and log the outcome with the live review ID. Skip shadowing when the reviewer is busy, shadow intake has stopped, or a rollout budget is configured. ## Testing Add app-server coverage for immediate approvals, ordinary synchronous reviews, and fresh reviews with and without a rollout budget. Hold a shadow denial in flight to verify that the tool and turn can finish, a second request skips the busy reviewer, and stopped intake prevents new shadow reviews while the in-flight verdict can still finish. GitOrigin-RevId: 5e31f3d7e3b0433455b8f2a5fb52e483588b1b29
This commit is contained in:
@@ -75,6 +75,9 @@ use super::mcp_tool::TEST_TOOL_NAME;
|
||||
use super::mcp_tool::start_mcp_server;
|
||||
use super::mcp_tool::start_mcp_server_with_tools;
|
||||
|
||||
#[path = "guardian_v3_shadow_tests.rs"]
|
||||
mod v3_shadow;
|
||||
|
||||
#[path = "guardian_v3_sync_tests.rs"]
|
||||
mod v3_sync;
|
||||
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
#![cfg(test)]
|
||||
//! Only fresh GV2 reviews start a shadow, and tool execution never waits for its verdict.
|
||||
|
||||
use super::super::mcp_tool::wait_for_mcp_tool_call_completed;
|
||||
use super::*;
|
||||
use app_test_support::create_final_assistant_message_sse_response as assistant_response;
|
||||
use codex_app_server_protocol::GuardianApprovalReviewStatus;
|
||||
use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification;
|
||||
use codex_app_server_protocol::ThreadHistoryMode;
|
||||
use core_test_support::streaming_sse::StreamingSseChunk;
|
||||
use core_test_support::streaming_sse::start_streaming_sse_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case("node_repl", "js", "auto", None, None, 0; "immediate approval")]
|
||||
#[test_case(TEST_SERVER_NAME, TEST_TOOL_NAME, "prompt", None, None, 2; "ordinary sync reviews")]
|
||||
#[test_case(TEST_SERVER_NAME, TEST_TOOL_NAME, "prompt", Some(true), None, 2; "sensitive elicitation requires fresh review")]
|
||||
#[test_case(TEST_SERVER_NAME, TEST_TOOL_NAME, "prompt", Some(true), Some(true), 2; "enforced budget leaves fresh reviews to GV2")]
|
||||
#[test_case(TEST_SERVER_NAME, TEST_TOOL_NAME, "prompt", Some(true), Some(false), 2; "unenforced budget leaves fresh reviews to GV2")]
|
||||
#[tokio::test]
|
||||
async fn only_fresh_reviews_start_a_nonblocking_shadow(
|
||||
name: &'static str,
|
||||
tool: &'static str,
|
||||
approval_mode: &str,
|
||||
sensitive_action: Option<bool>,
|
||||
enforce_budget: Option<bool>,
|
||||
expected_reviews: usize,
|
||||
) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let server = responses::start_mock_server().await;
|
||||
let (release, gate) = tokio::sync::oneshot::channel();
|
||||
let (stream, mut completions) = start_streaming_sse_server(vec![vec![StreamingSseChunk {
|
||||
gate: Some(gate),
|
||||
body: assistant_response(r#"{"outcome":"deny","rationale":"shadow only"}"#)?,
|
||||
}]])
|
||||
.await;
|
||||
let redirect = format!("{}/v1/responses", stream.uri());
|
||||
const STOP_INTAKE: &str = "Trigger a routing failure.";
|
||||
let next_call = Arc::new(Mutex::new(None::<&str>));
|
||||
let pending_call = Arc::clone(&next_call);
|
||||
let requests = responses::mount_response_handler(&server, move |request| {
|
||||
let body = request.body_json();
|
||||
let properties = &body["text"]["format"]["schema"]["properties"];
|
||||
let text = if properties.get("routes").is_some() {
|
||||
let items = request.inputs_of_type("function_call_output");
|
||||
let batch = items.iter().rev().find(|item| item["name"] == "guardian_housekeeper_input").expect("routing batch");
|
||||
let input: Value = serde_json::from_str(batch["output"].as_str().expect("batch text")).expect("batch JSON");
|
||||
if input["sources"].to_string().contains(STOP_INTAKE) {
|
||||
return responses::sse_response(assistant_response(r#"{"descriptions":[],"routes":[]}"#).unwrap());
|
||||
}
|
||||
let count = input["sources"].as_array().expect("batch sources").len();
|
||||
json!({"descriptions":[{"channel":"task","description":"User task"}],"routes":vec![vec!["task"];count]}).to_string()
|
||||
} else if properties.get("outcome").is_some() {
|
||||
if body["tools"].to_string().contains("guardian_board") {
|
||||
return wiremock::ResponseTemplate::new(/*s*/ 307)
|
||||
.insert_header("location", redirect.as_str());
|
||||
}
|
||||
r#"{"outcome":"allow","rationale":"live approval"}"#.to_string()
|
||||
} else if let Some(id) = pending_call.lock().unwrap().take() {
|
||||
return responses::sse_response(responses::sse(vec![
|
||||
responses::ev_response_created(id),
|
||||
responses::ev_function_call_with_namespace(id, &format!("mcp__{name}"), tool, &json!({"message": id}).to_string()),
|
||||
responses::ev_completed(id),
|
||||
]));
|
||||
} else {
|
||||
"Done.".to_string()
|
||||
};
|
||||
responses::sse_response(assistant_response(&text).expect("mock response"))
|
||||
})
|
||||
.await;
|
||||
let (mcp_url, mcp) =
|
||||
start_mcp_server_with_tools(&["js", TEST_TOOL_NAME], sensitive_action).await?;
|
||||
let home = TempDir::new()?;
|
||||
let mut config = MockResponsesConfig::new(&server.uri());
|
||||
if let Some(enforce_limit) = enforce_budget {
|
||||
config = config.with_extra_config(&format!(
|
||||
"[features.rollout_budget]\nenabled = true\nenforce_limit = {enforce_limit}\nlimit_budget = 100000.0\nreminder_at_remaining_tokens = []"
|
||||
));
|
||||
}
|
||||
config
|
||||
.with_provider_config("supports_websockets = false")
|
||||
.with_approval_policy("on-request")
|
||||
.with_root_config("approvals_reviewer = \"auto_review\"")
|
||||
.with_extra_config(&format!(
|
||||
"[mcp_servers.{name}]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"{approval_mode}\""
|
||||
))
|
||||
.enable_feature(Feature::GuardianApproval)
|
||||
.enable_feature(Feature::GuardianV2)
|
||||
.enable_feature(Feature::GuardianRecordedItems)
|
||||
.disable_feature(Feature::GuardianDenialReconsideration)
|
||||
.disable_feature(Feature::EnableRequestCompression)
|
||||
.write(home.path())?;
|
||||
let config = load_default_config_for_test(&home).await;
|
||||
let mut model = codex_core::test_support::construct_model_info_offline(MODEL, &config);
|
||||
model.node_repl_auto_review_required = true;
|
||||
write_models_cache_with_models(home.path(), vec![model]).await?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_json_logging("warn,codex_guardian_v3::host=debug,codex_core::guardian=debug")
|
||||
.build_initialized_with_timeout(TIMEOUT)
|
||||
.await?;
|
||||
let thread = app
|
||||
.start_thread(ThreadStartParams {
|
||||
history_mode: Some(ThreadHistoryMode::Paginated),
|
||||
config: Some([("features.guardianv3.shadow_enabled".into(), json!(true))].into()),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
|
||||
// Ensure the action exercises an enrolled reviewer even when startup is slow.
|
||||
app.wait_for_json_log_event("guardian_v3.shadow_intake_started", TIMEOUT)
|
||||
.await?;
|
||||
// Neither the tool nor the parent turn needs the held GV3 verdict.
|
||||
let turn = |text: &str| TurnStartParams {
|
||||
thread_id: thread.id.clone(),
|
||||
input: vec![UserInput::Text {
|
||||
text: text.into(),
|
||||
text_elements: vec![],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let check = async |app: &mut TestAppServer, id: &'static str, prompt: &str| {
|
||||
*next_call.lock().unwrap() = Some(id);
|
||||
let completed = timeout(
|
||||
TIMEOUT,
|
||||
app.start_turn_and_wait_for_completion(turn(prompt)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(completed.turn.status, TurnStatus::Completed);
|
||||
let call = wait_for_mcp_tool_call_completed(app, id).await?;
|
||||
assert!(matches!(
|
||||
call.item.payload,
|
||||
ThreadItemPayload::McpToolCall {
|
||||
status: McpToolCallStatus::Completed,
|
||||
..
|
||||
}
|
||||
));
|
||||
// Include late completions from earlier turns so a shadow denial cannot go unnoticed.
|
||||
let mut review_ids = Vec::new();
|
||||
for method in app.pending_notification_methods() {
|
||||
if method == "item/autoApprovalReview/completed" {
|
||||
let review: ItemGuardianApprovalReviewCompletedNotification =
|
||||
app.read_notification(&method).await?;
|
||||
assert_eq!(review.thread_id, thread.id);
|
||||
assert_eq!(review.review.status, GuardianApprovalReviewStatus::Approved);
|
||||
review_ids.push(review.review_id);
|
||||
}
|
||||
}
|
||||
assert_eq!(review_ids.len(), expected_reviews);
|
||||
anyhow::Ok(review_ids)
|
||||
};
|
||||
let first_approvals = check(&mut app, "check", USER_CONTEXT).await?;
|
||||
assert_eq!(
|
||||
app.pending_notification_methods()
|
||||
.iter()
|
||||
.filter(|method| *method == "item/autoApprovalReview/started")
|
||||
.count(),
|
||||
expected_reviews
|
||||
);
|
||||
if sensitive_action.is_none() || enforce_budget.is_some() {
|
||||
app.shutdown_gracefully().await?;
|
||||
assert!(stream.requests().await.is_empty());
|
||||
stream.shutdown().await;
|
||||
mcp.abort();
|
||||
return Ok(());
|
||||
}
|
||||
timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 1)).await?;
|
||||
let verdicts = requests
|
||||
.requests()
|
||||
.into_iter()
|
||||
.filter(|r| {
|
||||
r.body_json()["text"]["format"]["schema"]["properties"]
|
||||
.get("outcome")
|
||||
.is_some()
|
||||
})
|
||||
.count();
|
||||
assert_eq!(verdicts, expected_reviews + 1);
|
||||
|
||||
let shadow = requests
|
||||
.requests()
|
||||
.into_iter()
|
||||
.map(|r| r.body_json())
|
||||
.find(|body| body["tools"].to_string().contains("guardian_board"))
|
||||
.expect("shadow reviewer request");
|
||||
let metadata = &shadow["client_metadata"];
|
||||
let turn_metadata: Value = serde_json::from_str(
|
||||
metadata["x-codex-turn-metadata"]
|
||||
.as_str()
|
||||
.expect("turn metadata"),
|
||||
)?;
|
||||
assert!(turn_metadata.get("guardian_recorded_items").is_none());
|
||||
let shadow_id = metadata["thread_id"].as_str().expect("shadow thread ID");
|
||||
// A second sensitive request must finish without queueing behind the held verdict.
|
||||
check(&mut app, "busy", "Check while the reviewer is busy.").await?;
|
||||
app.wait_for_stderr_line("Guardian shadow reviewer busy", TIMEOUT)
|
||||
.await?;
|
||||
assert_eq!(stream.requests().await.len(), 1);
|
||||
|
||||
// Fail routing with a GV3 verdict in flight.
|
||||
app.start_turn_and_wait_for_completion(turn(STOP_INTAKE))
|
||||
.await?;
|
||||
app.wait_for_stderr_line("Guardian housekeeping stopped", TIMEOUT)
|
||||
.await?;
|
||||
release.send(()).expect("shadow is still running");
|
||||
timeout(TIMEOUT, completions.remove(0)).await??;
|
||||
// The completed verdict releases the slot, so "busy" cannot explain the skip.
|
||||
let verdict = app
|
||||
.wait_for_matching_json_log_event(
|
||||
"completed shadow verdict",
|
||||
|event| event["fields"]["message"] == "Guardian shadow verdict",
|
||||
TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(verdict["fields"]["outcome"], "Deny");
|
||||
assert!(
|
||||
first_approvals
|
||||
.iter()
|
||||
.any(|id| verdict["fields"]["review_id"] == id.as_str())
|
||||
);
|
||||
check(&mut app, "next", "Check again.").await?;
|
||||
app.wait_for_stderr_line(
|
||||
"Guardian shadow review skipped after intake stopped",
|
||||
TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(stream.requests().await.len(), 1);
|
||||
app.shutdown_gracefully().await?;
|
||||
assert!(
|
||||
codex_core::find_thread_path_by_id_str(home.path(), shadow_id, /*state_db_ctx*/ None)
|
||||
.await?
|
||||
.is_none()
|
||||
);
|
||||
stream.shutdown().await;
|
||||
mcp.abort();
|
||||
Ok(())
|
||||
}
|
||||
@@ -17,6 +17,9 @@ use codex_guardian_reviewer::SessionDisposition;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[path = "shadow.rs"]
|
||||
pub(super) mod shadow;
|
||||
|
||||
pub(super) async fn root_history_version(
|
||||
parent: &Session,
|
||||
reviewer: &dyn AttachedReviewer,
|
||||
|
||||
@@ -187,6 +187,7 @@ pub(crate) fn decide_approval(
|
||||
}
|
||||
}
|
||||
let retried = reasons.retry.is_some();
|
||||
let request = Arc::new(request);
|
||||
let decision = codex_guardian_reviewer::ReviewRequest {
|
||||
sampling_model: &context.model_info.slug,
|
||||
turn_id: &turn.sub_id,
|
||||
@@ -196,7 +197,7 @@ pub(crate) fn decide_approval(
|
||||
session: Arc::clone(&session),
|
||||
history_reset: history_reset.clone(),
|
||||
context: context.clone(),
|
||||
request: request.clone(),
|
||||
request: Arc::clone(&request),
|
||||
reasons,
|
||||
options,
|
||||
},
|
||||
|
||||
@@ -349,7 +349,7 @@ async fn prepare_attached_reviewer(
|
||||
session: input.session,
|
||||
history_reset,
|
||||
context: input.context,
|
||||
request: input.request.into(),
|
||||
request: Arc::new(input.request.into()),
|
||||
reasons: input.reasons,
|
||||
options: GuardianReviewOptions {
|
||||
require_guardian: true,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#[path = "attached_review.rs"]
|
||||
mod attached;
|
||||
use super::super::runtime::ReviewRuntime;
|
||||
use super::super::runtime::validate;
|
||||
use super::*;
|
||||
use crate::codex_thread::GuardianAuthorizationVersion;
|
||||
@@ -127,7 +128,87 @@ impl ReviewAuthorization {
|
||||
}
|
||||
}
|
||||
|
||||
impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
impl ReviewRuntime {
|
||||
async fn approval_inputs(
|
||||
&self,
|
||||
) -> Result<(GuardianApprovalRequest, GuardianReviewContext), ReviewDecision> {
|
||||
let request = validate(&self.request, &self.context)?.clone();
|
||||
let mut context = self.context.clone();
|
||||
context.capture_project_instructions(&self.session).await;
|
||||
Ok((request, context))
|
||||
}
|
||||
|
||||
/// Reserve the reviewer after any live plugin lookup, so that lookup never holds the slot.
|
||||
async fn prepare_approval(
|
||||
&self,
|
||||
review_id: &str,
|
||||
request: GuardianApprovalRequest,
|
||||
context: GuardianReviewContext,
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<PreparedApproval, ReviewDecision> {
|
||||
let session = &self.session;
|
||||
let (root_history, attached) = if let Some(provider) = &self.attached_reviewer {
|
||||
let root_history = attached::root_history_version(session, provider.as_ref())
|
||||
.await
|
||||
.map_err(|error| ReviewDecision::denied(error.to_string()))?;
|
||||
let started = Instant::now();
|
||||
tracing::info!(
|
||||
%review_id,
|
||||
tool_call_id = self.request.tool_call_id.as_deref(),
|
||||
probe_review = match context.guardian_probe {
|
||||
Some(true) => "required",
|
||||
Some(false) => "not_required",
|
||||
None => "not_reported",
|
||||
},
|
||||
"Guardian V3 review preparation started"
|
||||
);
|
||||
let result = AttachedApproval::prepare(
|
||||
Arc::clone(provider),
|
||||
session,
|
||||
&context,
|
||||
deadline,
|
||||
cancellation,
|
||||
)
|
||||
.await;
|
||||
let result = if cancellation.is_cancelled() {
|
||||
Err(ReviewPreparationError::Cancelled)
|
||||
} else {
|
||||
result
|
||||
};
|
||||
tracing::info!(
|
||||
%review_id,
|
||||
ready = result.is_ok(),
|
||||
failure_reason = result.as_ref().err().map(tracing::field::display),
|
||||
preparation_ms = started.elapsed().as_millis() as u64,
|
||||
"Guardian V3 review preparation finished"
|
||||
);
|
||||
let prepared = result.map_err(|error| match error {
|
||||
ReviewPreparationError::Cancelled => ReviewDecision::Abort,
|
||||
_ => ReviewDecision::denied(format!(
|
||||
"Guardian V3 could not prepare the evidence for this action: {error}"
|
||||
)),
|
||||
})?;
|
||||
(root_history, Some(prepared))
|
||||
} else {
|
||||
let root = session
|
||||
.guardian_root_snapshot()
|
||||
.await
|
||||
.map_err(|error| ReviewDecision::denied(error.to_string()))?;
|
||||
(root.as_ref().map(root_history_key), None)
|
||||
};
|
||||
Ok(PreparedApproval {
|
||||
request,
|
||||
category: self.request.category,
|
||||
context,
|
||||
root_history,
|
||||
formatted_action: None,
|
||||
attached,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ReviewHost for ReviewRuntime {
|
||||
type Prepared = PreparedApproval;
|
||||
type Evidence = ApprovalEvidence;
|
||||
|
||||
@@ -146,6 +227,10 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
Some((turn.sub_id.clone(), Arc::clone(&turn.model_info().model)))
|
||||
}
|
||||
|
||||
fn start_shadow(&self, approval_id: &str, reason: GuardianReviewReason) {
|
||||
attached::shadow::start(self, approval_id, reason);
|
||||
}
|
||||
|
||||
async fn prepare(
|
||||
&self,
|
||||
review_id: &str,
|
||||
@@ -153,29 +238,10 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(PreparedApproval, codex_guardian_reviewer::ReviewReport), ReviewDecision> {
|
||||
let super::super::runtime::ReviewRuntime {
|
||||
session,
|
||||
history_reset: _,
|
||||
attached_reviewer,
|
||||
mut context,
|
||||
request,
|
||||
reasons: _,
|
||||
options,
|
||||
} = self.clone();
|
||||
let request = match validate(&request, &context) {
|
||||
Ok(request) => request.clone(),
|
||||
Err(decision) => return Err(decision),
|
||||
};
|
||||
context.capture_project_instructions(&session).await;
|
||||
let (request, context) = self.approval_inputs().await?;
|
||||
let session = &self.session;
|
||||
let model_context = context.model_context();
|
||||
let turn = Arc::clone(context.turn());
|
||||
let GuardianReviewOptions {
|
||||
plugin_attribution_override,
|
||||
approval_request_source,
|
||||
external_cancel: _,
|
||||
require_synchronous_review: _,
|
||||
require_guardian: _,
|
||||
} = options;
|
||||
let target_item_id = guardian_request_target_item_id(&request).map(str::to_string);
|
||||
let assessment_turn_id = guardian_request_turn_id(&request, &turn.sub_id).to_string();
|
||||
// An explicit action turn outside this context has unknown lineage.
|
||||
@@ -184,7 +250,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let plugin_attribution = match plugin_attribution_override {
|
||||
let plugin_attribution = match self.options.plugin_attribution_override.clone() {
|
||||
Some(attribution) => Some(attribution),
|
||||
None if matches!(&request, GuardianApprovalRequest::ExecCommand { .. }) => {
|
||||
let attribution_deadline =
|
||||
@@ -223,66 +289,19 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
target_item_id,
|
||||
plugin_id,
|
||||
script_path,
|
||||
approval_request_source,
|
||||
approval_request_source: self.options.approval_request_source,
|
||||
reviewed_action: guardian_reviewed_action(&request),
|
||||
action: guardian_assessment_action(&request),
|
||||
review_reason,
|
||||
model_context,
|
||||
timeout: turn.config.guardian_review_timeout,
|
||||
};
|
||||
let (root_history, attached) = if let Some(provider) = attached_reviewer {
|
||||
let root_history = attached::root_history_version(&session, provider.as_ref())
|
||||
.await
|
||||
.map_err(|error| ReviewDecision::denied(error.to_string()))?;
|
||||
let started = Instant::now();
|
||||
tracing::info!(
|
||||
%review_id,
|
||||
tool_call_id = self.request.tool_call_id.as_deref(),
|
||||
probe_review = match context.guardian_probe {
|
||||
Some(true) => "required",
|
||||
Some(false) => "not_required",
|
||||
None => "not_reported",
|
||||
},
|
||||
"Guardian V3 review preparation started"
|
||||
);
|
||||
let result =
|
||||
AttachedApproval::prepare(provider, &session, &context, deadline, cancellation)
|
||||
.await;
|
||||
let result = if cancellation.is_cancelled() {
|
||||
Err(ReviewPreparationError::Cancelled)
|
||||
} else {
|
||||
result
|
||||
};
|
||||
tracing::info!(
|
||||
%review_id,
|
||||
ready = result.is_ok(),
|
||||
failure_reason = result.as_ref().err().map(tracing::field::display),
|
||||
preparation_ms = started.elapsed().as_millis() as u64,
|
||||
"Guardian V3 review preparation finished"
|
||||
);
|
||||
let prepared = result.map_err(|error| match error {
|
||||
ReviewPreparationError::Cancelled => ReviewDecision::Abort,
|
||||
_ => ReviewDecision::denied(format!(
|
||||
"Guardian V3 could not prepare the evidence for this action: {error}"
|
||||
)),
|
||||
})?;
|
||||
(root_history, Some(prepared))
|
||||
} else {
|
||||
let root = session
|
||||
.guardian_root_snapshot()
|
||||
.await
|
||||
.map_err(|error| ReviewDecision::denied(error.to_string()))?;
|
||||
(root.as_ref().map(root_history_key), None)
|
||||
};
|
||||
let mut prepared = self
|
||||
.prepare_approval(review_id, request, context, deadline, cancellation)
|
||||
.await?;
|
||||
prepared.formatted_action = format_guardian_action_pretty(&prepared.request).ok();
|
||||
Ok((
|
||||
PreparedApproval {
|
||||
formatted_action: format_guardian_action_pretty(&request).ok(),
|
||||
request,
|
||||
category: self.request.category,
|
||||
context,
|
||||
root_history,
|
||||
attached,
|
||||
},
|
||||
prepared,
|
||||
codex_guardian_reviewer::ReviewReport::new(metadata),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ pub(super) struct ReviewRuntime {
|
||||
pub(super) session: Arc<Session>,
|
||||
pub(super) history_reset: CancellationToken,
|
||||
pub(super) context: GuardianReviewContext,
|
||||
pub(super) request: ReviewAction,
|
||||
pub(super) request: Arc<ReviewAction>,
|
||||
pub(super) reasons: ApprovalRequestReasons,
|
||||
pub(super) options: GuardianReviewOptions,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Runs one best-effort GV3 verdict per actor at a time when GV2 requires a fresh verdict.
|
||||
//! Only preparation and inference are shared. No evidence, client events or feedback are published.
|
||||
|
||||
use crate::guardian::routes_approval_policy_to_guardian;
|
||||
use crate::guardian::runtime::ReviewRuntime;
|
||||
use crate::guardian_review::ShadowReviewer;
|
||||
use codex_features::Feature;
|
||||
use codex_guardian_reviewer::GuardianReviewOutcome;
|
||||
use codex_guardian_reviewer::ReviewDeadline;
|
||||
use codex_guardian_reviewer::ReviewHost;
|
||||
use codex_guardian_reviewer::ReviewerTasks;
|
||||
use codex_guardian_reviewer::run_before_review_deadline;
|
||||
use codex_protocol::approvals::GuardianReviewReason;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ShadowSlot(Arc<Mutex<()>>);
|
||||
|
||||
pub(in crate::guardian) fn start(
|
||||
live: &ReviewRuntime,
|
||||
approval_id: &str,
|
||||
reason: GuardianReviewReason,
|
||||
) {
|
||||
// A fresh review cannot be cut short by a late async approval.
|
||||
if reason != GuardianReviewReason::FreshRequired {
|
||||
return;
|
||||
}
|
||||
let store = &live.session.services.thread_extension_data;
|
||||
let Some(observer) = store.get::<ShadowReviewer>() else {
|
||||
return;
|
||||
};
|
||||
let config = &live.context.turn().config;
|
||||
if observer.cancellation.is_cancelled()
|
||||
|| live.attached_reviewer.is_some()
|
||||
|| !config.features.enabled(Feature::GuardianV3Shadow)
|
||||
|| !config.features.enabled(Feature::GuardianV2)
|
||||
|| !routes_approval_policy_to_guardian(
|
||||
live.context.approval_policy,
|
||||
live.context.approvals_reviewer,
|
||||
)
|
||||
// Even an unenforced budget can add reminders to the live agent's prompt.
|
||||
|| live.session.work_budget().config().is_some()
|
||||
|| live.validate_action().is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(runtime) = store.get::<ReviewerTasks>() else {
|
||||
return;
|
||||
};
|
||||
// The live decision already holds a tracker token until this dispatch completes.
|
||||
if live.history_reset.is_cancelled() || runtime.cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let slot = store.get_or_init(ShadowSlot::default);
|
||||
let Ok(permit) = Arc::clone(&slot.0).try_lock_owned() else {
|
||||
tracing::debug!("Guardian shadow reviewer busy");
|
||||
return;
|
||||
};
|
||||
// Admission only. A later intake failure must not cancel this verdict.
|
||||
if observer.intake_stopped.is_cancelled() {
|
||||
tracing::debug!("Guardian shadow review skipped after intake stopped");
|
||||
return;
|
||||
}
|
||||
let deadline = ReviewDeadline::from_timeout(config.guardian_review_timeout);
|
||||
let mut shadow = live.clone();
|
||||
shadow.attached_reviewer = Some(Arc::clone(&observer.reviewer));
|
||||
shadow.context.review_execution = None;
|
||||
let review_id = approval_id.to_owned();
|
||||
let cancel =
|
||||
crate::exec::cancel_when_either(observer.cancellation.clone(), live.history_reset.clone());
|
||||
runtime.tasks.spawn(async move {
|
||||
let _cancel_on_drop = cancel.clone().drop_guard();
|
||||
let prepared = run_before_review_deadline(deadline, Some(&cancel), async {
|
||||
let (request, context) = shadow.approval_inputs().await?;
|
||||
shadow
|
||||
.prepare_approval(&review_id, request, context, deadline, &cancel)
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
let Ok(Ok(mut prepared)) = prepared else {
|
||||
tracing::debug!(%review_id, "Guardian shadow preparation failed");
|
||||
return;
|
||||
};
|
||||
let Some(attached) = &mut prepared.attached else {
|
||||
return;
|
||||
};
|
||||
attached.config.spawn_config.feedback_enabled = false;
|
||||
// Drive a single attempt to completion, including cancellation and draining the session.
|
||||
// A retry could observe instructions that arrived after the live decision.
|
||||
let (outcome, _analytics, _evidence) = shadow.attempt(&prepared, deadline, &cancel).await;
|
||||
drop(prepared);
|
||||
drop(permit);
|
||||
match outcome {
|
||||
GuardianReviewOutcome::Completed(assessment) => {
|
||||
tracing::debug!(%review_id, outcome = ?assessment.outcome, "Guardian shadow verdict");
|
||||
}
|
||||
GuardianReviewOutcome::Error(error) => {
|
||||
tracing::debug!(%review_id, reason = ?error.failure_reason(), "Guardian shadow failure");
|
||||
}
|
||||
GuardianReviewOutcome::CachedApproval => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -43,6 +43,8 @@ pub trait ReviewHost: Clone + Send + Sync + 'static {
|
||||
fn servicing_turn(&self) -> impl Future<Output = Option<(String, Arc<ModelInfo>)>> + Send;
|
||||
/// Returns the owning turn and optional target item after validating the action.
|
||||
fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision>;
|
||||
/// Optionally observe a synchronous review without affecting the live decision.
|
||||
fn start_shadow(&self, _approval_id: &str, _reason: GuardianReviewReason) {}
|
||||
/// Prepares evidence and accounting, with a client event only for supported actions.
|
||||
fn prepare(
|
||||
&self,
|
||||
@@ -108,6 +110,9 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
&[("route", "required_sync"), ("reason", reason.into())],
|
||||
);
|
||||
}
|
||||
if !self.cancellation.is_cancelled() {
|
||||
self.host.start_shadow(self.approval_id, reason);
|
||||
}
|
||||
let host_deadline = self.host_deadline;
|
||||
let deadline =
|
||||
host_deadline.unwrap_or_else(|| ReviewDeadline::from_timeout(self.timeout));
|
||||
|
||||
Reference in New Issue
Block a user