diff --git a/docs/incidents.md b/docs/incidents.md index 21ae72a02..86363db22 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -94,7 +94,9 @@ pipeline still calls it there. | bn. `bn_infra_list_follows_aws` | Security, Infrastructure kept ten rows while AWS had moved on: an RDS instance deleted two days before still showed two pending actions, a Lambda function on a retired runtime came from a Terraform module nothing called, five rows already fixed kept their Runbook and Fix PR buttons, an older CVE row and the engine patch to the same version stood as two rows, and a serverless platform update and an operating system update on each instance AWS listed never appeared. The read kept every resource for three days and the match took them all as running. | Each read says which kinds it saw in full; what a full read no longer lists is dropped and its findings close as removed, with the time; a failed or partial read drops and closes nothing. The same move on one database is one item. Every pending action is an item, applied by CoderHelm after one approval when it has no code change, and a version change on a resource in code is a pull request whichever source raised it. Closed items offer nothing to do. Opening the page refreshes a read older than five minutes, at most once per team in that time. | | 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 security fix's pull request gets the same: its sections are computed from the lockfile on the head and nothing else of its old body is kept (`security_fixes::fresh_body`). A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | 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 diff --git a/services/common/src/run_questions.rs b/services/common/src/run_questions.rs index 4404fc80a..36398a2b1 100644 --- a/services/common/src/run_questions.rs +++ b/services/common/src/run_questions.rs @@ -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 { diff --git a/services/common/src/stop_rules/screen.rs b/services/common/src/stop_rules/screen.rs index 6fd5ac25c..6f1b724e1 100644 --- a/services/common/src/stop_rules/screen.rs +++ b/services/common/src/stop_rules/screen.rs @@ -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 } diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 363664f44..932843db7 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -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>, + form: super::llm::AnswerForm, ) -> Result> { let family = ModelFamily::of(model_id); // Cache breakpoint on the last tool: caches the tool definitions, which @@ -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; @@ -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, @@ -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 @@ -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; @@ -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. @@ -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::>() + .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 { @@ -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"); @@ -2153,6 +2267,7 @@ mod accounting_tests { None, observer, Some(log), + super::super::llm::AnswerForm::Auto, ) .await } @@ -2430,6 +2545,7 @@ mod accounting_tests { None, None, None, + super::super::llm::AnswerForm::Auto, ) .await; let err = out.expect_err("the loop pauses"); @@ -2478,6 +2594,7 @@ mod accounting_tests { None, None, None, + super::super::llm::AnswerForm::Auto, ) .await } diff --git a/services/worker/src/agent/llm.rs b/services/worker/src/agent/llm.rs index 12fec8fd3..e17c1ebd7 100644 --- a/services/worker/src/agent/llm.rs +++ b/services/worker/src/agent/llm.rs @@ -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, @@ -153,6 +212,55 @@ pub trait ToolExecutor: Send + Sync { ) -> Result>; } +#[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; diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 95b7e46bc..4399f1ce7 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -285,6 +285,75 @@ pub async fn converse( opts: ConverseOptions, observer: Option<&dyn super::llm::LoopObserver>, conversation_log: Option<&mut Vec>, +) -> Result> { + converse_as( + state, + provider, + agent, + model_id, + system_prompt, + messages, + tools, + tool_executor, + usage, + opts, + observer, + conversation_log, + super::llm::AnswerForm::Auto, + ) + .await +} + +/// [`converse`] for a loop whose answer is a written document (the +/// planner's plan): a turn cut at the output limit continues the document +/// where it stopped, and the answer is the cut text and its continuation +/// together (see `llm::AnswerForm::Document`). +#[allow(clippy::too_many_arguments)] +pub async fn converse_document( + state: &crate::WorkerState, + provider: &ModelProvider, + agent: common::agent_policy::Agent, + model_id: &str, + system_prompt: &str, + messages: &mut Vec<(String, Vec)>, + tools: &[ToolDefinition], + tool_executor: &dyn ToolExecutor, + usage: &mut TokenUsage, + opts: ConverseOptions, +) -> Result> { + converse_as( + state, + provider, + agent, + model_id, + system_prompt, + messages, + tools, + tool_executor, + usage, + opts, + None, + None, + super::llm::AnswerForm::Document, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn converse_as( + state: &crate::WorkerState, + provider: &ModelProvider, + agent: common::agent_policy::Agent, + model_id: &str, + system_prompt: &str, + messages: &mut Vec<(String, Vec)>, + tools: &[ToolDefinition], + tool_executor: &dyn ToolExecutor, + usage: &mut TokenUsage, + opts: ConverseOptions, + observer: Option<&dyn super::llm::LoopObserver>, + conversation_log: Option<&mut Vec>, + form: super::llm::AnswerForm, ) -> Result> { // A switch in Settings, System, Models reaches the next loop. common::model_provider::refresh(&state.dynamo, &state.config.settings_table_name).await; @@ -318,6 +387,7 @@ pub async fn converse( opts.effort, observer, log, + form, ) .await; if own_log { diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 35dd5fe27..90620c741 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -832,6 +832,7 @@ async fn build( number, ticket_id, &pr, + fresh, ) .await } else { diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index 48f809b0e..f27b6c195 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -588,8 +588,9 @@ pub fn next_step_gaps(d: Option<&FixDecision>) -> Vec { /// The message that sends a planner back with what its decision lacks. pub fn send_back(gaps: &[String]) -> String { format!( - "Before this decision stands:\n{}\nThen answer again in full: the four openspec files and the fix_location.json block, with `data_shows` saying only what your lookups returned.", - gaps.iter().map(|g| format!("- {g}")).collect::>().join("\n") + "Before this decision stands:\n{}\nThen answer with `data_shows` saying only what your lookups returned. {}", + gaps.iter().map(|g| format!("- {g}")).collect::>().join("\n"), + common::run_questions::CHANGED_FILES_ONLY ) } diff --git a/services/worker/src/passes/incidents/br_description_writer_upgrade.rs b/services/worker/src/passes/incidents/br_description_writer_upgrade.rs index 0a6e544e1..761780f9d 100644 --- a/services/worker/src/passes/incidents/br_description_writer_upgrade.rs +++ b/services/worker/src/passes/incidents/br_description_writer_upgrade.rs @@ -303,3 +303,156 @@ fn the_watch_sweep_catches_up_a_few_per_team() { // No age window: an old run's open pull request is reached too. assert!(!all.contains(":cut")); } + +/// A security fix's pull request from before the upgrade: its old body has +/// no lead or reviewer-block markers and its check rows froze as running. +/// Its sections are computed from the lockfile on the head +/// (`security_fixes::at_head`), which in an ordinary rebuild keeps the rest +/// of the body. In the catch-up, wholly CoderHelm's, it is built from the +/// sections computed now and the facts alone: no old line survives, and +/// the line that closes its issue is kept. +#[test] +fn an_old_security_description_keeps_no_old_line() { + use crate::passes::security_fixes; + use common::dep_head::{self, LockAt}; + use common::security_fixes::{self as sec, Advisory, Bump, Finding, FindingState, FixUnit}; + + let unit = FixUnit { + repo: format!("{OWNER}/{REPO}"), + ecosystem: "npm".into(), + bundle: true, + bumps: vec![Bump { + package: "xml-kit".into(), + from: "1.4.4".into(), + to: "1.4.9".into(), + major: false, + manifest: "pnpm-lock.yaml".into(), + }], + ..Default::default() + }; + let finding = Finding { + id: "f-1".into(), + package: "xml-kit".into(), + version: "1.4.4".into(), + fixed_version: Some("1.4.9".into()), + manifest: "pnpm-lock.yaml".into(), + advisory: Advisory { + primary: "GHSA-xxxx-0011".into(), + ids: vec!["GHSA-xxxx-0011".into()], + ..Default::default() + }, + ..Default::default() + }; + let state = FindingState::default(); + let copies = |v: &str| Some(vec![("xml-kit".to_string(), v.to_string())]); + let head = dep_head::resolve( + &unit, + HEAD, + &[LockAt { + path: "pnpm-lock.yaml".into(), + base: copies("1.4.4"), + head: copies("1.4.9"), + why: String::new(), + }], + ); + let check = common::upgrade_notes::WhatToCheck::default(); + let pairs = [(&finding, &state)]; + + let old_body = format!( + "{marker} +Bumps xml-kit to fix GHSA-xxxx-0011. + +**For the reviewer** +* **Look first:** `pnpm-lock.yaml`, the only change. +* **Roll back:** revert this pull request; nothing outside the code changes with it. + +**Rollback:** Revert this pull request; nothing outside the code changes with it. + +### Verification + +| Check | Result | +|---|---| +| Lint (CI) | Not run: still running when this was written | +| Unit tests (CI) | Not run: still running when this was written | +| Audit (CI) | Not run: still running when this was written | + +Fixes #34 +", + marker = sec::MARKER + ); + assert!(!old_body.contains("")); + let old = stamped_before(&old_body); + assert_eq!(description::catch_up(&old, HEAD), CatchUp::Rebuild); + + // What `at_head` gives the build in the catch-up: the sections computed + // now, and only the closing line of the old body. + let computed = sec::pr_body_at_head( + &unit, + &pairs, + "Bumped.", + &check, + &sec::BodyLinks::default(), + &head, + ); + // Before: the ordinary rebuild keeps the rest of the old body. + let kept = security_fixes::rebuilt_body(&description::flat(&old), &computed); + assert!(kept.contains("Look first") && kept.contains("still running when this was written")); + let base = security_fixes::fresh_body(&computed, &description::flat(&old)); + let dependency = common::pr_dependency::facts(&unit, &pairs, &head, &check); + let files = vec![( + "pnpm-lock.yaml".to_string(), + "modified".to_string(), + "@@ -1 +1 @@\n-a\n+b\n".to_string(), + )]; + let floor = pr_risk::floor(&files, &std::collections::HashMap::new()); + let checks: Vec = ["Lint", "Unit tests"] + .iter() + .map(|n| Check { + name: n.to_string(), + url: format!("https://ci.example.com/{}", n.replace(' ', "-")), + state: State::Passed, + }) + .collect(); + let facts = description_facts::facts(&Inputs { + head: HEAD, + body: &base, + files: &files, + floor: &floor, + checks: Some(&checks), + why: None, + dependency: Some(dependency), + outside: None, + run_url: "", + notes: vec![], + evidence: vec![], + repo_url: "https://github.com/acme/site", + }); + let shaped = description_facts::shape_for(&base, "Fix GHSA-xxxx-0011", facts, None, None); + let next = description::with_stamp(&shaped.body, HEAD); + let reviewed = common::pr_review::review(&description::clean(&next)); + let new = common::pr_layout::layout(&common::person_gate::sink(&reviewed.body).text); + + for line in [ + "still running when this was written", + "Look first", + "Roll back", + "For the reviewer", + "| Audit (CI)", + ] { + assert!(!new.contains(line), "{line:?} is still in: {new}"); + } + assert!(new.contains("xml-kit"), "the computed sections: {new}"); + assert!(new.contains("Fixes #34"), "the issue still closes: {new}"); + assert!(description::is_current(&new, HEAD), "{new}"); + assert_eq!(description::catch_up(&new, HEAD), CatchUp::Current); + + // The build passes the catch-up on to the security sections. + let src = include_str!("../description.rs"); + let build = fn_src(src, "\nasync fn build("); + let at = &build[build.find("security_fixes::at_head(").unwrap()..]; + assert!(at[..at.find(".await").unwrap()].contains("fresh,"), "{at}"); + let sec_src = include_str!("../security_fixes.rs"); + let at_head = fn_src(sec_src, "\npub(crate) async fn at_head("); + assert!(at_head.contains("if fresh_only {")); + assert!(at_head.contains("fresh_body(&fresh, body)")); +} diff --git a/services/worker/src/passes/incidents/bs_cut_plan_revision.rs b/services/worker/src/passes/incidents/bs_cut_plan_revision.rs new file mode 100644 index 000000000..4c1280be3 --- /dev/null +++ b/services/worker/src/passes/incidents/bs_cut_plan_revision.rs @@ -0,0 +1,242 @@ +//! bs. A ticket with a long history (earlier runs, pull requests closed +//! unmerged, review comments) was planned. The plan check left two items +//! open (a review comment on an earlier pull request the plan never +//! answered, and an outside-steps note) and sent the plan back. The +//! revision reached the output limit partway through its last block, before +//! any tool call. The loop told the planner "make a change in small +//! edit_file calls", the coder's note; the planner has no such tool and +//! wrote only its decision block again ("the four files above are +//! unchanged"). The worker read only that last turn: no tasks, no design. +//! The run failed "Plan generation produced an empty or malformed plan ... +//! retry the run", throwing the first plan away. +//! +//! Guarantee: a planner's cut answer is continued where it stopped and read +//! with what came before the cut, file by file; the planner is told to +//! continue its document, never the coder's edit_file note; a revision that +//! comes back empty, cut off or malformed never replaces a valid file; files +//! still missing are asked for alone; a plan still unusable is planned again +//! in a fresh step and only then reported, as CoderHelm's own failure, and +//! no run ever tells a person to retry it. + +use super::fixture::*; +use crate::agent::anthropic::replay_cut_turns; +use crate::agent::llm::{AnswerForm, ToolDefinition}; +use crate::passes::plan_sections::{self, State}; + +const OLD: &str = "retry the run"; + +fn tools(names: &[&str]) -> Vec { + names + .iter() + .map(|n| ToolDefinition { + name: n.to_string(), + description: String::new(), + input_schema: serde_json::json!({}), + }) + .collect() +} + +/// The first plan, written in full: the plan the check sent back. +fn first_plan() -> String { + format!( + "```proposal.md\nAdd the card block to the page builder.\n```\n\ + ```design.md\napps/web/src/blocks/Card.tsx renders the block; the schema adds it.\n```\n\ + ```tasks.md\n{}\n```\n\ + ```spec.md\nGiven a page with a card block, when it renders, then the card shows.\n```\n\ + ```fix_location.json\n{{\"fix_location\":\"code\",\"cause\":\"New block\"}}\n```", + plan_tasks_md() + ) +} + +/// The revision's two turns, as the incident had them: the four files and +/// the start of the decision, cut at the output limit; then only the +/// decision written again from its start. +fn revision_turns() -> (String, String) { + let cut = format!( + "Revised for the two open items.\n\n\ + ```proposal.md\nAdd the card block; the earlier review's metadata case is handled.\n```\n\ + ```design.md\nCard.tsx renders the block; metadata keeps the earlier special case.\n```\n\ + ```tasks.md\n{}\n- [ ] apps/web/src/lib/metadata.ts: [modify] Keep the special case\n```\n\ + ```spec.md\nGiven a card page, when its metadata renders, then the special case holds.\n```\n\ + ```fix_location.json\n{{\"fix_location\":\"code\",\"cause\":\"New wo", + plan_tasks_md() + ); + let next = "My last answer was cut off partway through the `fix_location.json` block, so \ + here it is again in full. The four openspec files in that answer were complete \ + and are unchanged.\n\n```fix_location.json\n{\"fix_location\":\"code\",\"cause\":\"New block\"}\n```" + .to_string(); + (cut, next) +} + +fn plan_of(text: &str) -> crate::passes::plan::PlanResult { + let a = plan_sections::read(text); + crate::passes::plan::PlanResult { + proposal: a.complete("proposal.md").into(), + design: a.complete("design.md").into(), + tasks: a.complete("tasks.md").into(), + spec: a.complete("spec.md").into(), + repo_tasks: vec![], + fix: None, + } +} + +#[test] +fn a_cut_revision_keeps_its_files_and_the_planner_reads_the_planner_note() { + let planner = tools(&["read_file_lines", "search_code", "query_content"]); + let (cut, next) = revision_turns(); + + // Before: the loop read only the last turn, and the planner read the + // coder's note. That last turn holds no plan. + let before = plan_of(&next); + assert!(plan_sections::unusable(&before).is_some()); + let (notes, _) = replay_cut_turns( + AnswerForm::Auto, + &tools(&["read_file", "edit_file"]), + &[(&cut, "max_tokens"), (&next, "end_turn")], + ); + assert!( + notes[0].contains("small edit_file calls"), + "the coder still gets its note" + ); + + // After: the planner's loop continues the document and returns the cut + // text with its continuation. + let (notes, answer) = replay_cut_turns( + AnswerForm::Document, + &planner, + &[(&cut, "max_tokens"), (&next, "end_turn")], + ); + assert_eq!(notes.len(), 1); + assert!(!notes[0].contains("edit_file"), "{}", notes[0]); + assert!(notes[0].contains("Continue it exactly where it stopped")); + let a = plan_sections::read(&answer); + for f in plan_sections::FILES { + assert_eq!(a.state(f), State::Complete, "{f}"); + } + assert_eq!(a.state(plan_sections::DECISION), State::Complete); + let revised = plan_of(&answer); + assert!(plan_sections::unusable(&revised).is_none()); + assert!( + revised.tasks.contains("metadata.ts"), + "the revision's own tasks" + ); + + // A planner that only thought to the limit is told to write, not edit. + let (notes, _) = replay_cut_turns( + AnswerForm::Document, + &planner, + &[("", "max_tokens"), (&first_plan(), "end_turn")], + ); + assert!(!notes[0].contains("edit_file")); + assert!(notes[0].contains("write the document")); + // Any other loop without edit tools is told to answer, not edit. + let (notes, _) = replay_cut_turns( + AnswerForm::Auto, + &planner, + &[("", "max_tokens"), ("done", "end_turn")], + ); + assert!(!notes[0].contains("edit_file")); +} + +#[test] +fn a_revision_that_comes_back_empty_never_replaces_the_valid_plan() { + let valid = plan_of(&first_plan()); + assert!(plan_sections::unusable(&valid).is_none()); + // The revision as the old loop returned it: the decision alone. + let (_, next) = revision_turns(); + let answer = plan_sections::read(&next); + let (kept, lost) = plan_sections::merge(valid.clone(), plan_of(&next), &answer); + assert!(lost.is_empty()); + assert_eq!(kept.tasks, valid.tasks); + assert_eq!(kept.design, valid.design); + assert!(plan_sections::unusable(&kept).is_none(), "the run goes on"); + + // A revision cut inside its tasks: the earlier tasks stand, named lost. + let cut = "```design.md\nD2\n```\n```tasks.md\n- [ ] apps/web/src/blocks/Card.tsx: [mod"; + let answer = plan_sections::read(cut); + let (kept, lost) = plan_sections::merge(valid.clone(), plan_of(cut), &answer); + assert_eq!(lost, vec!["tasks.md"]); + assert_eq!(kept.tasks, valid.tasks); + assert_eq!( + kept.design, "D2", + "a file written in full is the revision's" + ); + + let mut end = Ending { + status: "running".into(), + ..Default::default() + }; + end.said("Plan check: 2 left open: [history_used] ... [outside_steps] ..."); + end.never_says(OLD); + end.never_says("empty or malformed plan"); +} + +#[test] +fn a_plan_with_no_valid_first_round_is_repaired_file_by_file() { + // No valid plan to fall back on: the files missing are asked for alone. + let cut = "```proposal.md\nP\n```\n```design.md\nD cut"; + let p = plan_of(cut); + assert_eq!( + plan_sections::to_repair(&p), + vec!["design.md", "tasks.md", "spec.md"] + ); + let ask = + plan_sections::repair_prompt(&plan_sections::to_repair(&p), &plan_sections::read(cut)); + assert!(ask.contains("`design.md` was cut off")); + assert!(ask.contains("`tasks.md` is missing")); + assert!(!ask.contains("edit_file")); + // The repair's answer fills them in; the proposal stays. + let reply = format!( + "```design.md\nD\n```\n```tasks.md\n{}\n```\n```spec.md\nS\n```", + plan_tasks_md() + ); + let (out, _) = plan_sections::merge(p, plan_of(&reply), &plan_sections::read(&reply)); + assert!(plan_sections::unusable(&out).is_none()); + assert_eq!(out.proposal, "P"); +} + +#[test] +fn a_plan_still_unusable_plans_again_in_a_fresh_step_then_says_why() { + let mut ps = crate::passes::steps::PlanState::new(OWNER, REPO, BASE); + assert!(ps.may_plan_again()); + let before = ps.mark(); + ps.plan_retries += 1; + assert_ne!(ps.mark(), before, "planning again counts as progress"); + assert!(!ps.may_plan_again(), "bounded"); + let why = plan_sections::unusable(&plan_of("")).unwrap(); + let failure = crate::passes::plan_failure(&why, None); + assert!(failure.contains("the plan has no usable `proposal.md`, `design.md`, `tasks.md`")); + assert!(failure.contains("CoderHelm's own failure")); + assert!(!failure.to_lowercase().contains(OLD)); + + // The pipeline's own places: the plan pass writes through the document + // loop, revisions are merged, the repair runs, and the guard plans + // again in a fresh step instead of failing with a retry instruction. + let plan = include_str!("../plan.rs"); + let run = fn_src(plan, "pub async fn run("); + assert!( + !run.contains("provider::converse("), + "the planner's calls are document loops" + ); + assert!(run.matches("provider::converse_document(").count() >= 5); + assert!(run.contains("super::plan_sections::repair_prompt(")); + assert!(run.matches("revise(").count() >= 4); + let rp = run_passes_src(); + assert!(rp.contains("plan_sections::unusable(&plan_result)")); + assert!(rp.contains("plan_again_or_stop(")); + for src in [plan, include_str!("../mod.rs")] { + assert!(!src.contains("Nothing was asked of a person; retry the run")); + assert!(!src.contains("transient model formatting issue")); + } + for src in [ + include_str!("../fix_location.rs"), + include_str!("../resolved.rs"), + include_str!("../../../../common/src/run_questions.rs"), + include_str!("../../../../common/src/stop_rules/screen.rs"), + ] { + assert!( + !src.contains("COMPLETE plan again"), + "a send-back asks for the changed files only" + ); + } +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 0c6d4782c..c1627b553 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -57,6 +57,7 @@ mod bn_infra_list_follows_aws; mod bp_repo_traced_not_asked; mod bq_upstream_read_not_guessed; mod br_description_writer_upgrade; +mod bs_cut_plan_revision; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 9e4d8be11..25a54af27 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1334,6 +1334,7 @@ pub mod plan_chat; pub(crate) mod plan_coverage; pub mod plan_execute; mod plan_judge; +pub(crate) mod plan_sections; /// Plugin runs, publishing, source sync and results. pub mod plugins; mod pr; @@ -3355,19 +3356,13 @@ async fn run_passes( fix_route, fix_location::Route::OutsideOnly | fix_location::Route::Ask )); - if !plan_is_directive - && (plan_result.tasks.trim().is_empty() || plan_result.design.trim().is_empty()) - { - warn!( - run_id, - "Plan generation produced empty tasks/design — failing run" - ); + // A plan the planner couldn't complete, even after it was asked for + // just the missing files (see `plan_sections`), is planned again in a + // fresh step, and only then reported, as CoderHelm's own failure. + if let Some(why) = plan_sections::unusable(&plan_result).filter(|_| !plan_is_directive) { + warn!(run_id, why = %why, "Plan not usable after its repairs"); close_memory(state, agent_memory.take()).await; - return Err( - "Plan generation produced an empty or malformed plan (missing tasks/design). \ - This is usually a transient model formatting issue — retry the run." - .into(), - ); + return plan_again_or_stop(state, msg, run_id, &mut ps, &why).await; } // Not knowing where the fix belongs is a question only when a person @@ -3438,11 +3433,15 @@ async fn run_passes( "Plan has no decision and nothing to decide from — planner failure" ); close_memory(state, agent_memory.take()).await; - return Err( - "Planner failure: the plan carried no fix_location decision and its tasks name \ - no files to decide from. Nothing was asked of a person; retry the run." - .into(), - ); + return plan_again_or_stop( + state, + msg, + run_id, + &mut ps, + "the plan carried no decision on where the fix belongs and its tasks name no \ + files to decide from", + ) + .await; }; if decision.cause.trim().is_empty() { // A plan that codes nothing but wrote no decision: its one line @@ -3709,12 +3708,11 @@ async fn run_passes( .await?; if plan_result.tasks.starts_with("CLARIFICATION_NEEDED:") { close_memory(state, agent_memory.take()).await; - return Err(format!( - "Planner failure: the plan asked again after planning on the assumption \"{}\". \ - Nothing was asked of a person; retry the run.", + let why = format!( + "the plan asked again after planning on the assumption \"{}\"", judged.assumption().unwrap_or("") - ) - .into()); + ); + return plan_again_or_stop(state, msg, run_id, &mut ps, &why).await; } } } @@ -7270,6 +7268,60 @@ fn stopped_keeping(why: &str, kept: &str) -> String { format!("{why} The work so far is kept on branch `{kept}`.") } +/// A plan that is not usable (see `plan_sections::unusable`) after the +/// planner was asked for its missing files: planning starts again in a +/// fresh step, up to `steps::MAX_PLAN_RETRIES` times, from nothing but +/// the ticket. After that, or when no step can be queued, the run ends on +/// CoderHelm's own failure, saying what the plan lacked; never on an +/// instruction to a person. +async fn plan_again_or_stop( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + ps: &mut steps::PlanState, + why: &str, +) -> Result<(), Box> { + if !ps.may_plan_again() { + return Err(plan_failure(why, None).into()); + } + ps.plan_retries = ps.plan_retries.saturating_add(1); + ps.checked = false; + steps::save_plan(state, &msg.team_id, run_id, ps).await; + plan::unmark_plan_run(state, msg).await; + match try_auto_continue( + state, + msg, + run_id, + &None, + &[], + true, + &format!("Plan check (format): {why}; planning again"), + ) + .await + { + Handoff::Continued => Ok(()), + Handoff::Stopped(reason) => Err(plan_failure(why, Some(&reason)).into()), + } +} + +/// The run's error when it has no usable plan: what the plan lacked and +/// what CoderHelm already did about it, as CoderHelm's own failure. +pub(crate) fn plan_failure(why: &str, no_step: Option<&str>) -> String { + let tried = match no_step { + Some(reason) => format!( + "after asking the planner again for what was missing; it couldn't plan again in a \ + fresh step ({reason})" + ), + None => "after asking the planner again for what was missing and planning again in a \ + fresh step" + .to_string(), + }; + format!( + "CoderHelm couldn't write a usable plan for this ticket: {why}, {tried}. This is \ + CoderHelm's own failure, not the ticket's." + ) +} + /// Continue the run in a fresh step at `gate`, with the branch as it is: /// the checkpoint names the gate (and what the skipped stages carry), and a /// new message starts the next step. Only a run that can't continue (the diff --git a/services/worker/src/passes/model_route_eval.rs b/services/worker/src/passes/model_route_eval.rs index c5978454b..9666799bf 100644 --- a/services/worker/src/passes/model_route_eval.rs +++ b/services/worker/src/passes/model_route_eval.rs @@ -983,6 +983,7 @@ async fn route_implement_live() { None, None, None, + crate::agent::llm::AnswerForm::Auto, ) .await .map_err(|e| e.to_string()); diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 5383a05f5..61eff2771 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -13,7 +13,7 @@ use crate::WorkerState; /// any change to how plans are made or what a plan must carry, so a plan /// written by an older planner is never reused. pub const PLANNER_VERSION: &str = - "2026-11-13.intent-history-env-near-match-stop-rules-data-rules-cross-repo-asking-reproduce-decision-reask-series-habits"; + "2026-11-15.intent-history-env-near-match-stop-rules-data-rules-cross-repo-asking-reproduce-decision-reask-series-habits-sections"; /// The openspec file holding the plan's end-to-end checklist, readable. pub const END_TO_END_FILE: &str = "end_to_end.md"; @@ -46,6 +46,16 @@ const OUTSIDE_TOOLS: &[&str] = &[ ]; pub async fn mark_plan_run(state: &WorkerState, msg: &TicketMessage, run_id: &str) { + write_plan_run(state, msg, run_id).await +} + +/// The cached plan belongs to no run: the run's next step plans again +/// instead of taking up a plan that was not usable. +pub async fn unmark_plan_run(state: &WorkerState, msg: &TicketMessage) { + write_plan_run(state, msg, "").await +} + +async fn write_plan_run(state: &WorkerState, msg: &TicketMessage, run_id: &str) { let prefix = crate::passes::openspec_prefix( &msg.team_id, &msg.ticket_id, @@ -114,33 +124,91 @@ pub fn review_draft(files: &PlanResult) -> String { } /// What the planner is told after the review: the notes as advice, and to -/// answer with the whole plan again. +/// answer with only the files the notes change (see +/// `common::run_questions::CHANGED_FILES_ONLY`). pub fn revision_prompt(advice: &str) -> String { format!( "{advice}\n\nRevise your plan once with these notes: change it only where a note points \ - to a real gap for this change. Then output the COMPLETE plan again in exactly the same \ - format as before (every file block, the fix decision included), not just the changes." + to a real gap for this change. {}", + common::run_questions::CHANGED_FILES_ONLY ) } -/// The revised plan when it parsed into a plan, else the draft. The +/// The draft with the revision's files over it (see `plan_sections::merge`): +/// a file the revision wrote in full replaces the draft's, anything else +/// keeps the draft's. A revision that turns the plan into a directive +/// (nothing needed, a question) is not taken from a review's notes. The /// decision on where the fix belongs stays the draft's: it was checked -/// against the planner's trace, and a review doesn't move it. -pub fn take_revision(draft: PlanResult, revised: PlanResult) -> (PlanResult, bool) { - let lost_design = revised.design.trim().is_empty() && !draft.design.trim().is_empty(); - if !reviewable(&revised) || lost_design { +/// against the planner's trace, and a review doesn't move it. True when the +/// revision changed a file. +pub fn take_revision( + draft: PlanResult, + text: &str, + intent: super::triage::TicketIntent, +) -> (PlanResult, bool) { + use super::plan_sections::{read, valid, State, FILES}; + let answer = read(text); + let wrote = |n: &str| answer.state(n) == State::Complete && valid(n, answer.complete(n)); + if wrote("tasks.md") && super::plan_sections::directive(answer.complete("tasks.md")) { return (draft, false); } - ( - PlanResult { - fix: draft.fix, - ..revised - }, - true, - ) + let took = FILES.iter().any(|n| wrote(n)); + let fix = draft.fix.clone(); + let (mut out, _) = super::plan_sections::merge(draft, plan_of(&answer, intent), &answer); + out.fix = fix; + (out, took) +} + +/// Reads a revision's reply over the plan before it (see +/// `plan_sections::merge`): a reply that failed, or came back empty, cut +/// off or malformed, never replaces a valid file. `answer` becomes the +/// reply's own blocks. +fn revise( + files: &mut PlanResult, + answer: &mut super::plan_sections::Answer, + reply: Result>, + intent: super::triage::TicketIntent, + ticket_id: &str, + what: &str, +) { + let text = match reply { + Ok(t) => t, + Err(e) => { + warn!(ticket_id = %ticket_id, error = %e, what, "Plan revision failed; the plan before it stands"); + return; + } + }; + let read = super::plan_sections::read(&text); + let revised = plan_of(&read, intent); + let (merged, lost) = super::plan_sections::merge(std::mem::take(files), revised, &read); + if !lost.is_empty() { + warn!(ticket_id = %ticket_id, files = ?lost, what, "Plan revision lost files (cut off or empty); the earlier ones stand"); + } + *files = merged; + *answer = read; +} + +/// A repair's options: the planner's own, a few turns to finish the files +/// (a cut file continues where it stopped); the second repair with twice +/// the output budget and more effort. +fn repair_opts(plan_opts: llm::ConverseOptions, repair: u32) -> llm::ConverseOptions { + if repair <= 1 { + llm::ConverseOptions { + max_turns: 3, + ..plan_opts + } + } else { + llm::ConverseOptions { + max_turns: 3, + max_tokens: plan_opts.max_tokens.saturating_mul(2), + effort: Some("xhigh"), + ..plan_opts + } + } } /// Result of the plan pass: the four openspec files. +#[derive(Clone, Default)] pub struct PlanResult { pub proposal: String, pub design: String, @@ -785,7 +853,7 @@ Then the ```fix_location.json block described above."#, let model_id = provider.judgment_model_id(); let can_look_up = live.as_ref().is_some_and(|l| !l.tools().is_empty()); let lookups = || live.as_ref().map_or(0, |l| l.lookups_made()); - let mut response = provider::converse( + let response = provider::converse_document( state, provider, common::agent_policy::Agent::Planner, @@ -796,8 +864,6 @@ Then the ```fix_location.json block described above."#, &executor, usage, plan_opts, - None, - None, ) .await?; // A decision about data that skipped part of the trace (no lookups, no @@ -810,7 +876,8 @@ Then the ```fix_location.json block described above."#, .map(|r| r.clone()) .unwrap_or_default() }; - let draft = parse_openspec_files(&response, intent); + let mut answer = super::plan_sections::read(&response); + let draft = plan_of(&answer, intent); info!( ticket_id = %msg.ticket_id, consulted = ?executor.read_only.consulted.repos(), @@ -892,6 +959,10 @@ Then the ```fix_location.json block described above."#, super::plan_file_gaps(github, &msg.repo_owner, &msg.repo_name, &draft.tasks).await, ); } + // The plan as it stands: the draft, then each revision over it (see + // `plan_sections::merge`). A revision that comes back empty, cut off or + // malformed never replaces a file of a valid plan. + let mut files = draft.clone(); if !back.is_empty() { info!( ticket_id = %msg.ticket_id, @@ -905,32 +976,31 @@ Then the ```fix_location.json block described above."#, serde_json::json!({"type": "text", "text": super::fix_location::send_back(&back)}), ], )); - response = provider::converse( - state, - provider, - common::agent_policy::Agent::Planner, - model_id, - &full_system, - &mut messages, - &tools, - &executor, - usage, - plan_opts, - None, - None, - ) - .await?; + revise( + &mut files, + &mut answer, + provider::converse_document( + state, + provider, + common::agent_policy::Agent::Planner, + model_id, + &full_system, + &mut messages, + &tools, + &executor, + usage, + plan_opts, + ) + .await, + intent, + &msg.ticket_id, + "plan check", + ); } if let Some(s) = &skills { s.drain_usage_into(usage); } - let mut files = parse_openspec_files(&response, intent); - // A plan that asks what is settled on the ticket (answers given in - // CoderHelm, choices people made on its notices), or what CoderHelm - // decides itself, goes back once with the answers (the model judges - // each question against them, see `resolved`). What it still asks - // after that is filtered below. let asked = clarification_of(&files.tasks); let verdicts = super::resolved::judge(state, provider, &asked, &msg.answers, usage).await; let repeats: Vec<(common::run_questions::Question, super::resolved::Verdict)> = asked @@ -952,22 +1022,26 @@ Then the ```fix_location.json block described above."#, "text": super::resolved::send_back(&repeats, &msg.answers), })], )); - response = provider::converse( - state, - provider, - common::agent_policy::Agent::Planner, - model_id, - &full_system, - &mut messages, - &tools, - &executor, - usage, - plan_opts, - None, - None, - ) - .await?; - files = parse_openspec_files(&response, intent); + revise( + &mut files, + &mut answer, + provider::converse_document( + state, + provider, + common::agent_policy::Agent::Planner, + model_id, + &full_system, + &mut messages, + &tools, + &executor, + usage, + plan_opts, + ) + .await, + intent, + &msg.ticket_id, + "settled questions", + ); } // The stop rules (see stop_gate): a question about the run's own // tooling is never asked, one resting on a difference between @@ -1005,22 +1079,26 @@ Then the ```fix_location.json block described above."#, "text": common::stop_rules::screen::send_back(&s, diagnosis.as_ref()), })], )); - response = provider::converse( - state, - provider, - common::agent_policy::Agent::Planner, - model_id, - &full_system, - &mut messages, - &tools, - &executor, - usage, - plan_opts, - None, - None, - ) - .await?; - files = parse_openspec_files(&response, intent); + revise( + &mut files, + &mut answer, + provider::converse_document( + state, + provider, + common::agent_policy::Agent::Planner, + model_id, + &full_system, + &mut messages, + &tools, + &executor, + usage, + plan_opts, + ) + .await, + intent, + &msg.ticket_id, + "stop rules", + ); let again = clarification_of(&files.tasks); if !again.is_empty() { let s = super::stop_gate::screen_questions( @@ -1067,13 +1145,86 @@ Then the ```fix_location.json block described above."#, } } } + // Files still missing or cut off after the send-backs (the output limit, + // a revision that wrote only its last block): the planner is asked for + // just those files, at most `plan_sections::MAX_REPAIRS` times, the + // second with twice the output budget and more effort. Each answer is + // read file by file and merged; a valid file is never replaced by a + // worse one. + let mut repairs: u32 = 0; + let mut repaired: Vec<&'static str> = Vec::new(); + while repairs < super::plan_sections::MAX_REPAIRS { + let names = super::plan_sections::to_repair(&files); + if names.is_empty() { + break; + } + repairs += 1; + warn!( + ticket_id = %msg.ticket_id, + files = ?names, + repair = repairs, + "Plan files missing or cut off — asking the planner for just those" + ); + for n in &names { + if !repaired.contains(n) { + repaired.push(n); + } + } + messages.push(( + "user".to_string(), + vec![serde_json::json!({ + "type": "text", + "text": super::plan_sections::repair_prompt(&names, &answer), + })], + )); + let opts = repair_opts(plan_opts, repairs); + revise( + &mut files, + &mut answer, + provider::converse_document( + state, + provider, + common::agent_policy::Agent::Planner, + model_id, + &full_system, + &mut messages, + &tools, + &executor, + usage, + opts, + ) + .await, + intent, + &msg.ticket_id, + "repair", + ); + } + if repairs > 0 { + let left = super::plan_sections::missing(&files); + let outcome = if left.is_empty() { + "got them".to_string() + } else { + format!("still missing {}", left.join(", ")) + }; + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Plan check (format): {} missing or cut off; asked the planner for just those \ + ({repairs} time(s)): {outcome}.", + repaired.join(", ") + ), + ) + .await; + } // A plan whose answer carried no decision that reads is a format // failure, never a question for a person: the planner is asked once // more for only the block (one small call, no tools), and when that // still gives none, the plan itself decides (see `fix_location::fallback`). let mut block_failure: Option = None; if files.fix.is_none() && needs_decision(&files.tasks) { - let problem = match super::fix_location::parse_detailed(&response) { + let problem = match super::fix_location::parse_detailed(&answer.decision_text()) { Err(p) => p, Ok(_) => super::fix_location::BlockProblem::Missing, }; @@ -1184,11 +1335,10 @@ Then the ```fix_location.json block described above."#, files.fix = Some(d); } None => { - return Err(format!( - "Planner failure: {line}, and the plan has no tasks to decide from. \ - Nothing was asked of a person; retry the run." - ) - .into()); + // No decision and no tasks to decide from: the plan is not + // usable, and the run plans again in a fresh step (see + // `plan_sections::unusable` where the run reads it). + warn!(ticket_id = %msg.ticket_id, problem = %line, "Plan has no decision and no tasks to decide from"); } } } @@ -1358,7 +1508,7 @@ Then the ```fix_location.json block described above."#, effort: Some(super::skills::review_effort("plan")), ..plan_opts }; - match provider::converse( + match provider::converse_document( state, provider, common::agent_policy::Agent::Planner, @@ -1369,14 +1519,11 @@ Then the ```fix_location.json block described above."#, &executor, usage, one_turn, - None, - None, ) .await { Ok(text) => { - let (kept, took) = - take_revision(files, parse_openspec_files(&text, intent)); + let (kept, took) = take_revision(files.clone(), &text, intent); files = kept; revised = took; if !took { @@ -1804,45 +1951,39 @@ fn with_questions(proposal: &str, d: &super::fix_location::FixDecision) -> Strin /// The proposal's heading for what only a person can answer. const QUESTIONS_HEADING: &str = "## Questions only a person can answer"; +/// The plan in an answer: each openspec file the answer wrote in full (a +/// file cut off before its fence closed reads as empty, never as complete; +/// see `plan_sections`), and the decision block. +#[cfg(test)] fn parse_openspec_files(response: &str, intent: super::triage::TicketIntent) -> PlanResult { - let filenames = ["proposal.md", "design.md", "tasks.md", "spec.md"]; - let mut contents: Vec = Vec::new(); - - for filename in &filenames { - let marker = format!("```{filename}"); - if let Some(start) = response.find(&marker) { - let content_start = response[start..] - .find('\n') - .map(|i| start + i + 1) - .unwrap_or(start); - let end = response[content_start..] - .find("```") - .map(|i| content_start + i) - .unwrap_or(response.len()); - contents.push(response[content_start..end].trim().to_string()); - } else { - contents.push(String::new()); - } - } - - let tasks_content = contents[2].clone(); - let repo_tasks = parse_repo_tasks(&tasks_content); + plan_of(&super::plan_sections::read(response), intent) +} +fn plan_of( + answer: &super::plan_sections::Answer, + intent: super::triage::TicketIntent, +) -> PlanResult { + let tasks = answer.complete("tasks.md").to_string(); PlanResult { - proposal: contents.remove(0), - design: contents.remove(0), - tasks: contents.remove(0), - spec: contents.remove(0), - repo_tasks, + proposal: answer.complete("proposal.md").to_string(), + design: answer.complete("design.md").to_string(), + repo_tasks: parse_repo_tasks(&tasks), + tasks, + spec: answer.complete("spec.md").to_string(), // A doubt asked early is one of the decision's questions from the // start, so every check of them reads it (see habits). - fix: super::fix_location::parse_for(response, intent).map(|mut d| { + fix: super::fix_location::parse_for(&answer.decision_text(), intent).map(|mut d| { super::habits::fold_questions(&mut d); d }), } } +/// The per-repo task breakdown of a task list (see [`parse_repo_tasks`]). +pub(super) fn repo_tasks_of(tasks: &str) -> Vec { + parse_repo_tasks(tasks) +} + /// Parse `## owner/repo` headers in tasks.md for multi-repo support. /// Returns empty vec if no repo headers found (single-repo mode). fn parse_repo_tasks(tasks: &str) -> Vec { @@ -2452,23 +2593,54 @@ mod plan_review_tests { #[test] fn a_revision_that_doesnt_parse_keeps_the_draft() { let draft = plan("- [ ] 1. Add the path"); - let (kept, took) = take_revision( - draft, - parse_openspec_files("Sorry, here are my thoughts.", Default::default()), - ); + let (kept, took) = take_revision(draft, "Sorry, here are my thoughts.", Default::default()); assert!(!took); assert_eq!(kept.tasks, "- [ ] 1. Add the path"); let revised = "```proposal.md\nAdd a rollback path, tested\n```\n```design.md\nD2\n```\n\ ```tasks.md\n- [ ] 1. Add the path\n- [ ] 2. Test the rollback\n```\n\ ```spec.md\nS2\n```"; + let (kept, took) = + take_revision(plan("- [ ] 1. Add the path"), revised, Default::default()); + assert!(took); + assert!(kept.tasks.contains("Test the rollback")); + assert!(revision_prompt("## notes").contains("only the openspec files your changes touch")); + } + + #[test] + fn a_revision_of_one_file_keeps_the_others() { + // The notes changed only the tasks: the design, proposal and spec + // stay the draft's, and the decision stays the draft's. + let mut draft = plan("- [ ] 1. Add the path"); + draft.fix = Some(crate::passes::fix_location::FixDecision { + cause: "draft".into(), + ..Default::default() + }); let (kept, took) = take_revision( - plan("- [ ] 1. Add the path"), - parse_openspec_files(revised, Default::default()), + draft, + "```tasks.md\n- [ ] 1. Add the path\n- [ ] 2. Test it\n```\n```fix_location.json\n{\"fix_location\":\"code\",\"cause\":\"moved\"}\n```", + Default::default(), ); assert!(took); - assert!(kept.tasks.contains("Test the rollback")); - assert!(revision_prompt("## notes").contains("COMPLETE plan again")); + assert!(kept.tasks.contains("Test it")); + assert_eq!(kept.proposal, "Add a rollback path"); + assert_eq!(kept.fix.unwrap().cause, "draft"); + // A revision cut off in its only file changes nothing. + let (kept, took) = take_revision( + plan("- [ ] 1. Add the path"), + "```tasks.md\n- [ ] 1. Add the path\n- [ ] 2. Te", + Default::default(), + ); + assert!(!took); + assert_eq!(kept.tasks, "- [ ] 1. Add the path"); + // Nor does one that turns the plan into "nothing needed". + let (kept, took) = take_revision( + plan("- [ ] 1. Add the path"), + "```tasks.md\nNO_CHANGES_NEEDED: done\n```", + Default::default(), + ); + assert!(!took); + assert_eq!(kept.tasks, "- [ ] 1. Add the path"); } #[test] diff --git a/services/worker/src/passes/plan_sections.rs b/services/worker/src/passes/plan_sections.rs new file mode 100644 index 000000000..4799003cd --- /dev/null +++ b/services/worker/src/passes/plan_sections.rs @@ -0,0 +1,432 @@ +//! The planner's answer, read file by file. +//! +//! A run once lost a good plan to one cut answer. The plan check sent the +//! plan back with two open items; the planner's revision reached the output +//! limit partway through its last block, wrote only that block again on the +//! next turn ("the four files above are unchanged"), and the worker read +//! only that last turn: no tasks, no design, and the run failed telling the +//! person to retry it. +//! +//! Now the answer is read per block: +//! +//! - [`read`]: every known block in the text (the four openspec files and +//! the decision), each the last one written in full; a block whose fence +//! never closed, or that a new block of a known name interrupted, is cut +//! and never read as complete. +//! - [`merge`]: a revision replaces only the files it wrote in full; a file +//! it left out, cut or wrote empty keeps the last valid one. A revision +//! never empties a valid plan. +//! - [`missing`]: what a usable plan still lacks, file by file, for a repair +//! that asks for just those files. +//! - [`unusable`]: why a plan can't be built from, in a sentence, or `None`. + +use super::plan::PlanResult; + +/// The openspec files, in the order a plan writes them. +pub const FILES: [&str; 4] = ["proposal.md", "design.md", "tasks.md", "spec.md"]; + +/// The decision block's fence name. +pub const DECISION: &str = "fix_location.json"; + +const NAMES: [&str; 5] = [FILES[0], FILES[1], FILES[2], FILES[3], DECISION]; + +/// Repairs of missing files asked of the planner before the plan is +/// judged unusable (the second at a higher effort). +pub const MAX_REPAIRS: u32 = 2; + +/// How a block stands in an answer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum State { + Missing, + /// Its fence opened and never closed (the output limit, usually). + Cut, + Complete, +} + +/// The known blocks of one answer: for each name, the last block written in +/// full, else the last cut one. +#[derive(Clone, Debug, Default)] +pub struct Answer { + blocks: Vec<(&'static str, State, String)>, +} + +impl Answer { + pub fn state(&self, name: &str) -> State { + self.blocks + .iter() + .find(|(n, _, _)| *n == name) + .map_or(State::Missing, |(_, s, _)| *s) + } + + /// The block's text when it was written in full, else empty. + pub fn complete(&self, name: &str) -> &str { + self.blocks + .iter() + .find(|(n, s, _)| *n == name && *s == State::Complete) + .map_or("", |(_, _, b)| b.trim()) + } + + /// The decision block as the decision's own parser reads it: closed + /// when it was written in full, open when it was cut, absent when + /// missing. + pub fn decision_text(&self) -> String { + match self.blocks.iter().find(|(n, _, _)| *n == DECISION) { + Some((_, State::Complete, b)) => format!("```{DECISION}\n{}\n```", b.trim()), + Some((_, _, b)) => format!("```{DECISION}\n{}", b.trim()), + None => String::new(), + } + } + + fn set(&mut self, name: &'static str, state: State, body: String) { + // A complete block is never replaced by a later cut one. + match self.blocks.iter_mut().find(|(n, _, _)| *n == name) { + Some(slot) if state == State::Complete || slot.1 != State::Complete => { + *slot = (name, state, body) + } + Some(_) => {} + None => self.blocks.push((name, state, body)), + } + } +} + +/// The known block a fence line opens, if any: "```tasks.md". +fn opens(line: &str) -> Option<&'static str> { + let rest = line.trim().strip_prefix("```")?.trim(); + NAMES.iter().copied().find(|n| *n == rest) +} + +/// Reads every known block in an answer. Inside a block, a fence with a +/// language (```ts) opens a nested code block and a bare ``` closes it; a +/// bare ``` with nothing nested closes the block. +pub fn read(text: &str) -> Answer { + let mut out = Answer::default(); + let mut open: Option<(&'static str, Vec<&str>, usize)> = None; + for line in text.lines() { + if let Some(name) = opens(line) { + if let Some((prev, body, _)) = open.take() { + out.set(prev, State::Cut, body.join("\n")); + } + open = Some((name, Vec::new(), 0)); + continue; + } + let Some((name, body, depth)) = open.as_mut() else { + continue; + }; + let t = line.trim(); + if t == "```" { + if *depth == 0 { + let (name, body) = (*name, body.join("\n")); + open = None; + out.set(name, State::Complete, body); + continue; + } + *depth -= 1; + } else if t.starts_with("```") { + *depth += 1; + } else if *depth == 0 && t.ends_with("```") { + // The closing fence written on the last line of the block. + let (name, mut body) = (*name, body.clone()); + body.push(line.trim_end().trim_end_matches('`')); + open = None; + out.set(name, State::Complete, body.join("\n")); + continue; + } + body.push(line); + } + if let Some((name, body, _)) = open { + out.set(name, State::Cut, body.join("\n")); + } + out +} + +/// Tasks that are an answer in themselves: nothing to change, a question, +/// or a fix outside the code. +pub fn directive(tasks: &str) -> bool { + let t = tasks.trim_start(); + t.starts_with("NO_CHANGES_NEEDED") + || t.starts_with("CLARIFICATION_NEEDED") + || t.starts_with(super::fix_location::NO_CODE_CHANGE) +} + +/// Whether one file of a plan is usable as written: not empty, and a task +/// list holds at least one task (or is a directive). +pub fn valid(name: &str, body: &str) -> bool { + let b = body.trim(); + if b.is_empty() { + return false; + } + if name == "tasks.md" { + return directive(b) || b.lines().any(|l| l.trim_start().starts_with("- [")); + } + true +} + +fn file(p: &PlanResult, name: &str) -> String { + match name { + "proposal.md" => p.proposal.clone(), + "design.md" => p.design.clone(), + "tasks.md" => p.tasks.clone(), + _ => p.spec.clone(), + } +} + +fn set_file(p: &mut PlanResult, name: &str, body: String) { + match name { + "proposal.md" => p.proposal = body, + "design.md" => p.design = body, + "tasks.md" => p.tasks = body, + _ => p.spec = body, + } +} + +/// The files a plan of work must have before it is built: the proposal, +/// the design and the tasks (the spec is asked for, never required). A +/// directive needs only its tasks. +pub fn missing(p: &PlanResult) -> Vec<&'static str> { + if directive(&p.tasks) { + return Vec::new(); + } + ["proposal.md", "design.md", "tasks.md"] + .into_iter() + .filter(|n| !valid(n, &file(p, n))) + .collect() +} + +/// The files a repair asks for: the required ones [`missing`] names, and +/// the spec when it is empty too. +pub fn to_repair(p: &PlanResult) -> Vec<&'static str> { + let mut out = missing(p); + if !out.is_empty() && p.spec.trim().is_empty() { + out.push("spec.md"); + } + out +} + +/// Why a plan can't be built from, in a sentence; `None` when it can. +pub fn unusable(p: &PlanResult) -> Option { + let m = missing(p); + if m.is_empty() { + return None; + } + Some(format!( + "the plan has no usable {}", + m.iter() + .map(|n| format!("`{n}`")) + .collect::>() + .join(", ") + )) +} + +/// A revision over the plan before it. Each file is the revision's when +/// it wrote that file in full and it is valid, else the earlier plan's: +/// a file the revision left out, cut off or wrote empty stays as it was. +/// The decision is the revision's when it wrote one that reads. The names +/// of the files kept from before because the revision lost them (cut or +/// empty, not merely left out) come back with it. +pub fn merge( + prev: PlanResult, + revised: PlanResult, + answer: &Answer, +) -> (PlanResult, Vec<&'static str>) { + let mut out = revised; + let mut lost = Vec::new(); + for name in FILES { + let new = file(&out, name); + if valid(name, &new) { + continue; + } + let old = file(&prev, name); + // A directive's tasks stand alone: the earlier tasks never come back + // under it, and its empty files stay empty. + if directive(&out.tasks) && name != "tasks.md" { + continue; + } + if valid(name, &old) || (name == "spec.md" && !old.trim().is_empty()) { + if answer.state(name) != State::Missing || !new.trim().is_empty() { + lost.push(name); + } + set_file(&mut out, name, old); + } + } + out.repo_tasks = super::plan::repo_tasks_of(&out.tasks); + if out.fix.is_none() { + out.fix = prev.fix; + } + (out, lost) +} + +/// What the planner is asked when files are missing from its plan: only +/// those files, each whole in its own fence. +pub fn repair_prompt(names: &[&str], answer: &Answer) -> String { + let list = names + .iter() + .map(|n| { + let why = match answer.state(n) { + State::Cut => "was cut off before its fence closed", + State::Complete => "has no usable content (a task list needs `- [ ]` tasks)", + State::Missing => "is missing", + }; + format!("- `{n}` {why}") + }) + .collect::>() + .join("\n"); + format!( + "Your plan is not complete yet:\n{list}\n\nWrite only these files now, each whole in \ + its own fence (```name ... ```), in the same format as before, and nothing else: no \ + other file, no decision block, no notes. Keep each one short; the files not listed are \ + kept as they are." + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plan(tasks: &str) -> PlanResult { + PlanResult { + proposal: "P".into(), + design: "D".into(), + tasks: tasks.into(), + spec: "S".into(), + repo_tasks: vec![], + fix: None, + } + } + + const FULL: &str = "```proposal.md\nP1\n```\n```design.md\nD1\n```\n```tasks.md\n- [ ] a.ts: [modify] A\n```\n```spec.md\nS1\n```\n```fix_location.json\n{\"fix_location\":\"code\"}\n```"; + + #[test] + fn every_block_is_read_whole() { + let a = read(FULL); + for n in NAMES { + assert_eq!(a.state(n), State::Complete, "{n}"); + } + assert_eq!(a.complete("tasks.md"), "- [ ] a.ts: [modify] A"); + assert!(a.decision_text().ends_with("\n```")); + } + + #[test] + fn a_nested_code_block_stays_inside_its_file() { + let a = read("```design.md\nUse this:\n```ts\nconst a = 1;\n```\nThen that.\n```\n"); + assert_eq!(a.state("design.md"), State::Complete); + assert_eq!( + a.complete("design.md"), + "Use this:\n```ts\nconst a = 1;\n```\nThen that." + ); + } + + #[test] + fn a_cut_block_is_never_complete() { + // Cut at the end of the text. + let a = read("```proposal.md\nP\n```\n```tasks.md\n- [ ] a.ts: [mod"); + assert_eq!(a.state("proposal.md"), State::Complete); + assert_eq!(a.state("tasks.md"), State::Cut); + assert_eq!(a.complete("tasks.md"), ""); + // Cut by a block of a known name written again from its start: the + // later, whole one counts. + let a = read( + "```fix_location.json\n{\"cause\": \"New woMy last answer was cut.\n```fix_location.json\n{\"fix_location\":\"both\"}\n```", + ); + assert_eq!(a.state(DECISION), State::Complete); + assert_eq!(a.complete(DECISION), "{\"fix_location\":\"both\"}"); + // A whole block is never replaced by a later cut one. + let a = read("```spec.md\nS\n```\n```spec.md\nS2 cut"); + assert_eq!(a.complete("spec.md"), "S"); + assert_eq!(read("no fences").state("tasks.md"), State::Missing); + // A fence closed on the block's last line still closes it. + let a = read("```tasks.md\n- [ ] a.ts: [modify] A```\n"); + assert_eq!(a.complete("tasks.md"), "- [ ] a.ts: [modify] A"); + } + + #[test] + fn a_task_list_needs_tasks() { + assert!(valid("tasks.md", "- [ ] a.ts: [modify] A")); + assert!(valid("tasks.md", "NO_CHANGES_NEEDED: already there")); + assert!(valid( + "tasks.md", + "CLARIFICATION_NEEDED:\n- question: which?" + )); + assert!(!valid("tasks.md", "I will now write the tasks.")); + assert!(!valid("design.md", " ")); + assert!(valid("design.md", "D")); + } + + #[test] + fn missing_names_each_required_file() { + assert!(missing(&plan("- [ ] a.ts: [modify] A")).is_empty()); + let mut p = plan(""); + p.design.clear(); + p.spec.clear(); + assert_eq!(missing(&p), vec!["design.md", "tasks.md"]); + assert_eq!(to_repair(&p), vec!["design.md", "tasks.md", "spec.md"]); + assert_eq!( + unusable(&p).unwrap(), + "the plan has no usable `design.md`, `tasks.md`" + ); + // A directive needs nothing else. + let mut d = plan("NO_CHANGES_NEEDED: done"); + d.design.clear(); + assert!(unusable(&d).is_none()); + } + + #[test] + fn a_revision_never_empties_a_valid_plan() { + let prev = plan("- [ ] a.ts: [modify] A"); + // The revision wrote only its decision, after a cut. + let text = "```fix_location.json\n{\"fix_location\":\"code\"}\n```"; + let a = read(text); + let revised = PlanResult { + proposal: String::new(), + design: String::new(), + tasks: String::new(), + spec: String::new(), + repo_tasks: vec![], + fix: None, + }; + let (out, lost) = merge(prev, revised, &a); + assert_eq!(out.tasks, "- [ ] a.ts: [modify] A"); + assert_eq!(out.design, "D"); + assert!(lost.is_empty(), "left out is not lost: {lost:?}"); + + // A revision that changes only the tasks keeps the rest. + let prev = plan("- [ ] a.ts: [modify] A"); + let mut revised = plan("- [ ] a.ts: [modify] A\n- [ ] b.ts: [create] B"); + revised.design.clear(); + revised.proposal.clear(); + revised.spec.clear(); + let a = read("```tasks.md\n- [ ] a.ts: [modify] A\n- [ ] b.ts: [create] B\n```"); + let (out, _) = merge(prev, revised, &a); + assert!(out.tasks.contains("b.ts")); + assert_eq!(out.design, "D"); + + // A cut file is lost and named; the earlier one stands. + let prev = plan("- [ ] a.ts: [modify] A"); + let mut revised = plan(""); + revised.design.clear(); + let a = read("```design.md\nD2 cut"); + let (out, lost) = merge(prev, revised, &a); + assert_eq!(out.design, "D"); + assert_eq!(lost, vec!["design.md"]); + } + + #[test] + fn a_directive_revision_stands_alone() { + let prev = plan("- [ ] a.ts: [modify] A"); + let mut revised = plan("NO_CHANGES_NEEDED: already in place"); + revised.design.clear(); + let a = read("```tasks.md\nNO_CHANGES_NEEDED: already in place\n```"); + let (out, _) = merge(prev, revised, &a); + assert!(out.tasks.starts_with("NO_CHANGES_NEEDED")); + assert_eq!(out.design, ""); + } + + #[test] + fn a_repair_asks_for_only_the_missing_files() { + let a = read("```tasks.md\n- [ ] a.ts: [mod"); + let p = repair_prompt(&["design.md", "tasks.md"], &a); + assert!(p.contains("`design.md` is missing")); + assert!(p.contains("`tasks.md` was cut off")); + assert!(p.contains("Write only these files")); + assert!(!p.contains("edit_file")); + } +} diff --git a/services/worker/src/passes/resolved.rs b/services/worker/src/passes/resolved.rs index 6ea33bea5..4f311261d 100644 --- a/services/worker/src/passes/resolved.rs +++ b/services/worker/src/passes/resolved.rs @@ -263,9 +263,9 @@ pub fn send_back(asked: &[(Question, Verdict)], settled: &[Answer]) -> String { } out.push_str( "Plan with what is settled now. Use CLARIFICATION_NEEDED only for something still \ - open, asking about that alone. Output the COMPLETE plan again in exactly the same \ - format as before (every file block, the fix decision included).", + open, asking about that alone. ", ); + out.push_str(common::run_questions::CHANGED_FILES_ONLY); out } diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index c1710b597..3e041a17e 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -1116,6 +1116,7 @@ pub(super) async fn live_review_in_repo( None, None, None, + crate::agent::llm::AnswerForm::Auto, ) .await .map_err(|e| format!("the review call failed: {e}"))?; diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index e02f87cc6..cbb79c2b5 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -4649,7 +4649,10 @@ async fn refresh_ci_sections(cx: &Ctx<'_>, repo: &str, number: u64, ticket: &str /// the base branch), "What to check" and Proof (where CI stands on this /// head). The rest (the draft status at its top, the run's words) stays. /// `None` for a pull request that is not a dependency fix's. Saved by -/// `description::reconcile`, the only caller. +/// `description::reconcile`, the only caller. `fresh`: the catch-up after +/// an upgrade, on a description wholly CoderHelm's: nothing of the old +/// body is kept but the lines that close an issue ([`fresh_body`]). +#[allow(clippy::too_many_arguments)] pub(crate) async fn at_head( state: &WorkerState, gh: &GitHubClient, @@ -4658,6 +4661,7 @@ pub(crate) async fn at_head( number: u64, ticket: &str, pr: &Value, + fresh_only: bool, ) -> Option<(String, common::pr_facts::DependencyFacts)> { let unit = load_unit(state, team_id, ticket).await?; if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM { @@ -4701,9 +4705,29 @@ pub(crate) async fn at_head( // The same lockfile read, as facts: what the lead and the fact check of // the description are written from. let facts = common::pr_dependency::facts(&unit, &pairs, &head, &check); + if fresh_only { + return Some((fresh_body(&fresh, body), facts)); + } Some((rebuilt_body(body, &fresh), facts)) } +/// A security pull request's description built again from its head alone +/// (the catch-up after an upgrade, `description::catch_up_run`): the +/// sections computed now, and of the old body only the lines that close an +/// issue (`description::fresh_base`). No earlier writer's line (a frozen +/// check row, a reviewer block, a lead without markers) is carried over. +pub(crate) fn fresh_body(fresh: &str, old: &str) -> String { + let closing = crate::passes::description::fresh_base(old); + let closing: Vec<&str> = closing + .lines() + .filter(|l| !fresh.contains(l.trim())) + .collect(); + if closing.is_empty() { + return fresh.to_string(); + } + format!("{}\n\n{}", fresh.trim_end(), closing.join("\n")) +} + /// `body` with the sections computed from the head taken from `fresh`. /// Every section CoderHelm owns elsewhere (the draft status, review fixes, /// the settled items, CI notes, the reviewer guide, open items and the diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs index f02b55b84..dfe7ce26b 100644 --- a/services/worker/src/passes/steps.rs +++ b/services/worker/src/passes/steps.rs @@ -246,6 +246,12 @@ impl Carry { /// open after it stays on the decision and planning moves on. pub const MAX_PLAN_REPLANS: u32 = 1; +/// Fresh steps a run plans again in when its plan is still not usable after +/// the planner was asked for the missing files (`plan_sections`). After +/// them the run ends on CoderHelm's own failure, saying what the plan +/// lacked; it never asks a person to retry it. +pub const MAX_PLAN_RETRIES: u32 = 1; + /// How far planning got, kept on the checkpoint so a step that runs out of /// time while planning hands off to the next one instead of failing. #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -272,6 +278,10 @@ pub struct PlanState { /// The plan check's gaps still open on the latest plan. #[serde(default)] pub open_gaps: Vec, + /// Fresh steps planning started again in because the plan was not + /// usable (see [`MAX_PLAN_RETRIES`]). + #[serde(default)] + pub plan_retries: u32, } impl PlanState { @@ -298,6 +308,11 @@ impl PlanState { self.open_gaps = open_gaps.to_vec(); } + /// Whether an unusable plan may be planned again in a fresh step. + pub fn may_plan_again(&self) -> bool { + self.plan_retries < MAX_PLAN_RETRIES + } + /// Whether the checks may ask for another re-plan. pub fn may_replan(&self) -> bool { self.replans < MAX_PLAN_REPLANS @@ -314,7 +329,13 @@ impl PlanState { pub fn mark(&self) -> String { progress_mark( "", - &format!("plan:r{}:g{}", self.revision, self.open_gaps.len()), + // A fresh step that plans again counts as a revision: it is + // progress, and bounded by its own count. + &format!( + "plan:r{}:g{}", + self.revision.saturating_add(self.plan_retries), + self.open_gaps.len() + ), ) } }