Preserve complete actions in Guardian approval reviews (#44569)

## Why

Truncating action arguments can leave approval reviewers evaluating incomplete actions. Large actions need complete review input and explicit handling when they exceed the review budget.

## What changed

- Remove action truncation and the fixed synchronous action byte limit. Admit complete actions against the whole-request budget, splitting long text losslessly into bounded transport parts and accounting for their framing.
- Route actions exceeding the asynchronous action budget to synchronous review. Prevent cached scores from covering oversized calls, including expanded approval arguments, while allowing later small actions to recover score reuse.
- Request user approval when optional review exhausts its local input budget. Keep required review and compaction service failures closed to approval, and retire exhausted review sessions.

## Testing

Add coverage for complete large-action delivery, optional user fallback, required-review denial, subsequent review recovery, async overflow through MCP approval routing, and lossless text splitting with budget accounting.

GitOrigin-RevId: 08f06e68a94b2f779480dd6b6cf5bc30b241f6dd
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-10 16:01:02 +00:00
1 parent 3319d9b296
commit 9c4879f3a5
33 files changed
+841 -547

No files matched your search

+3 -3
View File
@@ -1,6 +1,6 @@
//! Planned-action prompt framing shared by the two production reviewers.
//! Hosts retain their action serialization and truncation policies; this module
//! only renders already-bounded JSON and reasons, preserving content-item boundaries.
//! Hosts serialize complete actions; whole-request admission bounds the input.
//! This module frames JSON and reasons before composition splits long text for transport.
use crate::ContextSection;
use crate::SectionContributor;
@@ -8,7 +8,7 @@ use crate::SectionError;
use crate::SectionInput;
use crate::SectionScope;
/// Host-prepared action evidence. JSON and optional reason must already be bounded.
/// Host-prepared action evidence. JSON stays complete through request admission.
#[derive(Clone, PartialEq)]
pub struct PlannedAction {
pub json: String,
+15 -1
View File
@@ -168,7 +168,21 @@ pub fn estimate_input_tokens(item: &ResponseItem) -> usize {
}
pub(super) fn content_tokens(item: &ContentItem) -> usize {
let bytes = ByteCount::measure(|counter| serde_json::to_writer(counter, item));
let mut bytes = ByteCount::measure(|counter| serde_json::to_writer(counter, item));
if let ContentItem::InputText { text } = item {
let extra_parts = crate::composition::bounded_text_parts(text)
.count()
.saturating_sub(1);
let framing = ByteCount::measure(|counter| {
serde_json::to_writer(
counter,
&ContentItem::InputText {
text: String::new(),
},
)
});
bytes = bytes.saturating_add(extra_parts.saturating_mul(framing.saturating_add(1)));
}
adjusted_tokens(bytes, std::slice::from_ref(item))
}
+35 -5
View File
@@ -2,10 +2,12 @@
//! Profiles retain the host-selected transcript slice; composition owns
//! framing, message boundaries and section placement, without retaining history.
//! Each content item keeps its selection policy until transport conversion.
//! Long text splits losslessly only after admission, preserving whole-entry selection.
use codex_context_fragments::ContextualUserFragment;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::TruncationPolicy;
use codex_protocol::user_input::UserInput;
use crate::ActionPresentation;
@@ -272,10 +274,13 @@ impl ComposedContext {
};
for item in content {
inputs.push(match item.content {
ContentItem::InputText { text } => UserInput::Text {
text,
text_elements: Vec::new(),
},
ContentItem::InputText { text } => {
inputs.extend(bounded_text_parts(&text).map(|part| UserInput::Text {
text: part.to_owned(),
text_elements: Vec::new(),
}));
continue;
}
ContentItem::InputImage { image_url, detail } => {
UserInput::Image { image_url, detail }
}
@@ -297,7 +302,18 @@ impl ComposedContext {
for section in self.sections {
match section.delivery {
SectionDelivery::UserContent(content) => {
user_content.extend(content.into_iter().map(|item| item.content))
for item in content {
match item.content {
ContentItem::InputText { text } => {
user_content.extend(bounded_text_parts(&text).map(|part| {
ContentItem::InputText {
text: part.to_owned(),
}
}));
}
content => user_content.push(content),
}
}
}
SectionDelivery::Message(message) => {
if !user_content.is_empty() {
@@ -314,6 +330,20 @@ impl ComposedContext {
}
}
/// Bounds individual text parts without changing source text or entry identity.
/// Budget estimates include the extra wire framing before transport conversion.
pub(super) fn bounded_text_parts(text: &str) -> impl Iterator<Item = &str> {
let mut remaining = Some(text);
std::iter::from_fn(move || {
let text = remaining.take()?;
let end = text.floor_char_boundary(TruncationPolicy::Tokens(9_000).byte_budget());
if end < text.len() {
remaining = Some(&text[end..]);
}
Some(&text[..end])
})
}
pub(super) fn user_message(content: Vec<ContentItem>) -> ResponseItem {
ResponseItem::Message {
id: None,
@@ -54,3 +54,44 @@ fn delivery_preserves_arbitrary_message_boundaries_and_rejects_them_for_sync() {
})
);
}
#[test]
fn long_text_delivery_is_lossless_bounded_and_fully_budgeted() {
let text = "é🙂\"\n".repeat(/*n*/ 20_000);
let context = ComposedContext {
sections: vec![SectionOutput {
id: "planned_action",
delivery: text_content(vec![text.clone()]),
}],
truncations: Vec::new(),
};
let estimated = context.estimated_tokens();
let messages = context.clone().into_messages();
let ResponseItem::Message { content, .. } = &messages[0] else {
panic!("user message")
};
let parts = content
.iter()
.map(|item| match item {
ContentItem::InputText { text } => text.as_str(),
_ => panic!("text part"),
})
.collect::<Vec<_>>();
assert_eq!(parts.concat(), text);
assert!(
parts
.iter()
.all(|part| part.len() <= TruncationPolicy::Tokens(9_000).byte_budget())
);
assert!(estimated >= crate::estimate_input_tokens(&messages[0]));
assert_eq!(
context.into_user_inputs().unwrap(),
parts
.into_iter()
.map(|part| UserInput::Text {
text: part.to_owned(),
text_elements: Vec::new(),
})
.collect::<Vec<_>>()
);
}