From 569734f9334084f3d1e706e6a4f13675b581a5db Mon Sep 17 00:00:00 2001 From: "r4yharris-agent-coder[bot]" <334673250+r4yharris-agent-coder[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:00:08 -0500 Subject: [PATCH] feat(seats,planning,execution): add context compaction, failure classification, wall-clock reviewer reserve, duplicate-read guard, and consumer planner thinking control (FEATURE_SPEC 3, 5.2, 5.3, 5.4, 5.5, 5.8) AI-Agent: r4yharris-agent-coder AI-Model: GPT-6.1-Sol AI-Run: 1|github-copilot|GPT-6.1-Sol@-|x|-/1000000|-|ghcp-20261203-rca|rca-orchestration-resilience --- rust/execution/tools.rs | 13 ++- rust/planning/artifacts.rs | 33 ++++++ rust/planning/lifecycle.rs | 29 +++-- rust/seats/coder.rs | 223 +++++++++++++++++++++++++++++++++++-- rust/seats/tests.rs | 119 ++++++++++++++++++++ 5 files changed, 399 insertions(+), 18 deletions(-) diff --git a/rust/execution/tools.rs b/rust/execution/tools.rs index b192c4e..c00909c 100644 --- a/rust/execution/tools.rs +++ b/rust/execution/tools.rs @@ -3992,7 +3992,18 @@ impl Boundary { { args.extend(tests); } - result.commands.push(format!("node {}", args.join(" "))); + let display_args = args + .iter() + .map(|arg| { + if arg == TS_IMPORT_HOOK { + "" + } else { + arg.as_str() + } + }) + .collect::>() + .join(" "); + result.commands.push(format!("node {display_args}")); result.output = self .process( &node, diff --git a/rust/planning/artifacts.rs b/rust/planning/artifacts.rs index 3484bbd..5360939 100644 --- a/rust/planning/artifacts.rs +++ b/rust/planning/artifacts.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeSet; use std::fs::{self, OpenOptions}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; @@ -520,6 +521,38 @@ pub fn normalize_description(input: &Value) -> Result { } } } + if field == "design" { + if let Value::Object(entries) = entry { + let mut normalized = Value::Object(entries.clone()); + for (sub, limit) in [ + ("outline", 16usize), + ("edge_cases", 16), + ("out_of_scope", 12), + ] { + if let Some(sub_val) = entry.get(sub) + && let Some(raw_items) = domain::items(sub_val) + && raw_items.iter().all(|v| v.as_string().is_some()) + { + let mut seen = BTreeSet::new(); + let mut cleaned = Vec::new(); + for item in raw_items { + if let Some(t) = item.as_string() { + let s = trim(&encode(t).replace(['\r', '\n'], " ")).to_owned(); + if !s.is_empty() && seen.insert(s.clone()) { + cleaned.push(s); + } + } + } + if cleaned.len() > limit { + cleaned.truncate(limit); + } + domain::put(&mut normalized, sub, strings(&cleaned))?; + } + } + domain::put(&mut result, field, normalized)?; + continue; + } + } domain::put(&mut result, field, entry.clone())?; } } diff --git a/rust/planning/lifecycle.rs b/rust/planning/lifecycle.rs index 9ee03ad..606cc3c 100644 --- a/rust/planning/lifecycle.rs +++ b/rust/planning/lifecycle.rs @@ -1851,17 +1851,26 @@ impl Driver<'_, T, O> { turn += 1; self.check()?; let completion = loop { - match self - .complete( - &mut chat, - &request( - &messages, - boundary.as_ref().map(|_| tools::definitions(false)), - ), - &assignment.task, - ) - .await + let mut req = request( + &messages, + boundary.as_ref().map(|_| tools::definitions(false)), + ); + if crate::llm::reasoning::uses_deepseek_reasoning( + config.get("llm").unwrap_or(&Value::Null), + ) + .unwrap_or(false) + && boundary + .as_ref() + .is_some_and(|b| !b.writer.root().join("rust").join("shell.rs").is_file()) { + let _ = domain::put(&mut req, "reasoning_effort", Value::string("none")); + let _ = domain::put( + &mut req, + "chat_template_kwargs", + Value::object(vec![("thinking", Value::Boolean(false))]), + ); + } + match self.complete(&mut chat, &req, &assignment.task).await { Ok(completion) => break completion, Err(failure) => { if timeout_used diff --git a/rust/seats/coder.rs b/rust/seats/coder.rs index cee2bd8..bcb8298 100644 --- a/rust/seats/coder.rs +++ b/rust/seats/coder.rs @@ -508,18 +508,157 @@ impl Progress { self.repair_budget ))); } - self.repairs += 1; - let mut feedback = Text::from(format!("Actual approved tests failed (exit {exit}). Repair {} of {}. No change is verified. Repair only task-authorized files, do not weaken checks or classify unmeasured failures as preexisting. Change strategy instead of repeating a failed repair.\n\n", self.repairs, self.repair_budget).as_str()); - let tail = Text::from(output.as_str()); - let mut start = tail.0.len().saturating_sub(4096); - while matches!(tail.0.get(start), Some(0xdc00..=0xdfff)) { - start += 1; + let infra = classify_infrastructure_failure(&output); + if infra.is_some() && self.repairs >= 1 { + return Err(Handoff::RepeatedFailure.error(format!( + "Infrastructure/dependency failure persisted (exit {exit}); stopping code repair loop to avoid blind retries" + ))); } - feedback.0.extend(tail.0.iter().skip(start)); + self.repairs += 1; + let header = if let Some(category) = infra { + format!( + "[Environment/Dependency Failure: {category}] Test runner exited {exit} (repair {} of {}). Do not make blind source edits to mask missing host tools/dependencies; inspect the error below and either fix a genuine project bug or report the environment blocker.\n\n", + self.repairs, self.repair_budget + ) + } else { + format!( + "Actual approved tests failed (exit {exit}). Repair {} of {}. No change is verified. Repair only task-authorized files, do not weaken checks or classify unmeasured failures as preexisting. Change strategy instead of repeating a failed repair.\n\n", + self.repairs, self.repair_budget + ) + }; + let mut feedback = Text::from(header.as_str()); + let excerpt = extract_diagnostic_excerpt(&output); + feedback.0.extend(Text::from(excerpt.as_str()).0); Ok(feedback) } } +pub(crate) fn classify_infrastructure_failure(output: &str) -> Option<&'static str> { + if output.contains("NETSDK1045") || output.contains("sdk-not-found") { + return Some("dotnet SDK mismatch"); + } + if output.contains("PluginResolutionException") + || output.contains("DependencyResolutionException") + || output.contains("Could not transfer artifact") + { + return Some("Maven plugin/dependency resolution"); + } + if output.contains("ModuleNotFoundError: No module named") { + return Some("missing Python module"); + } + if output.contains("ERR_MODULE_NOT_FOUND") && output.contains("Cannot find package") { + return Some("missing Node package"); + } + if output.contains("no matching package named") && output.contains("--offline") { + return Some("offline Cargo crate cache miss"); + } + None +} + +pub(crate) fn extract_diagnostic_excerpt(output: &str) -> String { + let mut highlights = Vec::new(); + let mut highlight_chars = 0usize; + let mut seen = BTreeSet::new(); + for raw_line in output.lines() { + let line = raw_line.trim(); + if line.is_empty() { + continue; + } + let is_signal = line.starts_with("error[") + || line.starts_with("error:") + || line.starts_with("[ERROR]") + || line.starts_with("FAILED ") + || line.starts_with("E ") + || line.starts_with("not ok ") + || line.contains("AssertionError") + || line.contains("panicked at") + || line.contains("Exception:") + || line.contains("Error: ") + || line.contains("error CS"); + if is_signal && seen.insert(line.to_owned()) { + let len = line.chars().count(); + if highlights.len() >= 24 || highlight_chars + len > 2048 { + break; + } + highlight_chars += len + 1; + highlights.push(line.to_owned()); + } + } + let tail_text = Text::from(output); + let mut start = tail_text.0.len().saturating_sub(2800); + while matches!(tail_text.0.get(start), Some(0xdc00..=0xdfff)) { + start += 1; + } + let tail = Text(tail_text.0[start..].to_vec()) + .to_utf8() + .unwrap_or_default(); + if highlights.is_empty() { + return tail; + } + format!( + "Key diagnostics:\n{}\n\nTail:\n{}", + highlights.join("\n"), + tail + ) +} + +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 threshold = ((context_budget * 40) / 100).min(64_000); + if total <= threshold || messages.len() <= 8 { + return 0; + } + let keep_tail = 6usize; + let end = messages.len().saturating_sub(keep_tail); + let mut current = total; + let mut compacted = 0usize; + for msg in messages.iter_mut().take(end).skip(2) { + 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.", + ), + ), + ]) + .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; + } + } + compacted +} + fn offering( boundary: &tools::Boundary, attempt: &finalization::Attempt, @@ -1009,6 +1148,17 @@ impl Driver<'_, T, O> { .max(exploration_floor) .min(turns as usize); let context_budget = budget(config)?; + let task_timeout_ms = domain::safe_integer( + config + .as_value() + .get("seat") + .and_then(|seat| seat.get("task_timeout_ms")), + ) + .filter(|ms| *ms >= 60_000); + let coder_started = std::time::Instant::now(); + let mut wrap_up_sent = false; + let mut edit_epoch: u64 = 0; + let mut recent_reads: BTreeMap = BTreeMap::new(); boundary.require_git().await?; let validation = boundary.git_validation()?.clone(); progress.validation = Some(validation.clone()); @@ -1022,6 +1172,19 @@ impl Driver<'_, T, O> { .as_ref() .ok_or_else(|| execution::denied("Current coder context artifact is missing"))? .require_current(boundary, false)?; + 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) + { + wrap_up_sent = true; + messages.push(message( + "user", + Text::from( + "Time budget notice: 65% of the task wall-clock budget has elapsed; reserve the remaining budget for finalization and independent review. Finish any remaining edit now, run matching tests once, update every checklist item with current evidence, and emit your concise final summary.", + ), + )); + } let is_single_docs = boundary.document().files_allowed.len() == 1 && execution::policy::docs_only(&boundary.document().files_allowed) .unwrap_or(false); @@ -1557,6 +1720,22 @@ impl Driver<'_, T, O> { boundary.require_git().await?; } let scope_before = boundary.scope_files().len(); + let read_key = if call.name == "read_file" { + Some(call.args.json()) + } else { + None + }; + let duplicate_unchanged_read = read_key.as_ref().is_some_and(|key| { + recent_reads.get(key).is_some_and(|&(epoch, msg_idx)| { + epoch == edit_epoch + && messages.get(msg_idx).is_some_and(|msg| { + msg.get("content") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .is_some_and(|s| !s.contains("\"compacted\":true")) + }) + }) + }); let executed = if force_write && [ "read_file", @@ -1578,6 +1757,21 @@ impl Driver<'_, T, O> { ), ("executed", Value::Boolean(false)), ])) + } else if duplicate_unchanged_read { + attempt.reject_pending(call); + Ok(Value::object(vec![ + ("already_in_context", Value::Boolean(true)), + ( + "path", + call.args.get("path").cloned().unwrap_or(Value::Null), + ), + ( + "note", + Value::string( + "File is unchanged since your earlier read still present in context; proceed with edit_file, write_file, or run_test instead of re-reading.", + ), + ), + ])) } else { attempt.execute(boundary, call, &options.projection).await }; @@ -1662,7 +1856,22 @@ impl Driver<'_, T, O> { } Err(error) => return Err(error), }; + if matches!( + call.name.as_str(), + "write_file" | "edit_file" | "delete_file" + ) && response.get("executed") != Some(&Value::Boolean(false)) + { + edit_epoch = edit_epoch.saturating_add(1); + } + let msg_idx = messages.len(); messages.push(tool_result(call, response.clone())); + if let Some(key) = read_key + && !duplicate_unchanged_read + && response.get("executed") != Some(&Value::Boolean(false)) + { + recent_reads.insert(key, (edit_epoch, msg_idx)); + } + compact_transcript(&mut messages, context_budget); bounded_request(&request(&messages, None, false), context_budget)?; self.emit( boundary, diff --git a/rust/seats/tests.rs b/rust/seats/tests.rs index 4ee9cfd..a6e8b0a 100644 --- a/rust/seats/tests.rs +++ b/rust/seats/tests.rs @@ -2071,3 +2071,122 @@ async fn private_receipt_rechecks_same_byte_artifact_identity_not_only_model_jso .await; locks::finish(result, boundary.close().await) } + +#[test] +fn compact_transcript_folds_aged_large_tool_outputs_while_keeping_recent_turns_verbatim() { + let mut messages = vec![ + Value::object(vec![ + ("role", Value::string("system")), + ("content", Value::string("system prompt")), + ]), + Value::object(vec![ + ("role", Value::string("user")), + ("content", Value::string("task prompt")), + ]), + Value::object(vec![ + ("role", Value::string("tool")), + ("name", Value::string("read_file")), + ("content", Value::string(&"a".repeat(8000))), + ]), + Value::object(vec![ + ("role", Value::string("tool")), + ("name", Value::string("run_test")), + ("content", Value::string(&"b".repeat(8000))), + ]), + ]; + for idx in 0..6 { + messages.push(Value::object(vec![ + ("role", Value::string("tool")), + ("name", Value::string("read_file")), + ( + "content", + Value::string(&format!("recent-{idx}-{}", "c".repeat(1500))), + ), + ])); + } + let folded = coder::compact_transcript(&mut messages, 12_000); + assert_eq!(folded, 2); + assert!( + messages[2] + .get("content") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .is_some_and(|s| s.contains("\"compacted\":true") && s.contains("read_file")) + ); + assert!( + messages[9] + .get("content") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .is_some_and(|s| s.starts_with("recent-5-") && !s.contains("\"compacted\":true")) + ); +} + +#[test] +fn infrastructure_failure_classifier_and_diagnostic_extractor_separate_env_errors_from_assertions() +{ + assert_eq!( + coder::classify_infrastructure_failure("error NETSDK1045: The current .NET SDK"), + Some("dotnet SDK mismatch") + ); + assert_eq!( + coder::classify_infrastructure_failure("PluginResolutionException: offline"), + Some("Maven plugin/dependency resolution") + ); + assert_eq!( + coder::classify_infrastructure_failure("ModuleNotFoundError: No module named 'foo'"), + Some("missing Python module") + ); + assert_eq!( + coder::classify_infrastructure_failure( + "AssertionError: expected 1 to equal 2\nTests run: 5, Failures: 1" + ), + None + ); + let noisy = format!( + "error[E0308]: mismatched types\n{}\ntest result: FAILED. 0 passed; 1 failed;", + "noise line\n".repeat(400) + ); + let excerpt = coder::extract_diagnostic_excerpt(&noisy); + assert!(excerpt.contains("error[E0308]: mismatched types")); + assert!(excerpt.contains("test result: FAILED")); +} + +#[test] +fn planner_description_normalization_deduplicates_and_caps_soft_design_prose_lists() +-> Result<(), Error> { + let mut edge_cases = Vec::new(); + for idx in 0..20 { + edge_cases.push(Value::string(&format!("case-{idx}"))); + } + edge_cases.push(Value::string("case-0")); + let input = Value::object(vec![ + ("title", Value::string("Normalize design prose")), + ( + "acceptance_checks", + Value::Array(vec![Value::string("tests pass")]), + ), + ( + "files_allowed", + Value::Array(vec![Value::string("src/index.ts")]), + ), + ( + "design", + Value::object(vec![ + ("extend", Value::Array(Vec::new())), + ("new_exports", Value::Array(Vec::new())), + ("outline", Value::Array(vec![Value::string("step 1")])), + ("edge_cases", Value::Array(edge_cases)), + ("out_of_scope", Value::Array(Vec::new())), + ]), + ), + ]); + let normalized = crate::planning::artifacts::normalize_description(&input)?; + let capped = normalized + .get("design") + .and_then(|d| d.get("edge_cases")) + .and_then(domain::items) + .map_or(0, <[Value]>::len); + assert_eq!(capped, 16); + Ok(()) +}