From 06f334aa4b053023c5b4199dde0ba9c004d64820 Mon Sep 17 00:00:00 2001 From: felixxia-oai Date: Wed, 25 Nov 2026 14:59:14 +0000 Subject: [PATCH] Add opt-in shadow intake for Guardian V3 (#63949) ## What changed Add the default-off `features.guardianv3_shadow` flag and ignore it in project config. When Guardian V2 handles Auto Review and Guardian V3 is disabled, enroll eligible new threads in background evidence intake while Guardian V2 keeps making approval decisions. Share an in-memory evidence board between the root and its child agents. Keep shadow reviewer sessions ephemeral and suppress their events in the parent thread. Retry failed intake startup on a later turn, and stop shadow work when the root leaves Auto Review or shuts down. ## Testing Cover enrollment for opted-in new threads, startup retry, child attachment and cancellation, and the absence of an on-disk board. Verify that project config cannot set the flag. GitOrigin-RevId: 7c31c1d831498ba012193579123ac87779b76b85 --- codex-rs/app-server/src/extensions.rs | 10 +- codex-rs/config/src/loader/mod.rs | 1 + codex-rs/config/src/loader/tests.rs | 3 +- codex-rs/core/config.schema.json | 6 + .../core/src/guardian/review_session_setup.rs | 8 +- codex-rs/core/src/guardian_review.rs | 10 + codex-rs/ext/guardian-v3/src/actor.rs | 30 ++- codex-rs/ext/guardian-v3/src/conversation.rs | 8 + codex-rs/ext/guardian-v3/src/host.rs | 212 ++++++++++++++---- codex-rs/ext/guardian-v3/src/host_tests.rs | 159 +++++++++++++ codex-rs/ext/guardian-v3/src/lib.rs | 1 + codex-rs/ext/guardian-v3/src/shadow.rs | 167 ++++++++++++++ codex-rs/features/src/lib.rs | 8 + 13 files changed, 565 insertions(+), 58 deletions(-) create mode 100644 codex-rs/ext/guardian-v3/src/shadow.rs diff --git a/codex-rs/app-server/src/extensions.rs b/codex-rs/app-server/src/extensions.rs index c992d001b4..b66e7c73a0 100644 --- a/codex-rs/app-server/src/extensions.rs +++ b/codex-rs/app-server/src/extensions.rs @@ -107,11 +107,13 @@ pub(crate) fn thread_extensions( git_attribution_base_url, http_client_factory, ); + let board_manager = thread_manager.clone(); + let board_host = + move |root| codex_agent_message_board_host::local_board_host(board_manager.clone(), root); if config.features.enabled(codex_features::Feature::GuardianV3) { - let board_manager = thread_manager.clone(); - codex_guardian_v3::install(&mut builder, thread_manager.clone(), config, move |root| { - codex_agent_message_board_host::local_board_host(board_manager.clone(), root) - }); + codex_guardian_v3::install(&mut builder, thread_manager.clone(), config, board_host); + } else { + codex_guardian_v3::install_shadow(&mut builder, thread_manager.clone(), board_host); } codex_guardian_v2::install(&mut builder, auth_manager.clone(), thread_manager); codex_memories_extension::install(&mut builder, codex_otel::global()); diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs index 88adf330a1..1e6e8dfd71 100644 --- a/codex-rs/config/src/loader/mod.rs +++ b/codex-rs/config/src/loader/mod.rs @@ -1404,6 +1404,7 @@ fn sanitize_project_config( "respect_system_proxy", "system_proxy_fallback", "credential_masking", + "guardianv3_shadow", ] { if features.remove(key).is_some() { ignored_keys.push(format!("features.{key}")); diff --git a/codex-rs/config/src/loader/tests.rs b/codex-rs/config/src/loader/tests.rs index b6ffd272b7..a71dc1da91 100644 --- a/codex-rs/config/src/loader/tests.rs +++ b/codex-rs/config/src/loader/tests.rs @@ -1359,11 +1359,12 @@ fn project_config_cannot_supply_guardian_v3_prompts_or_their_cap() { } #[test] -fn project_config_cannot_change_system_proxy_routing_or_credential_masking() { +fn project_config_cannot_change_protected_features() { for key in [ "respect_system_proxy", "system_proxy_fallback", "credential_masking", + "guardianv3_shadow", ] { for enabled in [false, true] { let mut config: TomlValue = diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 084399c834..bb4ea0f6b2 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1132,6 +1132,9 @@ "guardianv3": { "$ref": "#/definitions/FeatureToml_for_GuardianV3ConfigToml" }, + "guardianv3_shadow": { + "type": "boolean" + }, "hooks": { "type": "boolean" }, @@ -8519,6 +8522,9 @@ "guardianv3": { "$ref": "#/definitions/FeatureToml_for_GuardianV3ConfigToml" }, + "guardianv3_shadow": { + "type": "boolean" + }, "hooks": { "type": "boolean" }, diff --git a/codex-rs/core/src/guardian/review_session_setup.rs b/codex-rs/core/src/guardian/review_session_setup.rs index 8f5b77d6e4..4826371dfb 100644 --- a/codex-rs/core/src/guardian/review_session_setup.rs +++ b/codex-rs/core/src/guardian/review_session_setup.rs @@ -197,7 +197,13 @@ impl PreparedGuardianContext { cancellation: CancellationToken, ) -> GuardianReviewSession { let session = Arc::clone(&thread.session); - if self.parent.enabled(Feature::GuardianRecordedItems) { + if self.parent.enabled(Feature::GuardianRecordedItems) + && session + .services + .thread_extension_data + .get::() + .is_none() + { session .parent_observer_event_tx .get_or_init(|| self.parent.get_tx_event()); diff --git a/codex-rs/core/src/guardian_review.rs b/codex-rs/core/src/guardian_review.rs index 2a7e3ad793..9a19d2fd81 100644 --- a/codex-rs/core/src/guardian_review.rs +++ b/codex-rs/core/src/guardian_review.rs @@ -40,6 +40,16 @@ pub fn reviewer_headers(config: &crate::config::Config) -> crate::CodexResponses } } +/// Kept out of the authoritative reviewer slot so routing and prewarming stay unchanged. +pub struct ShadowReviewer { + pub reviewer: std::sync::Arc, + /// Stops this actor when it shuts down or the root leaves Auto Review. + pub cancellation: tokio_util::sync::CancellationToken, +} + +/// Marks the private inference thread, which must never forward items to its parent. +pub struct ShadowReviewSession; + /// Safe to report with a review ID before a verdict has started. #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] pub enum ReviewPreparationError { diff --git a/codex-rs/ext/guardian-v3/src/actor.rs b/codex-rs/ext/guardian-v3/src/actor.rs index 3bcb41d2d6..d3fd3b97cd 100644 --- a/codex-rs/ext/guardian-v3/src/actor.rs +++ b/codex-rs/ext/guardian-v3/src/actor.rs @@ -57,7 +57,9 @@ impl PreparedReviewer { } pub fn finish(mut self, disposition: SessionDisposition) { - if disposition == SessionDisposition::Reusable { + if disposition == SessionDisposition::Reusable + && !self.conversation.thread.has_shutdown_status() + { self.conversation.kind = GuardianReviewSessionKind::TrunkReused; *self.slot = Some(self.conversation); } @@ -72,6 +74,7 @@ impl ActorReviewer { path: AgentPath, retrieval: ReviewRetrieval, tree: Arc, + cancellation: CancellationToken, ) -> Self { Self { manager, @@ -84,7 +87,10 @@ impl ActorReviewer { binding: None, })), slot: Default::default(), - lifetime: Default::default(), + lifetime: ReviewerTasks { + cancellation, + ..Default::default() + }, } } @@ -92,6 +98,11 @@ impl ActorReviewer { self.lifetime.cancellation.cancel(); self.lifetime.tasks.close(); self.lifetime.tasks.wait().await; + // A loaded child may keep its cancelled registration until its next + // turn. Release the retired conversation and its board handles now. + if let Ok(mut slot) = self.slot.try_lock() { + slot.take(); + } let delivery = self .delivery .lock() @@ -113,6 +124,7 @@ impl ActorReviewer { } let delivery = state .tree + .delivery .get() .ok_or(ReviewPreparationError::EvidenceUnavailable)?; let binding = LiveRetrievalBinding::new(board, self.actor, self.path.clone(), delivery) @@ -197,10 +209,16 @@ impl ActorReviewer { ) -> Result { let binding = self.binding(Arc::clone(&worker.reader))?; let stop = self.lifetime.cancellation.child_token(); - let conversation = - Conversation::start(manager, setup, &self.lifetime, binding, stop.clone()) - .await - .map_err(|_| ReviewPreparationError::ReviewerUnavailable)?; + let conversation = Conversation::start( + manager, + setup, + &self.lifetime, + binding, + stop.clone(), + worker.shadow, + ) + .await + .map_err(|_| ReviewPreparationError::ReviewerUnavailable)?; self.observe_inbox( Arc::clone(&worker.reader), &conversation.inbox, diff --git a/codex-rs/ext/guardian-v3/src/conversation.rs b/codex-rs/ext/guardian-v3/src/conversation.rs index f13903b9a5..af3ad7d47d 100644 --- a/codex-rs/ext/guardian-v3/src/conversation.rs +++ b/codex-rs/ext/guardian-v3/src/conversation.rs @@ -64,11 +64,19 @@ impl Conversation { owner: &ReviewerTasks, binding: LiveRetrievalBinding, stop: CancellationToken, + shadow: bool, ) -> anyhow::Result { let key = prepared.reuse_key(/*previous*/ None); let (mut options, state) = prepared .thread_options(GuardianReviewSessionKind::TrunkNew, /*snapshot*/ None) .await; + if shadow { + options.config.ephemeral = true; + options.config.feedback_enabled = false; + options + .thread_extension_init + .insert(codex_core::guardian_review::ShadowReviewSession); + } options.initial_history = codex_history::InitialHistory::New; let mut registry = ExtensionRegistryBuilder::::default(); crate::install_retrieval_tools(&mut registry); diff --git a/codex-rs/ext/guardian-v3/src/host.rs b/codex-rs/ext/guardian-v3/src/host.rs index 88757e8fec..50330ca03e 100644 --- a/codex-rs/ext/guardian-v3/src/host.rs +++ b/codex-rs/ext/guardian-v3/src/host.rs @@ -12,6 +12,7 @@ use codex_core::ThreadManager; use codex_core::config::Config; use codex_core::guardian_review::PreserveReviewWrites; use codex_core::guardian_review::ReviewRetrieval; +use codex_core::guardian_review::ShadowReviewer; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; @@ -21,6 +22,7 @@ use codex_extension_api::ThreadStartInput; use codex_extension_api::ThreadStopInput; use codex_extension_api::TurnAbortInput; use codex_extension_api::TurnLifecycleContributor; +use codex_extension_api::TurnStartInput; use codex_extension_api::TurnStopInput; use codex_features::GuardianV3HousekeeperConfigToml; use codex_guardian_reviewer::ReviewerTasks; @@ -34,6 +36,7 @@ use codex_protocol::ThreadId; use codex_protocol::items::TurnItem; use codex_state::SqliteConfig; use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; use crate::ActorReviewer; use crate::EvidenceCursor; @@ -42,6 +45,9 @@ use crate::LiveDelivery; use crate::local_board; use crate::local_board_options; +#[path = "shadow.rs"] +mod shadow; + #[cfg(test)] #[path = "host_tests.rs"] mod tests; @@ -54,8 +60,9 @@ pub fn install( ) { let settings = config.guardian_v3.as_deref(); let host = Arc::new(Host { + shadow: false, manager, - deliveries: Mutex::default(), + deliveries: Arc::default(), storage: if settings .and_then(|settings| settings.message_board_in_memory) .unwrap_or(false) @@ -74,12 +81,47 @@ pub fn install( .and_then(|settings| settings.reviewer.as_ref()) .and_then(|reviewer| reviewer.retrieval_instructions.as_deref()), ), - board_host: Box::new(board_host), + board_host: Arc::new(board_host), }); registry.thread_lifecycle_contributor(host.clone()); registry.turn_lifecycle_contributor(host); } +/// Desktop supplies rollout overrides at thread start, after registration. +pub fn install_shadow( + registry: &mut ExtensionRegistryBuilder, + manager: Weak, + board_host: impl Fn(ThreadId) -> Arc + Send + Sync + 'static, +) { + let host = Arc::new(Host { + shadow: true, + manager, + deliveries: Arc::default(), + storage: BoardStorage::Memory, + housekeeper: Arc::default(), + retrieval: crate::board_retrieval(/*instructions*/ None), + board_host: Arc::new(board_host), + }); + registry.thread_lifecycle_contributor(host.clone()); + registry.config_contributor(host.clone()); + registry.turn_lifecycle_contributor(host); +} + +impl Host { + fn enabled(&self, config: &Config) -> bool { + !self.shadow + || (config + .features + .enabled(codex_features::Feature::GuardianV3Shadow) + && config.features.enabled(codex_features::Feature::GuardianV2) + && routes_approval_policy_to_guardian( + config.permissions.approval_policy.value(), + config.approvals_reviewer, + )) + } +} + +#[derive(Clone)] enum BoardStorage { File(SqliteConfig), Memory, @@ -87,18 +129,26 @@ enum BoardStorage { // Shared by loaded actors, even before their first review. // Only the root can initialize the cursor, using its own history. -pub(super) type TreeDelivery = OnceLock>; +#[derive(Default)] +pub(super) struct TreeDelivery { + pub(super) delivery: OnceLock>, + stop: CancellationToken, + actors: Mutex>>, +} +#[derive(Clone)] struct Host { + shadow: bool, manager: Weak, - deliveries: Mutex>>, + deliveries: Arc>>>, storage: BoardStorage, housekeeper: Arc, retrieval: ReviewRetrieval, - board_host: Box Arc + Send + Sync>, + board_host: Arc Arc + Send + Sync>, } pub(super) struct RootWorker { + pub(super) shadow: bool, pub(super) reader: Arc, wake: mpsc::Sender<()>, lifetime: ReviewerTasks, @@ -110,44 +160,58 @@ impl Host { .deliveries .lock() .unwrap_or_else(PoisonError::into_inner); - if let Some(tree) = deliveries.get(&root).and_then(Weak::upgrade) { + if let Some(tree) = deliveries.get(&root).and_then(Weak::upgrade) + && !tree.stop.is_cancelled() + { return tree; } deliveries.retain(|_, tree| tree.strong_count() > 0); - let tree = Arc::new(TreeDelivery::new()); + let tree = Arc::new(TreeDelivery::default()); deliveries.insert(root, Arc::downgrade(&tree)); tree } + fn reviewer( + &self, + identity: &shadow::Actor, + tree: &Arc, + cancellation: CancellationToken, + ) -> Arc { + Arc::new(ActorReviewer::new( + self.manager.clone(), + identity.root, + identity.actor, + identity.path.clone(), + self.retrieval.clone(), + Arc::clone(tree), + cancellation, + )) + } + async fn activate( &self, root: ThreadId, tree: &TreeDelivery, - input: &ThreadReadyInput<'_, Config>, + thread: &ExtensionData, + mode: codex_protocol::protocol::ThreadHistoryMode, + initialization: HistoryInitialization, ) -> anyhow::Result<()> { - // On resume the intake cursor starts at the tail. A new in-memory board - // cannot serve earlier evidence, so leave its attached reviewer unavailable. - if matches!(self.storage, BoardStorage::Memory) { - anyhow::ensure!( - matches!( - input.history_initialization, - HistoryInitialization::New | HistoryInitialization::Cleared - ), - "in-memory Guardian evidence requires a fresh root" - ); - } let history = self .manager .upgrade() .context("Guardian host stopped")? .thread_store(); - let cursor = EvidenceCursor::at_thread_ready( - history.as_ref(), - root, - input.history_mode, - input.history_initialization, - ) - .await?; + if matches!(self.storage, BoardStorage::Memory) { + anyhow::ensure!( + matches!( + initialization, + HistoryInitialization::New | HistoryInitialization::Cleared + ), + "in-memory Guardian evidence requires a fresh root" + ); + } + let cursor = + EvidenceCursor::at_thread_ready(history.as_ref(), root, mode, initialization).await?; let board_host = (self.board_host)(root); let board = match &self.storage { BoardStorage::File(sqlite) => { @@ -165,11 +229,23 @@ impl Host { .await? } }; + // No awaits after this check. A concurrent stop must either cancel + // startup or find the published worker to drain. + let _publication = tree.actors.lock().unwrap_or_else(PoisonError::into_inner); + if tree.stop.is_cancelled() { + return Ok(()); + } let reader: Arc = Arc::new(board.read_only_handle()); - let lifetime = ReviewerTasks::default(); + let lifetime = ReviewerTasks { + cancellation: tree.stop.child_token(), + ..Default::default() + }; let (wake, mut wakes) = mpsc::channel(1); let initial_position = cursor.position(); - let delivery = Arc::clone(tree.get_or_init(|| Arc::new(LiveDelivery::from_cursor(cursor)))); + let delivery = Arc::clone( + tree.delivery + .get_or_init(|| Arc::new(LiveDelivery::from_cursor(cursor))), + ); let saved = delivery.cursor(); // A surviving child can keep a cursor behind the resumed root's history tail. if saved.position().thread_id == initial_position.thread_id @@ -177,6 +253,7 @@ impl Host { { let _ = wake.try_send(()); } + let shadow = self.shadow; let manager = self.manager.clone(); let settings = Arc::clone(&self.housekeeper); let cancellation = lifetime.cancellation.clone(); @@ -187,7 +264,11 @@ impl Host { while let Some(Some(())) = cancellation.run_until_cancelled(wakes.recv()).await { let cursor = delivery.cursor(); let read = async { - history.flush_thread(root).await?; + // Shadow reads can catch up on the next wake without + // contending with live appends for the history writer. + if !shadow { + history.flush_thread(root).await?; + } cursor.read_history(history.as_ref()).await }; let Some(records) = cancellation.run_until_cancelled(read).await else { @@ -252,7 +333,8 @@ impl Host { tracing::warn!(%root, "Guardian housekeeping stopped"); } }); - input.thread_store.insert(RootWorker { + thread.insert(RootWorker { + shadow: self.shadow, wake, lifetime, reader, @@ -266,12 +348,20 @@ impl ThreadLifecycleContributor for Host { &'a self, input: ThreadStartInput<'a, Config>, ) -> ExtensionFuture<'a, ()> { - // Let accepted instructions outlive an interrupted turn on this root. + if !self.enabled(input.config) { + return Box::pin(std::future::ready(())); + } if !input.config.ephemeral && !input.session_source.is_internal() && input.thread_store.level_id() == input.session_store.level_id() { - input.thread_store.insert(PreserveReviewWrites); + if self.shadow { + // Observe settings changes even before the root is ready. + input.thread_store.insert(shadow::Enrollment::default()); + } else { + // Only authoritative GV3 needs evidence writes to survive interruption. + input.thread_store.insert(PreserveReviewWrites); + } } Box::pin(std::future::ready(())) } @@ -281,7 +371,10 @@ impl ThreadLifecycleContributor for Host { input: ThreadReadyInput<'a, Config>, ) -> ExtensionFuture<'a, ()> { Box::pin(async move { - if input.session_source.is_internal() || input.config.ephemeral { + if input.session_source.is_internal() + || input.config.ephemeral + || !self.enabled(input.config) + { return; } let (Ok(actor), Ok(root)) = ( @@ -298,23 +391,39 @@ impl ThreadLifecycleContributor for Host { else { return; }; + let identity = shadow::Actor { root, actor, path }; + if self.shadow { + // Only the root supplies history. Children can inherit context and share its board. + if actor == root + && (input.history_mode + != codex_protocol::protocol::ThreadHistoryMode::Paginated + || !matches!(input.history_initialization, HistoryInitialization::New)) + { + return; + } + input.thread_store.insert(identity); + self.start_shadow_if_needed(input.thread_store); + return; + } let tree = self.tree_delivery(root); - let actor_reviewer = Arc::new(ActorReviewer::new( - self.manager.clone(), - root, - actor, - path, - self.retrieval.clone(), - Arc::clone(&tree), - )); - input.thread_store.insert_arc(Arc::clone(&actor_reviewer)); - let attached: Arc = - actor_reviewer.clone(); + // The authoritative reviewer must stay attached even if intake fails. + let reviewer = self.reviewer(&identity, &tree, tree.stop.child_token()); + let attached: Arc = reviewer.clone(); + input.thread_store.insert_arc(Arc::clone(&reviewer)); input.thread_store.insert(attached); if actor != root { return; } - if let Err(error) = self.activate(root, &tree, &input).await { + if let Err(error) = self + .activate( + root, + &tree, + input.thread_store, + input.history_mode, + input.history_initialization, + ) + .await + { tracing::warn!(%root, error = %error, "Guardian intake unavailable"); return; } @@ -322,12 +431,18 @@ impl ThreadLifecycleContributor for Host { input.config.permissions.approval_policy.value(), input.config.approvals_reviewer, ) { - actor_reviewer.schedule_root_prewarm(); + reviewer.schedule_root_prewarm(); } }) } fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { Box::pin(async move { + input.thread_store.remove::(); + if let Some(enrollment) = input.thread_store.remove::() { + enrollment.stop(input.thread_store); + enrollment.drain().await; + } + input.thread_store.remove::(); if let Some(actor) = input.thread_store.remove::() { actor.shutdown().await; } @@ -341,6 +456,11 @@ impl ThreadLifecycleContributor for Host { } impl TurnLifecycleContributor for Host { + fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> { + self.start_shadow_if_needed(input.thread_store); + Box::pin(std::future::ready(())) + } + fn on_item_completed<'a>( &'a self, thread: &'a ExtensionData, diff --git a/codex-rs/ext/guardian-v3/src/host_tests.rs b/codex-rs/ext/guardian-v3/src/host_tests.rs index 9c5f6cf789..2a57671035 100644 --- a/codex-rs/ext/guardian-v3/src/host_tests.rs +++ b/codex-rs/ext/guardian-v3/src/host_tests.rs @@ -496,3 +496,162 @@ async fn committed_posts_reach_current_subscribers_once_across_channel_retries() ); Ok(()) } + +#[tokio::test] +async fn shadow_intake_enrolls_only_new_opted_in_roots() -> anyhow::Result<()> { + use codex_core::guardian_review::AttachedReviewer; + use codex_core::guardian_review::ShadowReviewer; + use codex_extension_api::ExtensionData; + use codex_extension_api::ExtensionRegistryBuilder; + use codex_extension_api::ThreadReadyInput; + use codex_extension_api::ThreadStopInput; + use codex_features::Feature; + use codex_protocol::AgentPath; + use codex_protocol::ThreadId; + use codex_protocol::protocol::AskForApproval; + use codex_protocol::protocol::SessionSource; + use codex_protocol::protocol::SubAgentSource; + use futures::FutureExt; + + core_test_support::skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let test = test_codex() + .with_history_mode(ThreadHistoryMode::Paginated) + .build_with_auto_env(&server) + .await?; + let root = test.session_configured.thread_id; + let session = ExtensionData::new(root.to_string()); + let thread = test.codex.thread_extension_data(); + let mut registry = ExtensionRegistryBuilder::default(); + crate::install_shadow( + &mut registry, + Arc::downgrade(&test.thread_manager), + |root| board_host(root), + ); + let registry = registry.build(); + let lifecycle = ®istry.thread_lifecycle_contributors()[0]; + let mut config = test.config.clone(); + config.features.enable(Feature::GuardianV2)?; + config.approvals_reviewer = ApprovalsReviewer::AutoReview; + config + .permissions + .approval_policy + .set(AskForApproval::OnRequest)?; + let mode = test + .codex + .thread_settings_snapshot() + .await + .collaboration_mode; + let turn = ExtensionData::new("retry"); + let start = || codex_extension_api::TurnStartInput { + turn_id: "retry", + collaboration_mode: &mode, + token_usage_at_turn_start: None, + session_store: &session, + thread_store: thread, + turn_store: &turn, + }; + let turns = ®istry.turn_lifecycle_contributors()[0]; + // Force the first lookup to fail, then retry with the live manager on a turn. + let mut unavailable = ExtensionRegistryBuilder::default(); + crate::install_shadow(&mut unavailable, std::sync::Weak::new(), |root| { + board_host(root) + }); + let unavailable = unavailable.build(); + for (enrolled, history, expected) in [ + (false, HistoryInitialization::New, false), + (true, HistoryInitialization::ColdResume, false), + (true, HistoryInitialization::WarmFork, false), + (true, HistoryInitialization::New, true), + ] { + if enrolled { + config.features.enable(Feature::GuardianV3Shadow)?; + } + lifecycle + .on_thread_start(codex_extension_api::ThreadStartInput { + config: &config, + session_source: &SessionSource::Exec, + persistent_thread_state_available: true, + environments: &[], + mcp_resource_client: None, + extension_metrics: None, + session_store: &session, + thread_store: thread, + }) + .await; + assert!(thread.get::().is_none()); + let ready = unavailable.thread_lifecycle_contributors()[0] + .on_thread_ready(ThreadReadyInput { + config: &config, + session_source: &SessionSource::Exec, + history_initialization: history, + history_mode: ThreadHistoryMode::Paginated, + session_store: &session, + thread_store: thread, + }) + .now_or_never(); + assert_eq!(ready, Some(())); + assert!(thread.get::().is_none()); + if let Some(enrollment) = thread.get::() { + enrollment.drain().await; + assert!(thread.get::().is_none()); + assert!(thread.get::().is_none()); + assert_eq!(turns.on_turn_start(start()).now_or_never(), Some(())); + enrollment.drain().await; + } + assert_eq!(thread.get::().is_some(), expected); + assert_eq!(thread.get::().is_some(), expected); + assert!(thread.get::>().is_none()); + } + let old_reviewer = thread.get::().context("first reviewer")?; + let child = ExtensionData::new(ThreadId::new().to_string()); + let source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: root, + depth: 1, + agent_path: Some( + AgentPath::root() + .join("worker") + .map_err(anyhow::Error::msg)?, + ), + agent_nickname: None, + agent_role: None, + }); + lifecycle + .on_thread_ready(ThreadReadyInput { + config: &config, + session_source: &source, + history_initialization: HistoryInitialization::WarmFork, + history_mode: ThreadHistoryMode::Paginated, + session_store: &session, + thread_store: &child, + }) + .await; + let child_reviewer = child.get::().context("child reviewer")?; + assert!(child.get::().is_none()); + + let mut disabled = config.clone(); + disabled.approvals_reviewer = ApprovalsReviewer::User; + let settings = ®istry.config_contributors()[0]; + settings.on_config_changed(&session, thread, &config, &disabled); + assert!(old_reviewer.cancellation.is_cancelled()); + assert!(child_reviewer.cancellation.is_cancelled()); + assert!(thread.get::().is_none()); + assert!(thread.get::().is_none()); + + lifecycle + .on_thread_stop(ThreadStopInput { + thread_store: thread, + session_store: &session, + }) + .await; + assert!(thread.get::().is_none()); + assert!( + !config + .sqlite_config() + .home() + .join("message_board_guardian_1.sqlite") + .exists() + ); + test.codex.shutdown_and_wait().await?; + Ok(()) +} diff --git a/codex-rs/ext/guardian-v3/src/lib.rs b/codex-rs/ext/guardian-v3/src/lib.rs index 7d091037f9..300bac85f4 100644 --- a/codex-rs/ext/guardian-v3/src/lib.rs +++ b/codex-rs/ext/guardian-v3/src/lib.rs @@ -21,6 +21,7 @@ mod housekeeper_sampler; mod housekeeper_transport; mod inbox; pub use host::install; +pub use host::install_shadow; mod retrieval_tools; mod sampling; mod subscription_tools; diff --git a/codex-rs/ext/guardian-v3/src/shadow.rs b/codex-rs/ext/guardian-v3/src/shadow.rs new file mode 100644 index 0000000000..61c659079a --- /dev/null +++ b/codex-rs/ext/guardian-v3/src/shadow.rs @@ -0,0 +1,167 @@ +//! Shadow intake starts off the live path and stops when the root leaves Auto Review. + +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::PoisonError; +use std::sync::Weak; + +use anyhow::Context; +use codex_core::config::Config; +use codex_core::guardian_review::ShadowReviewer; +use codex_extension_api::ConfigContributor; +use codex_extension_api::ExtensionData; +use codex_protocol::AgentPath; +use codex_protocol::ThreadId; +use tokio_util::task::TaskTracker; + +use super::ActorReviewer; +use super::Host; +use super::RootWorker; +use super::TreeDelivery; + +pub(super) struct Actor { + pub(super) root: ThreadId, + pub(super) actor: ThreadId, + pub(super) path: AgentPath, +} + +#[derive(Default)] +enum State { + // Covers startup and the published worker. Both share one cancellation token. + Running(Arc), + Off, + #[default] + PendingStart, +} + +#[derive(Default)] +pub(super) struct Enrollment { + state: Mutex, + tasks: TaskTracker, +} + +impl Enrollment { + pub(super) fn stop(&self, thread: &ExtensionData) { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let State::Running(tree) = std::mem::replace(&mut *state, State::Off) else { + return; + }; + // Serialize cancellation with publishing a reviewer or worker at startup. + let actors = tree.actors.lock().unwrap_or_else(PoisonError::into_inner); + tree.stop.cancel(); + let reviewers: Vec<_> = actors.iter().filter_map(Weak::upgrade).collect(); + thread.remove::(); + thread.remove::(); + let worker = thread.remove::(); + // Settings callbacks are synchronous. Drain accepted writes and reviewer + // sessions off the live path; thread shutdown joins this cleanup. + self.tasks.spawn(async move { + for reviewer in reviewers { + reviewer.shutdown().await; + } + if let Some(worker) = worker { + worker.lifetime.tasks.close(); + worker.lifetime.tasks.wait().await; + } + }); + } + + pub(super) async fn drain(&self) { + self.tasks.close(); + self.tasks.wait().await; + } +} + +impl ConfigContributor for Host { + fn on_config_changed( + &self, + _session: &ExtensionData, + thread: &ExtensionData, + _previous: &Config, + config: &Config, + ) { + let Some(enrollment) = thread.get::() else { + return; + }; + if !self.enabled(config) { + enrollment.stop(thread); + } + } +} + +impl Host { + fn attach_shadow(&self, thread: &ExtensionData, identity: &Actor, tree: &Arc) { + let mut actors = tree.actors.lock().unwrap_or_else(PoisonError::into_inner); + if tree.stop.is_cancelled() || tree.delivery.get().is_none() { + return; + } + let cancellation = tree.stop.child_token(); + let reviewer = self.reviewer(identity, tree, cancellation.clone()); + actors.retain(|actor| actor.strong_count() > 0); + actors.push(Arc::downgrade(&reviewer)); + thread.insert_arc(Arc::clone(&reviewer)); + thread.insert(ShadowReviewer { + reviewer: reviewer.clone(), + cancellation, + }); + if identity.actor == identity.root { + reviewer.schedule_root_prewarm(); + // User-message and turn-end wakes may have arrived before startup. + super::wake_worker(thread); + } + } + + pub(super) fn start_shadow_if_needed(&self, thread: &ExtensionData) { + let Some(identity) = thread.get::() else { + return; + }; + let root = identity.root; + if identity.actor != root { + // The root board may become available after a child starts. + if thread.get::().is_some() { + return; + } + self.attach_shadow(thread, &identity, &self.tree_delivery(root)); + return; + } + let Some(enrollment) = thread.get::() else { + return; + }; + let mut state = enrollment + .state + .lock() + .unwrap_or_else(PoisonError::into_inner); + let State::PendingStart = *state else { + return; + }; + let tree = self.tree_delivery(root); + *state = State::Running(Arc::clone(&tree)); + let host = self.clone(); + let current = Arc::clone(&enrollment); + enrollment.tasks.spawn(async move { + let startup = async { + let manager = host.manager.upgrade().context("Guardian host stopped")?; + let root_thread = manager + .get_thread_with_extension::(root, |e| { + std::ptr::eq(e, current.as_ref()) + }) + .await?; + let thread = root_thread.thread_extension_data(); + host.activate(root, &tree, thread, codex_protocol::protocol::ThreadHistoryMode::Paginated, codex_history::HistoryInitialization::New).await?; + host.attach_shadow(thread, &identity, &tree); + if !tree.stop.is_cancelled() { + tracing::debug!(event.name = "guardian_v3.shadow_intake_started", %root, "Guardian shadow intake started"); + } + anyhow::Ok(()) + }; + if let Some(Err(_)) = tree.stop.run_until_cancelled(startup).await { + let mut state = current.state.lock().unwrap_or_else(PoisonError::into_inner); + if !tree.stop.is_cancelled() { + *state = State::PendingStart; + drop(state); + tracing::warn!(%root, "Guardian shadow intake unavailable until the next turn"); + } + } + }); + } +} diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index ccdb5a7db8..5206c6529a 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -493,6 +493,8 @@ pub enum Feature { GuardianV2DecisionsComparison, /// Enable Guardian V3 integrations. GuardianV3, + /// Observe Guardian V3 alongside the existing automatic reviewer. + GuardianV3Shadow, /// Removed compatibility flag for the unused Guardian extension prototype. GuardianExt, /// Enable persisted thread goals and automatic goal continuation. @@ -2384,6 +2386,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::GuardianV3Shadow, + key: "guardianv3_shadow", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::GuardianExt, key: "guardian_ext",