mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Persist verified user answers in Guardian thread context (#42579)
## Why Guardian authorization reviews need host-verified `request_user_input` answers to remain aligned with thread history across compaction, resume, and rollback. ## What changed - Record verified question-and-answer pairs in retained thread context when `GuardianThreadContext` is enabled, and source both local and delegated Guardian review evidence from that context. - Preserve complete answer records within the evidence budget. Mark authorization context incomplete when records are unavailable or oversized, and defer cached fast approvals in that case. - Keep the existing runtime-only answer path for threads that do not enable the thread-owned context. ## Testing - Cover answer retention through compaction and resume, removal after rollback, source-call eviction, oversized answers, delegated review evidence, and legacy behavior. GitOrigin-RevId: 01f6f4541515434a0d00fdde318ff59f2f8bd2eb
This commit is contained in:
1 parent
7a7c188682
commit
1d74c3ba1e
22 files changed
+960
-397
No files matched your search
@@ -1,7 +1,5 @@
|
||||
use crate::codex_thread::GuardianRootMessage;
|
||||
use crate::context::GuardianReviewEvidence;
|
||||
use crate::function_tool::FunctionCallError;
|
||||
use crate::guardian::guardian_truncate_text;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolPayload;
|
||||
@@ -16,6 +14,9 @@ use crate::tools::handlers::request_user_input_spec::request_user_input_unavaila
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_features::Feature;
|
||||
use codex_history::RetainedContextEvent;
|
||||
use codex_history::VerifiedAnswer;
|
||||
use codex_history::VerifiedQuestionAnswer;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::request_user_input::RequestUserInputArgs;
|
||||
use codex_tools::ToolName;
|
||||
@@ -25,9 +26,6 @@ pub struct RequestUserInputHandler {
|
||||
pub available_modes: Vec<ModeKind>,
|
||||
}
|
||||
|
||||
const MAX_GUARDIAN_USER_INPUT_ANSWERS: usize = 8;
|
||||
const MAX_GUARDIAN_USER_INPUT_TOKENS: usize = 900;
|
||||
|
||||
impl ToolExecutor<ToolInvocation> for RequestUserInputHandler {
|
||||
fn tool_name(&self) -> ToolName {
|
||||
ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME)
|
||||
@@ -101,45 +99,56 @@ impl RequestUserInputHandler {
|
||||
"failed to serialize {REQUEST_USER_INPUT_TOOL_NAME} response: {err}"
|
||||
))
|
||||
})?;
|
||||
let user_input = questions
|
||||
.iter()
|
||||
.filter_map(|question| {
|
||||
let response = response.answers.get(&question.id)?;
|
||||
let answers = response
|
||||
.answers
|
||||
.iter()
|
||||
.filter(|answer| !answer.trim().is_empty())
|
||||
.take(MAX_GUARDIAN_USER_INPUT_ANSWERS)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
if answers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut question_text = question.question.clone();
|
||||
for option in question
|
||||
.options
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|option| response.answers.contains(&option.label))
|
||||
.take(MAX_GUARDIAN_USER_INPUT_ANSWERS)
|
||||
{
|
||||
question_text.push_str(&format!("\n{}: {}", option.label, option.description));
|
||||
}
|
||||
Some(format!(
|
||||
"{}{}",
|
||||
GuardianRootMessage::Assistant(question_text).render(),
|
||||
GuardianRootMessage::User(answers.join("\n")).render()
|
||||
))
|
||||
})
|
||||
.take(MAX_GUARDIAN_USER_INPUT_ANSWERS)
|
||||
.collect::<String>();
|
||||
if !user_input.is_empty() && turn.config.features.enabled(Feature::GuardianApproval) {
|
||||
let fragment = guardian_truncate_text(&user_input, MAX_GUARDIAN_USER_INPUT_TOKENS).0;
|
||||
if turn.config.features.enabled(Feature::GuardianApproval) {
|
||||
session
|
||||
.services
|
||||
.thread_extension_data
|
||||
.get_or_init(GuardianReviewEvidence::default)
|
||||
.record_user_input(&call_id, fragment);
|
||||
.record_user_input(&call_id, &questions, &response);
|
||||
}
|
||||
// Capture and consumption use the same fixed thread feature setting. Legacy
|
||||
// threads must not construct retained answers, persist them, or advance their revision.
|
||||
if turn.config.features.enabled(Feature::GuardianApproval)
|
||||
&& session.enabled(Feature::GuardianThreadContext)
|
||||
{
|
||||
let user_input = questions
|
||||
.iter()
|
||||
.filter_map(|question| {
|
||||
let response = response.answers.get(&question.id)?;
|
||||
let answers = response
|
||||
.answers
|
||||
.iter()
|
||||
.filter(|answer| !answer.trim().is_empty())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
if answers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut question_text = question.question.clone();
|
||||
for option in question
|
||||
.options
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|option| response.answers.contains(&option.label))
|
||||
{
|
||||
question_text
|
||||
.push_str(&format!("\n{}: {}", option.label, option.description));
|
||||
}
|
||||
Some(VerifiedQuestionAnswer {
|
||||
question: question_text,
|
||||
answer: answers.join("\n"),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !user_input.is_empty() {
|
||||
session
|
||||
.record_retained_context(RetainedContextEvent::VerifiedAnswer(VerifiedAnswer {
|
||||
turn_id: turn.sub_id.clone(),
|
||||
call_id,
|
||||
questions: user_input,
|
||||
}))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(boxed_tool_output(FunctionToolOutput::from_text(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::*;
|
||||
use crate::GuardianAuthorizationVersion;
|
||||
use crate::session::step_context::StepContext;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
use crate::session::tests::make_session_and_context_with_auth_and_config_and_rx;
|
||||
use crate::session::tests::make_session_and_context_with_rx;
|
||||
use crate::session::tests::update_selected_settings_for_test;
|
||||
use crate::session::tests::update_turn_settings_for_test;
|
||||
@@ -8,14 +10,13 @@ use crate::state::ActiveTurn;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::turn_diff_tracker::TurnDiffTracker;
|
||||
use codex_guardian_context::RenderedVerifiedAnswers;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::request_user_input::RequestUserInputAnswer;
|
||||
use codex_protocol::request_user_input::RequestUserInputResponse;
|
||||
use codex_utils_output_truncation::approx_token_count;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
@@ -81,146 +82,167 @@ async fn multi_agent_v2_request_user_input_rejects_subagent_threads() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case(None; "empty")]
|
||||
#[test_case(Some(("other_question", "A".to_owned())); "unrequested question")]
|
||||
#[test_case(Some(("pick_one", " ".to_owned())); "blank answer")]
|
||||
#[test_case(Some(("pick_one", "A".to_owned())); "genuine answer")]
|
||||
#[test_case(Some(("pick_one", "x\n".repeat(900))); "multiline answer remains bounded")]
|
||||
#[test_case(None, RenderedVerifiedAnswers { fragments: vec![], complete: true }; "empty")]
|
||||
#[test_case(Some(("other_question", "A".to_owned())), RenderedVerifiedAnswers { fragments: vec![], complete: true }; "unrequested question")]
|
||||
#[test_case(Some(("pick_one", " ".to_owned())), RenderedVerifiedAnswers { fragments: vec![], complete: true }; "blank answer")]
|
||||
#[test_case(Some(("pick_one", "A".to_owned())), RenderedVerifiedAnswers {
|
||||
fragments: vec!["assistant: Pick one\nassistant: A: A\nuser: A\n".to_owned()],
|
||||
complete: true,
|
||||
}; "genuine answer")]
|
||||
#[test_case(Some(("pick_one", "A\nB".to_owned())), RenderedVerifiedAnswers {
|
||||
fragments: vec!["assistant: Pick one\nuser: A\nuser: B\n".to_owned()],
|
||||
complete: true,
|
||||
}; "short multiline answer")]
|
||||
#[test_case(Some(("pick_one", "x\n".repeat(/*n*/ 900))), RenderedVerifiedAnswers {
|
||||
fragments: vec!["Host notice: some verified user answers are unavailable within the evidence budget. Do not treat the remaining answers as complete authorization for an action.\n".to_owned()],
|
||||
complete: false,
|
||||
}; "oversized multiline answer")]
|
||||
#[tokio::test]
|
||||
async fn request_user_input_sets_non_blocking_outside_plan_mode(answer: Option<(&str, String)>) {
|
||||
let (session, turn, events) = make_session_and_context_with_rx().await;
|
||||
*session.active_turn.lock().await = Some(ActiveTurn::default());
|
||||
|
||||
let request = tokio::spawn({
|
||||
let session = Arc::clone(&session);
|
||||
let turn = Arc::clone(&turn);
|
||||
async move {
|
||||
RequestUserInputHandler {
|
||||
available_modes: vec![ModeKind::Default],
|
||||
}
|
||||
.handle(ToolInvocation {
|
||||
session,
|
||||
step_context: StepContext::for_test(Arc::clone(&turn)),
|
||||
turn,
|
||||
cancellation_token: tokio_util::sync::CancellationToken::new(),
|
||||
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
|
||||
call_id: "call-1".to_string(),
|
||||
tool_name: codex_tools::ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME),
|
||||
source: crate::tools::context::ToolCallSource::Direct,
|
||||
payload: ToolPayload::Function {
|
||||
arguments: json!({
|
||||
"questions": [{
|
||||
"header": "Hdr",
|
||||
"question": "Pick one",
|
||||
"id": "pick_one",
|
||||
"options": [
|
||||
{
|
||||
"label": "A",
|
||||
"description": "A"
|
||||
},
|
||||
{
|
||||
"label": "B",
|
||||
"description": "B"
|
||||
}
|
||||
]
|
||||
}]
|
||||
})
|
||||
.to_string(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
|
||||
let event = events.recv().await.expect("request_user_input event");
|
||||
let EventMsg::RequestUserInput(request_event) = event.msg else {
|
||||
panic!("expected request_user_input event");
|
||||
};
|
||||
assert_eq!(request_event.call_id, "call-1");
|
||||
assert!(!request_event.is_blocking);
|
||||
|
||||
session
|
||||
.notify_user_input_response(
|
||||
&request_event.turn_id,
|
||||
RequestUserInputResponse {
|
||||
answers: answer
|
||||
.iter()
|
||||
.map(|(question_id, answer)| {
|
||||
(
|
||||
(*question_id).to_owned(),
|
||||
RequestUserInputAnswer {
|
||||
answers: vec![answer.clone()],
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
async fn request_user_input_sets_non_blocking_outside_plan_mode(
|
||||
answer: Option<(&str, String)>,
|
||||
expected: RenderedVerifiedAnswers,
|
||||
) {
|
||||
for thread_context_enabled in [false, true] {
|
||||
let (session, turn, events) = make_session_and_context_with_auth_and_config_and_rx(
|
||||
codex_login::CodexAuth::from_api_key("Test API Key"),
|
||||
Vec::new(),
|
||||
|config| {
|
||||
config
|
||||
.features
|
||||
.set_enabled(Feature::GuardianThreadContext, thread_context_enabled)
|
||||
.expect("test context mode");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let output = request
|
||||
.await
|
||||
.expect("request_user_input handler task should finish")
|
||||
.expect("request_user_input handler should succeed");
|
||||
assert!(output.success_for_logging());
|
||||
let recorded_answer = session
|
||||
.services
|
||||
.thread_extension_data
|
||||
.get::<GuardianReviewEvidence>()
|
||||
.and_then(|evidence| evidence.user_input_for_call("call-1"));
|
||||
if let Some(("pick_one", answer)) = answer {
|
||||
if answer.contains('\n') {
|
||||
let fragment = recorded_answer.expect("genuine multiline answer should be recorded");
|
||||
assert!(approx_token_count(&fragment) <= MAX_GUARDIAN_USER_INPUT_TOKENS);
|
||||
assert!(fragment.contains("<truncated omitted_approx_tokens="));
|
||||
} else if !answer.trim().is_empty() {
|
||||
assert_eq!(
|
||||
recorded_answer,
|
||||
Some("assistant: Pick one\nassistant: A: A\nuser: A\n".to_owned())
|
||||
);
|
||||
} else {
|
||||
assert_eq!(recorded_answer, None);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(recorded_answer, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_user_input_evidence_is_bounded() {
|
||||
let (session, turn, _) = make_session_and_context_with_rx().await;
|
||||
let evidence = GuardianReviewEvidence::default();
|
||||
for index in 0..10 {
|
||||
let call_id = format!("call-{index}");
|
||||
session
|
||||
.record_conversation_items(
|
||||
turn.as_ref(),
|
||||
&[ResponseItem::FunctionCall {
|
||||
id: None,
|
||||
name: REQUEST_USER_INPUT_TOOL_NAME.to_owned(),
|
||||
namespace: None,
|
||||
arguments: "{}".to_owned(),
|
||||
call_id: call_id.clone(),
|
||||
encrypted_function_args: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
.services
|
||||
.thread_extension_data
|
||||
.insert(GuardianReviewEvidence::from_features(
|
||||
session.features().get(),
|
||||
));
|
||||
let original_history = session.conversation_history_snapshot().await;
|
||||
*session.active_turn.lock().await = Some(ActiveTurn::default());
|
||||
|
||||
let request = tokio::spawn({
|
||||
let session = Arc::clone(&session);
|
||||
let turn = Arc::clone(&turn);
|
||||
async move {
|
||||
RequestUserInputHandler {
|
||||
available_modes: vec![ModeKind::Default],
|
||||
}
|
||||
.handle(ToolInvocation {
|
||||
session,
|
||||
step_context: StepContext::for_test(Arc::clone(&turn)),
|
||||
turn,
|
||||
cancellation_token: tokio_util::sync::CancellationToken::new(),
|
||||
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
|
||||
call_id: "call-1".to_string(),
|
||||
tool_name: codex_tools::ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME),
|
||||
source: crate::tools::context::ToolCallSource::Direct,
|
||||
payload: ToolPayload::Function {
|
||||
arguments: json!({
|
||||
"questions": [{
|
||||
"header": "Hdr",
|
||||
"question": "Pick one",
|
||||
"id": "pick_one",
|
||||
"options": [
|
||||
{
|
||||
"label": "A",
|
||||
"description": "A"
|
||||
},
|
||||
{
|
||||
"label": "B",
|
||||
"description": "B"
|
||||
}
|
||||
]
|
||||
}]
|
||||
})
|
||||
.to_string(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
|
||||
let event = events.recv().await.expect("request_user_input event");
|
||||
let EventMsg::RequestUserInput(request_event) = event.msg else {
|
||||
panic!("expected request_user_input event");
|
||||
};
|
||||
assert_eq!(request_event.call_id, "call-1");
|
||||
assert!(!request_event.is_blocking);
|
||||
|
||||
session
|
||||
.notify_user_input_response(
|
||||
&request_event.turn_id,
|
||||
RequestUserInputResponse {
|
||||
answers: answer
|
||||
.iter()
|
||||
.map(|(question_id, answer)| {
|
||||
(
|
||||
(*question_id).to_owned(),
|
||||
RequestUserInputAnswer {
|
||||
answers: vec![answer.clone()],
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
evidence.record_user_input(&call_id, format!("user: answer-{index}\n"));
|
||||
|
||||
let output = request
|
||||
.await
|
||||
.expect("request_user_input handler task should finish")
|
||||
.expect("request_user_input handler should succeed");
|
||||
assert!(output.success_for_logging());
|
||||
let history = session.conversation_history_snapshot().await;
|
||||
let RenderedVerifiedAnswers {
|
||||
fragments,
|
||||
complete,
|
||||
} = codex_guardian_context::render_verified_answers(
|
||||
history.retained_context().expect("host context snapshot"),
|
||||
);
|
||||
if thread_context_enabled {
|
||||
assert_eq!(
|
||||
(&fragments, complete),
|
||||
(&expected.fragments, expected.complete)
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
history.retained_context(),
|
||||
original_history.retained_context()
|
||||
);
|
||||
}
|
||||
let evidence = session
|
||||
.services
|
||||
.thread_extension_data
|
||||
.get_or_init(GuardianReviewEvidence::default);
|
||||
let legacy_answer = evidence.user_input_for_call(history.as_ref(), "call-1");
|
||||
let has_answer = matches!(&answer, Some(("pick_one", answer)) if !answer.trim().is_empty());
|
||||
assert_eq!(
|
||||
evidence.authorization_version(history.as_ref()),
|
||||
GuardianAuthorizationVersion {
|
||||
user_message_revision: original_history.user_message_revision()
|
||||
+ u64::from(thread_context_enabled && has_answer),
|
||||
user_input_response_count: usize::from(!thread_context_enabled && has_answer),
|
||||
retained_context_complete: !thread_context_enabled || expected.complete,
|
||||
},
|
||||
);
|
||||
match &answer {
|
||||
Some(("pick_one", answer)) if !thread_context_enabled && !answer.trim().is_empty() => {
|
||||
let fragment = legacy_answer.expect("legacy answer");
|
||||
assert!(codex_utils_output_truncation::approx_token_count(&fragment) <= 900);
|
||||
assert_eq!(
|
||||
fragment.contains("<truncated omitted_approx_tokens="),
|
||||
!expected.complete,
|
||||
);
|
||||
}
|
||||
_ => assert_eq!(
|
||||
legacy_answer,
|
||||
fragments.first().cloned().filter(|_| complete)
|
||||
),
|
||||
}
|
||||
}
|
||||
let history = session.conversation_history_snapshot().await;
|
||||
assert_eq!(
|
||||
evidence.user_input_fragments(history.as_ref()),
|
||||
(2..10)
|
||||
.map(|index| format!("user: answer-{index}\n"))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
evidence
|
||||
.authorization_version(history.as_ref())
|
||||
.user_input_response_count,
|
||||
10
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in new issue
Block a user