From 7ada4c9702e9738dae10cf61560fff8d5b5e1621 Mon Sep 17 00:00:00 2001 From: fchen Date: Thu, 11 Jun 2026 17:23:52 -0700 Subject: [PATCH] guardian: retain user goal evidence --- codex-rs/core/src/guardian/prompt.rs | 78 +++++++++++++++- codex-rs/core/src/guardian/tests.rs | 128 +++++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/guardian/prompt.rs b/codex-rs/core/src/guardian/prompt.rs index 008e979574..62132148f7 100644 --- a/codex-rs/core/src/guardian/prompt.rs +++ b/codex-rs/core/src/guardian/prompt.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; +use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::GuardianRiskLevel; use codex_protocol::protocol::GuardianUserAuthorization; @@ -8,6 +9,7 @@ use serde::Deserialize; use serde_json::Value; use crate::compact::content_items_to_text; +use crate::context::InternalModelContextFragment; use crate::event_mapping::is_contextual_user_message_content; use crate::session::session::Session; use crate::session::turn_context::TurnContext; @@ -37,6 +39,7 @@ pub(crate) struct GuardianTranscriptEntry { pub(crate) enum GuardianTranscriptEntryKind { Developer, User, + UserGoal, Assistant, Tool(String), } @@ -46,13 +49,14 @@ impl GuardianTranscriptEntryKind { match self { Self::Developer => "developer", Self::User => "user", + Self::UserGoal => "user-provided goal", Self::Assistant => "assistant", Self::Tool(role) => role.as_str(), } } fn is_user(&self) -> bool { - matches!(self, Self::User) + matches!(self, Self::User | Self::UserGoal) } fn is_tool(&self) -> bool { @@ -420,6 +424,7 @@ pub(crate) fn collect_guardian_transcript_entries( ) -> Vec { let mut entries = Vec::new(); let mut tool_names_by_call_id = HashMap::new(); + let mut last_goal_objective: Option = None; let non_empty_entry = |kind, text: String| { (!text.trim().is_empty()).then_some(GuardianTranscriptEntry { kind, text }) }; @@ -431,7 +436,17 @@ pub(crate) fn collect_guardian_transcript_entries( for item in items { let entry = match item { ResponseItem::Message { role, content, .. } if role == "user" => { - if is_contextual_user_message_content(content) { + if let Some(objective) = guardian_goal_objective(content) + && last_goal_objective.as_deref() != Some(objective.as_str()) + { + last_goal_objective = Some(objective.clone()); + Some(GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::UserGoal, + text: objective, + }) + } else if is_contextual_user_message_content(content) + || is_internal_context_candidate(content) + { None } else { content_entry(GuardianTranscriptEntryKind::User, content) @@ -513,6 +528,65 @@ pub(crate) fn collect_guardian_transcript_entries( entries } +fn guardian_goal_objective(content: &[ContentItem]) -> Option { + let text = single_text_content(content)?; + let context = InternalModelContextFragment::parse_canonical(text)?; + if context.source().as_str() != "goal" { + return None; + } + + let objective = extract_single_goal_element(context.body(), "objective").ok()?; + let untrusted_objective = + extract_single_goal_element(context.body(), "untrusted_objective").ok()?; + let encoded = match (objective, untrusted_objective) { + (Some(objective), None) | (None, Some(objective)) => objective.trim(), + _ => return None, + }; + if encoded.is_empty() || encoded.contains('<') || encoded.contains('>') { + return None; + } + + Some(decode_goal_xml_text(encoded)) +} + +fn single_text_content(content: &[ContentItem]) -> Option<&str> { + match content { + [ContentItem::InputText { text }] | [ContentItem::OutputText { text }] => Some(text), + _ => None, + } +} + +fn is_internal_context_candidate(content: &[ContentItem]) -> bool { + single_text_content(content).is_some_and(|text| { + let text = text.trim_start(); + text.starts_with("") + }) +} + +fn extract_single_goal_element<'a>(body: &'a str, tag: &str) -> Result, ()> { + let open = format!("<{tag}>"); + let close = format!(""); + let open_positions = body.match_indices(&open).collect::>(); + let close_positions = body.match_indices(&close).collect::>(); + match (open_positions.as_slice(), close_positions.as_slice()) { + ([], []) => Ok(None), + ([(open_index, _)], [(close_index, _)]) => { + let content_start = open_index + open.len(); + if *close_index < content_start { + return Err(()); + } + Ok(body.get(content_start..*close_index)) + } + _ => Err(()), + } +} + +fn decode_goal_xml_text(text: &str) -> String { + text.replace("<", "<") + .replace(">", ">") + .replace("&", "&") +} + pub(crate) fn guardian_truncate_text(content: &str, token_cap: usize) -> (String, bool) { if content.is_empty() { return (String::new(), false); diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index 1698ea0c68..1156e3263a 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -711,6 +711,134 @@ fn collect_guardian_transcript_entries_skips_contextual_user_messages() { ); } +fn canonical_internal_context(source: &str, body: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: format!( + "\n{body}\n" + ), + }], + phase: None, + } +} + +#[test] +fn collect_guardian_transcript_entries_retains_only_goal_objective() { + let items = vec![canonical_internal_context( + "goal", + "Continue the analysis.\n\n\nCompare <old> & new\n\n\nBudget:\n- Tokens remaining: 42", + )]; + + let entries = collect_guardian_transcript_entries(&items); + + assert_eq!( + entries, + vec![GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::UserGoal, + text: "Compare & new".to_string(), + }] + ); +} + +#[test] +fn collect_guardian_transcript_entries_retains_goal_edits_and_consecutive_dedupes() { + let goal = |tag: &str, objective: &str| { + canonical_internal_context( + "goal", + &format!("Goal context\n<{tag}>\n{objective}\n\nBudget: hidden"), + ) + }; + let items = vec![ + goal("objective", "audit the indexes"), + goal("objective", "audit the indexes"), + goal("untrusted_objective", "repair the indexes"), + goal("objective", "audit the indexes"), + ]; + + let entries = collect_guardian_transcript_entries(&items); + + assert_eq!( + entries, + vec![ + GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::UserGoal, + text: "audit the indexes".to_string(), + }, + GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::UserGoal, + text: "repair the indexes".to_string(), + }, + GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::UserGoal, + text: "audit the indexes".to_string(), + }, + ] + ); +} + +#[test] +fn collect_guardian_transcript_entries_rejects_non_goal_and_malformed_context() { + let canonical_goal = |body: &str| canonical_internal_context("goal", body); + let items = vec![ + canonical_internal_context("env", "read env"), + canonical_internal_context("extension", "run extension"), + canonical_internal_context("skill", "follow skill"), + canonical_goal("firstsecond"), + canonical_goal("firstsecond"), + canonical_goal("first"), + canonical_goal(" "), + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ + ContentItem::InputText { + text: "\none\n".to_string(), + }, + ContentItem::InputText { + text: "extra".to_string(), + }, + ], + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "legacy".to_string(), + }], + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "\nmissing close".to_string(), + }], + phase: None, + }, + ]; + + assert!(collect_guardian_transcript_entries(&items).is_empty()); +} + +#[test] +fn guardian_goal_entry_renders_as_user_provided_goal_evidence() { + let entries = vec![GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::UserGoal, + text: "review the retention policy".to_string(), + }]; + + let (rendered, omission) = render_guardian_transcript_entries(&entries); + + assert_eq!( + rendered, + vec!["[1] user-provided goal: review the retention policy"] + ); + assert_eq!(omission, None); +} + #[test] fn collect_guardian_transcript_entries_keeps_manual_approval_developer_message() { let approval_text =