Wire Guardian V3 housekeeping into the app server (#61797)

## What changed

- Install Guardian V3 with a local message-board host when the server enables `features.guardianv3.enabled`, independently of thread overrides.
- Clear inherited user, thread, and project instructions from Guardian V3 private threads and skip repository instruction discovery.

## Testing

Add integration coverage for routing the first live message while the actor is still sampling, for both new and resumed threads. Verify that resumed history is skipped, `AGENTS.md` reaches only the actor, and thread overrides cannot enable or disable server-level housekeeping.

GitOrigin-RevId: 3f3ae1be404c9e17b73eea12c95f5a95c96052cf
This commit is contained in:
felixxia-oai
2026-11-16 12:03:11 +00:00
committed by copyberry
parent cd18053706
commit 9544f09e7b
6 changed files with 178 additions and 5 deletions
@@ -124,6 +124,17 @@ pub async fn delete_agent_message_boards(
})
}
/// Host membership and clock for a local board in this existing agent tree.
pub fn local_board_host(manager: Weak<ThreadManager>, root: ThreadId) -> Arc<dyn MessageBoardHost> {
Arc::new(LocalBoardHost {
manager,
tree: root.into(),
caller: root,
remote_notifications: false,
connection: None,
})
}
#[derive(Clone)]
struct LocalBoardHost {
manager: Weak<ThreadManager>,
+11
View File
@@ -104,6 +104,17 @@ pub(crate) fn thread_extensions(
git_attribution_base_url,
http_client_factory,
);
if config.features.enabled(codex_features::Feature::GuardianV3) {
let board_manager = thread_manager.clone();
codex_guardian_v3::install(
&mut builder,
thread_manager.clone(),
config.sqlite_config().clone(),
move |root| {
codex_agent_message_board_host::local_board_host(board_manager.clone(), root)
},
);
}
codex_guardian_v2::install(&mut builder, auth_manager.clone(), thread_manager);
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_mcp_extension::install(&mut builder);
@@ -807,3 +807,132 @@ async fn guardian_review_reuses_private_recorded_call_history_per_parent() -> Re
app.shutdown_gracefully().await?;
Ok(())
}
#[test_case(None; "new_root")]
#[test_case(Some("This instruction predates the resume."); "resumed_root")]
#[tokio::test]
async fn v3_routes_the_first_live_message_while_the_actor_is_still_sampling(
prior_message: Option<&str>,
) -> Result<()> {
skip_if_no_network!(Ok(()));
// Neither model can finish a turn or issue a tool call before both requests arrive.
let (first, first_gate) = oneshot::channel();
let (second, second_gate) = oneshot::channel();
let response = assistant_response(
r#"{"routes":[["release"]],"descriptions":{"release":"Release policy"}}"#,
)?;
let (server, _) = start_streaming_sse_server(
[first_gate, second_gate]
.into_iter()
.map(|gate| {
vec![StreamingSseChunk {
gate: Some(gate),
body: response.clone(),
}]
})
.collect(),
)
.await;
let home = TempDir::new()?;
sync_config(server.uri())
.with_extra_config("[features.guardianv3]\nenabled = true")
.write(home.path())?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.build_initialized_with_timeout(TIMEOUT)
.await?;
let project_rule = "Write release notes in French.";
let env = app.auto_env()?;
env.environment()
.get_filesystem()
.write_file(
&env.selection().cwd.join("AGENTS.md")?,
project_rule.as_bytes().to_vec(),
Default::default(),
/*sandbox*/ None,
)
.await?;
let thread = if let Some(prior_message) = prior_message {
let thread_id = app_test_support::create_fake_paginated_rollout(
home.path(),
"2025-01-01T00-01-00",
"2025-01-01T00:01:00Z",
prior_message,
Some("mock_provider"),
/*git_info*/ None,
)?;
let resumed: ThreadResumeResponse = app
.request(|request_id| ClientRequest::ThreadResume {
request_id,
params: ThreadResumeParams {
thread_id,
// A thread override cannot disable the server's housekeeper.
config: Some([("features.guardianv3.enabled".into(), json!(false))].into()),
exclude_turns: true,
..Default::default()
},
})
.await?;
resumed.thread
} else {
app.start_thread(ThreadStartParams {
history_mode: Some(codex_app_server_protocol::ThreadHistoryMode::Paginated),
..Default::default()
})
.await?
.thread
};
let instruction = "Hold the release until Friday.";
let environment = app.auto_env_params()?;
let _: TurnStartResponse = app
.request(|request_id| ClientRequest::TurnStart {
request_id,
params: TurnStartParams {
thread_id: thread.id,
environments: Some(vec![environment]),
input: vec![UserInput::Text {
text: instruction.to_owned(),
text_elements: vec![],
}],
..Default::default()
},
})
.await?;
timeout(TIMEOUT, server.wait_for_request_count(/*count*/ 2)).await?;
let requests = server.requests().await;
let mut routed = false;
for request in requests {
let body: Value = serde_json::from_slice(&request)?;
let items = body["input"].as_array().expect("request input");
let routing_input = items
.iter()
.find(|item| item["name"] == "guardian_housekeeper_input");
let has_project_rule = items.iter().any(|item| {
item["type"] == "message" && item["content"].to_string().contains(project_rule)
});
assert_eq!(
has_project_rule,
routing_input.is_none(),
"only the actor receives AGENTS.md"
);
if let Some(input) = routing_input {
let output = input["output"].as_str().expect("housekeeper input text");
routed = output.contains(instruction);
if let Some(prior_message) = prior_message {
assert!(
!output.contains(prior_message),
"resume must skip existing history"
);
}
}
}
assert!(
routed,
"the background request must include the first original"
);
let _ = first.send(());
let _ = second.send(());
app.shutdown_gracefully().await?;
server.shutdown().await;
Ok(())
}
@@ -383,15 +383,20 @@ async fn thread_delete_removes_persisted_boards_even_with_agent_feature_disabled
MockResponsesConfig::new(&server.uri())
.enable_feature(Feature::AgentMessageBoard)
.enable_feature(Feature::MultiAgentV2)
.with_extra_config(&format!(
"[features.guardianv3]\nenabled = {guardian_v3_enabled}"
))
.with_extra_config("[features.guardianv3]\nenabled = false")
.write(home.path())?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.build_initialized()
.await?;
let thread = app.start_thread(ThreadStartParams::default()).await?.thread;
let thread = app
.start_thread(ThreadStartParams {
history_mode: Some(codex_app_server_protocol::ThreadHistoryMode::Paginated),
config: Some([("features.guardianv3.enabled".into(), json!(true))].into()),
..Default::default()
})
.await?
.thread;
let completed = app
.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.id.clone(),
@@ -413,6 +418,13 @@ async fn thread_delete_removes_persisted_boards_even_with_agent_feature_disabled
.await?;
assert_eq!(board_counts(&pool).await?, (1, 1, 2));
let guardian_options = guardian_board_options();
// A thread override cannot create a Guardian board on a server with GV3 disabled.
assert!(
!sqlite
.home()
.join("message_board_guardian_1.sqlite")
.exists()
);
let retained_id = create_delete_test_rollout(home.path(), /*minute*/ 1, "Keep me")?;
for owner in [&thread.id, &retained_id] {
configure_local_board(
@@ -75,6 +75,14 @@ impl PreparedGuardianContext {
}
impl PreparedGuardianContext {
/// Start with no parent user, thread or project instructions and skip repository discovery.
pub fn without_parent_instructions(mut self) -> Self {
self.key.user_instructions = None;
self.key.thread_instructions = None;
self.key.project_instructions = Some(Arc::default());
self
}
pub fn reuse_key(
&self,
previous: Option<&GuardianReviewSession>,
@@ -27,7 +27,9 @@ impl PrivateThread {
owner: &ReviewerTasks,
instructions: &str,
) -> anyhow::Result<Self> {
let prepared = prepare_review_prewarm(parent).await?;
let prepared = prepare_review_prewarm(parent)
.await?
.without_parent_instructions();
let key = prepared.reuse_key(/*previous*/ None);
let (mut options, state) = prepared
.thread_options(GuardianReviewSessionKind::TrunkNew, /*snapshot*/ None)