Preserve Guardian authorization evidence until request budgeting (#44570)

## Why

Transcript limits could shorten user instructions or omit later messages before Guardian evaluated the complete request budget, losing restrictions or prior approvals even when they would fit.

## What changed

- Keep user messages and manual approvals complete and in source order through transcript collection and retention.
- Preserve historical instructions while synchronous review can still compact history. If the final request still cannot fit, discard optional evidence before shortening older historical entries with truncation markers, preserving later restrictions where possible.
- Warn that shortened instructions and approvals are incomplete and that missing evidence does not authorize actions.
- Let asynchronous review defer to synchronous review when complete instructions exceed its budget.

## Testing

Add coverage for complete instruction retention, approval and restriction ordering, marked truncation of oversized Unicode text, compaction before truncation, and asynchronous fallback when instructions do not fit.

GitOrigin-RevId: e6159e876231347986b937ee7e07f944b83bfbe6
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-10 16:02:36 +00:00
1 parent 9c4879f3a5
commit 287e4f7dbf
21 files changed
+575 -335

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@ pub enum ContextPresentation<'a> {
Async,
}
/// Host-selected, already bounded transcript entries and omission notice.
/// Host-selected transcript entries and omission notice, before request admission.
pub struct RenderedTranscript {
pub items: Vec<Budgeted<String>>,
pub omission_note: Option<String>,
+81 -5
View File
@@ -1,11 +1,13 @@
//! Fits newly composed evidence into the remaining complete-request allowance.
//! Required evidence is never truncated. Optional content is removed in a stable
//! order, and a host-owned omission fragment is reserved before any removal.
//! Required action evidence is never truncated. Optional evidence leaves first;
//! hosts may shorten historical instructions after compaction cannot make room.
//! Every reduction reserves an omission notice and preserves source order.
use std::collections::HashSet;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ImageDetail;
use codex_protocol::protocol::TruncationPolicy;
use crate::ComposedContext;
use crate::RequestBudget;
@@ -42,6 +44,13 @@ impl<T> Budgeted<T> {
}
}
pub(crate) fn historical(content: T) -> Self {
Self {
content,
retention: Retention::Historical,
}
}
pub(crate) fn optional(content: T, priority: BudgetPriority) -> Self {
Self {
content,
@@ -62,9 +71,19 @@ impl<T> std::fmt::Debug for Budgeted<T> {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Retention {
Required,
Historical,
Optional(BudgetPriority),
}
/// Whether the host has reached the final attempt to fit historical evidence.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HistoryTruncation {
/// Preserve original instructions while the host can still compact history.
Preserve,
/// Shorten older historical entries only after optional evidence is exhausted.
Allow,
}
impl ComposedContext {
/// Applies host image admission before aggregate selection, preserving section
/// identity and each retained item's selection policy.
@@ -77,12 +96,13 @@ impl ComposedContext {
}
}
/// Returns complete evidence that fits, or no context at all. The host owns
/// the bounded omission fragment and the existing reviewer history/checkpoint.
/// Fits evidence according to the host recovery phase, or returns no context.
/// The host owns the bounded omission fragment and existing reviewer history.
pub fn enforce_budget(
mut self,
budget: RequestBudget,
omission_notice: String,
history_truncation: HistoryTruncation,
) -> Result<Self, SectionError> {
let remaining = budget
.max_input_tokens
@@ -130,6 +150,62 @@ impl ComposedContext {
remaining_items[section_index] = content.len();
}
}
let mut history_truncated = false;
if history_truncation == HistoryTruncation::Allow && required_tokens > remaining {
// Source order makes older evidence yield first. Keep each source's
// label, both ends and the standard marker; later restrictions stay
// complete whenever older entries can supply the needed space.
'history: for section in &mut self.sections {
let SectionDelivery::UserContent(content) = &mut section.delivery else {
continue;
};
for item in content {
if item.retention != Retention::Historical {
continue;
}
let original_tokens = content_tokens(&item.content);
let ContentItem::InputText { text } = &mut item.content else {
continue;
};
let target = original_tokens.saturating_sub(required_tokens - remaining);
let mut upper = TruncationPolicy::Bytes(text.len()).token_budget();
let mut lower = 32.min(upper);
let mut shortened = crate::truncate_text(text, lower);
while lower < upper {
let mid = lower + (upper - lower).div_ceil(2);
let candidate = crate::truncate_text(text, mid);
if content_tokens(&ContentItem::InputText {
text: candidate.clone(),
}) <= target
{
lower = mid;
shortened = candidate;
} else {
upper = mid - 1;
}
}
let saved =
original_tokens.saturating_sub(content_tokens(&ContentItem::InputText {
text: shortened.clone(),
}));
if saved == 0 {
continue;
}
self.truncations.push(TruncationObservation {
component: section.id,
original_bytes: text.len(),
retained_bytes: shortened.len(),
});
*text = shortened;
history_truncated = true;
required_tokens = required_tokens.saturating_sub(saved);
needed = needed.saturating_sub(saved);
if required_tokens <= remaining {
break 'history;
}
}
}
}
// Evidence that cannot fit beside the required content and notice must
// leave first, without evicting useful smaller entries on its behalf.
let optional_allowance =
@@ -162,7 +238,7 @@ impl ComposedContext {
}
needed = needed.saturating_sub(remove(section_index, index, tokens));
}
if removed.is_empty() {
if removed.is_empty() && !history_truncated {
return Err(SectionError::EvidenceLimitExceeded {
section: "request_budget",
});
@@ -12,6 +12,86 @@ fn text(value: &str) -> ContentItem {
}
}
#[test]
fn recovery_shortens_older_history_only_after_optional_evidence() {
let older = format!("[1] user: {}original suffix", "é🙂\"\n".repeat(/*n*/ 6_000));
let commentary = text(&"optional commentary ".repeat(/*n*/ 1_000));
let approval = text("[3] developer: user approved this action");
let restriction = text("[4] user: only modify scratch files");
let action = text("complete action");
let notice = SectionOutput {
id: "budget_omission",
delivery: SectionDelivery::UserContent(vec![Budgeted::required(text(
"evidence omitted or shortened",
))]),
};
let context = ComposedContext {
sections: vec![SectionOutput {
id: "conversation_transcript",
delivery: SectionDelivery::UserContent(vec![
Budgeted::historical(text(&older)),
Budgeted::optional(commentary.clone(), BudgetPriority::Commentary),
Budgeted::historical(approval.clone()),
Budgeted::historical(restriction.clone()),
Budgeted::required(action.clone()),
]),
}],
truncations: Vec::new(),
};
for reduction in [0, 4_000] {
let available = context.estimated_tokens() - content_tokens(&commentary)
+ section_tokens(&notice)
- reduction;
let budget = RequestBudget {
max_input_tokens: available + 2_000,
existing_context_tokens: 2_000,
};
if reduction > 0 {
assert!(
context
.clone()
.enforce_budget(
budget,
"evidence omitted or shortened".to_owned(),
HistoryTruncation::Preserve
)
.is_err()
);
}
let selected = context
.clone()
.enforce_budget(
budget,
"evidence omitted or shortened".to_owned(),
HistoryTruncation::Allow,
)
.unwrap();
assert!(selected.estimated_tokens() <= available);
let SectionDelivery::UserContent(content) = &selected.sections[0].delivery else {
panic!("expected user evidence")
};
let ContentItem::InputText { text: retained } = &content[0].content else {
panic!("expected historical text")
};
if reduction == 0 {
assert_eq!(retained, &older);
} else {
assert!(retained.starts_with("[1] user: "));
assert!(retained.ends_with("original suffix"));
assert!(retained.contains("<truncated omitted_approx_tokens="));
}
assert_eq!(
content,
&vec![
Budgeted::historical(text(retained)),
Budgeted::historical(approval.clone()),
Budgeted::historical(restriction.clone()),
Budgeted::required(action.clone()),
]
);
}
}
#[test]
fn planned_action_budget_omits_descriptions_without_changing_arguments() {
let action = crate::PlannedAction {
@@ -46,6 +126,7 @@ fn planned_action_budget_omits_descriptions_without_changing_arguments() {
existing_context_tokens: 0,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
// The sync preamble is also required and remains ahead of the action.
@@ -115,6 +196,7 @@ fn budget_reserves_existing_context_and_preserves_required_messages() {
existing_context_tokens: 2_000,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
assert!(context.estimated_tokens() <= available);
@@ -137,6 +219,7 @@ fn budget_reserves_existing_context_and_preserves_required_messages() {
existing_context_tokens: 0,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
assert_eq!(
@@ -177,6 +260,7 @@ fn image_omission_preserves_text_and_later_eviction_policy() {
existing_context_tokens: 0,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
assert_eq!(
@@ -197,6 +281,7 @@ fn image_omission_preserves_text_and_later_eviction_policy() {
existing_context_tokens: 0,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
assert_eq!(
@@ -210,6 +295,7 @@ fn image_omission_preserves_text_and_later_eviction_policy() {
existing_context_tokens: 0,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
assert_eq!(
@@ -261,6 +347,7 @@ fn image_omission_preserves_text_and_later_eviction_policy() {
existing_context_tokens: 0,
},
"evidence omitted".to_owned(),
HistoryTruncation::Preserve,
)
.unwrap();
assert_eq!(
+3 -3
View File
@@ -1,8 +1,8 @@
//! Structured transcript evidence shared by synchronous and asynchronous Guardian.
//!
//! Entry kinds preserve source attribution for consumer-specific retention and
//! rendering. Text is bounded during collection, with its original size retained
//! for truncation accounting.
//! rendering. User text and manual approvals stay complete for admission; other text is
//! capped during collection, with its original size retained for accounting.
/// Semantic role of one parent-conversation transcript entry.
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -45,7 +45,7 @@ impl ConversationTranscriptEntryKind {
pub struct ConversationTranscriptEntry {
/// Semantic role used for consumer-specific retention and truncation.
pub kind: ConversationTranscriptEntryKind,
/// Text bounded by the current request's per-entry limits.
/// Complete authorization evidence, or other text bounded by per-entry limits.
pub text: String,
/// Size before truncation, retained for omission and truncation accounting.
pub original_bytes: usize,
+1 -4
View File
@@ -29,9 +29,6 @@ pub use section::ContextSection;
pub use entry::ConversationTranscriptEntry;
pub use entry::ConversationTranscriptEntryKind;
pub use history::TranscriptHistory;
pub use retention::UserMessageCost;
pub use retention::UserMessageSelection;
pub use retention::select_user_messages;
pub use transcript::ConversationTranscriptConfig;
pub use transcript::ConversationTranscriptOptions;
pub use transcript::MANUAL_APPROVAL_DEVELOPER_PREFIX;
@@ -51,6 +48,7 @@ mod action;
mod enforcement;
pub(crate) use enforcement::BudgetPriority;
pub use enforcement::Budgeted;
pub use enforcement::HistoryTruncation;
pub(crate) use enforcement::Retention;
mod budget;
mod composition;
@@ -92,7 +90,6 @@ pub use reviews::RenderedReviewEvidence;
pub use reviews::ReviewEvidence;
pub use reviews::render_review_evidence;
pub use truncation::TruncationObservation;
mod retention;
mod section;
pub use permissions::PermissionContext;
mod transcript;
+28 -27
View File
@@ -1,6 +1,8 @@
//! Resolved Guardian evidence profiles and pure transcript retention.
//! Sync keeps recent entries; async protects approvals/final answers and evicts
//! in cacheable chunks. Hosts still own history snapshots and delivery cursors.
//! User messages and manual approvals stay complete until whole-request admission.
//! They may be shortened with explicit markers only during budget recovery.
use codex_protocol::protocol::TruncationPolicy;
@@ -16,8 +18,6 @@ use crate::Retention;
use crate::TranscriptEntryLimits;
use crate::TranscriptRetentionConfig;
use crate::TruncationObservation;
use crate::UserMessageCost;
use crate::select_user_messages;
use self::window::TranscriptWindow;
mod window;
@@ -37,6 +37,7 @@ pub struct ContextProfile {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TranscriptEntryKind {
User,
ManualApproval,
ProtectedMessage,
Message,
Tool,
@@ -115,8 +116,10 @@ impl ContextProfile {
.map(|(index, entry)| {
let kind = match &entry.kind {
ConversationTranscriptEntryKind::User => TranscriptEntryKind::User,
ConversationTranscriptEntryKind::Developer
| ConversationTranscriptEntryKind::ProtectedAssistant => {
ConversationTranscriptEntryKind::Developer => {
TranscriptEntryKind::ManualApproval
}
ConversationTranscriptEntryKind::ProtectedAssistant => {
TranscriptEntryKind::ProtectedMessage
}
ConversationTranscriptEntryKind::Assistant
@@ -143,30 +146,27 @@ impl ContextProfile {
}
})
.collect::<Vec<_>>();
let user_messages = entries
.iter()
.enumerate()
.filter_map(|(index, entry)| {
(entry.kind == TranscriptEntryKind::User).then_some(UserMessageCost {
index,
tokens: entry.tokens,
})
})
.collect::<Vec<_>>();
let selection =
select_user_messages(&user_messages, self.retention.max_message_transcript_tokens);
let mut included = vec![false; entries.len()];
for index in selection.indices {
included[index] = true;
let mut authorization_tokens = 0usize;
for (index, entry) in entries.iter().enumerate() {
if matches!(
entry.kind,
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval
) {
included[index] = true;
authorization_tokens = authorization_tokens.saturating_add(entry.tokens);
}
}
match self.target {
ContextTarget::Sync => {
let mut message_tokens = selection.tokens;
let mut message_tokens = authorization_tokens;
let mut tool_tokens = 0usize;
let mut retained_non_user_entries = 0;
for (index, entry) in entries.iter().enumerate().rev() {
if entry.kind == TranscriptEntryKind::User
|| retained_non_user_entries >= self.retention.max_recent_non_user_entries
if matches!(
entry.kind,
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval
) || retained_non_user_entries >= self.retention.max_recent_non_user_entries
{
continue;
}
@@ -189,7 +189,7 @@ impl ContextProfile {
let available = self
.retention
.max_message_transcript_tokens
.saturating_sub(selection.tokens);
.saturating_sub(authorization_tokens);
let mut window = TranscriptWindow::new(&entries, &self.retention, available);
for index in 0..entries.len() {
window.insert(index);
@@ -209,9 +209,9 @@ impl ContextProfile {
.filter_map(|(index, entry)| {
let component = match entry.kind {
TranscriptEntryKind::User => "transcript_user",
TranscriptEntryKind::ProtectedMessage | TranscriptEntryKind::Message => {
"transcript_message"
}
TranscriptEntryKind::ManualApproval
| TranscriptEntryKind::ProtectedMessage
| TranscriptEntryKind::Message => "transcript_message",
TranscriptEntryKind::Tool => "transcript_tool",
};
let retained_bytes = if included[index] {
@@ -228,9 +228,10 @@ impl ContextProfile {
}
if included[index] {
Some(match entry.kind {
TranscriptEntryKind::User | TranscriptEntryKind::ProtectedMessage => {
Budgeted::required(entry.text)
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval => {
Budgeted::historical(entry.text)
}
TranscriptEntryKind::ProtectedMessage => Budgeted::required(entry.text),
TranscriptEntryKind::Message => {
Budgeted::optional(entry.text, BudgetPriority::Commentary)
}
@@ -66,8 +66,10 @@ impl<'a> TranscriptWindow<'a> {
let kind = self.entries[index].kind;
let tokens = self.entries[index].tokens;
if kind == TranscriptEntryKind::User
|| self.max_entries == 0
if matches!(
kind,
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval
) || self.max_entries == 0
|| !self.make_room_for_token_budget(kind, tokens)
|| !self.make_room_for_entry_limit(kind)
{
@@ -91,7 +93,9 @@ impl<'a> TranscriptWindow<'a> {
self.message_token_budget
}
TranscriptEntryKind::Tool => self.tool_token_budget,
TranscriptEntryKind::User => unreachable!("user entries were selected separately"),
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval => {
unreachable!("user entries were selected separately")
}
};
let protected_tokens = if kind == TranscriptEntryKind::Message {
self.protected_messages.tokens
@@ -111,7 +115,9 @@ impl<'a> TranscriptWindow<'a> {
],
TranscriptEntryKind::Message => &[TranscriptEntryKind::Message],
TranscriptEntryKind::Tool => &[TranscriptEntryKind::Tool],
TranscriptEntryKind::User => unreachable!("user entries were selected separately"),
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval => {
unreachable!("user entries were selected separately")
}
};
let entries = self.entries;
@@ -201,7 +207,9 @@ impl<'a> TranscriptWindow<'a> {
.tokens
.saturating_add(self.ordinary_messages.tokens),
TranscriptEntryKind::Tool => self.tools.tokens,
TranscriptEntryKind::User => unreachable!("user entries were selected separately"),
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval => {
unreachable!("user entries were selected separately")
}
};
retained_tokens.saturating_add(tokens) <= token_budget
@@ -212,7 +220,9 @@ impl<'a> TranscriptWindow<'a> {
TranscriptEntryKind::ProtectedMessage => &self.protected_messages,
TranscriptEntryKind::Message => &self.ordinary_messages,
TranscriptEntryKind::Tool => &self.tools,
TranscriptEntryKind::User => unreachable!("user entries were selected separately"),
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval => {
unreachable!("user entries were selected separately")
}
}
}
@@ -221,7 +231,9 @@ impl<'a> TranscriptWindow<'a> {
TranscriptEntryKind::ProtectedMessage => &mut self.protected_messages,
TranscriptEntryKind::Message => &mut self.ordinary_messages,
TranscriptEntryKind::Tool => &mut self.tools,
TranscriptEntryKind::User => unreachable!("user entries were selected separately"),
TranscriptEntryKind::User | TranscriptEntryKind::ManualApproval => {
unreachable!("user entries were selected separately")
}
}
}
}
@@ -8,8 +8,8 @@ fn profiles_preserve_distinct_retention_and_original_numbering() {
let entries = [
(ConversationTranscriptEntryKind::User, "inspect only"),
(
ConversationTranscriptEntryKind::Developer,
"approved action",
ConversationTranscriptEntryKind::ProtectedAssistant,
"proposed action",
),
(ConversationTranscriptEntryKind::Assistant, "working"),
]
@@ -30,7 +30,7 @@ fn profiles_preserve_distinct_retention_and_original_numbering() {
(sync.items, sync.omission_note),
(
vec![
Budgeted::required("[8] user: inspect only".to_owned()),
Budgeted::historical("[8] user: inspect only".to_owned()),
Budgeted::optional(
"[10] assistant: working".to_owned(),
BudgetPriority::Commentary
@@ -43,8 +43,8 @@ fn profiles_preserve_distinct_retention_and_original_numbering() {
(asynchronous.items, asynchronous.omission_note),
(
vec![
Budgeted::required("[1] user: inspect only\n".to_owned()),
Budgeted::required("[2] developer: approved action\n".to_owned())
Budgeted::historical("[1] user: inspect only\n".to_owned()),
Budgeted::required("[2] assistant: proposed action\n".to_owned())
],
None,
),
@@ -1,48 +0,0 @@
//! Shared user-message selection, independent of rendering and non-user eviction.
//!
//! Callers supply costs including their own formatting. The first user message
//! remains an anchor even when it exceeds the budget, preserving existing behavior.
/// Rendered cost and original transcript position of a genuine user message.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UserMessageCost {
pub index: usize,
pub tokens: usize,
}
/// Selected original indices and their total rendered token cost.
#[derive(Debug, Default, Eq, PartialEq)]
pub struct UserMessageSelection {
pub indices: Vec<usize>,
pub tokens: usize,
}
/// Keeps the first and latest user messages, then fills from newest to oldest.
///
/// Supply messages in conversation order with distinct original indices. The
/// returned indices are in selection order; callers render in conversation order.
/// Non-user evidence uses the remaining budget under the caller's own policy.
pub fn select_user_messages(
messages: &[UserMessageCost],
max_message_tokens: usize,
) -> UserMessageSelection {
let Some((first, remaining)) = messages.split_first() else {
return UserMessageSelection::default();
};
let mut selection = UserMessageSelection {
indices: vec![first.index],
tokens: first.tokens,
};
// The latest message is considered first, including when it cannot fit.
for message in remaining.iter().rev() {
if selection.tokens.saturating_add(message.tokens) <= max_message_tokens {
selection.indices.push(message.index);
selection.tokens += message.tokens;
}
}
selection
}
#[cfg(test)]
#[path = "retention_tests.rs"]
mod tests;
@@ -1,48 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn user_selection_preserves_anchors_and_fills_from_newest() {
let messages = [
UserMessageCost {
index: 2,
tokens: 4,
},
UserMessageCost {
index: 5,
tokens: 3,
},
UserMessageCost {
index: 8,
tokens: 6,
},
UserMessageCost {
index: 10,
tokens: 2,
},
];
for (budget, indices, tokens) in [
(0, vec![2], 4),
(4, vec![2], 4),
(6, vec![2, 10], 6),
(9, vec![2, 10, 5], 9),
(12, vec![2, 10, 8], 12),
(15, vec![2, 10, 8, 5], 15),
] {
assert_eq!(
select_user_messages(&messages, budget),
UserMessageSelection { indices, tokens },
);
}
assert_eq!(
select_user_messages(&[], /*max_message_tokens*/ 10),
UserMessageSelection::default(),
);
assert_eq!(
select_user_messages(&messages[..1], /*max_message_tokens*/ 10),
UserMessageSelection {
indices: vec![2],
tokens: 4
},
);
}
+21 -14
View File
@@ -1,7 +1,7 @@
//! Collects bounded conversation evidence before consumer-specific rendering.
//!
//! Both Guardian consumers receive the same role and tool-source attribution,
//! with per-entry caps applied before accumulation. Resolved context profiles
//! with complete user messages and capped non-user entries. Resolved context profiles
//! apply aggregate retention after the host selects its full/delta slice. Tool outputs with a
//! call ID retain their generic label when the call is unavailable. Outputs
//! without a call ID require an explicit name.
@@ -55,7 +55,7 @@ impl Default for ConversationTranscriptOptions {
/// Per-entry caps resolved by the caller for the current review.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranscriptEntryLimits {
/// Cap for user, developer, assistant, and plaintext reasoning entries.
/// Cap for assistant and plaintext reasoning entries; user and manual approvals stay complete.
pub message_tokens: usize,
/// Cap for tool calls and ordinary tool outputs.
pub tool_tokens: usize,
@@ -66,14 +66,15 @@ pub struct TranscriptEntryLimits {
/// Aggregate limits for retaining rendered transcript entries.
///
/// Context profiles apply the sync or async selection rules using these limits.
/// Collection applies per-entry caps before profile retention.
/// User messages and manual approvals survive these soft limits; the complete
/// request budget can shorten them with markers after other recovery is exhausted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranscriptRetentionConfig {
/// Budget for rendered user, developer, assistant, and reasoning entries.
pub max_message_transcript_tokens: usize,
/// Separate budget for rendered tool calls and results.
pub max_tool_transcript_tokens: usize,
/// Maximum retained entries other than user messages.
/// Maximum retained entries other than user messages and manual approvals.
pub max_recent_non_user_entries: usize,
}
@@ -104,7 +105,7 @@ impl SectionContributor for ConversationTranscriptSection {
/// Extracts bounded transcript entries without composing other context sections.
///
/// Entries preserve conversation order and role/tool attribution. Per-entry
/// Entries preserve conversation order and role/tool attribution. Non-user
/// limits apply during collection; context profiles own aggregate retention.
pub fn collect_transcript(
history: &dyn SectionHistory,
@@ -302,22 +303,28 @@ pub fn collect_transcript(
if text.trim().is_empty() {
continue;
}
let token_cap = match &kind {
ConversationTranscriptEntryKind::User
| ConversationTranscriptEntryKind::Developer
| ConversationTranscriptEntryKind::Assistant
let original_bytes = text.len();
let text = match &kind {
ConversationTranscriptEntryKind::User | ConversationTranscriptEntryKind::Developer => {
text
}
ConversationTranscriptEntryKind::Assistant
| ConversationTranscriptEntryKind::ProtectedAssistant
| ConversationTranscriptEntryKind::Reasoning => config.entry_limits.message_tokens,
| ConversationTranscriptEntryKind::Reasoning => {
truncate_text(&text, config.entry_limits.message_tokens)
}
ConversationTranscriptEntryKind::ToolCall(_)
| ConversationTranscriptEntryKind::ToolOutput(_) => config.entry_limits.tool_tokens,
| ConversationTranscriptEntryKind::ToolOutput(_) => {
truncate_text(&text, config.entry_limits.tool_tokens)
}
ConversationTranscriptEntryKind::NodeReplToolOutput(_) => {
config.entry_limits.node_repl_output_tokens
truncate_text(&text, config.entry_limits.node_repl_output_tokens)
}
};
entries.push(ConversationTranscriptEntry {
kind,
text: truncate_text(&text, token_cap),
original_bytes: text.len(),
text,
original_bytes,
});
}
@@ -41,7 +41,10 @@ fn entry(kind: ConversationTranscriptEntryKind, text: &str) -> ConversationTrans
#[test]
fn registered_transcript_preserves_shared_roles_and_node_repl_tool_attribution() {
let approved_action = format!("{MANUAL_APPROVAL_DEVELOPER_PREFIX}\nApproved action: {{}}");
let approved_action = format!(
"{MANUAL_APPROVAL_DEVELOPER_PREFIX}\nApproved action: {}",
"exact action ".repeat(/*n*/ 1_000)
);
let history = vec![
ResponseItem::Message {
id: None,
@@ -340,7 +343,7 @@ fn reused_registry_applies_current_history_sources_and_entry_limits() {
transcript_items(&sections[0]),
vec![ConversationTranscriptEntry {
kind: ConversationTranscriptEntryKind::User,
text: truncate_text(&text, message_tokens),
text: text.clone(),
original_bytes: text.len(),
}]
);
@@ -377,7 +380,7 @@ fn reused_registry_applies_current_history_sources_and_entry_limits() {
.expect("transcript collection should succeed");
let mut expected = vec![ConversationTranscriptEntry {
kind: ConversationTranscriptEntryKind::User,
text: truncate_text(&text, /*max_tokens*/ 60),
text: text.clone(),
original_bytes: text.len(),
}];
if include_tool_calls {