diff --git a/rust/delivery.rs b/rust/delivery.rs index 8c7b52a..c6a62de 100644 --- a/rust/delivery.rs +++ b/rust/delivery.rs @@ -1627,6 +1627,7 @@ impl Driver<'_, T, O> { initial_baseline: Some(&baseline), capsule: capsule.as_ref(), continuation: guidance.as_ref(), + elapsed_ms: u64::from(budget.elapsed_ms().unwrap_or(0)), ..coder::Options::default() }, )).await; diff --git a/rust/delivery/continuation.rs b/rust/delivery/continuation.rs index 7ca6037..15e7cd1 100644 --- a/rust/delivery/continuation.rs +++ b/rust/delivery/continuation.rs @@ -117,7 +117,7 @@ impl Budget { self.timings.clone() } - fn elapsed_ms(&self) -> Option { + pub(super) fn elapsed_ms(&self) -> Option { u32::try_from(self.started.elapsed().as_millis()).ok() } diff --git a/rust/seats/coder.rs b/rust/seats/coder.rs index bcb8298..ce3aa5b 100644 --- a/rust/seats/coder.rs +++ b/rust/seats/coder.rs @@ -17,6 +17,7 @@ pub struct Options<'a> { pub prior_feedback: Option<&'a Text>, pub continuation: Option<&'a Text>, pub recording: Recording<'a>, + pub elapsed_ms: u64, } pub struct CoderResult { @@ -602,15 +603,30 @@ pub(crate) fn extract_diagnostic_excerpt(output: &str) -> String { ) } +fn message_chars(msg: &Value) -> usize { + let content_len = msg + .get("content") + .and_then(Value::as_string) + .map_or(0, |text| text.0.len()); + let calls_len = msg + .get("tool_calls") + .and_then(domain::items) + .map_or(0, |calls| { + calls + .iter() + .map(|call| { + call.get("function") + .and_then(|f| f.get("arguments")) + .and_then(Value::as_string) + .map_or(0, |text| text.0.len()) + }) + .sum() + }); + content_len + calls_len +} + pub(crate) fn compact_transcript(messages: &mut [Value], context_budget: usize) -> usize { - let total: usize = messages - .iter() - .map(|msg| { - msg.get("content") - .and_then(Value::as_string) - .map_or(0, |text| text.0.len()) - }) - .sum(); + let total: usize = messages.iter().map(message_chars).sum(); let threshold = ((context_budget * 40) / 100).min(64_000); if total <= threshold || messages.len() <= 8 { return 0; @@ -623,37 +639,74 @@ pub(crate) fn compact_transcript(messages: &mut [Value], context_budget: usize) if current <= threshold { break; } - if !domain::is_text(msg.get("role"), "tool") { - continue; - } - let len = msg - .get("content") - .and_then(Value::as_string) - .map_or(0, |text| text.0.len()); - if len <= 1200 { - continue; - } - let tool_name = msg - .get("name") - .and_then(Value::as_string) - .and_then(|t| t.to_utf8().ok()) - .unwrap_or_else(|| "tool".to_owned()); - let stub = Value::object(vec![ - ("compacted", Value::Boolean(true)), - ("tool", Value::string(&tool_name)), - ("original_chars", Value::Number(len as f64)), - ( - "note", - Value::string( - "Earlier large tool output compacted to preserve context budget; call the tool again if exact content is needed.", + if domain::is_text(msg.get("role"), "tool") { + let len = msg + .get("content") + .and_then(Value::as_string) + .map_or(0, |text| text.0.len()); + if len <= 1200 { + continue; + } + let tool_name = msg + .get("name") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .unwrap_or_else(|| "tool".to_owned()); + let stub = Value::object(vec![ + ("compacted", Value::Boolean(true)), + ("tool", Value::string(&tool_name)), + ("original_chars", Value::Number(len as f64)), + ( + "note", + Value::string( + "Earlier large tool output compacted to preserve context budget; call the tool again if exact content is needed.", + ), ), - ), - ]) - .json(); - let stub_len = stub.encode_utf16().count(); - if stub_len < len && domain::put(msg, "content", Value::string(&stub)).is_ok() { - current = current.saturating_sub(len - stub_len); - compacted += 1; + ]) + .json(); + let stub_len = stub.encode_utf16().count(); + if stub_len < len && domain::put(msg, "content", Value::string(&stub)).is_ok() { + current = current.saturating_sub(len - stub_len); + compacted += 1; + } + } else if domain::is_text(msg.get("role"), "assistant") + && let Some(calls) = msg.get("tool_calls").and_then(domain::items) + { + let mut updated_calls = calls.to_vec(); + let mut changed = false; + for call in &mut updated_calls { + if let Some(func) = call.get("function") + && let Some(args_text) = func.get("arguments").and_then(Value::as_string) + && args_text.0.len() > 1200 + { + let len = args_text.0.len(); + let name = func + .get("name") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .unwrap_or_else(|| "tool".to_owned()); + let stub = Value::object(vec![ + ("compacted", Value::Boolean(true)), + ("tool", Value::string(&name)), + ("original_chars", Value::Number(len as f64)), + ]) + .json(); + let stub_len = stub.encode_utf16().count(); + if stub_len < len { + let mut new_func = func.clone(); + if domain::put(&mut new_func, "arguments", Value::string(&stub)).is_ok() + && domain::put(call, "function", new_func).is_ok() + { + current = current.saturating_sub(len - stub_len); + compacted += 1; + changed = true; + } + } + } + } + if changed { + let _ = domain::put(msg, "tool_calls", Value::Array(updated_calls)); + } } } compacted @@ -1175,7 +1228,9 @@ impl Driver<'_, T, O> { compact_transcript(&mut messages, context_budget); if !wrap_up_sent && let Some(limit_ms) = task_timeout_ms - && coder_started.elapsed().as_millis() >= u128::from((limit_ms * 65) / 100) + && u128::from(options.elapsed_ms) + .saturating_add(coder_started.elapsed().as_millis()) + >= u128::from((limit_ms * 65) / 100) { wrap_up_sent = true; messages.push(message( diff --git a/rust/seats/reviewer.rs b/rust/seats/reviewer.rs index 1f3b388..b05420b 100644 --- a/rust/seats/reviewer.rs +++ b/rust/seats/reviewer.rs @@ -499,6 +499,51 @@ fn normalized(source: &Text) -> Result { .to_owned()) } +fn normalized_unwrapped(source: &Text) -> Result { + let raw = source.to_utf8()?; + let stripped = raw + .lines() + .map(|line| { + let trimmed = line.trim_start(); + trimmed + .strip_prefix("+ ") + .or_else(|| trimmed.strip_prefix("- ")) + .or_else(|| { + trimmed + .strip_prefix('+') + .filter(|rest| !rest.starts_with('+')) + }) + .unwrap_or(line) + }) + .collect::>() + .join(" ") + .replace('`', ""); + Ok(execution::regex(r"\s+")? + .replace_all(&stripped, " ") + .trim() + .to_owned()) +} + +pub(crate) fn contains_grounded(haystack: &Text, needle: &Text) -> Result { + let norm_needle = normalized(needle)?; + if norm_needle.is_empty() { + return Ok(false); + } + if normalized(haystack)?.contains(&norm_needle) { + return Ok(true); + } + let unwrapped_needle = normalized_unwrapped(needle)?; + if unwrapped_needle + .chars() + .filter(|c| !c.is_whitespace()) + .count() + < 8 + { + return Ok(false); + } + Ok(normalized_unwrapped(haystack)?.contains(&unwrapped_needle)) +} + fn grounded_audit( content: &Text, ask: &Text, @@ -636,7 +681,7 @@ fn grounded_audit( execution::required(ground, "obligation")?, "Audit obligation must be text", )?; - if !normalized(ask)?.contains(&normalized(&obligation)?) { + if !contains_grounded(ask, &obligation)? { if is_html_only_audit { return pass_fallback(); } @@ -663,7 +708,7 @@ fn grounded_audit( execution::required(ground, "excerpt")?, "Audit excerpt must be text", )?; - if !normalized(source)?.contains(&normalized(&excerpt)?) { + if !contains_grounded(source, &excerpt)? { if is_html_only_audit { return pass_fallback(); } @@ -1634,17 +1679,11 @@ impl Driver<'_, T, O> { }) { Ok(a) => a, Err(first_err) => { - if first_err - .message - .contains("not stated by the authoritative") - || first_err.message.contains("excerpt") - || first_err.message.contains("unobserved") - || first_err.code == Some("ROSTER_TOOL_FREE_AUTHORITY") - { + if first_err.code == Some("ROSTER_TOOL_FREE_AUTHORITY") { return Err(first_err); } let retry_prompt = format!( - "Invalid Original Ask audit JSON ({}). Remember: requirements already present in the complete delivered files on disk count as satisfied even if unchanged in the diff. If the delivered files on disk satisfy the Original Ask, return ONLY: {{\"verdict\":\"pass\",\"reasons\":[],\"security_notes\":[],\"checks\":[{{\"id\":1,\"met\":true,\"evidence\":\"Delivered files satisfy the Original Ask.\"}}]}}. Only return verdict \"fail\" if a requested deliverable is genuinely missing from the complete delivered files, with one exact grounds entry {{\"obligation\":\"...\",\"file\":\"...\",\"excerpt\":\"...\",\"reason\":\"...\"}} per reason.", + "Invalid Original Ask audit response ({}). Copy every negative ground's `obligation` verbatim from `## Original Ask` and every `excerpt` verbatim from `## Exact delivered sources` (no paraphrasing, no invented lines, no diff prefixes). Requirements already satisfied in the complete delivered files on disk count as met even if unchanged in the diff. If the delivered files satisfy the Original Ask, return ONLY: {{\"verdict\":\"pass\",\"reasons\":[],\"security_notes\":[],\"checks\":[{{\"id\":1,\"met\":true,\"evidence\":\"Delivered files satisfy the Original Ask.\"}}]}}. Only return verdict \"fail\" for a genuine violation with exact verbatim grounds.", first_err.message ); let retry_req = apply_reviewer_json_guard(request( diff --git a/rust/seats/tests.rs b/rust/seats/tests.rs index a6e8b0a..a1b9859 100644 --- a/rust/seats/tests.rs +++ b/rust/seats/tests.rs @@ -1829,6 +1829,7 @@ async fn invented_original_ask_obligations_or_source_excerpts_are_not_accepted_a write("docs/guide.md", "# Guide\n\nDelivered guide.\n"), )]), summary(), + review_packet(audit.clone()), review_packet(audit), ]); let mut events = Events::default(); @@ -1860,7 +1861,7 @@ async fn invented_original_ask_obligations_or_source_excerpts_are_not_accepted_a "excerpt" } ))); - assert_eq!(transport.requests.len(), 3); + assert_eq!(transport.requests.len(), 4); assert!(!fixture.read("REVIEW.md")?.contains("Verdict: pass")); Ok(()) } @@ -2093,6 +2094,27 @@ fn compact_transcript_folds_aged_large_tool_outputs_while_keeping_recent_turns_v ("name", Value::string("run_test")), ("content", Value::string(&"b".repeat(8000))), ]), + Value::object(vec![ + ("role", Value::string("assistant")), + ("content", Value::string("")), + ( + "tool_calls", + Value::Array(vec![Value::object(vec![ + ("id", Value::string("call_1")), + ("type", Value::string("function")), + ( + "function", + Value::object(vec![ + ("name", Value::string("write_file")), + ( + "arguments", + Value::string(&format!("{{\"content\":\"{}\"}}", "x".repeat(6000))), + ), + ]), + ), + ])]), + ), + ]), ]; for idx in 0..6 { messages.push(Value::object(vec![ @@ -2105,7 +2127,7 @@ fn compact_transcript_folds_aged_large_tool_outputs_while_keeping_recent_turns_v ])); } let folded = coder::compact_transcript(&mut messages, 12_000); - assert_eq!(folded, 2); + assert_eq!(folded, 3); assert!( messages[2] .get("content") @@ -2114,7 +2136,18 @@ fn compact_transcript_folds_aged_large_tool_outputs_while_keeping_recent_turns_v .is_some_and(|s| s.contains("\"compacted\":true") && s.contains("read_file")) ); assert!( - messages[9] + messages[4] + .get("tool_calls") + .and_then(domain::items) + .and_then(|c| c.first()) + .and_then(|c| c.get("function")) + .and_then(|f| f.get("arguments")) + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .is_some_and(|s| s.contains("\"compacted\":true") && s.contains("write_file")) + ); + assert!( + messages[10] .get("content") .and_then(Value::as_string) .and_then(|t| t.to_utf8().ok()) @@ -2190,3 +2223,29 @@ fn planner_description_normalization_deduplicates_and_caps_soft_design_prose_lis assert_eq!(capped, 16); Ok(()) } + +#[test] +fn grounded_audit_matching_handles_backticks_and_diff_prefixes_while_rejecting_invented_text() +-> Result<(), Error> { + let ask = Text::from( + "Update `XML.unescape` and `XMLTokener.unescapeEntity` so `XML.toJSONObject(XML.toString(obj))` round-trips.", + ); + assert!(reviewer::contains_grounded( + &ask, + &Text::from("XML.unescape and XMLTokener.unescapeEntity") + )?); + assert!(!reviewer::contains_grounded( + &ask, + &Text::from("Deploy an unrequested external system") + )?); + let source = Text::from(" if (codePoint == 0x0c) {\n return true;\n }\n"); + assert!(reviewer::contains_grounded( + &source, + &Text::from("+ if (codePoint == 0x0c) {\n+ return true;") + )?); + assert!(!reviewer::contains_grounded( + &source, + &Text::from("Invented absent source text") + )?); + Ok(()) +}