diff --git a/codex-rs/core/src/guardian/review_session_setup.rs b/codex-rs/core/src/guardian/review_session_setup.rs index e1385b3c31..acf21118dd 100644 --- a/codex-rs/core/src/guardian/review_session_setup.rs +++ b/codex-rs/core/src/guardian/review_session_setup.rs @@ -76,6 +76,16 @@ impl PreparedGuardianContext { } impl PreparedGuardianContext { + /// Compares reviewer settings and the parent's history-reset version. + /// Callers separately decide whether changes to parent history or the root's + /// authorization and review-context revisions allow reuse. + pub fn matches_session_configuration(&self, previous: &GuardianReviewSession) -> bool { + let mut key = self.key.clone(); + key.root_review_version = previous.reuse_key.root_review_version; + key.parent_history_version = previous.reuse_key.parent_history_version; + key == previous.reuse_key + } + pub fn reuse_key( &self, previous: Option<&GuardianReviewSession>, diff --git a/codex-rs/ext/guardian-v3/src/actor.rs b/codex-rs/ext/guardian-v3/src/actor.rs new file mode 100644 index 0000000000..64192a21b6 --- /dev/null +++ b/codex-rs/ext/guardian-v3/src/actor.rs @@ -0,0 +1,108 @@ +//! One isolated verdict conversation per acting agent. Only a completed reusable turn +//! returns its conversation to the slot; dropping a reservation retires its thread. +use std::sync::Arc; +use std::sync::Weak; + +use anyhow::Context; +use codex_core::ThreadManager; +use codex_core::guardian_review::PreparedGuardianContext; +use codex_guardian_reviewer::ReviewerTasks; +use codex_guardian_reviewer::SessionDisposition; +use codex_protocol::AgentPath; +use codex_protocol::ThreadId; +use tokio::sync::Mutex; +use tokio::sync::OwnedMutexGuard; +use tokio_util::sync::CancellationToken; + +use crate::LiveRetrievalBinding; +use crate::conversation::Conversation; +use crate::host::RootWorker; + +pub struct ActorReviewer { + manager: Weak, + root: ThreadId, + actor: ThreadId, + path: AgentPath, + slot: Arc>>, + lifetime: ReviewerTasks, +} + +pub struct PreparedReviewer { + conversation: Conversation, + slot: OwnedMutexGuard>, +} + +impl PreparedReviewer { + pub fn thread_id(&self) -> ThreadId { + self.conversation.thread.startup_metadata().thread_id + } + + pub fn finish(mut self, disposition: SessionDisposition) { + if disposition == SessionDisposition::Reusable { + *self.slot = Some(self.conversation); + } + } +} + +impl ActorReviewer { + pub(super) fn new( + manager: Weak, + root: ThreadId, + actor: ThreadId, + path: AgentPath, + ) -> Self { + Self { + manager, + root, + actor, + path, + slot: Default::default(), + lifetime: Default::default(), + } + } + + pub(super) async fn shutdown(&self) { + self.lifetime.cancellation.cancel(); + self.lifetime.tasks.close(); + self.lifetime.tasks.wait().await; + } + + /// Reserve this actor's reviewer for one verdict without starting a model turn. + pub async fn reserve( + &self, + setup: &PreparedGuardianContext, + cancel: &CancellationToken, + ) -> anyhow::Result { + let _task = self.lifetime.tasks.token(); + let reserve = async { + let mut slot = self.slot.clone().lock_owned().await; + let conversation = match slot.take() { + Some(previous) if setup.matches_session_configuration(&previous.runtime) => { + previous + } + _ => { + let manager = self.manager.upgrade().context("Guardian host stopped")?; + let root = manager.get_thread(self.root).await?; + let worker = root + .thread_extension_data() + .get::() + .context("Guardian board unavailable")?; + let binding = LiveRetrievalBinding::new( + worker.reader.clone(), + self.actor, + self.path.clone(), + )?; + Conversation::start(&manager, setup, &self.lifetime, binding).await? + } + }; + Ok(PreparedReviewer { conversation, slot }) + }; + tokio::select! { + biased; + _ = self.lifetime.cancellation.cancelled() => anyhow::bail!("Guardian actor stopped"), + _ = setup.history_reset.cancelled() => anyhow::bail!("Guardian actor history reset"), + _ = cancel.cancelled() => anyhow::bail!("Guardian review cancelled"), + result = reserve => result, + } + } +} diff --git a/codex-rs/ext/guardian-v3/src/conversation.rs b/codex-rs/ext/guardian-v3/src/conversation.rs new file mode 100644 index 0000000000..fd89f11d7a --- /dev/null +++ b/codex-rs/ext/guardian-v3/src/conversation.rs @@ -0,0 +1,86 @@ +//! A retained verdict conversation binds one actor’s live board tools to an isolated reviewer thread. +use std::sync::Arc; + +use crate::LiveRetrievalBinding; +use codex_analytics::GuardianReviewSessionKind; +use codex_core::CodexThread; +use codex_core::ThreadManager; +use codex_core::config::Config; +use codex_core::guardian_review::GuardianReviewSession; +use codex_core::guardian_review::PreparedGuardianContext; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::IsolatedSessionExtensions; +use codex_extension_api::SessionIsolation; +use codex_extension_api::ToolName; +use codex_extension_api::ToolPolicy; +use codex_guardian_reviewer::ReviewerTasks; +use codex_protocol::protocol::InternalSessionSource; +use codex_protocol::protocol::SessionSource; +use tokio_util::sync::DropGuard; + +pub(super) struct Conversation { + pub(super) thread: Arc, + _stop: DropGuard, + pub(super) runtime: GuardianReviewSession, +} + +impl Conversation { + pub(super) async fn start( + manager: &Arc, + prepared: &PreparedGuardianContext, + owner: &ReviewerTasks, + binding: LiveRetrievalBinding, + ) -> anyhow::Result { + let key = prepared.reuse_key(/*previous*/ None); + let (mut options, state) = prepared + .thread_options(GuardianReviewSessionKind::TrunkNew, /*snapshot*/ None) + .await; + options.initial_history = codex_history::InitialHistory::New; + let mut registry = ExtensionRegistryBuilder::::default(); + crate::install_retrieval_tools(&mut registry); + options + .thread_extension_init + .insert(IsolatedSessionExtensions(Arc::new(registry.build()))); + // Code Mode dispatches nested calls through this same board-only registry. + let allowed = LiveRetrievalBinding::tool_names() + .chain(["exec", "wait"].map(ToolName::plain)) + .collect(); + options.thread_source = Some(codex_protocol::protocol::ThreadSource::GuardianReview); + options.client_mcp_extensions = Default::default(); + options.session_source = Some(SessionSource::Internal(InternalSessionSource::Guardian)); + options + .thread_extension_init + .insert(SessionIsolation::Isolated); + options.thread_extension_init.insert(binding); + options.thread_extension_init.insert(ToolPolicy { + allowed_tools: Some(allowed), + ..Default::default() + }); + options + .thread_extension_init + .insert(codex_core::guardian_review::reviewer_headers( + &options.config, + )); + let stop = owner.cancellation.child_token(); + let stop_guard = stop.clone().drop_guard(); + let until = stop.clone(); + let reset = prepared.history_reset.clone(); + let spawned = manager + .start_thread_until( + options, + async move { + tokio::select! { _ = until.cancelled() => (), _ = reset.cancelled() => () } + }, + &owner.tasks, + ) + .await?; + let runtime = prepared + .bind_thread(&spawned.thread, key, state, stop) + .await; + Ok(Self { + thread: spawned.thread, + _stop: stop_guard, + runtime, + }) + } +} diff --git a/codex-rs/ext/guardian-v3/src/host.rs b/codex-rs/ext/guardian-v3/src/host.rs index 975b944ec4..dabbd725a8 100644 --- a/codex-rs/ext/guardian-v3/src/host.rs +++ b/codex-rs/ext/guardian-v3/src/host.rs @@ -18,11 +18,13 @@ use codex_extension_api::TurnStopInput; use codex_guardian_reviewer::ReviewerTasks; use codex_message_board::AgentMessageBoard; use codex_message_board::MessageBoardHost; +use codex_protocol::AgentPath; use codex_protocol::ThreadId; use codex_protocol::items::TurnItem; use codex_state::SqliteConfig; use tokio::sync::mpsc; +use crate::ActorReviewer; use crate::EvidenceCursor; use crate::Housekeeper; use crate::cutoff::RootEvidence; @@ -49,7 +51,8 @@ struct Host { board_host: Box Arc + Send + Sync>, } -struct RootWorker { +pub(super) struct RootWorker { + pub(super) reader: Arc, wake: mpsc::Sender<()>, lifetime: Arc, } @@ -83,6 +86,11 @@ impl Host { lifetime .tasks .spawn(queue.clone().capture_on_activity(wakes)); + let worker = RootWorker { + wake, + lifetime: Arc::clone(&lifetime), + reader: Arc::clone(&reader), + }; let scope = lifetime.clone(); let manager = self.manager.clone(); lifetime.tasks.spawn(async move { @@ -134,7 +142,7 @@ impl Host { } }); input.thread_store.insert_arc(queue); - input.thread_store.insert(RootWorker { wake, lifetime }); + input.thread_store.insert(worker); Ok(()) } } @@ -145,15 +153,29 @@ impl ThreadLifecycleContributor for Host { input: ThreadReadyInput<'a, Config>, ) -> ExtensionFuture<'a, ()> { Box::pin(async move { - if input.session_source.is_internal() - || input.config.ephemeral - || input.thread_store.level_id() != input.session_store.level_id() - { + if input.session_source.is_internal() || input.config.ephemeral { return; } - let Ok(root) = ThreadId::from_string(input.thread_store.level_id()) else { + let (Ok(actor), Ok(root)) = ( + ThreadId::from_string(input.thread_store.level_id()), + ThreadId::from_string(input.session_store.level_id()), + ) else { return; }; + // Legacy spawned agents have no board identity and keep their native reviewer. + let Some(path) = input + .session_source + .get_agent_path() + .or_else(|| (actor == root).then(AgentPath::root)) + else { + return; + }; + let actor_reviewer = + Arc::new(ActorReviewer::new(self.manager.clone(), root, actor, path)); + input.thread_store.insert_arc(actor_reviewer); + if actor != root { + return; + } if let Err(error) = self.activate(root, &input).await { tracing::warn!(%root, error = %error, "Guardian intake unavailable"); } @@ -161,6 +183,9 @@ impl ThreadLifecycleContributor for Host { } fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { Box::pin(async move { + if let Some(actor) = input.thread_store.remove::() { + actor.shutdown().await; + } if let Some(worker) = input.thread_store.remove::() { input.thread_store.remove::(); worker.lifetime.cancellation.cancel(); diff --git a/codex-rs/ext/guardian-v3/src/lib.rs b/codex-rs/ext/guardian-v3/src/lib.rs index bf61d57bab..a53bc8cdeb 100644 --- a/codex-rs/ext/guardian-v3/src/lib.rs +++ b/codex-rs/ext/guardian-v3/src/lib.rs @@ -8,6 +8,10 @@ use codex_message_board::LocalBoardOptions; use codex_protocol::SessionId; use codex_state::SqliteConfig; +mod actor; +mod conversation; +pub use actor::ActorReviewer; +pub use actor::PreparedReviewer; mod cutoff; pub use cutoff::ReviewCutoff; pub use cutoff::RootEvidence; diff --git a/codex-rs/ext/guardian-v3/tests/housekeeping.rs b/codex-rs/ext/guardian-v3/tests/housekeeping.rs index e95f45c3b8..b6334a32dd 100644 --- a/codex-rs/ext/guardian-v3/tests/housekeeping.rs +++ b/codex-rs/ext/guardian-v3/tests/housekeeping.rs @@ -781,3 +781,86 @@ async fn command_token_rotation_between_batches_reauthenticates_the_housekeeper( test.codex.shutdown_and_wait().await?; Ok(()) } + +#[tokio::test] +async fn retains_only_reusable_reviewer_conversations() -> anyhow::Result<()> { + use codex_core::guardian_review::prepare_review_prewarm; + use codex_extension_api::ExtensionData; + use codex_extension_api::ExtensionRegistryBuilder; + use codex_extension_api::ThreadReadyInput; + use codex_extension_api::ThreadStopInput; + use codex_guardian_reviewer::SessionDisposition; + use codex_protocol::protocol::SessionSource; + use codex_protocol::protocol::SubAgentSource; + + core_test_support::skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let test = test_codex() + .with_history_mode(ThreadHistoryMode::Paginated) + .with_config(|config| config.approvals_reviewer = ApprovalsReviewer::User) + .build_with_auto_env(&server) + .await?; + let actor_thread = &test.codex; + let root = actor_thread.startup_metadata().thread_id; + let mut registry = ExtensionRegistryBuilder::default(); + codex_guardian_v3::install( + &mut registry, + Arc::downgrade(&test.thread_manager), + test.config.sqlite_config().clone(), + |root| board_host(root), + ); + let registry = registry.build(); + let session = ExtensionData::new(root.to_string()); + let thread = actor_thread.thread_extension_data(); + let lifecycle = ®istry.thread_lifecycle_contributors()[0]; + let child = ExtensionData::new(codex_protocol::ThreadId::new().to_string()); + lifecycle + .on_thread_ready(ThreadReadyInput { + config: &test.config, + session_source: &SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: root, + depth: 1, + agent_path: None, + agent_nickname: None, + agent_role: None, + }), + history_initialization: codex_history::HistoryInitialization::New, + history_mode: ThreadHistoryMode::Paginated, + session_store: &session, + thread_store: &child, + }) + .await; + assert!(child.get::().is_none()); + lifecycle + .on_thread_ready(ThreadReadyInput { + config: &test.config, + session_source: &SessionSource::Exec, + history_initialization: codex_history::HistoryInitialization::New, + history_mode: ThreadHistoryMode::Paginated, + session_store: &session, + thread_store: thread, + }) + .await; + let actor = thread + .get::() + .expect("reviewer installed"); + let context = prepare_review_prewarm(actor_thread, codex_guardian_v3::BOARD_RETRIEVAL).await?; + let cancel = CancellationToken::new(); + let first = actor.reserve(&context, &cancel).await?; + let id = first.thread_id(); + first.finish(SessionDisposition::Reusable); + let second = actor.reserve(&context, &cancel).await?; + assert_eq!(id, second.thread_id()); + drop(second); + let third = actor.reserve(&context, &cancel).await?; + assert_ne!(id, third.thread_id()); + third.finish(SessionDisposition::Discard); + lifecycle + .on_thread_stop(ThreadStopInput { + thread_store: thread, + session_store: &session, + }) + .await; + test.codex.shutdown_and_wait().await?; + Ok(()) +}