aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
//! Owns Guardian approval-request data, classification, and assessment/reporting mappings.
|
||||
//! Request debug output excludes action arguments, which may contain credentials.
|
||||
|
||||
use codex_analytics::GuardianReviewedAction;
|
||||
use crate::GuardianReviewedAction;
|
||||
use codex_protocol::approvals::GuardianAssessmentAction;
|
||||
use codex_protocol::approvals::GuardianCommandSource;
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Converts reviewer outcomes into decisions and reports. The host publishes these
|
||||
//! reports and applies them only to the action whose evidence was reviewed.
|
||||
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_analytics::GuardianReviewDecision;
|
||||
use codex_analytics::GuardianReviewTerminalStatus;
|
||||
use crate::GuardianReviewDecision;
|
||||
use crate::GuardianReviewDetails;
|
||||
use crate::GuardianReviewTerminalStatus;
|
||||
use codex_prompts::ResolvedModelMessages;
|
||||
use codex_prompts::render_guardian_rejection;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
@@ -31,7 +31,7 @@ pub struct ReviewCompletion {
|
||||
/// Absent for actions reviewed without an action-specific client report.
|
||||
pub event: Option<GuardianAssessmentEvent>,
|
||||
pub warning: Option<String>,
|
||||
pub analytics: GuardianReviewAnalyticsResult,
|
||||
pub details: GuardianReviewDetails,
|
||||
/// Only completed assessments may enter the evidence cache or count as policy denials.
|
||||
pub assessment_outcome: Option<GuardianAssessmentOutcome>,
|
||||
}
|
||||
@@ -41,7 +41,7 @@ pub fn complete_review(
|
||||
model: &ModelInfo,
|
||||
require_guardian: bool,
|
||||
mut event: Option<GuardianAssessmentEvent>,
|
||||
mut analytics: GuardianReviewAnalyticsResult,
|
||||
mut details: GuardianReviewDetails,
|
||||
) -> ReviewCompletion {
|
||||
let completed_assessment = match &outcome {
|
||||
GuardianReviewOutcome::Completed(assessment) => Some(assessment.outcome),
|
||||
@@ -54,43 +54,43 @@ pub fn complete_review(
|
||||
event.decision_source = None;
|
||||
event.rationale = Some("Approved using a current low-risk async score.".to_owned());
|
||||
}
|
||||
analytics.decision = GuardianReviewDecision::Approved;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::Approved;
|
||||
analytics.failure_reason = None;
|
||||
details.decision = GuardianReviewDecision::Approved;
|
||||
details.terminal_status = GuardianReviewTerminalStatus::Approved;
|
||||
details.failure_reason = None;
|
||||
return ReviewCompletion {
|
||||
decision: Some(ReviewDecision::Approved),
|
||||
event,
|
||||
warning: None,
|
||||
analytics,
|
||||
details,
|
||||
assessment_outcome: None,
|
||||
};
|
||||
}
|
||||
GuardianReviewOutcome::Completed(assessment) => {
|
||||
let approved = matches!(assessment.outcome, GuardianAssessmentOutcome::Allow);
|
||||
analytics.decision = if approved {
|
||||
details.decision = if approved {
|
||||
GuardianReviewDecision::Approved
|
||||
} else {
|
||||
GuardianReviewDecision::Denied
|
||||
};
|
||||
analytics.terminal_status = if approved {
|
||||
details.terminal_status = if approved {
|
||||
GuardianReviewTerminalStatus::Approved
|
||||
} else {
|
||||
GuardianReviewTerminalStatus::Denied
|
||||
};
|
||||
analytics.failure_reason = None;
|
||||
analytics.risk_level = Some(assessment.risk_level);
|
||||
analytics.user_authorization = Some(assessment.user_authorization);
|
||||
analytics.outcome = Some(assessment.outcome);
|
||||
details.failure_reason = None;
|
||||
details.risk_level = Some(assessment.risk_level);
|
||||
details.user_authorization = Some(assessment.user_authorization);
|
||||
details.outcome = Some(assessment.outcome);
|
||||
assessment
|
||||
}
|
||||
GuardianReviewOutcome::Error(error) => {
|
||||
analytics.failure_reason = Some(error.failure_reason());
|
||||
details.failure_reason = Some(error.failure_reason());
|
||||
match error {
|
||||
GuardianReviewError::InputBudgetExceeded if !require_guardian => {
|
||||
let rationale =
|
||||
format!("Automatic approval review failed: {INPUT_BUDGET_MESSAGE}");
|
||||
analytics.decision = GuardianReviewDecision::Aborted;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::Aborted;
|
||||
details.decision = GuardianReviewDecision::Aborted;
|
||||
details.terminal_status = GuardianReviewTerminalStatus::Aborted;
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::Aborted;
|
||||
event.rationale = Some(rationale.clone());
|
||||
@@ -99,14 +99,14 @@ pub fn complete_review(
|
||||
decision: None,
|
||||
event,
|
||||
warning: Some(rationale),
|
||||
analytics,
|
||||
details,
|
||||
assessment_outcome: None,
|
||||
};
|
||||
}
|
||||
GuardianReviewError::Timeout => {
|
||||
let rationale = "Automatic approval review timed out while evaluating the requested approval.".to_string();
|
||||
analytics.decision = GuardianReviewDecision::Denied;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::TimedOut;
|
||||
details.decision = GuardianReviewDecision::Denied;
|
||||
details.terminal_status = GuardianReviewTerminalStatus::TimedOut;
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::TimedOut;
|
||||
event.rationale = Some(rationale.clone());
|
||||
@@ -115,13 +115,13 @@ pub fn complete_review(
|
||||
decision: Some(ReviewDecision::TimedOut),
|
||||
event,
|
||||
warning: Some(rationale),
|
||||
analytics,
|
||||
details,
|
||||
assessment_outcome: None,
|
||||
};
|
||||
}
|
||||
GuardianReviewError::Cancelled => {
|
||||
analytics.decision = GuardianReviewDecision::Aborted;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::Aborted;
|
||||
details.decision = GuardianReviewDecision::Aborted;
|
||||
details.terminal_status = GuardianReviewTerminalStatus::Aborted;
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::Aborted;
|
||||
}
|
||||
@@ -129,7 +129,7 @@ pub fn complete_review(
|
||||
decision: Some(ReviewDecision::Abort),
|
||||
event,
|
||||
warning: None,
|
||||
analytics,
|
||||
details,
|
||||
assessment_outcome: None,
|
||||
};
|
||||
}
|
||||
@@ -150,8 +150,8 @@ pub fn complete_review(
|
||||
"guardian review failed"
|
||||
}
|
||||
};
|
||||
analytics.decision = GuardianReviewDecision::Denied;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::FailedClosed;
|
||||
details.decision = GuardianReviewDecision::Denied;
|
||||
details.terminal_status = GuardianReviewTerminalStatus::FailedClosed;
|
||||
let rationale = format!("Automatic approval review failed: {message}");
|
||||
// Keep the existing blocked status for client compatibility.
|
||||
if let Some(event) = event.as_mut() {
|
||||
@@ -164,7 +164,7 @@ pub fn complete_review(
|
||||
))),
|
||||
event,
|
||||
warning: Some(rationale),
|
||||
analytics,
|
||||
details,
|
||||
assessment_outcome: None,
|
||||
};
|
||||
}
|
||||
@@ -214,7 +214,7 @@ pub fn complete_review(
|
||||
decision: Some(decision),
|
||||
event,
|
||||
warning: Some(warning),
|
||||
analytics,
|
||||
details,
|
||||
assessment_outcome: completed_assessment,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ use crate::ReviewDeadline;
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::GuardianReviewDetails;
|
||||
use anyhow::anyhow;
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_protocol::protocol::ErrorEvent;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
@@ -71,7 +71,7 @@ pub async fn wait_for_guardian_review(
|
||||
expected_turn_id: &str,
|
||||
deadline: ReviewDeadline,
|
||||
external_cancel: Option<&CancellationToken>,
|
||||
analytics_result: &mut GuardianReviewAnalyticsResult,
|
||||
details: &mut GuardianReviewDetails,
|
||||
) -> ReviewTurnResult {
|
||||
let timeout = deadline.wait();
|
||||
tokio::pin!(timeout);
|
||||
@@ -117,7 +117,7 @@ pub async fn wait_for_guardian_review(
|
||||
}
|
||||
Ok(event) => match event.msg {
|
||||
EventMsg::TurnComplete(turn_complete) => {
|
||||
analytics_result.time_to_first_token_ms = turn_complete
|
||||
details.time_to_first_token_ms = turn_complete
|
||||
.time_to_first_token_ms
|
||||
.and_then(|ms| u64::try_from(ms).ok());
|
||||
if turn_complete.last_agent_message.is_none()
|
||||
|
||||
@@ -41,6 +41,17 @@ mod reporting;
|
||||
mod retry;
|
||||
mod review;
|
||||
mod review_action;
|
||||
mod review_result;
|
||||
pub use review_result::GuardianAdditionalPermissions;
|
||||
pub use review_result::GuardianApprovalRequestSource;
|
||||
pub use review_result::GuardianReviewDecision;
|
||||
pub use review_result::GuardianReviewDetails;
|
||||
pub use review_result::GuardianReviewFailureReason;
|
||||
pub use review_result::GuardianReviewSessionDetails;
|
||||
pub use review_result::GuardianReviewSessionKind;
|
||||
pub use review_result::GuardianReviewTerminalStatus;
|
||||
pub use review_result::GuardianReviewedAction;
|
||||
pub use review_result::now_unix_millis;
|
||||
mod review_evidence;
|
||||
mod review_state;
|
||||
pub use review_state::CheckpointRecovery;
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_analytics::GuardianApprovalRequestSource;
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_analytics::GuardianReviewDecision;
|
||||
use codex_analytics::GuardianReviewFailureReason;
|
||||
use codex_analytics::GuardianReviewSessionKind;
|
||||
use codex_analytics::GuardianReviewTerminalStatus;
|
||||
use codex_analytics::GuardianReviewedAction;
|
||||
use crate::GuardianApprovalRequestSource;
|
||||
use crate::GuardianReviewDecision;
|
||||
use crate::GuardianReviewDetails;
|
||||
use crate::GuardianReviewFailureReason;
|
||||
use crate::GuardianReviewSessionKind;
|
||||
use crate::GuardianReviewTerminalStatus;
|
||||
use crate::GuardianReviewedAction;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_otel::GUARDIAN_REVIEW_COUNT_METRIC;
|
||||
use codex_otel::GUARDIAN_REVIEW_DURATION_METRIC;
|
||||
@@ -38,7 +38,7 @@ pub fn token_usage_delta(start: &TokenUsage, end: &TokenUsage) -> TokenUsage {
|
||||
|
||||
pub(crate) fn emit_guardian_review_metrics(
|
||||
session_telemetry: &SessionTelemetry,
|
||||
result: &GuardianReviewAnalyticsResult,
|
||||
result: &GuardianReviewDetails,
|
||||
approval_request_source: GuardianApprovalRequestSource,
|
||||
reviewed_action: &GuardianReviewedAction,
|
||||
elapsed: Duration,
|
||||
@@ -129,7 +129,7 @@ fn emit_guardian_token_usage_histograms(
|
||||
}
|
||||
|
||||
fn guardian_review_metric_tags(
|
||||
result: &GuardianReviewAnalyticsResult,
|
||||
result: &GuardianReviewDetails,
|
||||
approval_request_source: GuardianApprovalRequestSource,
|
||||
reviewed_action: &GuardianReviewedAction,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
@@ -469,7 +469,7 @@ mod tests {
|
||||
expected_mcp_tags: BTreeMap<String, String>,
|
||||
) {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
let result = GuardianReviewAnalyticsResult {
|
||||
let result = GuardianReviewDetails {
|
||||
attempt_count: 2,
|
||||
decision: GuardianReviewDecision::Approved,
|
||||
terminal_status: GuardianReviewTerminalStatus::Approved,
|
||||
@@ -491,7 +491,7 @@ mod tests {
|
||||
codex_rollout_budget_units: None,
|
||||
}),
|
||||
time_to_first_token_ms: Some(123),
|
||||
..GuardianReviewAnalyticsResult::without_session()
|
||||
..GuardianReviewDetails::without_session()
|
||||
};
|
||||
|
||||
emit_guardian_review_metrics(
|
||||
@@ -620,7 +620,7 @@ mod tests {
|
||||
),
|
||||
retry_at: Some(start + Duration::from_secs(2)),
|
||||
}),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
None::<()>,
|
||||
)
|
||||
},
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! completed assessments from failures without assigning risk to errors.
|
||||
|
||||
use crate::GuardianAssessment;
|
||||
use codex_analytics::GuardianReviewFailureReason;
|
||||
use crate::GuardianReviewFailureReason;
|
||||
use codex_protocol::protocol::CodexErrorInfo;
|
||||
use tokio::time::Instant;
|
||||
|
||||
|
||||
@@ -10,8 +10,8 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_analytics::GuardianReviewSessionKind;
|
||||
use crate::GuardianReviewDetails;
|
||||
use crate::GuardianReviewSessionKind;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -68,7 +68,7 @@ pub trait ReviewerRequest: Send + Sync {
|
||||
pub struct ReviewSessionResult {
|
||||
pub outcome: GuardianReviewSessionOutcome,
|
||||
pub disposition: SessionDisposition,
|
||||
pub analytics: GuardianReviewAnalyticsResult,
|
||||
pub details: GuardianReviewDetails,
|
||||
}
|
||||
|
||||
/// How the pool may reuse a session and its committed history after an attempt.
|
||||
@@ -184,7 +184,7 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
pub async fn review<R>(
|
||||
&self,
|
||||
request: R,
|
||||
) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult)
|
||||
) -> (GuardianReviewSessionOutcome, GuardianReviewDetails)
|
||||
where
|
||||
R: ReviewerRequest<Session = S>,
|
||||
{
|
||||
@@ -242,11 +242,11 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
Ok(Err(error)) => {
|
||||
return (
|
||||
GuardianReviewSessionOutcome::PromptBuildFailed(error),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
);
|
||||
}
|
||||
Err(outcome) => {
|
||||
return (outcome, GuardianReviewAnalyticsResult::without_session());
|
||||
return (outcome, GuardianReviewDetails::without_session());
|
||||
}
|
||||
};
|
||||
let review_lock = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
@@ -256,7 +256,7 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
Err(error) => {
|
||||
return (
|
||||
GuardianReviewSessionOutcome::PromptBuildFailed(error.into()),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -270,14 +270,14 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
}
|
||||
(state.as_ref().cloned(), context, reserved_permit)
|
||||
}
|
||||
Err(outcome) => return (outcome, GuardianReviewAnalyticsResult::without_session()),
|
||||
Err(outcome) => return (outcome, GuardianReviewDetails::without_session()),
|
||||
};
|
||||
let Some(trunk) = trunk else {
|
||||
return (
|
||||
GuardianReviewSessionOutcome::Completed(Err(anyhow::anyhow!(
|
||||
"guardian review session was not available after spawn"
|
||||
))),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
);
|
||||
};
|
||||
if trunk.session.context() != &context || (requires_fresh_session && !spawned_trunk) {
|
||||
@@ -304,7 +304,7 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
let ReviewSessionResult {
|
||||
outcome,
|
||||
disposition,
|
||||
analytics,
|
||||
details,
|
||||
} = request.run(&trunk.session, kind).await;
|
||||
if disposition == SessionDisposition::Rollback {
|
||||
// Publish retirement before releasing the permit. Concurrent reviews only
|
||||
@@ -326,7 +326,7 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
state.take();
|
||||
}
|
||||
}
|
||||
(outcome, analytics)
|
||||
(outcome, details)
|
||||
}
|
||||
|
||||
/// Reviews in a temporary session without reading or changing the reusable reviewer.
|
||||
@@ -334,7 +334,7 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
pub async fn review_isolated<R>(
|
||||
&self,
|
||||
request: &R,
|
||||
) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult)
|
||||
) -> (GuardianReviewSessionOutcome, GuardianReviewDetails)
|
||||
where
|
||||
R: ReviewerRequest<Session = S>,
|
||||
{
|
||||
@@ -347,7 +347,7 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
request: &R,
|
||||
context: S::Context,
|
||||
snapshot: Option<S::Snapshot>,
|
||||
) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult)
|
||||
) -> (GuardianReviewSessionOutcome, GuardianReviewDetails)
|
||||
where
|
||||
R: ReviewerRequest<Session = S>,
|
||||
{
|
||||
@@ -370,17 +370,17 @@ impl<S: ReviewerSession> ReviewerPool<S> {
|
||||
Ok(Err(error)) => {
|
||||
return (
|
||||
GuardianReviewSessionOutcome::PromptBuildFailed(error),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
);
|
||||
}
|
||||
Err(outcome) => return (outcome, GuardianReviewAnalyticsResult::without_session()),
|
||||
Err(outcome) => return (outcome, GuardianReviewDetails::without_session()),
|
||||
};
|
||||
let ReviewSessionResult {
|
||||
outcome, analytics, ..
|
||||
outcome, details, ..
|
||||
} = request
|
||||
.run(&session, GuardianReviewSessionKind::EphemeralForked)
|
||||
.await;
|
||||
(outcome, analytics)
|
||||
(outcome, details)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ impl ReviewerRequest for Request {
|
||||
ReviewSessionResult {
|
||||
outcome: GuardianReviewSessionOutcome::Completed(Err(anyhow::anyhow!("test verdict"))),
|
||||
disposition: SessionDisposition::Reusable,
|
||||
analytics: GuardianReviewAnalyticsResult::without_session(),
|
||||
details: GuardianReviewDetails::without_session(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,9 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::GuardianApprovalRequestSource;
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_analytics::GuardianReviewTrackContext;
|
||||
use codex_analytics::GuardianReviewedAction;
|
||||
use crate::GuardianApprovalRequestSource;
|
||||
use crate::GuardianReviewDetails;
|
||||
use crate::GuardianReviewedAction;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::approvals::GuardianAssessmentAction;
|
||||
@@ -51,7 +49,6 @@ pub struct ReviewMetadata {
|
||||
pub struct ReviewReport {
|
||||
started: Option<GuardianAssessmentEvent>,
|
||||
started_instant: Instant,
|
||||
tracking: GuardianReviewTrackContext,
|
||||
approval_request_source: GuardianApprovalRequestSource,
|
||||
reviewed_action: GuardianReviewedAction,
|
||||
}
|
||||
@@ -59,17 +56,7 @@ pub struct ReviewReport {
|
||||
impl ReviewReport {
|
||||
pub fn new(metadata: ReviewMetadata) -> Self {
|
||||
let started_instant = Instant::now();
|
||||
let tracking = GuardianReviewTrackContext::new(
|
||||
metadata.thread_id,
|
||||
metadata.turn_id.clone(),
|
||||
metadata.review_id.clone(),
|
||||
metadata.target_item_id.clone(),
|
||||
metadata.approval_request_source,
|
||||
metadata.reviewed_action.clone(),
|
||||
metadata
|
||||
.timeout
|
||||
.map_or(0, |timeout| timeout.as_millis() as u64),
|
||||
);
|
||||
let started_at_ms = crate::now_unix_millis();
|
||||
let started = metadata.action.map(|action| GuardianAssessmentEvent {
|
||||
review_reason: Some(metadata.review_reason),
|
||||
model_context: Some(metadata.model_context),
|
||||
@@ -78,7 +65,7 @@ impl ReviewReport {
|
||||
plugin_id: metadata.plugin_id,
|
||||
script_path: metadata.script_path,
|
||||
turn_id: metadata.turn_id,
|
||||
started_at_ms: tracking.started_at_ms.try_into().unwrap_or_default(),
|
||||
started_at_ms: started_at_ms.try_into().unwrap_or_default(),
|
||||
completed_at_ms: None,
|
||||
status: GuardianAssessmentStatus::InProgress,
|
||||
risk_level: None,
|
||||
@@ -90,7 +77,6 @@ impl ReviewReport {
|
||||
Self {
|
||||
started,
|
||||
started_instant,
|
||||
tracking,
|
||||
approval_request_source: metadata.approval_request_source,
|
||||
reviewed_action: metadata.reviewed_action,
|
||||
}
|
||||
@@ -100,13 +86,13 @@ impl ReviewReport {
|
||||
self.started.clone()
|
||||
}
|
||||
|
||||
/// Completes the report and captures the elapsed duration to use when tracking it.
|
||||
/// Completes the report and captures the elapsed duration used for local metrics.
|
||||
pub fn complete(
|
||||
&self,
|
||||
outcome: GuardianReviewOutcome,
|
||||
model: &ModelInfo,
|
||||
require_guardian: bool,
|
||||
analytics: GuardianReviewAnalyticsResult,
|
||||
details: GuardianReviewDetails,
|
||||
completed_at_ms: i64,
|
||||
) -> (ReviewCompletion, Duration) {
|
||||
let elapsed = self.started_instant.elapsed();
|
||||
@@ -116,17 +102,16 @@ impl ReviewReport {
|
||||
event.decision_source = Some(GuardianAssessmentDecisionSource::Agent);
|
||||
}
|
||||
(
|
||||
crate::complete_review(outcome, model, require_guardian, event, analytics),
|
||||
crate::complete_review(outcome, model, require_guardian, event, details),
|
||||
elapsed,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn track(
|
||||
/// Records local-only review metrics. Nothing is sent anywhere.
|
||||
pub fn record_metrics(
|
||||
&self,
|
||||
telemetry: &SessionTelemetry,
|
||||
analytics: &AnalyticsEventsClient,
|
||||
result: GuardianReviewAnalyticsResult,
|
||||
completed_at_ms: u64,
|
||||
result: GuardianReviewDetails,
|
||||
elapsed: Duration,
|
||||
) {
|
||||
crate::metrics::emit_guardian_review_metrics(
|
||||
@@ -136,7 +121,6 @@ impl ReviewReport {
|
||||
&self.reviewed_action,
|
||||
elapsed,
|
||||
);
|
||||
analytics.track_guardian_review(&self.tracking, result, completed_at_ms, elapsed);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -71,10 +71,8 @@ fn review_completion_uses_one_monotonic_duration(
|
||||
reasoning_effort: None,
|
||||
},
|
||||
});
|
||||
report.tracking.started_at_ms = 1_654_073_807_000;
|
||||
if let Some(event) = &mut report.started {
|
||||
event.started_at_ms =
|
||||
i64::try_from(report.tracking.started_at_ms).expect("start timestamp");
|
||||
event.started_at_ms = 1_654_073_807_000;
|
||||
}
|
||||
assert_eq!(report.started_event().is_some(), has_client_event);
|
||||
report.started_instant = Instant::now() - Duration::from_millis(456);
|
||||
@@ -97,14 +95,14 @@ fn review_completion_uses_one_monotonic_duration(
|
||||
GuardianReviewOutcome::Error(crate::GuardianReviewError::Timeout),
|
||||
&model,
|
||||
/*require_guardian*/ true,
|
||||
GuardianReviewAnalyticsResult {
|
||||
GuardianReviewDetails {
|
||||
attempt_count: 2,
|
||||
token_usage: Some(TokenUsage {
|
||||
input_tokens: 10,
|
||||
total_tokens: 10,
|
||||
..Default::default()
|
||||
}),
|
||||
..GuardianReviewAnalyticsResult::without_session()
|
||||
..GuardianReviewDetails::without_session()
|
||||
},
|
||||
/*completed_at_ms*/ 1_792_141_011_000,
|
||||
);
|
||||
@@ -119,15 +117,9 @@ fn review_completion_uses_one_monotonic_duration(
|
||||
has_client_event.then_some((1_654_073_807_000, Some(1_792_141_011_000)))
|
||||
);
|
||||
|
||||
// Simulate tracking later: the captured interval must not be measured again.
|
||||
// Simulate recording later: the captured interval must not be measured again.
|
||||
report.started_instant -= Duration::from_secs(1);
|
||||
report.track(
|
||||
&telemetry,
|
||||
&AnalyticsEventsClient::disabled(),
|
||||
completed.analytics,
|
||||
/*completed_at_ms*/ 1_792_141_011_000,
|
||||
elapsed,
|
||||
);
|
||||
report.record_metrics(&telemetry, completed.details, elapsed);
|
||||
|
||||
let snapshot = telemetry.snapshot_metrics().expect("metrics snapshot");
|
||||
let names = snapshot
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//! Resubmissions are independent; this layer keeps no state between approval requests.
|
||||
//! Changed local evidence retries cooperatively without service backoff, under the same limits.
|
||||
|
||||
use crate::GuardianReviewDetails;
|
||||
use crate::GuardianReviewError;
|
||||
use crate::GuardianReviewOutcome;
|
||||
use crate::ReviewDeadline;
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_protocol::protocol::CodexErrorInfo;
|
||||
use rand::Rng;
|
||||
use std::future::Future;
|
||||
@@ -28,7 +28,7 @@ pub async fn run_with_retry<Evidence, F, Attempt>(
|
||||
mut run_attempt: F,
|
||||
) -> (
|
||||
GuardianReviewOutcome,
|
||||
GuardianReviewAnalyticsResult,
|
||||
GuardianReviewDetails,
|
||||
Option<Evidence>,
|
||||
)
|
||||
where
|
||||
@@ -36,7 +36,7 @@ where
|
||||
Attempt: Future<
|
||||
Output = (
|
||||
GuardianReviewOutcome,
|
||||
GuardianReviewAnalyticsResult,
|
||||
GuardianReviewDetails,
|
||||
Option<Evidence>,
|
||||
),
|
||||
>,
|
||||
@@ -49,12 +49,12 @@ where
|
||||
let mut attempt_count = 1;
|
||||
let mut context_changed = false;
|
||||
loop {
|
||||
let (outcome, mut analytics_result, evidence) = run_attempt(deadline).await;
|
||||
analytics_result.attempt_count = attempt_count;
|
||||
context_changed |= analytics_result.context_changed;
|
||||
analytics_result.context_changed = context_changed;
|
||||
let (outcome, mut details, evidence) = run_attempt(deadline).await;
|
||||
details.attempt_count = attempt_count;
|
||||
context_changed |= details.context_changed;
|
||||
details.context_changed = context_changed;
|
||||
if attempt_count >= max_attempts || !should_retry_guardian_review(&outcome) {
|
||||
return (outcome, analytics_result, evidence);
|
||||
return (outcome, details, evidence);
|
||||
}
|
||||
let retry_at = match &outcome {
|
||||
GuardianReviewOutcome::Error(GuardianReviewError::Session { retry_at, .. }) => {
|
||||
@@ -97,7 +97,7 @@ where
|
||||
}
|
||||
}
|
||||
if let Some(error) = wait_error {
|
||||
return (GuardianReviewOutcome::Error(error), analytics_result, None);
|
||||
return (GuardianReviewOutcome::Error(error), details, None);
|
||||
}
|
||||
attempt_count += 1;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#[cfg(test)]
|
||||
use super::*;
|
||||
use crate::GuardianAssessment;
|
||||
use crate::GuardianReviewFailureReason;
|
||||
use crate::GuardianReviewResponse;
|
||||
use crate::GuardianReviewSessionOutcome;
|
||||
use codex_analytics::GuardianReviewFailureReason;
|
||||
use codex_protocol::protocol::GuardianAssessmentOutcome;
|
||||
use codex_protocol::protocol::GuardianRiskLevel;
|
||||
use codex_protocol::protocol::GuardianUserAuthorization;
|
||||
@@ -186,7 +186,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget(
|
||||
let mut attempts = 0;
|
||||
let started_at = Instant::now();
|
||||
let deadline = ReviewDeadline::from_timeout(timeout);
|
||||
let (outcome, analytics, evidence) = run_with_retry(
|
||||
let (outcome, details, evidence) = run_with_retry(
|
||||
GuardianReviewSessionLimits {
|
||||
max_attempts: 3,
|
||||
deadline,
|
||||
@@ -204,7 +204,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget(
|
||||
} else {
|
||||
GuardianReviewOutcome::Error(GuardianReviewError::StaleAuthorization)
|
||||
},
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
Some(attempt),
|
||||
)
|
||||
}
|
||||
@@ -226,7 +226,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget(
|
||||
}
|
||||
let expected_attempts = success_on_attempt.min(3);
|
||||
assert_eq!(
|
||||
(attempts, analytics.attempt_count, evidence),
|
||||
(attempts, details.attempt_count, evidence),
|
||||
(
|
||||
expected_attempts,
|
||||
expected_attempts,
|
||||
@@ -239,7 +239,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget(
|
||||
async fn stale_authorization_does_not_extend_the_deadline() {
|
||||
let deadline = ReviewDeadline::At(Instant::now() + Duration::from_secs(/*secs*/ 1));
|
||||
let mut attempts = 0;
|
||||
let (outcome, analytics, _) = run_with_retry(
|
||||
let (outcome, details, _) = run_with_retry(
|
||||
GuardianReviewSessionLimits {
|
||||
max_attempts: 3,
|
||||
deadline,
|
||||
@@ -253,7 +253,7 @@ async fn stale_authorization_does_not_extend_the_deadline() {
|
||||
deadline.wait().await;
|
||||
(
|
||||
GuardianReviewOutcome::Error(GuardianReviewError::StaleAuthorization),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
None::<()>,
|
||||
)
|
||||
}
|
||||
@@ -264,5 +264,5 @@ async fn stale_authorization_does_not_extend_the_deadline() {
|
||||
outcome,
|
||||
GuardianReviewOutcome::Error(GuardianReviewError::Timeout)
|
||||
));
|
||||
assert_eq!((attempts, analytics.attempt_count), (1, 1));
|
||||
assert_eq!((attempts, details.attempt_count), (1, 1));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! The host binds the original action, captures evidence and enforces authorization.
|
||||
//! Async approvals can return while cancelled attempts finish under the parent's task tracker.
|
||||
|
||||
use crate::GuardianReviewDetails;
|
||||
use crate::GuardianReviewError;
|
||||
use crate::GuardianReviewOutcome;
|
||||
use crate::GuardianReviewSessionLimits;
|
||||
@@ -9,7 +10,6 @@ use crate::ReviewDeadline;
|
||||
use crate::ReviewDenials;
|
||||
use crate::ReviewReport;
|
||||
use crate::ReviewRequest;
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::SynchronousApprovalReviewer;
|
||||
use codex_protocol::approvals::GuardianReviewReason;
|
||||
@@ -59,7 +59,7 @@ pub trait ReviewHost: Clone + Send + Sync + 'static {
|
||||
) -> impl Future<
|
||||
Output = (
|
||||
GuardianReviewOutcome,
|
||||
GuardianReviewAnalyticsResult,
|
||||
GuardianReviewDetails,
|
||||
Option<Self::Evidence>,
|
||||
),
|
||||
> + Send;
|
||||
@@ -144,25 +144,25 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
.await
|
||||
}
|
||||
});
|
||||
let (outcome, analytics, evidence) = if let Some(async_approval) = async_approval {
|
||||
let (outcome, details, evidence) = if let Some(async_approval) = async_approval {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut review => result,
|
||||
() = async_approval => {
|
||||
cancellation.cancel();
|
||||
let analytics = if let Some(runtime) = self.thread_store.get::<crate::ReviewerTasks>() {
|
||||
let details = if let Some(runtime) = self.thread_store.get::<crate::ReviewerTasks>() {
|
||||
// Keep driving the same attempt: its pool reservation stays held
|
||||
// until it drains, and parent shutdown joins the tracked cleanup.
|
||||
runtime.tasks.spawn(async move { let _ = review.await; });
|
||||
// Final session and usage metadata are not available yet.
|
||||
GuardianReviewAnalyticsResult {
|
||||
GuardianReviewDetails {
|
||||
attempt_count: attempts.load(Ordering::Relaxed),
|
||||
..GuardianReviewAnalyticsResult::without_session()
|
||||
..GuardianReviewDetails::without_session()
|
||||
}
|
||||
} else {
|
||||
// Hosts without a lifetime tracker must finish cleanup here.
|
||||
let (_, analytics, _) = review.await;
|
||||
analytics
|
||||
let (_, details, _) = review.await;
|
||||
details
|
||||
};
|
||||
let outcome = if !self.host.cached_approval_is_current(&prepared).await
|
||||
|| self.cancellation.is_cancelled() {
|
||||
@@ -172,35 +172,22 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
} else {
|
||||
GuardianReviewOutcome::CachedApproval
|
||||
};
|
||||
(outcome, analytics, None)
|
||||
(outcome, details, None)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
review.await
|
||||
};
|
||||
let completed_at_ms = codex_analytics::now_unix_millis();
|
||||
let completed_at_ms = crate::now_unix_millis();
|
||||
let cached_approval = matches!(outcome, GuardianReviewOutcome::CachedApproval);
|
||||
let (completed, elapsed) = report.complete(
|
||||
outcome,
|
||||
self.model,
|
||||
self.require_guardian,
|
||||
analytics,
|
||||
details,
|
||||
completed_at_ms.try_into().unwrap_or_default(),
|
||||
);
|
||||
if self.log_assessments
|
||||
&& !cached_approval
|
||||
&& let Some(event) = &completed.event
|
||||
{
|
||||
self.telemetry
|
||||
.guardian_assessment(event, completed.assessment_outcome);
|
||||
}
|
||||
report.track(
|
||||
self.telemetry,
|
||||
self.analytics,
|
||||
completed.analytics,
|
||||
completed_at_ms,
|
||||
elapsed,
|
||||
);
|
||||
report.record_metrics(self.telemetry, completed.details, elapsed);
|
||||
if let Some(message) = completed.warning {
|
||||
self.host
|
||||
.emit(EventMsg::GuardianWarning(WarningEvent { message }))
|
||||
|
||||
218
codex-rs/ext/guardian-reviewer/src/review_result.rs
Normal file
218
codex-rs/ext/guardian-reviewer/src/review_result.rs
Normal file
@@ -0,0 +1,218 @@
|
||||
//! Review result details used for local decisions and local-only metrics.
|
||||
//! Nothing here is sent anywhere: aKode has no usage-data reporting.
|
||||
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::models::SandboxPermissions;
|
||||
use codex_protocol::protocol::GuardianAssessmentOutcome;
|
||||
use codex_protocol::protocol::GuardianCommandSource;
|
||||
use codex_protocol::protocol::GuardianRiskLevel;
|
||||
use codex_protocol::protocol::GuardianUserAuthorization;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GuardianReviewDecision {
|
||||
Approved,
|
||||
Denied,
|
||||
Aborted,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GuardianReviewTerminalStatus {
|
||||
Approved,
|
||||
Denied,
|
||||
Aborted,
|
||||
TimedOut,
|
||||
FailedClosed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GuardianReviewFailureReason {
|
||||
StaleAuthorization,
|
||||
Timeout,
|
||||
Cancelled,
|
||||
PromptBuildError,
|
||||
SessionError,
|
||||
ParseError,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GuardianReviewSessionKind {
|
||||
TrunkNew,
|
||||
TrunkReused,
|
||||
EphemeralForked,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GuardianApprovalRequestSource {
|
||||
/// Approval requested directly by the main Codex turn.
|
||||
MainTurn,
|
||||
/// Approval requested by a delegated subagent and routed through the parent
|
||||
/// session for guardian review.
|
||||
DelegatedSubagent,
|
||||
}
|
||||
|
||||
/// Path-free permission metadata for a Guardian reviewed action.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct GuardianAdditionalPermissions {
|
||||
network: Option<GuardianNetworkPermissions>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
struct GuardianNetworkPermissions {
|
||||
enabled: Option<bool>,
|
||||
}
|
||||
|
||||
impl From<&AdditionalPermissionProfile> for GuardianAdditionalPermissions {
|
||||
fn from(permissions: &AdditionalPermissionProfile) -> Self {
|
||||
Self {
|
||||
network: permissions
|
||||
.network
|
||||
.as_ref()
|
||||
.map(|network| GuardianNetworkPermissions {
|
||||
enabled: network.enabled,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum GuardianReviewedAction {
|
||||
NativeToolCall {},
|
||||
Shell {
|
||||
sandbox_permissions: SandboxPermissions,
|
||||
additional_permissions: Option<GuardianAdditionalPermissions>,
|
||||
},
|
||||
UnifiedExec {
|
||||
sandbox_permissions: SandboxPermissions,
|
||||
additional_permissions: Option<GuardianAdditionalPermissions>,
|
||||
tty: bool,
|
||||
},
|
||||
WriteStdin {
|
||||
tty: bool,
|
||||
},
|
||||
Execve {
|
||||
source: GuardianCommandSource,
|
||||
additional_permissions: Option<GuardianAdditionalPermissions>,
|
||||
},
|
||||
ApplyPatch {},
|
||||
NetworkAccess {
|
||||
protocol: NetworkApprovalProtocol,
|
||||
port: u16,
|
||||
},
|
||||
McpToolCall {
|
||||
server: String,
|
||||
tool_name: String,
|
||||
connector_id: Option<String>,
|
||||
connector_name: Option<String>,
|
||||
tool_title: Option<String>,
|
||||
},
|
||||
RequestPermissions {},
|
||||
}
|
||||
|
||||
/// Details of one completed review, used for local decisions and local metrics.
|
||||
#[derive(Debug)]
|
||||
pub struct GuardianReviewDetails {
|
||||
pub guardian_context_mode: Option<&'static str>,
|
||||
pub decision: GuardianReviewDecision,
|
||||
pub terminal_status: GuardianReviewTerminalStatus,
|
||||
pub failure_reason: Option<GuardianReviewFailureReason>,
|
||||
pub attempt_count: i64,
|
||||
/// An allow was validated against changed parent/root authorization or review context.
|
||||
/// Retained across attempts; this does not identify the cause of a later cancellation.
|
||||
pub context_changed: bool,
|
||||
pub risk_level: Option<GuardianRiskLevel>,
|
||||
pub user_authorization: Option<GuardianUserAuthorization>,
|
||||
pub outcome: Option<GuardianAssessmentOutcome>,
|
||||
pub guardian_thread_id: Option<String>,
|
||||
pub guardian_session_kind: Option<GuardianReviewSessionKind>,
|
||||
pub guardian_model: Option<String>,
|
||||
pub guardian_reasoning_effort: Option<String>,
|
||||
pub guardian_default_review_model_id: Option<String>,
|
||||
pub guardian_catalog_contains_auto_review: Option<bool>,
|
||||
pub guardian_review_model_overridden: Option<bool>,
|
||||
pub guardian_review_model_override: Option<String>,
|
||||
pub guardian_model_provider_id: Option<String>,
|
||||
pub had_prior_review_context: Option<bool>,
|
||||
pub reviewed_action_truncated: bool,
|
||||
pub token_usage: Option<TokenUsage>,
|
||||
pub time_to_first_token_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl GuardianReviewDetails {
|
||||
pub fn without_session() -> Self {
|
||||
Self {
|
||||
guardian_context_mode: None,
|
||||
decision: GuardianReviewDecision::Denied,
|
||||
terminal_status: GuardianReviewTerminalStatus::FailedClosed,
|
||||
failure_reason: None,
|
||||
attempt_count: 1,
|
||||
context_changed: false,
|
||||
risk_level: None,
|
||||
user_authorization: None,
|
||||
outcome: None,
|
||||
guardian_thread_id: None,
|
||||
guardian_session_kind: None,
|
||||
guardian_model: None,
|
||||
guardian_reasoning_effort: None,
|
||||
guardian_default_review_model_id: None,
|
||||
guardian_catalog_contains_auto_review: None,
|
||||
guardian_review_model_overridden: None,
|
||||
guardian_review_model_override: None,
|
||||
guardian_model_provider_id: None,
|
||||
had_prior_review_context: None,
|
||||
reviewed_action_truncated: false,
|
||||
token_usage: None,
|
||||
time_to_first_token_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_session(params: GuardianReviewSessionDetails) -> Self {
|
||||
Self {
|
||||
guardian_thread_id: Some(params.guardian_thread_id),
|
||||
guardian_session_kind: Some(params.guardian_session_kind),
|
||||
guardian_model: Some(params.guardian_model),
|
||||
guardian_reasoning_effort: params.guardian_reasoning_effort,
|
||||
guardian_default_review_model_id: Some(params.guardian_default_review_model_id),
|
||||
guardian_catalog_contains_auto_review: Some(
|
||||
params.guardian_catalog_contains_auto_review,
|
||||
),
|
||||
guardian_review_model_overridden: Some(params.guardian_review_model_overridden),
|
||||
guardian_review_model_override: params.guardian_review_model_override,
|
||||
guardian_model_provider_id: Some(params.guardian_model_provider_id),
|
||||
had_prior_review_context: Some(params.had_prior_review_context),
|
||||
..Self::without_session()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GuardianReviewSessionDetails {
|
||||
pub guardian_thread_id: String,
|
||||
pub guardian_session_kind: GuardianReviewSessionKind,
|
||||
pub guardian_model: String,
|
||||
pub guardian_reasoning_effort: Option<String>,
|
||||
pub guardian_default_review_model_id: String,
|
||||
pub guardian_catalog_contains_auto_review: bool,
|
||||
pub guardian_review_model_overridden: bool,
|
||||
pub guardian_review_model_override: Option<String>,
|
||||
pub guardian_model_provider_id: String,
|
||||
pub had_prior_review_context: bool,
|
||||
}
|
||||
|
||||
/// Milliseconds since the Unix epoch.
|
||||
pub fn now_unix_millis() -> u64 {
|
||||
u64::try_from(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis(),
|
||||
)
|
||||
.unwrap_or(u64::MAX)
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use codex_analytics::GuardianReviewSessionKind;
|
||||
use crate::GuardianReviewSessionKind;
|
||||
use codex_history::InitialHistory;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_protocol::models::ContentItem;
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
//! Exercises async approval and authorization at the host boundary while cleanup is gated.
|
||||
|
||||
use super::*;
|
||||
use crate::GuardianApprovalRequestSource;
|
||||
use crate::GuardianReviewedAction;
|
||||
use crate::ReviewMetadata;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::GuardianApprovalRequestSource;
|
||||
use codex_analytics::GuardianReviewedAction;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -82,11 +81,7 @@ impl ReviewHost for GatedHost {
|
||||
_: &(),
|
||||
_: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> (
|
||||
GuardianReviewOutcome,
|
||||
GuardianReviewAnalyticsResult,
|
||||
Option<()>,
|
||||
) {
|
||||
) -> (GuardianReviewOutcome, GuardianReviewDetails, Option<()>) {
|
||||
self.started.notify_one();
|
||||
cancellation.cancelled().await;
|
||||
self.cleaning.notify_one();
|
||||
@@ -97,7 +92,7 @@ impl ReviewHost for GatedHost {
|
||||
GuardianReviewOutcome::Completed(
|
||||
crate::parse_guardian_assessment(r#"{"outcome":"deny"}"#).unwrap(),
|
||||
),
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewDetails::without_session(),
|
||||
Some(()),
|
||||
)
|
||||
}
|
||||
@@ -157,7 +152,6 @@ async fn async_approval_revalidates_without_waiting_for_tracked_cleanup(state: A
|
||||
"test".into(),
|
||||
SessionSource::Exec,
|
||||
);
|
||||
let analytics = AnalyticsEventsClient::disabled();
|
||||
let action = json!({});
|
||||
let request = ReviewRequest {
|
||||
serving_assessment: None,
|
||||
@@ -182,8 +176,6 @@ async fn async_approval_revalidates_without_waiting_for_tracked_cleanup(state: A
|
||||
timeout: Some(crate::REVIEW_TIMEOUT),
|
||||
model: &model,
|
||||
telemetry: &telemetry,
|
||||
log_assessments: false,
|
||||
analytics: &analytics,
|
||||
metrics: None,
|
||||
};
|
||||
let decision = request.review(
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
|
||||
use crate::ReviewDenials;
|
||||
use crate::ReviewHost;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_extension_api::ApprovalDecision;
|
||||
use codex_extension_api::ApprovalDecisionInput;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_extension_api::GuardianV2Enabled;
|
||||
use codex_extension_api::SynchronousApprovalReviewer;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -50,9 +48,6 @@ pub struct ReviewRequest<'a, H> {
|
||||
pub timeout: Option<std::time::Duration>,
|
||||
pub model: &'a ModelInfo,
|
||||
pub telemetry: &'a SessionTelemetry,
|
||||
/// The host verified the assessment opt-in and an explicit OTLP log destination.
|
||||
pub log_assessments: bool,
|
||||
pub analytics: &'a AnalyticsEventsClient,
|
||||
pub metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
}
|
||||
|
||||
@@ -180,26 +175,12 @@ impl<H: ReviewHost> ReviewRequest<'_, H> {
|
||||
}
|
||||
|
||||
pub(super) async fn cached_approval(&self) -> ReviewDecision {
|
||||
let (turn_id, item_id) = match self.host.validate_action() {
|
||||
Ok(target) => target,
|
||||
Err(decision) => return decision,
|
||||
};
|
||||
if let Err(decision) = self.host.validate_action() {
|
||||
return decision;
|
||||
}
|
||||
if self.cancellation.is_cancelled() {
|
||||
return ReviewDecision::Abort;
|
||||
}
|
||||
if self.thread_store.get::<GuardianV2Enabled>().is_some() {
|
||||
self.analytics
|
||||
.track_guardian_v2_event(codex_analytics::GuardianV2Event {
|
||||
thread_id: self.thread_id.to_string(),
|
||||
turn_id: turn_id.to_owned(),
|
||||
item_id: item_id.map(str::to_owned),
|
||||
model: Some(self.model.slug.clone()),
|
||||
occurred_at_ms: codex_analytics::now_unix_millis(),
|
||||
kind: codex_analytics::GuardianV2EventKind::FastDecision {
|
||||
decision: "approved",
|
||||
},
|
||||
});
|
||||
}
|
||||
if let Some((turn_id, _)) = self.host.servicing_turn().await {
|
||||
ReviewDenials::for_thread(self.thread_store)
|
||||
.record_non_denial(&turn_id)
|
||||
|
||||
Reference in New Issue
Block a user