diff --git a/docs/incidents.md b/docs/incidents.md index 8c9b61d4e..2577621c6 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -57,6 +57,7 @@ pipeline still calls it there. | z. `z_run_facts` | A run's plan check found 3 of 3 tasks done; a later fix round wrote 1 file and its task tracker, built from the plan's unchecked copy, saved 1 of 3 over the plan check's checklist. The same runs showed no changed files: `files_modified` was written only by a completion step nothing called. | A round's coder starts from the checklist as saved and only adds ticks; only the plan check unchecks a task. `files_modified` is the branch's work against its base, without the plan files, written when the pull request opens and after every round that records the run's status, capped at 500 paths. | | aa. `aa_promised_round` | A ticket run's own review requested changes. The run took review fix rounds until its automatic fix budget was spent, handed its pull request over with two of its own review's findings still listed, and finished. The draft was then held every hour for three days on "CoderHelm fixes them in its review rounds", and no round ever ran after the run was done. | A hold never promises CoderHelm work that isn't queued. A finished run's draft held on its own review's findings queues one review fix round for them, once per head, while the run has rounds left (its own review rounds, its automatic fix pushes and its fix cycles), and waits for it ("CoderHelm is fixing N findings from its review"), a wait bounded like every other. With no round left, after the run stopped its rounds itself, or once a round ran on the head and the findings are still there, the hold names what a person does and promises nothing. The security and planned work holds name a person's action too, since nothing runs those again once the run is over. A review of a finished run's pull request leaves its findings to that decision, so they are never fixed twice or outside the run's budget. | | ab. `ab_label_prefix` | A failing-test fix's staging deploy and staging end-to-end checks were skipped on its draft. The reading of why went through the staging workflow line by line and kept every quoted string next to a label test as a label name, so a prefix test (`startsWith(github.event.label.name, 'E2E:')`) became a label named `E2E:`, and a condition that needs the staging label *and* `CI:E2E` read as either one. The staging label was refused, the team's `E2E:*` family let the bare `E2E:` through, and CoderHelm added `CI:E2E` and `E2E:`. Adding a missing label creates it, so the repository got an `E2E:` label that matches no area, and `CI:E2E` alone could never run the job. | A job's `if:` is read as an expression (multi-line blocks included) into the label combinations that run it, with those of the jobs it needs. A prefix or substring test is a pattern, never a label: CoderHelm adds only an existing repository label that satisfies it, the one the team's settings name when several do, and nothing when that isn't one certain label; a family allows `E2E:nav`, never `E2E:`. A label is added only when it alone runs the check, the settings allow it, it isn't a deploy, staging or production label and none is on the pull request; otherwise the hold names the exact real label for a person to add. Labels the old reading added that were a bare prefix or couldn't run their check alone come off when CoderHelm itself put them on, and a bare-prefix repository label GitHub made for that add is deleted when nothing else carries it. | +| ac. `ac_partial_and_red_ci` | A Jira run stopped after two steps that changed nothing (the coder twice said the last planned file needed no change, in words the plan check did not know) and a separate salvage path opened "⚠️ Partial", "Closes #0", "ran out of time" and marked it completed; another run's CI fix changed nothing and the run was completed with its pull request marked ready while every check was red. | One path opens a stopped run's pull request (`stop_pr`: ticket line, Not finished with done and left tasks and the recorded reason); no body names issue `#0` (client guard); a planned file the coder says needs no change settles and stays settled across steps; a step after a stalled one takes one task with a different approach; a CI fix that changes nothing tries again with fresh evidence (reporter comments, annotations, rerun on infrastructure failures), then holds the draft with what fails and the run needs a person; `ready::decide` never marks a pull request ready with a failing or running check; a source scan allows `create_pull_request` and `mark_pr_ready` only in their one place each. | ## Adding a case diff --git a/services/gateway/src/routes/analytics.rs b/services/gateway/src/routes/analytics.rs index bf946c20d..1822c6d76 100644 --- a/services/gateway/src/routes/analytics.rs +++ b/services/gateway/src/routes/analytics.rs @@ -679,6 +679,47 @@ pub fn ci_outcomes(runs: &[&RunRow]) -> Value { "running": c("running"), }, "gave_up_reasons": gave_up_reasons, + // Runs that ended wrong (should be zero): see [`ended_wrong`]. + "ended_wrong": ended_wrong(runs), + }) +} + +/// Runs that ended in a state CoderHelm must never leave, counted so a +/// regression shows the day it happens: `completed` with this change's CI +/// still red, and `completed` after a stop mid-work (the old "partial" +/// salvage). Both must be zero; each lists its newest runs. +pub fn ended_wrong(runs: &[&RunRow]) -> Value { + let done = |r: &RunRow| matches!(r.status.as_str(), "completed" | "success"); + let completed_red: Vec<&RunRow> = runs + .iter() + .copied() + .filter(|r| done(r) && r.ci_went_red() && matches!(r.ci_end_state(), CiEnd::GaveUp(_))) + .collect(); + let completed_stopped: Vec<&RunRow> = runs + .iter() + .copied() + .filter(|r| { + done(r) + && (r.error_message.starts_with("Stopped:") + || r.error_message.starts_with("Partial implementation")) + }) + .collect(); + let newest = |v: &[&RunRow]| -> Vec { + let mut ids: Vec<(&str, &str)> = v + .iter() + .map(|r| (r.created_at.as_str(), r.run_id.as_str())) + .collect(); + ids.sort_by(|a, b| b.0.cmp(a.0)); + ids.into_iter() + .take(5) + .map(|(_, id)| id.to_string()) + .collect() + }; + json!({ + "completed_with_red_ci": completed_red.len(), + "completed_red_runs": newest(&completed_red), + "completed_after_stop": completed_stopped.len(), + "completed_after_stop_runs": newest(&completed_stopped), }) } @@ -3444,6 +3485,10 @@ mod tests { ]; let refs: Vec<&RunRow> = runs.iter().collect(); let ci = ci_outcomes(&refs); + // The two that gave up were left "completed" with red CI: counted + // as runs that ended wrong. + assert_eq!(ci["ended_wrong"]["completed_with_red_ci"], 2); + assert_eq!(ci["ended_wrong"]["completed_after_stop"], 0); assert_eq!(ci["runs_with_red_ci"], 6); assert_eq!(ci["red_on_base_runs"], 1); let o = &ci["outcomes"]; @@ -3890,4 +3935,25 @@ mod tests { .to_string(); assert!(lo < inside && inside < hi); } + + /// The salvaged run: completed after a stop mid-work. A run that needs a + /// person instead isn't counted. + #[test] + fn a_run_completed_after_a_stop_is_counted_as_ended_wrong() { + let runs = [ + RunRow { + error_message: "Partial implementation — agent timed out".into(), + ..run("1", 2, "completed") + }, + RunRow { + error_message: "Stopped: steps 2 and 3 made no progress.".into(), + ..run("2", 2, "needs_input") + }, + ]; + let refs: Vec<&RunRow> = runs.iter().collect(); + let w = ended_wrong(&refs); + assert_eq!(w["completed_after_stop"], 1); + assert_eq!(w["completed_after_stop_runs"][0], "1"); + assert_eq!(w["completed_with_red_ci"], 0); + } } diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index b9d74e821..37b0fca3c 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3252,6 +3252,8 @@ impl GitHubClient { draft: bool, ) -> Result> { let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls"); + // No body reaches GitHub naming issue #0 (`passes::outcome`). + let body = crate::passes::outcome::guard_body(body); self.post( &url, &serde_json::json!({ @@ -4316,6 +4318,7 @@ impl GitHubClient { body: &str, ) -> Result<(), Box> { let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}"); + let body = crate::passes::outcome::guard_body(body); self.patch(&url, &serde_json::json!({"body": body})).await?; Ok(()) } diff --git a/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs b/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs new file mode 100644 index 000000000..b6c6f9c3e --- /dev/null +++ b/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs @@ -0,0 +1,452 @@ +//! ac. Two runs on one repository, one afternoon. +//! +//! The first, from a Jira ticket, did seven of its eight planned tasks. The +//! eighth asked to adapt a scroll hook to a taller bar; the coder read the +//! hook, found it measures the bar at runtime, and said so: "The last task +//! needed no code change ... `useStickyScroll.ts` stays as it is". The plan +//! check only knew a task as done when its file changed, and its list of +//! no-change phrases didn't include those words, so two more steps asked the +//! same task, the coder gave the same answer, and the progress guard stopped +//! the run. A separate salvage path then opened a pull request titled +//! "⚠️ Partial: …" whose body was "Closes #0" (the ticket wasn't a GitHub +//! issue) and "the agent ran out of time" (it hadn't), marked the run +//! completed, and the pull request was later marked ready. +//! +//! The second run's pull request failed its end-to-end check. The fix pass +//! read a job log that only showed the report upload, changed nothing, and +//! the run was marked completed and the pull request marked ready with every +//! check red: the ready decision read CI only when CoderHelm's own checks had +//! findings. +//! +//! Guarantee: one path opens a stopped run's pull request (`stop_pr`, the +//! standard ticket line and sections, a "Not finished" section with what is +//! done, what is left and the recorded reason); no body ever names issue +//! `#0`; a planned file the coder says needs no change settles its task and +//! stays settled across steps; a step after one that changed nothing takes a +//! different approach; a CI fix that changes nothing gets new attempts with +//! fresh evidence and then holds the draft with what fails, the run needing +//! attention; and the ready decision never marks a pull request ready with a +//! failing or running check. + +use super::fixture::fn_src; +use crate::passes::outcome::{self, CiState}; +use crate::passes::plan_coverage::{self, Coverage, Next}; +use crate::passes::ready::{self, Ci, Decision, Facts}; + +const OLD_PARTIAL: &str = "⚠️ Partial"; +const OLD_CLOSES: &str = "Closes #0"; +const OLD_TIME: &str = "ran out of time"; + +/// Every `.rs` file of the worker, with its path. +fn worker_sources() -> Vec<(String, String)> { + fn walk(dir: &std::path::Path, out: &mut Vec<(String, String)>) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + let rel = p + .strip_prefix(concat!(env!("CARGO_MANIFEST_DIR"), "/src/")) + .unwrap() + .to_string_lossy() + .to_string(); + out.push((rel, std::fs::read_to_string(&p).unwrap())); + } + } + } + let mut out = Vec::new(); + walk( + std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")), + &mut out, + ); + out +} + +/// The files that call `needle`, outside tests and this file. +fn callers(needle: &str) -> Vec { + worker_sources() + .into_iter() + .filter(|(p, _)| !p.ends_with("ac_partial_and_red_ci.rs")) + .filter(|(_, src)| { + // The code before its test module (a `#[cfg(test)]` helper + // above it is code, too). + let code = src.split("#[cfg(test)]\nmod ").next().unwrap_or(""); + code.contains(needle) + }) + .map(|(p, _)| p) + .collect() +} + +/// New code can't open, describe or mark a pull request ready outside the +/// one path for each: a source scan, so a second salvage path fails here. +#[test] +fn pull_requests_are_opened_and_marked_ready_in_one_place_each() { + let mut opens = callers(".create_pull_request("); + opens.sort(); + assert_eq!( + opens, + vec![ + // The setup pull request (CI and end-to-end setup), not a run's. + "passes/e2e_setup.rs".to_string(), + // A run's pull request. + "passes/pr.rs".to_string(), + // A run stopped with work on its branch: the held draft. + "passes/stop_pr.rs".to_string(), + ], + "a new place opens pull requests: route it through `pr` or `stop_pr`" + ); + assert_eq!( + callers(".mark_pr_ready("), + vec!["passes/ready.rs".to_string()], + "only `ready::settle` marks a pull request ready" + ); + for (path, src) in worker_sources() { + if path.ends_with("ac_partial_and_red_ci.rs") || path.ends_with("outcome.rs") { + continue; + } + assert!(!src.contains("salvage_timeout_pr"), "{path}"); + assert!( + !src.contains("format!(\n \"⚠️ Partial:"), + "{path}" + ); + assert!(!src.contains("This implementation is partial"), "{path}"); + } + // Every body the client sends goes through the `#0` guard. + let gh = include_str!("../../clients/github.rs"); + // Each method, up to the next one: the guard runs before the body is sent. + let method = |head: &str| -> &str { + let at = gh.find(head).unwrap_or_else(|| panic!("{head} is gone")); + let rest = &gh[at + head.len()..]; + &rest[..rest.find("pub async fn ").unwrap_or(rest.len())] + }; + for m in [ + "pub async fn create_pull_request(", + "pub async fn update_pr_body(", + ] { + let body = method(m); + let guard = body + .find("outcome::guard_body(body)") + .unwrap_or_else(|| panic!("{m} has no #0 guard")); + let send = body + .find("self.post(") + .or_else(|| body.find("self.patch(")) + .unwrap(); + assert!(guard < send, "{m}"); + } +} + +/// The stopped Jira run's pull request: the standard draft, through +/// `stop_pr`, from both ways a step can stop mid-implement. +#[test] +fn a_run_stopped_mid_implement_opens_the_standard_held_draft() { + let src = include_str!("../mod.rs"); + let run = fn_src(src, "pub async fn orchestrate_ticket("); + assert!( + run.matches("stop_pr::open(").count() >= 2, + "error and timeout arms" + ); + assert!(!run.contains("salvage_timeout_pr")); + let stop = include_str!("../stop_pr.rs"); + let open_with = fn_src(stop, "pub async fn open_with("); + assert!(open_with.contains("outcome::ticket_line_for(msg)")); + assert!(open_with.contains("not_finished(")); + // The stop sentence names the task the steps were stuck on. + let why = crate::passes::steps::stall_reason( + 3, + "a8c88140", + "implement_started", + "coderhelm-wip/coderhelm/web-12", + Some("task 8 of 8 (`web/src/hooks/useStickyScroll.ts`: adapt the scroll offset)"), + ); + let stop = outcome::Stop::from_recorded(&why); + let words = stop.words(); + assert!( + words.contains("made no change to the branch while working on task 8 of 8"), + "{words}" + ); + for old in [OLD_PARTIAL, OLD_CLOSES, OLD_TIME] { + assert!(!words.contains(old)); + } +} + +#[test] +fn issue_zero_never_renders_in_any_body() { + for (github, n) in [(true, 0u64), (false, 0), (false, 7)] { + let line = outcome::ticket_line(github, n, "WEB-12"); + assert_eq!(line, "Source ticket: WEB-12"); + } + assert_eq!(outcome::ticket_line(true, 7, "GH-7"), "Closes #7"); + let pr = include_str!("../pr.rs"); + assert!(pr.contains("outcome::ticket_line_for(msg)")); + assert!(!pr.contains("\"Closes #{number}")); + // Whatever a builder writes, the client's guard takes `#0` out. + let old = "Closes #0\n\n⚠️ **This implementation is partial** — the agent ran out of time."; + assert!(!outcome::guard_body(old).contains("#0")); +} + +/// The coder's own words from the stopped run (file renamed). The old +/// phrase list matched neither line, so the task stayed open for two steps. +const CODER_NOTES: &str = "The last task needed no code change, so the branch now covers all \ +eight tasks. `useStickyScroll.ts` stays as it is because it measures the sticky bar's height when \ +the page runs, so a 12px taller bar is picked up on its own."; + +fn the_plan() -> String { + (1..=7) + .map(|i| format!("- [ ] web/src/blocks/part{i}.tsx: adjust the padding")) + .chain(std::iter::once( + "- [ ] web/src/hooks/useStickyScroll.ts: adapt the scroll offset to the taller bar" + .to_string(), + )) + .collect::>() + .join("\n") +} + +fn coverage_of(tasks: &[plan_coverage::PlanTask]) -> Coverage { + let changed: Vec = (1..=7) + .map(|i| format!("web/src/blocks/part{i}.tsx")) + .collect(); + plan_coverage::coverage(tasks, &changed) +} + +#[test] +fn a_planned_file_the_coder_says_needs_no_change_settles_and_stays_settled() { + let md = the_plan(); + let mut tasks = plan_coverage::plan_tasks(&md); + let cov = coverage_of(&tasks); + assert_eq!(cov.required_missing().len(), 1); + // The coder's words settle the task. + assert!( + plan_coverage::declined_by_coder(CODER_NOTES, "web/src/hooks/useStickyScroll.ts").is_some() + ); + let settled = plan_coverage::settle_declined(&mut tasks, &cov, CODER_NOTES); + assert_eq!( + settled, + vec!["web/src/hooks/useStickyScroll.ts".to_string()] + ); + let cov = coverage_of(&tasks); + assert_eq!( + plan_coverage::next(&cov, plan_coverage::MAX_ROUNDS, false), + Next::OpenWithOptional + ); + // Persisted on the checklist, the next step reads it settled too: no + // step asks the same task again. + let saved = + plan_coverage::with_declined(&plan_coverage::checked_tasks_md(&md, &cov), &cov.missing); + let next_step = plan_coverage::plan_tasks(&saved); + let again = coverage_of(&next_step); + assert!(again.required_missing().is_empty(), "{saved}"); + // And the pipeline does both: settles from the implement pass's own + // notes before any round, and saves the settled lines. + let pc = include_str!("../plan_coverage.rs"); + let close = fn_src(pc, "pub async fn close_gaps("); + assert!(close.contains("let mut notes = evidence.notes.clone();")); + assert!(close.contains("settle_declined(&mut tasks, &cov, ¬es)")); + let src = include_str!("../mod.rs"); + assert!(src.contains("plan_coverage::with_declined(")); +} + +#[test] +fn the_step_after_one_that_changed_nothing_takes_a_different_approach() { + let md = the_plan(); + let tasks = plan_coverage::plan_tasks(&md); + let cov = coverage_of(&tasks); + let files: Vec = (1..=7) + .map(|i| format!("web/src/blocks/part{i}.tsx")) + .collect(); + let fb = plan_coverage::narrowed_feedback(&cov, &files).unwrap(); + assert!(fb.contains("takes a different approach: one task only")); + assert!(fb.contains("task 8 of 8")); + assert!(fb.contains("web/src/hooks/useStickyScroll.ts")); + assert!(fb.contains(plan_coverage::NO_CHANGE_LINE)); + assert!(fb.contains("- `web/src/blocks/part1.tsx`")); + // The usual ask is not what a stalled step gets. + assert_ne!(fb, plan_coverage::round_feedback(&cov)); + // A coder that answers with the line settles the task. + let line = format!( + "{} web/src/hooks/useStickyScroll.ts: it measures the bar at runtime", + plan_coverage::NO_CHANGE_LINE + ); + assert!(plan_coverage::declined_by_coder(&line, "web/src/hooks/useStickyScroll.ts").is_some()); + // The pipeline passes the stall count and uses the narrowed ask. + let src = include_str!("../mod.rs"); + let cf = fn_src(src, "async fn continuation_feedback("); + assert!(cf.contains("stalled: u32")); + assert!(cf.contains("if stalled > 0 {")); + assert!(cf.contains("plan_coverage::narrowed_feedback(&cov, &files)")); + assert!(src.contains("stalled_steps,")); +} + +fn red() -> Ci { + ready::ci_standing( + &[ + serde_json::json!({"name": "Deploy Preview", "status": "completed", + "conclusion": "failure", "app": {"slug": "github-actions"}}), + ], + &[], + ) +} + +fn running() -> Ci { + ready::ci_standing( + &[ + serde_json::json!({"name": "Deploy Preview", "status": "in_progress", + "conclusion": null, "app": {"slug": "github-actions"}}), + ], + &[], + ) +} + +fn green() -> Ci { + ready::ci_standing( + &[ + serde_json::json!({"name": "Deploy Preview", "status": "completed", + "conclusion": "success", "app": {"slug": "github-actions"}}), + ], + &[], + ) +} + +/// The red-CI run's pull request at its hand-off: no CoderHelm findings, CI +/// failing. Before, `decide` said Ready. +#[test] +fn a_draft_with_failing_ci_is_held_with_the_check_named() { + let f = Facts { + draft: true, + title: "WEB-14: Line up the side menu".into(), + body: "Source ticket: WEB-14\n\n## Summary\nx\n\n## Changes\n- y\n\n## Verification\nz" + .into(), + ci: red(), + ..Default::default() + }; + assert!(ready::reads_ci(&f)); + match ready::decide(&f) { + Decision::Held { reasons } => { + assert!( + reasons[0] + .what + .contains("CI is failing on this head: `Deploy Preview`"), + "{reasons:?}" + ) + } + d => panic!("{d:?}"), + } + let running = Facts { + ci: running(), + ..f.clone() + }; + assert!(matches!(ready::decide(&running), Decision::Wait { .. })); + // A failure the base branch has too isn't this change's. + let on_base = Facts { + red_on_base: true, + ..f.clone() + }; + assert!(matches!(ready::decide(&on_base), Decision::Ready { .. })); +} + +/// The ready decision across the combinations: never ready with a failing +/// or running check (not on the base branch too), or with planned work left. +#[test] +fn the_ready_decision_keeps_the_rules_across_combinations() { + let unfinished = crate::passes::stop_pr::not_finished( + &outcome::Stop::from_recorded("Stopped: steps 2 and 3 made no progress."), + &crate::passes::stop_pr::Progress { + done: vec!["`a.ts`: x".into()], + remaining: vec!["`b.ts`: y".into()], + }, + "", + ); + let feature = Some(crate::passes::feature::FeatureHold { + sandbox_failed: vec!["`pnpm test`: 1 failed".into()], + checklist_fails: vec![], + }); + let mut n = 0; + for ci in [red(), running(), green(), Ci::default()] { + for red_on_base in [false, true] { + for approved in [false, true] { + for feat in [None, feature.clone()] { + for security in [false, true] { + for body_unfinished in [false, true] { + let body = if body_unfinished { + format!("Source ticket: WEB-1\n\n{unfinished}\n\n## Summary\nx") + } else { + "Source ticket: WEB-1\n\n## Summary\nx".to_string() + }; + let f = Facts { + draft: true, + body, + ci: ci.clone(), + red_on_base: red_on_base && ci.failing(), + approved, + feature: feat.clone(), + security, + ..Default::default() + }; + let d = ready::decide(&f); + let ci_state = CiState::of(&f.ci, f.red_on_base); + if matches!(d, Decision::Ready { .. } | Decision::Proving { .. }) { + assert!(ci_state.allows_done(), "ready with {ci_state:?}: {f:?}"); + assert!(!body_unfinished, "ready with planned work left"); + } + n += 1; + } + } + } + } + } + } + assert_eq!(n, 4 * 2 * 2 * 2 * 2 * 2); +} + +/// The CI fix's ends: a fix that changed nothing is followed by another +/// attempt, and every give-up goes through the one hand-off (the draft says +/// what fails, the run needs a person); no CI path says "completed" past the +/// outcome rule. +#[test] +fn a_ci_fix_that_changes_nothing_tries_again_then_holds_and_needs_attention() { + let src = include_str!("../resume.rs"); + let handle = fn_src(src, "pub async fn run("); + let no_change = &handle[handle + .find("if result.files_modified.is_empty() {") + .unwrap()..]; + let no_change = &no_change[..no_change.find("super::GaveUp::NoChange").unwrap()]; + assert!(no_change.contains("if attempt < max_attempts\n")); + assert!(no_change.contains("next_attempt_feedback(")); + assert!(no_change.contains("continue;")); + assert!(no_change.contains("return hand_off_red_ci(")); + assert!(!no_change.contains("complete_run_with_status(")); + assert!(!no_change.contains("mark_pr_ready(")); + for why in ["Budget", "Stalled", "NoChange", "FixError", "NoProgress"] { + let at = handle + .find(&format!("super::GaveUp::{why},")) + .unwrap_or_else(|| panic!("{why} goes through hand_off_red_ci")); + let before = &handle[..at]; + let call = before.rfind("hand_off_red_ci(").unwrap(); + assert!(at - call < 900, "{why}"); + } + let hand = fn_src(src, "async fn hand_off_red_ci("); + assert!(hand.contains("with_ci_failing(")); + assert!(hand.contains("mark_pr_ready(")); + assert!(hand.contains("wait_for_review(")); + assert!(!hand.contains("\"completed\"")); + // Whatever path asks for "completed", red CI on the record turns it into + // a wait on a person. + let complete = fn_src(src, "async fn complete_run_with_status("); + assert!(complete.contains("red_ci_blocks_completion(")); + assert_eq!( + crate::passes::resume::ci_state_of_record("failed", "no_change"), + CiState::Failing("the pull request's checks".into()) + ); + assert_eq!( + crate::passes::resume::ci_state_of_record("failed", "red_on_base"), + CiState::RedOnBase + ); + assert_eq!( + crate::passes::resume::ci_state_of_record("passed", ""), + CiState::Green + ); + // Each attempt reads fresh evidence, and the CI fix's conversation is + // saved like every pass's. + assert!(handle.contains("ci_evidence(")); + assert!(handle.contains("write_conversation_log(")); + assert!(handle.contains("looks_infra(&logs)")); +} diff --git a/services/worker/src/passes/incidents/f_steps.rs b/services/worker/src/passes/incidents/f_steps.rs index 2fda8903c..a9b2d0575 100644 --- a/services/worker/src/passes/incidents/f_steps.rs +++ b/services/worker/src/passes/incidents/f_steps.rs @@ -57,7 +57,7 @@ fn run_steps(heads: &[&str], at: Gate) -> (Ending, Vec) { if msg.continuation > 0 { stalled = steps::stalled_after(mark.as_deref(), &now, stalled); if steps::stops_for_stall(stalled) { - end.said(steps::stall_reason(step, head, at.as_str(), BRANCH)); + end.said(steps::stall_reason(step, head, at.as_str(), BRANCH, None)); end.status = common::run_status::FAILED.into(); return (end, sent); } diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 4ae94e164..d2963fb35 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -18,6 +18,7 @@ mod fixture; mod a_whole_branch; mod aa_promised_round; mod ab_label_prefix; +mod ac_partial_and_red_ci; mod b_open_pr_retry; mod c_codegen_egress; mod d_echoed_markers; diff --git a/services/worker/src/passes/incidents/t_unrun_check_hold.rs b/services/worker/src/passes/incidents/t_unrun_check_hold.rs index 9664a1352..e314aa3d1 100644 --- a/services/worker/src/passes/incidents/t_unrun_check_hold.rs +++ b/services/worker/src/passes/incidents/t_unrun_check_hold.rs @@ -129,14 +129,19 @@ fn the_decision_reads_ci_when_only_a_tooling_line_holds() { }; assert!(f.feature.is_none(), "no feature findings, as in the run"); assert!(ready::reads_ci(&f), "CI settles the line, so it is read"); - // A description with no line CI settles, and no feature findings, needs - // no CI read. + // Every open draft's CI is read now (a failing check holds any pull + // request); a closed one, or one a person put back to draft, is not. let plain = Facts { draft: true, body: "## Summary\nx\n".into(), ..Default::default() }; - assert!(!ready::reads_ci(&plain)); + assert!(ready::reads_ci(&plain)); + let closed = Facts { + closed: true, + ..plain.clone() + }; + assert!(!ready::reads_ci(&closed)); // A check the change really didn't pass is not settled by CI: no read // needed for it, and it still holds whatever CI says. let real = format!( diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 4d0444088..182ff2cd9 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -68,8 +68,8 @@ fn repos_reached_for(log: &[serde_json::Value], owner: &str, repo: &str) -> Vec< /// The agent-loop error emitted when the step budget is exhausted /// (anthropic.rs: "Reached the maximum number of steps (N) without finishing"). /// This means "needs more turns", NOT a real failure — treated like the -/// wall-clock timeout and auto-continued rather than salvaged into a -/// half-finished PR. Substring match is the same error-classification idiom as +/// wall-clock timeout and auto-continued rather than stopped with a +/// half-finished draft. Substring match is the same error-classification idiom as /// the `cancelled by user` check. Coupled to the message in /// `agent::anthropic::converse_tool_loop`. fn is_budget_exhausted(err_msg: &str) -> bool { @@ -1108,6 +1108,7 @@ mod model_route_eval; pub mod onboard; pub mod open_pr_choice; pub mod ops_tools; +pub mod outcome; pub mod outside_exec; pub mod outside_work; pub mod own_review; @@ -1387,12 +1388,12 @@ pub async fn orchestrate_ticket( } // Budget exhausted (hit the step limit) with committed partial // work is "needs more turns", not a real failure — auto-continue - // (bounded) from the branch instead of salvaging a half-finished - // PR the user sees as an error. Identical treatment to the - // wall-clock timeout arm; only THIS error class continues, other - // failures still salvage/fail below. + // (bounded) from the branch instead of stopping with a + // half-finished draft. Identical treatment to the wall-clock + // timeout arm; only THIS error class continues, other failures + // get the held draft or fail below. // Only a genuine mid-implement step-budget death continues (the - // salvage arm below uses the same "implement_started" signal). This + // held draft below uses the same "implement_started" signal). This // stays correct even if a future non-implement pass propagates the // same step-limit message — it won't match this checkpoint. let continued = !guard_ended @@ -1421,39 +1422,19 @@ pub async fn orchestrate_ticket( common::model_retry::is_transient_model_error(err) && requeue_after_model_error(state, &msg, &run_id).await }; - // Salvage before failing: an implement that burned its turn - // budget mid-task has already pushed real commits to the branch. - // Only mid-implement deaths salvage: for later-pass errors a - // salvage would mark the run completed and hide the real error - // behind a misleading "partial work" message. + // A run stopped after its work started (mid-implement or by a + // check after it) with work on its branch gets the standard + // held draft (`stop_pr`): its ticket line, what is done and + // left, and the recorded reason. One path, never a separate + // "partial" pull request. let salvaged = if continued || guard_ended { false } else if let Some((ref last_pass, ref branch, _)) = checkpoint { - if !branch.is_empty() && last_pass.as_str() == "implement_started" { - info!( - run_id, - branch, - "Error mid-implement — attempting to salvage partial work as draft PR" - ); - match salvage_timeout_pr(state, &msg, &run_id, branch, &usage, duration) - .await - { - Ok(pr_url) => { - info!(run_id, pr_url, "Salvaged partial work into draft PR"); - true - } - Err(salvage_err) => { - warn!(run_id, error = %salvage_err, "Failed to salvage partial work"); - false - } - } - } else if !branch.is_empty() + if !branch.is_empty() && stop_pr::opens_pr(last_pass) && e.downcast_ref::().is_none() && crate::agent::policy::claim_stop(&run_id).is_none() { - // A check after the work stopped the run: the work - // still gets its (draft) pull request, with why. match stop_pr::open(state, &msg, &run_id, branch, &sanitize_error(&err_msg)) .await { @@ -1533,8 +1514,8 @@ pub async fn orchestrate_ticket( .await; // Fallback (the usage limit, no work committed, no queue, or the - // enqueue failed): salvage the partial work as a draft PR, else - // fail with why. + // enqueue failed): the standard held draft for the work on the + // branch (`stop_pr`), else fail with why. if let Handoff::Stopped(why) = handoff { let guard_ended = run_guard::end_if_stopped( state, @@ -1552,19 +1533,21 @@ pub async fn orchestrate_ticket( "implement" | "implement_started" | "security" ) { - info!( - run_id, - branch, "Timeout — attempting to salvage partial work as draft PR" + // The standard held draft, with the recorded reason: + // the step's time limit and why no fresh step took over. + let reason = format!( + "The step reached its time limit and the run couldn't continue in a fresh step: {why}." ); - match salvage_timeout_pr(state, &msg, &run_id, branch, &usage, duration) - .await - { + match stop_pr::open(state, &msg, &run_id, branch, &reason).await { Ok(pr_url) => { - info!(run_id, pr_url, "Salvaged partial work into draft PR"); + info!( + run_id, + pr_url, "Opened a draft PR for a run stopped at its time limit" + ); true } Err(e) => { - warn!(run_id, error = %e, "Failed to salvage partial work"); + warn!(run_id, error = %e, "No draft PR for the stopped run"); false } } @@ -3596,6 +3579,9 @@ async fn run_passes( } else { None }; + // Steps in a row that changed nothing, after this one started: the + // first such step changes approach (`continuation_feedback`). + let mut stalled_steps = step_state.stalled; if msg.continuation > 0 && step_state.mark_step != step { let at = resume_gate .map(|g| g.as_str().to_string()) @@ -3612,11 +3598,14 @@ async fn run_passes( steps::stalled_after(step_state.mark.as_deref(), &mark, step_state.stalled) }; steps::save_mark(state, &msg.team_id, run_id, &mark, stalled, step).await; + stalled_steps = stalled; if steps::stops_for_stall(stalled) { let kept = keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + // The stop names the planned task the steps were stuck on. + let task = current_plan_task(&github, msg, &plan_result, &branch_name).await; close_memory(state, agent_memory.take()).await; - return Err(steps::stall_reason(step, &head, &at, &kept).into()); + return Err(steps::stall_reason(step, &head, &at, &kept, task.as_deref()).into()); } info!(run_id, step, stalled, at = %at, "Continuing the run in this step"); } @@ -4850,7 +4839,16 @@ async fn run_passes( } // A continuation picks up the planned tasks the branch doesn't do yet. let still_to_do = if msg.continuation > 0 { - continuation_feedback(state, run_id, &github, msg, &plan_result, &branch_name).await + continuation_feedback( + state, + run_id, + &github, + msg, + &plan_result, + &branch_name, + stalled_steps, + ) + .await } else { None }; @@ -5423,11 +5421,16 @@ async fn run_passes( .await; // Only the tasks the branch did are checked off, so the run page and // a later attempt see the truth. + // A task the coder settled without a change says so on its line, + // so a later step reads it as optional, never asks for it again. save_checked_tasks( state, msg, run_id, - &plan_coverage::checked_tasks_md(&plan_result.tasks, &cov), + &plan_coverage::with_declined( + &plan_coverage::checked_tasks_md(&plan_result.tasks, &cov), + &cov.missing, + ), ) .await; add_progress_note( @@ -6761,8 +6764,36 @@ async fn save_checked_tasks(state: &WorkerState, msg: &TicketMessage, run_id: &s } } +/// The planned task the run is on (the first one its branch doesn't do), +/// as `task K of N (`path`: what)`; `None` without a checklist. +async fn current_plan_task( + github: &GitHubClient, + msg: &TicketMessage, + plan: &plan::PlanResult, + branch: &str, +) -> Option { + let tasks = + plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) + .await; + if tasks.is_empty() { + return None; + } + let changes = plan_coverage::plan_changes( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + ) + .await?; + plan_coverage::current_task(&changes.coverage(&tasks)) +} + /// For a continuation: the planned tasks its branch doesn't do yet, as the /// implement pass's instructions. `None` when all are done or it can't tell. +/// After a step that changed nothing (`stalled` > 0) the approach changes: +/// one task, the branch's files so far, and the two ways to finish it +/// (`plan_coverage::narrowed_feedback`), never the same ask again. async fn continuation_feedback( state: &WorkerState, run_id: &str, @@ -6770,6 +6801,7 @@ async fn continuation_feedback( msg: &TicketMessage, plan: &plan::PlanResult, branch: &str, + stalled: u32, ) -> Option { let tasks = plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) @@ -6798,7 +6830,26 @@ async fn continuation_feedback( run_guard::Progress::TasksDone(cov.done.len()), ) .await; - (!cov.required_missing().is_empty()).then(|| plan_coverage::round_feedback(&cov)) + if cov.required_missing().is_empty() { + return None; + } + if stalled > 0 { + let files = plan_coverage::changed_files( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + ) + .await + .unwrap_or_default(); + info!( + run_id, + stalled, "The last step changed nothing: this one takes one task, a different approach" + ); + return plan_coverage::narrowed_feedback(&cov, &files); + } + Some(plan_coverage::round_feedback(&cov)) } /// Run implement → security → PR for a single repo. @@ -11357,118 +11408,6 @@ mod trace_name_tests { } } -/// Salvage partial work from a timed-out run by creating a draft PR. -/// Returns the PR URL on success. -async fn salvage_timeout_pr( - state: &WorkerState, - msg: &TicketMessage, - run_id: &str, - branch: &str, - usage: &TokenUsage, - duration: u64, -) -> Result> { - let github = GitHubClient::new( - &state.secrets.github_app_id, - &state.secrets.github_private_key, - msg.installation_id, - &state.http, - )?; - - // Check if there's actually a diff on the branch - let diff = github - .get_diff(&msg.repo_owner, &msg.repo_name, &msg.base_branch, branch) - .await?; - let files_changed = diff - .get("files") - .and_then(|f| f.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - if files_changed == 0 { - return Err("No changes on branch to salvage".into()); - } - - // Check for existing PR - let existing = github - .find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch) - .await?; - let (pr_number, pr_url) = if let Some(pr_data) = existing { - let n = pr_data.get("number").and_then(|v| v.as_u64()).unwrap_or(0); - let u = pr_data - .get("html_url") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - (n, u) - } else { - let conventions = load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; - let title = format!( - "⚠️ Partial: {}", - pr::pr_title(&conventions, &ticket_tokens(msg), msg) - ); - let body = format!( - "Closes #{}\n\n\ - ⚠️ **This implementation is partial** — the agent ran out of time before finishing all tasks.\n\n\ - Please review what's been done and either:\n\ - - Complete the remaining work manually, or\n\ - - Re-trigger the issue for the agent to continue\n", - msg.issue_number, - ); - let pr_data = github - .create_pull_request( - &msg.repo_owner, - &msg.repo_name, - common::truncate_str(&title, 72), - &body, - branch, - &msg.base_branch, - true, // draft - ) - .await?; - let n = pr_data.get("number").and_then(|v| v.as_u64()).unwrap_or(0); - let u = pr_data - .get("html_url") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - (n, u) - }; - - // Mark run as completed (not failed) — it produced a PR - let now = chrono::Utc::now().to_rfc3339(); - let delta = usage.unrecorded(); - let usage_res = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(&msg.team_id)) - .key("run_id", attr_s(run_id)) - .update_expression( - "SET #s = :s, status_run_id = :sri, pr_url = :pu, pr_number = :pn, \ - branch = :b, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ - cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ - cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, \ - error_message = :err", - ) - .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", attr_s("completed")) - .expression_attribute_values(":sri", attr_s(&format!("completed#{run_id}"))) - .expression_attribute_values(":pu", attr_s(&pr_url)) - .expression_attribute_values(":pn", attr_n(pr_number)) - .expression_attribute_values(":b", attr_s(branch)) - .usage_values(&delta) - .expression_attribute_values(":d", attr_n(duration)) - .expression_attribute_values(":t", attr_s(&now)) - .expression_attribute_values(":err", attr_s("Partial implementation — agent timed out")) - .send() - .await; - if usage_res.is_ok() { - usage.mark_recorded(&delta); - } - self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; - - Ok(pr_url) -} - /// Save a checkpoint after a pass completes so runs can resume on Lambda timeout. pub(crate) async fn save_checkpoint( state: &WorkerState, diff --git a/services/worker/src/passes/outcome.rs b/services/worker/src/passes/outcome.rs new file mode 100644 index 000000000..7dde694b9 --- /dev/null +++ b/services/worker/src/passes/outcome.rs @@ -0,0 +1,562 @@ +//! How a run ends and whether its pull request may leave draft, decided from +//! facts in one place, with the rules checked in code. +//! +//! Two runs on one day ended wrong. One stopped in the middle of its planned +//! work (two steps changed nothing), and a separate salvage path opened a +//! pull request titled "Partial", whose body said "Closes #0" for a ticket +//! that was not a GitHub issue and claimed the agent "ran out of time"; the +//! run read "completed" and the pull request was later marked ready. The +//! other run's CI failed, its fix attempt changed nothing, and the run was +//! marked completed with the pull request marked ready while every check was +//! red: the ready decision only read CI when CoderHelm's own checks had +//! findings. +//! +//! The rules, each enforced here and covered by tests: +//! +//! - A run is `completed` only when no planned task is left, no stop reason +//! is recorded, and the repository's CI is green, absent, or red only on +//! checks that fail on the base branch too ([`decide`]). Anything else needs +//! a person, with every reason named. +//! - A pull request leaves draft under the same conditions and never with a +//! failing or running check ([`ci_blocker`], used by `ready::decide`). +//! - The words a person reads about a stop come from the recorded reason +//! ([`Stop::words`]): only a recorded time limit says "time". +//! - Every pull request body names its ticket: `Closes #N` only for a real +//! GitHub issue (N > 0), else `Source ticket: KEY` ([`ticket_line`]); an +//! issue reference to `#0` never reaches GitHub ([`guard_body`], applied by +//! the GitHub client to every body it sends). + +/// Where the repository's own CI stands on the pull request's head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CiState { + /// The repository reports no checks at all. + NoChecks, + Green, + /// Checks are still running (their names). + Pending(String), + /// Checks failed (their names, and an excerpt when known). + Failing(String), + /// Every failing check also fails on the base branch. + RedOnBase, +} + +impl CiState { + /// From the ready decision's reading of CI. + pub fn of(ci: &super::ready::Ci, red_on_base: bool) -> CiState { + if ci.green { + CiState::Green + } else if ci.failing() { + if red_on_base { + CiState::RedOnBase + } else { + CiState::Failing( + ci.why + .trim_start_matches("CI fails on this head: ") + .trim_end_matches('.') + .to_string(), + ) + } + } else if ci.running() { + CiState::Pending( + ci.why + .trim_start_matches("CI is still running on this head: ") + .trim_end_matches('.') + .to_string(), + ) + } else { + CiState::NoChecks + } + } + + /// Whether this standing lets a run end done and a pull request leave + /// draft. + pub fn allows_done(&self) -> bool { + matches!( + self, + CiState::NoChecks | CiState::Green | CiState::RedOnBase + ) + } +} + +/// CoderHelm's review verdict on the head. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Review { + // Read from the review record by the ready decision; the run-end rule + // reads CI only. + #[allow(dead_code)] + Approved, + ChangesRequested, + /// No finished review (or the reviewer is off). + Missing, +} + +/// Why a run stopped before its work was done, as the run recorded it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stop { + /// Two steps in a row left the branch where it was. + NoProgress { + /// The step numbers, as the stop recorded them. + steps: (u32, u32), + /// Where the run was (`the implement work (planned tasks)`). + at: String, + /// The planned task it was on, when known. + task: Option, + }, + /// A step reached its time limit and no fresh step could take over. + OutOfTime(String), + /// Anything else, in the run's own words. + Other(String), +} + +impl Stop { + /// Reads the recorded stop sentence back into its kind. The sentences + /// are written by `steps::stall_reason` and the timeout arm; anything + /// else is kept as written. + pub fn from_recorded(text: &str) -> Stop { + let t = text.trim(); + if let Some(rest) = t.strip_prefix("Stopped: steps ") { + let mut nums = rest + .split(|c: char| !c.is_ascii_digit()) + .filter(|s| !s.is_empty()) + .filter_map(|s| s.parse::().ok()); + if let (Some(a), Some(b)) = (nums.next(), nums.next()) { + if rest.contains("made no progress") { + let at = rest + .split_once("stuck at ") + .map(|(_, r)| r.split(". ").next().unwrap_or(r).trim().to_string()) + .unwrap_or_default(); + let task = rest + .split_once("while working on ") + .map(|(_, r)| r.split(". ").next().unwrap_or(r).trim().to_string()); + return Stop::NoProgress { + steps: (a, b), + at, + task, + }; + } + } + } + if t.contains("reached its time limit") { + return Stop::OutOfTime(t.to_string()); + } + Stop::Other(t.to_string()) + } + + /// The reason a person reads. Only a recorded time limit mentions time. + pub fn words(&self) -> String { + match self { + Stop::NoProgress { steps, at, task } => { + let on = match task { + Some(t) if !t.is_empty() => format!(" while working on {t}"), + _ if !at.is_empty() => format!(" at {at}"), + _ => String::new(), + }; + format!( + "steps {} and {} made no change to the branch{on}, so the run stopped \ + instead of repeating them", + steps.0, steps.1 + ) + } + Stop::OutOfTime(why) | Stop::Other(why) => why.trim().trim_end_matches('.').to_string(), + } + } +} + +/// What the run's ending is decided from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Facts { + /// Planned tasks not done (paths or one-line tasks). + pub tasks_remaining: Vec, + pub ci: CiState, + pub review: Review, + /// The recorded reason the run stopped early, if it did. + pub stop: Option, +} + +/// How the run's status reads when it ends. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RunStatus { + /// Done: nothing is left for a person beyond reviewing the pull request. + Completed, + /// A person must act; the reasons say what. + NeedsAttention, + /// Nothing is wrong yet; CI is still running. + Waiting, +} + +/// The decision. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Outcome { + pub status: RunStatus, + /// The pull request may leave draft. + pub pr_ready: bool, + /// Every reason it isn't done, in the words a person reads. + pub reasons: Vec, +} + +/// The reason CI keeps a pull request a draft and a run from being done, or +/// `None` when CI allows it. +pub fn ci_blocker(ci: &CiState) -> Option { + match ci { + CiState::Failing(checks) => Some(format!("CI is failing: {checks}")), + CiState::Pending(checks) => Some(format!("CI is still running: {checks}")), + CiState::NoChecks | CiState::Green | CiState::RedOnBase => None, + } +} + +/// The one decision. +pub fn decide(f: &Facts) -> Outcome { + let mut reasons = Vec::new(); + if let Some(stop) = &f.stop { + reasons.push(format!("The run stopped: {}", stop.words())); + } + if !f.tasks_remaining.is_empty() { + reasons.push(format!( + "{} planned task(s) not done: {}", + f.tasks_remaining.len(), + f.tasks_remaining.join("; ") + )); + } + let ci = ci_blocker(&f.ci); + let only_waiting = reasons.is_empty() && matches!(f.ci, CiState::Pending(_)); + if let Some(c) = ci { + reasons.push(c); + } + if f.review == Review::ChangesRequested { + reasons.push("CoderHelm's review asked for changes on this head".to_string()); + } + let status = if reasons.is_empty() { + RunStatus::Completed + } else if only_waiting && f.review != Review::ChangesRequested { + RunStatus::Waiting + } else { + RunStatus::NeedsAttention + }; + Outcome { + status, + pr_ready: reasons.is_empty(), + reasons, + } +} + +/// The rules an outcome must keep, as a list of what it breaks (empty when +/// it keeps them all). The tests drive every combination through it. +pub fn broken_rules(f: &Facts, o: &Outcome) -> Vec<&'static str> { + let mut out = Vec::new(); + let done = o.status == RunStatus::Completed; + if (done || o.pr_ready) && !f.tasks_remaining.is_empty() { + out.push("done or ready with planned tasks left"); + } + if (done || o.pr_ready) && !f.ci.allows_done() { + out.push("done or ready with failing or running CI"); + } + if (done || o.pr_ready) && f.stop.is_some() { + out.push("done or ready after a recorded stop"); + } + if o.pr_ready && f.review == Review::ChangesRequested { + out.push("ready with the review asking for changes"); + } + if !done && o.reasons.is_empty() { + out.push("not done without a named reason"); + } + let says_time = o + .reasons + .iter() + .any(|r| r.to_lowercase().contains("time limit") || r.contains("ran out of time")); + if says_time && !matches!(f.stop, Some(Stop::OutOfTime(_))) { + out.push("claims a time limit that isn't the recorded reason"); + } + out +} + +// ── Pull request bodies ───────────────────────────────────────────────────── + +/// The ticket line every pull request body starts with: `Closes #N` for a +/// real GitHub issue, else `Source ticket: KEY`. +pub fn ticket_line(github_issue: bool, issue_number: u64, ticket_id: &str) -> String { + if github_issue && issue_number > 0 { + format!("Closes #{issue_number}") + } else { + format!("Source ticket: {}", ticket_id.trim()) + } +} + +/// [`ticket_line`] for a run's ticket. +pub fn ticket_line_for(msg: &crate::models::TicketMessage) -> String { + ticket_line( + matches!(msg.source, crate::models::TicketSource::Github), + msg.issue_number, + &msg.ticket_id, + ) +} + +/// Keywords GitHub reads as "this pull request closes that issue". +const CLOSING: &[&str] = &[ + "close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved", +]; + +/// Whether `line` refers to issue `#0` (with or without a closing keyword). +fn names_issue_zero(line: &str) -> bool { + let b = line.as_bytes(); + let mut i = 0; + while let Some(off) = line[i..].find("#0") { + let at = i + off; + let after = b.get(at + 2).copied(); + let before = if at == 0 { + None + } else { + b.get(at - 1).copied() + }; + let ends = after.is_none_or(|c| !c.is_ascii_alphanumeric()); + let starts = before.is_none_or(|c| !c.is_ascii_alphanumeric() && c != b'&'); + if ends && starts { + return true; + } + i = at + 2; + } + false +} + +/// The body with every reference to issue `#0` taken out: a line that is +/// only a closing keyword and `#0` goes, any other `#0` reference loses its +/// closing keyword and number. Applied to every body the GitHub client sends. +pub fn guard_body(body: &str) -> String { + if !body.contains("#0") { + return body.to_string(); + } + let mut out: Vec = Vec::new(); + for line in body.lines() { + if !names_issue_zero(line) { + out.push(line.to_string()); + continue; + } + let words: Vec<&str> = line.split_whitespace().collect(); + let only_ref = words.iter().all(|w| { + let lw = w + .trim_matches(|c: char| c == ':' || c == ',') + .to_lowercase(); + CLOSING.contains(&lw.as_str()) || names_issue_zero(w) + }); + if only_ref { + continue; + } + let mut kept: Vec<&str> = Vec::new(); + for w in words { + if names_issue_zero(w) { + if let Some(prev) = kept.last() { + let lw = prev.trim_matches(':').to_lowercase(); + if CLOSING.contains(&lw.as_str()) { + kept.pop(); + } + } + continue; + } + kept.push(w); + } + out.push(kept.join(" ")); + } + let mut s = out.join("\n"); + while s.starts_with('\n') { + s.remove(0); + } + s +} + +/// What a run's pull request body breaks: no ticket reference, an issue +/// `#0`, or a missing standard section. Empty when it keeps them all. +pub fn body_problems(body: &str, ticket_id: &str) -> Vec { + let mut out = Vec::new(); + let has_ticket = body.contains(&format!("Source ticket: {ticket_id}")) + || body.lines().any(|l| { + let l = l.trim(); + (l.starts_with("Closes #") || l.starts_with("Fixes #") || l.starts_with("Resolves #")) + && !names_issue_zero(l) + }); + if !has_ticket { + out.push("no ticket reference".to_string()); + } + if names_issue_zero(body) { + out.push("refers to issue #0".to_string()); + } + for section in ["Summary", "Changes", "Verification"] { + let found = body.lines().any(|l| { + let l = l + .trim() + .trim_start_matches('#') + .trim() + .trim_matches('*') + .trim(); + l.eq_ignore_ascii_case(section) + }); + if !found { + out.push(format!("no {section} section")); + } + } + if body.contains("⚠️ Partial") || body.contains("ran out of time before finishing") { + out.push("the old partial-salvage wording".to_string()); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn all_ci() -> Vec { + vec![ + CiState::NoChecks, + CiState::Green, + CiState::Pending("`build`".into()), + CiState::Failing("`e2e`".into()), + CiState::RedOnBase, + ] + } + + fn all_stops() -> Vec> { + vec![ + None, + Some(Stop::from_recorded( + "Stopped: steps 2 and 3 made no progress. The branch stayed at a8c8814 and the run \ + was stuck at the implement work (planned tasks). The work so far is kept on \ + branch `coderhelm-wip/x`.", + )), + Some(Stop::OutOfTime( + "The step reached its time limit and the run couldn't continue in a fresh step: \ + the usage limit." + .into(), + )), + Some(Stop::Other("A check after the work errored: the link check.".into())), + ] + } + + /// Every combination of tasks, CI, review and stop keeps every rule. + #[test] + fn every_combination_keeps_the_rules() { + let tasks = [vec![], vec!["`web/a.ts`: add the hook".to_string()]]; + let reviews = [Review::Approved, Review::ChangesRequested, Review::Missing]; + let mut n = 0; + for t in &tasks { + for ci in all_ci() { + for r in reviews { + for stop in all_stops() { + let f = Facts { + tasks_remaining: t.clone(), + ci: ci.clone(), + review: r, + stop: stop.clone(), + }; + let o = decide(&f); + assert!( + broken_rules(&f, &o).is_empty(), + "{f:?} {o:?}: {:?}", + broken_rules(&f, &o) + ); + n += 1; + } + } + } + } + assert_eq!(n, 2 * 5 * 3 * 4); + } + + #[test] + fn the_rules_catch_an_ending_that_breaks_them() { + // The red-CI run: completed and ready with every check failing. + let f = Facts { + tasks_remaining: vec![], + ci: CiState::Failing("`Deploy Preview`".into()), + review: Review::Missing, + stop: None, + }; + let wrong = Outcome { + status: RunStatus::Completed, + pr_ready: true, + reasons: vec![], + }; + assert!(broken_rules(&f, &wrong).contains(&"done or ready with failing or running CI")); + // The salvaged run: "ran out of time" for a stop that was no progress. + let f = Facts { + tasks_remaining: vec!["`web/useScroll.ts`".into()], + ci: CiState::NoChecks, + review: Review::Missing, + stop: Some(Stop::from_recorded( + "Stopped: steps 2 and 3 made no progress.", + )), + }; + let wrong = Outcome { + status: RunStatus::Completed, + pr_ready: false, + reasons: vec!["the agent ran out of time before finishing all tasks".into()], + }; + let broken = broken_rules(&f, &wrong); + assert!(broken.contains(&"done or ready with planned tasks left")); + assert!(broken.contains(&"claims a time limit that isn't the recorded reason")); + } + + #[test] + fn red_ci_needs_a_person_and_running_ci_is_a_wait() { + let mut f = Facts { + tasks_remaining: vec![], + ci: CiState::Failing("`e2e`".into()), + review: Review::Approved, + stop: None, + }; + let o = decide(&f); + assert_eq!(o.status, RunStatus::NeedsAttention); + assert!(!o.pr_ready); + assert_eq!(o.reasons, vec!["CI is failing: `e2e`".to_string()]); + f.ci = CiState::Pending("`build`".into()); + assert_eq!(decide(&f).status, RunStatus::Waiting); + f.ci = CiState::RedOnBase; + assert_eq!(decide(&f).status, RunStatus::Completed); + } + + #[test] + fn a_no_progress_stop_says_what_happened_never_time() { + let s = Stop::from_recorded( + "Stopped: steps 2 and 3 made no progress. The branch stayed at a8c8814 and the run \ + was stuck at the implement work (planned tasks) while working on task 8 of 8 \ + (`web/useScroll.ts`: adapt the hook). The work so far is kept on branch `x`.", + ); + let w = s.words(); + assert!( + w.starts_with( + "steps 2 and 3 made no change to the branch while working on task 8 of 8" + ), + "{w}" + ); + assert!(!w.to_lowercase().contains("time"), "{w}"); + } + + #[test] + fn issue_zero_never_renders() { + assert_eq!(ticket_line(true, 0, "GH-0"), "Source ticket: GH-0"); + assert_eq!(ticket_line(false, 0, "WEB-12"), "Source ticket: WEB-12"); + assert_eq!(ticket_line(true, 41, "GH-41"), "Closes #41"); + let old = "Closes #0\n\n⚠️ **This implementation is partial**"; + let g = guard_body(old); + assert!(!g.contains("#0"), "{g}"); + assert!(g.starts_with("⚠️")); + assert_eq!(guard_body("Fixes #0, see notes"), "see notes"); + // Real references and look-alikes stay. + assert_eq!(guard_body("Closes #10"), "Closes #10"); + assert_eq!( + guard_body("color #0a0a0a and �"), + "color #0a0a0a and �" + ); + } + + #[test] + fn a_body_without_the_ticket_or_sections_is_named() { + let good = + "Source ticket: WEB-12\n\n## Summary\nx\n\n## Changes\n- y\n\n## Verification\nz"; + assert!(body_problems(good, "WEB-12").is_empty()); + let old = "Closes #0\n\n⚠️ **This implementation is partial** — the agent ran out of time \ + before finishing all tasks."; + let p = body_problems(old, "WEB-12"); + assert!(p.contains(&"no ticket reference".to_string())); + assert!(p.contains(&"refers to issue #0".to_string())); + assert!(p.contains(&"no Summary section".to_string())); + assert!(p.contains(&"the old partial-salvage wording".to_string())); + } +} diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs index a3de5ba16..9502089e1 100644 --- a/services/worker/src/passes/plan_coverage.rs +++ b/services/worker/src/passes/plan_coverage.rs @@ -84,8 +84,29 @@ const NO_CHANGE_MARKS: &[&str] = &[ "does not need any change", "doesn't need changing", "nothing to change", + // How coders actually say it (a run looped two steps on a file its + // coder twice said "needed no code change" and "stays as it is"). + "needed no change", + "need no code change", + "needs no code change", + "needed no code change", + "no code change is needed", + "no code change needed", + "no change is needed", + "no changes are needed", + "requires no change", + "required no change", + "stays as it is", + "stays as is", + "left as it is", + "left unchanged", + "stays unchanged", ]; +/// The line a coder writes to settle a planned task without a change +/// (`round_feedback` asks for it): `No change needed: : `. +pub const NO_CHANGE_LINE: &str = "No change needed:"; + /// The coder's own line saying `path` needs no change, when it wrote one: the /// line names the file (its path or, when that is how the coder wrote it, /// its file name) and says no change is needed. @@ -407,7 +428,7 @@ pub fn round_feedback(cov: &Coverage) -> String { "The plan is not done yet: the branch doesn't change the file of {} of its {} tasks. \ Do these tasks now, in order, writing each task's files as soon as that task is done. \ Read what is already on the branch first and build on it; don't redo finished tasks.\n\n\ - Still to do:\n{}\n\nAlready done on the branch:\n{}", + Still to do:\n{}\n\nAlready done on the branch:\n{}\n\n{}", todo.len(), cov.total(), todo.join("\n"), @@ -415,10 +436,128 @@ pub fn round_feedback(cov: &Coverage) -> String { "(none)".to_string() } else { done.join("\n") - } + }, + settle_without_change() ) } +/// How a task is settled without a change, said the same way every time. +fn settle_without_change() -> String { + format!( + "If, after reading a task's file, it truly needs no change (the code already does what \ + the task asks), don't edit it: write one line `{NO_CHANGE_LINE} : ` in your final message. That settles the task; it is listed \ + on the pull request for a person to check." + ) +} + +/// A different approach after a step changed nothing: one task only (the +/// first one left), what the branch already changes, and the two ways to +/// finish it (the change, or the no-change line). `diff_files` is what the +/// branch changes so far. +pub fn narrowed_feedback(cov: &Coverage, diff_files: &[String]) -> Option { + let missing = cov.required_missing(); + let first = missing.first()?; + let n = cov.done.len() + 1; + let files = if diff_files.is_empty() { + "(nothing yet)".to_string() + } else { + diff_files + .iter() + .take(40) + .map(|f| format!("- `{f}`")) + .collect::>() + .join("\n") + }; + Some(format!( + "The last step changed nothing on the branch while this task was open, so this step \ + takes a different approach: one task only. Start fresh from the plan and the branch as \ + it is now; don't re-read or redo finished work.\n\n\ + The task (task {n} of {total}):\n{task}\n\n\ + The branch already changes these files (the other tasks are done there):\n{files}\n\n\ + Do exactly one of these, then stop:\n\ + 1. Make the change the task asks for in `{path}` and save the file.\n\ + 2. If the file already does what the task asks, write the line \ + `{NO_CHANGE_LINE} {path}: ` in your final \ + message. Saying it needs no change any other way leaves the task open, and the run \ + stops after this step.{more}", + total = cov.total(), + task = task_line(first), + path = first.path, + more = if missing.len() > 1 { + format!( + "\n\n{} more task(s) are left after this one; the next step takes them.", + missing.len() - 1 + ) + } else { + String::new() + } + )) +} + +/// The planned task a run is on: the first one left, as `task K of N +/// (`path`: what)`. +pub fn current_task(cov: &Coverage) -> Option { + let first = cov.required_missing().into_iter().next()?; + Some(format!( + "task {} of {} (`{}`: {})", + cov.done.len() + 1, + cov.total(), + first.path, + common::truncate_str(first.task.trim(), 160) + )) +} + +/// Marks the tasks whose file the coder said needs no change (in `notes`) +/// and the branch doesn't change: optional from now on, with the coder's +/// line. Returns the paths it settled. +pub fn settle_declined(tasks: &mut [PlanTask], cov: &Coverage, notes: &str) -> Vec { + let missing: Vec = cov + .required_missing() + .iter() + .map(|t| t.path.clone()) + .collect(); + let mut settled = Vec::new(); + for t in tasks.iter_mut().filter(|t| missing.contains(&t.path)) { + if let Some(why) = declined_by_coder(notes, &t.path) { + info!(path = %t.path, "The coder found a planned file needs no change"); + t.optional = true; + t.task = format!("{} (the coder found it needs no change: {why})", t.task); + settled.push(t.path.clone()); + } + } + settled +} + +/// The plan's checklist with each settled task's line saying so, so a later +/// step reads the task as optional (`is_optional` matches "no change +/// needed") instead of asking for it again. +pub fn with_declined(tasks_md: &str, tasks: &[PlanTask]) -> String { + tasks_md + .lines() + .map(|line| { + let Some(task) = plan_tasks(line).into_iter().next() else { + return line.to_string(); + }; + match tasks.iter().find(|t| t.path == task.path) { + Some(t) if t.optional && !task.optional => { + let why = t + .task + .split_once("(the coder found it needs no change: ") + .map(|(_, w)| w.trim_end_matches(')').trim()) + .unwrap_or(""); + format!( + "{line} (no change needed: {})", + common::truncate_str(why, 300) + ) + } + _ => line.to_string(), + } + }) + .collect::>() + .join("\n") +} + /// The run's status when it stops with planned work not done: plain, and /// naming the tasks (the run record keeps up to 500 characters; the full /// list is in [`progress_note`]). @@ -647,6 +786,9 @@ pub async fn close_gaps( return None; } let mut rounds = 0; + // The implement pass may already have said a planned file needs no + // change: that settles the task before any round asks for it again. + let mut notes = evidence.notes.clone(); loop { let cov = plan_changes( w.github, @@ -657,11 +799,25 @@ pub async fn close_gaps( ) .await? .coverage(&tasks); + let settled = settle_declined(&mut tasks, &cov, ¬es); + notes.clear(); + let cov = if settled.is_empty() { + cov + } else { + let mut c = cov; + for t in c.missing.iter_mut() { + if let Some(n) = tasks.iter().find(|n| n.path == t.path) { + *t = n.clone(); + } + } + c + }; info!( run_id = w.run_id, done = cov.done.len(), missing = cov.missing.len(), on_base = cov.on_base.len(), + settled = settled.len(), rounds, "Plan check" ); @@ -723,25 +879,19 @@ pub async fn close_gaps( match result { Ok(r) => { let timed_out = r.timed_out; - // Told to do a task, the coder wrote nothing for it and said - // why its file needs no change: that is its judgment, listed - // on the pull request for a person, never another round or - // step asking the same thing. - if r.files_modified.is_empty() { - let missing: Vec = cov - .required_missing() - .iter() - .map(|t| t.path.clone()) - .collect(); - for t in tasks.iter_mut().filter(|t| missing.contains(&t.path)) { - if let Some(why) = declined_by_coder(&r.evidence.notes, &t.path) { - info!(run_id = w.run_id, path = %t.path, "The coder found a planned file needs no change"); - t.optional = true; - t.task = - format!("{} (the coder found it needs no change: {why})", t.task); - } - } - } + // Told to do a task, the coder said why its file needs no + // change: that is its judgment, listed on the pull request + // for a person, never another round or step asking the same + // thing (settled at the top of the loop). + notes = r.evidence.notes.clone(); + super::write_conversation_log( + w.state, + &w.msg.team_id, + w.run_id, + "implement_plan_round", + &r.conversation_log, + ) + .await; evidence.merge(r.evidence); if timed_out { // No time for another round here; what it wrote counts. diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index fa8bc0fb3..d05f5d339 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -573,18 +573,13 @@ Return ONLY the markdown body text."#, None => clean_body.to_string(), }; let clean_body = clean_body.as_str(); - let full_body = if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - format!( - "Closes #{number}\n\n{clean_body}", - number = msg.issue_number, - ) + // One ticket line for every body (`outcome::ticket_line`): `Closes #N` + // only for a real GitHub issue. + let ticket = super::outcome::ticket_line_for(msg); + let full_body = if clean_body.contains(&ticket) { + clean_body.to_string() } else { - // Avoid duplicating "Source ticket:" if it's already in the body - if clean_body.contains(&format!("Source ticket: {}", msg.ticket_id)) { - clean_body.to_string() - } else { - format!("Source ticket: {}\n\n{clean_body}", msg.ticket_id) - } + format!("{ticket}\n\n{clean_body}") }; // CoderHelm's own sections go in their places around the writer's: the // blocks the change copied (under Changes), every step outside this PR diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index fc59897ff..eddfc44c3 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -426,6 +426,18 @@ pub fn decide(f: &Facts) -> Decision { if let Some(w) = sec_wait { proof_wait.get_or_insert(w); } + // Every other pull request too (`outcome`): never ready with a failing + // check, never ready while one runs. CoderHelm's own findings already + // name CI in their reason, so they aren't said twice. + if !f.security && f.feature.is_none() { + let (ci_hold, ci_wait) = repo_ci(f); + if let Some(r) = ci_hold { + reasons.push(r); + } + if let Some(w) = ci_wait { + proof_wait.get_or_insert(w); + } + } // CoderHelm's own sandbox and checklist findings weigh against the // repository's CI and the review: with both green they are open items // on a ready pull request, never a hold by themselves. @@ -983,7 +995,9 @@ async fn gather(ctx: &Ctx<'_>) -> Result { ) .await; f.approved = matches!(&verdict, Ok(Some(v)) if v == "APPROVE"); - if f.security && f.ci.failing() { + // A failure the base branch has too is not this change's: it holds + // nothing (`outcome::CiState::RedOnBase`), for every pull request. + if f.ci.failing() { f.red_on_base = red_on_base(ctx).await; } // Only a read that found no review: a failed read never queues one. @@ -1103,8 +1117,16 @@ async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { /// `proof::holds_blocked_on`). CI was once read only for the first: a pull /// request whose one hold was such a line read CI as "not green" without /// asking, and stayed a draft on every sweep although its CI had passed. +/// +/// Every open draft's CI is read now: a failing check holds any pull +/// request and a running one is waited for (`outcome::ci_blocker`). A pull +/// request with no feature findings once read CI never, and a run whose CI +/// was red end to end had its pull request marked ready. pub fn reads_ci(f: &Facts) -> bool { - f.feature.is_some() || f.security || super::proof::ci_settles_a_hold(&f.body) + !f.closed && f.put_back_by.is_none() + || f.feature.is_some() + || f.security + || super::proof::ci_settles_a_hold(&f.body) } /// A security fix's hold or wait on its CI: failing CI keeps the draft with @@ -1145,6 +1167,25 @@ pub fn security_ci(f: &Facts) -> (Option, Option) { (None, None) } +/// The repository's CI as a hold (failing, with the checks named and what +/// to do) or a wait (running), from the one rule in `outcome`. +pub fn repo_ci(f: &Facts) -> (Option, Option) { + use super::outcome::CiState; + match CiState::of(&f.ci, f.red_on_base) { + CiState::Failing(checks) => ( + Some(Reason::new( + format!("CI is failing on this head: {checks}"), + "Fix the failing checks on this branch (CoderHelm decides again on the push), or \ + re-run them if the failure isn't the change's; the pull request leaves draft once \ + CI is green.", + )), + None, + ), + CiState::Pending(checks) => (None, Some(format!("its CI is still running: {checks}"))), + CiState::NoChecks | CiState::Green | CiState::RedOnBase => (None, None), + } +} + /// Whether a check is CoderHelm's own (its review check, or any check its /// app reports): never the repository's CI. fn own_check(c: &serde_json::Value) -> bool { @@ -1975,13 +2016,19 @@ mod tests { let section = status_section(&d); assert!(section.contains("**This pull request stays a draft.**")); assert!(section.contains("`test`")); - // The same pull request without the marker is any other run's, and - // that run's hand-off still marks it ready for a person. + // The same pull request without the marker is any other run's: it + // is held on its failing check too, never marked ready red + // (`outcome::ci_blocker`). let plain = Facts { security: false, ..f.clone() }; - assert!(matches!(decide(&plain), Decision::Ready { .. })); + let Decision::Held { reasons } = decide(&plain) else { + panic!("held expected"); + }; + assert!(reasons[0] + .line() + .contains("CI is failing on this head: `test`")); // Green CI: ready. let green = Facts { ci: Ci { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 844aff0cf..e7b3c7157 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -735,17 +735,286 @@ fn split_base_failures( /// PR: a check that was green and went red on a small change is the shape a /// flaky test takes (a random id matching a pattern, a timing race). A check /// that never passed is fixed straight away. +/// A failure whose logs read as the runner's or a service's (`infra`, see +/// [`looks_infra`]) is re-run once too, whether or not it passed before. fn should_rerun( head: Option<&str>, rerun_heads: &[String], failing_workflows: &[String], passed_before: &std::collections::HashSet, + infra: bool, ) -> bool { let Some(head) = head.filter(|h| !h.is_empty()) else { return false; }; !rerun_heads.iter().any(|h| h == head) - && failing_workflows.iter().any(|w| passed_before.contains(w)) + && (infra || failing_workflows.iter().any(|w| passed_before.contains(w))) +} + +/// Lines that say a check failed for the runner's or a service's reason, +/// not the code's: a DNS miss, a refused or reset connection, a gateway +/// error, a runner that went away, a full disk, a rate limit. +const INFRA_MARKS: &[&str] = &[ + "getaddrinfo enotfound", + "getaddrinfo eai_again", + "econnreset", + "econnrefused", + "etimedout", + "socket hang up", + "could not resolve host", + "temporary failure in name resolution", + "502 bad gateway", + "503 service unavailable", + "504 gateway time", + "the runner has received a shutdown signal", + "lost communication with the server", + "no space left on device", + "api rate limit exceeded", + "toomanyrequests", + "tls handshake timeout", + "the hosted runner encountered an error", +]; + +/// The infrastructure line a failure's logs show, when they show one: the +/// failure is re-run once before any code changes for it. +pub(crate) fn looks_infra(logs: &str) -> Option { + logs.lines().find_map(|l| { + let low = l.to_lowercase(); + INFRA_MARKS + .iter() + .any(|m| low.contains(m)) + .then(|| common::truncate_str(l.trim(), 300).to_string()) + }) +} + +/// How many fix attempts one CI failure gets, each with fresh evidence and, +/// after one that changed nothing, a different approach +/// (`CODERHELM_CI_FIX_ATTEMPTS`, 1 to 10, default 3). +pub(crate) fn ci_fix_attempts() -> usize { + std::env::var("CODERHELM_CI_FIX_ATTEMPTS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|n| (1..=10).contains(n)) + .unwrap_or(3) +} + +/// The first lines of a failure that say what failed (the failing test or +/// the error), for the pull request and the run page. Empty when the logs +/// say nothing that reads as a failure. +pub(crate) fn failure_excerpt(logs: &str) -> String { + const MARKS: &[&str] = &[ + "error", + "failed", + "failure", + "✘", + "✕", + "×", + "assert", + "expected", + "exception", + "timed out", + "panicked", + ]; + let clean = |l: &str| -> String { + // GitHub's timestamp prefix (`2026-11-11T19:52:01.1234567Z `). + let t = l.trim(); + let t = match t.split_once(' ') { + Some((ts, rest)) if ts.len() >= 20 && ts.as_bytes()[4] == b'-' && ts.ends_with('Z') => { + rest + } + _ => t, + }; + t.trim().to_string() + }; + let lines: Vec = logs + .lines() + .map(clean) + .filter(|l| !l.is_empty() && !l.starts_with("##[group]") && !l.starts_with("##[endgroup]")) + .collect(); + let Some(i) = lines.iter().position(|l| { + let low = l.to_lowercase(); + MARKS.iter().any(|m| low.contains(m)) + && !low.contains("0 failed") + && !low.contains("failed: 0") + }) else { + return String::new(); + }; + let joined = lines[i..lines.len().min(i + 4)].join(" / "); + common::truncate_str(&joined, 400).to_string() +} + +/// Whether a pull request comment is a CI reporter's (a bot that isn't +/// CoderHelm): end-to-end and coverage reporters post the failing test's +/// name and error there, where the job's own log only says it uploaded them. +fn is_ci_reporter(c: &Value) -> bool { + let login = c["user"]["login"].as_str().unwrap_or(""); + let bot = c["user"]["type"].as_str() == Some("Bot") || login.ends_with("[bot]"); + bot && !super::is_own_login(login) && !c["body"].as_str().unwrap_or("").trim().is_empty() +} + +/// The newest CI reporter comments on the pull request (at most three). +async fn ci_reporter_comments(gh: &GitHubClient, owner: &str, repo: &str, pr: u64) -> String { + let Ok(comments) = gh.list_issue_comments(owner, repo, pr).await else { + return String::new(); + }; + comments + .iter() + .rev() + .filter(|c| is_ci_reporter(c)) + .take(3) + .map(|c| { + format!( + "--- comment by {} at {} ---\n{}", + c["user"]["login"].as_str().unwrap_or("a bot"), + c["created_at"].as_str().unwrap_or(""), + common::truncate_str(c["body"].as_str().unwrap_or(""), 4000) + ) + }) + .collect::>() + .join("\n\n") +} + +/// Everything a fix attempt reads about the failure, fresh each attempt: the +/// failing jobs' logs (`logs`), the failing checks' annotations and output, +/// and what CI reporters posted on the pull request. +async fn ci_evidence( + gh: &GitHubClient, + owner: &str, + repo: &str, + branch: &str, + pr: u64, + logs: &str, +) -> String { + let mut out = logs.to_string(); + if !out.contains("Check run annotations:") { + if let Ok(a) = gh.get_check_run_annotations(owner, repo, branch).await { + if !a.trim().is_empty() { + out.push_str("\n\nCheck run annotations and output:\n"); + out.push_str(&a); + } + } + } + let comments = ci_reporter_comments(gh, owner, repo, pr).await; + if !comments.is_empty() { + out.push_str("\n\nWhat CI reporters posted on the pull request (newest first):\n"); + out.push_str(&comments); + } + out +} + +/// The next attempt's instructions after one that changed nothing: the same +/// failure, what was tried, a different approach (reproduce first), and the +/// evidence read again. +pub(crate) fn next_attempt_feedback( + base: &str, + attempt: usize, + max: usize, + tried: &[String], + fresh: &str, +) -> String { + let tried: Vec = tried + .iter() + .enumerate() + .map(|(i, t)| format!("- Attempt {}: {}", i + 1, t)) + .collect(); + format!( + "{base}\n\nThis is CI fix attempt {attempt} of {max}. The earlier attempt(s) changed \ + nothing on the branch, and CI is still failing:\n{}\n\n\ + Take a different approach this time:\n\ + 1. Reproduce first: call run_checks, and run the failing check's own command (the test \ + file or job the evidence names) in the sandbox, before deciding anything.\n\ + 2. Read the evidence below line by line: the failing test's name, its assertion or error, \ + the file and line. CI reporters' comments often hold the failing test when the job log \ + only shows an upload step.\n\ + 3. If a test this pull request added or changed fails, read that test and the code it \ + drives, and fix whichever is wrong.\n\ + 4. Only if the failure truly isn't this pull request's (a service outside the repository \ + is down, a secret is missing), write one line starting `Not this change:` naming the \ + check, the error line, and what a person must do.\n\n\ + Fresh evidence:\n{fresh}", + tried.join("\n") + ) +} + +/// The pull request's section while CI fails and CoderHelm stopped fixing +/// it: the checks, the error, what was tried, what is needed. +pub(crate) const CI_FAILING_START: &str = ""; +pub(crate) const CI_FAILING_END: &str = ""; + +pub(crate) fn ci_failing_section( + checks: &[String], + excerpt: &str, + tried: &[String], + needed: &str, +) -> String { + let names = if checks.is_empty() { + "the repository's CI".to_string() + } else { + checks + .iter() + .map(|c| format!("`{c}`")) + .collect::>() + .join(", ") + }; + let mut lines = vec![format!("**CI is failing:** {names}.")]; + if !excerpt.trim().is_empty() { + lines.push(format!( + "- **Error:** `{}`", + excerpt.trim().replace('`', "'") + )); + } + if tried.is_empty() { + lines.push("- **Tried:** nothing yet.".to_string()); + } else { + lines.push(format!("- **Tried:** {}", tried.join("; "))); + } + lines.push(format!("- **Needed:** {}", needed.trim())); + format!( + "{CI_FAILING_START}\n## CI is failing\n{}\n{CI_FAILING_END}", + lines.join("\n") + ) +} + +/// The description with the CI failing section in place (replacing an older +/// one), right after the ticket line. +pub(crate) fn with_ci_failing(body: &str, section: &str) -> String { + let mut rest = body.to_string(); + if let (Some(a), Some(b)) = (rest.find(CI_FAILING_START), rest.find(CI_FAILING_END)) { + if b > a { + rest.replace_range(a..b + CI_FAILING_END.len(), ""); + } + } + let rest = rest.replace("\n\n\n\n", "\n\n"); + let first = rest.lines().next().unwrap_or("").trim().to_string(); + let ticket_first = first.starts_with("Source ticket:") + || first.starts_with("Closes #") + || first.starts_with("Fixes #"); + if ticket_first { + let after = rest[rest.find('\n').unwrap_or(rest.len())..].trim_start(); + format!("{first}\n\n{section}\n\n{after}") + } else { + format!("{section}\n\n{}", rest.trim_start()) + } +} + +/// The run's reason while its pull request's CI fails, in one sentence. +pub(crate) fn ci_failing_reason(checks: &[String], excerpt: &str, tried: usize) -> String { + let names = if checks.is_empty() { + "the repository's CI".to_string() + } else { + checks.join(", ") + }; + let mut r = format!("CI is failing: {names}"); + if !excerpt.trim().is_empty() { + r.push_str(&format!(": {}", common::truncate_str(excerpt.trim(), 240))); + } + if tried > 0 { + r.push_str(&format!( + ". CoderHelm made {tried} fix attempt(s) without getting it green" + )); + } + r.push_str(". The pull request stays a draft until CI passes"); + r } /// How long a failure waits for the rest of its head's checks to finish @@ -845,23 +1114,121 @@ mod ci_triage_tests { fn a_once_green_check_is_rerun_once_per_head() { let passed: HashSet = ["Test Suite".to_string()].into(); let failing = vec!["Test Suite".to_string()]; - assert!(should_rerun(Some("abc"), &[], &failing, &passed)); + assert!(should_rerun(Some("abc"), &[], &failing, &passed, false)); // Already re-run on this head: spend the attempt. assert!(!should_rerun( Some("abc"), &["abc".to_string()], &failing, - &passed + &passed, + false )); // Never green on this PR: fix it, a re-run would only wait. assert!(!should_rerun( Some("abc"), &[], &["Lint".to_string()], - &passed + &passed, + false )); // Unknown head: can't track the one re-run. - assert!(!should_rerun(None, &[], &failing, &passed)); + assert!(!should_rerun(None, &[], &failing, &passed, false)); + } + + /// A check that never passed but failed on a service outside the code + /// (the e2e job's staging API didn't resolve) is re-run once, not + /// "fixed"; on a head already re-run, the attempt is spent. + #[test] + fn an_infrastructure_failure_is_rerun_once() { + let logs = "2026-11-11T19:50:01.0000000Z FAIL src/test/integration/real-server.test.ts\n\ + 2026-11-11T19:50:01.0000000Z Error: getaddrinfo ENOTFOUND search-staging.example.internal"; + let infra = looks_infra(logs); + assert!( + infra.as_deref().unwrap_or("").contains("ENOTFOUND"), + "{infra:?}" + ); + let passed: HashSet = HashSet::new(); + let failing = vec!["E2E".to_string()]; + assert!(should_rerun( + Some("abc"), + &[], + &failing, + &passed, + infra.is_some() + )); + assert!(!should_rerun( + Some("abc"), + &["abc".into()], + &failing, + &passed, + true + )); + // A plain assertion failure is the code's: no re-run. + assert!( + looks_infra("expect(received).toBe(expected)\nExpected: 16\nReceived: 12").is_none() + ); + } + + #[test] + fn the_failure_excerpt_is_the_error_not_the_upload_step() { + let logs = "2026-11-11T19:50:00.1234567Z ##[group]Upload report\n\ + 2026-11-11T19:50:00.1234567Z Uploaded 14 files\n\ + 2026-11-11T19:49:58.1234567Z 1) [chromium] venues.spec.ts:131 the Info heading lines up\n\ + 2026-11-11T19:49:58.1234567Z Error: expect(received).toBeLessThanOrEqual(expected)\n\ + 2026-11-11T19:49:58.1234567Z Expected: <= 1\n\ + 2026-11-11T19:49:58.1234567Z Received: 32"; + let e = failure_excerpt(logs); + assert!( + e.starts_with("Error: expect(received).toBeLessThanOrEqual(expected)"), + "{e}" + ); + assert!(e.contains("Received: 32"), "{e}"); + assert_eq!(failure_excerpt("all good\n12 passed, 0 failed"), ""); + } + + #[test] + fn ci_reporters_are_bots_other_than_coderhelm() { + let c = |login: &str, kind: &str| json!({"user": {"login": login, "type": kind}, "body": "E2E: Playwright\n1 failed"}); + assert!(is_ci_reporter(&c("github-actions[bot]", "Bot"))); + assert!(!is_ci_reporter(&c("a-person", "User"))); + } + + /// The red-CI run: one fix attempt changed nothing. The next attempt is + /// told what was tried, to reproduce first, and gets the evidence again; + /// once attempts run out the pull request says exactly what fails. + #[test] + fn a_fix_that_changed_nothing_gets_a_different_attempt_then_a_precise_hold() { + assert_eq!(ci_fix_attempts(), 3); + let fb = next_attempt_feedback( + "CI workflow failed on PR #21.", + 2, + 3, + &["changed nothing: the log only showed the report upload".into()], + "--- comment by e2e-reporter[bot] ---\n1 failed: venues.spec.ts:131", + ); + assert!(fb.contains("CI fix attempt 2 of 3")); + assert!(fb.contains("Reproduce first: call run_checks")); + assert!(fb.contains("- Attempt 1: changed nothing")); + assert!(fb.contains("venues.spec.ts:131")); + let checks = vec!["Deploy Preview".to_string()]; + let excerpt = "Error: expect(received).toBeLessThanOrEqual(expected) / Expected: <= 1"; + let section = ci_failing_section( + &checks, + excerpt, + &["3 attempts changed nothing".into()], + "a person reads the end-to-end report", + ); + let body = with_ci_failing("Source ticket: WEB-14\n\n## Summary\nx", §ion); + assert!(body.starts_with("Source ticket: WEB-14\n\n\n## CI is failing\n**CI is failing:** `Deploy Preview`."), "{body}"); + assert!(body.contains("- **Error:** `Error: expect(received)")); + assert!(body.contains("## Summary\nx")); + // Written again, it replaces the old section. + let again = with_ci_failing(&body, §ion); + assert_eq!(again.matches(CI_FAILING_START).count(), 1); + let reason = ci_failing_reason(&checks, excerpt, 3); + assert!(reason.starts_with("CI is failing: Deploy Preview: Error: expect")); + assert!(reason.contains("3 fix attempt(s)")); + assert!(reason.contains("stays a draft")); } #[test] @@ -1500,6 +1867,7 @@ pub async fn run( &repo_name, branch_head.as_deref(), &events, + None, ) .await { @@ -1781,6 +2149,39 @@ pub async fn run( } }; + // Every attempt reads the whole failure: the jobs' logs, the failing + // checks' annotations and output, and what CI reporters posted on the + // pull request (an end-to-end job's log can show only its upload step). + let job_logs = logs; + let logs = ci_evidence( + &github, + &repo_owner, + &repo_name, + &branch, + pr_number, + &job_logs, + ) + .await; + // A failure on the runner or a service outside the code is re-run + // once before any code changes for it. + if let Some(line) = looks_infra(&logs) { + if try_rerun_once( + state, + &msg, + &github, + &run_record, + &repo_owner, + &repo_name, + branch_head.as_deref(), + &events, + Some(line), + ) + .await + { + return Ok(()); + } + } + // Load checkpoint for review cycle count let cycle = load_cycle_from_checkpoint(state, &msg.team_id, &msg.run_id).await; let over_cycle = cycle >= MAX_CI_FIX_CYCLES; @@ -1791,42 +2192,29 @@ pub async fn run( if over_cycle || !claimed { warn!( run_id = msg.run_id, - cycle, "Fix budget reached — completing for human review" + cycle, "Fix budget reached — the PR stays a draft with what fails" ); - super::record_ci_outcome( - state, - &msg.team_id, - &msg.run_id, - super::CiOutcome::HandedOff(super::GaveUp::Budget), - ) - .await; - // Every terminal path consumes its events; left unprocessed, the - // next resume (e.g. after a re-review) replayed these failures. - mark_events_processed(state, &msg.run_id, &events).await; - complete_run_with_status( + return hand_off_red_ci( state, + &msg, &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, + &github, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, &usage, wall_clock_secs(created_at, &start), - ) - .await?; - - // Still mark PR ready — let human review - mark_pr_ready( - state, - &msg.team_id, - &github, - &repo_owner, - &repo_name, - pr_number, + &events, + super::GaveUp::Budget, + &failure_excerpt(&logs), + &[format!("{cycle} fix cycle(s) on this pull request")], + "CoderHelm's fix budget for this run is spent: fix the failing check on this branch, or re-run it if it isn't the change's.", ) .await; - return Ok(()); } // Halt-on-no-progress: if the SAME failure keeps recurring, the fixes @@ -1836,50 +2224,29 @@ pub async fn run( if check_and_record_stall(state, &msg.team_id, &msg.run_id, &logs).await { warn!( run_id = msg.run_id, - "CI fixes stalled on the same failure — handing PR to human review" + "CI fixes stalled on the same failure — the PR stays a draft with what fails" ); - super::add_progress_note( - state, - &msg.team_id, - &msg.run_id, - "Automated fixes stalled on the same failure (no progress) — handed off for human review.", - ) - .await; - super::record_ci_outcome( - state, - &msg.team_id, - &msg.run_id, - super::CiOutcome::HandedOff(super::GaveUp::Stalled), - ) - .await; - // mark_pr_ready squashes the branch (while the PR is still a draft) - // before un-drafting, so the placeholder→revert→refix churn collapses - // into one clean commit here — no separate squash needed. The churn - // only ever leaked before because a stall-blind run timed out and - // never reached this handoff. - mark_events_processed(state, &msg.run_id, &events).await; - mark_pr_ready( - state, - &msg.team_id, - &github, - &repo_owner, - &repo_name, - pr_number, - ) - .await; - complete_run_with_status( + return hand_off_red_ci( state, + &msg, &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, + &github, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, &usage, wall_clock_secs(created_at, &start), + &events, + super::GaveUp::Stalled, + &failure_excerpt(&logs), + &["the same failure came back after each fix".to_string()], + "A person looks at the failing check: CoderHelm's fixes keep meeting the same failure.", ) - .await?; - return Ok(()); + .await; } // Implement fix @@ -1998,159 +2365,84 @@ pub async fn run( .await .ok(); - match implement::run( - state, - &ticket_msg, - &github, - &plan_result, - &ci_round.wip_branch, - &rules, - &repo_instructions, - Some(&feedback), - "medium", - &provider, - &mut usage, - &file_cache, - Some(&msg.run_id), - Some(super::round::deadline(start)), - // Scope to the PR only when this cycle is purely CI-driven; if - // human review comments ride along, the human's ask wins. - review_feedback.is_empty(), - ) - .await - { - Ok(result) if result.timed_out => { - // Out of its budget with work left: what it wrote is - // committed; the rest continues in a fresh step, or the run - // says the round didn't finish. - write_pass_trace( - state, - &msg.team_id, - &msg.run_id, - &format!("ci_fix:{}", cycle + 1), - pass_start, - &usage_before, - &usage, - None, - ) - .await; - mark_events_processed(state, &msg.run_id, &events).await; - if ci_round.may_continue() { - park_round( + // Up to `ci_fix_attempts` attempts on this failure in this round: one + // that changes nothing is followed by one with a different approach + // and fresh evidence, never by "completed". + let max_attempts = ci_fix_attempts(); + let mut attempt = 1usize; + let mut tried: Vec = Vec::new(); + let base_feedback = feedback + .split("\n\nFull logs:\n") + .next() + .unwrap_or(&feedback) + .to_string(); + let mut feedback = feedback; + loop { + match implement::run( + state, + &ticket_msg, + &github, + &plan_result, + &ci_round.wip_branch, + &rules, + &repo_instructions, + Some(&feedback), + "medium", + &provider, + &mut usage, + &file_cache, + Some(&msg.run_id), + Some(super::round::deadline(start)), + // Scope to the PR only when this cycle is purely CI-driven; if + // human review comments ride along, the human's ask wins. + review_feedback.is_empty(), + ) + .await + { + Ok(result) if result.timed_out => { + // Out of its budget with work left: what it wrote is + // committed; the rest continues in a fresh step, or the run + // says the round didn't finish. + write_pass_trace( state, - &msg, - (&ticket_msg, &usage), - &pr_ref, - &ci_round, - true, - created_at, - &start, + &msg.team_id, + &msg.run_id, + &format!("ci_fix:{}", cycle + 1), + pass_start, + &usage_before, + &usage, + None, ) - .await?; - return Ok(()); - } - super::round::finish_incomplete( - state, - &msg.team_id, - &msg.run_id, - &super::round::Pr { - github: &github, - owner: &repo_owner, - repo: &repo_name, - branch: &branch, - }, - &ci_round, - &run_round::out_of_time(ci_round.kind, ci_round.attempt), - ) - .await; - complete_run_with_status( - state, - &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, - &usage, - wall_clock_secs(created_at, &start), - ) - .await?; - return Ok(()); - } - Ok(mut result) => { - // One commit, one push: the fix lands on the pull request. - let message = - super::round::round_message(state, &msg.team_id, &ticket_msg, &ci_round).await; - let gh = super::round::Pr { - github: &github, - owner: &repo_owner, - repo: &repo_name, - branch: &branch, - }; - match super::round::land(&gh, &ci_round.wip_branch, &ci_round.base_sha, &message) - .await - { - super::round::Landed::Pushed { .. } => {} - super::round::Landed::Nothing => result.files_modified.clear(), - super::round::Landed::Refused(why) => { - mark_events_processed(state, &msg.run_id, &events).await; - super::round::finish_incomplete( + .await; + mark_events_processed(state, &msg.run_id, &events).await; + if ci_round.may_continue() { + park_round( state, - &msg.team_id, - &msg.run_id, - &gh, + &msg, + (&ticket_msg, &usage), + &pr_ref, &ci_round, - &format!("its changes couldn't land on the pull request: {why}"), - ) - .await; - complete_run_with_status( - state, - &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, - &usage, - wall_clock_secs(created_at, &start), + true, + created_at, + &start, ) - .await?; - return Ok(()); - } - } - super::round::clear(state, &msg.team_id, &msg.run_id).await; - info!( - run_id = msg.run_id, - files = result.files_modified.len(), - "CI fix implemented" - ); - write_pass_trace( - state, - &msg.team_id, - &msg.run_id, - &format!("ci_fix:{}", cycle + 1), - pass_start, - &usage_before, - &usage, - None, - ) - .await; - - if result.files_modified.is_empty() { - warn!( - run_id = msg.run_id, - "CI fix produced no changes — completing with PR for human review" - ); - super::webhooks::emit_ci_fix_completed(state, &ci_fix, "no_changes", 0).await; - super::record_ci_outcome( + .await?; + return Ok(()); + } + super::round::finish_incomplete( state, &msg.team_id, &msg.run_id, - super::CiOutcome::HandedOff(super::GaveUp::NoChange), + &super::round::Pr { + github: &github, + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + }, + &ci_round, + &run_round::out_of_time(ci_round.kind, ci_round.attempt), ) .await; - // Don't hard-fail — complete the run and mark PR ready for human review - mark_events_processed(state, &msg.run_id, &events).await; complete_run_with_status( state, &ticket_msg, @@ -2163,72 +2455,224 @@ pub async fn run( wall_clock_secs(created_at, &start), ) .await?; - mark_pr_ready( + return Ok(()); + } + Ok(mut result) => { + // One commit, one push: the fix lands on the pull request. + let message = + super::round::round_message(state, &msg.team_id, &ticket_msg, &ci_round) + .await; + let gh = super::round::Pr { + github: &github, + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + }; + match super::round::land( + &gh, + &ci_round.wip_branch, + &ci_round.base_sha, + &message, + ) + .await + { + super::round::Landed::Pushed { .. } => {} + super::round::Landed::Nothing => result.files_modified.clear(), + super::round::Landed::Refused(why) => { + mark_events_processed(state, &msg.run_id, &events).await; + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &gh, + &ci_round, + &format!("its changes couldn't land on the pull request: {why}"), + ) + .await; + complete_run_with_status( + state, + &ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + return Ok(()); + } + } + // What the fix read and tried, on the run page like every pass. + super::write_conversation_log( state, &msg.team_id, + &msg.run_id, + &format!("ci_fix_{}_{attempt}", cycle + 1), + &result.conversation_log, + ) + .await; + if !result.files_modified.is_empty() { + super::round::clear(state, &msg.team_id, &msg.run_id).await; + } + info!( + run_id = msg.run_id, + files = result.files_modified.len(), + attempt, + "CI fix implemented" + ); + write_pass_trace( + state, + &msg.team_id, + &msg.run_id, + &format!("ci_fix:{}", cycle + 1), + pass_start, + &usage_before, + &usage, + None, + ) + .await; + + if result.files_modified.is_empty() { + let said = result + .evidence + .notes + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("no explanation"); + tried.push(format!( + "attempt {attempt} changed nothing ({})", + common::truncate_str(said, 240) + )); + if attempt < max_attempts + && super::round::may_start(start, std::time::Instant::now()) + { + attempt += 1; + warn!( + run_id = msg.run_id, + attempt, max_attempts, "CI fix changed nothing — the next attempt takes a different approach" + ); + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "CI fix attempt {} of {max_attempts} changed nothing; attempt {attempt} reproduces the failure first and reads the evidence again.", + attempt - 1 + ), + ) + .await; + let fresh = ci_evidence( + &github, + &repo_owner, + &repo_name, + &branch, + pr_number, + &job_logs, + ) + .await; + feedback = next_attempt_feedback( + &base_feedback, + attempt, + max_attempts, + &tried, + &fresh, + ); + continue; + } + warn!( + run_id = msg.run_id, + attempts = attempt, + "CI fix produced no changes — the PR stays a draft with what fails, the run needs attention" + ); + super::round::clear(state, &msg.team_id, &msg.run_id).await; + super::webhooks::emit_ci_fix_completed(state, &ci_fix, "no_changes", 0) + .await; + return hand_off_red_ci( + state, + &msg, + &ticket_msg, &github, - &repo_owner, - &repo_name, - pr_number, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, + &usage, + wall_clock_secs(created_at, &start), + &events, + super::GaveUp::NoChange, + &failure_excerpt(&logs), + &tried, + "A person reads the failing check's report (its test name and error are above) and fixes it on this branch, or re-runs it if the failure isn't this change's.", + ) + .await; + } + super::webhooks::emit_ci_fix_completed( + state, + &ci_fix, + "pushed", + result.files_modified.len(), ) .await; - return Ok(()); } - super::webhooks::emit_ci_fix_completed( - state, - &ci_fix, - "pushed", - result.files_modified.len(), - ) - .await; - } - Err(e) => { - if wait_for_github(state, &msg, &*e).await - || requeue_after_model_error(state, &msg, &*e).await - { - return Ok(()); + Err(e) => { + if wait_for_github(state, &msg, &*e).await + || requeue_after_model_error(state, &msg, &*e).await + { + return Ok(()); + } + error!(run_id = msg.run_id, error = %e, "CI fix implementation failed — the PR stays a draft, the round is named as not finished"); + super::webhooks::emit_ci_fix_completed(state, &ci_fix, "failed", 0).await; + // Not "failed", and not handed over as if done: the run says + // the round didn't finish and what it pushed; Resume runs it + // again. + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &super::round::Pr { + github: &github, + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + }, + &ci_round, + &run_round::errored(ci_round.kind, &common::run_fail::error_text(&*e)), + ) + .await; + tried.push(format!( + "attempt {attempt} errored: {}", + common::truncate_str(&common::run_fail::error_text(&*e), 240) + )); + return hand_off_red_ci( + state, + &msg, + &ticket_msg, + &github, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, + &usage, + wall_clock_secs(created_at, &start), + &events, + super::GaveUp::FixError, + &failure_excerpt(&logs), + &tried, + "Retry the run from its page, or fix the failing check on this branch.", + ) + .await; } - error!(run_id = msg.run_id, error = %e, "CI fix implementation failed — the PR stays open, the round is named as not finished"); - super::webhooks::emit_ci_fix_completed(state, &ci_fix, "failed", 0).await; - super::record_ci_outcome( - state, - &msg.team_id, - &msg.run_id, - super::CiOutcome::HandedOff(super::GaveUp::FixError), - ) - .await; - mark_events_processed(state, &msg.run_id, &events).await; - // Not "failed", and not handed over as if done: the run says - // the round didn't finish and what it pushed; Resume runs it - // again. - super::round::finish_incomplete( - state, - &msg.team_id, - &msg.run_id, - &super::round::Pr { - github: &github, - owner: &repo_owner, - repo: &repo_name, - branch: &branch, - }, - &ci_round, - &run_round::errored(ci_round.kind, &common::run_fail::error_text(&*e)), - ) - .await; - complete_run_with_status( - state, - &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, - &usage, - wall_clock_secs(created_at, &start), - ) - .await?; - return Ok(()); } + break; } // A fix that left the tree unchanged (or returned it to an earlier @@ -2249,45 +2693,29 @@ pub async fn run( { warn!( run_id = msg.run_id, - "CI fixes are not changing the code — handing PR to human review" + "CI fixes are not changing the code — the PR stays a draft with what fails" ); - super::add_progress_note( - state, - &msg.team_id, - &msg.run_id, - "Automated fixes stopped changing the code (same files, same bytes) — handed off for human review.", - ) - .await; - super::record_ci_outcome( - state, - &msg.team_id, - &msg.run_id, - super::CiOutcome::HandedOff(super::GaveUp::NoProgress), - ) - .await; - mark_events_processed(state, &msg.run_id, &events).await; - mark_pr_ready( - state, - &msg.team_id, - &github, - &repo_owner, - &repo_name, - pr_number, - ) - .await; - complete_run_with_status( + return hand_off_red_ci( state, + &msg, &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, + &github, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, &usage, wall_clock_secs(created_at, &start), + &events, + super::GaveUp::NoProgress, + &failure_excerpt(&logs), + &["fixes stopped changing the code (same files, same bytes)".to_string()], + "A person looks at the failing check: CoderHelm's fixes stopped changing the code.", ) - .await?; - return Ok(()); + .await; } // The fix changed code: count it before going back to wait for CI. @@ -4171,6 +4599,7 @@ async fn try_rerun_once( name: &str, head: Option<&str>, events: &[RunEvent], + infra: Option, ) -> bool { let failed: Vec<&RunEvent> = events .iter() @@ -4187,7 +4616,13 @@ async fn try_rerun_once( .filter_map(|e| e.payload["workflow_name"].as_str().map(str::to_string)) .collect(); let passed_before = ci_passed_workflows(state, &msg.run_id).await; - if !should_rerun(head, &rerun_heads(run_record), &workflows, &passed_before) { + if !should_rerun( + head, + &rerun_heads(run_record), + &workflows, + &passed_before, + infra.is_some(), + ) { return false; } let mut started = false; @@ -4205,7 +4640,7 @@ async fn try_rerun_once( if !started { return false; } - info!(run_id = msg.run_id, workflows = ?workflows, "CI failed on a check that passed earlier on this PR — re-running once before a fix"); + info!(run_id = msg.run_id, workflows = ?workflows, infra = ?infra, "CI failed on a check that passed earlier on this PR, or on infrastructure — re-running once before a fix"); super::record_ci_outcome( state, &msg.team_id, @@ -4217,10 +4652,16 @@ async fn try_rerun_once( state, &msg.team_id, &msg.run_id, - &format!( - "CI failed on {} after passing earlier on this PR — re-running the failed jobs once before changing code.", - workflows.join(", ") - ), + &match &infra { + Some(line) => format!( + "CI failed on {} for a reason outside the code ({line}) — re-running the failed jobs once before changing code.", + workflows.join(", ") + ), + None => format!( + "CI failed on {} after passing earlier on this PR — re-running the failed jobs once before changing code.", + workflows.join(", ") + ), + }, ) .await; // The failures this re-run replaces; the re-run's own result arrives as @@ -5041,6 +5482,79 @@ async fn stop_on_own_findings( .await } +/// The checks a CI failure's events name (their workflows), in order. +fn failing_workflows(events: &[RunEvent]) -> Vec { + events + .iter() + .filter(|e| e.event_type == "ci_failed") + .filter_map(|e| e.payload["workflow_name"].as_str().map(str::to_string)) + .collect::>() + .into_iter() + .collect() +} + +/// The one way a run stops fixing a red CI: the pull request says what +/// fails (the check, the error, what was tried, what is needed), stays a +/// draft through the one ready decision (`ready::decide` holds on a failing +/// check), and the run waits on a person (`needs_input`, notified like every +/// run that needs attention). Never "completed", never marked ready. +#[allow(clippy::too_many_arguments)] +async fn hand_off_red_ci( + state: &WorkerState, + msg: &ResumeMessage, + ticket_msg: &TicketMessage, + github: &GitHubClient, + pr: &PrRef<'_>, + usage: &TokenUsage, + duration: u64, + events: &[RunEvent], + why: super::GaveUp, + excerpt: &str, + tried: &[String], + needed: &str, +) -> Result<(), Box> { + super::record_ci_outcome( + state, + &msg.team_id, + &msg.run_id, + super::CiOutcome::HandedOff(why), + ) + .await; + mark_events_processed(state, &msg.run_id, events).await; + let checks = failing_workflows(events); + let section = ci_failing_section(&checks, excerpt, tried, needed); + match github.get_pull_request(pr.owner, pr.repo, pr.number).await { + Ok(p) => { + let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); + if let Err(e) = github + .update_pr_body(pr.owner, pr.repo, pr.number, &body) + .await + { + warn!(run_id = msg.run_id, error = %e, "Could not write what fails on the pull request"); + } + } + Err(e) => { + warn!(run_id = msg.run_id, error = %e, "Could not read the pull request to say what fails") + } + } + let reason = ci_failing_reason(&checks, excerpt, tried.len()); + super::add_progress_note(state, &msg.team_id, &msg.run_id, &reason).await; + // The one ready decision: a failing check holds the draft, named. + mark_pr_ready(state, &msg.team_id, github, pr.owner, pr.repo, pr.number).await; + wait_for_review( + state, + ticket_msg, + &msg.run_id, + &reason, + pr.url, + pr.number, + pr.branch, + usage, + duration, + ) + .await +} + /// The run stops with its work on its pull request and something open on /// it: it waits on a person (`needs_input`), named as the pull request's /// review with `reason` as what is open (never a wait for nothing). @@ -5109,6 +5623,57 @@ async fn wait_on_person( .await } +/// The outcome rule over the run's CI record: `Some(why)` when its last CI +/// result on the pull request is a failure that is this change's (not one the +/// base branch has too, not an unrelated test fixed elsewhere). +async fn red_ci_blocks_completion( + state: &WorkerState, + team_id: &str, + run_id: &str, +) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("ci_last, ci_end") + .consistent_read(true) + .send() + .await + .ok()? + .item?; + let read = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let facts = super::outcome::Facts { + tasks_remaining: vec![], + ci: ci_state_of_record(&read("ci_last"), &read("ci_end")), + review: super::outcome::Review::Missing, + stop: None, + }; + let o = super::outcome::decide(&facts); + let broken = super::outcome::broken_rules(&facts, &o); + if !broken.is_empty() { + error!(run_id, broken = ?broken, "The run's outcome breaks a rule"); + } + (o.status != super::outcome::RunStatus::Completed).then(|| o.reasons.join("; ")) +} + +/// The run's CI standing from its record: `ci_last` and why the fix loop +/// ended (`ci_end`). +pub(crate) fn ci_state_of_record(ci_last: &str, ci_end: &str) -> super::outcome::CiState { + use super::outcome::CiState; + match (ci_last, ci_end) { + ("failed", "red_on_base" | "unrelated_test") => CiState::RedOnBase, + ("failed", _) => CiState::Failing("the pull request's checks".to_string()), + _ => CiState::Green, + } +} + /// Ends the run as `status`. A wait on a person goes through /// [`wait_for_review`], which names what it waits for. #[allow(clippy::too_many_arguments)] @@ -5124,6 +5689,18 @@ async fn complete_run_with_status( duration: u64, ) -> Result<(), Box> { debug_assert_ne!(status, "needs_input", "use wait_for_review"); + // The one outcome rule (`outcome::decide`): a run whose pull request's CI + // is red, by its own record, is never completed. It waits on a person, + // with why, on every path that would have said "completed". + if status == common::run_status::COMPLETED && pr_number > 0 { + if let Some(reason) = red_ci_blocks_completion(state, &msg.team_id, run_id).await { + warn!(run_id, reason = %reason, "A run whose CI is red is never completed: it waits on a person"); + return wait_for_review( + state, msg, run_id, &reason, pr_url, pr_number, branch, usage, duration, + ) + .await; + } + } end_run( state, msg, diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs index 2f6d68789..c678d6850 100644 --- a/services/worker/src/passes/steps.rs +++ b/services/worker/src/passes/steps.rs @@ -104,12 +104,17 @@ pub fn stops_for_stall(stalled: u32) -> bool { stalled >= MAX_STALLED_STEPS } -/// Why a stalled run stops, in a sentence. -pub fn stall_reason(step: u32, head: &str, at: &str, kept: &str) -> String { +/// Why a stalled run stops, in a sentence, naming the planned task it was +/// on when it knows (`task 8 of 8 (`path`: what)`). +pub fn stall_reason(step: u32, head: &str, at: &str, kept: &str, task: Option<&str>) -> String { let short: String = head.chars().take(7).collect(); + let on = match task { + Some(t) if !t.trim().is_empty() => format!(" while working on {}", t.trim()), + _ => String::new(), + }; format!( "Stopped: steps {} and {} made no progress. The branch stayed at {short} and the run was \ - stuck at {}. The work so far is kept on branch `{kept}`.", + stuck at {}{on}. The work so far is kept on branch `{kept}`.", step.saturating_sub(2).max(1), step.saturating_sub(1).max(1), where_label(at) @@ -542,7 +547,7 @@ mod tests { assert!(!stops_for_stall(s1), "one stalled step keeps going"); let s2 = stalled_after(Some(&mark), &mark, s1); assert!(stops_for_stall(s2)); - let why = stall_reason(7, "abcdef1234", "generators", "coderhelm-wip/x"); + let why = stall_reason(7, "abcdef1234", "generators", "coderhelm-wip/x", None); assert!(why.contains("steps 5 and 6 made no progress"), "{why}"); assert!(why.contains("abcdef1"), "{why}"); assert!(why.contains("generator check"), "{why}"); diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index e6f1edc72..7289cda20 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -16,7 +16,7 @@ //! approval nobody answered) still ends the run as it did. use crate::clients::github::GitHubClient; -use crate::models::{TicketMessage, TicketSource}; +use crate::models::TicketMessage; use crate::WorkerState; use common::run_status::EndedValues; use common::run_wait::{NeedsInput, WaitingOn}; @@ -28,19 +28,95 @@ pub fn opens_pr(last_pass: &str) -> bool { matches!(last_pass, "implement_started" | "implement" | "security") } -/// The ticket line: `Closes #n` for a GitHub issue, else the ticket id. -fn ticket_line(msg: &TicketMessage) -> String { - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - format!("Closes #{}", msg.issue_number) +/// What the run did of its plan when it stopped: the tasks done and the +/// tasks left, each as the plan wrote it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Progress { + pub done: Vec, + pub remaining: Vec, +} + +impl Progress { + /// From the plan check's coverage of the branch. + pub fn of(cov: &super::plan_coverage::Coverage) -> Progress { + let line = |t: &super::plan_coverage::PlanTask| format!("`{}`: {}", t.path, t.task); + Progress { + done: cov.done.iter().map(line).collect(), + remaining: cov.required_missing().into_iter().map(line).collect(), + } + } +} + +/// The "Not finished" section of a run stopped before its work was done: +/// why it stopped (the recorded reason, in plain words), what is done, what +/// is left, and what a person can do. It keeps the pull request a draft +/// (`proof::holds_unfinished`). +pub fn not_finished(stop: &super::outcome::Stop, progress: &Progress, run_link: &str) -> String { + let total = progress.done.len() + progress.remaining.len(); + let mut lines = vec![format!("- **Why it stopped:** {}.", stop.words())]; + if total > 0 { + let done = if progress.done.is_empty() { + "none".to_string() + } else { + progress.done.join("; ") + }; + lines.push(format!( + "- **Done ({} of {total}):** {}", + progress.done.len(), + common::truncate_str(&done, 1500) + )); + if !progress.remaining.is_empty() { + lines.push(format!("- **Not done ({}):**", progress.remaining.len())); + for (i, r) in progress.remaining.iter().take(15).enumerate() { + lines.push(format!( + " - [ ] task {} of {total}: {}", + progress.done.len() + i + 1, + common::truncate_str(r, 300) + )); + } + } + } + lines.push( + "- **What you can do:** finish what is left on this branch (CoderHelm picks up a push \ + or a comment here), comment with what to change, or delete this section if the work \ + left isn't needed. Then mark the pull request ready." + .to_string(), + ); + if !run_link.is_empty() { + lines.push(format!("- **Run:** {run_link}")); + } + format!( + "{}\n## Not finished\nThis pull request stays a draft: the run stopped before its work \ + was done.\n{}\n{}", + super::proof::UNFINISHED_START, + lines.join("\n"), + super::proof::UNFINISHED_END + ) +} + +/// `body` with the "Not finished" section in place: an older one replaced, +/// else right after the ticket line (or at the top). +pub fn with_unfinished(body: &str, section: &str) -> String { + let (start, end) = (super::proof::UNFINISHED_START, super::proof::UNFINISHED_END); + if let (Some(a), Some(b)) = (body.find(start), body.find(end)) { + if b > a { + return format!("{}{}{}", &body[..a], section.trim(), &body[b + end.len()..]); + } + } + let first = body.lines().next().unwrap_or("").trim(); + if first.starts_with("Source ticket:") || first.starts_with("Closes #") { + let rest = body[body.find('\n').unwrap_or(body.len())..].trim_start(); + format!("{first}\n\n{}\n\n{rest}", section.trim()) } else { - format!("Source ticket: {}", msg.ticket_id) + format!("{}\n\n{}", section.trim(), body.trim_start()) } } -/// The draft pull request's body: the ticket line, why the run stopped, what -/// is left as the open item, and what the checks left open (`open`, already -/// rendered with its own heading, or empty). -pub fn body(ticket: &str, reason: &str, files: &[String], open: &str) -> String { +/// The draft pull request's body: the ticket line, what is not finished +/// (when the run stopped mid-work), why the run stopped, the changes, what +/// was verified, and what the checks left open (`open`, already rendered +/// with its own heading, or empty). +pub fn body(ticket: &str, reason: &str, files: &[String], open: &str, unfinished: &str) -> String { let reason = reason.split_whitespace().collect::>().join(" "); let shown: Vec = files.iter().take(20).map(|f| format!("- `{f}`")).collect(); let more = files.len().saturating_sub(shown.len()); @@ -49,9 +125,16 @@ pub fn body(ticket: &str, reason: &str, files: &[String], open: &str) -> String } else { open.trim().to_string() }; + let top = if unfinished.trim().is_empty() { + String::new() + } else { + format!("{}\n\n", unfinished.trim()) + }; format!( - "{ticket}\n\n## Summary\n\nCoderHelm did this ticket's work on this branch and stopped \ - before marking it ready: {reason}\n\n## Changes\n\n{}{}\n\n{open_items}\n\n\ + "{ticket}\n\n{top}## Summary\n\nCoderHelm worked on this ticket on this branch and \ + stopped before marking it ready: {reason}\n\n## Changes\n\n{}{}\n\n## Verification\n\n\ + Not yet verified as a whole: the run stopped before its checks after the work finished. \ + The repository's CI runs on this pull request.\n\n{open_items}\n\n\ This is a draft. Push to this branch or comment on this pull request, and CoderHelm picks \ it up from here.", shown.join("\n"), @@ -63,6 +146,41 @@ pub fn body(ticket: &str, reason: &str, files: &[String], open: &str) -> String ) } +/// The plan's progress on the branch, when the run has a plan with tasks. +async fn progress( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + branch: &str, +) -> Progress { + let Some(plan) = super::run_plan_files(state, msg).await else { + return Progress::default(); + }; + let tasks = super::plan_coverage::tasks_for( + github, + &msg.repo_owner, + &msg.repo_name, + branch, + &plan.tasks, + ) + .await; + if tasks.is_empty() { + return Progress::default(); + } + match super::plan_coverage::plan_changes( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + ) + .await + { + Some(c) => Progress::of(&c.coverage(&tasks)), + None => Progress::default(), + } +} + /// Opens (or finds) the draft pull request for a stopped run's branch and /// records it on the run. Errors when the branch holds no work. pub async fn open( @@ -140,12 +258,56 @@ pub async fn open_with( .filter(|s| !s.is_empty()) .collect::>() .join("\n\n"); + // A stop before the work was done says so at the top, with what is done + // and what is left; the section keeps the pull request a draft. + let stop = super::outcome::Stop::from_recorded(reason); + let progress = progress(state, msg, &github, branch).await; + let mid_work = !progress.remaining.is_empty() + || matches!( + stop, + super::outcome::Stop::NoProgress { .. } | super::outcome::Stop::OutOfTime(_) + ); + let unfinished = if mid_work { + not_finished( + &stop, + &progress, + &format!( + "{}/runs/detail?id={run_id}", + common::public_urls::app_url(&state.config.stage) + ), + ) + } else { + String::new() + }; + // The standard body's rules (`outcome::body_problems`): a slip is said + // loudly, never sent silently. + let draft_body = body( + &super::outcome::ticket_line_for(msg), + reason, + &work, + &open_text, + &unfinished, + ); + let problems = super::outcome::body_problems(&draft_body, &msg.ticket_id); + if !problems.is_empty() { + tracing::error!(run_id, problems = ?problems, "The stopped run's pull request body breaks the body rules"); + } let existing = github .find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch) .await?; let (number, url) = match existing { Some(p) => { let number = p["number"].as_u64().unwrap_or(0); + // The pull request already open says what is not finished too. + if !unfinished.is_empty() { + let now = with_unfinished(p["body"].as_str().unwrap_or(""), &unfinished); + if let Err(e) = github + .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &now) + .await + { + tracing::warn!(run_id, error = %e, "Could not say what is not finished on the open pull request"); + } + } if !items.is_empty() { super::pr::put_open_items( &github, @@ -168,7 +330,7 @@ pub async fn open_with( &msg.repo_owner, &msg.repo_name, common::truncate_str(&title, 72), - &body(&ticket_line(msg), reason, &work, &open_text), + &draft_body, branch, &msg.base_branch, true, @@ -260,6 +422,7 @@ mod tests { "Stopped before opening a pull request: 2 of 9 planned tasks are not done", &["web/a.tsx".into()], "", + "", ); assert!(b.starts_with("Source ticket: T-1")); assert!(b.contains("## Open items\n\n- [ ] Stopped before opening a pull request: 2 of 9")); @@ -271,8 +434,73 @@ mod tests { "It kept continuing", &[], "## Open items\n- the vendor sends cents", + "", ); assert!(b.contains("## Open items\n- the vendor sends cents")); assert_eq!(b.matches("## Open items").count(), 1); } + + /// The stopped Jira run: seven of eight tasks done, two steps changed + /// nothing. Its draft is the standard one: the ticket line, a specific + /// "Not finished" section, Summary, Changes and Verification; never + /// "Closes #0", "Partial" or "ran out of time". + #[test] + fn a_run_stopped_mid_work_gets_the_standard_draft_with_what_is_left() { + let reason = "Stopped: steps 2 and 3 made no progress. The branch stayed at a8c8814 and \ + the run was stuck at the implement work (planned tasks) while working on \ + task 8 of 8 (`web/hooks/useStickyScroll.ts`: adapt the scroll offset). The \ + work so far is kept on branch `coderhelm-wip/coderhelm/web-12`."; + let progress = Progress { + done: (1..=7) + .map(|i| format!("`web/f{i}.tsx`: task {i}")) + .collect(), + remaining: vec!["`web/hooks/useStickyScroll.ts`: adapt the scroll offset".into()], + }; + let stop = super::super::outcome::Stop::from_recorded(reason); + let nf = not_finished( + &stop, + &progress, + "https://app.example.com/runs/detail?id=r1", + ); + let b = body( + &super::super::outcome::ticket_line(false, 0, "WEB-12"), + reason, + &["web/f1.tsx".into()], + "", + &nf, + ); + assert!(b.starts_with("Source ticket: WEB-12\n"), "{b}"); + assert!(super::super::proof::holds_unfinished(&b)); + assert!(b.contains("## Not finished")); + assert!(b.contains("**Why it stopped:** steps 2 and 3 made no change to the branch while working on task 8 of 8")); + assert!(b.contains("**Done (7 of 8):**")); + assert!(b.contains("task 8 of 8: `web/hooks/useStickyScroll.ts`: adapt the scroll offset")); + assert!(b.contains("**What you can do:**")); + assert!(b.contains("https://app.example.com/runs/detail?id=r1")); + assert!( + super::super::outcome::body_problems(&b, "WEB-12").is_empty(), + "{:?}", + super::super::outcome::body_problems(&b, "WEB-12") + ); + for never in ["#0", "Partial", "ran out of time"] { + assert!(!b.contains(never), "{never}"); + } + } + + #[test] + fn an_open_pull_request_gets_the_section_once() { + let nf = not_finished( + &super::super::outcome::Stop::Other("A check errored".into()), + &Progress::default(), + "", + ); + let b = with_unfinished("Source ticket: WEB-3\n\n## Summary\nx", &nf); + assert!( + b.starts_with("Source ticket: WEB-3\n\n"), + "{b}" + ); + let again = with_unfinished(&b, &nf); + assert_eq!(again.matches("## Not finished").count(), 1); + assert!(again.contains("## Summary\nx")); + } }