diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index be169547b3..d2b7eadb29 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -453,6 +453,7 @@ pub struct GuardianReviewEventParams { pub guardian_context_mode: Option<&'static str>, pub thread_id: String, pub turn_id: String, + pub root_turn_id: Option, pub review_id: String, pub target_item_id: Option, pub approval_request_source: GuardianApprovalRequestSource, @@ -493,6 +494,7 @@ pub struct GuardianReviewEventParams { pub struct GuardianReviewTrackContext { thread_id: String, turn_id: String, + root_turn_id: Option, review_id: String, target_item_id: Option, approval_request_source: GuardianApprovalRequestSource, @@ -502,9 +504,11 @@ pub struct GuardianReviewTrackContext { } impl GuardianReviewTrackContext { + #[allow(clippy::too_many_arguments)] pub fn new( thread_id: String, turn_id: String, + root_turn_id: Option, review_id: String, target_item_id: Option, approval_request_source: GuardianApprovalRequestSource, @@ -514,6 +518,7 @@ impl GuardianReviewTrackContext { Self { thread_id, turn_id, + root_turn_id, review_id, target_item_id, approval_request_source, @@ -534,6 +539,7 @@ impl GuardianReviewTrackContext { guardian_context_mode: result.guardian_context_mode, thread_id: self.thread_id.clone(), turn_id: self.turn_id.clone(), + root_turn_id: self.root_turn_id.clone(), review_id: self.review_id.clone(), target_item_id: self.target_item_id.clone(), approval_request_source: self.approval_request_source, diff --git a/codex-rs/analytics/src/tests/suite/approvals_tests.rs b/codex-rs/analytics/src/tests/suite/approvals_tests.rs index c49a7570a5..c97fc27fb2 100644 --- a/codex-rs/analytics/src/tests/suite/approvals_tests.rs +++ b/codex-rs/analytics/src/tests/suite/approvals_tests.rs @@ -298,6 +298,7 @@ async fn guardian_review_event_ingests_custom_fact_with_optional_target_item() { guardian_context_mode: None, thread_id: "thread-guardian".to_string(), turn_id: "turn-guardian".to_string(), + root_turn_id: None, review_id: "review-guardian".to_string(), target_item_id: None, approval_request_source: GuardianApprovalRequestSource::DelegatedSubagent, diff --git a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs index c6b5ac7436..232f498047 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs @@ -291,6 +291,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer( let mut previous_review_id = None; let mut denied_turns = Vec::new(); let mut seen_requests = 0; + let root_turn_id = "reviewed-root-turn"; for (call_id, prompt, status) in turns { // Keep the revocation out of the board until the pending action requests its review. let gate = if prompt == REVOCATION { @@ -319,6 +320,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer( let id = app .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + root_turn_id: Some(root_turn_id.to_owned()), input: vec![UserInput::Text { text: prompt.to_owned(), text_elements: Vec::new(), @@ -484,6 +486,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer( }) .await?; let params = &review_event["event_params"]; + assert_eq!(params["root_turn_id"], root_turn_id); assert_eq!(params["guardian_model"], body["model"]); assert_eq!(params["guardian_model_provider_id"], "openai-custom"); assert_eq!( diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs index 756a9287a3..648d69f06b 100644 --- a/codex-rs/core/src/guardian/mod.rs +++ b/codex-rs/core/src/guardian/mod.rs @@ -108,6 +108,8 @@ pub(crate) struct GuardianReviewContext { /// A host-verified, still-running tool invocation that requested this nested review. pub(crate) enclosing_invocation_id: Option, turn: Arc, + /// Analytics lineage of the action, which can come from an earlier turn. + reviewed_action_root_turn_id: Option, review_execution: Option, environments: TurnEnvironmentSnapshot, project_instructions: Option>, @@ -147,8 +149,10 @@ impl GuardianReviewContext { turn: Arc, settings: &ResolvedStepSettings, environments: &TurnEnvironmentSnapshot, + reviewed_action_root_turn_id: Option, ) -> Self { Self { + reviewed_action_root_turn_id, request_country: settings.request_country().clone(), serving_assessment: None, guardian_probe: None, @@ -188,6 +192,7 @@ impl From<&Arc> for GuardianReviewContext { enclosing_invocation_id: None, parent_response: step.turn.extension_data.get::(), turn: Arc::clone(&step.turn), + reviewed_action_root_turn_id: step.turn.turn_metadata_state.root_turn_id(), environments: step.environments.clone(), project_instructions: Some(step.loaded_agents_md.clone().unwrap_or_default()), model_info: Arc::clone(&step.settings.model_info), @@ -218,6 +223,7 @@ impl From> for GuardianReviewContext { personality: turn.personality(), approval_policy: turn.approval_policy(), approvals_reviewer: turn.config.approvals_reviewer, + reviewed_action_root_turn_id: turn.turn_metadata_state.root_turn_id(), turn, } } diff --git a/codex-rs/core/src/guardian/review_request.rs b/codex-rs/core/src/guardian/review_request.rs index 121b3ab750..b6bc9e4897 100644 --- a/codex-rs/core/src/guardian/review_request.rs +++ b/codex-rs/core/src/guardian/review_request.rs @@ -177,6 +177,12 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { } = 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 { .. }) => { @@ -210,6 +216,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { 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, diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index 85f6161a63..dbf56249b4 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -791,6 +791,7 @@ async fn guardian_mcp_uses_thread_permissions_for_an_unavailable_captured_enviro Arc::clone(&turn), &turn.initial_settings, &captured, + /*reviewed_action_root_turn_id*/ None, ); let collected = collect_guardian_prompt_items_with_parent_turn( &session, diff --git a/codex-rs/core/src/session/mcp.rs b/codex-rs/core/src/session/mcp.rs index 10903dae65..3980d989f6 100644 --- a/codex-rs/core/src/session/mcp.rs +++ b/codex-rs/core/src/session/mcp.rs @@ -1150,6 +1150,7 @@ async fn review_guardian_mcp_elicitation( Arc::clone(&turn_context), &step_settings, &turn_context.initial_environments, + /*reviewed_action_root_turn_id*/ None, ) }); let review_config = &review_context.turn().config; diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index 0a25366972..f9093cc7b9 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -289,6 +289,7 @@ impl PendingHostApproval { struct ActiveNetworkApprovalCall { registration_id: String, turn_id: String, + root_turn_id: Option, trigger: GuardianNetworkAccessTrigger, tool_name: ToolName, command: String, @@ -307,6 +308,8 @@ enum ActiveNetworkApprovalAttribution { struct NetworkRequestAttribution { owner_call: Option>, environment_id: Option, + /// Only a verified execution tag establishes the action's root. + reviewed_action_root_turn_id: Option, } #[derive(Default)] @@ -600,6 +603,7 @@ impl NetworkApprovalService { .clone() .unwrap_or_else(|| call.environment_id.clone()); return (call.environment_id == environment_id).then_some(NetworkRequestAttribution { + reviewed_action_root_turn_id: call.root_turn_id.clone(), owner_call: Some(call), environment_id: Some(environment_id), }); @@ -616,6 +620,7 @@ impl NetworkApprovalService { return Some(NetworkRequestAttribution { owner_call, environment_id: Some(environment_id), + reviewed_action_root_turn_id: None, }); } @@ -623,12 +628,14 @@ impl NetworkApprovalService { ActiveNetworkApprovalAttribution::None => Some(NetworkRequestAttribution { owner_call: None, environment_id: None, + reviewed_action_root_turn_id: None, }), ActiveNetworkApprovalAttribution::Single(call) => { let environment_id = call.environment_id.clone(); Some(NetworkRequestAttribution { owner_call: Some(call), environment_id: Some(environment_id), + reviewed_action_root_turn_id: None, }) } ActiveNetworkApprovalAttribution::Ambiguous => None, @@ -762,6 +769,7 @@ impl NetworkApprovalService { let Some(NetworkRequestAttribution { owner_call, environment_id: active_environment_id, + reviewed_action_root_turn_id, }) = self.resolve_request_attribution(&request).await else { return NetworkDecision::deny(REASON_NOT_ALLOWED); @@ -847,6 +855,7 @@ impl NetworkApprovalService { Arc::clone(&turn_context), &settings, review_environments, + reviewed_action_root_turn_id, ); if !allows_network_approval_flow(review_context.approval_policy) { if let Some(owner_call) = owner_call.as_ref() { @@ -1277,6 +1286,7 @@ pub(crate) async fn begin_network_approval( .register_call(ActiveNetworkApprovalCall { registration_id: registration_id.clone(), turn_id: turn.sub_id.clone(), + root_turn_id: turn.turn_metadata_state.root_turn_id(), trigger, tool_name, command, diff --git a/codex-rs/core/src/tools/network_approval_tests.rs b/codex-rs/core/src/tools/network_approval_tests.rs index 94c8c87110..ce6d172c47 100644 --- a/codex-rs/core/src/tools/network_approval_tests.rs +++ b/codex-rs/core/src/tools/network_approval_tests.rs @@ -800,6 +800,7 @@ async fn register_call_with_default_shell_trigger( let registration = service.register_call(ActiveNetworkApprovalCall { registration_id: registration_id.to_string(), turn_id: "turn-1".to_string(), + root_turn_id: None, tool_name: ToolName::plain("exec_command"), trigger: GuardianNetworkAccessTrigger { call_id: registration_id.to_string(), @@ -838,6 +839,7 @@ async fn active_call_preserves_triggering_command_context() { let _registration = service.register_call(ActiveNetworkApprovalCall { registration_id: "registration-1".to_string(), turn_id: "turn-1".to_string(), + root_turn_id: Some("issuing-root".to_string()), trigger: expected.clone(), tool_name: tool_name.clone(), command: "curl https://example.com".to_string(), @@ -847,15 +849,48 @@ async fn active_call_preserves_triggering_command_context() { cancellation_token: CancellationToken::new(), }); - let call = service - .resolve_single_active_call() + let request = NetworkPolicyRequest { + protocol: NetworkProtocol::Http, + host: "example.com".to_string(), + port: 80, + execution_id: Some("registration-1".to_string()), + environment_id: Some("remote".to_string()), + client_addr: None, + method: None, + command: None, + exec_policy_hint: None, + disconnect: None, + cancellation: None, + }; + let attributed = service + .resolve_request_attribution(&request) .await - .expect("single active call should resolve"); + .expect("tagged request should resolve"); + assert_eq!( + attributed.reviewed_action_root_turn_id.as_deref(), + Some("issuing-root") + ); + let call = attributed.owner_call.expect("registered execution"); assert_eq!(&call.trigger, &expected); assert_eq!(call.tool_name, tool_name); assert_eq!(call.command, "curl https://example.com"); assert_eq!(call.environment_id, "remote"); + + let untagged = service + .resolve_request_attribution(&NetworkPolicyRequest { + execution_id: None, + ..request + }) + .await + .expect("untagged request can use current settings"); + assert_eq!( + ( + untagged.owner_call.is_some(), + untagged.reviewed_action_root_turn_id + ), + (true, None) + ); } #[tokio::test] diff --git a/codex-rs/core/tests/suite/network_approval.rs b/codex-rs/core/tests/suite/network_approval.rs index 9dbb857fb8..684315ef55 100644 --- a/codex-rs/core/tests/suite/network_approval.rs +++ b/codex-rs/core/tests/suite/network_approval.rs @@ -1,5 +1,8 @@ use anyhow::Context; use anyhow::Result; +use codex_analytics::AnalyticsEventsClient; +use codex_analytics::AppServerRpcTransport; +use codex_app_server_protocol as app; use codex_config::test_support::CloudConfigBundleFixture; use codex_config::types::ApprovalsReviewer; use codex_core::EnvironmentConfig; @@ -19,6 +22,7 @@ use codex_extension_api::ToolLifecycleContributor; use codex_extension_api::ToolLifecycleFuture; use codex_features::Feature; use codex_history::RolloutItem; +use codex_login::CodexAuth; #[cfg(unix)] use codex_network_proxy::CredentialProviderConfig; #[cfg(unix)] @@ -66,6 +70,7 @@ use codex_protocol::protocol::TurnEnvironmentSelections; use codex_protocol::request_permissions::PermissionGrantScope; use codex_protocol::request_permissions::RequestPermissionProfile; use codex_protocol::request_permissions::RequestPermissionsResponse; +use codex_protocol::turn_input::TurnStartOptions; use codex_protocol::user_input::UserInput; use codex_thread_store::LoadThreadHistoryParams; use core_test_support::PathBufExt; @@ -80,6 +85,7 @@ use core_test_support::responses::mount_response_once_match; use core_test_support::responses::mount_sse_once; use core_test_support::responses::mount_sse_once_match; use core_test_support::responses::mount_sse_sequence; +use core_test_support::responses::received_analytics_events; use core_test_support::responses::sse; use core_test_support::responses::sse_response; use core_test_support::responses::start_mock_server; @@ -111,6 +117,10 @@ use tempfile::TempDir; use test_case::test_case; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; +use wiremock::Mock; +use wiremock::ResponseTemplate; +use wiremock::matchers::method; +use wiremock::matchers::path; const NETWORK_TEST_HOST: &str = "codex-network-test.invalid"; const NETWORK_TEST_TARGET: &str = "http://codex-network-test.invalid:80"; @@ -847,16 +857,55 @@ async fn background_network_approval_uses_current_review_settings_and_original_e skip_if_sandbox!(Ok(())); let server = start_mock_server().await; + Mock::given(method("POST")) + .and(path("/codex/analytics-events/events")) + .respond_with(ResponseTemplate::new(/*status*/ 200)) + .mount(&server) + .await; + let analytics = AnalyticsEventsClient::new( + codex_core::test_support::auth_manager_from_auth( + CodexAuth::create_dummy_chatgpt_auth_for_testing(), + ), + server.uri(), + /*analytics_enabled*/ Some(true), + ); let test = managed_network_unified_exec_builder(&[ Feature::RequestPermissionsTool, Feature::StepModelSwitching, ])? + .with_analytics_events_client(analytics.clone()) .with_model("guardian-parent-a") .with_config(|config| { config.model_catalog = Some(guardian_parent_catalog()); }) .build_with_remote_and_local_env(&server) .await?; + let session = &test.session_configured; + analytics.track_initialize( + /*connection_id*/ 1, + app::InitializeParams::default(), + "test-client".to_string(), + AppServerRpcTransport::Stdio, + ); + let sandbox = test.codex.config_snapshot().await.sandbox_policy(); + let thread_response = serde_json::from_value(json!({ + "thread": { + "id": session.thread_id, "sessionId": session.session_id, "preview": "", + "ephemeral": false, "modelProvider": session.model_provider_id, + "createdAt": 1, "updatedAt": 1, "status": {"type": "idle"}, + "cwd": session.cwd, "cliVersion": "0.0.0", "source": "exec", "turns": [], + }, + "model": session.model, "modelProvider": session.model_provider_id, "cwd": session.cwd, + "approvalPolicy": app::AskForApproval::from(session.approval_policy), + "approvalsReviewer": app::ApprovalsReviewer::from(session.approvals_reviewer), + "sandbox": app::SandboxPolicy::from(sandbox), + }))?; + analytics.track_response( + /*connection_id*/ 1, + app::RequestId::Integer(1), + &app::ClientResponsePayload::ThreadStart(thread_response), + ); + let start_call_id = "cross-turn-network-start"; let permission_call_id = "cross-turn-network-permissions"; let stdin_call_id = "cross-turn-network-stdin"; @@ -955,14 +1004,22 @@ async fn background_network_approval_uses_current_review_settings_and_original_e } let responses = mount_sse_sequence(&server, events).await; - submit_managed_network_turn( - &test, - "start a background terminal that waits before requesting network access", - vec![local(test.config.cwd.clone())], - ApprovalsReviewer::User, - AskForApproval::OnRequest, - ) - .await?; + let issuing_root_turn_id = "issuing-root"; + test.codex + .start_or_steer_turn( + managed_network_turn_input( + &test, + "start a background terminal that waits before requesting network access", + vec![local(test.config.cwd.clone())], + ApprovalsReviewer::User, + AskForApproval::OnRequest, + ) + .on_start(TurnStartOptions { + root_turn_id: Some(issuing_root_turn_id.to_string()), + ..Default::default() + }), + ) + .await?; let EventMsg::TurnStarted(first_turn) = wait_for_event(&test.codex, |event| { matches!(event, EventMsg::TurnStarted(_)) }) @@ -999,6 +1056,10 @@ async fn background_network_approval_uses_current_review_settings_and_original_e }, }), ..Default::default() + }) + .on_start(TurnStartOptions { + root_turn_id: Some("servicing-root".to_string()), + ..Default::default() }), ) .await?; @@ -1065,6 +1126,17 @@ async fn background_network_approval_uses_current_review_settings_and_original_e }; assert_eq!(assessment.turn_id, active_turn_id); wait_for_turn_complete(&test).await; + tokio::time::timeout(Duration::from_secs(10), analytics.flush()).await?; + let reviews = received_analytics_events(&server, "codex_guardian_review").await; + let review = reviews + .iter() + .map(|event| &event["event_params"]) + .find(|params| params["review_id"] == assessment.id) + .context("expected analytics for the terminal's network review")?; + assert_eq!( + (review["turn_id"].as_str(), review["root_turn_id"].as_str()), + (Some(active_turn_id.as_str()), Some(issuing_root_turn_id)), + ); let actions = guardian_network_actions(&responses)?; assert_eq!(actions.len(), 2); @@ -3572,6 +3644,25 @@ async fn submit_managed_network_turn( approvals_reviewer: ApprovalsReviewer, approval_policy: AskForApproval, ) -> Result<()> { + test.codex + .start_or_steer_turn(managed_network_turn_input( + test, + prompt, + environments, + approvals_reviewer, + approval_policy, + )) + .await?; + Ok(()) +} + +fn managed_network_turn_input( + test: &TestCodex, + prompt: &str, + environments: Vec, + approvals_reviewer: ApprovalsReviewer, + approval_policy: AskForApproval, +) -> TurnInputRequest { let permission_profile = PermissionProfile::workspace_write_with( &[], NetworkSandboxPolicy::Enabled, @@ -3583,32 +3674,26 @@ async fn submit_managed_network_turn( let turn_environment_selections = TurnEnvironmentSelections::new(test.config.cwd.clone(), environments); - test.codex - .start_or_steer_turn( - TurnInputRequest::user_input(vec![UserInput::Text { - text: prompt.into(), - text_elements: Vec::new(), - }]) - .with_thread_settings(ThreadSettingsOverrides { - environments: Some(turn_environment_selections.into_requests()), - approval_policy: Some(approval_policy), - approvals_reviewer: Some(approvals_reviewer), - sandbox_policy: Some(sandbox_policy), - permission_profile, - collaboration_mode: Some(CollaborationMode { - mode: ModeKind::Default, - settings: Settings { - model: test.session_configured.model.clone(), - reasoning_effort: None, - developer_instructions: None, - }, - }), - ..Default::default() - }), - ) - .await?; - - Ok(()) + TurnInputRequest::user_input(vec![UserInput::Text { + text: prompt.into(), + text_elements: Vec::new(), + }]) + .with_thread_settings(ThreadSettingsOverrides { + environments: Some(turn_environment_selections.into_requests()), + approval_policy: Some(approval_policy), + approvals_reviewer: Some(approvals_reviewer), + sandbox_policy: Some(sandbox_policy), + permission_profile, + collaboration_mode: Some(CollaborationMode { + mode: ModeKind::Default, + settings: Settings { + model: test.session_configured.model.clone(), + reasoning_effort: None, + developer_instructions: None, + }, + }), + ..Default::default() + }) } fn decoded_request_body(request: &wiremock::Request) -> Option> { diff --git a/codex-rs/ext/guardian-reviewer/src/reporting.rs b/codex-rs/ext/guardian-reviewer/src/reporting.rs index 4629afe594..eeb34ded34 100644 --- a/codex-rs/ext/guardian-reviewer/src/reporting.rs +++ b/codex-rs/ext/guardian-reviewer/src/reporting.rs @@ -34,6 +34,7 @@ use crate::ReviewCompletion; pub struct ReviewMetadata { pub thread_id: String, pub turn_id: String, + pub root_turn_id: Option, /// Origin of the issuing turn, inherited by delegated turns at admission. pub turn_trigger: Option, pub review_id: String, @@ -79,6 +80,7 @@ impl ReviewReport { let tracking = GuardianReviewTrackContext::new( metadata.thread_id, metadata.turn_id.clone(), + metadata.root_turn_id, metadata.review_id.clone(), metadata.target_item_id.clone(), metadata.approval_request_source, diff --git a/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs b/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs index 1cfbb6812e..c8cb3f2058 100644 --- a/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs @@ -59,6 +59,7 @@ fn review_report_bounds_turn_origin_on_both_verdicts( let report = ReviewReport::new(ReviewMetadata { thread_id: "thread".into(), turn_id: "turn".into(), + root_turn_id: None, turn_trigger: turn_trigger.map(str::to_owned), review_id: "review".into(), target_item_id: None, @@ -168,6 +169,7 @@ fn review_completion_uses_one_monotonic_duration( let mut report = ReviewReport::new(ReviewMetadata { thread_id: "thread".to_string(), turn_id: "turn".to_string(), + root_turn_id: None, turn_trigger: None, review_id: "review".to_string(), target_item_id: None, diff --git a/codex-rs/ext/guardian-reviewer/src/review_tests.rs b/codex-rs/ext/guardian-reviewer/src/review_tests.rs index 9c8bf7bb68..56e2204c7d 100644 --- a/codex-rs/ext/guardian-reviewer/src/review_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/review_tests.rs @@ -73,6 +73,7 @@ impl ReviewHost for GatedHost { ReviewReport::new(ReviewMetadata { thread_id: "thread".into(), turn_id: "turn".into(), + root_turn_id: None, turn_trigger: None, review_id: approval_id.into(), target_item_id: Some("call".into()),