Skip to content
Closed
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 docs/incidents.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ pipeline still calls it there.
| bp. `bp_repo_traced_not_asked` | A secrets finding on a production API's log group posted "Which repo should this fix go to?" with the right repo as its best guess, two others as "also possible", no fix started, and "there is no direct AWS pointer" as its reason. The task definition's image came from an ECR repository named for the app plus its environment word, tagged with the app's name and the commit it was built from, and pushed by the app repo's workflow; none of it counted, and the hedged answer was cached for a week. | The repo is traced (`common::log_repo`): the running image's commit is looked up in every repo's history, a workflow or build file that ships the image counts as shipping it while Terraform that only defines it is context, image repository and tag names count without their environment word, and the classes and text of the error's own lines are looked for in the code. Evidence for one repo starts the fix there, saves the repo and says why in one line; split evidence still starts on the best guess with one card offering "Wrong repo? Move it"; only a log group nothing ties to any repo asks. An older resolver's or an unsure answer is not served from the cache for long. |
| bq. `bq_upstream_read_not_guessed` | A card said "1 new log finding: Seen again: Request failed with 503 in AUTH GUARD" for two lines of an error the API logs most days, with "the evidence does not show which upstream service returned the 503", an AWS account id line and a generic link; nothing had read the guard's code, which names the service it calls, and each analysis sent every line of a burst to the model. | A sighting is judged against its own week first (`common::log_triage`, the analyzer's same cases): at its usual rate it is counted with no card and no fix, rising is act, new or back after a quiet week is said once. A failed call's code is read: the card names the upstream (host and setting), its timeout and retries, the lines, tasks and the week's rate, with the decision on the first line and no account id. A burst is one entry before any model call, known errors are counted without the model, and an hourly budget caps analyses. |
| br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. |
| bs. `bs_cut_plan_revision` | A ticket with a long history was planned, and the plan check sent the plan back with two open items. The revision reached the output limit partway through its last block. The planner was told the coder's note ("make a change in small edit_file calls"), wrote only its decision block again, and the worker read only that last turn: no tasks, no design. The run failed with "empty or malformed plan ... retry the run" and the first plan was thrown away. | A planner's cut answer is continued where it stopped and read together with what came before the cut, file by file (`plan_sections`). A cut turn's note fits its loop: the coder's edit note only where there are edit tools, the planner's "continue the document" note, a shorter answer for everyone else. A revision that comes back empty, cut off or malformed never replaces a valid file, and a send-back asks for only the files that change. Files still missing are asked for alone, twice at most, the second with a larger output budget. A plan still not usable is planned again in a fresh step, then reported as CoderHelm's own failure, saying what it lacked. No run tells a person to retry it. |

## Adding a case

Expand Down
13 changes: 11 additions & 2 deletions services/common/src/run_questions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,12 +546,21 @@ pub fn send_back(repeats: &[Question], answers: &[Answer]) -> String {
}
out.push_str(
"Plan with those answers now. Use CLARIFICATION_NEEDED only for something the answers \
leave open, asking about that alone. Output the COMPLETE plan again in exactly the same \
format as before (every file block, the fix decision included).",
leave open, asking about that alone. ",
);
out.push_str(CHANGED_FILES_ONLY);
out
}

/// How the planner answers a send-back: the decision and only the files
/// the change touches, never the whole plan again. A revision that wrote
/// every file again once reached the output limit and lost the plan; the
/// worker keeps each file the revision leaves out (`plan_sections::merge`).
pub const CHANGED_FILES_ONLY: &str = "Answer with the fix_location.json block, whole, and only \
the openspec files your changes touch, each whole in its own fence and in the same format as \
before. A file you leave out stays exactly as it was; never write a file again only to \
repeat it.";

/// The words that carry a question's meaning: lowercase, three letters or
/// more, common filler dropped.
fn words(s: &str) -> Vec<String> {
Expand Down
6 changes: 2 additions & 4 deletions services/common/src/stop_rules/screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,10 +546,8 @@ pub fn send_back(s: &Screened, diagnosis: Option<&TicketDiagnosis>) -> String {
the contradiction.\n",
);
}
out.push_str(
"\nPlan the change now. Output the COMPLETE plan again in exactly the same format as \
before (every file block, the fix decision included).",
);
out.push_str("\nPlan the change now. ");
out.push_str(crate::run_questions::CHANGED_FILES_ONLY);
out
}

Expand Down
133 changes: 125 additions & 8 deletions services/worker/src/agent/anthropic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,7 @@ pub async fn converse_tool_loop(
effort: Option<&str>,
observer: Option<&dyn super::llm::LoopObserver>,
mut conversation_log: Option<&mut Vec<Value>>,
form: super::llm::AnswerForm,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
let family = ModelFamily::of(model_id);
// Cache breakpoint on the last tool: caches the tool definitions, which
Expand Down Expand Up @@ -743,6 +744,14 @@ pub async fn converse_tool_loop(
// [`MAX_CUT_RETRIES`] times.
let mut effort = effort;
let mut cut_retries: u32 = 0;
// What a cut turn is told depends on the work: a coder acts in small
// edits, a planner continues its document where it stopped (the
// planner was once told to make "small edit_file calls" it doesn't
// have, wrote only its last block again, and the run lost its plan).
let work = form.work(tools);
// A document's text written before a cut: the answer is that text and
// its continuation, never the continuation alone.
let mut written = String::new();

loop {
turns += 1;
Expand Down Expand Up @@ -898,6 +907,7 @@ pub async fn converse_tool_loop(
) {
cut_retries += 1;
effort = Some(lower_effort(effort));
let note = take_cut(work, cut, &blocks, &mut written);
warn!(
max_tokens,
retry = cut_retries,
Expand All @@ -911,7 +921,7 @@ pub async fn converse_tool_loop(
call,
turns,
common::agent_log::NoteKind::OutputLimit,
OUTPUT_LIMIT_NOTE,
note,
);
if cut == CutTurn::ThinkingOnly {
// A reply that only thought is dropped: its thinking was cut
Expand All @@ -923,18 +933,18 @@ pub async fn converse_tool_loop(
messages.pop();
match messages.last_mut() {
Some((role, content)) if role == "user" => {
content.push(json!({"type": "text", "text": OUTPUT_LIMIT_NOTE}));
content.push(json!({"type": "text", "text": note}));
}
_ => messages.push((
"user".to_string(),
vec![json!({"type": "text", "text": OUTPUT_LIMIT_NOTE})],
vec![json!({"type": "text", "text": note})],
)),
}
} else {
// What it said stays in history: the model sees where it was cut.
messages.push((
"user".to_string(),
vec![json!({"type": "text", "text": OUTPUT_LIMIT_NOTE})],
vec![json!({"type": "text", "text": note})],
));
}
continue;
Expand Down Expand Up @@ -968,7 +978,8 @@ pub async fn converse_tool_loop(
"stop_reason": response.stop_reason
}));
}
return extract_text(&blocks);
let text = extract_text(&blocks)?;
return Ok(super::llm::stitch(&written, &text));
}

// What the agent said before its calls: the "why" on an approval card.
Expand Down Expand Up @@ -1509,13 +1520,106 @@ fn read_message(
/// before the loop reads the cut as the answer.
const MAX_CUT_RETRIES: u32 = 3;

/// What the model reads after a turn cut at the output limit before any
/// tool call.
const OUTPUT_LIMIT_NOTE: &str = "[SYSTEM NOTE] Your last turn reached the output limit before \
/// What a loop that edits files (the coder, the feedback and fix rounds)
/// reads after a turn cut at the output limit before any tool call.
const EDIT_CUT_NOTE: &str = "[SYSTEM NOTE] Your last turn reached the output limit before \
you made any tool call, so nothing was done. Think briefly, then act now: make the next tool \
call, and make a change in small edit_file calls (a few lines each), one call per turn if \
needed. If the task is not needed, say so in one sentence; otherwise give your final answer.";

/// What a loop that writes a document (the planner) reads after a turn
/// that wrote part of it and was cut at the output limit.
const DOCUMENT_CUT_NOTE: &str = "[SYSTEM NOTE] Your last answer reached the output limit and \
was cut off mid-way. Continue it exactly where it stopped: start with the next characters of \
the cut text, repeat nothing already written, and finish every file and block that is still \
open, closing each fence. Keep it short: the files before the cut are kept as they are.";

/// What a loop that writes a document reads after a turn that only
/// thought, up to the output limit, and wrote nothing.
const DOCUMENT_THOUGHT_NOTE: &str = "[SYSTEM NOTE] Your last turn reached the output limit while \
thinking, before it wrote anything. Think briefly, then act now: make the next lookup you \
need, or write the document, each file whole in its own fence and kept short.";

/// What any other loop (a reviewer, a check, a question screen) reads after
/// a turn cut at the output limit before any tool call.
const ANSWER_CUT_NOTE: &str = "[SYSTEM NOTE] Your last turn reached the output limit before \
you made any tool call or finished your answer, so nothing was done. Think briefly, then act \
now: make the next tool call you need, or give your final answer, shorter than before.";

/// One cut turn taken again: the note it reads, with a document's cut text
/// kept in `written` (the answer is stitched from it).
fn take_cut(
work: super::llm::CutWork,
cut: CutTurn,
blocks: &[ContentBlock],
written: &mut String,
) -> &'static str {
if work == super::llm::CutWork::Document && cut == CutTurn::SaidSomething {
*written = super::llm::stitch(written, &text_of(blocks));
}
cut_note(work, cut)
}

fn text_of(blocks: &[ContentBlock]) -> String {
blocks
.iter()
.filter_map(|b| match b {
ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}

/// The loop's handling of turns that made no tool call, replayed without a
/// model: each turn as (its text, empty for one that only thought; its stop
/// reason). The notes the model read, and the answer the loop returns.
#[cfg(test)]
pub(crate) fn replay_cut_turns(
form: super::llm::AnswerForm,
tools: &[ToolDefinition],
turns: &[(&str, &str)],
) -> (Vec<&'static str>, String) {
let work = form.work(tools);
let mut written = String::new();
let mut notes = Vec::new();
let mut retries = 0;
for (text, stop) in turns {
let blocks = if text.is_empty() {
Vec::new()
} else {
vec![ContentBlock::Text {
text: text.to_string(),
}]
};
match cut_before_acting(
&blocks,
Some(stop),
false,
!tools.is_empty(),
false,
retries,
) {
Some(cut) => {
retries += 1;
notes.push(take_cut(work, cut, &blocks, &mut written));
}
None => return (notes, super::llm::stitch(&written, &text_of(&blocks))),
}
}
(notes, written)
}

/// The note a cut turn reads, for the work its loop does.
fn cut_note(work: super::llm::CutWork, cut: CutTurn) -> &'static str {
match (work, cut) {
(super::llm::CutWork::Edits, _) => EDIT_CUT_NOTE,
(super::llm::CutWork::Document, CutTurn::SaidSomething) => DOCUMENT_CUT_NOTE,
(super::llm::CutWork::Document, CutTurn::ThinkingOnly) => DOCUMENT_THOUGHT_NOTE,
(super::llm::CutWork::Answer, _) => ANSWER_CUT_NOTE,
}
}

/// A turn cut at the output limit before any tool call.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum CutTurn {
Expand Down Expand Up @@ -1674,6 +1778,16 @@ mod tests {
cut(&thought, max, false, false, false, 0),
Some(CutTurn::ThinkingOnly)
);
// Each loop reads the note for its own work: only a loop that can
// edit files is told to make edit_file calls.
use super::super::llm::CutWork;
for c in [CutTurn::ThinkingOnly, CutTurn::SaidSomething] {
assert!(cut_note(CutWork::Edits, c).contains("small edit_file calls"));
assert!(!cut_note(CutWork::Document, c).contains("edit_file"));
assert!(!cut_note(CutWork::Answer, c).contains("edit_file"));
}
assert!(cut_note(CutWork::Document, CutTurn::SaidSomething)
.contains("Continue it exactly where it stopped"));
assert_eq!(lower_effort(Some("high")), "medium");
assert_eq!(lower_effort(Some("medium")), "low");
assert_eq!(lower_effort(Some("low")), "low");
Expand Down Expand Up @@ -2153,6 +2267,7 @@ mod accounting_tests {
None,
observer,
Some(log),
super::super::llm::AnswerForm::Auto,
)
.await
}
Expand Down Expand Up @@ -2430,6 +2545,7 @@ mod accounting_tests {
None,
None,
None,
super::super::llm::AnswerForm::Auto,
)
.await;
let err = out.expect_err("the loop pauses");
Expand Down Expand Up @@ -2478,6 +2594,7 @@ mod accounting_tests {
None,
None,
None,
super::super::llm::AnswerForm::Auto,
)
.await
}
Expand Down
108 changes: 108 additions & 0 deletions services/worker/src/agent/llm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,65 @@ pub fn input_summary(input: &Value) -> String {
}
}

/// What a tool loop's answer is, for what it is told when a turn reaches the
/// output limit before any tool call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AnswerForm {
/// Decided from the tools: a loop that can edit files is told to act in
/// small edits; any other is told to make its next call or answer
/// shorter.
Auto,
/// A written document (the planner's plan): a cut turn's text is kept
/// and the model continues it where it stopped; the answer is the cut
/// text and its continuation, stitched ([`stitch`]).
Document,
}

/// What the model gets after a turn cut at the output limit before any
/// tool call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CutWork {
/// It can edit files: act in small edits.
Edits,
/// It writes a document: continue it where it stopped.
Document,
/// Anything else: the next call, or a shorter answer.
Answer,
}

/// The tools that change files in a loop's working tree.
pub const EDIT_TOOLS: &[&str] = &["edit_file", "write_file", "batch_write"];

impl AnswerForm {
/// The work a cut turn is told to get on with.
pub fn work(self, tools: &[ToolDefinition]) -> CutWork {
match self {
AnswerForm::Document => CutWork::Document,
AnswerForm::Auto if tools.iter().any(|t| EDIT_TOOLS.contains(&t.name.as_str())) => {
CutWork::Edits
}
AnswerForm::Auto => CutWork::Answer,
}
}
}

/// A document cut at the output limit and the model's continuation of it,
/// as one text. A continuation that starts with a code fence (the fence the
/// cut text left open, or a file written again from its start) begins on a
/// line of its own; any other continues the cut text exactly where it
/// stopped, mid-line included.
pub fn stitch(cut: &str, next: &str) -> String {
if cut.is_empty() {
return next.to_string();
}
let rest = next.trim_start();
if rest.starts_with("```") {
let sep = if cut.ends_with('\n') { "" } else { "\n" };
return format!("{cut}{sep}{rest}");
}
format!("{cut}{next}")
}

pub struct ToolDefinition {
pub name: String,
pub description: String,
Expand All @@ -153,6 +212,55 @@ pub trait ToolExecutor: Send + Sync {
) -> Result<Value, Box<dyn std::error::Error + Send + Sync>>;
}

#[cfg(test)]
mod cut_tests {
use super::*;

fn tool(name: &str) -> ToolDefinition {
ToolDefinition {
name: name.into(),
description: String::new(),
input_schema: serde_json::json!({}),
}
}

#[test]
fn a_cut_turn_is_told_the_work_its_loop_does() {
let coder = [tool("read_file"), tool("edit_file")];
let reader = [tool("read_file"), tool("search_code")];
assert_eq!(AnswerForm::Auto.work(&coder), CutWork::Edits);
assert_eq!(AnswerForm::Auto.work(&reader), CutWork::Answer);
assert_eq!(AnswerForm::Auto.work(&[]), CutWork::Answer);
// The planner reads with tools and writes a document.
assert_eq!(AnswerForm::Document.work(&reader), CutWork::Document);
assert_eq!(AnswerForm::Document.work(&coder), CutWork::Document);
}

#[test]
fn a_continuation_is_stitched_where_the_cut_stopped() {
// Exactly where it stopped, mid-line.
assert_eq!(
stitch("```tasks.md\n- [ ] a.ts: [mod", "ify] Add\n```"),
"```tasks.md\n- [ ] a.ts: [modify] Add\n```"
);
// The fence it left open closes on its own line.
assert_eq!(
stitch("```design.md\nD", "\n```\n```spec.md\nS\n```"),
"```design.md\nD\n```\n```spec.md\nS\n```"
);
assert_eq!(stitch("```design.md\nD", "```"), "```design.md\nD\n```");
// A block written again from its start opens on its own line.
assert_eq!(
stitch(
"```fix_location.json\n{\"cause\": \"New wo",
"```fix_location.json\n{}\n```"
),
"```fix_location.json\n{\"cause\": \"New wo\n```fix_location.json\n{}\n```"
);
assert_eq!(stitch("", "all of it"), "all of it");
}
}

#[cfg(test)]
mod input_summary_tests {
use super::input_summary;
Expand Down
Loading
Loading