mirror of
https://github.com/openai/codex.git
synced 2026-11-26 23:40:43 +00:00
## Why An unrelated thread goal update could invalidate a pending Guardian V3 approval and trigger a second assessment even though the update never reached the attached reviewer. ## What changed Let attached Guardian V3 reviewers finish with the evidence admitted for the current attempt. Later evidence can inform subsequent reviews. Keep the cancellation, deadline, and root history checks for attached verdicts. ## Testing Update the app-server regression test to change the thread goal while an MCP approval is pending and verify that the original approval stands after a single assessment. GitOrigin-RevId: 6e7ffad243c7c59f0f97bdbe555886ff58531835
438 lines
17 KiB
Rust
438 lines
17 KiB
Rust
//! Binds an immutable action and root lifetime to fresh per-attempt authorization evidence.
|
|
//! The extension chooses effects; this adapter supplies evidence, validation and publication.
|
|
|
|
#[path = "attached_review.rs"]
|
|
mod attached;
|
|
use super::super::runtime::validate;
|
|
use super::*;
|
|
use crate::codex_thread::GuardianAuthorizationVersion;
|
|
use crate::guardian_review::ReviewPreparationError;
|
|
use attached::AttachedApproval;
|
|
use codex_config::config_toml::CircuitBreakAction;
|
|
use codex_guardian_context::CachedApprovalContext;
|
|
use codex_guardian_reviewer::ReviewDeadline;
|
|
use codex_guardian_reviewer::ReviewHost;
|
|
use codex_protocol::approvals::GuardianReviewReason;
|
|
use codex_protocol::error::CodexErrorDetails;
|
|
use codex_protocol::protocol::ErrorEvent;
|
|
|
|
type RootHistory = (codex_protocol::ThreadId, Option<[u8; 16]>, u64);
|
|
|
|
fn root_history_key(root: &crate::GuardianRootSnapshot) -> RootHistory {
|
|
(
|
|
root.root_thread_id,
|
|
root.authorization_version.root_runtime_id,
|
|
root.history_reset_version,
|
|
)
|
|
}
|
|
|
|
fn root_versions(root: crate::GuardianRootSnapshot) -> (GuardianAuthorizationVersion, u64) {
|
|
(root.authorization_version, root.review_context_revision)
|
|
}
|
|
|
|
pub(in crate::guardian) struct PreparedApproval {
|
|
request: GuardianApprovalRequest,
|
|
category: GuardianScope,
|
|
context: GuardianReviewContext,
|
|
// Unlike authorization, the original history lifetime cannot advance on retry.
|
|
root_history: Option<RootHistory>,
|
|
formatted_action: Option<String>,
|
|
attached: Option<AttachedApproval>,
|
|
}
|
|
|
|
pub(in crate::guardian) struct ApprovalEvidence {
|
|
store: Arc<GuardianReviewEvidence>,
|
|
authorization_version: GuardianAuthorizationVersion,
|
|
review_context_revision: u64,
|
|
root_versions: Option<(GuardianAuthorizationVersion, u64)>,
|
|
}
|
|
|
|
/// Authorization captured before an attempt, checked while the reviewer is still reserved.
|
|
pub(in crate::guardian) struct ReviewAuthorization {
|
|
user_message_revision: u64,
|
|
review_context_revision: u64,
|
|
root_history: Option<RootHistory>,
|
|
root_authorization_version: Option<GuardianAuthorizationVersion>,
|
|
root_review_context_revision: Option<u64>,
|
|
history_reset: CancellationToken,
|
|
}
|
|
|
|
/// Keeps observed context changes separate from the invalidation outcome.
|
|
/// A concurrent stop or history reset can take precedence over changed context.
|
|
pub(in crate::guardian) struct ReviewInvalidation {
|
|
pub(in crate::guardian) outcome: codex_guardian_reviewer::GuardianReviewSessionOutcome,
|
|
pub(in crate::guardian) context_changed: bool,
|
|
}
|
|
|
|
impl ReviewAuthorization {
|
|
pub(in crate::guardian) async fn invalidation(
|
|
&self,
|
|
session: &Session,
|
|
cancellation: Option<&CancellationToken>,
|
|
) -> Option<ReviewInvalidation> {
|
|
use codex_guardian_reviewer::GuardianReviewSessionOutcome;
|
|
|
|
let stopped = || {
|
|
self.history_reset.is_cancelled()
|
|
|| cancellation.is_some_and(CancellationToken::is_cancelled)
|
|
};
|
|
let root_snapshot = match session.guardian_root_snapshot().await {
|
|
Ok(snapshot) => snapshot,
|
|
Err(error) => {
|
|
let outcome = if matches!(error.details(), CodexErrorDetails::Timeout) && !stopped()
|
|
{
|
|
GuardianReviewSessionOutcome::TimedOut
|
|
} else {
|
|
tracing::warn!("Guardian root evidence unavailable during validation");
|
|
GuardianReviewSessionOutcome::Aborted
|
|
};
|
|
return Some(ReviewInvalidation {
|
|
outcome,
|
|
context_changed: false,
|
|
});
|
|
}
|
|
};
|
|
let root_history_changed =
|
|
self.root_history != root_snapshot.as_ref().map(root_history_key);
|
|
let root_review_changed = self.root_review_context_revision
|
|
!= root_snapshot
|
|
.as_ref()
|
|
.map(|snapshot| snapshot.review_context_revision);
|
|
let authorization_changed = self.root_authorization_version
|
|
!= root_snapshot.map(|snapshot| snapshot.authorization_version);
|
|
let history = session.conversation_history_snapshot().await;
|
|
let authorization_changed =
|
|
authorization_changed || self.user_message_revision != history.user_message_revision();
|
|
let review_context_changed = root_review_changed
|
|
|| self.review_context_revision != history.guardian_review_context_revision();
|
|
// An actual stop or history reset wins over a concurrent evidence change.
|
|
let outcome = if stopped() || root_history_changed {
|
|
Some(GuardianReviewSessionOutcome::Aborted)
|
|
} else if authorization_changed || review_context_changed {
|
|
tracing::info!(
|
|
thread_id = %session.thread_id,
|
|
authorization_changed,
|
|
review_context_changed,
|
|
"Guardian approval invalidated by changed review evidence"
|
|
);
|
|
Some(GuardianReviewSessionOutcome::StaleAuthorization)
|
|
} else {
|
|
None
|
|
};
|
|
outcome.map(|outcome| ReviewInvalidation {
|
|
outcome,
|
|
context_changed: authorization_changed || review_context_changed,
|
|
})
|
|
}
|
|
}
|
|
|
|
impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|
type Prepared = PreparedApproval;
|
|
type Evidence = ApprovalEvidence;
|
|
|
|
fn permissions(&self) -> Option<codex_guardian_context::PermissionContext> {
|
|
let request = self.request.request.as_ref().ok()?;
|
|
crate::guardian::permissions::for_request(request, Some(&self.context))
|
|
.ok()
|
|
.flatten()
|
|
}
|
|
|
|
async fn servicing_turn(
|
|
&self,
|
|
) -> Option<(String, Arc<codex_protocol::openai_models::ModelInfo>)> {
|
|
let active = self.session.active_turn.lock().await;
|
|
let turn = &active.as_ref()?.task.as_ref()?.turn_context;
|
|
Some((turn.sub_id.clone(), Arc::clone(&turn.model_info().model)))
|
|
}
|
|
|
|
async fn prepare(
|
|
&self,
|
|
review_id: &str,
|
|
review_reason: GuardianReviewReason,
|
|
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 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.
|
|
let root_turn_id = if assessment_turn_id == turn.sub_id {
|
|
context.reviewed_action_root_turn_id.clone()
|
|
} else {
|
|
None
|
|
};
|
|
let plugin_attribution = match plugin_attribution_override {
|
|
Some(attribution) => Some(attribution),
|
|
None if matches!(&request, GuardianApprovalRequest::ExecCommand { .. }) => {
|
|
let attribution_deadline =
|
|
deadline.cap(Instant::now() + GUARDIAN_PLUGIN_ATTRIBUTION_TIMEOUT);
|
|
let attribution = tokio::select! {
|
|
biased;
|
|
_ = cancellation.cancelled() => return Err(ReviewDecision::Abort),
|
|
attribution = tokio::time::timeout_at(
|
|
attribution_deadline,
|
|
plugin_attribution_for_guardian_request(&context, &request),
|
|
) => attribution,
|
|
};
|
|
match attribution {
|
|
Ok(attribution) => attribution,
|
|
Err(_) => {
|
|
tracing::warn!(
|
|
timeout_ms = GUARDIAN_PLUGIN_ATTRIBUTION_TIMEOUT.as_millis(),
|
|
"Guardian plugin attribution timed out"
|
|
);
|
|
None
|
|
}
|
|
}
|
|
}
|
|
None => plugin_attribution_for_guardian_request(&context, &request).await,
|
|
};
|
|
let (plugin_id, script_path) = plugin_attribution
|
|
.as_ref()
|
|
.map(PluginCommandAttribution::serialized_fields)
|
|
.unzip();
|
|
let metadata = codex_guardian_reviewer::ReviewMetadata {
|
|
thread_id: session.thread_id.to_string(),
|
|
turn_id: assessment_turn_id,
|
|
root_turn_id,
|
|
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
|
|
review_id: review_id.to_owned(),
|
|
target_item_id,
|
|
plugin_id,
|
|
script_path,
|
|
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 = session
|
|
.guardian_root_snapshot()
|
|
.await
|
|
.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 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}"
|
|
)),
|
|
})?;
|
|
Some(prepared)
|
|
} else {
|
|
None
|
|
};
|
|
Ok((
|
|
PreparedApproval {
|
|
formatted_action: format_guardian_action_pretty(&request).ok(),
|
|
request,
|
|
category: self.request.category,
|
|
context,
|
|
root_history,
|
|
attached,
|
|
},
|
|
codex_guardian_reviewer::ReviewReport::new(metadata),
|
|
))
|
|
}
|
|
|
|
async fn attempt(
|
|
&self,
|
|
prepared: &PreparedApproval,
|
|
deadline: ReviewDeadline,
|
|
cancellation: &CancellationToken,
|
|
) -> (
|
|
GuardianReviewOutcome,
|
|
GuardianReviewAnalyticsResult,
|
|
Option<ApprovalEvidence>,
|
|
) {
|
|
if self.history_reset.is_cancelled() || cancellation.is_cancelled() {
|
|
return (
|
|
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled),
|
|
GuardianReviewAnalyticsResult::without_session(),
|
|
None,
|
|
);
|
|
}
|
|
// Every attempt rebuilds the prompt from live history. Capture its revision and
|
|
// cache attribution anew too; a retried verdict must not use the first snapshot.
|
|
let session = &self.session;
|
|
let root_snapshot = match session.guardian_root_snapshot().await {
|
|
Ok(snapshot) => snapshot,
|
|
Err(error) => {
|
|
return (
|
|
GuardianReviewOutcome::Error(GuardianReviewError::PromptBuild {
|
|
message: error.to_string(),
|
|
}),
|
|
GuardianReviewAnalyticsResult::without_session(),
|
|
None,
|
|
);
|
|
}
|
|
};
|
|
if prepared.root_history != root_snapshot.as_ref().map(root_history_key) {
|
|
return (
|
|
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled),
|
|
GuardianReviewAnalyticsResult::without_session(),
|
|
None,
|
|
);
|
|
}
|
|
let root_versions = root_snapshot.map(root_versions);
|
|
let (root_authorization_version, root_review_context_revision) = root_versions.unzip();
|
|
// Keep the authorization revision even when no cacheable review evidence exists.
|
|
let history = session.conversation_history_snapshot().await;
|
|
let user_message_revision = history.user_message_revision();
|
|
let review_context_revision = history.guardian_review_context_revision();
|
|
let review_evidence = session
|
|
.services
|
|
.thread_extension_data
|
|
.get::<GuardianReviewEvidence>()
|
|
.map(|store| ApprovalEvidence {
|
|
authorization_version: store.authorization_version(history.as_ref()),
|
|
review_context_revision,
|
|
store,
|
|
root_versions,
|
|
});
|
|
drop(history);
|
|
let (outcome, analytics) = if let Some(attached) = &prepared.attached {
|
|
attached
|
|
.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(),
|
|
prepared.request.clone(),
|
|
prepared.category,
|
|
self.reasons.clone(),
|
|
ReviewAttemptOptions {
|
|
authorization: Some(authorization),
|
|
external_cancel: Some(cancellation.clone()),
|
|
deadline,
|
|
},
|
|
)
|
|
.await
|
|
};
|
|
|
|
let review_evidence = match &outcome {
|
|
GuardianReviewOutcome::Completed(_) => review_evidence,
|
|
GuardianReviewOutcome::CachedApproval | GuardianReviewOutcome::Error(_) => None,
|
|
};
|
|
(outcome, analytics, review_evidence)
|
|
}
|
|
|
|
async fn cached_approval_context(
|
|
&self,
|
|
prepared: &PreparedApproval,
|
|
) -> Option<CachedApprovalContext> {
|
|
let root = self.session.guardian_root_snapshot().await.ok()?;
|
|
let history = self.session.conversation_history_snapshot().await;
|
|
if self.history_reset.is_cancelled()
|
|
|| self.validate_action().is_err()
|
|
|| prepared.root_history != root.as_ref().map(root_history_key)
|
|
{
|
|
return None;
|
|
}
|
|
Some(CachedApprovalContext {
|
|
user_message_revision: history.user_message_revision(),
|
|
review_context_revision: history.guardian_review_context_revision(),
|
|
root_versions: root.map(root_versions),
|
|
})
|
|
}
|
|
|
|
fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision> {
|
|
let request = validate(&self.request, &self.context)?;
|
|
Ok((
|
|
guardian_request_turn_id(request, &self.context.turn().sub_id),
|
|
guardian_request_target_item_id(request),
|
|
))
|
|
}
|
|
|
|
async fn emit(&self, event: EventMsg) {
|
|
self.session.send_event(self.context.turn(), event).await;
|
|
}
|
|
|
|
async fn record_evidence(
|
|
&self,
|
|
prepared: &PreparedApproval,
|
|
evidence: ApprovalEvidence,
|
|
event: &codex_protocol::protocol::GuardianAssessmentEvent,
|
|
) {
|
|
if let Some(action) = &prepared.formatted_action {
|
|
evidence.store.record(
|
|
event,
|
|
action,
|
|
evidence.authorization_version,
|
|
evidence.review_context_revision,
|
|
evidence.root_versions,
|
|
&self.session.context_ids,
|
|
);
|
|
}
|
|
}
|
|
|
|
async fn interrupt(&self, turn_id: &str, warning: EventMsg, error: ErrorEvent) {
|
|
let Some(turn) = self.session.turn_context_for_sub_id(turn_id).await else {
|
|
return;
|
|
};
|
|
let error = (turn.config.guardian_circuit_break_action == CircuitBreakAction::Strict)
|
|
.then_some(error);
|
|
self.session
|
|
.interrupt_turn_with_warning(turn_id, warning, error)
|
|
.await;
|
|
}
|
|
}
|