mirror of
https://github.com/openai/codex.git
synced 2026-11-22 23:00:42 +00:00
Use serving assessments for adaptive Guardian review (#58075)
## What changed - Match final serving assessments to their response and output item, then retain them with tool invocations and code cells across waits. - Use matching assessments instead of asynchronous scoring for adaptive review: low-risk actions can skip synchronous review, while elevated-risk actions require it. - Revalidate captured authorization and policy before approval. Require fresh review for stale or incomplete authorization, preserve explicit review requirements, and discard assessments when hooks rewrite tool input. - Keep asynchronous scoring as the fallback when an assessment is missing or does not match. ## Testing Add integration coverage for direct and nested tool calls, hook rewrites, explicit escalation, interrupted responses, catalog-driven policy, incomplete authorization, and assessment retention across code-cell yields and waits. GitOrigin-RevId: 4346a227204137f018c03c34b302d6f1e9592c96
This commit is contained in:
@@ -32,6 +32,8 @@ pub trait SynchronousApprovalReviewer: Send + Sync {
|
||||
|
||||
/// Inputs to Guardian's policy choice. Conversation and scores stay thread-owned.
|
||||
pub struct ApprovalDecisionInput<'a> {
|
||||
/// Final serving value for this action. The host still requires fresh review when stale.
|
||||
pub serving_assessment: Option<bool>,
|
||||
pub approval_id: &'a str,
|
||||
/// Host tool invocation being approved, absent for approvals without a tool call.
|
||||
pub tool_call_id: Option<&'a str>,
|
||||
|
||||
@@ -116,6 +116,9 @@ impl McpToolContext {
|
||||
|
||||
/// Input supplied when the host starts executing one tool call.
|
||||
pub struct ToolStartInput<'a> {
|
||||
/// Final serving assessment for the unchanged action, including its code cell's value.
|
||||
/// When present, replaces asynchronous scoring; it does not grant execution permission.
|
||||
pub serving_assessment: Option<bool>,
|
||||
/// Store scoped to the host session runtime.
|
||||
pub session_store: &'a ExtensionData,
|
||||
/// Store scoped to this thread runtime.
|
||||
|
||||
@@ -249,6 +249,7 @@ async fn build_round_trips_every_contributor_category() {
|
||||
assert_eq!(registry.turn_item_contributors().len(), 1);
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
let input = codex_extension_api::ApprovalDecisionInput {
|
||||
serving_assessment: None,
|
||||
permissions: Some(&Default::default()),
|
||||
approval_id: "approval-1",
|
||||
tool_call_id: None,
|
||||
|
||||
@@ -160,6 +160,7 @@ async fn async_approval_revalidates_without_waiting_for_tracked_cleanup(state: A
|
||||
let analytics = AnalyticsEventsClient::disabled();
|
||||
let action = json!({});
|
||||
let request = ReviewRequest {
|
||||
serving_assessment: None,
|
||||
host: host.clone(),
|
||||
approval_id: "approval",
|
||||
tool_call_id: Some("call"),
|
||||
|
||||
@@ -25,6 +25,8 @@ use tokio_util::sync::CancellationToken;
|
||||
/// One captured action and its host-enforced constraints. Guardian derives the
|
||||
/// contributor input and owns cancellation for the complete review operation.
|
||||
pub struct ReviewRequest<'a, H> {
|
||||
/// Final serving value retained by the host for this action.
|
||||
pub serving_assessment: Option<bool>,
|
||||
pub host: H,
|
||||
pub approval_id: &'a str,
|
||||
pub tool_call_id: Option<&'a str>,
|
||||
@@ -102,6 +104,7 @@ impl<H: ReviewHost> ReviewRequest<'_, H> {
|
||||
};
|
||||
let permissions = self.host.permissions();
|
||||
let input = ApprovalDecisionInput {
|
||||
serving_assessment: self.serving_assessment,
|
||||
permissions: permissions.as_ref(),
|
||||
approval_id: self.approval_id,
|
||||
tool_call_id: self.tool_call_id,
|
||||
|
||||
@@ -104,7 +104,16 @@ impl GuardianApprovalReviewer {
|
||||
if adaptive && let Some(metrics) = input.metrics.as_deref() {
|
||||
metrics.counter("codex.guardian_v2.adaptive_review", /*inc*/ 1, &[]);
|
||||
}
|
||||
let reason = if adaptive {
|
||||
let reason = if input.require_fresh_review {
|
||||
GuardianReviewReason::FreshRequired
|
||||
} else if !adaptive {
|
||||
GuardianReviewReason::Policy
|
||||
} else if let Some(requires_review) = input.serving_assessment {
|
||||
if !requires_review {
|
||||
return ApprovalDecision::Allow;
|
||||
}
|
||||
GuardianReviewReason::ElevatedRisk
|
||||
} else {
|
||||
match guardian_config.as_ref() {
|
||||
Some(config) => {
|
||||
match cached_evidence(thread, input, config, &policy, input.metrics.as_deref())
|
||||
@@ -119,10 +128,6 @@ impl GuardianApprovalReviewer {
|
||||
GuardianReviewReason::ScoringFailure
|
||||
}
|
||||
}
|
||||
} else if input.require_fresh_review {
|
||||
GuardianReviewReason::FreshRequired
|
||||
} else {
|
||||
GuardianReviewReason::Policy
|
||||
};
|
||||
tracing::debug!(
|
||||
decision_source = "synchronous_assessment",
|
||||
@@ -157,7 +162,9 @@ impl GuardianApprovalReviewer {
|
||||
&[
|
||||
(
|
||||
"route",
|
||||
if adaptive {
|
||||
if input.serving_assessment.is_some() {
|
||||
"serving_assessment"
|
||||
} else if adaptive {
|
||||
"async_fallback"
|
||||
} else {
|
||||
"required_sync"
|
||||
@@ -169,7 +176,14 @@ impl GuardianApprovalReviewer {
|
||||
}
|
||||
match input
|
||||
.synchronous_reviewer
|
||||
.review(reason, Some(Box::pin(async_approval)))
|
||||
.review(
|
||||
reason,
|
||||
if input.serving_assessment.is_some() {
|
||||
None
|
||||
} else {
|
||||
Some(Box::pin(async_approval))
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(decision) => ApprovalDecision::Reviewed(decision),
|
||||
|
||||
@@ -1,51 +1,3 @@
|
||||
//! Binds cached scores to the user authorization, review context, and model policy they evaluated.
|
||||
//! Uses the host authorization snapshot for asynchronous score freshness.
|
||||
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::GuardianAuthorizationVersion;
|
||||
use codex_core::context::GuardianReviewEvidence;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct ScoreAuthorization {
|
||||
pub(super) permissions: codex_guardian_context::PermissionContext,
|
||||
pub(super) settings: codex_protocol::protocol::ThreadSettingsSnapshot,
|
||||
pub(super) environments: Vec<codex_protocol::protocol::TurnEnvironmentSelection>,
|
||||
pub(super) local: GuardianAuthorizationVersion,
|
||||
pub(super) review_context_revision: u64,
|
||||
pub(super) root: Option<GuardianAuthorizationVersion>,
|
||||
pub(super) root_review_context_revision: Option<u64>,
|
||||
pub(super) model: Option<std::sync::Arc<codex_protocol::openai_models::ModelInfo>>,
|
||||
}
|
||||
|
||||
impl ScoreAuthorization {
|
||||
pub(super) async fn is_current(&self, thread: &CodexThread) -> bool {
|
||||
self == &Self::current(thread, &self.permissions).await
|
||||
}
|
||||
|
||||
pub(super) async fn current(
|
||||
thread: &CodexThread,
|
||||
permissions: &codex_guardian_context::PermissionContext,
|
||||
) -> Self {
|
||||
let root = thread.guardian_root_snapshot().await;
|
||||
let history = thread.conversation_history_snapshot().await;
|
||||
let local = thread
|
||||
.thread_extension_data()
|
||||
.get_or_init(GuardianReviewEvidence::default)
|
||||
.authorization_version(history.as_ref());
|
||||
Self {
|
||||
permissions: permissions.clone(),
|
||||
settings: thread.thread_settings_snapshot().await,
|
||||
environments: thread
|
||||
.config_snapshot()
|
||||
.await
|
||||
.environment_selections()
|
||||
.to_vec(),
|
||||
local,
|
||||
review_context_revision: history.guardian_review_context_revision(),
|
||||
root: root.as_ref().map(|snapshot| snapshot.authorization_version),
|
||||
root_review_context_revision: root.map(|snapshot| snapshot.review_context_revision),
|
||||
model: thread
|
||||
.thread_extension_data()
|
||||
.get::<codex_protocol::openai_models::ModelInfo>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) use codex_core::GuardianScoreAuthorization as ScoreAuthorization;
|
||||
|
||||
@@ -227,6 +227,7 @@ async fn assert_catalog_budget(evidence: BudgetEvidence) -> Result<()> {
|
||||
};
|
||||
fixture.registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &fixture.session_store,
|
||||
thread_store,
|
||||
|
||||
@@ -659,6 +659,7 @@ async fn delayed_classification_skips_after_newer_score_and_history_complete() -
|
||||
let history = fixture.test.codex.conversation_history_snapshot().await;
|
||||
let observe = |call_id, permissions| {
|
||||
fixture.registry.tool_lifecycle_contributors()[0].on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions,
|
||||
session_store: &fixture.session_store,
|
||||
thread_store: store,
|
||||
|
||||
@@ -343,6 +343,7 @@ async fn installed_extension_uses_http_after_warm_socket_auth_expires() -> Resul
|
||||
}
|
||||
registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &session_store,
|
||||
thread_store,
|
||||
@@ -622,6 +623,7 @@ async fn sandboxed_shell_classification_respects_review_scope() -> Result<()> {
|
||||
] {
|
||||
fixture.registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { panic!("unexpected permission resolution") }),
|
||||
session_store: &fixture.session_store,
|
||||
thread_store,
|
||||
@@ -721,6 +723,7 @@ async fn computer_use_only_scores_cannot_approve_other_actions() -> Result<()> {
|
||||
};
|
||||
fixture.registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &fixture.session_store,
|
||||
thread_store,
|
||||
@@ -1091,6 +1094,7 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
|
||||
registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &session_store,
|
||||
thread_store,
|
||||
@@ -1212,6 +1216,7 @@ impl GuardianFailureFixture {
|
||||
};
|
||||
self.registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &self.session_store,
|
||||
thread_store,
|
||||
@@ -2508,6 +2513,7 @@ async fn contributor_skips_required_models_in_standard_scope() -> Result<()> {
|
||||
};
|
||||
registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { panic!("unexpected permission resolution") }),
|
||||
session_store: &session_store,
|
||||
thread_store,
|
||||
@@ -2813,6 +2819,7 @@ async fn contributor_counts_failed_thread_lookups_toward_score_lag() -> Result<(
|
||||
};
|
||||
registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &session_store,
|
||||
thread_store,
|
||||
@@ -3345,6 +3352,7 @@ async fn assert_parent_compaction_reuse(parent_context_for_review: bool) -> Resu
|
||||
|
||||
registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &session_store,
|
||||
thread_store,
|
||||
@@ -3439,6 +3447,7 @@ async fn assert_parent_compaction_reuse(parent_context_for_review: bool) -> Resu
|
||||
let call_id = format!("call-{}", index + 2);
|
||||
registry.tool_lifecycle_contributors()[0]
|
||||
.on_tool_start(ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &session_store,
|
||||
thread_store,
|
||||
@@ -3545,6 +3554,7 @@ async fn cached_approval_respects_action_order_and_wrapper_lag() -> Result<()> {
|
||||
},
|
||||
};
|
||||
progress.observe(&ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: &fixture.session_store,
|
||||
thread_store: store,
|
||||
@@ -3692,6 +3702,7 @@ async fn cached_approval(
|
||||
}
|
||||
};
|
||||
let input = codex_extension_api::ApprovalDecisionInput {
|
||||
serving_assessment: None,
|
||||
permissions: Some(&Default::default()),
|
||||
approval_id: "cache-probe",
|
||||
tool_call_id: action.get("id").and_then(serde_json::Value::as_str),
|
||||
@@ -3745,6 +3756,7 @@ fn seed_cached_score(
|
||||
|
||||
fn observe_unscored_call(progress: &GuardianV2ScoreProgress, store: &ExtensionData) -> usize {
|
||||
progress.observe(&ToolStartInput {
|
||||
serving_assessment: None,
|
||||
permissions: Box::pin(async { Some(Default::default()) }),
|
||||
session_store: store,
|
||||
thread_store: store,
|
||||
|
||||
@@ -65,6 +65,30 @@ impl GuardianV2Extension {
|
||||
let Some(score_progress) = input.thread_store.get::<GuardianV2ScoreProgress>() else {
|
||||
return;
|
||||
};
|
||||
let is_js_execution = input.mcp_tool.is_some_and(|tool| {
|
||||
let info = tool.tool_info();
|
||||
is_node_repl_backed_connector(&info.server_name, info.connector_id.as_deref())
|
||||
&& if info.server_name == "codex_apps" {
|
||||
info.tool
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.get("_codex_apps"))
|
||||
.and_then(|meta| meta.get("resource_uri"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(|uri| uri.trim_matches('/').rsplit('/').next())
|
||||
== Some("js")
|
||||
} else {
|
||||
info.tool.name == "js"
|
||||
}
|
||||
});
|
||||
if input.serving_assessment.is_some() {
|
||||
if is_js_execution {
|
||||
score_progress.observe_js_execution();
|
||||
}
|
||||
let index = score_progress.observe(&input);
|
||||
score_progress.invalidate(index);
|
||||
return;
|
||||
}
|
||||
let parent_model = input.thread_store.get::<ModelInfo>();
|
||||
let policy = guardian_config.policy_for_model(parent_model.as_deref());
|
||||
if !policy.scoring_enabled() {
|
||||
@@ -123,22 +147,7 @@ impl GuardianV2Extension {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if input.mcp_tool.is_some_and(|tool| {
|
||||
let info = tool.tool_info();
|
||||
is_node_repl_backed_connector(&info.server_name, info.connector_id.as_deref())
|
||||
&& if info.server_name == "codex_apps" {
|
||||
info.tool
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.get("_codex_apps"))
|
||||
.and_then(|meta| meta.get("resource_uri"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(|uri| uri.trim_matches('/').rsplit('/').next())
|
||||
== Some("js")
|
||||
} else {
|
||||
info.tool.name == "js"
|
||||
}
|
||||
}) {
|
||||
if is_js_execution {
|
||||
score_progress.observe_js_execution();
|
||||
}
|
||||
let metrics = score_progress.metrics.clone();
|
||||
|
||||
Reference in New Issue
Block a user