fix(core): sanitize watchdog fallback inbox text

This commit is contained in:
Friel
2026-04-02 17:16:42 +00:00
parent 63b1bb2a8e
commit 4430c8eb55
4 changed files with 249 additions and 40 deletions
+58 -15
View File
@@ -758,14 +758,18 @@ impl AgentControl {
/// Deliver watchdog wake-up input to an owner thread.
///
/// This intentionally bypasses `agent_use_function_call_inbox` for non-subagent owners.
/// Every watchdog check-in must wake the owner exactly once, and the injected inbox path
/// reliably starts or resumes the owner's next turn while preserving helper identity.
/// A watchdog helper wakes the owner through this path only when the helper produced a real
/// fallback report. Empty/no-report helper completions are ignored so the next scheduled
/// watchdog check-in can try again without leaking helper prompt scaffolding into root.
pub(crate) async fn send_watchdog_wakeup(
&self,
agent_id: ThreadId,
sender_thread_id: ThreadId,
message: String,
) -> CodexResult<String> {
let Some(message) = sanitize_watchdog_wakeup_message(message) else {
return Ok(String::new());
};
let state = self.upgrade()?;
let thread = state.get_thread(agent_id).await?;
let snapshot = thread.config_snapshot().await;
@@ -1112,19 +1116,7 @@ impl AgentControl {
Err(_) => false,
};
if !helper_sent_input {
let fallback_message = match &status {
AgentStatus::Completed(Some(message)) if !message.trim().is_empty() => {
Some(message.clone())
}
AgentStatus::Completed(_) => Some(
"Watchdog check-in completed without calling send_input or returning a final message."
.to_string(),
),
AgentStatus::Errored(message) if !message.trim().is_empty() => {
Some(message.clone())
}
_ => None,
};
let fallback_message = watchdog_fallback_message_from_status(&status);
if let Some(message) = fallback_message {
let _ = control
.send_watchdog_wakeup(owner_thread_id, child_thread_id, message)
@@ -1723,6 +1715,57 @@ fn build_agent_inbox_items(
Ok(items)
}
fn watchdog_fallback_message_from_status(status: &AgentStatus) -> Option<String> {
let message = match status {
AgentStatus::Completed(Some(message)) => message,
AgentStatus::Completed(None)
| AgentStatus::Errored(_)
| AgentStatus::Interrupted
| AgentStatus::Shutdown
| AgentStatus::NotFound
| AgentStatus::PendingInit
| AgentStatus::Running => return None,
};
sanitize_watchdog_wakeup_message(message.clone())
}
fn sanitize_watchdog_wakeup_message(message: String) -> Option<String> {
let Some(stripped_message) = strip_leading_watchdog_prompt_scaffold(&message) else {
let message = message.trim();
return (!message.is_empty()).then(|| message.to_string());
};
let stripped_message = stripped_message.trim();
(!stripped_message.is_empty()).then(|| stripped_message.to_string())
}
fn strip_leading_watchdog_prompt_scaffold(message: &str) -> Option<&str> {
let mut lines = message.split_inclusive('\n').scan(0, |offset, line| {
let line_start = *offset;
*offset += line.len();
Some((line_start, line))
});
let Some((_, first_line)) = lines.find(|(_, line)| !line.trim().is_empty()) else {
return None;
};
if first_line.trim() != "# You are a Subagent" {
return None;
}
for (line_start, line) in lines {
let trimmed_line = line.trim();
if trimmed_line.starts_with("AUTOPLAN_WATCHDOG_REPORT")
|| trimmed_line.starts_with("Watchdog:")
|| trimmed_line.starts_with("Watchdog report:")
{
return Some(message[line_start..].trim().trim_start_matches('\n'));
}
}
Some("")
}
async fn inject_agent_message(
state: &ThreadManagerState,
thread: &Arc<crate::CodexThread>,
+176
View File
@@ -590,6 +590,134 @@ async fn send_agent_message_to_root_thread_injects_response_items_when_enabled()
}
}
#[tokio::test]
async fn send_watchdog_wakeup_strips_helper_prompt_scaffold_from_fallback_message() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let leaked_prompt = "# You are a Subagent\n\n\
Read AGENTS.watchdog.md before responding.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6\n\n\
watchdog charter: keep the root AutoPlan aligned";
let submission_id = harness
.control
.send_watchdog_wakeup(
receiver_thread_id,
sender_thread_id,
leaked_prompt.to_string(),
)
.await
.expect("send_watchdog_wakeup should succeed");
assert!(submission_id.is_empty());
assert_no_injected_agent_inbox_payload(&harness, receiver_thread_id);
}
#[tokio::test]
async fn send_watchdog_wakeup_preserves_benign_marker_mentions_in_regular_fallback_reports() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "Watchdog report: the watchdog charter was refreshed and no action is needed.";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(!submission_id.is_empty());
let payload = injected_agent_inbox_payload(&harness, receiver_thread_id);
assert_eq!(
payload,
AgentInboxPayload::new(sender_thread_id, message.to_string())
);
}
#[tokio::test]
async fn send_watchdog_wakeup_preserves_report_body_after_stripping_helper_scaffold() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "# You are a Subagent\n\n\
Read AGENTS.watchdog.md before responding.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6\n\n\
watchdog charter: keep the root AutoPlan aligned\n\n\
Watchdog report: branch checks are green.";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(!submission_id.is_empty());
let payload = injected_agent_inbox_payload(&harness, receiver_thread_id);
assert_eq!(
payload,
AgentInboxPayload::new(
sender_thread_id,
"Watchdog report: branch checks are green.".to_string()
)
);
}
#[tokio::test]
async fn send_watchdog_wakeup_strips_ordinary_prompt_instructions_before_report_marker() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "# You are a Subagent\n\n\
More importantly, you are a **watchdog check-in agent**.\n\
Keep the root agent unblocked, on-task, and executing real work.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6\n\n\
AUTOPLAN_WATCHDOG_REPORT\n\
required_action: rerun CI\n\
reason: current checks are stale";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(!submission_id.is_empty());
let payload = injected_agent_inbox_payload(&harness, receiver_thread_id);
assert_eq!(payload.sender_thread_id, sender_thread_id);
assert_eq!(
payload.message,
"AUTOPLAN_WATCHDOG_REPORT\n\
required_action: rerun CI\n\
reason: current checks are stale"
);
assert!(!payload.message.contains("# You are a Subagent"));
assert!(
!payload
.message
.contains("More importantly, you are a **watchdog check-in agent**.")
);
assert!(!payload.message.contains("Target agent id:"));
}
#[tokio::test]
async fn send_watchdog_wakeup_emits_nothing_when_scaffold_has_no_report_marker() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "# You are a Subagent\n\n\
More importantly, you are a **watchdog check-in agent**.\n\
Keep the root agent unblocked, on-task, and executing real work.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(submission_id.is_empty());
assert_no_injected_agent_inbox_payload(&harness, receiver_thread_id);
}
#[tokio::test]
async fn send_inter_agent_communication_without_turn_queues_message_without_triggering_turn() {
let harness = AgentControlHarness::new().await;
@@ -2486,3 +2614,51 @@ async fn resume_agent_from_rollout_skips_descendants_when_parent_resume_fails()
.await
.expect("tree shutdown after partial subtree resume should succeed");
}
fn injected_agent_inbox_payload(
harness: &AgentControlHarness,
receiver_thread_id: ThreadId,
) -> AgentInboxPayload {
let captured = harness
.manager
.captured_ops()
.into_iter()
.find(|(thread_id, op)| {
*thread_id == receiver_thread_id && matches!(op, Op::InjectResponseItems { .. })
})
.expect("expected injected agent inbox op");
let Op::InjectResponseItems { items } = captured.1 else {
unreachable!("matched above");
};
let output = items
.iter()
.find_map(|item| match item {
ResponseInputItem::FunctionCallOutput { output, .. } => Some(output),
_ => None,
})
.expect("expected function call output item");
let output_text = output
.body
.to_text()
.expect("payload should convert to text");
serde_json::from_str(&output_text).expect("payload should be valid json")
}
fn assert_no_injected_agent_inbox_payload(
harness: &AgentControlHarness,
receiver_thread_id: ThreadId,
) {
assert!(
harness
.manager
.captured_ops()
.into_iter()
.all(|(thread_id, op)| {
thread_id != receiver_thread_id || !matches!(op, Op::InjectResponseItems { .. })
}),
"expected no injected watchdog inbox op"
);
}
+14 -24
View File
@@ -243,37 +243,27 @@ impl WatchdogManager {
.await
.map(|thread| thread.last_completed_turn_used_agent_send_input())
.unwrap_or(false);
// Every watchdog check-in must wake the owner thread exactly once.
// A watchdog helper should wake the owner through `send_input` or a
// final assistant report. If neither exists, emit nothing here and
// let the next scheduled check-in try again.
//
// Preferred path: the helper explicitly calls `send_input`.
// Mandatory fallback: if the helper reaches a terminal state without
// using `send_input`, forward a conclusory inbox message to the
// owner so the owner thread is still resumed.
// Fallback: if the helper reaches a terminal state without using
// `send_input`, forward only a real final assistant message. If
// there is no report body, emit nothing and schedule the next
// helper normally.
if !helper_sent_input {
let fallback_message = match &helper_status {
AgentStatus::Completed(Some(message)) if !message.trim().is_empty() => {
Some(message.clone())
}
AgentStatus::Completed(_) => Some(
"Watchdog check-in completed without calling send_input or returning a final message."
.to_string(),
),
AgentStatus::Errored(message) if !message.trim().is_empty() => Some(
format!("Watchdog check-in failed before calling send_input: {message}"),
),
AgentStatus::Errored(_) => Some(
"Watchdog check-in failed before calling send_input.".to_string(),
),
AgentStatus::Interrupted => {
Some("Watchdog check-in was interrupted before calling send_input.".to_string())
}
AgentStatus::Shutdown => {
Some("Watchdog check-in ended before calling send_input.".to_string())
}
AgentStatus::NotFound => Some(
"Watchdog check-in disappeared before calling send_input.".to_string(),
),
AgentStatus::PendingInit | AgentStatus::Running => None,
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Interrupted
| AgentStatus::Shutdown
| AgentStatus::NotFound
| AgentStatus::PendingInit
| AgentStatus::Running => None,
};
if let Some(message) = fallback_message {
@@ -45,7 +45,7 @@ impl ToolHandler for Handler {
.await
{
return Err(FunctionCallError::RespondToModel(format!(
"wait_agent is not available to watchdog check-in agents. This thread is a one-shot watchdog check-in for owner {owner_thread_id}. Send the result to the parent/root agent with `send_input`. If you finish without `send_input`, runtime will forward your conclusory message to the owner as the mandatory fallback wake-up path. Exiting without either `send_input` or a final message is a bug; every watchdog check-in must wake the owner thread."
"wait_agent is not available to watchdog check-in agents. This thread is a one-shot watchdog check-in for owner {owner_thread_id}. Send the result to the parent/root agent with `send_input`, or finish with a final assistant report that runtime can forward as fallback. If you exit without either one, runtime emits no root-visible fallback message and the next scheduled watchdog check-in will try again."
)));
}