Preserve delivered assistant messages in Guardian retained context (#47585)

## Why

Guardian authorization reviews need the assistant message that prompted a user’s approval, even when a post-tool hook blocks the messaging result or compaction removes the original tool call.

## What changed

Retain confirmed delivered assistant text from tool-output metadata at the original call’s position in thread-owned Guardian context. Recover these messages when restoring checkpoints and respect the call’s inherited-context status.

## Testing

Extend authorization coverage to verify that a delivered message remains in the Guardian root snapshot after a blocked tool result, compaction, and resume, and update checkpoint expectations to preserve assistant/approval ordering.

GitOrigin-RevId: df30ec8a3ef21443210a937ab6db119de8a5fd51
This commit is contained in:
felixxia-oai
2026-09-23 16:16:54 +00:00
committed by copyberry
parent 876ce590e1
commit 7342991f0c
2 changed files with 111 additions and 1 deletions
@@ -11,6 +11,7 @@ use crate::guardian::GUARDIAN_MAX_ROOT_MESSAGE_TOKENS;
use crate::guardian::guardian_truncate_text;
use codex_history::CodexHarnessMetadata;
use codex_history::RetainedContext;
use codex_history::RetainedInputSource;
use codex_history::RetainedUserMessage;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
@@ -24,6 +25,21 @@ pub(super) enum RetainedMessageSource {
impl ContextManager {
pub(crate) fn restore_retained_context(&mut self, checkpoint: Option<&RetainedContext>) {
Arc::make_mut(&mut self.retained_context).restore(checkpoint, &self.items);
if self.guardian_context_mode == GuardianContextMode::ThreadOwned {
let items = Arc::clone(&self.items);
for envelope in items.iter().filter(|envelope| {
envelope
.metadata
.as_ref()
.is_some_and(|metadata| metadata.delivered_assistant_message.is_some())
}) {
self.record_retained_message(
&envelope.item,
envelope.metadata.as_ref(),
RetainedMessageSource::Checkpoint,
);
}
}
if self.retain_inherited_user_messages
&& !self.retained_context.has_inherited_user_messages()
{
@@ -51,6 +67,37 @@ impl ContextManager {
metadata: Option<&CodexHarnessMetadata>,
source: RetainedMessageSource,
) {
if self.guardian_context_mode == GuardianContextMode::ThreadOwned
&& let Some(text) =
metadata.and_then(|metadata| metadata.delivered_assistant_message.as_ref())
&& let ResponseItem::FunctionCallOutput {
call_id: Some(call_id),
..
} = item
{
let Some(call) = self.items.iter().rev().find(|envelope| {
matches!(&envelope.item, ResponseItem::FunctionCall { call_id: id, .. } if id == call_id)
}) else {
return;
};
let source = RetainedInputSource::from(call.metadata.as_ref());
if source == RetainedInputSource::Inherited && !self.retain_inherited_user_messages {
return;
}
// The host captured this bounded text before post-tool hooks. The output
// may be rejected, aborted, or truncated; retain the confirmed text at
// the original call's position, not at its later completion position.
Arc::make_mut(&mut self.retained_context).record_assistant_message(
RetainedUserMessage {
turn_id: call.item.turn_id().unwrap_or_default().to_owned(),
message_id: call.item.id().map(|id| id.as_str().to_owned()),
text: text.clone(),
complete: true,
},
source,
);
return;
}
let is_assistant =
matches!(item, ResponseItem::Message { role, .. } if role == "assistant");
if metadata.is_some_and(|metadata| metadata.compaction_output)
@@ -300,6 +300,13 @@ async fn guardian_subagent_review_preserves_late_root_user_authorization(
.expect("write messaging rewrite hook");
})
.with_config(move |config| {
if block_post_hook {
config.model_provider.name = "Local compaction test provider".to_owned();
config
.features
.disable(Feature::TokenBudget)
.expect("use local compaction");
}
if messaging_case {
trust_discovered_hooks(config);
let servers = json!({(messaging_namespace): {
@@ -976,6 +983,10 @@ async fn guardian_subagent_review_preserves_late_root_user_authorization(
// the inherited instruction first without losing the queued local grant.
(inherited_prefix, MissingCheckpointSource::None, true),
] {
// The blocked-result case uses a real compaction and resume below.
if block_post_hook {
continue;
}
let mut expected = expected_authorization.clone();
let inherited_message_id = retained["user_messages"]
.as_array()
@@ -1101,7 +1112,7 @@ async fn guardian_subagent_review_preserves_late_root_user_authorization(
exchange,
if !question_delivered {
vec![approval]
} else if preserve_acceptance_order {
} else if preserve_acceptance_order || !retained.is_null() {
vec![
GuardianRootMessage::Assistant(root_assistant_reply.clone()),
approval,
@@ -1174,6 +1185,58 @@ async fn guardian_subagent_review_preserves_late_root_user_authorization(
(expected, false),
);
}
if block_post_hook {
let relevant = |messages: Vec<GuardianRootMessage>| {
messages
.into_iter()
.filter(|message| {
!matches!(message,
GuardianRootMessage::Assistant(text) if text != &root_assistant_reply)
})
.collect::<Vec<_>>()
};
let before = relevant(
worker_thread
.guardian_root_snapshot()
.await
.expect("before compaction")
.messages,
);
let compact = mount_sse_once_match(
&server,
move |request: &wiremock::Request| is_root_request(request, root_thread_id),
sse(vec![
ev_assistant_message("compact-root", "Deployment context compacted."),
ev_completed("compact-root-response"),
]),
)
.await;
root.submit(Op::Compact).await?;
wait_for_event(&root, |event| matches!(event, EventMsg::TurnComplete(_))).await;
compact.single_request();
assert!(!root.conversation_history_snapshot().await.items().any(|item| {
matches!(item, ResponseItem::FunctionCall { call_id, .. } if call_id == MESSAGE_CALL_ID)
}));
root.flush_rollout().await?;
let saved = test
.thread_store
.load_latest_model_context(LoadThreadHistoryParams {
thread_id: root_thread_id,
include_archived: false,
})
.await?;
root = super::guardian_checkpoint_migration::resume(&test, &root, saved.items).await?;
assert_eq!(
relevant(
worker_thread
.guardian_root_snapshot()
.await
.expect("after compacted resume")
.messages
),
before
);
}
root.shutdown_and_wait().await?;
}