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
13 changes: 12 additions & 1 deletion rust/execution/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
"<roster-ts-hook>"
} else {
arg.as_str()
}
})
.collect::<Vec<_>>()
.join(" ");
result.commands.push(format!("node {display_args}"));
result.output = self
.process(
&node,
Expand Down
33 changes: 33 additions & 0 deletions rust/planning/artifacts.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -520,6 +521,38 @@ pub fn normalize_description(input: &Value) -> Result<Value, Error> {
}
}
}
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())?;
}
}
Expand Down
29 changes: 19 additions & 10 deletions rust/planning/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1851,17 +1851,26 @@ impl<T: Transport, O: Observer> 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
Expand Down
223 changes: 216 additions & 7 deletions rust/seats/coder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1009,6 +1148,17 @@ impl<T: Transport, O: Observer> 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<String, (u64, usize)> = BTreeMap::new();
boundary.require_git().await?;
let validation = boundary.git_validation()?.clone();
progress.validation = Some(validation.clone());
Expand All @@ -1022,6 +1172,19 @@ impl<T: Transport, O: Observer> 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);
Expand Down Expand Up @@ -1557,6 +1720,22 @@ impl<T: Transport, O: Observer> 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",
Expand All @@ -1578,6 +1757,21 @@ impl<T: Transport, O: Observer> 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
};
Expand Down Expand Up @@ -1662,7 +1856,22 @@ impl<T: Transport, O: Observer> 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,
Expand Down
Loading
Loading