mirror of
https://github.com/openai/codex.git
synced 2026-11-22 23:16:05 +00:00
## Why A checkpoint produced by a previous model may be incompatible with the selected Guardian reviewer. Legacy review must retain user restrictions and verified answers across compaction and restart until a compatible checkpoint is available. ## What changed - Expose retained user evidence independently of whether Guardian reviews the legacy transcript or parent context. - Resolve the selected reviewer's compaction compatibility hash during resume and remote compaction. Preserve the legacy transcript when checkpoint compatibility is unknown or mismatched. - Activate parent-context review immediately after compatible compaction and invalidate pending reviews bound to the previous evidence policy. Ordinary compaction preserves pending reviews. - Keep strict compatibility checks for previously migrated checkpoints whose complete legacy transcript is no longer available. ## Testing Add coverage for mismatched checkpoint hashes, retained evidence during legacy review, and pending-review cancellation on migration. Add a request-history scenario covering a model switch, incompatible automatic compaction, restart, and compatible manual compaction with preserved user restrictions and verified answers. GitOrigin-RevId: b52bfd7c21ce7ebed482174c8d7c327e50b1ada8
291 lines
11 KiB
Rust
291 lines
11 KiB
Rust
//! Supplies host review preparation and context-dependent configuration.
|
|
//! Guardian's extension owns routing, execution, reporting and denial accounting.
|
|
|
|
#[path = "review_request.rs"]
|
|
mod request;
|
|
|
|
use crate::context::GuardianContextMode;
|
|
use codex_analytics::GuardianApprovalRequestSource;
|
|
use codex_analytics::GuardianReviewAnalyticsResult;
|
|
use codex_core_plugins::PluginCommandAttribution;
|
|
use codex_features::Feature;
|
|
use codex_guardian_reviewer::GuardianReviewError;
|
|
use codex_guardian_reviewer::GuardianReviewOutcome;
|
|
#[cfg(test)]
|
|
use codex_guardian_reviewer::GuardianReviewSessionLimits;
|
|
use codex_guardian_reviewer::ReviewModel;
|
|
use codex_protocol::protocol::EventMsg;
|
|
use codex_protocol::protocol::InternalSessionSource;
|
|
use codex_protocol::protocol::ReviewDecision;
|
|
use codex_protocol::protocol::SessionSource;
|
|
use codex_protocol::protocol::SubAgentSource;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
use tokio::time::Instant;
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
use crate::context::GuardianNodeReplPolicy;
|
|
use crate::context::GuardianReviewEvidence;
|
|
use crate::session::session::Session;
|
|
|
|
use super::ApprovalRequestReasons;
|
|
#[cfg(test)]
|
|
use super::GUARDIAN_REVIEW_TIMEOUT;
|
|
use super::GUARDIAN_REVIEWER_NAME;
|
|
use super::GuardianApprovalRequest;
|
|
use super::GuardianAssessmentOutcome;
|
|
use super::GuardianReviewContext;
|
|
use super::approval_request::format_guardian_action_pretty;
|
|
use super::approval_request::guardian_assessment_action;
|
|
use super::approval_request::guardian_request_target_item_id;
|
|
use super::approval_request::guardian_request_turn_id;
|
|
use super::approval_request::guardian_reviewed_action;
|
|
use super::review_session::GuardianReviewSessionParams;
|
|
use super::review_session::build_guardian_review_session_config;
|
|
use codex_guardian_reviewer::guardian_output_schema;
|
|
|
|
const GUARDIAN_PLUGIN_ATTRIBUTION_TIMEOUT: Duration = Duration::from_secs(5);
|
|
|
|
async fn plugin_attribution_for_guardian_request(
|
|
context: &GuardianReviewContext,
|
|
request: &GuardianApprovalRequest,
|
|
) -> Option<PluginCommandAttribution> {
|
|
let turn = context.turn();
|
|
match request {
|
|
GuardianApprovalRequest::ExecCommand {
|
|
environment_id,
|
|
command,
|
|
cwd,
|
|
..
|
|
} => {
|
|
let turn_environment =
|
|
context
|
|
.environments()
|
|
.turn_environments()
|
|
.find(|environment| {
|
|
environment.selection.environment_id.as_str() == environment_id
|
|
})?;
|
|
if turn_environment.environment.is_remote() {
|
|
let file_system = turn_environment.environment.get_filesystem();
|
|
turn.plugin_attribution_for_executor_command(command, cwd, file_system.as_ref())
|
|
.await
|
|
} else {
|
|
cwd.to_abs_path()
|
|
.ok()
|
|
.and_then(|cwd| turn.plugin_attribution_for_command(command, &cwd))
|
|
}
|
|
}
|
|
#[cfg(unix)]
|
|
GuardianApprovalRequest::Execve {
|
|
program, argv, cwd, ..
|
|
} => {
|
|
let command = if argv.is_empty() {
|
|
vec![program.clone()]
|
|
} else {
|
|
std::iter::once(program.clone())
|
|
.chain(argv.iter().skip(1).cloned())
|
|
.collect()
|
|
};
|
|
turn.plugin_attribution_for_command(&command, cwd)
|
|
}
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn new_guardian_review_id() -> String {
|
|
uuid::Uuid::new_v4().to_string()
|
|
}
|
|
|
|
pub(crate) use codex_guardian_reviewer::routes_approval_policy_to_guardian;
|
|
|
|
pub(crate) fn is_basic_session_source(session_source: &SessionSource) -> bool {
|
|
match session_source {
|
|
SessionSource::SubAgent(SubAgentSource::Other(label)) => label == GUARDIAN_REVIEWER_NAME,
|
|
SessionSource::Internal(InternalSessionSource::Guardian) => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct GuardianReviewOptions {
|
|
/// Requires Guardian rather than a manual approval; cached evidence may still satisfy it.
|
|
pub(crate) require_guardian: bool,
|
|
pub(crate) plugin_attribution_override: Option<PluginCommandAttribution>,
|
|
pub(crate) approval_request_source: GuardianApprovalRequestSource,
|
|
pub(crate) external_cancel: Option<CancellationToken>,
|
|
/// Escalate from extension fast approval to the synchronous Guardian reviewer.
|
|
pub(crate) require_synchronous_review: bool,
|
|
}
|
|
|
|
pub(super) struct GuardianReviewSessionConfig {
|
|
pub(super) spawn_config: crate::config::Config,
|
|
pub(super) node_repl_policy: GuardianNodeReplPolicy,
|
|
pub(super) compaction_model_hash: Option<String>,
|
|
review_model: ReviewModel,
|
|
}
|
|
|
|
pub(super) async fn guardian_review_session_config(
|
|
session: &Session,
|
|
context: &GuardianReviewContext,
|
|
) -> anyhow::Result<GuardianReviewSessionConfig> {
|
|
let turn = context.turn();
|
|
let network_proxy = session.services.network_proxy.load_full();
|
|
let live_network_config = match network_proxy.as_ref() {
|
|
Some(network_proxy) => Some(network_proxy.proxy().current_cfg().await?),
|
|
None => None,
|
|
};
|
|
let (review_model, guardian_model_info) =
|
|
super::reviewer_config::resolve_review_model(session, context).await;
|
|
let reviewer_config = session
|
|
.services
|
|
.thread_extension_data
|
|
.get::<codex_guardian_reviewer::ReviewerConfig<crate::config::Config>>()
|
|
.ok_or_else(|| anyhow::anyhow!("Guardian reviewer configuration is not installed"))?;
|
|
let mut spawn_config = build_guardian_review_session_config(
|
|
(reviewer_config.0)(turn.config.as_ref())?,
|
|
live_network_config,
|
|
review_model.model.as_str(),
|
|
review_model.reasoning_effort.clone(),
|
|
context.reasoning_summary,
|
|
context.personality,
|
|
guardian_model_info.model_messages.as_ref(),
|
|
)?;
|
|
if context.model_info.computer_use_review_required() {
|
|
spawn_config
|
|
.features
|
|
.enable(Feature::RetainClientDeveloperMessages)
|
|
.map_err(|error| {
|
|
anyhow::anyhow!(
|
|
"guardian review session could not preserve REPL developer policy: {error}"
|
|
)
|
|
})?;
|
|
}
|
|
if review_model.model != context.model_info.slug {
|
|
spawn_config.model_context_window = None;
|
|
spawn_config.model_auto_compact_token_limit = None;
|
|
}
|
|
Ok(GuardianReviewSessionConfig {
|
|
spawn_config,
|
|
compaction_model_hash: guardian_model_info.comp_hash.clone(),
|
|
node_repl_policy: GuardianNodeReplPolicy::from_model_messages(
|
|
guardian_model_info.model_messages.as_ref(),
|
|
),
|
|
review_model,
|
|
})
|
|
}
|
|
|
|
/// Runs the guardian in a locked-down reusable review session.
|
|
///
|
|
/// The guardian itself should not mutate state or trigger further approvals, so
|
|
/// it is pinned to a read-only sandbox with `approval_policy = never` and
|
|
/// nonessential agent features disabled. When the cached trunk session is idle,
|
|
/// later approvals append onto that same guardian conversation to preserve a
|
|
/// stable prompt-cache key. If the trunk is already busy, the review runs in an
|
|
/// ephemeral fork from the last committed trunk rollout so parallel approvals
|
|
/// do not block each other or mutate the cached thread. The trunk is recreated
|
|
/// when the effective review-session config changes, and any future compaction
|
|
/// must continue to preserve the guardian policy as exact top-level developer
|
|
/// context. It may still reuse the parent's managed-network allowlist for
|
|
/// read-only checks, but it intentionally runs without inherited exec-policy
|
|
/// rules.
|
|
async fn run_guardian_review_session_before_deadline(
|
|
session: Arc<Session>,
|
|
context: GuardianReviewContext,
|
|
request: GuardianApprovalRequest,
|
|
reasons: ApprovalRequestReasons,
|
|
schema: serde_json::Value,
|
|
external_cancel: Option<CancellationToken>,
|
|
deadline: Instant,
|
|
) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) {
|
|
let Some(pool) = session.guardian_review_session() else {
|
|
return (
|
|
GuardianReviewOutcome::Error(GuardianReviewError::prompt_build(anyhow::anyhow!(
|
|
"Guardian extension is not installed for this thread"
|
|
))),
|
|
GuardianReviewAnalyticsResult::without_session(),
|
|
);
|
|
};
|
|
let session_config = match guardian_review_session_config(session.as_ref(), &context).await {
|
|
Ok(session_config) => session_config,
|
|
Err(err) => {
|
|
return (
|
|
GuardianReviewOutcome::Error(GuardianReviewError::prompt_build(err)),
|
|
GuardianReviewAnalyticsResult::without_session(),
|
|
);
|
|
}
|
|
};
|
|
let (session_outcome, session_analytics_result) =
|
|
Box::pin(super::review_session::run_guardian_review_session(
|
|
pool,
|
|
GuardianReviewSessionParams {
|
|
parent_session: Arc::clone(&session),
|
|
parent_context: context.clone(),
|
|
parent_history: session.clone_history().await,
|
|
spawn_config: session_config.spawn_config,
|
|
node_repl_policy: session_config.node_repl_policy,
|
|
request,
|
|
reasons,
|
|
schema,
|
|
review_model: session_config.review_model,
|
|
compaction_model_hash: session_config.compaction_model_hash,
|
|
reasoning_summary: context.reasoning_summary,
|
|
personality: context.personality,
|
|
external_cancel,
|
|
deadline,
|
|
},
|
|
))
|
|
.await;
|
|
|
|
(session_outcome.into(), session_analytics_result)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(super) async fn run_guardian_review_session_with_retry(
|
|
session: Arc<Session>,
|
|
context: impl Into<GuardianReviewContext>,
|
|
request: GuardianApprovalRequest,
|
|
reasons: ApprovalRequestReasons,
|
|
schema: serde_json::Value,
|
|
external_cancel: Option<CancellationToken>,
|
|
max_attempts: i64,
|
|
) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) {
|
|
run_guardian_review_session_with_retry_before_deadline(
|
|
session,
|
|
context,
|
|
request,
|
|
reasons,
|
|
schema,
|
|
external_cancel,
|
|
GuardianReviewSessionLimits {
|
|
max_attempts,
|
|
deadline: Instant::now() + GUARDIAN_REVIEW_TIMEOUT,
|
|
},
|
|
)
|
|
.await
|
|
}
|
|
|
|
#[cfg(test)]
|
|
async fn run_guardian_review_session_with_retry_before_deadline(
|
|
session: Arc<Session>,
|
|
context: impl Into<GuardianReviewContext>,
|
|
request: GuardianApprovalRequest,
|
|
reasons: ApprovalRequestReasons,
|
|
schema: serde_json::Value,
|
|
external_cancel: Option<CancellationToken>,
|
|
limits: GuardianReviewSessionLimits,
|
|
) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) {
|
|
let context = context.into();
|
|
codex_guardian_reviewer::run_with_retry(limits, external_cancel.as_ref(), |deadline| {
|
|
run_guardian_review_session_before_deadline(
|
|
Arc::clone(&session),
|
|
context.clone(),
|
|
request.clone(),
|
|
reasons.clone(),
|
|
schema.clone(),
|
|
external_cancel.clone(),
|
|
deadline,
|
|
)
|
|
})
|
|
.await
|
|
}
|