mirror of
https://github.com/openai/codex.git
synced 2026-11-26 23:40:43 +00:00
Use Guardian V3 to assess recorded tool calls (#64157)
## Why `thread/guardianReview` used the transcript reviewer even when the app server was configured to use Guardian V3 for live approvals. Recorded calls can now be assessed with the same reviewer as live calls. ## What changed When Guardian V3 is enabled at app-server startup, `thread/guardianReview` waits for pending injected history to reach the Guardian board, then returns a fresh assessment without executing the tool call or caching an approval. When V3 is disabled at startup, the endpoint uses the transcript reviewer. V3 requires a fresh, idle, non-ephemeral root thread with paginated history and rejects `rootEvidence`. Recorded browser calls receive the same browser policy as live calls. ## Testing Add coverage for sequential history batches without tool execution, unsupported thread types, routing failures and timeouts, and preservation of the initial denial when reconsideration stalls. GitOrigin-RevId: a8ad15cd2bb2d6d5d105c672f64c6cc71dfc6ff8
This commit is contained in:
@@ -278,9 +278,19 @@ instructions, use `thread/fork` followed by `turn/start`.
|
||||
## Recorded Guardian reviews (experimental)
|
||||
|
||||
On an idle thread, `thread/guardianReview` assesses the supplied `toolCall`
|
||||
without appending or executing it. To review an archived worker's action,
|
||||
start a dedicated ephemeral thread and load the worker's history with
|
||||
`thread/inject_items`. Supply the action and parent messages in the review request.
|
||||
without appending or executing it.
|
||||
|
||||
With `features.guardianv3.enabled = true` at app-server startup, use
|
||||
`thread/start` to create a fresh root thread with `ephemeral: false` and
|
||||
`historyMode: "paginated"`. Inject history with `thread/inject_items`, then
|
||||
call `thread/guardianReview` with `threadId` and `toolCall`. V3 waits for
|
||||
pending history to be processed before assessing the call. Wait for the verdict
|
||||
before injecting another batch on the same thread. V3 rejects `rootEvidence`.
|
||||
|
||||
The worker example below uses the transcript reviewer with Guardian V3 disabled
|
||||
at app-server startup. Start a dedicated ephemeral thread and inject the archived
|
||||
worker's history with `thread/inject_items`. Supply the action and parent
|
||||
messages in the review request.
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ use codex_app_server_protocol::ThreadGuardianReviewResponse;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadPrepareApprovedPlanParams;
|
||||
use codex_app_server_protocol::ThreadPrepareApprovedPlanResponse;
|
||||
use codex_core::guardian_review::RecordedReviewMode;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::models::AgentMessageInputContent;
|
||||
@@ -218,12 +219,23 @@ impl TurnRequestProcessor {
|
||||
// Older servers silently ignore rootEvidence. Acknowledge it on success so clients
|
||||
// can distinguish a worker review from one that used only the injected history.
|
||||
let used_root_evidence = params.root_evidence.is_some();
|
||||
// The startup flag installs the reviewer. A thread override cannot change it.
|
||||
let mode = if self.config.features.enabled(Feature::GuardianV3) {
|
||||
if used_root_evidence {
|
||||
return Err(invalid_request(
|
||||
"Guardian V3 recorded review does not support rootEvidence",
|
||||
));
|
||||
}
|
||||
RecordedReviewMode::Attached(Box::pin(codex_guardian_v3::route_pending_history(
|
||||
Arc::clone(&thread),
|
||||
)))
|
||||
} else {
|
||||
RecordedReviewMode::Transcript {
|
||||
root_evidence: params.root_evidence,
|
||||
}
|
||||
};
|
||||
let result = thread
|
||||
.guardian_review_with_root_evidence(
|
||||
¶ms.tool_call,
|
||||
params.root_evidence,
|
||||
cancellation,
|
||||
)
|
||||
.review_recorded_call(¶ms.tool_call, mode, cancellation)
|
||||
.await
|
||||
.map_err(|err| match err.details() {
|
||||
CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()),
|
||||
|
||||
@@ -810,7 +810,13 @@ async fn guardian_review_assesses_allowlisted_calls_and_reuses_private_history_p
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let parent = app.start_thread(ThreadStartParams::default()).await?.thread;
|
||||
let other = app.start_thread(ThreadStartParams::default()).await?.thread;
|
||||
let other = app
|
||||
.start_thread(ThreadStartParams {
|
||||
config: Some([("features.guardianv3.enabled".into(), json!(true))].into()),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
|
||||
let script = r#"for (const path of ["a", "b"]) await tools.exec_command({cmd: "git ls-files " + path});"#;
|
||||
let command = |id: &str| {
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
//! Exercise the native approval route with and without the Guardian board extension.
|
||||
//! Exercise native approvals and recorded reviews with the Guardian board extension.
|
||||
use super::super::mcp_tool::wait_for_mcp_tool_call_completed;
|
||||
use super::sync_sessions::sync_config;
|
||||
use super::*;
|
||||
use app_test_support::create_final_assistant_message_sse_response as assistant_response;
|
||||
use codex_app_server_protocol::GuardianApprovalReviewStatus;
|
||||
use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadGoalSetResponse;
|
||||
use codex_app_server_protocol::ThreadHistoryMode;
|
||||
use codex_app_server_protocol::ThreadInjectItemsParams;
|
||||
use codex_app_server_protocol::ThreadInjectItemsResponse;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_models_manager::model_info::model_info_from_slug;
|
||||
use core_test_support::apps_test_server::AppsTestServer;
|
||||
use core_test_support::context_snapshot;
|
||||
use core_test_support::context_snapshot::ContextSnapshotOptions;
|
||||
use core_test_support::context_snapshot::SnapshotEntry;
|
||||
use core_test_support::streaming_sse::StreamingSseChunk;
|
||||
use core_test_support::streaming_sse::start_streaming_sse_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -16,8 +23,12 @@ use std::sync::atomic::AtomicBool;
|
||||
use test_case::test_case;
|
||||
|
||||
enum ReviewCase {
|
||||
LegacyHistory,
|
||||
ColdResume,
|
||||
V3,
|
||||
V3WithReconsideration,
|
||||
V3RoutingFailure,
|
||||
V3RoutingTimeout,
|
||||
EphemeralV3,
|
||||
Native,
|
||||
}
|
||||
@@ -158,6 +169,36 @@ fn received_user_instruction(request: &responses::ResponsesRequest, text: &str)
|
||||
})
|
||||
}
|
||||
|
||||
fn routing_input(request: &responses::ResponsesRequest) -> Value {
|
||||
let item = request
|
||||
.inputs_of_type("function_call_output")
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|item| item["name"] == "guardian_housekeeper_input")
|
||||
.expect("routing originals");
|
||||
let output = item["output"].as_str().expect("housekeeper input text");
|
||||
serde_json::from_str(output).expect("valid housekeeper input JSON")
|
||||
}
|
||||
|
||||
fn route_release(request: &responses::ResponsesRequest, routing_failure: bool) -> String {
|
||||
let input = routing_input(request);
|
||||
let sources = input["sources"].as_array().expect("housekeeper sources");
|
||||
// A nonempty batch with no destinations is a terminal routing error.
|
||||
release_routes(if routing_failure { 0 } else { sources.len() })
|
||||
}
|
||||
|
||||
fn release_routes(count: usize) -> String {
|
||||
let text = json!({
|
||||
"descriptions": [{"channel": "release", "description": "Release policy"}],
|
||||
"routes": vec![vec!["release"]; count],
|
||||
})
|
||||
.to_string();
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("route", &text),
|
||||
responses::ev_completed("route"),
|
||||
])
|
||||
}
|
||||
|
||||
#[test_case(ReviewCase::V3, None; "v3_follows_subscribed_revocation_and_reapproval")]
|
||||
#[test_case(ReviewCase::V3, Some(true); "v3_reports_high_probe_without_changing_verdicts")]
|
||||
#[test_case(ReviewCase::V3, Some(false); "v3_reports_low_probe_without_changing_verdicts")]
|
||||
@@ -456,6 +497,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
|
||||
"metadata": {"guardian": {"item_id": call_id, "requires_review": requires_review}},
|
||||
}));
|
||||
}
|
||||
let recorded_call = call["item"].clone();
|
||||
events.extend([call, responses::ev_completed(call_id)]);
|
||||
let (_actor, issue_call) = hold_response(&actor_url, responses::sse(events)).await;
|
||||
let id = app
|
||||
@@ -626,9 +668,12 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
|
||||
.contains("If the user explicitly approves a previously rejected action")),
|
||||
followup
|
||||
);
|
||||
assert!(developer.iter().any(|text| {
|
||||
text.contains("Browser connector (`connector_openai_browser` on `codex_apps`)")
|
||||
}));
|
||||
let browser_policy = developer
|
||||
.iter()
|
||||
.find(|text| {
|
||||
text.contains("Browser connector (`connector_openai_browser` on `codex_apps`)")
|
||||
})
|
||||
.expect("live browser policy");
|
||||
assert!(body["input"].to_string().contains("release-action"));
|
||||
if uses_board {
|
||||
let review_event = wait_for_matching_analytics_event(&server, TIMEOUT, |event| {
|
||||
@@ -676,6 +721,36 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
|
||||
&& parts.iter().any(|text| text.contains("release-action")))
|
||||
);
|
||||
}
|
||||
if empty_board && !reconsider && probe.is_none() {
|
||||
let replay = app
|
||||
.start_thread(ThreadStartParams {
|
||||
history_mode: Some(ThreadHistoryMode::Paginated),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
let instruction = json!({
|
||||
"type": "message", "role": "user",
|
||||
"content": [{"type": "input_text", "text": prompt}],
|
||||
});
|
||||
let id = send_recorded_review(&mut app, &replay.id, vec![instruction], &recorded_call)
|
||||
.await?;
|
||||
let result: Value = app.read_response(id).await?;
|
||||
assert_eq!(result["callId"], call_id);
|
||||
let calls = requests.requests();
|
||||
let recorded = calls[seen_requests..]
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|r| expects_field(r, "outcome"))
|
||||
.expect("recorded browser verdict");
|
||||
assert!(
|
||||
recorded
|
||||
.message_input_texts("developer")
|
||||
.contains(browser_policy),
|
||||
"recorded review must include the live browser policy"
|
||||
);
|
||||
seen_requests = calls.len();
|
||||
}
|
||||
if followup && !late {
|
||||
assert!(
|
||||
received_user_instruction(verdict, prompt),
|
||||
@@ -707,3 +782,435 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
|
||||
app.shutdown_gracefully().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn recorded_command(user: &str, call_id: &str, command: &str) -> [Value; 2] {
|
||||
let mut arguments = json!({
|
||||
"cmd": command,
|
||||
"sandbox_permissions": "require_escalated",
|
||||
"justification": "Write the candidate.",
|
||||
});
|
||||
arguments.sort_all_objects();
|
||||
[
|
||||
json!({
|
||||
"type": "message", "role": "user",
|
||||
"content": [{"type": "input_text", "text": user}],
|
||||
}),
|
||||
json!({
|
||||
"type": "function_call", "name": "exec_command", "call_id": call_id,
|
||||
"arguments": arguments.to_string(),
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
async fn send_recorded_review(
|
||||
app: &mut TestAppServer,
|
||||
thread_id: &str,
|
||||
items: Vec<Value>,
|
||||
tool_call: &Value,
|
||||
) -> Result<i64> {
|
||||
let inject = app
|
||||
.send_thread_inject_items_request(ThreadInjectItemsParams {
|
||||
thread_id: thread_id.to_owned(),
|
||||
items,
|
||||
})
|
||||
.await?;
|
||||
let _: ThreadInjectItemsResponse = app.read_response(inject).await?;
|
||||
app.send_raw_request(
|
||||
"thread/guardianReview",
|
||||
Some(json!({"threadId": thread_id, "toolCall": tool_call})),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[test_case(ReviewCase::V3; "reviews_sequential_batches_without_execution")]
|
||||
#[test_case(ReviewCase::LegacyHistory; "unsupported_history_is_an_error")]
|
||||
#[test_case(ReviewCase::EphemeralV3; "ephemeral_thread_is_an_error")]
|
||||
#[test_case(ReviewCase::ColdResume; "resumed_thread_is_an_error")]
|
||||
#[test_case(ReviewCase::V3RoutingFailure; "routing_failure_is_an_error")]
|
||||
#[test_case(ReviewCase::V3RoutingTimeout; "stalled_routing_times_out")]
|
||||
#[test_case(ReviewCase::V3WithReconsideration; "stalled_reconsideration_preserves_denial")]
|
||||
#[tokio::test]
|
||||
async fn recorded_v3_review(case: ReviewCase) -> Result<()> {
|
||||
const DENIAL: &str = "The user did not approve this write.";
|
||||
let reconsider = matches!(case, ReviewCase::V3WithReconsideration);
|
||||
let resumed = matches!(case, ReviewCase::ColdResume);
|
||||
let legacy = matches!(case, ReviewCase::LegacyHistory);
|
||||
let ephemeral = matches!(case, ReviewCase::EphemeralV3);
|
||||
let routing_failure = matches!(case, ReviewCase::V3RoutingFailure);
|
||||
let routing_timeout = matches!(case, ReviewCase::V3RoutingTimeout);
|
||||
let server = responses::start_mock_server().await;
|
||||
let route = |count| responses::sse_response(release_routes(count));
|
||||
let search = |call_id, response_id| {
|
||||
responses::sse_response(responses::sse(vec![
|
||||
responses::ev_function_call_with_namespace(
|
||||
call_id,
|
||||
"guardian_board",
|
||||
"search_posts",
|
||||
r#"{"channel_name":"release","max_chars_per_post":2048}"#,
|
||||
),
|
||||
responses::ev_completed(response_id),
|
||||
]))
|
||||
};
|
||||
let verdict = |id, text: &str| {
|
||||
responses::sse_response(responses::sse(vec![
|
||||
responses::ev_assistant_message(id, text),
|
||||
responses::ev_completed(id),
|
||||
]))
|
||||
};
|
||||
let requests = if matches!(case, ReviewCase::V3) {
|
||||
let allow = r#"{"outcome":"allow","rationale":"Requested write."}"#;
|
||||
responses::mount_response_sequence(
|
||||
&server,
|
||||
vec![
|
||||
route(1),
|
||||
search("find-release", "search"),
|
||||
verdict("verdict", allow),
|
||||
route(3),
|
||||
search("find-release-followup", "search-followup"),
|
||||
verdict("verdict-followup", allow),
|
||||
],
|
||||
)
|
||||
.await
|
||||
} else if reconsider {
|
||||
let denial = verdict(
|
||||
"verdict",
|
||||
&json!({"outcome":"deny","rationale":DENIAL}).to_string(),
|
||||
);
|
||||
responses::mount_response_sequence(
|
||||
&server,
|
||||
vec![route(1), denial.clone(), denial.set_delay(TIMEOUT)],
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
responses::mount_response_handler(&server, move |request| {
|
||||
let response = responses::sse_response(route_release(&request, routing_failure));
|
||||
if routing_timeout {
|
||||
response.set_delay(TIMEOUT)
|
||||
} else {
|
||||
response
|
||||
}
|
||||
})
|
||||
.await
|
||||
};
|
||||
let home = TempDir::new()?;
|
||||
let mut config =
|
||||
sync_config(&server.uri()).with_extra_config("[features.guardianv3]\nenabled = true");
|
||||
if reconsider {
|
||||
config = config.enable_feature(Feature::GuardianDenialReconsideration);
|
||||
}
|
||||
if reconsider || routing_timeout {
|
||||
config = config.with_root_config("auto_review.timeout_ms = 10000");
|
||||
}
|
||||
config.write(home.path())?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let thread = app
|
||||
.start_thread(ThreadStartParams {
|
||||
ephemeral: Some(ephemeral),
|
||||
history_mode: legacy.then_some(ThreadHistoryMode::Legacy),
|
||||
// Turning off the thread flag must not bypass the server's attached reviewer.
|
||||
config: Some([("features.guardianv3.enabled".into(), json!(false))].into()),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
let user = "Record the release candidate.";
|
||||
let command = "echo release > candidate.txt";
|
||||
let [instruction, first_call] = recorded_command(user, "release-1", command);
|
||||
if resumed {
|
||||
let inject = app
|
||||
.send_thread_inject_items_request(ThreadInjectItemsParams {
|
||||
thread_id: thread.id.clone(),
|
||||
items: vec![json!({
|
||||
"type": "message", "role": "user",
|
||||
"content": [{"type": "input_text", "text": "Do not write files."}],
|
||||
})],
|
||||
})
|
||||
.await?;
|
||||
let _: ThreadInjectItemsResponse = app.read_response(inject).await?;
|
||||
app.shutdown_gracefully().await?;
|
||||
app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let resume = app
|
||||
.send_raw_request("thread/resume", Some(json!({"threadId": thread.id})))
|
||||
.await?;
|
||||
let _: Value = app.read_response(resume).await?;
|
||||
}
|
||||
let review = send_recorded_review(&mut app, &thread.id, vec![instruction], &first_call).await?;
|
||||
if routing_timeout {
|
||||
let error = timeout(
|
||||
TIMEOUT,
|
||||
app.read_stream_until_error_message(RequestId::Integer(review)),
|
||||
)
|
||||
.await??;
|
||||
assert!(
|
||||
error.error.message.contains("request timed out"),
|
||||
"{}",
|
||||
error.error.message
|
||||
);
|
||||
let calls = requests.requests();
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert!(expects_field(&calls[0], "routes"));
|
||||
} else if ephemeral || routing_failure || legacy || resumed {
|
||||
let error = app
|
||||
.read_stream_until_error_message(RequestId::Integer(review))
|
||||
.await?;
|
||||
let calls = requests.requests();
|
||||
if routing_failure {
|
||||
assert!(
|
||||
error
|
||||
.error
|
||||
.message
|
||||
.contains("could not prepare the evidence")
|
||||
);
|
||||
assert!(!calls.is_empty());
|
||||
assert!(calls.iter().all(|call| expects_field(call, "routes")));
|
||||
} else {
|
||||
assert_eq!(error.error.code, -32600);
|
||||
assert_eq!(
|
||||
error.error.message,
|
||||
"Guardian V3 recorded review requires a fresh, non-ephemeral root thread with paginated history"
|
||||
);
|
||||
assert!(calls.is_empty());
|
||||
}
|
||||
if ephemeral {
|
||||
let worker = app
|
||||
.send_raw_request(
|
||||
"thread/guardianReview",
|
||||
Some(json!({
|
||||
"threadId": thread.id,
|
||||
"toolCall": first_call,
|
||||
"rootEvidence": {
|
||||
"messages": [{"role": "user", "text": user}],
|
||||
"missingUserInstructions": false,
|
||||
"missingAssistantContext": false,
|
||||
},
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
let rejected = app
|
||||
.read_stream_until_error_message(RequestId::Integer(worker))
|
||||
.await?;
|
||||
assert_eq!(rejected.error.code, -32600);
|
||||
assert!(
|
||||
rejected
|
||||
.error
|
||||
.message
|
||||
.contains("does not support rootEvidence")
|
||||
);
|
||||
assert!(requests.requests().is_empty());
|
||||
}
|
||||
} else if reconsider {
|
||||
let result: Value = timeout(TIMEOUT, app.read_response(review)).await??;
|
||||
assert_eq!(result["callId"], "release-1");
|
||||
assert_eq!(result["assessment"]["outcome"], "deny");
|
||||
assert_eq!(result["assessment"]["rationale"], DENIAL);
|
||||
assert_eq!(
|
||||
requests
|
||||
.requests()
|
||||
.iter()
|
||||
.filter(|r| expects_field(r, "outcome"))
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
} else {
|
||||
let result: Value = app.read_response(review).await?;
|
||||
assert_eq!(result["callId"], "release-1");
|
||||
assert_eq!(result["assessment"]["outcome"], "allow");
|
||||
let calls = requests.requests();
|
||||
let verdict = calls.last().expect("verdict");
|
||||
let evidence = verdict
|
||||
.function_call_output_text("find-release")
|
||||
.expect("board search");
|
||||
assert!(evidence.contains(user), "{evidence}");
|
||||
|
||||
let next_user = "Update the release candidate.";
|
||||
let next_command = "echo updated > candidate.txt";
|
||||
let [instruction, next_call] = recorded_command(next_user, "release-2", next_command);
|
||||
let output = json!({
|
||||
"type": "function_call_output",
|
||||
"call_id": "release-1",
|
||||
"output": "The recorded write succeeded.",
|
||||
});
|
||||
let review = send_recorded_review(
|
||||
&mut app,
|
||||
&thread.id,
|
||||
vec![first_call, output, instruction],
|
||||
&next_call,
|
||||
)
|
||||
.await?;
|
||||
let result: Value = app.read_response(review).await?;
|
||||
assert_eq!(result["callId"], "release-2");
|
||||
assert_eq!(result["assessment"]["outcome"], "allow");
|
||||
|
||||
let all_calls = requests.requests();
|
||||
let env = app.auto_env()?;
|
||||
let selection = env.selection();
|
||||
let cwd = selection.cwd.inferred_native_path_string();
|
||||
let bodies = all_calls
|
||||
.iter()
|
||||
.map(|call| {
|
||||
normalize_recorded_review_request(call.body_json(), &cwd, &selection.environment_id)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let entries = bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>();
|
||||
insta::assert_snapshot!(
|
||||
"recorded_v3_review_request_history",
|
||||
context_snapshot::format_context_snapshot(
|
||||
"Review two recorded release commands on the same thread without executing either.",
|
||||
&entries,
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
);
|
||||
let [routing, search, followup] = &all_calls[calls.len()..] else {
|
||||
panic!("expected one new routing request followed by a board search and verdict");
|
||||
};
|
||||
assert!(expects_field(routing, "routes"));
|
||||
let routing = routing_input(routing);
|
||||
let sources = routing["sources"].as_array().expect("housekeeper sources");
|
||||
let [recorded_call, recorded_output, instruction] = sources.as_slice() else {
|
||||
panic!("expected only originals from the second batch: {sources:?}");
|
||||
};
|
||||
assert_eq!(recorded_call["original"]["payload"]["call_id"], "release-1");
|
||||
let recorded_output = &recorded_output["original"]["payload"];
|
||||
assert_eq!(recorded_output["type"], "function_call_output");
|
||||
assert_eq!(recorded_output["call_id"], "release-1");
|
||||
assert_eq!(
|
||||
instruction["original"]["payload"]["content"][0]["text"],
|
||||
next_user,
|
||||
);
|
||||
assert!(expects_field(search, "outcome"));
|
||||
assert!(expects_field(followup, "outcome"));
|
||||
let evidence = followup
|
||||
.function_call_output_text("find-release-followup")
|
||||
.expect("followup board search");
|
||||
assert!(evidence.contains(user), "{evidence}");
|
||||
assert!(evidence.contains(next_user), "{evidence}");
|
||||
assert_eq!(
|
||||
followup.body_json()["client_metadata"]["thread_id"]
|
||||
.as_str()
|
||||
.expect("followup reviewer thread"),
|
||||
verdict.body_json()["client_metadata"]["thread_id"]
|
||||
.as_str()
|
||||
.expect("first reviewer thread"),
|
||||
);
|
||||
assert!(
|
||||
followup
|
||||
.message_input_texts("user")
|
||||
.iter()
|
||||
.any(|text| text.contains(next_command))
|
||||
);
|
||||
}
|
||||
let env = app.auto_env()?;
|
||||
let candidate = env.selection().cwd.join("candidate.txt")?;
|
||||
let error = env
|
||||
.environment()
|
||||
.get_filesystem()
|
||||
.read_file(
|
||||
&candidate,
|
||||
ReadFileOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("recorded review must not create candidate.txt");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
|
||||
app.shutdown_gracefully().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Normalize volatile values and sort JSON object keys. Keep evidence order and
|
||||
// contents, including the pending action, in the snapshot.
|
||||
fn normalize_recorded_review_request(
|
||||
mut body: Value,
|
||||
cwd: &str,
|
||||
environment_id: &str,
|
||||
) -> Result<Value> {
|
||||
fn normalize_original(source: &mut Value) {
|
||||
let ordinal = source["id"]["ordinal"].as_u64();
|
||||
if let (Some(ordinal), Some(id)) = (ordinal, source.pointer_mut("/original/payload/id"))
|
||||
&& let Some((kind, suffix)) = id.as_str().and_then(|id| id.split_once('_'))
|
||||
&& uuid::Uuid::parse_str(suffix).is_ok()
|
||||
{
|
||||
*id = json!(format!("{kind}_<SOURCE_{ordinal}>"));
|
||||
}
|
||||
if let Some(create_time) = source
|
||||
.pointer_mut("/original/payload/internal_chat_message_metadata_passthrough/create_time")
|
||||
{
|
||||
*create_time = json!(0);
|
||||
}
|
||||
}
|
||||
|
||||
let environment = format!("environment {environment_id:?}");
|
||||
if let Some(items) = body["input"].as_array_mut() {
|
||||
for item in items {
|
||||
if let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) {
|
||||
for part in content {
|
||||
if let Some(text) = part["text"].as_str() {
|
||||
if let Ok(mut action) = serde_json::from_str::<Value>(text)
|
||||
&& action["tool"] == "exec_command"
|
||||
{
|
||||
if action["cwd"] == cwd {
|
||||
action["cwd"] = json!("<EXECUTOR_CWD>");
|
||||
}
|
||||
if action["environment_id"] == environment_id {
|
||||
action["environment_id"] = json!("<ENVIRONMENT>");
|
||||
}
|
||||
// Keep the shell script and replace the platform-specific argv prefix.
|
||||
if let Some(argv) = action["command"].as_array_mut()
|
||||
&& argv.len() > 1
|
||||
&& let Some(script) = argv.pop()
|
||||
{
|
||||
*argv = vec![json!("<SHELL>"), script];
|
||||
}
|
||||
action.sort_all_objects();
|
||||
part["text"] =
|
||||
json!(format!("{}\n", serde_json::to_string_pretty(&action)?));
|
||||
} else {
|
||||
part["text"] =
|
||||
json!(text.replace(&environment, "environment \"<ENVIRONMENT>\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(output) = item["output"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
if item["name"] == "guardian_housekeeper_input" {
|
||||
let mut routing: Value = serde_json::from_str(output)?;
|
||||
if let Some(sources) = routing["sources"].as_array_mut() {
|
||||
sources.iter_mut().for_each(normalize_original);
|
||||
}
|
||||
routing.sort_all_objects();
|
||||
item["output"] = json!(serde_json::to_string(&routing)?);
|
||||
} else if matches!(
|
||||
item["call_id"].as_str(),
|
||||
Some("find-release" | "find-release-followup")
|
||||
) {
|
||||
let mut search: Value = serde_json::from_str(output)?;
|
||||
if let Some(posts) = search["results"].as_array_mut() {
|
||||
for post in posts {
|
||||
if let Some(created_at) = post.get_mut("created_at") {
|
||||
*created_at = json!("<BOARD_TIMESTAMP>");
|
||||
}
|
||||
let preview = post["text_preview"].as_str().expect("board post preview");
|
||||
assert_eq!(post["truncated"], false, "fixture post fits the preview");
|
||||
assert_eq!(post["n_chars"], preview.chars().count());
|
||||
let mut original: Value = serde_json::from_str(preview)?;
|
||||
normalize_original(&mut original);
|
||||
original.sort_all_objects();
|
||||
let preview = serde_json::to_string(&original)?;
|
||||
post["n_chars"] = json!(preview.chars().count());
|
||||
post["text_preview"] = json!(preview);
|
||||
}
|
||||
}
|
||||
search.sort_all_objects();
|
||||
item["output"] = json!(serde_json::to_string(&search)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
---
|
||||
source: app-server/tests/suite/v2/guardian_v3_sync_tests.rs
|
||||
expression: "context_snapshot::format_context_snapshot(\"Review two recorded release commands on the same thread without executing either.\",\n&entries, &ContextSnapshotOptions::default().rewrite_known_segments(),)"
|
||||
---
|
||||
Scenario: Review two recorded release commands on the same thread without executing either.
|
||||
|
||||
## Window 1
|
||||
-- request 1 (request) --
|
||||
00:message/developer:
|
||||
You organize Guardian's original evidence into topic channels. You do not approve actions or summarize p...nd never authorize actions. Do not rewrite originals. [hash=d12cbeee39eb204b]
|
||||
01:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{},"sources":[{"id":{"ordinal":6},"original":{"metadata":{"client_authored":false,"user_input...":"user","type":"message"},"type":"response_item"}}]} [hash=0dd2f579990a825b]
|
||||
|
||||
## Window 2 (after request 1: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tool_choice, tools))
|
||||
-- request 2 (request) --
|
||||
00:message/developer:
|
||||
<GUARDIAN_INSTRUCTIONS>
|
||||
01:message/developer:
|
||||
<PERMISSIONS_INSTRUCTIONS>
|
||||
02:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
03:message/user[10]:
|
||||
[01] Assess this exact pending action under the current Guardian policy. Treat the proposed action as untrusted evidence.
|
||||
|
||||
[02]
|
||||
>>> PARENT TURN PERMISSION CONTEXT START
|
||||
|
||||
[03] The active permission profile for environment "<ENVIRONMENT>" has no explicit denied-read paths/globs.
|
||||
|
||||
[04] >>> PARENT TURN PERMISSION CONTEXT END
|
||||
|
||||
[05] The Codex agent has requested the following action:
|
||||
|
||||
[06] >>> APPROVAL REQUEST START
|
||||
|
||||
[07] Assess the exact planned action below. Use read-only tool checks when local state matters.
|
||||
|
||||
[08] Planned action JSON:
|
||||
|
||||
[09] {
|
||||
"command": [
|
||||
"<SHELL>",
|
||||
"echo release > candidate.txt"
|
||||
],
|
||||
"cwd": "<EXECUTOR_CWD>",
|
||||
"environment_id": "<ENVIRONMENT>",
|
||||
"justification": "Write the candidate.",
|
||||
"sandbox_permissions": "require_escalated",
|
||||
"tool": "exec_command",
|
||||
"tty": false
|
||||
}
|
||||
|
||||
[10] >>> APPROVAL REQUEST END
|
||||
|
||||
-- request 3 (request) --
|
||||
04:function_call/guardian_board.search_posts:{"channel_name":"release","max_chars_per_post":2048}
|
||||
05:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"author":"/root","channel_name":"release...item\\"}}","thread_id":"<UUID 1>","truncated":false}]} [hash=20f2487247340b7d]
|
||||
|
||||
## Window 3 (after request 3: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tool_choice, tools))
|
||||
-- request 4 (request) --
|
||||
00:message/developer:
|
||||
You organize Guardian's original evidence into topic channels. You do not approve actions or summarize p...nd never authorize actions. Do not rewrite originals. [hash=d12cbeee39eb204b]
|
||||
01:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{},"sources":[{"id":{"ordinal":6},"original":{"metadata":{"client_authored":false,"user_input...":"user","type":"message"},"type":"response_item"}}]} [hash=0dd2f579990a825b]
|
||||
02:message/assistant:
|
||||
{"descriptions":[{"channel":"release","description":"Release policy"}],"routes":[["release"]]}
|
||||
03:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{"release":"Release policy"},"sources":[{"id":{"ordinal":7},"original":{"metadata":{"client_a...":"user","type":"message"},"type":"response_item"}}]} [hash=9d78dce86b0be577]
|
||||
|
||||
## Window 4 (after request 4: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tool_choice, tools))
|
||||
-- request 5 (request) --
|
||||
00:message/developer:
|
||||
<GUARDIAN_INSTRUCTIONS>
|
||||
01:message/developer:
|
||||
<PERMISSIONS_INSTRUCTIONS>
|
||||
02:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
03:message/user[10]:
|
||||
[01] Assess this exact pending action under the current Guardian policy. Treat the proposed action as untrusted evidence.
|
||||
|
||||
[02]
|
||||
>>> PARENT TURN PERMISSION CONTEXT START
|
||||
|
||||
[03] The active permission profile for environment "<ENVIRONMENT>" has no explicit denied-read paths/globs.
|
||||
|
||||
[04] >>> PARENT TURN PERMISSION CONTEXT END
|
||||
|
||||
[05] The Codex agent has requested the following action:
|
||||
|
||||
[06] >>> APPROVAL REQUEST START
|
||||
|
||||
[07] Assess the exact planned action below. Use read-only tool checks when local state matters.
|
||||
|
||||
[08] Planned action JSON:
|
||||
|
||||
[09] {
|
||||
"command": [
|
||||
"<SHELL>",
|
||||
"echo release > candidate.txt"
|
||||
],
|
||||
"cwd": "<EXECUTOR_CWD>",
|
||||
"environment_id": "<ENVIRONMENT>",
|
||||
"justification": "Write the candidate.",
|
||||
"sandbox_permissions": "require_escalated",
|
||||
"tool": "exec_command",
|
||||
"tty": false
|
||||
}
|
||||
|
||||
[10] >>> APPROVAL REQUEST END
|
||||
|
||||
04:function_call/guardian_board.search_posts:{"channel_name":"release","max_chars_per_post":2048}
|
||||
05:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"author":"/root","channel_name":"release...item\\"}}","thread_id":"<UUID 1>","truncated":false}]} [hash=20f2487247340b7d]
|
||||
06:message/assistant:
|
||||
{"outcome":"allow","rationale":"Requested write."}
|
||||
07:message/developer:
|
||||
Use prior reviews as context, not binding precedent. Follow the Workspace Policy. If the user explicitly...y explicitly disallows user overwrites in such cases. [hash=4bb4d33a4360b6b8]
|
||||
08:message/user[10]:
|
||||
[01] Assess this exact pending action under the current Guardian policy. Treat the proposed action as untrusted evidence.
|
||||
|
||||
[02]
|
||||
>>> PARENT TURN PERMISSION CONTEXT START
|
||||
|
||||
[03] The active permission profile for environment "<ENVIRONMENT>" has no explicit denied-read paths/globs.
|
||||
|
||||
[04] >>> PARENT TURN PERMISSION CONTEXT END
|
||||
|
||||
[05] The Codex agent has requested the following action:
|
||||
|
||||
[06] >>> APPROVAL REQUEST START
|
||||
|
||||
[07] Assess the exact planned action below. Use read-only tool checks when local state matters.
|
||||
|
||||
[08] Planned action JSON:
|
||||
|
||||
[09] {
|
||||
"command": [
|
||||
"<SHELL>",
|
||||
"echo updated > candidate.txt"
|
||||
],
|
||||
"cwd": "<EXECUTOR_CWD>",
|
||||
"environment_id": "<ENVIRONMENT>",
|
||||
"justification": "Write the candidate.",
|
||||
"sandbox_permissions": "require_escalated",
|
||||
"tool": "exec_command",
|
||||
"tty": false
|
||||
}
|
||||
|
||||
[10] >>> APPROVAL REQUEST END
|
||||
|
||||
-- request 6 (request) --
|
||||
09:function_call/guardian_board.search_posts:{"channel_name":"release","max_chars_per_post":2048}
|
||||
10:function_call_output:{"has_more":false,"n_returned":4,"next_cursor":null,"results":[{"author":"/root","channel_name":"release...item\\"}}","thread_id":"<UUID 1>","truncated":false}]} [hash=edb9ecc6950ff740]
|
||||
@@ -26,6 +26,7 @@ use codex_exec_server::SelectedCapabilityRootsStatus;
|
||||
use codex_extension_api::ConversationHistorySnapshot;
|
||||
use codex_extension_api::ThreadIdleCause;
|
||||
use codex_features::Feature;
|
||||
use codex_history::HistoryInitialization;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_models_manager::ModelsManagerConfig;
|
||||
use codex_otel::SessionTelemetry;
|
||||
@@ -1227,31 +1228,33 @@ impl CodexThread {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Review the supplied tool call without executing it.
|
||||
pub async fn guardian_review(
|
||||
/// Assess a recorded call using the reviewer selected by the host.
|
||||
pub async fn review_recorded_call(
|
||||
&self,
|
||||
tool_call: &ResponseItem,
|
||||
cancellation: &CancellationToken,
|
||||
) -> CodexResult<crate::guardian_review::GuardianReviewResult> {
|
||||
self.guardian_review_with_root_evidence(
|
||||
tool_call,
|
||||
/*root_evidence*/ None,
|
||||
cancellation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Use the supplied parent evidence only for this review of the injected history.
|
||||
pub async fn guardian_review_with_root_evidence(
|
||||
&self,
|
||||
tool_call: &ResponseItem,
|
||||
root_evidence: Option<codex_app_server_protocol::GuardianRootEvidence>,
|
||||
mode: crate::guardian_review::RecordedReviewMode,
|
||||
cancellation: &CancellationToken,
|
||||
) -> CodexResult<crate::guardian_review::GuardianReviewResult> {
|
||||
if self.session.active_turn.lock().await.is_some() {
|
||||
return Err(CodexErr::InvalidRequest("thread has an active turn".into()));
|
||||
}
|
||||
if root_evidence.is_some()
|
||||
if matches!(
|
||||
mode,
|
||||
crate::guardian_review::RecordedReviewMode::Attached(_)
|
||||
) {
|
||||
// On resume or fork, evidence intake starts at the existing history tail.
|
||||
let (config, initialization, history_mode) = self.session.thread_ready_config().await;
|
||||
if !matches!(initialization, HistoryInitialization::New)
|
||||
|| self.session_source().is_non_root_agent()
|
||||
|| config.ephemeral
|
||||
|| history_mode != ThreadHistoryMode::Paginated
|
||||
{
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"Guardian V3 recorded review requires a fresh, non-ephemeral root thread with paginated history".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if mode.root_evidence().is_some()
|
||||
&& (!self.config().await.ephemeral
|
||||
|| matches!(self.session_source(), SessionSource::SubAgent(_)))
|
||||
{
|
||||
@@ -1260,14 +1263,8 @@ impl CodexThread {
|
||||
));
|
||||
}
|
||||
let history = self.session.clone_history().await;
|
||||
crate::guardian::review_tool_call(
|
||||
&self.session,
|
||||
history,
|
||||
tool_call,
|
||||
root_evidence,
|
||||
cancellation,
|
||||
)
|
||||
.await
|
||||
crate::guardian::review_tool_call(&self.session, history, tool_call, mode, cancellation)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Inject raw Responses items. Plaintext agent-mail batches in a native MAv2
|
||||
|
||||
@@ -3,25 +3,37 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_analytics::GuardianApprovalRequestSource;
|
||||
use codex_app_server_protocol::GuardianRootEvidence;
|
||||
use codex_app_server_protocol::GuardianRootEvidenceMessage;
|
||||
use codex_features::Feature;
|
||||
use codex_guardian_context::GuardianRootMessage;
|
||||
use codex_guardian_reviewer::GuardianAssessment;
|
||||
use codex_guardian_reviewer::GuardianReviewError;
|
||||
use codex_guardian_reviewer::GuardianReviewOutcome;
|
||||
use codex_guardian_reviewer::ReviewDeadline;
|
||||
use codex_guardian_reviewer::ReviewHost;
|
||||
use codex_protocol::approvals::GuardianReviewReason;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
use codex_tools::FunctionCallError;
|
||||
use codex_tools::ToolName;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::ApprovalRequestReasons;
|
||||
use super::GuardianReviewContext;
|
||||
use super::GuardianReviewOptions;
|
||||
use super::from_approval_action;
|
||||
use super::new_guardian_review_id;
|
||||
use super::review::PreparedApproval;
|
||||
use super::review::ReviewInput;
|
||||
use super::runtime::ReviewRuntime;
|
||||
use crate::context_manager::ContextManager;
|
||||
use crate::guardian_review::AttachedReviewer;
|
||||
use crate::guardian_review::GuardianReviewResult;
|
||||
use crate::guardian_review::RecordedReviewMode;
|
||||
use crate::mcp_tool_call;
|
||||
use crate::session::session::Session;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
@@ -43,7 +55,7 @@ pub(crate) async fn review_tool_call(
|
||||
session: &Arc<Session>,
|
||||
history: ContextManager,
|
||||
tool_call: &ResponseItem,
|
||||
root_evidence: Option<GuardianRootEvidence>,
|
||||
mode: RecordedReviewMode,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<GuardianReviewResult> {
|
||||
let is_supported_builtin = match tool_call {
|
||||
@@ -89,7 +101,7 @@ pub(crate) async fn review_tool_call(
|
||||
"direct review does not support replaying request_permissions".into(),
|
||||
));
|
||||
}
|
||||
if let Some(evidence) = &root_evidence
|
||||
if let Some(evidence) = mode.root_evidence()
|
||||
&& !evidence.messages.iter().any(
|
||||
|entry| matches!(entry, GuardianRootEvidenceMessage::User(text) if !text.trim().is_empty()),
|
||||
)
|
||||
@@ -98,7 +110,7 @@ pub(crate) async fn review_tool_call(
|
||||
}
|
||||
let deadline = ReviewDeadline::from_timeout(session.get_config().await.guardian_review_timeout);
|
||||
|
||||
let review = async {
|
||||
let resolve_recorded_call = async |root_evidence: Option<GuardianRootEvidence>| {
|
||||
let turn = session
|
||||
.new_turn_with_default_settings(uuid::Uuid::now_v7().to_string(), Default::default())
|
||||
.await;
|
||||
@@ -253,26 +265,143 @@ pub(crate) async fn review_tool_call(
|
||||
retry: None,
|
||||
},
|
||||
};
|
||||
let assessment = input
|
||||
.assess_isolated(deadline, cancellation)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
GuardianReviewError::Cancelled => CodexErr::TurnAborted,
|
||||
GuardianReviewError::Timeout => CodexErr::RequestTimeout,
|
||||
other => CodexErr::Fatal(format!("Guardian assessment failed: {other:?}")),
|
||||
})?;
|
||||
Ok((invocation.call_id, input))
|
||||
};
|
||||
let review = async {
|
||||
let (call_id, assessment) = match mode {
|
||||
RecordedReviewMode::Transcript { root_evidence } => {
|
||||
before_deadline(deadline, async {
|
||||
let (call_id, input) = resolve_recorded_call(root_evidence).await?;
|
||||
let assessment = input
|
||||
.assess_with_transcript_reviewer(deadline, cancellation)
|
||||
.await
|
||||
.map_err(assessment_error)?;
|
||||
Ok((call_id, assessment))
|
||||
})
|
||||
.await?
|
||||
}
|
||||
RecordedReviewMode::Attached(route_pending_history) => {
|
||||
let (call_id, runtime, prepared) = before_deadline(deadline, async {
|
||||
let (call_id, input) = resolve_recorded_call(/*root_evidence*/ None).await?;
|
||||
let reviewer = session
|
||||
.services
|
||||
.thread_extension_data
|
||||
.get::<Arc<dyn AttachedReviewer>>()
|
||||
.ok_or_else(|| {
|
||||
CodexErr::Fatal("Guardian reviewer is unavailable".into())
|
||||
})?;
|
||||
route_pending_history.await.map_err(|error| {
|
||||
CodexErr::Fatal(format!("Guardian could not prepare the evidence: {error}"))
|
||||
})?;
|
||||
let (runtime, prepared) = prepare_attached_reviewer(
|
||||
input,
|
||||
Arc::clone(reviewer.as_ref()),
|
||||
deadline,
|
||||
cancellation,
|
||||
)
|
||||
.await?;
|
||||
Ok((call_id, runtime, prepared))
|
||||
})
|
||||
.await?;
|
||||
let assessment =
|
||||
assess_with_attached_reviewer(runtime, prepared, deadline, cancellation)
|
||||
.await?;
|
||||
(call_id, assessment)
|
||||
}
|
||||
};
|
||||
Ok(GuardianReviewResult {
|
||||
call_id: invocation.call_id.into(),
|
||||
call_id: call_id.into(),
|
||||
assessment,
|
||||
})
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => Err(CodexErr::TurnAborted),
|
||||
_ = deadline.wait() => Err(CodexErr::RequestTimeout),
|
||||
result = review => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn before_deadline<T>(
|
||||
deadline: ReviewDeadline,
|
||||
work: impl Future<Output = Result<T>>,
|
||||
) -> Result<T> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = deadline.wait() => Err(CodexErr::RequestTimeout),
|
||||
result = work => result,
|
||||
}
|
||||
}
|
||||
|
||||
/// The attached reviewer reads live evidence, so recorded evals use a dedicated
|
||||
/// thread and inject only between reviews.
|
||||
async fn prepare_attached_reviewer(
|
||||
input: ReviewInput,
|
||||
reviewer: Arc<dyn AttachedReviewer>,
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(ReviewRuntime, PreparedApproval)> {
|
||||
let (version, history_reset) = input.session.history_reset().await;
|
||||
if version != input.history.reset_version {
|
||||
return Err(CodexErr::TurnAborted);
|
||||
}
|
||||
let runtime = ReviewRuntime {
|
||||
attached_reviewer: Some(reviewer),
|
||||
session: input.session,
|
||||
history_reset,
|
||||
context: input.context,
|
||||
request: input.request.into(),
|
||||
reasons: input.reasons,
|
||||
options: GuardianReviewOptions {
|
||||
require_guardian: true,
|
||||
require_synchronous_review: true,
|
||||
plugin_attribution_override: None,
|
||||
approval_request_source: GuardianApprovalRequestSource::MainTurn,
|
||||
external_cancel: Some(cancellation.clone()),
|
||||
},
|
||||
};
|
||||
// A failure to prepare evidence is an RPC error, never a denial.
|
||||
let id = new_guardian_review_id();
|
||||
let (prepared, _) = runtime
|
||||
.prepare(&id, GuardianReviewReason::Policy, deadline, cancellation)
|
||||
.await
|
||||
.map_err(|decision| match decision {
|
||||
ReviewDecision::Abort => CodexErr::TurnAborted,
|
||||
ReviewDecision::Denied { rejection } => CodexErr::Fatal(rejection),
|
||||
other => CodexErr::Fatal(format!("Unexpected preparation decision: {other:?}")),
|
||||
})?;
|
||||
Ok((runtime, prepared))
|
||||
}
|
||||
|
||||
/// Assess without publishing or caching approval.
|
||||
async fn assess_with_attached_reviewer(
|
||||
runtime: ReviewRuntime,
|
||||
prepared: PreparedApproval,
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<GuardianAssessment> {
|
||||
// The verdict runner owns the same deadline. Let it drain a stalled
|
||||
// reconsideration and recover the first denial.
|
||||
let (outcome, _, _) = runtime.attempt(&prepared, deadline, cancellation).await;
|
||||
match outcome {
|
||||
GuardianReviewOutcome::Completed(assessment) => Ok(assessment),
|
||||
GuardianReviewOutcome::Error(GuardianReviewError::Session { message, .. }) => {
|
||||
Err(CodexErr::Fatal(message))
|
||||
}
|
||||
GuardianReviewOutcome::Error(error) => Err(assessment_error(error)),
|
||||
GuardianReviewOutcome::CachedApproval => Err(CodexErr::Fatal(
|
||||
"Expected a fresh Guardian assessment".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn assessment_error(error: GuardianReviewError) -> CodexErr {
|
||||
match error {
|
||||
GuardianReviewError::Cancelled => CodexErr::TurnAborted,
|
||||
GuardianReviewError::Timeout => CodexErr::RequestTimeout,
|
||||
other => CodexErr::Fatal(format!("Guardian assessment failed: {other:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn root_messages(evidence: &GuardianRootEvidence) -> Vec<GuardianRootMessage> {
|
||||
let mut messages = vec![GuardianRootMessage::RetainedContextScope];
|
||||
if evidence.missing_user_instructions {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#[path = "review_request.rs"]
|
||||
mod request;
|
||||
pub(super) use request::PreparedApproval;
|
||||
pub(super) use request::ReviewAuthorization;
|
||||
|
||||
use crate::guardian_review::ReviewRetrieval;
|
||||
@@ -227,7 +228,7 @@ impl ReviewInput {
|
||||
/// Assess the recorded call in a Guardian session separate from the actor.
|
||||
/// The parent can reuse that session across calls.
|
||||
/// The caller enforces the deadline and cancellation during setup.
|
||||
pub(super) async fn assess_isolated(
|
||||
pub(super) async fn assess_with_transcript_reviewer(
|
||||
self,
|
||||
deadline: ReviewDeadline,
|
||||
cancellation: &CancellationToken,
|
||||
|
||||
@@ -206,7 +206,7 @@ fn guardian_exec_command_request(id: &str) -> GuardianApprovalRequest {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn isolated_review_returns_assessment_for_prepared_action() -> anyhow::Result<()> {
|
||||
async fn review_returns_assessment_for_prepared_action() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
let assessment = serde_json::json!({
|
||||
@@ -244,12 +244,12 @@ async fn isolated_review_returns_assessment_for_prepared_action() -> anyhow::Res
|
||||
session,
|
||||
};
|
||||
let result = input
|
||||
.assess_isolated(
|
||||
.assess_with_transcript_reviewer(
|
||||
codex_guardian_reviewer::ReviewDeadline::Unlimited,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.expect("isolated assessment");
|
||||
.expect("Guardian assessment");
|
||||
assert_eq!(result, serde_json::from_value(assessment)?);
|
||||
let request = mock.single_request();
|
||||
let rendered = serde_json::to_string(&request.input())?;
|
||||
|
||||
@@ -18,6 +18,24 @@ pub enum ReviewRetrieval {
|
||||
Extension(std::sync::Arc<str>),
|
||||
}
|
||||
|
||||
/// How the host requests review of a single recorded tool call.
|
||||
pub enum RecordedReviewMode {
|
||||
Transcript {
|
||||
root_evidence: Option<codex_app_server_protocol::GuardianRootEvidence>,
|
||||
},
|
||||
/// Route pending history under the recorded review deadline.
|
||||
Attached(codex_extension_api::ExtensionFuture<'static, Result<(), ReviewPreparationError>>),
|
||||
}
|
||||
|
||||
impl RecordedReviewMode {
|
||||
pub(crate) fn root_evidence(&self) -> Option<&codex_app_server_protocol::GuardianRootEvidence> {
|
||||
match self {
|
||||
Self::Transcript { root_evidence } => root_evidence.as_ref(),
|
||||
Self::Attached(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of checking a recorded call without executing it.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct GuardianReviewResult {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::suite::scenarios::guardian_direct_mcp::recorded_mcp_items;
|
||||
use crate::suite::scenarios::guardian_direct_review::assess_with_transcript_reviewer;
|
||||
use crate::suite::scenarios::guardian_direct_review::model_input;
|
||||
use codex_core::context::UserGoalUpdate;
|
||||
use codex_history::RolloutItem;
|
||||
@@ -135,10 +136,7 @@ async fn live_and_recorded_mcp_reviews_use_the_server_owners_denied_paths() -> R
|
||||
let items = recorded_mcp_items(&test.codex, prompt).await?;
|
||||
let tool_call = items.last().expect("recorded call").clone();
|
||||
recorded.thread.inject_response_items(items).await?;
|
||||
recorded
|
||||
.thread
|
||||
.guardian_review(&tool_call, &tokio_util::sync::CancellationToken::new())
|
||||
.await?;
|
||||
assess_with_transcript_reviewer(&recorded.thread, &tool_call).await?;
|
||||
let requests = responses.requests();
|
||||
let [review, _, replay] = requests.as_slice() else {
|
||||
anyhow::bail!("expected live review, parent completion, and recorded review");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Direct MCP review uses the current catalog and policy without dispatching the recorded call.
|
||||
|
||||
use super::guardian_direct_review::assess_with_transcript_reviewer;
|
||||
use super::guardian_direct_review::model_input;
|
||||
use anyhow::Result;
|
||||
use codex_config::types::AppToolApproval;
|
||||
@@ -29,7 +30,6 @@ use core_test_support::wait_for_mcp_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn direct_mcp_review_without_dispatch() -> Result<()> {
|
||||
@@ -102,10 +102,7 @@ async fn direct_mcp_review_without_dispatch() -> Result<()> {
|
||||
wait_for_mcp_server(&direct.thread, "codex_apps").await?;
|
||||
let tool_call = items.last().expect("recorded call").clone();
|
||||
direct.thread.inject_response_items(items).await?;
|
||||
let result = direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?;
|
||||
let result = assess_with_transcript_reviewer(&direct.thread, &tool_call).await?;
|
||||
assert_eq!(
|
||||
result,
|
||||
GuardianReviewResult {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Direct review preserves live action rendering without executing commands or applying patches.
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::config::Constrained;
|
||||
use codex_core::guardian_review::GuardianReviewResult;
|
||||
use codex_core::guardian_review::RecordedReviewMode;
|
||||
use codex_features::Feature;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -30,6 +32,21 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(in crate::suite) async fn assess_with_transcript_reviewer(
|
||||
thread: &CodexThread,
|
||||
tool_call: &ResponseItem,
|
||||
) -> codex_protocol::error::Result<GuardianReviewResult> {
|
||||
thread
|
||||
.review_recorded_call(
|
||||
tool_call,
|
||||
RecordedReviewMode::Transcript {
|
||||
root_evidence: None,
|
||||
},
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn direct_exec_review_matches_live_action_without_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -128,10 +145,7 @@ async fn direct_exec_review_matches_live_action_without_execution() -> Result<()
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let result = direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?;
|
||||
let result = assess_with_transcript_reviewer(&direct.thread, &tool_call).await?;
|
||||
assert_eq!(
|
||||
result,
|
||||
GuardianReviewResult {
|
||||
@@ -149,9 +163,7 @@ async fn direct_exec_review_matches_live_action_without_execution() -> Result<()
|
||||
.thread
|
||||
.inject_response_items(vec![tool_call.clone()])
|
||||
.await?;
|
||||
let error = direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
let error = assess_with_transcript_reviewer(&direct.thread, &tool_call)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
@@ -167,10 +179,7 @@ async fn direct_exec_review_matches_live_action_without_execution() -> Result<()
|
||||
.thread
|
||||
.inject_response_items(vec![tool_call.clone()])
|
||||
.await?;
|
||||
let follow_up = direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?;
|
||||
let follow_up = assess_with_transcript_reviewer(&direct.thread, &tool_call).await?;
|
||||
assert_eq!(follow_up.call_id, "follow-up");
|
||||
assert!(!harness.path_exists("guardian-follow-up.txt").await?);
|
||||
|
||||
@@ -186,9 +195,7 @@ async fn direct_exec_review_matches_live_action_without_execution() -> Result<()
|
||||
"type": "function_call", "name": "exec_command", "call_id": "after-grant",
|
||||
"arguments": r#"{"cmd":"git init guardian-skipped"}"#,
|
||||
}))?;
|
||||
let error = direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
let error = assess_with_transcript_reviewer(&direct.thread, &tool_call)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
@@ -339,10 +346,7 @@ async fn direct_patch_review_matches_live_action_without_writes(
|
||||
let tool_call = items.last().expect("recorded call").clone();
|
||||
direct.thread.inject_response_items(items).await?;
|
||||
assert_eq!(
|
||||
direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?,
|
||||
assess_with_transcript_reviewer(&direct.thread, &tool_call).await?,
|
||||
GuardianReviewResult {
|
||||
call_id: "patch-review".to_owned(),
|
||||
assessment: serde_json::from_value(assessment)?,
|
||||
@@ -470,10 +474,7 @@ async fn direct_permissions_review_matches_live_action() -> Result<()> {
|
||||
let tool_call = items.pop().expect("recorded permission request");
|
||||
direct.thread.inject_response_items(items).await?;
|
||||
assert_eq!(
|
||||
direct
|
||||
.thread
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?,
|
||||
assess_with_transcript_reviewer(&direct.thread, &tool_call).await?,
|
||||
GuardianReviewResult {
|
||||
call_id: "permissions-review".to_owned(),
|
||||
assessment: serde_json::from_value(assessment)?,
|
||||
@@ -575,9 +576,7 @@ async fn direct_permissions_review_returns_assessment_when_policy_disallows_requ
|
||||
"arguments": r#"{"permissions":{"network":{"enabled":true}}}"#,
|
||||
}))?;
|
||||
assert_eq!(
|
||||
test.codex
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?,
|
||||
assess_with_transcript_reviewer(&test.codex, &tool_call).await?,
|
||||
GuardianReviewResult {
|
||||
call_id: "permissions-review".into(),
|
||||
assessment: serde_json::from_value(assessment)?,
|
||||
@@ -665,9 +664,7 @@ prefix_rule(pattern=["git", "init", "guardian-rewritten"], decision="prompt")
|
||||
.inject_response_items(vec![tool_call.clone()])
|
||||
.await?;
|
||||
assert_eq!(
|
||||
test.codex
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
.await?,
|
||||
assess_with_transcript_reviewer(&test.codex, &tool_call).await?,
|
||||
GuardianReviewResult {
|
||||
call_id: "hook-review".to_owned(),
|
||||
assessment: serde_json::from_value(assessment)?,
|
||||
@@ -755,9 +752,7 @@ async fn direct_exec_review_honors_hook_denial_before_policy_skip() -> Result<()
|
||||
"type": "function_call", "call_id": "hook-review", "name": "exec_command",
|
||||
"arguments": r#"{"cmd":"git init guardian-original"}"#,
|
||||
}))?;
|
||||
let error = test
|
||||
.codex
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
let error = assess_with_transcript_reviewer(&test.codex, &tool_call)
|
||||
.await
|
||||
.expect_err("hook must reject the call before policy can skip review");
|
||||
assert!(matches!(
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use super::super::hooks::install_allow_permission_request_hook;
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use super::super::hooks::read_permission_request_hook_inputs;
|
||||
use super::guardian_direct_review::assess_with_transcript_reviewer;
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
@@ -20,7 +21,6 @@ use core_test_support::responses::ev_function_call;
|
||||
use core_test_support::responses::mount_sse_once;
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn managed_checkpoint_requires_fresh_human_decisions() -> Result<()> {
|
||||
@@ -145,9 +145,7 @@ justification = "A person must approve this command."
|
||||
"type": "function_call", "name": "exec_command", "call_id": "direct-review",
|
||||
"arguments": r#"{"cmd":"echo checkpoint-ok","login":false}"#,
|
||||
}))?;
|
||||
let error = test
|
||||
.codex
|
||||
.guardian_review(&tool_call, &CancellationToken::new())
|
||||
let error = assess_with_transcript_reviewer(&test.codex, &tool_call)
|
||||
.await
|
||||
.expect_err("managed checkpoint requires a human");
|
||||
assert!(matches!(
|
||||
|
||||
@@ -143,7 +143,11 @@ impl GuardianApprovalRequest {
|
||||
match self {
|
||||
Self::ExecCommand { .. } | Self::WriteStdin { .. } => GuardianScope::Shell,
|
||||
Self::ApplyPatch { .. } => GuardianScope::FileChanges,
|
||||
Self::McpToolCall { server, .. } => GuardianScope::for_mcp_server(server),
|
||||
Self::McpToolCall {
|
||||
server,
|
||||
connector_id,
|
||||
..
|
||||
} => GuardianScope::for_mcp_connector(server, connector_id.as_deref()),
|
||||
Self::NetworkAccess { .. } => GuardianScope::Network,
|
||||
Self::RequestPermissions { .. } => GuardianScope::Permissions,
|
||||
Self::NativeToolCall { .. } => GuardianScope::NativeTool,
|
||||
|
||||
@@ -8,9 +8,11 @@ use std::sync::PoisonError;
|
||||
use std::sync::Weak;
|
||||
|
||||
use anyhow::Context;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::guardian_review::PreserveReviewWrites;
|
||||
use codex_core::guardian_review::ReviewPreparationError;
|
||||
use codex_core::guardian_review::ReviewRetrieval;
|
||||
use codex_core::guardian_review::ShadowReviewer;
|
||||
use codex_extension_api::ExtensionData;
|
||||
@@ -36,6 +38,7 @@ use codex_protocol::ThreadId;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_state::SqliteConfig;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::ActorReviewer;
|
||||
@@ -159,10 +162,27 @@ struct Host {
|
||||
pub(super) struct RootWorker {
|
||||
pub(super) shadow: bool,
|
||||
pub(super) reader: Arc<dyn AgentMessageBoard>,
|
||||
wake: mpsc::Sender<()>,
|
||||
// Live wakes coalesce. Callers that need to wait supply a reply sender.
|
||||
wake: mpsc::Sender<Option<oneshot::Sender<()>>>,
|
||||
lifetime: ReviewerTasks,
|
||||
}
|
||||
|
||||
/// Wake the root worker and wait for it to route pending history to the board.
|
||||
pub async fn route_pending_history(root: Arc<CodexThread>) -> Result<(), ReviewPreparationError> {
|
||||
use ReviewPreparationError::EvidenceUnavailable;
|
||||
let worker = root
|
||||
.thread_extension_data()
|
||||
.get::<RootWorker>()
|
||||
.ok_or(EvidenceUnavailable)?;
|
||||
let (done, routed) = oneshot::channel();
|
||||
worker
|
||||
.wake
|
||||
.send(Some(done))
|
||||
.await
|
||||
.map_err(|_| EvidenceUnavailable)?;
|
||||
routed.await.map_err(|_| EvidenceUnavailable)
|
||||
}
|
||||
|
||||
impl Host {
|
||||
fn tree_delivery(&self, root: ThreadId) -> Arc<TreeDelivery> {
|
||||
let mut deliveries = self
|
||||
@@ -256,7 +276,7 @@ impl Host {
|
||||
cancellation: tree.stop.child_token(),
|
||||
..Default::default()
|
||||
};
|
||||
let (wake, mut wakes) = mpsc::channel(1);
|
||||
let (wake, mut wakes) = mpsc::channel::<Option<oneshot::Sender<()>>>(1);
|
||||
let initial_position = cursor.position();
|
||||
let delivery = Arc::clone(
|
||||
tree.delivery
|
||||
@@ -267,7 +287,7 @@ impl Host {
|
||||
if saved.position().thread_id == initial_position.thread_id
|
||||
&& saved.position().end_ordinal_exclusive < initial_position.end_ordinal_exclusive
|
||||
{
|
||||
let _ = wake.try_send(());
|
||||
let _ = wake.try_send(None);
|
||||
}
|
||||
let shadow = self.shadow;
|
||||
let manager = self.manager.clone();
|
||||
@@ -277,7 +297,13 @@ impl Host {
|
||||
let work = async {
|
||||
let board = Arc::new(board);
|
||||
let mut housekeeper = None;
|
||||
while let Some(Some(())) = cancellation.run_until_cancelled(wakes.recv()).await {
|
||||
while let Some(Some(done)) = cancellation.run_until_cancelled(wakes.recv()).await {
|
||||
// On failure, dropping the sender wakes the caller with an error.
|
||||
let finish = || {
|
||||
if let Some(done) = done {
|
||||
let _ = done.send(());
|
||||
}
|
||||
};
|
||||
let cursor = delivery.cursor();
|
||||
let read = async {
|
||||
// Shadow reads can catch up on the next wake without
|
||||
@@ -298,6 +324,7 @@ impl Host {
|
||||
tracing::warn!(root_thread_id = %root, %error, "Guardian intake rejected stored evidence");
|
||||
})?;
|
||||
if !snapshot.source_advanced() {
|
||||
finish();
|
||||
continue;
|
||||
}
|
||||
for &source_ordinal in &snapshot.skipped_incomplete_deliveries {
|
||||
@@ -311,6 +338,7 @@ impl Host {
|
||||
}
|
||||
if snapshot.records().is_empty() {
|
||||
delivery.acknowledge(&snapshot, /*count*/ 0)?;
|
||||
finish();
|
||||
continue;
|
||||
}
|
||||
let housekeeper = match &mut housekeeper {
|
||||
@@ -335,6 +363,7 @@ impl Host {
|
||||
};
|
||||
// route_next drains accepted appends before honoring cancellation.
|
||||
while housekeeper.route_next(&snapshot, &cancellation).await? != 0 {}
|
||||
finish();
|
||||
tracing::debug!(
|
||||
name: "guardian_v3.housekeeping_routed",
|
||||
root_thread_id = %root,
|
||||
@@ -494,6 +523,6 @@ impl TurnLifecycleContributor for Host {
|
||||
|
||||
fn wake_worker(thread: &ExtensionData) {
|
||||
if let Some(worker) = thread.get::<RootWorker>() {
|
||||
let _ = worker.wake.try_send(());
|
||||
let _ = worker.wake.try_send(None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ use codex_thread_store::PersistContext;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::mount_sse_once;
|
||||
use core_test_support::responses::received_responses_requests;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::responses::user_message_item;
|
||||
@@ -293,6 +294,14 @@ async fn activity_routes_committed_posts_in_source_order(in_memory: bool) -> any
|
||||
}
|
||||
assert_eq!(queued_originals, [first_original, second_original]);
|
||||
|
||||
// A wake after both batches were published must reply without another model request.
|
||||
let requests_before = received_responses_requests(&server).await.len();
|
||||
tokio::time::timeout(wait, super::route_pending_history(Arc::clone(&test.codex))).await??;
|
||||
assert_eq!(
|
||||
received_responses_requests(&server).await.len(),
|
||||
requests_before
|
||||
);
|
||||
|
||||
// Reject unattributed user-role records without advancing the surviving tree's cursor.
|
||||
let published = inbox.delivery.cursor();
|
||||
test.thread_store
|
||||
|
||||
@@ -22,6 +22,7 @@ mod housekeeper_transport;
|
||||
mod inbox;
|
||||
pub use host::install;
|
||||
pub use host::install_shadow;
|
||||
pub use host::route_pending_history;
|
||||
mod retrieval_tools;
|
||||
mod sampling;
|
||||
mod subscription_tools;
|
||||
|
||||
Reference in New Issue
Block a user