Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rust/delivery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,7 @@ impl<T: Transport, O: Observer> 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;
Expand Down
2 changes: 1 addition & 1 deletion rust/delivery/continuation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ impl Budget {
self.timings.clone()
}

fn elapsed_ms(&self) -> Option<u32> {
pub(super) fn elapsed_ms(&self) -> Option<u32> {
u32::try_from(self.started.elapsed().as_millis()).ok()
}

Expand Down
133 changes: 94 additions & 39 deletions rust/seats/coder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -1175,7 +1228,9 @@ impl<T: Transport, O: Observer> 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(
Expand Down
59 changes: 49 additions & 10 deletions rust/seats/reviewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,51 @@ fn normalized(source: &Text) -> Result<String, Error> {
.to_owned())
}

fn normalized_unwrapped(source: &Text) -> Result<String, Error> {
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::<Vec<_>>()
.join(" ")
.replace('`', "");
Ok(execution::regex(r"\s+")?
.replace_all(&stripped, " ")
.trim()
.to_owned())
}

pub(crate) fn contains_grounded(haystack: &Text, needle: &Text) -> Result<bool, Error> {
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,
Expand Down Expand Up @@ -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();
}
Expand All @@ -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();
}
Expand Down Expand Up @@ -1634,17 +1679,11 @@ impl<T: Transport, O: Observer> 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(
Expand Down
65 changes: 62 additions & 3 deletions rust/seats/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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(())
}
Expand Down Expand Up @@ -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![
Expand All @@ -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")
Expand All @@ -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())
Expand Down Expand Up @@ -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(())
}
Loading