diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 7270560c6..0781932ad 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -160,6 +160,32 @@ fn empty_overwrite_refusal( }) } +/// What [`GitHubClient::start_branch`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BranchStart { + /// The branch didn't exist; it starts at the base. + Created, + /// A leftover branch with no open pull request was moved to the base. + Reset, + /// The branch has an open pull request: kept at its head. + KeptOpenPr, +} + +impl BranchStart { + /// The progress note for `branch` started from `base`. + pub fn note(self, branch: &str, base: &str) -> String { + match self { + BranchStart::Created => format!("Created branch {branch} from {base}"), + BranchStart::Reset => format!( + "Reset branch {branch} to {base} (a leftover branch with no open pull request)" + ), + BranchStart::KeptOpenPr => format!( + "Branch {branch} has an open pull request: continuing from its head, nothing reset" + ), + } + } +} + /// GitHub REST API client using installation token auth. pub struct GitHubClient { app_id: String, @@ -1247,6 +1273,21 @@ impl GitHubClient { branch: &str, from_ref: &str, ) -> Result> { + self.start_branch(owner, repo, branch, from_ref) + .await + .map(|(sha, _)| sha) + } + + /// Creates `branch` at `from_ref`, or says what it did with a branch of + /// that name that already exists ([`BranchStart`]), so a run's progress + /// note never says "created" over work it kept. + pub async fn start_branch( + &self, + owner: &str, + repo: &str, + branch: &str, + from_ref: &str, + ) -> Result<(String, BranchStart), Box> { let sha = self.get_ref(owner, repo, from_ref).await?; let url = format!("{API_BASE}/repos/{owner}/{repo}/git/refs"); let headers = self.auth_headers().await?; @@ -1265,23 +1306,29 @@ impl GitHubClient { // base, which empties the PR's diff and makes GitHub AUTO-CLOSE the // PR (observed live: a conflict-resolution run wiped a PR this way). // With an open PR we continue from the branch's current head; only - // a stale, PR-less leftover branch is reset. + // a stale, PR-less leftover branch is reset. When GitHub can't say + // whether it has an open PR, nothing is reset: a failed lookup + // used to read as "no PR" and wiped the branch. let prs_url = format!( "{API_BASE}/repos/{owner}/{repo}/pulls?head={owner}:{branch}&state=open&per_page=1" ); - let has_open_pr = self - .get(&prs_url) - .await - .ok() - .and_then(|v| v.as_array().map(|a| !a.is_empty())) - .unwrap_or(false); + let has_open_pr = match self.get(&prs_url).await { + Ok(v) => v.as_array().is_some_and(|a| !a.is_empty()), + Err(e) => { + return Err(format!( + "branch {branch} already exists and GitHub couldn't say whether it has an \ + open pull request ({e}); it was left as it is" + ) + .into()) + } + }; if has_open_pr { let head = self.get_ref(owner, repo, branch).await?; tracing::info!( branch, "Branch has an open PR — continuing from its head, NOT resetting to base" ); - return Ok(head); + return Ok((head, BranchStart::KeptOpenPr)); } let update_url = format!("{API_BASE}/repos/{owner}/{repo}/git/refs/heads/{branch}"); let data = self @@ -1294,7 +1341,7 @@ impl GitHubClient { .pointer("/object/sha") .and_then(|v| v.as_str()) .ok_or("Missing sha in update ref response")?; - return Ok(new_sha.to_string()); + return Ok((new_sha.to_string(), BranchStart::Reset)); } let data: serde_json::Value = resp.error_for_status()?.json().await?; @@ -1302,7 +1349,7 @@ impl GitHubClient { .pointer("/object/sha") .and_then(|v| v.as_str()) .ok_or("Missing sha in create branch response")?; - Ok(new_sha.to_string()) + Ok((new_sha.to_string(), BranchStart::Created)) } // ─── Merge ─────────────────────────────────────────────────── diff --git a/services/worker/src/passes/feature/checklist.rs b/services/worker/src/passes/feature/checklist.rs index af68e6aa5..de2e520fb 100644 --- a/services/worker/src/passes/feature/checklist.rs +++ b/services/worker/src/passes/feature/checklist.rs @@ -6,6 +6,10 @@ //! - type-check, lint and unit tests, with the repository's own scripts; //! - the unit tests the acceptance criteria imply: one per listed option or //! case ([`acceptance_cases`]), counted in the diff ([`unit_cases_added`]); +//! - every value of each new configurable thing the change adds (a schema +//! field's option list, a string-literal union prop, an on/off field's +//! shown and hidden cases) named in the tests ([`new_options`], +//! [`untested_options`]); //! - the end-to-end spec, and its entry in any test map the repository keeps //! ([`missing_from_test_maps`]); //! - the checks of each test package outside the main workspace; @@ -159,6 +163,266 @@ pub fn unit_cases_added(files: &[(String, String, String)]) -> usize { .sum() } +/// A new configurable thing the change adds and the values tests must set. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewOption { + pub name: String, + pub values: Vec, + /// An on/off field: its values are `true` and `false`. + pub toggle: bool, +} + +/// Whether a path is a test file. +pub fn is_test_path(path: &str) -> bool { + let l = path.to_lowercase(); + l.contains(".test.") + || l.contains(".spec.") + || l.contains("/test/") + || l.contains("/tests/") + || l.contains("__tests__") + || l.starts_with("test/") + || l.starts_with("tests/") + || l.rsplit('/').next().is_some_and(|n| n.starts_with("test_")) + || is_e2e(path) +} + +/// Source files whose new options count: code a person writes, never +/// generated output. +fn option_source(path: &str) -> bool { + let l = path.to_lowercase(); + let code = [ + ".ts", ".tsx", ".js", ".jsx", ".mjs", ".vue", ".svelte", ".py", ".rb", ".go", ".rs", ".kt", + ".java", ".cs", + ] + .iter() + .any(|e| l.ends_with(e)); + code && !is_test_path(path) + && !l.ends_with(".d.ts") + && ![ + "generated", + ".gen.", + "sanity.types", + "graphql.ts", + "schema.ts.snap", + ] + .iter() + .any(|m| l.contains(m)) +} + +/// The string literals in `text`, in order. +fn literals(text: &str) -> Vec { + let mut out = Vec::new(); + let mut chars = text.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if c == '\'' || c == '"' || c == '`' { + let rest = &text[i + 1..]; + if let Some(end) = rest.find(c) { + let lit = &rest[..end]; + if !lit.is_empty() && !lit.contains('\n') { + out.push(lit.to_string()); + } + // Skip past the closing quote. + for _ in 0..lit.chars().count() + 1 { + chars.next(); + } + } + } + } + out +} + +/// The quoted value after `key:` anywhere on a line (`name: 'tabs'` and +/// `defineField({ name: 'tabs', ...` both give `tabs`). +fn keyed(line: &str, key: &str) -> Option { + let mut from = 0; + while let Some(i) = line[from..].find(key) { + let at = from + i; + from = at + key.len(); + let before_ok = line[..at] + .chars() + .next_back() + .is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_')); + let Some(rest) = line[from..].trim_start().strip_prefix(':') else { + continue; + }; + let rest = rest.trim_start(); + if before_ok && rest.starts_with(['\'', '"', '`']) { + return literals(rest).into_iter().next(); + } + } + None +} + +fn option_list_start(line: &str) -> bool { + let t = line.trim_start(); + ["list", "options", "enum", "choices", "values"] + .iter() + .any(|k| { + t.strip_prefix(k) + .and_then(|r| r.trim_start().strip_prefix(':')) + .is_some_and(|r| r.trim_start().starts_with('[')) + }) +} + +/// A string-literal union on one line (`variant?: 'a' | 'b'`, +/// `type Size = "sm" | "lg"`): its name and values. +fn union(line: &str) -> Option<(String, Vec)> { + let t = line.trim().trim_end_matches([';', ',']); + let (head, body) = if let Some((h, b)) = t.split_once('=') { + (h, b) + } else { + t.split_once(':')? + }; + let body = body.trim(); + let parts: Vec<&str> = body + .split('|') + .map(str::trim) + .filter(|p| !p.is_empty()) + .collect(); + if parts.len() < 2 { + return None; + } + let mut values = Vec::new(); + for p in &parts { + let q = p.chars().next()?; + if !(q == '\'' || q == '"') || !p.ends_with(q) || p.len() < 3 { + return None; + } + values.push(p[1..p.len() - 1].to_string()); + } + let name = head + .trim() + .trim_start_matches("export ") + .trim_start_matches("type ") + .trim_end_matches('?') + .trim() + .to_string(); + (!name.is_empty() && !name.contains(' ')).then_some((name, values)) +} + +/// The new configurable things the diff's added lines declare in source +/// files: option lists (`list: [...]`, `options: [...]`, with `value:` +/// keys or plain strings), string-literal unions, and on/off fields +/// (`type: 'boolean'`), each named by the nearest `name:` before it. +pub fn new_options(files: &[(String, String, String)]) -> Vec { + let mut out: Vec = Vec::new(); + for (path, status, patch) in files { + if status == "removed" || !option_source(path) { + continue; + } + let added: Vec<&str> = patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| &l[1..]) + .collect(); + let mut last_name: Option = None; + let mut i = 0; + while i < added.len() { + let line = added[i]; + if let Some(n) = keyed(line, "name") { + last_name = Some(n); + } + if option_list_start(line) { + // Collect the list to its closing bracket. + let mut depth = 0i32; + let mut text = String::new(); + let mut j = i; + while j < added.len() { + let l = added[j]; + let from = if j == i { l.find('[').unwrap_or(0) } else { 0 }; + for c in l[from..].chars() { + match c { + '[' => depth += 1, + ']' => depth -= 1, + _ => {} + } + } + text.push_str(l); + text.push('\n'); + if depth <= 0 { + break; + } + j += 1; + } + let keyed_values: Vec = + text.lines().filter_map(|l| keyed(l, "value")).collect(); + let values = if keyed_values.is_empty() { + literals(&text[text.find('[').map_or(0, |k| k + 1)..]) + } else { + keyed_values + }; + if values.len() >= 2 { + out.push(NewOption { + name: last_name + .clone() + .unwrap_or_else(|| "an option list".to_string()), + values, + toggle: false, + }); + } + i = j + 1; + continue; + } + if let Some(ty) = keyed(line, "type") { + if ty == "boolean" { + // The field's name is before it or just after. + let name = last_name.clone().or_else(|| { + added[i + 1..added.len().min(i + 6)] + .iter() + .find_map(|l| keyed(l, "name")) + }); + if let Some(name) = name { + out.push(NewOption { + name, + values: vec!["true".into(), "false".into()], + toggle: true, + }); + } + } + } + if let Some((name, values)) = union(line) { + out.push(NewOption { + name, + values, + toggle: false, + }); + } + i += 1; + } + } + out.dedup(); + out +} + +/// The values of `options` no test names, as "name: value". A value is +/// named when the tests quote it; an on/off field's case when a test line +/// names the field with `true` (shown) or with `false` (hidden). +pub fn untested_options(options: &[NewOption], tests: &str) -> Vec { + let mut out = Vec::new(); + for o in options { + for v in &o.values { + let named = if o.toggle { + tests + .lines() + .any(|l| l.contains(o.name.as_str()) && l.contains(v.as_str())) + } else { + ['\'', '"', '`'] + .iter() + .any(|q| tests.contains(&format!("{q}{v}{q}"))) + }; + if !named { + let case = match (o.toggle, v.as_str()) { + (true, "true") => "true (shown)".to_string(), + (true, _) => "false (hidden)".to_string(), + _ => format!("`{v}`"), + }; + out.push(format!("`{}` to {case}", o.name)); + } + } + } + out +} + /// Widths a spec sets its viewport to. fn widths(text: &str) -> Vec { let mut out = Vec::new(); @@ -325,6 +589,12 @@ pub struct Facts { pub map_missing: Vec, /// The repository has end-to-end tests. pub has_e2e: bool, + /// How many new configurable things the change adds. + #[serde(default)] + pub options_found: usize, + /// Their values no test names, as "name: value". + #[serde(default)] + pub options_untested: Vec, } /// The items that read the diff alone. @@ -345,6 +615,28 @@ pub fn static_items(f: &Facts) -> Vec { ), )); } + if f.options_found > 0 { + if f.options_untested.is_empty() { + out.push(Item::new( + "tests for each option", + Status::Pass, + format!( + "every value of {} new option(s) is named in a test", + f.options_found + ), + )); + } else { + let mut shown: Vec = f.options_untested.iter().take(8).cloned().collect(); + if f.options_untested.len() > 8 { + shown.push(format!("{} more", f.options_untested.len() - 8)); + } + out.push(Item::new( + "tests for each option", + Status::Fail, + format!("no test sets {}", shown.join("; ")), + )); + } + } if f.has_e2e && f.ui { if f.specs.is_empty() { out.push(Item::new( @@ -408,7 +700,9 @@ pub fn feedback(items: &[Item]) -> String { s.push_str(&format!("- {f}\n")); } s.push_str(&format!( - "Unit tests: one test per option or case the acceptance criteria list. A new \ + "Unit tests: one test per option or case the acceptance criteria list, and one per \ + value of each new option the change adds (each value of an option list or union, the \ + shown and the hidden case of an on/off field). A new \ end-to-end spec goes in every test map the repository keeps. For UI, the spec checks \ `document.documentElement.scrollWidth <= window.innerWidth` at a viewport {NARROW_MAX}px \ wide or less and one {WIDE_MIN}px wide or more.\n" @@ -505,6 +799,8 @@ mod tests { responsive_specs: vec![], map_missing: vec!["e2e/test-map.json: e2e/quote.spec.ts".into()], has_e2e: true, + options_found: 0, + options_untested: vec![], }; let items = static_items(&f); assert_eq!(failing(&items).len(), 3); @@ -519,4 +815,98 @@ mod tests { }; assert!(failing(&static_items(&ok)).is_empty()); } + + /// The observed kind of feature: a CMS block with an option list per + /// tab, an on/off field and a prop union. Every value needs a test. + #[test] + fn every_value_of_a_new_option_is_named_in_a_test() { + let schema = "+export const heroBlock = defineType({\n\ + + name: 'heroBlock',\n\ + + fields: [\n\ + + defineField({\n\ + + name: 'sortBy',\n\ + + type: 'string',\n\ + + options: {\n\ + + list: [\n\ + + { title: 'Start date', value: 'startDate' },\n\ + + { title: 'Spots left', value: 'spotsLeft' },\n\ + + ],\n\ + + },\n\ + + }),\n\ + + defineField({ name: 'showBlurb', type: 'boolean' }),\n\ + + ],\n\ + +});\n"; + let component = "+type HeroProps = {\n+ size?: 'small' | 'large';\n+};\n"; + let files = vec![ + ( + "studio/blocks/hero.ts".to_string(), + "added".to_string(), + schema.to_string(), + ), + ( + "web/src/hero.tsx".to_string(), + "added".to_string(), + component.to_string(), + ), + ( + "web/src/sanity.types.ts".to_string(), + "modified".to_string(), + "+ kind?: 'a' | 'b';\n".to_string(), + ), + ]; + let opts = new_options(&files); + let names: Vec<&str> = opts.iter().map(|o| o.name.as_str()).collect(); + assert_eq!(names, vec!["sortBy", "showBlurb", "size"], "{opts:?}"); + assert_eq!(opts[0].values, vec!["startDate", "spotsLeft"]); + assert!(opts[1].toggle); + + let tests = "it('sorts by start date', () => render({ sortBy: 'startDate' }))\n\ + it('shows the blurb', () => render({ showBlurb: true }))\n\ + it('is small', () => render({ size: \"small\" }))\n"; + let missing = untested_options(&opts, tests); + assert_eq!( + missing, + vec![ + "`sortBy` to `spotsLeft`".to_string(), + "`showBlurb` to false (hidden)".to_string(), + "`size` to `large`".to_string(), + ] + ); + let all = format!( + "{tests}it('spots', () => render({{ sortBy: 'spotsLeft' }}))\n\ + it('hides', () => render({{ showBlurb: false }}))\n\ + it('large', () => render({{ size: 'large' }}))\n" + ); + assert!(untested_options(&opts, &all).is_empty()); + + let f = Facts { + options_found: opts.len(), + options_untested: missing, + ..Default::default() + }; + let items = static_items(&f); + assert!(markdown(&items) + .contains("[FAIL] tests for each option: no test sets `sortBy` to `spotsLeft`")); + assert!(feedback(&items).contains("the shown and the hidden case")); + } + + #[test] + fn test_files_and_unrelated_brackets_are_not_options() { + let files = vec![ + ( + "src/a.test.ts".to_string(), + "added".to_string(), + "+const x: 'a' | 'b' = 'a';\n".to_string(), + ), + ( + "src/b.ts".to_string(), + "added".to_string(), + "+const opts = { options: [...defaults, extra] };\n+const n = a | b;\n".to_string(), + ), + ]; + assert!(new_options(&files).is_empty()); + assert!(is_test_path("e2e/tests/hero.spec.ts")); + assert!(is_test_path("tests/test_hero.py")); + assert!(!is_test_path("src/hero.tsx")); + } } diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index 74b9456b4..0a097f855 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -343,7 +343,26 @@ async fn checklist_facts( .filter(|(p, s, _)| s == "added" && content::is_e2e_spec(p)) .map(|(p, _, _)| p.clone()) .collect(); + // Every value of each new option the change adds, against the tests the + // change adds or changes (read whole: a large file's patch is cut). + let options = checklist::new_options(files); + let mut tests_text = String::new(); + if !options.is_empty() { + for (p, _, patch) in files + .iter() + .filter(|(p, s, _)| s != "removed" && checklist::is_test_path(p)) + .take(15) + { + match w.github.read_file(owner, repo, p, w.branch).await { + Ok(t) => tests_text.push_str(&t), + Err(_) => tests_text.push_str(patch), + } + tests_text.push('\n'); + } + } let facts = checklist::Facts { + options_found: options.len(), + options_untested: checklist::untested_options(&options, &tests_text), cases_required: checklist::acceptance_cases(&w.msg.body, &w.plan.spec), cases_added: checklist::unit_cases_added(files), ui: checklist::is_ui(&paths), diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a432abbf7..17745dab5 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -733,6 +733,7 @@ mod plan_judge; /// Plugin runs, publishing, source sync and results. pub mod plugins; mod pr; +mod pr_holder; pub mod pr_outcomes; mod proof; pub mod quarantine; @@ -764,6 +765,7 @@ pub mod review_thread_reply; pub mod review_verdict; pub mod rewards; pub(crate) mod round; +mod run_end; mod security; #[cfg(test)] mod selfhost_links; @@ -1507,6 +1509,58 @@ async fn run_passes( warn!(run_id, error = %e, "Failed to persist resolved base_branch to run record"); } + // --- One writer per pull request branch, across runs of the ticket --- + // CoderHelm's own open pull request for the ticket (an earlier run's): + // while that run still works on it, this run stops before writing; once + // it is done, this run continues it as its update and holds its writer + // slot, so the earlier run's feedback or CI pass waits instead of + // writing the same branch. + let mut pr_writer_guards: Vec = Vec::new(); + let mut claimed_pr: Option = None; + if !is_internal_ticket(&msg.ticket_id) { + let repo_full = format!("{}/{}", msg.repo_owner, msg.repo_name); + if let Some(own) = history.own_open_pr(&repo_full) { + let (number, url, title) = ( + own.number, + pr_url_of(&repo_full, own.number), + own.title.clone(), + ); + let earlier = pr_holder::holder_runs(&history, &repo_full, number); + match pr_holder::claim(state, &msg.team_id, run_id, &earlier).await { + pr_holder::Claim::Busy { + run_id: holder, + why, + } => { + pr_holder::stop_busy( + state, + msg, + run_id, + usage, + start, + (&repo_full, number, &url, &title), + &holder, + &why, + ) + .await; + return Ok(()); + } + pr_holder::Claim::Free(guards) => { + if msg.continuation == 0 && msg.model_retries == 0 { + add_progress_note( + state, + &msg.team_id, + run_id, + &pr_holder::continue_note(number, &earlier), + ) + .await; + } + pr_writer_guards.extend(guards); + claimed_pr = Some(number); + } + } + } + } + // Load enabled MCP plugins once for this run let mcp_table = if state.config.mcp_configs_table_name.is_empty() { &state.config.settings_table_name @@ -2441,13 +2495,16 @@ async fn run_passes( } else { let own_branch = match &own_open { Some((number, branch)) => { - add_progress_note( - state, - &msg.team_id, - run_id, - &format!("Continuing on my open pull request #{number} for this ticket"), - ) - .await; + // Said already, with the earlier run, when it was claimed. + if claimed_pr != Some(*number) { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Continuing on my open pull request #{number} for this ticket"), + ) + .await; + } branch.clone() } None => { @@ -2509,6 +2566,9 @@ async fn run_passes( } }; + // Set when this step's implement pass wrote no file (the run's work may + // still be on the branch from its earlier steps). + let mut step_wrote_nothing = false; let impl_result = if can_skip_implement { // Resume: reconstruct impl_result from the existing branch diff info!(run_id, branch = %branch_name, "Checkpoint resume: skipping implement pass"); @@ -2583,6 +2643,58 @@ async fn run_passes( None } }; + // The branch's open pull request is an earlier run's of this ticket + // (found by the branch name, not by the ticket's own-PR lookup): + // the same one-writer rule as at the start of the run. + if let Some(number) = existing_pr + .as_ref() + .and_then(|p| p["number"].as_u64()) + .filter(|n| claimed_pr != Some(*n)) + { + let repo_full = format!("{}/{}", msg.repo_owner, msg.repo_name); + let earlier = pr_holder::holder_runs(&history, &repo_full, number); + if !earlier.is_empty() { + match pr_holder::claim(state, &msg.team_id, run_id, &earlier).await { + pr_holder::Claim::Busy { + run_id: holder, + why, + } => { + let pr = existing_pr.as_ref().unwrap_or(&serde_json::Value::Null); + pr_holder::stop_busy( + state, + msg, + run_id, + usage, + start, + ( + &repo_full, + number, + pr["html_url"].as_str().unwrap_or(""), + pr["title"].as_str().unwrap_or(""), + ), + &holder, + &why, + ) + .await; + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + pr_holder::Claim::Free(guards) => { + if msg.continuation == 0 && msg.model_retries == 0 { + add_progress_note( + state, + &msg.team_id, + run_id, + &pr_holder::continue_note(number, &earlier), + ) + .await; + } + pr_writer_guards.extend(guards); + } + } + } + } + // Someone else's open pull request for this ticket (a person's, or an // earlier run's on another branch), and nobody has said what to do // about it: don't open a second one; ask (once). @@ -3000,11 +3112,12 @@ async fn run_passes( // A continuation of this same run (out of time, a model error) keeps // the commits its earlier attempt pushed: resetting the branch to its // base here threw that work away before the continuation could build - // on it. + // on it. That holds with an open pull request on the branch too: the + // continuation used to go through create_branch there, which kept the + // head but said "Created branch" in every step. let keep_own_branch = same_run && !skip_branch_reset && ticket_update_pr.is_none() - && existing_pr.is_none() && github .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) .await @@ -3034,21 +3147,23 @@ async fn run_passes( ) .await; } else { - // Create working branch (or reset existing one to base) - github - .create_branch( + // Create working branch (or reset a leftover one to base; a + // branch with an open pull request keeps its head). The note + // says which, never "created" over kept work. + let (_, started) = github + .start_branch( &msg.repo_owner, &msg.repo_name, &branch_name, &msg.base_branch, ) .await?; - info!(run_id, branch = %branch_name, "Created working branch"); + info!(run_id, branch = %branch_name, ?started, "Working branch ready"); add_progress_note( state, &msg.team_id, run_id, - &format!("Created branch {}", branch_name), + &started.note(&branch_name, &msg.base_branch), ) .await; @@ -3056,7 +3171,10 @@ async fn run_passes( // reused plan's `- [x]` checkmarks no longer reflect reality — // implement is told to skip checked tasks, which silently dropped // the wiped work. Reset every task to unchecked. - if plan_was_reused && plan_result.tasks.contains("- [x]") { + if started != crate::clients::github::BranchStart::KeptOpenPr + && plan_was_reused + && plan_result.tasks.contains("- [x]") + { plan_result.tasks = plan_result.tasks.replace("- [x]", "- [ ]"); let tasks_key = format!( "{}/tasks.md", @@ -3935,6 +4053,130 @@ async fn run_passes( return Ok(()); } + // A step that wrote no file is judged on the run's whole work: the + // branch's diff against its base, summed over every step (a + // continuation's earlier steps, or the open pull request it + // continues). Only a branch with none of the work, and a ticket that + // names no file, ever reaches the "add more detail" ending below. + if result.files_modified.is_empty() { + step_wrote_nothing = true; + let work = plan_coverage::changed_files( + &github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + &branch_name, + ) + .await + .map(|c| run_end::work_files(&c, &msg.ticket_id)); + let tasks = plan_coverage::tasks_for( + &github, + &msg.repo_owner, + &msg.repo_name, + &branch_name, + &plan_result.tasks, + ) + .await; + let ticket_names_files = + run_end::ticket_names_files(&format!("{}\n{}", msg.title, msg.body)); + let mut verdict = run_end::judge( + work.as_deref(), + &tasks, + &run_end::coder_questions(&result.evidence.notes), + ticket_names_files, + ); + // Nothing on the branch, and the plan says what to build: one + // more build, told every task, before anything is asked. + if matches!(verdict, run_end::Empty::Unbuilt(_)) + && tasks.iter().any(|t| !t.optional && !t.generated) + && has_time_for_remediation(start) + { + add_progress_note( + state, + &msg.team_id, + run_id, + "The coder wrote no file and the branch has none of the change: building again, told every planned task", + ) + .await; + let again = implement::run( + state, + msg, + &github, + &plan_result, + &branch_name, + &rules, + &repo_instructions, + Some(&run_end::build_round_feedback(&tasks)), + &effective_complexity, + &provider, + usage, + &file_cache, + Some(run_id), + implement_deadline, + false, + ) + .await?; + if again.files_modified.is_empty() { + let mut evidence = std::mem::take(&mut result.evidence); + evidence.merge(again.evidence); + verdict = run_end::judge( + work.as_deref(), + &tasks, + &run_end::coder_questions(&evidence.notes), + ticket_names_files, + ); + result.evidence = evidence; + } else { + verdict = run_end::Empty::Carry(again.files_modified.clone()); + result.evidence.merge(again.evidence); + result.conversation_log.extend(again.conversation_log); + } + } + match verdict { + run_end::Empty::Carry(files) => { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "This step wrote no new file; the branch holds the run's work on {} file(s): checking it against the plan", + files.len() + ), + ) + .await; + result.files_modified = files; + } + run_end::Empty::Ask(qs) => { + let text = format!( + "I built what I could and need a decision before I go on:\n{}", + qs.iter() + .map(|q| format!("- {q}")) + .collect::>() + .join("\n") + ); + ask_on_ticket( + state, + msg, + run_id, + &github, + &run_end::questions_from(&qs), + &text, + &text, + "A decision is needed", + ) + .await; + mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids).await; + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + run_end::Empty::Unbuilt(reason) => { + close_memory(state, agent_memory.take()).await; + return Err(reason.into()); + } + run_end::Empty::Generic => {} + } + } + if result.files_modified.is_empty() { warn!(run_id, "Implement pass produced zero file changes"); // The files it went for were in a different repo of the org (one @@ -4024,6 +4266,17 @@ async fn run_passes( check_cancelled(state, &msg.team_id, run_id).await?; let mut impl_result = impl_result; let mut plan_optional: Vec = Vec::new(); + // The branch head before the plan rounds: a step that wrote nothing and + // whose rounds moved nothing made no progress, and another fresh step + // would only repeat it. + let head_before_rounds = if step_wrote_nothing { + github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) + .await + .ok() + } else { + None + }; let coverage = plan_coverage::close_gaps( &plan_coverage::Work { state, @@ -4060,12 +4313,60 @@ async fn run_passes( &plan_coverage::progress_note(&cov), ) .await; + let generated = cov.generated_missing(); + if !generated.is_empty() { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Generated file(s) the plan names are left to the generator check, which runs their generator before the pull request: {}", + generated + .iter() + .map(|t| format!("`{}`", t.path)) + .collect::>() + .join(", ") + ), + ) + .await; + } match plan_coverage::next(&cov, plan_coverage::MAX_ROUNDS, false) { plan_coverage::Next::Complete => {} plan_coverage::Next::OpenWithOptional => { plan_optional = plan_coverage::optional_findings(&cov); } plan_coverage::Next::Round | plan_coverage::Next::Unfinished => { + let stalled = match &head_before_rounds { + Some(before) => github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) + .await + .is_ok_and(|now| &now == before), + None => false, + }; + if stalled { + // This step and its rounds changed nothing for the tasks + // left: say which, and why, instead of another step. + save_checkpoint( + state, + &msg.team_id, + run_id, + "implement", + &branch_name, + 0, + usage, + ) + .await; + let kept = + keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name) + .await; + close_memory(state, agent_memory.take()).await; + return Err(plan_coverage::stop_reason_why( + &cov, + &kept, + "the last step changed no file for them", + ) + .into()); + } // A fresh invocation, with its own time, continues from this // branch (bounded); the continuation is told what's left. save_checkpoint( @@ -4700,8 +5001,23 @@ async fn run_passes( /// pull request: a later run of the ticket resets the run branch to its /// base, and the work must survive that. Returns the branch the work is on /// (the run branch itself when the copy can't be made). +/// +/// `coderhelm-wip/` is also where a fix round on that branch's pull +/// request keeps its checkpoints. A WIP branch holding commits the run +/// branch doesn't have (a round's, or an earlier stop's) is never moved: +/// the work is kept on a branch of its own instead. async fn keep_wip_branch(github: &GitHubClient, owner: &str, repo: &str, branch: &str) -> String { - let wip = common::run_round::wip_branch(branch); + let mut wip = common::run_round::wip_branch(branch); + if github.get_ref(owner, repo, &wip).await.is_ok() { + let holds_other_work = match github.get_diff(owner, repo, branch, &wip).await { + Ok(compare) => wip_holds_other_work(&compare), + // Can't tell: never move it. + Err(_) => true, + }; + if holds_other_work { + wip = format!("{wip}-kept-{}", chrono::Utc::now().format("%Y%m%d%H%M%S")); + } + } match github.create_branch(owner, repo, &wip, branch).await { Ok(_) => wip, Err(e) => { @@ -4711,6 +5027,12 @@ async fn keep_wip_branch(github: &GitHubClient, owner: &str, repo: &str, branch: } } +/// A compare of `...` says the WIP branch has +/// commits the run branch doesn't: moving it would lose them. +fn wip_holds_other_work(compare: &serde_json::Value) -> bool { + compare["ahead_by"].as_u64().unwrap_or(1) > 0 +} + /// The plan's checklist with only the done tasks checked, written where the /// run page and a later attempt read it. async fn save_checked_tasks(state: &WorkerState, msg: &TicketMessage, run_id: &str, md: &str) { @@ -4745,7 +5067,9 @@ async fn continuation_feedback( plan: &plan::PlanResult, branch: &str, ) -> Option { - let tasks = plan_coverage::plan_tasks(&plan.tasks); + let tasks = + plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) + .await; if tasks.is_empty() { return None; } @@ -4788,18 +5112,19 @@ async fn run_repo_pipeline( let repo_owner = &msg.repo_owner; let repo_name = &msg.repo_name; - // Create working branch - github - .create_branch(repo_owner, repo_name, branch_name, base_branch) + // Create working branch (a branch with an open pull request keeps its + // head; the note says which). + let (_, started) = github + .start_branch(repo_owner, repo_name, branch_name, base_branch) .await?; - info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), branch = %branch_name, "Created working branch"); + info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), branch = %branch_name, ?started, "Working branch ready"); add_progress_note( state, &msg.team_id, run_id, &format!( - "Created branch {} on {}/{}", - branch_name, repo_owner, repo_name + "{} in {repo_owner}/{repo_name}", + started.note(branch_name, base_branch) ), ) .await; @@ -4887,16 +5212,32 @@ async fn run_repo_pipeline( ) .await; - if impl_result.files_modified.is_empty() { - return Err(format!( - "No files modified in {}/{}. The issue may need more detail.", - repo_owner, repo_name - ) - .into()); - } - // --- Plan check: this repository's tasks are done before its PR --- let mut impl_result = impl_result; + // A pass that wrote nothing is judged on the branch's whole work (an + // open pull request it continues may already hold it), never on the + // pass alone; with none, the reason names the planned tasks. + if impl_result.files_modified.is_empty() { + let work = + plan_coverage::changed_files(github, repo_owner, repo_name, base_branch, branch_name) + .await + .map(|c| run_end::work_files(&c, &msg.ticket_id)); + let tasks = + plan_coverage::tasks_for(github, repo_owner, repo_name, branch_name, &repo_plan.tasks) + .await; + match run_end::judge(work.as_deref(), &tasks, &[], false) { + run_end::Empty::Carry(files) => impl_result.files_modified = files, + run_end::Empty::Unbuilt(reason) => { + return Err(format!("{repo_owner}/{repo_name}: {reason}").into()) + } + _ => { + return Err(format!( + "No files modified in {repo_owner}/{repo_name}, and its plan names no file to change." + ) + .into()) + } + } + } let mut plan_optional: Vec = Vec::new(); if let Some(cov) = plan_coverage::close_gaps( &plan_coverage::Work { @@ -6757,6 +7098,11 @@ fn looks_like_path(t: &str) -> bool { !t.contains(' ') && t.contains('.') && t.contains('/') } +/// A pull request's address on GitHub. +fn pr_url_of(repo: &str, number: u64) -> String { + format!("https://github.com/{repo}/pull/{number}") +} + /// CoderHelm's own pull requests for the ticket in this repository, from /// its earlier runs: never "existing work" for itself. fn own_pr_numbers(history: &ticket_history::TicketHistory, owner: &str, name: &str) -> Vec { @@ -9768,6 +10114,40 @@ mod ci_outcome_tests { } } +#[cfg(test)] +mod branch_keep_tests { + use super::wip_holds_other_work; + use crate::clients::github::BranchStart; + + #[test] + fn a_wip_branch_with_commits_of_its_own_is_never_moved() { + assert!(wip_holds_other_work( + &serde_json::json!({"ahead_by": 2, "behind_by": 0}) + )); + assert!(!wip_holds_other_work( + &serde_json::json!({"ahead_by": 0, "behind_by": 5}) + )); + // A compare that doesn't say: never moved. + assert!(wip_holds_other_work(&serde_json::json!({}))); + } + + /// The observed run said "Created branch" in each of its four steps + /// while the branch kept an open pull request's commits. + #[test] + fn the_branch_note_says_what_happened() { + assert_eq!( + BranchStart::Created.note("feature/a", "main"), + "Created branch feature/a from main" + ); + assert!(BranchStart::Reset + .note("feature/a", "main") + .contains("no open pull request")); + let kept = BranchStart::KeptOpenPr.note("feature/a", "main"); + assert!(kept.contains("continuing from its head, nothing reset")); + assert!(!kept.contains("Created")); + } +} + #[cfg(test)] mod repos_reached_for_tests { use super::repos_reached_for; diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs index b2329945e..798616646 100644 --- a/services/worker/src/passes/plan_coverage.rs +++ b/services/worker/src/passes/plan_coverage.rs @@ -16,6 +16,14 @@ //! ([`stop_reason`]). Only tasks the plan itself marks optional may be left //! out, and the pull request then says so under Open items, with the reason //! ([`optional_findings`]). +//! +//! A task whose file a code generator writes (a generated types file, an +//! extracted schema) is not the coder's to write: the generator check +//! (`generators::gate`) runs the generator before the pull request opens +//! and blocks it when its output is out of date. Such a task never holds +//! the plan check ([`mark_generated`]): a run once looped through every +//! continuation on two generated files the generator, run each step, left +//! unchanged, and then ended saying it changed nothing. use tracing::{info, warn}; @@ -42,6 +50,8 @@ pub struct PlanTask { pub is_new: bool, /// The plan says the task may be left out. pub optional: bool, + /// A code generator writes the file: the generator check decides it. + pub generated: bool, } /// Words that mark a task the plan leaves to judgment: never a reason to @@ -69,6 +79,58 @@ fn is_optional(desc: &str) -> bool { || OPTIONAL_MARKS.iter().any(|m| d.contains(m)) } +/// Words that say the task's file is a generator's output. +const GENERATED_MARKS: &[&str] = &[ + "regenerate", + "re-generate", + "generated by", + "(generated)", + "generated file", + "auto-generated", + "autogenerated", + "schema extract", +]; + +fn is_generated_desc(desc: &str) -> bool { + let d = desc.to_lowercase(); + GENERATED_MARKS.iter().any(|m| d.contains(m)) +} + +/// Marks the tasks whose file a detected generator writes (`outputs`: +/// the generators' output globs). +pub fn mark_generated(tasks: &mut [PlanTask], outputs: &[String]) { + for t in tasks.iter_mut() { + if outputs + .iter() + .any(|g| super::generators::glob_match(g, &t.path)) + { + t.generated = true; + } + } +} + +/// The plan's tasks for `branch`, with the ones a detected generator +/// writes marked. +pub async fn tasks_for( + github: &GitHubClient, + owner: &str, + repo: &str, + branch: &str, + tasks_md: &str, +) -> Vec { + let mut tasks = plan_tasks(tasks_md); + if tasks.is_empty() { + return tasks; + } + let files = super::generators::load(github, owner, repo, branch).await; + let outputs: Vec = super::generators::detect(&files) + .into_iter() + .flat_map(|g| g.outputs) + .collect(); + mark_generated(&mut tasks, &outputs); + tasks +} + /// Every task of the checklist that names a file, in order. Lines that don't /// follow the `- [ ] path: description` format are not tasks this check can /// hold the change to, and are skipped. @@ -107,6 +169,7 @@ pub fn plan_tasks(tasks_md: &str) -> Vec { task: desc.trim().to_string(), is_new, optional: is_optional(desc), + generated: is_generated_desc(desc), }); } out @@ -125,9 +188,22 @@ impl Coverage { self.done.len() + self.missing.len() } - /// Tasks the plan needs that aren't done. + /// Tasks the plan needs that aren't done (a generator's output is the + /// generator check's, not the coder's). pub fn required_missing(&self) -> Vec<&PlanTask> { - self.missing.iter().filter(|t| !t.optional).collect() + self.missing + .iter() + .filter(|t| !t.optional && !t.generated) + .collect() + } + + /// Generated files the plan names that the branch doesn't change yet: + /// the generator check runs their generator before the pull request. + pub fn generated_missing(&self) -> Vec<&PlanTask> { + self.missing + .iter() + .filter(|t| t.generated && !t.optional) + .collect() } /// Tasks the plan marks optional that aren't done. @@ -228,11 +304,18 @@ pub fn round_feedback(cov: &Coverage) -> String { /// naming the tasks (the run record keeps up to 500 characters; the full /// list is in [`progress_note`]). pub fn stop_reason(cov: &Coverage, branch: &str) -> String { + stop_reason_why(cov, branch, "") +} + +/// [`stop_reason`] with why the tasks aren't done, when the run knows. +pub fn stop_reason_why(cov: &Coverage, branch: &str, why: &str) -> String { let missing = cov.required_missing(); let paths: Vec = missing.iter().map(|t| format!("`{}`", t.path)).collect(); + let why = why.trim().trim_end_matches('.'); + let room = 280usize.saturating_sub(why.len()); let mut list = String::new(); for (i, p) in paths.iter().enumerate() { - if list.len() + p.len() > 280 { + if list.len() + p.len() > room { list.push_str(&format!(" and {} more", paths.len() - i)); break; } @@ -242,10 +325,15 @@ pub fn stop_reason(cov: &Coverage, branch: &str) -> String { list.push_str(p); } format!( - "Stopped before opening a pull request: {} of {} planned tasks are not done ({list}). \ + "Stopped before opening a pull request: {} of {} planned tasks are not done ({list}){}. \ The work so far is on branch `{branch}`; Retry continues from the plan.", missing.len(), cov.total(), + if why.is_empty() { + String::new() + } else { + format!(": {why}") + }, ) } @@ -260,7 +348,13 @@ pub fn progress_note(cov: &Coverage) -> String { lines.push(format!("- [x] {}", t.path)); } for t in &cov.missing { - let note = if t.optional { " (optional)" } else { "" }; + let note = if t.optional { + " (optional)" + } else if t.generated { + " (generated: the generator check runs it before the pull request)" + } else { + "" + }; lines.push(format!("- [ ] {}{note}", t.path)); } lines.join("\n") @@ -353,7 +447,14 @@ pub async fn close_gaps( usage: &mut TokenUsage, has_time: impl Fn() -> bool, ) -> Option { - let tasks = plan_tasks(&w.plan.tasks); + let tasks = tasks_for( + w.github, + &w.msg.repo_owner, + &w.msg.repo_name, + w.branch, + &w.plan.tasks, + ) + .await; if tasks.is_empty() { return None; } @@ -570,6 +671,48 @@ mod tests { assert!(r.len() <= 500); } + /// The observed run: every task done but a generated types file and an + /// extracted schema, which the generator left unchanged in each step. + /// The plan check hands them to the generator check instead of + /// continuing on them until the run ends. + #[test] + fn generated_files_never_hold_the_plan_check() { + let plan = "- [ ] `studio/schemaTypes/blocks/hero.ts`: Create the block schema\n\ + - [ ] `studio/schema.json`: Regenerate with schema extract\n\ + - [ ] `web/src/sanity.types.ts`: Update the types for the new block\n"; + let mut tasks = plan_tasks(plan); + assert!(!tasks[0].generated); + assert!(tasks[1].generated, "the task says so"); + assert!(!tasks[2].generated, "only the generator's outputs say so"); + mark_generated(&mut tasks, &["web/**/sanity.types.ts".to_string()]); + assert!(tasks[2].generated); + let cov = coverage(&tasks, &changed(&["studio/schemaTypes/blocks/hero.ts"])); + assert!(cov.required_missing().is_empty()); + assert_eq!(cov.generated_missing().len(), 2); + assert_eq!(next(&cov, MAX_ROUNDS, false), Next::Complete); + let note = progress_note(&cov); + assert!(note.contains("- [ ] web/src/sanity.types.ts (generated")); + // Not pushed on a coder round either. + assert!(!round_feedback(&cov).contains("sanity.types.ts")); + } + + #[test] + fn the_stop_status_can_say_why() { + let cov = coverage(&plan_tasks(PLAN), &changed(&["src/blocks/registry.ts"])); + let r = stop_reason_why(&cov, "b", "the last step changed no file for them."); + assert!(r.contains("(`src/blocks/gallery/index.ts`")); + assert!(r.contains(": the last step changed no file for them. The work so far")); + let plan: String = (0..40) + .map(|i| format!("- [ ] `src/very/long/path/to/module_{i}/file_{i}.ts`: Create it\n")) + .collect(); + let long = stop_reason_why( + &coverage(&plan_tasks(&plan), &[]), + "coderhelm-wip/feature/a-long-branch-name", + "the last step changed no file for them", + ); + assert!(long.len() <= 500, "{}", long.len()); + } + #[test] fn only_done_tasks_are_checked_off() { let cov = coverage(&plan_tasks(PLAN), &changed(&["src/blocks/registry.ts"])); diff --git a/services/worker/src/passes/pr_holder.rs b/services/worker/src/passes/pr_holder.rs new file mode 100644 index 000000000..d7ca04c55 --- /dev/null +++ b/services/worker/src/passes/pr_holder.rs @@ -0,0 +1,407 @@ +//! One writer per pull request branch, across runs of a ticket. +//! +//! A person pressed Retry on a stopped run of a ticket whose earlier run had +//! an open pull request. The new run took the same branch (the pull +//! request's), built on it for forty minutes, while the earlier run's +//! feedback pass worked the same pull request: two runs writing one branch. +//! Each run's writer slot only guarded the run itself. +//! +//! The rules here: +//! +//! - A run that is about to work on an open pull request an earlier run of +//! the ticket opened finds that run ([`holder_runs`]) and reads it fresh. +//! While it is still working ([`busy`]: queued or running, waiting for CI +//! and fixing what fails, writing to the branch now, or a fix round under +//! way or parked), the new run stops before it writes anything and says so +//! on the run page, naming the pull request and the run +//! ([`busy_note`], [`stop_busy`]). +//! - When the earlier run is done, the new run continues that pull request +//! as its update ([`continue_note`]) and holds the earlier run's writer +//! slot while it works ([`claim`]): a feedback or CI pass of the earlier +//! run waits for it instead of writing the branch at the same time. + +use common::run_round::{Round, State}; +use common::run_status::{self, EndedValues}; +use tracing::{info, warn}; + +use crate::models::{TicketMessage, TokenUsage}; +use crate::WorkerState; + +use super::ticket_history::TicketHistory; +use super::{attr_n, attr_s, RunUsageValues, RunWriterGuard}; + +/// Run statuses that mean the run is still working on its pull request. +const WORKING: [&str; 4] = [ + run_status::PENDING, + run_status::QUEUED, + run_status::RUNNING, + run_status::AWAITING_CI, +]; + +/// An earlier run that opened the pull request, as its record says now. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Holder { + pub run_id: String, + pub status: String, + /// Unix seconds its writer slot is held until (0: free). + pub writer_until: i64, + /// What holds the slot (`feedback#…`, `resume#…`). + pub writer_holder: String, + pub round: Option, +} + +impl Holder { + pub fn from_item( + run_id: &str, + item: &std::collections::HashMap, + ) -> Holder { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + Holder { + run_id: run_id.to_string(), + status: s("status"), + writer_until: item + .get("writer_until") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + writer_holder: s("writer_holder"), + round: Round::from_item(item), + } + } +} + +/// Why the earlier run is still working on its pull request, in a person's +/// words; `None` when it is done with it. `holder`: this run's own name on +/// a writer slot (its own hold is not someone else's work). +pub fn busy(h: &Holder, now: chrono::DateTime, holder: &str) -> Option { + if run_status::ended_by_person(&h.status) { + return None; + } + if WORKING.contains(&h.status.as_str()) { + return Some(match h.status.as_str() { + run_status::AWAITING_CI => { + "it is waiting for CI on the pull request and fixes what fails".to_string() + } + run_status::RUNNING => "it is still running".to_string(), + _ => "it is queued to start".to_string(), + }); + } + if h.writer_until > now.timestamp() && h.writer_holder != holder { + let pass = h + .writer_holder + .split('#') + .next() + .filter(|p| !p.is_empty()) + .unwrap_or("a"); + return Some(format!("it is writing to the branch now (its {pass} pass)")); + } + if let Some(r) = &h.round { + let deadline = chrono::DateTime::parse_from_rfc3339(&r.deadline_at) + .map(|d| d.with_timezone(&chrono::Utc)) + .ok(); + let grace = chrono::Duration::seconds(common::run_round::SWEEP_GRACE_SECS as i64); + // A round past its deadline and the sweep's grace is gone, not + // working: the sweep closes it. + let live = r.state == State::Pending || deadline.is_none_or(|d| d + grace > now); + if live { + return Some(match r.state { + State::Pending => format!("its {} is waiting to run", r.kind.label()), + State::Running => format!("its {} is under way", r.kind.label()), + }); + } + } + None +} + +/// The earlier runs of the ticket that opened `repo#number`. +pub fn holder_runs(history: &TicketHistory, repo: &str, number: u64) -> Vec { + history + .runs + .iter() + .filter(|r| { + r.pr_list + .iter() + .any(|p| p.pr_number == number && p.repo.eq_ignore_ascii_case(repo)) + || (r.pr_number == number + && (r.repo.is_empty() || r.repo.eq_ignore_ascii_case(repo))) + }) + .map(|r| r.run_id.clone()) + .collect() +} + +/// This run's name on an earlier run's writer slot. +pub fn holder_name(run_id: &str) -> String { + format!("ticket_run#{run_id}") +} + +/// The run page's note when the run continues the earlier run's pull +/// request. +pub fn continue_note(number: u64, earlier: &[String]) -> String { + format!( + "This ticket already has CoderHelm's open pull request #{number}{}: this run continues it \ + as its update, on its branch, and opens no other. The earlier run doesn't write to the \ + branch while this one works.", + match earlier.last() { + Some(r) => format!(" (from run {r})"), + None => String::new(), + } + ) +} + +/// The run page's note (and the run's status) when the earlier run is +/// still working on the pull request. +pub fn busy_note(number: u64, holder_run: &str, why: &str) -> String { + format!( + "Stopped before writing anything: this ticket's open pull request #{number} belongs to run \ + {holder_run}, and {why}. Two runs never write the same branch. Retry once that run is \ + done: the retry then continues #{number} as its update." + ) +} + +/// What [`claim`] found. +pub enum Claim { + /// The earlier runs are done; this run holds their writer slots. + Free(Vec), + /// An earlier run is still working on the pull request. + Busy { run_id: String, why: String }, +} + +/// Reads each earlier run fresh and, when none is working on the pull +/// request, takes their writer slots for this invocation. +pub async fn claim(state: &WorkerState, team_id: &str, run_id: &str, earlier: &[String]) -> Claim { + let me = holder_name(run_id); + let mut guards = Vec::new(); + for other in earlier { + let item = match state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(other)) + .send() + .await + { + Ok(out) => out.item, + Err(e) => { + warn!(run_id, other, error = %e, "Could not read the pull request's earlier run"); + return Claim::Busy { + run_id: other.clone(), + why: "its record couldn't be read to make sure it isn't working on it" + .to_string(), + }; + } + }; + let Some(item) = item else { continue }; + let h = Holder::from_item(other, &item); + if let Some(why) = busy(&h, chrono::Utc::now(), &me) { + return Claim::Busy { + run_id: other.clone(), + why, + }; + } + match super::acquire_run_writer_guard(state, team_id, other, &me).await { + Some(g) => guards.push(g), + None => { + return Claim::Busy { + run_id: other.clone(), + why: "it is writing to the branch now".to_string(), + } + } + } + } + Claim::Free(guards) +} + +/// Ends the run without writing: the pull request's earlier run is still +/// working on it. The run reads as covered by that pull request, and Retry +/// continues it once the earlier run is done. +#[allow(clippy::too_many_arguments)] +pub async fn stop_busy( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + usage: &TokenUsage, + start: &std::time::Instant, + pr: (&str, u64, &str, &str), + holder_run: &str, + why: &str, +) { + let (repo, number, url, title) = pr; + let note = busy_note(number, holder_run, why); + info!( + run_id, + pr = number, + holder_run, + why, + "Pull request busy with an earlier run" + ); + super::add_progress_note(state, &msg.team_id, run_id, ¬e).await; + let record = serde_json::json!({ + "repo": repo, + "number": number, + "url": url, + "title": title, + "author": "CoderHelm", + "reason": format!("run {holder_run} is still working on it"), + "signals": ["it is CoderHelm's own pull request for this ticket"], + }); + let status = run_status::COVERED_BY_PR; + let delta = usage.unrecorded(); + let written = 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, covered_by = :cb, error_message = :em, \ + 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, current_pass = :cp", + ) + .condition_expression(run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(status)) + .expression_attribute_values(":sri", attr_s(&format!("{status}#{run_id}"))) + .expression_attribute_values(":cb", attr_s(&record.to_string())) + .expression_attribute_values(":em", attr_s(¬e)) + .usage_values(&delta) + .expression_attribute_values(":d", attr_n(start.elapsed().as_secs())) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":cp", attr_s("done")) + .send() + .await; + if let Err(e) = written { + warn!(run_id, error = %e, "Could not record the stop for a busy pull request"); + } + super::webhooks::emit_run(state, &msg.team_id, run_id, status).await; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::ticket_history::PriorRun; + use common::run_round::Kind; + + fn at(s: &str) -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339(s) + .unwrap() + .with_timezone(&chrono::Utc) + } + + fn holder(status: &str) -> Holder { + Holder { + run_id: "R0".into(), + status: status.into(), + ..Default::default() + } + } + + /// The observed case: the earlier run read `completed` while its + /// feedback pass held its writer slot and worked the pull request. + #[test] + fn a_completed_run_writing_its_branch_is_busy() { + let now = at("2026-01-10T01:55:00Z"); + let mut h = holder("completed"); + h.writer_until = now.timestamp() + 600; + h.writer_holder = "feedback#1793152075223200704".into(); + let why = busy(&h, now, &holder_name("R1")).unwrap(); + assert_eq!(why, "it is writing to the branch now (its feedback pass)"); + // Its slot expired: done. + h.writer_until = now.timestamp() - 1; + assert_eq!(busy(&h, now, &holder_name("R1")), None); + // This run's own hold (a continuation of it) is not someone else's. + h.writer_until = now.timestamp() + 600; + h.writer_holder = holder_name("R1"); + assert_eq!(busy(&h, now, &holder_name("R1")), None); + } + + #[test] + fn working_statuses_are_busy_and_ended_ones_are_not() { + let now = at("2026-01-10T01:55:00Z"); + for s in ["pending", "queued", "running", "awaiting_ci"] { + assert!(busy(&holder(s), now, "x").is_some(), "{s}"); + } + assert!(busy(&holder("awaiting_ci"), now, "x") + .unwrap() + .contains("waiting for CI")); + for s in [ + "completed", + "needs_input", + "failed", + "covered_by_pr", + "cancelled", + "closed", + ] { + assert_eq!(busy(&holder(s), now, "x"), None, "{s}"); + } + } + + #[test] + fn a_round_under_way_or_parked_is_busy_until_the_sweep_would_close_it() { + let now = at("2026-01-10T02:00:00Z"); + let mut round = Round::start(Kind::Feedback, 1, "", "", false, at("2026-01-10T01:50:00Z")); + round.deadline_at = "2026-01-10T02:02:00Z".into(); + let mut h = holder("completed"); + h.round = Some(round.clone()); + assert!(busy(&h, now, "x").unwrap().contains("under way")); + // Long past its deadline and the grace: gone, not working. + round.deadline_at = "2026-01-10T01:00:00Z".into(); + h.round = Some(round.clone()); + assert_eq!(busy(&h, now, "x"), None); + // Parked: waits for a fresh invocation, still the run's. + round.state = State::Pending; + h.round = Some(round); + assert!(busy(&h, now, "x").unwrap().contains("waiting to run")); + } + + #[test] + fn the_runs_that_opened_the_pull_request_are_found() { + let mut history = TicketHistory::default(); + history.runs.push(PriorRun { + run_id: "R0".into(), + repo: "acme/web".into(), + pr_number: 41, + pr_list: vec![common::run_prs::RunPr { + repo: "acme/web".into(), + pr_number: 41, + ..Default::default() + }], + ..Default::default() + }); + history.runs.push(PriorRun { + run_id: "R1".into(), + repo: "acme/web".into(), + ..Default::default() + }); + assert_eq!( + holder_runs(&history, "Acme/Web", 41), + vec!["R0".to_string()] + ); + assert!(holder_runs(&history, "acme/api", 41).is_empty()); + assert!(holder_runs(&history, "acme/web", 7).is_empty()); + } + + #[test] + fn the_notes_name_the_pull_request_and_the_run() { + let busy = busy_note( + 41, + "R0", + "it is writing to the branch now (its feedback pass)", + ); + assert!(busy.contains("#41")); + assert!(busy.contains("run R0")); + assert!(busy.contains("Two runs never write the same branch")); + assert!(busy.contains("Retry once that run is done")); + let cont = continue_note(41, &["R0".to_string()]); + assert!(cont.contains("open pull request #41 (from run R0)")); + assert!(cont.contains("continues it as its update")); + } +} diff --git a/services/worker/src/passes/run_end.rs b/services/worker/src/passes/run_end.rs new file mode 100644 index 000000000..6eabd411d --- /dev/null +++ b/services/worker/src/passes/run_end.rs @@ -0,0 +1,307 @@ +//! How a run ends when an implement step changes no file. +//! +//! A run's work can span several steps: a step that runs out of its time +//! continues in a fresh one, and each step only counts the files it wrote +//! itself. A run once built fourteen files over three steps; its fourth step +//! found nothing left to write, and the run ended as "I ran but produced no +//! file changes" with two generic questions ("Which files or components +//! should change?", "What should happen instead?"), although the branch held +//! all the work and the ticket named every file. +//! +//! The rules here: +//! +//! - The run's work is the branch's diff against the base it started from +//! ([`work_files`]), summed over every step: never the last step alone. A +//! step that changed nothing on a branch that holds the work goes on to +//! the plan check and the pull request ([`Empty::Carry`]). +//! - With nothing on the branch and a plan that names its files, the run +//! builds once more, told every planned task ([`build_round_feedback`]). +//! - Still nothing: a question the coder itself wrote (naming what it +//! couldn't decide) is asked ([`Empty::Ask`]); otherwise, when the ticket +//! or the plan already names the files, the run stops naming the planned +//! tasks that aren't built ([`Empty::Unbuilt`]). It never asks the generic +//! questions then. +//! - The generic questions ([`Empty::Generic`]) are only for a ticket that +//! names no file and a plan with no file tasks. + +use super::plan_coverage::PlanTask; + +/// What a step that changed no file leads to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Empty { + /// The branch holds the run's work (these files): judge that. + Carry(Vec), + /// Ask the coder's own questions (each names what it couldn't decide). + Ask(Vec), + /// Nothing built although the ticket or plan names the files: stop + /// with this reason, no question. + Unbuilt(String), + /// The ticket names no file and the plan has no file tasks: ask what + /// should change. + Generic, +} + +/// The files the branch changes that are the run's work: everything but the +/// plan files CoderHelm commits beside it (`openspec/specs//`). +pub fn work_files(changed: &[String], ticket_id: &str) -> Vec { + let spec_dir = format!("openspec/specs/{}/", ticket_id.to_lowercase()); + changed + .iter() + .filter(|p| { + let p = p.trim_start_matches("./"); + ticket_id.is_empty() || !p.to_lowercase().starts_with(&spec_dir) + }) + .cloned() + .collect() +} + +/// The questions the coder ended its account with: lines ending in `?` +/// that say what it couldn't decide. At most three. +pub fn coder_questions(notes: &str) -> Vec { + let mut out: Vec = Vec::new(); + for line in notes.lines() { + let q = line + .trim() + .trim_start_matches(['-', '*', '>', ' ']) + .trim_start_matches(|c: char| c.is_ascii_digit() || c == '.' || c == ')') + .trim() + .trim_start_matches("Question:") + .trim_start_matches("QUESTION:") + .trim(); + // A question worth asking names something: a few words at least. + if q.ends_with('?') && q.split_whitespace().count() >= 5 && q.len() <= 400 { + let q = q.to_string(); + if !out.contains(&q) { + out.push(q); + } + } + if out.len() == 3 { + break; + } + } + out +} + +/// Whether the ticket's text names a file (`dir/name.ext`). +pub fn ticket_names_files(text: &str) -> bool { + text.split(|c: char| c.is_whitespace() || "`'\"()[]<>,;".contains(c)) + .map(|t| t.trim_end_matches(['.', ':'])) + .any(|t| { + let Some((dir, file)) = t.rsplit_once('/') else { + return false; + }; + !dir.is_empty() + && !t.contains("://") + && file.rsplit_once('.').is_some_and(|(stem, ext)| { + !stem.is_empty() + && (1..=5).contains(&ext.len()) + && ext.chars().all(|c| c.is_ascii_alphanumeric()) + }) + }) +} + +/// What a step that changed no file leads to. `work`: the branch's work +/// files (`None` when GitHub couldn't say: then nothing is claimed either +/// way and the plan decides); `tasks`: the plan's file tasks; +/// `questions`: the coder's own; `ticket_names_files`: the ticket's text +/// names a file. +pub fn judge( + work: Option<&[String]>, + tasks: &[PlanTask], + questions: &[String], + ticket_names_files: bool, +) -> Empty { + if let Some(w) = work.filter(|w| !w.is_empty()) { + return Empty::Carry(w.to_vec()); + } + if !questions.is_empty() { + return Empty::Ask(questions.to_vec()); + } + let required: Vec<&PlanTask> = tasks + .iter() + .filter(|t| !t.optional && !t.generated) + .collect(); + if !required.is_empty() || ticket_names_files { + return Empty::Unbuilt(unbuilt_reason(&required, work.is_none())); + } + Empty::Generic +} + +fn unbuilt_reason(required: &[&PlanTask], unread: bool) -> String { + let mut list = String::new(); + for (i, t) in required.iter().enumerate() { + let p = format!("`{}`", t.path); + if list.len() + p.len() > 260 { + list.push_str(&format!(" and {} more", required.len() - i)); + break; + } + if i > 0 { + list.push_str(", "); + } + list.push_str(&p); + } + let what = if required.is_empty() { + "the files the ticket names".to_string() + } else { + format!("{} planned task(s): {list}", required.len()) + }; + format!( + "Stopped without a pull request: the coder wrote no file{}, although the ticket and plan \ + say what to build ({what}). That is CoderHelm's miss, not missing detail: Retry builds it \ + from the same plan.", + if unread { + " (and GitHub couldn't show the branch's diff)" + } else { + " on the branch" + } + ) +} + +/// What the extra build round is told when a step wrote nothing and the +/// branch holds nothing: every planned task, and to ask only what it +/// truly can't decide, after building the rest. +pub fn build_round_feedback(tasks: &[PlanTask]) -> String { + let todo: Vec = tasks + .iter() + .filter(|t| !t.optional && !t.generated) + .map(|t| format!("- [ ] `{}`: {}", t.path, t.task)) + .collect(); + format!( + "Your last pass wrote no file and the branch has none of this change yet. The ticket and \ + plan say what to build: do every task below now, writing each file as soon as it is \ + done.\n\n{}\n\nIf one detail truly can't be decided from the ticket, the code or a \ + lookup, build everything else first, then end your summary with one question per open \ + detail, naming the file, field or option it decides (for example: \"Should the `size` \ + option of `src/blocks/card.ts` default to `small` or `large`?\").", + todo.join("\n") + ) +} + +/// The coder's questions as the run's questions, each saying the rest was +/// built or tried first. +pub fn questions_from(qs: &[String]) -> Vec { + qs.iter() + .enumerate() + .map(|(i, q)| common::run_questions::Question { + id: format!("q{}", i + 1), + question: q.clone(), + why: "The coder couldn't decide this from the ticket, the code or a lookup, and the \ + change depends on it." + .to_string(), + suggestions: Vec::new(), + decision: String::new(), + evidence: Vec::new(), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::plan_coverage::plan_tasks; + + const PLAN: &str = "- [ ] `web/src/blocks/hero.tsx`: Create the hero block\n\ + - [ ] `web/src/blocks/hero.test.tsx`: Add tests for each tab option\n\ + - [ ] `e2e/test-map.json`: Register the new spec\n\ + - [ ] `studio/schema.json`: Regenerate with schema extract\n"; + + fn files(p: &[&str]) -> Vec { + p.iter().map(|s| s.to_string()).collect() + } + + /// The observed run: the last step wrote nothing, the branch held the + /// work of the earlier steps. + #[test] + fn a_step_that_wrote_nothing_on_a_branch_with_the_work_carries_on() { + let branch = files(&[ + "openspec/specs/abc-12/tasks.md", + "web/src/blocks/hero.tsx", + "web/src/blocks/hero.test.tsx", + "e2e/test-map.json", + ]); + let work = work_files(&branch, "ABC-12"); + assert_eq!(work.len(), 3, "the plan files are not the work"); + let out = judge(Some(&work), &plan_tasks(PLAN), &[], true); + assert_eq!(out, Empty::Carry(work)); + } + + #[test] + fn only_the_plan_files_on_the_branch_is_no_work() { + let work = work_files(&files(&["openspec/specs/abc-12/proposal.md"]), "ABC-12"); + assert!(work.is_empty()); + // The ticket and plan name the files: never the generic questions. + match judge(Some(&work), &plan_tasks(PLAN), &[], true) { + Empty::Unbuilt(r) => { + assert!(r.contains("3 planned task(s)"), "{r}"); + assert!(r.contains("`web/src/blocks/hero.tsx`")); + assert!( + !r.contains("schema.json"), + "a generated file isn't the coder's" + ); + assert!(r.contains("Retry")); + assert!(r.len() <= 500, "fits the run record's reason"); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn the_coders_own_question_is_asked_not_the_generic_ones() { + let notes = "Built the block.\n\nOpen question:\n- Should the `layout` field of \ + `web/src/blocks/hero.tsx` default to `grid` or `carousel`?\n- ok?\n"; + let qs = coder_questions(notes); + assert_eq!( + qs, + vec![ + "Should the `layout` field of `web/src/blocks/hero.tsx` default to `grid` or `carousel`?" + .to_string() + ], + "a bare 'ok?' is not a question worth asking" + ); + assert_eq!( + judge(Some(&[]), &plan_tasks(PLAN), &qs, true), + Empty::Ask(qs.clone()) + ); + let asked = questions_from(&qs); + assert_eq!(asked[0].id, "q1"); + assert!(asked[0].question.contains("`layout`")); + } + + #[test] + fn generic_questions_only_when_nothing_names_a_file() { + assert_eq!(judge(Some(&[]), &[], &[], false), Empty::Generic); + assert!(matches!( + judge(Some(&[]), &[], &[], true), + Empty::Unbuilt(_) + )); + // An unreadable diff never claims "no changes" for a planned ticket. + assert!(matches!( + judge(None, &plan_tasks(PLAN), &[], false), + Empty::Unbuilt(r) if r.contains("couldn't show") + )); + } + + #[test] + fn a_ticket_that_names_a_file_is_read_as_such() { + assert!(ticket_names_files( + "Add the block in `web/src/blocks/hero.tsx` and register it." + )); + assert!(ticket_names_files("Update e2e/test-map.json.")); + assert!(!ticket_names_files( + "See https://example.com/docs/page.html" + )); + assert!(!ticket_names_files( + "The hero should show three tabs and/or a title." + )); + } + + #[test] + fn the_build_round_names_every_task_and_how_to_ask() { + let fb = build_round_feedback(&plan_tasks(PLAN)); + assert!(fb.contains("`web/src/blocks/hero.tsx`")); + assert!(fb.contains("`e2e/test-map.json`")); + assert!(!fb.contains("schema.json")); + assert!(fb.contains("build everything else first")); + assert!(fb.contains("naming the file, field or option")); + } +}