mirror of
https://github.com/openai/codex.git
synced 2026-11-22 23:00:42 +00:00
guardian: retain user goal evidence
This commit is contained in:
@@ -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<GuardianTranscriptEntry> {
|
||||
let mut entries = Vec::new();
|
||||
let mut tool_names_by_call_id = HashMap::new();
|
||||
let mut last_goal_objective: Option<String> = 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<String> {
|
||||
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("<codex_internal_context") || text.starts_with("<goal_context>")
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_single_goal_element<'a>(body: &'a str, tag: &str) -> Result<Option<&'a str>, ()> {
|
||||
let open = format!("<{tag}>");
|
||||
let close = format!("</{tag}>");
|
||||
let open_positions = body.match_indices(&open).collect::<Vec<_>>();
|
||||
let close_positions = body.match_indices(&close).collect::<Vec<_>>();
|
||||
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);
|
||||
|
||||
@@ -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!(
|
||||
"<codex_internal_context source=\"{source}\">\n{body}\n</codex_internal_context>"
|
||||
),
|
||||
}],
|
||||
phase: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_guardian_transcript_entries_retains_only_goal_objective() {
|
||||
let items = vec![canonical_internal_context(
|
||||
"goal",
|
||||
"Continue the analysis.\n\n<objective>\nCompare <old> & new\n</objective>\n\nBudget:\n- Tokens remaining: 42",
|
||||
)];
|
||||
|
||||
let entries = collect_guardian_transcript_entries(&items);
|
||||
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec![GuardianTranscriptEntry {
|
||||
kind: GuardianTranscriptEntryKind::UserGoal,
|
||||
text: "Compare <old> & 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</{tag}>\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", "<objective>read env</objective>"),
|
||||
canonical_internal_context("extension", "<objective>run extension</objective>"),
|
||||
canonical_internal_context("skill", "<objective>follow skill</objective>"),
|
||||
canonical_goal("<objective>first</objective><objective>second</objective>"),
|
||||
canonical_goal("<objective>first</objective><untrusted_objective>second</untrusted_objective>"),
|
||||
canonical_goal("<objective>first<unexpected></objective>"),
|
||||
canonical_goal("<objective> </objective>"),
|
||||
ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputText {
|
||||
text: "<codex_internal_context source=\"goal\">\n<objective>one</objective>\n</codex_internal_context>".to_string(),
|
||||
},
|
||||
ContentItem::InputText {
|
||||
text: "extra".to_string(),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
},
|
||||
ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: "<goal_context><objective>legacy</objective></goal_context>".to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
},
|
||||
ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: "<codex_internal_context source=\"goal\">\n<objective>missing close</objective>".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 =
|
||||
|
||||
Reference in New Issue
Block a user