diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 2e900dec03..cb66a94270 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2950,6 +2950,10 @@ "non_code_mode_only": { "type": "boolean" }, + "preserve_fork_prefix": { + "description": "Preserve the parent's model-visible history on full forks and append child instructions. Defaults to false. Legacy compaction without a reusable context baseline still rebuilds.", + "type": "boolean" + }, "root_agent_usage_hint_text": { "type": "string" }, diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index 4bf2d80602..cca217e8d0 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -20,10 +20,14 @@ use crate::context::DeveloperInstructions; use crate::context::ManagedDeveloperInstructions; use crate::context::MultiAgentModeInstructions; use crate::context::MultiAgentRoleInstructions; +use crate::context::MultiAgentUsageHint; use crate::context::world_state::IncrementalToolsHint; use crate::context::world_state::PersistentModeState; use crate::session::multi_agents::resolve_usage_hints; +use crate::tasks::InterruptedTurnHistoryMarker; +use crate::thread_manager::ForkSnapshot; use crate::thread_manager::StartThreadOptions; +use crate::thread_manager::fork_history_from_snapshot; use codex_context_fragments::set_annotated_content; use codex_context_fragments::to_annotated_content; use codex_features::Feature; @@ -1109,15 +1113,25 @@ impl LocalAgentControl { break; } let mut replaced_parent_developer_instructions = false; - // Scrub inherited hints and replace only the parent's developer-instruction fragment. - // Compaction stores response items separately, so sanitize both top-level messages and - // compacted replacement histories with the same policy. + let preserve_fork_prefix = multi_agent_version == MultiAgentVersion::V2 + && config.multi_agent_v2.preserve_fork_prefix + && preserve_context_baselines; + if preserve_fork_prefix { + let InitialHistory::Forked(items) = fork_history_from_snapshot( + ForkSnapshot::Interrupted, + InitialHistory::Forked(forked_rollout_items), + InterruptedTurnHistoryMarker::Disabled, + ) else { + unreachable!("a forked snapshot remains forked"); + }; + forked_rollout_items = items; + } let retain_forked_item = |envelope: &mut ResponseItemEnvelope, replaced: &mut bool| { if multi_agent_version == MultiAgentVersion::V2 - && matches!(&envelope.item, ResponseItem::Message { role, .. } if role == "user" || role == "assistant") + && (preserve_fork_prefix + || matches!(&envelope.item, ResponseItem::Message { role, .. } if role == "user" || role == "assistant")) { - // Persist the scope of every inherited conversational message, including the suffix - // after a checkpoint. Resume must not recapture it as local authorization. + // Resume must not recapture copied parent messages as local authorization. envelope .metadata .get_or_insert_default() @@ -1130,6 +1144,9 @@ impl LocalAgentControl { // Assistant and tool positions belong to the parent counter, not the child. metadata.user_input_order = None; } + if preserve_fork_prefix { + return true; + } let response_item = &mut envelope.item; // Tool declarations and their comparison baseline must survive or be rebuilt together. // Apply this to both standalone items and compaction replacement histories. @@ -1199,7 +1216,9 @@ impl LocalAgentControl { true }; forked_rollout_items.retain_mut(|item| { - if !keep_forked_rollout_item(item, preserve_context_baselines) + let keep = (preserve_fork_prefix && matches!(item, RolloutItem::ResponseItem(_))) + || keep_forked_rollout_item(item, preserve_context_baselines); + if !keep || destination_history_mode == Some(ThreadHistoryMode::Paginated) && matches!( &*item, @@ -1265,6 +1284,13 @@ impl LocalAgentControl { | RolloutItem::SecurityRiskScore(_) => false, } }); + if preserve_fork_prefix { + forked_rollout_items.push(RolloutItem::ResponseItem( + ContextualUserFragment::into(MultiAgentUsageHint::new( + "You are now a newly spawned child agent. The preceding conversation is inherited parent context. Follow your own role, identity, and task below; earlier identities, tasks, and action-specific approvals belong to your ancestors. Inherited tool calls are historical records; live tool sessions and process handles are not inherited. Report your result to your parent.", + )).into(), + )); + } // Full forks reuse the parent's reference context instead of rebuilding it. If that // context omitted the parent's developer fragment, append the child's override so its // instructions still reach the model exactly once. diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 866cdc7385..361551c992 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -3575,8 +3575,12 @@ async fn spawn_agent_full_fork_restores_instructions_after_compaction_discards_p /// A legacy compaction clears the child's baseline, so its first turn must /// rebuild configured developer instructions exactly once. +#[test_case::test_case(false; "filtered fork")] +#[test_case::test_case(true; "preserve prefix fallback")] #[tokio::test] -async fn spawn_agent_full_fork_legacy_compaction_rebuilds_child_instructions_once() { +async fn spawn_agent_full_fork_legacy_compaction_rebuilds_child_instructions_once( + preserve_fork_prefix: bool, +) { let managed_policy = "Managed policy for every agent."; let current_managed_fragment = format!( "\n{managed_policy}\n" @@ -3612,6 +3616,7 @@ async fn spawn_agent_full_fork_legacy_compaction_rebuilds_child_instructions_onc ) .expect("managed requirements stack"); let mut child_config = parent_config.clone(); + child_config.multi_agent_v2.preserve_fork_prefix = preserve_fork_prefix; child_config.developer_instructions = Some("Child developer instructions.".to_string()); child_config.multi_agent_v2.subagent_developer_instructions = Some("Child developer instructions.".to_string()); diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index f74b3df282..ed22c53c09 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -12143,6 +12143,7 @@ usage_hint_text = "Custom delegation guidance." root_agent_usage_hint_text = "Root guidance." subagent_usage_hint_text = "Subagent guidance." subagent_developer_instructions = " Delegate carefully. " +preserve_fork_prefix = true multi_agent_mode_hint_text = "Custom mode guidance." tool_namespace = "agents" hide_spawn_agent_metadata = true @@ -12203,6 +12204,7 @@ max_concurrent_threads_per_session = 9 Some("agents") ); assert!(config.multi_agent_v2.hide_spawn_agent_metadata); + assert!(config.multi_agent_v2.preserve_fork_prefix); assert!(!config.multi_agent_v2.expose_spawn_agent_model_overrides); assert!(!config.multi_agent_v2.wait_agent_enabled); assert!(config.multi_agent_v2.disable_direct_message); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index f10ea126f9..a908f40632 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1368,6 +1368,7 @@ pub struct MultiAgentV2Config { pub root_agent_usage_hint_text: Option, pub subagent_usage_hint_text: Option, pub subagent_developer_instructions: Option, + pub preserve_fork_prefix: bool, pub multi_agent_mode_hint_text: Option, pub tool_namespace: Option, pub hide_spawn_agent_metadata: bool, @@ -1390,6 +1391,7 @@ impl MultiAgentV2Config { root_agent_usage_hint_text: None, subagent_usage_hint_text: None, subagent_developer_instructions: None, + preserve_fork_prefix: false, multi_agent_mode_hint_text: None, tool_namespace: Some(DEFAULT_MULTI_AGENT_V2_TOOL_NAMESPACE.to_string()), hide_spawn_agent_metadata: true, @@ -2847,6 +2849,9 @@ fn resolve_multi_agent_v2_config(config_toml: &ConfigToml) -> MultiAgentV2Config let subagent_developer_instructions = base .and_then(|config| config.subagent_developer_instructions.as_ref()) .map(|instructions| instructions.trim().to_string()); + let preserve_fork_prefix = base + .and_then(|config| config.preserve_fork_prefix) + .unwrap_or(default.preserve_fork_prefix); let multi_agent_mode_hint_text = base .and_then(|config| config.multi_agent_mode_hint_text.as_ref()) .cloned() @@ -2868,6 +2873,7 @@ fn resolve_multi_agent_v2_config(config_toml: &ConfigToml) -> MultiAgentV2Config root_agent_usage_hint_text, subagent_usage_hint_text, subagent_developer_instructions, + preserve_fork_prefix, multi_agent_mode_hint_text, tool_namespace, hide_spawn_agent_metadata, diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 38ef4a59c0..9988b1810d 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -213,6 +213,7 @@ impl SharedConversationHistory { self.items .iter() .filter(|envelope| !is_guardian_context_message(&envelope.item)) + .filter(|envelope| !codex_guardian_context::is_inherited_manual_approval(envelope)) .map(|envelope| { ( &envelope.item, diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index c5551b6320..e363460ec7 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -2259,9 +2259,9 @@ fn format_exec_output_prefers_line_marker_when_both_limits_exceeded() { assert_truncated_message_matches(&truncated, "line-0-", /*expected_removed*/ 17_423); } -#[cfg(not(debug_assertions))] -#[test] -fn normalize_adds_missing_output_for_custom_tool_call() { +#[cfg_attr(not(debug_assertions), test_case::test_case(false; "local"))] +#[test_case::test_case(true; "inherited")] +fn normalize_adds_missing_output_for_custom_tool_call(inherited: bool) { let items = vec![ResponseItem::CustomToolCall { id: None, status: None, @@ -2272,6 +2272,10 @@ fn normalize_adds_missing_output_for_custom_tool_call() { internal_chat_message_metadata_passthrough: None, }]; let mut h = create_history_with_items(items); + Arc::make_mut(&mut h.items)[0] + .metadata + .get_or_insert_default() + .inherited_user_message = inherited; h.normalize_history(&default_input_modalities()); @@ -2298,9 +2302,9 @@ fn normalize_adds_missing_output_for_custom_tool_call() { ); } -#[cfg(not(debug_assertions))] -#[test] -fn normalize_adds_missing_output_for_local_shell_call_with_id() { +#[cfg_attr(not(debug_assertions), test_case::test_case(false; "local"))] +#[test_case::test_case(true; "inherited")] +fn normalize_adds_missing_output_for_local_shell_call_with_id(inherited: bool) { let items = vec![ResponseItem::LocalShellCall { id: None, call_id: Some("shell-1".to_string()), @@ -2315,6 +2319,10 @@ fn normalize_adds_missing_output_for_local_shell_call_with_id() { internal_chat_message_metadata_passthrough: None, }]; let mut h = create_history_with_items(items); + Arc::make_mut(&mut h.items)[0] + .metadata + .get_or_insert_default() + .inherited_user_message = inherited; h.normalize_history(&default_input_modalities()); diff --git a/codex-rs/core/src/context_manager/normalize.rs b/codex-rs/core/src/context_manager/normalize.rs index 7fc45ba217..532cfdfb34 100644 --- a/codex-rs/core/src/context_manager/normalize.rs +++ b/codex-rs/core/src/context_manager/normalize.rs @@ -87,9 +87,17 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec) ResponseItem::CustomToolCall { id, call_id, .. } if !custom_tool_output_ids.contains(call_id.as_str()) => { - error_or_panic(format!( - "Custom tool call output is missing for call id: {call_id}" - )); + // Preserved-prefix forks mark copied calls as inherited. A call still + // running in the parent has no output in the child's snapshot. + if !envelope + .metadata + .as_ref() + .is_some_and(|metadata| metadata.inherited_user_message) + { + error_or_panic(format!( + "Custom tool call output is missing for call id: {call_id}" + )); + } missing_outputs_to_insert.push(( idx, ResponseItemEnvelope::new(ResponseItem::CustomToolCallOutput { @@ -107,9 +115,17 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec) call_id: Some(call_id), .. } if !function_output_ids.contains(call_id.as_str()) => { - error_or_panic(format!( - "Local shell call output is missing for call id: {call_id}" - )); + // Preserved-prefix forks mark copied calls as inherited. A call still + // running in the parent has no output in the child's snapshot. + if !envelope + .metadata + .as_ref() + .is_some_and(|metadata| metadata.inherited_user_message) + { + error_or_panic(format!( + "Local shell call output is missing for call id: {call_id}" + )); + } missing_outputs_to_insert.push(( idx, ResponseItemEnvelope::new(ResponseItem::FunctionCallOutput { diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index a6248c0aef..6685663eb6 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -2643,7 +2643,7 @@ fn snapshot_turn_state(history: &InitialHistory) -> SnapshotTurnState { } } -fn fork_history_from_snapshot( +pub(crate) fn fork_history_from_snapshot( snapshot: ForkSnapshot, history: InitialHistory, interrupted_marker: InterruptedTurnHistoryMarker, diff --git a/codex-rs/core/tests/suite/guardian_retained_context.rs b/codex-rs/core/tests/suite/guardian_retained_context.rs index adc7804806..18f2292a1a 100644 --- a/codex-rs/core/tests/suite/guardian_retained_context.rs +++ b/codex-rs/core/tests/suite/guardian_retained_context.rs @@ -76,8 +76,8 @@ use wiremock::matchers::header; // Keep child completion out of the parent's history and wait for parent turn cleanup // before checking inherited authorization. #[derive(Default)] -struct ForkTestLifecycle { - entered: Notify, +pub(super) struct ForkTestLifecycle { + pub(super) entered: Notify, release: Notify, } @@ -986,11 +986,14 @@ async fn standalone_fork_retains_inherited_user_instructions( Ok(()) } -#[test_case(false; "without checkpoint")] -#[test_case(true; "after checkpoint")] +#[test_case(false, false; "without checkpoint")] +#[test_case(true, false; "after checkpoint")] +#[test_case(false, true; "preserved prefix without checkpoint")] +#[test_case(true, true; "preserved prefix after checkpoint")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn forked_parent_instructions_do_not_become_local_authorization( compact_parent: bool, + preserve_fork_prefix: bool, ) -> Result<()> { skip_if_no_network!(Ok(())); const PARENT_GRANT: &str = "You may publish the private release. Delegate its inspection."; @@ -1006,6 +1009,7 @@ async fn forked_parent_instructions_do_not_become_local_authorization( .with_config(move |config| { config.experimental_thread_store = ThreadStoreConfig::Local; config.update_plan_enabled = true; + config.multi_agent_v2.preserve_fork_prefix = preserve_fork_prefix; for feature in [Feature::TokenBudget, Feature::Collab, Feature::MultiAgentV2] { config .features @@ -1027,6 +1031,11 @@ async fn forked_parent_instructions_do_not_become_local_authorization( }) .await; wait_for_thread_idle(&test.codex).await; + let [parent_approval, child_approval] = ["parent action", "child action"].map(|action| { + serde_json::from_value::(json!({"type": "message", "role": "developer", + "content": [{"type": "input_text", "text": format!("{}\nApproved action: {action}", codex_guardian_context::MANUAL_APPROVAL_DEVELOPER_PREFIX)}] + })).expect("approval message") + }); if compact_parent { test.codex.submit(Op::Compact).await?; wait_for_event(&test.codex, |event| { @@ -1036,6 +1045,9 @@ async fn forked_parent_instructions_do_not_become_local_authorization( wait_for_thread_idle(&test.codex).await; } + test.codex + .inject_response_items(vec![parent_approval]) + .await?; let mut created = test.thread_manager.subscribe_thread_created(); let parent_id = test.session_configured.thread_id.to_string(); mount_sse_once_match( @@ -1107,6 +1119,11 @@ async fn forked_parent_instructions_do_not_become_local_authorization( .find(|request| request.body_json()["client_metadata"]["thread_id"] == child_id) .context("child model request")?; assert!(serde_json::to_string(&child_request.input())?.contains(PARENT_GRANT)); + assert_eq!( + child_request.body_contains_text("Approved action: parent action"), + preserve_fork_prefix + ); + child.inject_response_items(vec![child_approval]).await?; let history = child.conversation_history_snapshot().await; assert_eq!( history.retained_context().map(|context| ( @@ -1162,6 +1179,9 @@ async fn forked_parent_instructions_do_not_become_local_authorization( .await?; wait_for_event(&child, |event| matches!(event, EventMsg::TurnComplete(_))).await; let history = child.conversation_history_snapshot().await; + let reviewer_history = serde_json::to_string(&history.review_items().collect::>())?; + assert!(!reviewer_history.contains("Approved action: parent action")); + assert!(reviewer_history.contains("Approved action: child action")); let expected = history.retained_context().cloned(); assert_eq!( expected.as_ref().map(|context| context @@ -1200,18 +1220,22 @@ async fn forked_parent_instructions_do_not_become_local_authorization( Ok(()) } -#[test_case(ThreadHistoryMode::Legacy; "legacy child fork")] -#[test_case(ThreadHistoryMode::Paginated; "paginated child fork")] +#[test_case(ThreadHistoryMode::Legacy, false; "legacy child fork")] +#[test_case(ThreadHistoryMode::Paginated, false; "paginated child fork")] +#[test_case(ThreadHistoryMode::Legacy, true; "legacy preserved child fork")] +#[test_case(ThreadHistoryMode::Paginated, true; "paginated preserved child fork")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn retained_answers_cross_real_session_boundaries( history_mode: ThreadHistoryMode, + preserve_fork_prefix: bool, ) -> Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; let test = test_codex() .with_history_mode(history_mode) - .with_config(|config| { + .with_config(move |config| { config.experimental_thread_store = ThreadStoreConfig::Local; + config.multi_agent_v2.preserve_fork_prefix = preserve_fork_prefix; for feature in [ Feature::TokenBudget, Feature::DefaultModeRequestUserInput, diff --git a/codex-rs/core/tests/suite/scenarios_partial_answers.rs b/codex-rs/core/tests/suite/scenarios_partial_answers.rs index d36f149e94..74c9e56706 100644 --- a/codex-rs/core/tests/suite/scenarios_partial_answers.rs +++ b/codex-rs/core/tests/suite/scenarios_partial_answers.rs @@ -1,8 +1,13 @@ //! Partial answers retain their phase in live events and subsequent model requests. +use super::super::guardian_retained_context::ForkTestLifecycle; use super::*; use codex_protocol::models::MessagePhase; +use codex_protocol::protocol::ThreadHistoryMode; +use core_test_support::ThreadIdle; +use core_test_support::responses; use pretty_assertions::assert_eq; +use test_case::test_case; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn partial_answers_preserve_phase_across_sampling_continuation() -> Result<()> { @@ -104,8 +109,16 @@ async fn partial_answers_preserve_phase_across_sampling_continuation() -> Result Ok(()) } +#[test_case(false, false, ThreadHistoryMode::Legacy; "filtered")] +#[test_case(true, false, ThreadHistoryMode::Legacy; "preserved legacy")] +#[test_case(true, false, ThreadHistoryMode::Paginated; "preserved paginated")] +#[test_case(true, true, ThreadHistoryMode::Paginated; "preserved code mode")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn partial_answers_survive_forked_child_requests() -> Result<()> { +async fn partial_answers_survive_forked_child_requests( + preserve_fork_prefix: bool, + code_mode: bool, + history_mode: ThreadHistoryMode, +) -> Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; let mut partial = ev_assistant_message("fragment", "The first result is ready."); @@ -118,7 +131,7 @@ async fn partial_answers_survive_forked_child_requests() -> Result<()> { ev_assistant_message("done", "Done."), ev_completed("done"), ]); - let mock = mount_sse_sequence( + mount_sse_sequence( &server, vec![ sse(vec![ @@ -129,7 +142,10 @@ async fn partial_answers_survive_forked_child_requests() -> Result<()> { ev_completed("results"), ]), sse(vec![ - ev_function_call_with_namespace( + if code_mode { + ev_custom_tool_call("spawn-worker", "exec", + r#"text(await tools.collaboration__spawn_agent({task_name: "worker", message: "Check both inherited results.", fork_turns: "all"}));"#) + } else { ev_function_call_with_namespace( "spawn-worker", "collaboration", "spawn_agent", @@ -139,18 +155,48 @@ async fn partial_answers_survive_forked_child_requests() -> Result<()> { "fork_turns": "all", }) .to_string(), - ), + ) }, ev_completed("spawn"), ]), - // Parent continuation and child inference may arrive in either order. - done.clone(), - done, ], ) .await; + let child_gate = Arc::new(ForkTestLifecycle::default()); + let mut extensions = ExtensionRegistryBuilder::::new(); + extensions.tool_lifecycle_contributor(child_gate.clone()); + extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle)); let test = test_codex() - .with_config(|config| { + .with_model(if preserve_fork_prefix { + "gpt-5.6-sol" + } else { + "test-gpt-5.1" + }) + .with_history_mode(history_mode) + .with_extensions(Arc::new(extensions.build())) + .with_config(move |config| { configure_scenario_catalog(config); + config.multi_agent_v2.preserve_fork_prefix = preserve_fork_prefix; + config.multi_agent_v2.non_code_mode_only = !code_mode; + if code_mode { + config + .features + .enable(Feature::CodeMode) + .expect("enable Code Mode"); + config + .features + .enable(Feature::MultiAgentV2DynamicTools) + .expect("enable agent tools in Code Mode"); + } + if preserve_fork_prefix { + config.update_plan_enabled = true; + config.multi_agent_v2.root_agent_usage_hint_text = + Some("You are /root. Coordinate the investigation.".into()); + config.multi_agent_v2.subagent_usage_hint_text = + Some("You are a worker. Report to your parent.".into()); + config.developer_instructions = Some("Coordinate the investigation.".into()); + config.multi_agent_v2.subagent_developer_instructions = + Some("Check both results independently.".into()); + } config .features .enable(Feature::Collab) @@ -162,6 +208,38 @@ async fn partial_answers_survive_forked_child_requests() -> Result<()> { }) .build_with_auto_env(&server) .await?; + let parent_id = test.session_configured.thread_id.to_string(); + responses::mount_sse_once_match( + &server, + wiremock::matchers::header("thread-id", parent_id.as_str()), + done.clone(), + ) + .await; + let root_id = parent_id.clone(); + responses::mount_sse_once_match( + &server, + move |request: &wiremock::Request| { + request + .headers + .get("thread-id") + .is_some_and(|id| id != root_id.as_str()) + }, + if preserve_fork_prefix { + // Keep the child active until the parent is idle, making completion mail deterministic. + sse(vec![ + ev_function_call_with_namespace( + "child-pause", + "functions", + "update_plan", + r#"{"plan":[{"step":"Check results","status":"in_progress"}]}"#, + ), + ev_completed("child-pause"), + ]) + } else { + done + }, + ) + .await; test.submit_turn("Give me both results.").await?; test.submit_turn("Have a worker check both results.") .await?; @@ -173,13 +251,21 @@ async fn partial_answers_survive_forked_child_requests() -> Result<()> { .find(|id| *id != test.session_configured.thread_id) .expect("forked child"); let child = test.thread_manager.get_thread(child_id).await?; - wait_for_event(&child, |event| matches!(event, EventMsg::TurnComplete(_))).await; - let child_requests = mock - .requests() - .into_iter() + if preserve_fork_prefix { + child_gate.entered.notified().await; + } else { + wait_for_event(&child, |event| matches!(event, EventMsg::TurnComplete(_))).await; + } + ThreadIdle::wait(&test.codex).await; + let mut requests = responses::received_responses_requests(&server).await; + requests + .sort_by_key(|request| request.header("thread-id").as_deref() != Some(parent_id.as_str())); + let child_requests = requests + .iter() .filter(|request| { request.body_json()["client_metadata"]["thread_id"] == child_id.to_string() }) + .cloned() .collect::>(); assert_eq!(child_requests.len(), 1); let body = child_requests[0].body_json(); @@ -190,27 +276,69 @@ async fn partial_answers_survive_forked_child_requests() -> Result<()> { .filter(|item| item["type"] == "message" && item["role"] == "assistant") .map(|item| (item["phase"].clone(), item["content"].clone())) .collect::>(); - assert_eq!( - assistant_messages, - vec![ + let mut expected_messages = vec![ + ( + json!("partial_answer"), + json!([{"type":"output_text", "text":"The first result is ready."}]), + ), + ( + json!("final_answer"), + json!([{"type":"output_text", "text":"The second result is ready."}]), + ), + ]; + if preserve_fork_prefix { + expected_messages.insert( + 1, ( - json!("partial_answer"), - json!([{"type":"output_text", "text":"The first result is ready."}]) + json!("commentary"), + json!([{"type":"output_text", "text":"Checking the remaining result."}]), ), - ( - json!("final_answer"), - json!([{"type":"output_text", "text":"The second result is ready."}]) - ), - ] - ); - insta::assert_snapshot!( - "partial_answer_fork", - context_snapshot::format_request_history_snapshot( - "A forked worker receives both stable answer fragments, with their phases preserved and parent commentary filtered out.", - &child_requests, - &ContextSnapshotOptions::default().rewrite_known_segments(), - ) - ); + ); + let parent_input = requests[1].input(); + assert_eq!( + responses::strip_response_item_ids_from_json(json!( + &child_requests[0].input()[..parent_input.len()] + )), + responses::strip_response_item_ids_from_json(json!(parent_input)) + ); + assert_eq!(body["tools"], requests[1].body_json()["tools"]); + assert_eq!( + body["instructions"], + requests[1].body_json()["instructions"] + ); + assert!(child_requests[0].body_contains_text("Check both results independently.")); + if code_mode { + assert_eq!( + child_requests[0].custom_tool_call_output_content_and_success("spawn-worker"), + Some((Some("aborted".into()), None)) + ); + assert!( + requests[2] + .custom_tool_call_output("spawn-worker") + .to_string() + .contains("/root/worker") + ); + } else { + insta::assert_snapshot!( + "preserved_answer_fork", + context_snapshot::format_request_history_snapshot( + "A worker inherits the parent prefix unchanged and receives its own instructions. Requests are grouped by parent, then child.", + &requests, + &ContextSnapshotOptions::default().rewrite_known_segments() + ) + ); + } + } else { + insta::assert_snapshot!( + "partial_answer_fork", + context_snapshot::format_request_history_snapshot( + "A forked worker receives both stable answer fragments, with their phases preserved and parent commentary filtered out.", + &child_requests, + &ContextSnapshotOptions::default().rewrite_known_segments(), + ) + ); + } + assert_eq!(assistant_messages, expected_messages); child.shutdown_and_wait().await?; Ok(()) } diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__partial_answers__preserved_answer_fork.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__partial_answers__preserved_answer_fork.snap new file mode 100644 index 0000000000..cfc2708279 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__partial_answers__preserved_answer_fork.snap @@ -0,0 +1,92 @@ +--- +source: core/tests/suite/scenarios_partial_answers.rs +expression: "context_snapshot::format_request_history_snapshot(\"A worker inherits the parent prefix unchanged and receives its own instructions. Requests are grouped by parent, then child.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments())" +--- +Scenario: A worker inherits the parent prefix unchanged and receives its own instructions. Requests are grouped by parent, then child. + +## Window 1 +-- request 1 (turn) -- +00:additional_tools/developer (2; hash=cefa72e421dc276f): + - namespace/functions; hash=125a3a92f05f72e9 + - custom/exec + - function/wait + - function/request_user_input + - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=2c8d6295978dbe63 + - function/followup_task + - function/interrupt_agent + - function/list_agents + - function/send_message + - function/spawn_agent + - function/wait_agent +01:message/developer: + +02:message/developer[2]: + [01] Coordinate the investigation. + [02] +03:message/developer: + You are /root. Coordinate the investigation. +04:message/developer: + +05:message/user: + +06:message/user: + Give me both results. +-- request 2 (turn) -- +07:message/assistant: + The first result is ready. +08:message/assistant: + Checking the remaining result. +09:message/assistant: + The second result is ready. +10:message/user: + Have a worker check both results. +-- request 3 (turn) -- +11:function_call/collaboration.spawn_agent:{"fork_turns":"all","message":"Check both inherited results.","task_name":"worker"} +12:function_call_output:{"task_name":"/root/worker"} + +## Window 2 (after request 3: input diverged at item 12) +-- request 4 (turn) -- +00:additional_tools/developer (2; hash=cefa72e421dc276f): + - namespace/functions; hash=125a3a92f05f72e9 + - custom/exec + - function/wait + - function/request_user_input + - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=2c8d6295978dbe63 + - function/followup_task + - function/interrupt_agent + - function/list_agents + - function/send_message + - function/spawn_agent + - function/wait_agent +01:message/developer: + +02:message/developer[2]: + [01] Coordinate the investigation. + [02] +03:message/developer: + You are /root. Coordinate the investigation. +04:message/developer: + +05:message/user: + +06:message/user: + Give me both results. +07:message/assistant: + The first result is ready. +08:message/assistant: + Checking the remaining result. +09:message/assistant: + The second result is ready. +10:message/user: + Have a worker check both results. +11:function_call/collaboration.spawn_agent:{"fork_turns":"all","message":"Check both inherited results.","task_name":"worker"} +12:function_call_output:aborted +13:message/developer: + You are now a newly spawned child agent. The preceding conversation is inherited parent context. Follow ...are not inherited. Report your result to your parent. [hash=0e586a5d405d39db] +14:message/developer: + Check both results independently. +15:message/developer: + You are a worker. Report to your parent. +16:message/developer: + +17:agent_message diff --git a/codex-rs/exec-server/src/fs_sandbox_windows_tests.rs b/codex-rs/exec-server/src/fs_sandbox_windows_tests.rs index 9c22542838..d21e72cf32 100644 --- a/codex-rs/exec-server/src/fs_sandbox_windows_tests.rs +++ b/codex-rs/exec-server/src/fs_sandbox_windows_tests.rs @@ -67,7 +67,7 @@ async fn noisy_failing_helper_preserves_exit_status_and_bounded_stderr() { let mut command = { let mut command = Command::new("sh"); command.arg("-c").arg( - "printf 'expected helper diagnostic' >&2; i=0; while [ \"$i\" -lt 1024 ]; do printf '%0128d' 0 >&2; i=$((i + 1)); done; exit 7", + "printf 'expected helper diagnostic' >&2; i=0; while [ \"$i\" -lt 1024 ]; do printf '%0128d' 0 >&2; i=$((i + 1)); done; printf 'response before failure\\n'; exit 7", ); command }; @@ -83,17 +83,19 @@ async fn noisy_failing_helper_preserves_exit_status_and_bounded_stderr() { command .arg("-NoProfile") .arg("-Command") - .arg("[Console]::Error.Write('expected helper diagnostic' + ('x' * 131072)); exit 7"); + .arg("[Console]::Error.Write('expected helper diagnostic' + ('x' * 131072)); [Console]::Out.WriteLine('response before failure'); exit 7"); command }; command.envs(std::env::vars_os()); let mut child = command.spawn().expect("noisy helper process"); + let stdout = child.stdout.take().expect("helper stdout"); let stderr = drain_helper_stderr(&mut child); - let error = tokio::time::timeout( - Duration::from_secs(/*secs*/ 8), - reap_helper_after_response(child, stderr), - ) + let error = tokio::time::timeout(Duration::from_secs(/*secs*/ 8), async { + // Cleanup starts after the response, not during slow helper startup. + read_helper_response(stdout).await?; + reap_helper_after_response(child, stderr).await + }) .await .expect("helper stderr must be drained during bounded cleanup") .expect_err("nonzero helper exit should fail after its stderr pipe fills"); diff --git a/codex-rs/features/src/feature_configs.rs b/codex-rs/features/src/feature_configs.rs index a67162ee9b..09562e8722 100644 --- a/codex-rs/features/src/feature_configs.rs +++ b/codex-rs/features/src/feature_configs.rs @@ -313,6 +313,10 @@ pub struct MultiAgentV2ConfigToml { /// Overrides inherited developer instructions for subagents without role-specific instructions. #[serde(skip_serializing_if = "Option::is_none")] pub subagent_developer_instructions: Option, + /// Preserve the parent's model-visible history on full forks and append child instructions. + /// Defaults to false. Legacy compaction without a reusable context baseline still rebuilds. + #[serde(skip_serializing_if = "Option::is_none")] + pub preserve_fork_prefix: Option, #[serde(skip_serializing_if = "Option::is_none")] pub multi_agent_mode_hint_text: Option, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index 5891dc0c9b..646ae0fc6d 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -755,6 +755,7 @@ usage_hint_text = "Custom delegation guidance." root_agent_usage_hint_text = "Root guidance." subagent_usage_hint_text = "Subagent guidance." subagent_developer_instructions = "Delegate carefully." +preserve_fork_prefix = true multi_agent_mode_hint_text = "Custom mode guidance." tool_namespace = "agents" hide_spawn_agent_metadata = true @@ -784,6 +785,7 @@ non_code_mode_only = true root_agent_usage_hint_text: Some("Root guidance.".to_string()), subagent_usage_hint_text: Some("Subagent guidance.".to_string()), subagent_developer_instructions: Some("Delegate carefully.".to_string()), + preserve_fork_prefix: Some(true), multi_agent_mode_hint_text: Some("Custom mode guidance.".to_string()), tool_namespace: Some("agents".to_string()), hide_spawn_agent_metadata: Some(true), diff --git a/codex-rs/guardian-context/src/history.rs b/codex-rs/guardian-context/src/history.rs index 310e50be2e..90aad3efd9 100644 --- a/codex-rs/guardian-context/src/history.rs +++ b/codex-rs/guardian-context/src/history.rs @@ -228,7 +228,12 @@ impl TranscriptHistory { impl SectionHistory for TranscriptHistory { fn items(&self) -> Box + Send + '_> { - Box::new(self.items.iter().map(|(item, _)| &item.item)) + Box::new( + self.items + .iter() + .filter(|(item, _)| !crate::is_inherited_manual_approval(item)) + .map(|(item, _)| &item.item), + ) } } diff --git a/codex-rs/guardian-context/src/history_tests.rs b/codex-rs/guardian-context/src/history_tests.rs index 80624ca373..4748ad192e 100644 --- a/codex-rs/guardian-context/src/history_tests.rs +++ b/codex-rs/guardian-context/src/history_tests.rs @@ -33,6 +33,39 @@ fn rollback_keeps_the_earlier_prefix_or_clears_an_evicted_boundary() { assert_eq!(history.items().count(), 0); } +#[test] +fn inherited_manual_approvals_stay_out_of_review_after_checkpoint_replay() { + for content_type in ["input_text", "output_text"] { + let approval: ResponseItem = serde_json::from_value(json!({ + "type": "message", "role": "developer", "content": [{ + "type": content_type, "text": format!("{}\nApproved action: original action", crate::MANUAL_APPROVAL_DEVELOPER_PREFIX) + }] + })).unwrap(); + let mut inherited = ResponseItemEnvelope::new(approval.clone()); + inherited + .metadata + .get_or_insert_default() + .inherited_user_message = true; + let mut history = TranscriptHistory::default(); + history.reset([inherited.clone(), approval.clone().into()].iter()); + assert_eq!( + history.items().cloned().collect::>(), + vec![approval.clone()] + ); + let checkpoint = history.checkpoint(); + assert_eq!( + checkpoint.0[0], inherited, + "model history keeps the original approval and provenance" + ); + let mut restored = TranscriptHistory::default(); + restored.reset(checkpoint.0.iter()); + assert_eq!( + restored.items().cloned().collect::>(), + vec![approval] + ); + } +} + #[test] fn each_kind_evicts_its_own_oldest_entries_without_reordering() { let users = [message("first"), message("second"), message("third")]; diff --git a/codex-rs/guardian-context/src/lib.rs b/codex-rs/guardian-context/src/lib.rs index 6fc08650cc..f126d4f05a 100644 --- a/codex-rs/guardian-context/src/lib.rs +++ b/codex-rs/guardian-context/src/lib.rs @@ -41,6 +41,7 @@ pub use transcript::MANUAL_APPROVAL_DEVELOPER_PREFIX; pub use transcript::TranscriptEntryLimits; pub use transcript::TranscriptRetentionConfig; pub use transcript::collect_transcript; +pub use transcript::is_inherited_manual_approval; pub use truncation::truncate_text; mod verified_answers; diff --git a/codex-rs/guardian-context/src/transcript.rs b/codex-rs/guardian-context/src/transcript.rs index ff50ecc9d3..02fffef0f8 100644 --- a/codex-rs/guardian-context/src/transcript.rs +++ b/codex-rs/guardian-context/src/transcript.rs @@ -37,6 +37,19 @@ pub(crate) const TRANSCRIPT_OMISSION_NOTICE: &str = "Some conversation entries w pub const MANUAL_APPROVAL_DEVELOPER_PREFIX: &str = "The user has manually approved a specific action that was previously `Rejected`."; +/// Copied approval messages are model context, not a child's trusted approval evidence. +/// Filter before dropping envelope provenance, including when replaying review checkpoints. +pub fn is_inherited_manual_approval(envelope: &codex_history::ResponseItemEnvelope) -> bool { + envelope + .metadata + .as_ref() + .is_some_and(|metadata| metadata.inherited_user_message) + && matches!(&envelope.item, ResponseItem::Message { role, content, .. } + if role == "developer" && content.iter().any(|part| + matches!(part, ContentItem::InputText { text } | ContentItem::OutputText { text } + if text.starts_with(MANUAL_APPROVAL_DEVELOPER_PREFIX)))) +} + /// Evidence sources included alongside user and assistant conversation messages. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ConversationTranscriptOptions {