From eb8f8f7c000a728eba36f7ca2cc373401effbdce Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 1 Dec 2026 14:16:06 -0500 Subject: [PATCH 1/3] A run builds every repository of its plan, and nothing waits on a person without a typed reason --- docs/api/openapi.json | 24 +- docs/incidents/xj_plan_builds_every_repo.md | 12 + services/common/src/draft_hold.rs | 17 +- services/common/src/lib.rs | 6 + services/common/src/merge_standing.rs | 292 ++++++++++- services/common/src/plan_repos.rs | 306 ++++++++++++ services/common/src/rendered.rs | 28 ++ services/common/src/run_ending.rs | 141 +++++- services/common/src/stub_check.rs | 311 ++++++++++++ services/common/src/waiting_line.rs | 193 ++++++- services/gateway/src/routes/api.rs | 14 +- services/worker/src/passes/await_merge.rs | 9 +- services/worker/src/passes/completeness.rs | 26 +- .../src/passes/incidents/ae_budget_rounds.rs | 8 +- .../incidents/ba_verdict_on_old_commit.rs | 4 +- .../incidents/bt_proof_answer_closes.rs | 23 +- .../incidents/bu_web_change_unchecked.rs | 2 +- .../incidents/xj_plan_builds_every_repo.rs | 469 ++++++++++++++++++ services/worker/src/passes/mod.rs | 81 ++- services/worker/src/passes/own_problems.rs | 8 + .../worker/src/passes/own_review_ledger.rs | 105 +++- services/worker/src/passes/plan_continue.rs | 433 ++++++++++++++++ services/worker/src/passes/pr_watch.rs | 51 ++ services/worker/src/passes/ready.rs | 125 ++++- services/worker/src/passes/recover.rs | 6 + services/worker/src/passes/resume.rs | 220 ++++---- .../worker/src/passes/review_acceptance.rs | 57 +++ services/worker/src/passes/review_agent.rs | 19 +- services/worker/src/passes/review_pr.rs | 133 +++-- 29 files changed, 2887 insertions(+), 236 deletions(-) create mode 100644 docs/incidents/xj_plan_builds_every_repo.md create mode 100644 services/common/src/plan_repos.rs create mode 100644 services/common/src/stub_check.rs create mode 100644 services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs create mode 100644 services/worker/src/passes/plan_continue.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index bdf0b0561..9a8ea2ed4 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -5189,6 +5189,13 @@ ], "type": "string" }, + "needs_person": { + "description": "A person must act: a reason only a person has (a typed hand-off).\nFalse for every hold CoderHelm settles itself.", + "examples": [ + true + ], + "type": "boolean" + }, "pr_number": { "description": "The pull request.", "examples": [ @@ -5227,7 +5234,8 @@ "kind", "summary", "reasons", - "pr_number" + "pr_number", + "needs_person" ], "type": "object" }, @@ -5286,8 +5294,20 @@ "RunMergeStanding": { "description": "Where a run's pull request stands on its way to merge.", "properties": { + "approvals": { + "description": "Approving reviews from people the repository's rule requires\n(`needs_person_approval`, `repo_requires_person_review`). Null when\nnot known.", + "examples": [ + 1 + ], + "format": "int32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, "code": { - "description": "Stable code: `merged`, `closed`, `reviewing`, `fixing_review`,\n`review_changes_requested`, `checks_running`, `checks_failing`,\n`conflict`, `draft`, `auto_merge_off`, `needs_person_approval`,\n`repo_requires_person_review` or `merging`.", + "description": "Stable code: `merged`, `closed`, `reviewing`, `fixing_review`,\n`review_changes_requested`, `checks_running`, `checks_failing`,\n`conflict`, `draft`, `auto_merge_off`, `needs_person_approval`,\n`repo_requires_person_review`, `building_plan`, `plan_needs_access`\nor `merging`.", "examples": [ "auto_merge_off" ], diff --git a/docs/incidents/xj_plan_builds_every_repo.md b/docs/incidents/xj_plan_builds_every_repo.md new file mode 100644 index 000000000..50b1797b4 --- /dev/null +++ b/docs/incidents/xj_plan_builds_every_repo.md @@ -0,0 +1,12 @@ +# xj. `xj_plan_builds_every_repo` + +**What happened:** A ticket's plan spanned two repositories: an infrastructure repository (the module for a scheduled function) and an API repository (the function's code, its tests, a migration and its deploy workflow). The run opened a pull request in the infrastructure repository only, and its function was a placeholder file. The API repository's plan check said the plan was unfinished, and the multi-repository loop read that as "this repository failed" and moved on, so the run went on with one pull request and most of the API tasks still to do. CoderHelm's own review then asked for changes on the infrastructure pull request: an acceptance line the change doesn't deliver. The fix round worked for hours on a branch where that fix could not live, listed the findings as deferred, and the run ended "Done". Its page said "Waiting on: a person, CoderHelm's review asks for changes it could not make" next to "Nothing needed from you", and the review's additional findings showed an empty place: "πŸ’¬ `` β€” An acceptance line…". + +**The invariants, enforced in code:** + +1. **A run never ends while its own plan has undone tasks in a repository it can write to.** The run keeps its plan repository by repository (`common::plan_repos`) and the count it still owes (`plan_owed`). Every done or waiting ending goes through the one ending gate (`common::run_ending`), which writes it only under `PLAN_GATE`: the count is 0. A source scan fails when a new ending path is written outside that gate. The multi-repository loop keeps an unfinished repository as owed and takes a fresh step for it, and the plan sweep (`plan_continue::sweep`, on deploy and every 15 minutes) picks up runs that still owe one, including runs from before the record kept the plan. +2. **A pull request is never offered for review while it ships a placeholder in place of what its ticket needs, or while another part of the plan is unbuilt.** `common::stub_check` reads the diff for placeholder files, empty handlers, "not implemented" errors and TODOs where the implementation goes. The ready decision (`ready::offer_blocked`) waits on them, the coder replaces them in a round of its own, and the one call that marks a pull request ready checks again right before GitHub is asked. The parts of a plan are linked: each pull request names itself "part 1 of 2" or "part 2 of 2" and the order they merge in. +3. **"Deferred" is only for a typed person-only reason.** A finding whose fix the run's own plan or routes can make is never deferred: the rest of the plan is built first (`plan_continue::continue_if_owed`, before any fix round or deferral), and only a reason that types as `PersonOnly` defers (`own_review_ledger::typed_settle`). CoderHelm's own limits are an internal alert and a typed stop that names what its review still asks for. They are never "Done", never deferred and never a person's wait. +4. **Every "waiting on a person" goes through #930's `PersonOnly`.** The merge standing (`Standing::person_only`), the draft hold (`DraftHold::person_only`) and the run page's line (`waiting_line`) name a person only through it. The page's "Needs a person" badge and its top line are read from that one state, so they can't disagree. When the only wait left is the repository's required approval, the line says exactly "Needs 1 approval from a person (repo rule)" with the pull request. A source scan fails when a new text claims a person is needed without the type. + +The empty place in a finding is gone. A finding on no file is listed by its title, and the text guard (`rendered::person_text`) fails on an empty code span or an empty name. diff --git a/services/common/src/draft_hold.rs b/services/common/src/draft_hold.rs index eb81dae6c..ccd009e3b 100644 --- a/services/common/src/draft_hold.rs +++ b/services/common/src/draft_hold.rs @@ -234,7 +234,22 @@ impl DraftHold { /// anything else, and GitHub refusing to mark it ready, are CoderHelm's /// to finish. pub fn needs_person(&self) -> bool { - self.kind == Kind::Held && self.reasons.iter().any(|r| r.human_only().is_some()) + self.person_only().is_some() + } + + /// The typed hand-off a held pull request waits on + /// (`person_only::PersonOnly`, #930's one type for a person's to-do): + /// a reason on the human-only list whose words name nothing CoderHelm + /// owns. `None` for every other hold: it is CoderHelm's to finish. + pub fn person_only(&self) -> Option { + if self.kind != Kind::Held { + return None; + } + self.reasons.iter().find_map(|r| { + let why = r.human_only()?; + let need = format!("{} {}", r.what, r.todo); + crate::person_only::of_human_only(why, need.trim()).ok() + }) } fn pr_words(&self) -> String { diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 7942e01ec..9eb718d56 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -244,6 +244,9 @@ pub mod paged; pub mod placeholders; /// Which waiting plan tasks a merged run releases. pub mod plan_dependents; +/// A run's plan, repository by repository: what each part built and what +/// the run still owes before it finishes. +pub mod plan_repos; pub mod plan_state; pub mod plan_sync; /// Every body CoderHelm sends GitHub fits GitHub's limit. @@ -282,6 +285,9 @@ pub mod run_prs; /// Scope decided once at plan time, held in every round and in the /// description. pub mod scope_ledger; +/// A pull request never ships a placeholder in place of what its ticket +/// asks for: the diff check before it is offered for review. +pub mod stub_check; pub mod waiting_line; // review_stats: time-ordered review records for analytics /// A run waiting for another ticket's change to merge, and what it does diff --git a/services/common/src/merge_standing.rs b/services/common/src/merge_standing.rs index e72a2efa8..462fc2aab 100644 --- a/services/common/src/merge_standing.rs +++ b/services/common/src/merge_standing.rs @@ -16,6 +16,8 @@ use serde::{Deserialize, Serialize}; +use crate::person_only::PersonOnly; + /// The run record's field holding the standing, as JSON. pub const FIELD: &str = "merge_standing"; @@ -47,6 +49,15 @@ pub struct Facts { /// GitHub reports the merge blocked by the branch's rules although the /// checks are green (`mergeable_state` = `blocked`). pub blocked_by_rules: bool, + /// Approving reviews from people the repository's rules require on the + /// branch ([`approvals_required`]); 0 when not known. + pub approvals_required: u32, + /// Repositories of the run's plan that still owe their tasks + /// (`plan_repos`): the run builds them before anything else. + pub plan_owed: Vec, + /// The one reason a person is needed for the run's plan: a repository + /// CoderHelm can't write to (`plan_repos::Part::person_only`). + pub plan_person: Option, } /// One standing, as shown. @@ -67,6 +78,51 @@ pub struct Standing { /// GitHub URL); empty otherwise. #[serde(default, skip_serializing_if = "String::is_empty")] pub link: String, + /// The approving reviews from people the repository's rule requires, + /// for `needs_person_approval` and `repo_requires_person_review`; 0 + /// when not known. + #[serde(default, skip_serializing_if = "is_zero")] + pub approvals: u32, +} + +fn is_zero(n: &u32) -> bool { + *n == 0 +} + +/// "1 approval", "2 approvals". +pub fn approvals_words(n: u32) -> String { + let n = n.max(1); + if n == 1 { + "1 approval".into() + } else { + format!("{n} approvals") + } +} + +/// The approving reviews the branch's rules require, from GitHub's rules +/// for the branch (`GET /repos/{o}/{r}/rules/branches/{b}`) and its classic +/// protection (`GET .../branches/{b}/protection`), the larger of the two. +/// 0 when neither names a count. +pub fn approvals_required( + rules: Option<&serde_json::Value>, + protection: Option<&serde_json::Value>, +) -> u32 { + let from_rules = rules + .and_then(|r| r.as_array()) + .map(|a| { + a.iter() + .filter(|r| r["type"].as_str() == Some("pull_request")) + .filter_map(|r| r["parameters"]["required_approving_review_count"].as_u64()) + .max() + .unwrap_or(0) + }) + .unwrap_or(0); + let from_protection = protection + .and_then(|p| { + p["required_pull_request_reviews"]["required_approving_review_count"].as_u64() + }) + .unwrap_or(0); + from_rules.max(from_protection).min(u64::from(u32::MAX)) as u32 } impl Standing { @@ -77,9 +133,15 @@ impl Standing { next: next.to_string(), needs_person, link, + approvals: 0, } } + fn with_approvals(mut self, n: u32) -> Standing { + self.approvals = n; + self + } + pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or_default() } @@ -103,10 +165,52 @@ pub fn branch_rules_url(repo: &str) -> String { format!("https://github.com/{repo}/settings/branches") } +/// GitHub's page where an organization's owner sets an app's repository +/// access. +pub fn app_access_url(repo: &str) -> String { + let owner = repo.split('/').next().unwrap_or(repo); + format!("https://github.com/organizations/{owner}/settings/installations") +} + +impl Standing { + /// The typed hand-off this standing waits on (#930's + /// `person_only::PersonOnly`): the repository's approval rule, the + /// team's auto-merge rule, or a repository CoderHelm can't write to. + /// `None` for everything CoderHelm does itself. A standing names a + /// person (`needs_person`) only when this is `Some` ([`decide`]). + pub fn person_only(&self) -> Option { + use crate::person_only::{admit, Grantor, Want}; + match self.code.as_str() { + "needs_person_approval" | "repo_requires_person_review" => admit( + Want::Approval, + &format!( + "{} from a person, required by the repository's rule", + approvals_words(self.approvals) + ), + ) + .ok(), + "auto_merge_off" => admit( + Want::Approval, + "a person on the team merges it: the team's rule turns auto-merge off", + ) + .ok(), + "plan_needs_access" => admit(Want::Grant(Grantor::OrgOwner), &self.text).ok(), + _ => None, + } + } +} + /// The standing of `repo`'s pull request, from the facts, first holder /// first. CoderHelm's own work (a review of the head, a fix round, checks) -/// never asks for a person; only the team's own rules do. +/// never asks for a person; only the team's own rules do, and only through +/// the typed hand-off ([`Standing::person_only`]). pub fn decide(repo: &str, f: &Facts) -> Standing { + let mut s = decide_raw(repo, f); + s.needs_person = s.needs_person && s.person_only().is_some(); + s +} + +fn decide_raw(repo: &str, f: &Facts) -> Standing { let none = String::new; if f.merged { return Standing::new( @@ -126,6 +230,24 @@ pub fn decide(repo: &str, f: &Facts) -> Standing { none(), ); } + // The run's own plan comes first: a repository it still owes is built + // before anything about this pull request is asked of anyone. + if !f.plan_owed.is_empty() { + return Standing::new( + "building_plan", + format!( + "The plan still has tasks in {}: CoderHelm is building them.", + f.plan_owed + .iter() + .map(|r| format!("`{r}`")) + .collect::>() + .join(" and ") + ), + "Its pull request opens linked to this one, with the order they merge in.", + false, + none(), + ); + } if f.conflict { return Standing::new( "conflict", @@ -170,15 +292,17 @@ pub fn decide(repo: &str, f: &Facts) -> Standing { none(), ) } else { + // CoderHelm's own review is CoderHelm's to answer: a + // fix round, or its review reading what its rounds + // settled. Never a person's wait. Standing::new( "review_changes_requested", format!( - "CoderHelm's review asks for changes on `{}`; what it could not fix \ - is listed as deferred on the pull request.", + "CoderHelm's review asks for changes on `{}`; CoderHelm takes them \ + in its next fix round.", short(sha) ), - "CoderHelm does not merge over its own review; the deferred findings \ - say what each needs.", + "The fix is pushed and its review reads the new head.", false, none(), ) @@ -219,6 +343,16 @@ pub fn decide(repo: &str, f: &Facts) -> Standing { none(), ); } + if let Some(p) = &f.plan_person { + return Standing::new( + "plan_needs_access", + format!("{}.", p.line().trim_end_matches('.')), + "Once it is granted, CoderHelm builds that part of the plan and links its pull \ + request to this one.", + true, + app_access_url(repo), + ); + } if !f.auto_merge { return Standing::new( "auto_merge_off", @@ -229,26 +363,43 @@ pub fn decide(repo: &str, f: &Facts) -> Standing { ); } if f.require_human_approval && !f.human_approved { + let n = f.approvals_required.max(1); return Standing::new( "needs_person_approval", - "This repo's auto-merge setting requires an approving review from a person before \ - CoderHelm merges." - .into(), + format!( + "This repo's rule requires {} from a person before CoderHelm merges.", + approvals_words(n) + ), "Once a person approves this commit, CoderHelm merges it and follows the deploy.", true, settings_path(repo), - ); + ) + .with_approvals(n); } if f.blocked_by_rules { - return Standing::new( - "repo_requires_person_review", - "Your repo's branch rules block the merge: they require an approving review from a \ - person (or another rule GitHub enforces on this branch)." - .into(), - "Once the branch's rules are met, CoderHelm merges it and follows the deploy.", - true, - branch_rules_url(repo), - ); + return if f.approvals_required > 0 { + Standing::new( + "repo_requires_person_review", + format!( + "Your repo's branch rules require {} from a person before the merge.", + approvals_words(f.approvals_required) + ), + "Once a person approves this commit, CoderHelm merges it and follows the deploy.", + true, + branch_rules_url(repo), + ) + .with_approvals(f.approvals_required) + } else { + Standing::new( + "repo_requires_person_review", + "Your repo's branch rules block the merge: they require an approving review from \ + a person (or another rule GitHub enforces on this branch)." + .into(), + "Once the branch's rules are met, CoderHelm merges it and follows the deploy.", + true, + branch_rules_url(repo), + ) + }; } Standing::new( "merging", @@ -313,7 +464,101 @@ mod tests { let s = decide("acme/shop", &f); assert_eq!(s.code, "review_changes_requested"); assert!(!s.needs_person); - assert!(s.text.contains("deferred")); + assert!(!s.text.contains("deferred") && !s.text.contains("could not")); + assert!(s.text.contains("next fix round"), "{}", s.text); + } + + #[test] + fn a_plan_that_still_owes_a_repo_is_built_before_anything_else() { + let mut f = clear(); + f.own_verdict = Some(("REQUEST_CHANGES".into(), HEAD.into())); + f.require_human_approval = true; + f.plan_owed = vec!["acme/bookstore-api".into()]; + let s = decide("acme/bookstore-infra", &f); + assert_eq!(s.code, "building_plan"); + assert!(!s.needs_person); + assert!(s.text.contains("`acme/bookstore-api`"), "{}", s.text); + assert_eq!(crate::rendered::person_text(&s.text), None); + } + + #[test] + fn a_repo_coderhelm_cannot_write_to_is_named_as_the_one_reason() { + let mut f = clear(); + f.plan_person = Some( + crate::person_only::admit( + crate::person_only::Want::Grant(crate::person_only::Grantor::OrgOwner), + "Grant the CoderHelm GitHub app write access to acme/bookstore-api", + ) + .unwrap(), + ); + let s = decide("acme/bookstore-infra", &f); + assert_eq!(s.code, "plan_needs_access"); + assert!(s.needs_person); + assert!(s.text.contains("acme/bookstore-api"), "{}", s.text); + assert_eq!( + s.link, + "https://github.com/organizations/acme/settings/installations" + ); + } + + /// The owner's rule: nothing says a person is needed without #930's + /// typed hand-off. + #[test] + fn a_person_is_named_only_through_the_typed_hand_off() { + let mut all = vec![clear()]; + for i in 0..9 { + let mut f = clear(); + match i { + 0 => f.auto_merge = false, + 1 => f.require_human_approval = true, + 2 => f.blocked_by_rules = true, + 3 => { + f.blocked_by_rules = true; + f.approvals_required = 2 + } + 4 => f.own_verdict = Some(("REQUEST_CHANGES".into(), HEAD.into())), + 5 => f.plan_owed = vec!["acme/bookstore-api".into()], + 6 => { + f.plan_person = crate::person_only::admit( + crate::person_only::Want::Grant(crate::person_only::Grantor::OrgOwner), + "Grant the CoderHelm GitHub app write access to acme/bookstore-api", + ) + .ok() + } + 7 => f.draft = true, + _ => f.checks_running = true, + } + all.push(f); + } + for f in all { + let s = decide("acme/bookstore-infra", &f); + assert_eq!(s.needs_person, s.person_only().is_some(), "{s:?}"); + } + } + + #[test] + fn the_required_approvals_are_counted_from_the_branch_rules() { + let rules = serde_json::json!([ + {"type": "required_status_checks", "parameters": {}}, + {"type": "pull_request", "parameters": {"required_approving_review_count": 1}} + ]); + let classic = serde_json::json!({"required_pull_request_reviews": {"required_approving_review_count": 2}}); + assert_eq!(approvals_required(Some(&rules), None), 1); + assert_eq!(approvals_required(Some(&rules), Some(&classic)), 2); + assert_eq!(approvals_required(None, None), 0); + let mut f = clear(); + f.require_human_approval = true; + f.approvals_required = 1; + let s = decide("acme/bookstore-infra", &f); + assert_eq!(s.approvals, 1); + assert!(s.text.contains("1 approval from a person"), "{}", s.text); + let mut g = clear(); + g.blocked_by_rules = true; + g.approvals_required = 2; + let s = decide("acme/bookstore-infra", &g); + assert_eq!(s.code, "repo_requires_person_review"); + assert_eq!(s.approvals, 2); + assert!(s.text.contains("2 approvals from a person"), "{}", s.text); } #[test] @@ -331,9 +576,12 @@ mod tests { let s = decide("acme/shop", &key); assert_eq!(s.code, "needs_person_approval"); assert!(s.needs_person); - assert!(s - .text - .contains("requires an approving review from a person")); + assert!( + s.text.contains("requires 1 approval from a person"), + "{}", + s.text + ); + assert_eq!(s.approvals, 1); key.human_approved = true; assert_eq!(decide("acme/shop", &key).code, "merging"); diff --git a/services/common/src/plan_repos.rs b/services/common/src/plan_repos.rs new file mode 100644 index 000000000..d0709fb12 --- /dev/null +++ b/services/common/src/plan_repos.rs @@ -0,0 +1,306 @@ +//! A run's plan, repository by repository: what each part of the plan +//! built, and what the run still owes. +//! +//! A ticket's plan spanned two repositories: an infrastructure repository +//! (the module for a scheduled function) and an API repository (the +//! function's code, its tests, a migration and its deploy workflow). The +//! run opened a pull request in the first and stopped the second with most +//! of its tasks still to do: the second repository's plan check said the +//! plan was unfinished, the multi-repository loop read that as "this +//! repository failed" and went on to the next, and the run finished with +//! one pull request. Its own review then asked for changes on the first +//! pull request that only the second repository's tasks would make, a fix +//! round spent hours on a branch where the fix could not live, and the run +//! ended "Done" while it said it was waiting on a person. +//! +//! [`PlanRepos`] is kept on the run record ([`FIELD`]): one [`Part`] per +//! repository of the plan, with its tasks, its pull request once open, and +//! the one reason a person is needed for it when CoderHelm can't write +//! there. [`PlanRepos::next`] is the only decision: a run whose plan still +//! owes a repository CoderHelm can write to builds it ([`Next::Build`]), +//! before it finishes, before a fix round and before any finding is +//! deferred; a repository CoderHelm can't write to is one typed hand-off +//! ([`PersonOnly`]); otherwise the plan is done. + +use serde::{Deserialize, Serialize}; + +use crate::person_only::{self, Grantor, PersonOnly, Want}; + +/// The run record's field holding the plan's repositories, as JSON. +pub const FIELD: &str = "plan_repos"; + +/// The run record's count of repositories the plan still owes +/// ([`PlanRepos::owed`]). Every done or waiting ending is written only +/// while it is absent or 0 (`run_ending::PLAN_GATE`). +pub const OWED_FIELD: &str = "plan_owed"; + +/// The tasks a task list holds, done and in all: `- [x]` and `- [ ]` lines. +pub fn count_tasks(md: &str) -> (u32, u32) { + md.lines().fold((0, 0), |(d, t), l| { + let l = l.trim_start(); + if l.starts_with("- [x]") || l.starts_with("- [X]") { + (d + 1, t + 1) + } else if l.starts_with("- [ ]") { + (d, t + 1) + } else { + (d, t) + } + }) +} + +/// One repository of the plan. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Part { + /// `owner/name`. + pub repo: String, + /// The plan's tasks for this repository. + #[serde(default)] + pub tasks: u32, + /// Those the branch did, as the plan check last counted. + #[serde(default)] + pub done: u32, + /// The pull request, once open; 0 before. + #[serde(default)] + pub pr: u64, + /// Why CoderHelm can't write here, named (the GitHub app's access, the + /// team's agent permissions); empty when it can. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub no_access: String, + /// Who grants that access. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub grantor: String, +} + +impl Part { + /// Whether the run still owes this repository's work: no pull request + /// yet, and no person-only reason keeps CoderHelm from writing there. + /// Words that name CoderHelm's own limit are no such reason: the + /// repository is still owed. + pub fn owed(&self) -> bool { + self.pr == 0 && self.person_only().is_none() + } + + /// The typed hand-off for a repository CoderHelm can't write to. `None` + /// when it can, or when the words name something CoderHelm owns (then + /// it is CoderHelm's to find a route for, never a person's). + pub fn person_only(&self) -> Option { + if self.no_access.trim().is_empty() || self.pr > 0 { + return None; + } + let by = match self.grantor.as_str() { + "org_owner" => Grantor::OrgOwner, + "team_admin" => Grantor::TeamAdmin, + _ => Grantor::RepoAdmin, + }; + person_only::admit(Want::Grant(by), &self.no_access).ok() + } +} + +/// What the run does next about its plan. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Next { + /// Every repository of the plan has its pull request. + Done, + /// These repositories still owe their tasks: the run builds them now. + Build(Vec), + /// The only thing left is a repository CoderHelm can't write to. + Person(PersonOnly), +} + +/// The plan's repositories, in the plan's order (the merge order). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PlanRepos { + /// The repository the plan was made and kept under (the ticket's); a + /// continuation of the run reads its plan there. + pub plan_repo: String, + pub parts: Vec, +} + +impl PlanRepos { + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option { + serde_json::from_str::(s) + .ok() + .filter(|p| !p.parts.is_empty()) + } + + /// The plan read from a task list with `## owner/name` sections, one + /// part per section in order; `None` for a single-repository plan. + pub fn of_tasks(plan_repo: &str, tasks_md: &str) -> Option { + let mut parts: Vec = Vec::new(); + for line in tasks_md.lines() { + if let Some(h) = line.strip_prefix("## ") { + let h = h.trim(); + if h.split_once('/').is_some_and(|(o, n)| { + !o.is_empty() && !n.is_empty() && !n.contains(' ') && !o.contains(' ') + }) { + parts.push(Part { + repo: h.to_string(), + ..Default::default() + }); + } + continue; + } + let Some(p) = parts.last_mut() else { continue }; + let (d, t) = count_tasks(line); + p.done += d; + p.tasks += t; + } + (parts.len() >= 2).then(|| PlanRepos { + plan_repo: plan_repo.to_string(), + parts, + }) + } + + /// The part for `repo`. + pub fn part_mut(&mut self, repo: &str) -> Option<&mut Part> { + self.parts + .iter_mut() + .find(|p| p.repo.eq_ignore_ascii_case(repo)) + } + + /// Records the pull requests the run has (`owner/name`, number). + pub fn with_prs<'a>(mut self, prs: impl IntoIterator) -> Self { + for (repo, n) in prs { + if let Some(p) = self.part_mut(repo) { + if n > 0 { + p.pr = n; + p.no_access.clear(); + } + } + } + self + } + + /// The repositories the run still owes, in the plan's order. + pub fn owed(&self) -> Vec { + self.parts + .iter() + .filter(|p| p.owed()) + .map(|p| p.repo.clone()) + .collect() + } + + /// What the run does next about its plan: build what it owes first; + /// a person only for a repository CoderHelm can't write to. + pub fn next(&self) -> Next { + let owed = self.owed(); + if !owed.is_empty() { + return Next::Build(owed); + } + match self.parts.iter().find_map(Part::person_only) { + Some(p) => Next::Person(p), + None => Next::Done, + } + } + + /// "part 1 of 2" for `repo`, by the plan's order. + pub fn part_label(&self, repo: &str) -> Option { + let i = self + .parts + .iter() + .position(|p| p.repo.eq_ignore_ascii_case(repo))?; + Some(format!("part {} of {}", i + 1, self.parts.len())) + } + + /// Tasks done and planned, across every repository ("8 of 29"). + pub fn counts(&self) -> (u32, u32) { + self.parts + .iter() + .fold((0, 0), |(d, t), p| (d + p.done.min(p.tasks), t + p.tasks)) + } + + /// One plain line for the run page while the run builds what it owes. + pub fn building_line(&self) -> Option { + let owed = self.owed(); + if owed.is_empty() { + return None; + } + let parts: Vec = owed + .iter() + .filter_map(|r| self.part_label(r).map(|l| format!("{r} ({l})"))) + .collect(); + Some(format!( + "CoderHelm is building the rest of the plan in {}; its pull request opens linked to the others.", + parts.join(" and ") + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TASKS: &str = "## acme/bookstore-infra\n\ + - [x] 1.1 Add the nightly stock sync module\n\ + - [x] 1.2 Schedule it at 02:00\n\ + ## acme/bookstore-api\n\ + - [x] 2.1 Write the sync handler\n\ + - [ ] 2.2 Test the handler\n\ + - [ ] 2.3 Add the migration\n\ + - [ ] 2.4 Deploy workflow for the function\n"; + + #[test] + fn a_two_repo_plan_owes_the_repo_without_a_pull_request() { + let p = PlanRepos::of_tasks("acme/bookstore-api", TASKS) + .unwrap() + .with_prs([("acme/bookstore-infra", 41)]); + assert_eq!(p.owed(), vec!["acme/bookstore-api".to_string()]); + assert_eq!(p.next(), Next::Build(vec!["acme/bookstore-api".into()])); + assert_eq!(p.counts(), (3, 6)); + assert_eq!( + p.part_label("acme/bookstore-api").as_deref(), + Some("part 2 of 2") + ); + let line = p.building_line().unwrap(); + assert!(line.contains("acme/bookstore-api (part 2 of 2)"), "{line}"); + assert_eq!(crate::rendered::person_text(&line), None, "{line}"); + let done = p.with_prs([("acme/bookstore-api", 12)]); + assert_eq!(done.next(), Next::Done); + assert_eq!(PlanRepos::from_json(&done.to_json()), Some(done)); + } + + #[test] + fn a_repo_coderhelm_cannot_write_to_is_the_one_person_only_reason() { + let mut p = PlanRepos::of_tasks("acme/bookstore-api", TASKS) + .unwrap() + .with_prs([("acme/bookstore-infra", 41)]); + let part = p.part_mut("acme/bookstore-api").unwrap(); + part.no_access = "Grant the CoderHelm GitHub app write access to acme/bookstore-api".into(); + part.grantor = "org_owner".into(); + match p.next() { + Next::Person(who) => { + assert_eq!(who.code(), "grant"); + assert!(who.line().contains("acme/bookstore-api"), "{}", who.line()); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn words_about_coderhelms_own_limits_never_become_a_persons() { + let mut p = PlanRepos::of_tasks("acme/bookstore-api", TASKS).unwrap(); + let part = p.part_mut("acme/bookstore-api").unwrap(); + part.no_access = "The step reached its time limit".into(); + // No person: never "waiting on a person" for CoderHelm's own time, + // and the repository is still the run's to build. + assert!(part.person_only().is_none()); + assert!(part.owed()); + assert_eq!( + p.next(), + Next::Build(vec![ + "acme/bookstore-infra".into(), + "acme/bookstore-api".into() + ]) + ); + } + + #[test] + fn a_single_repo_plan_is_none() { + assert!(PlanRepos::of_tasks("acme/web", "- [ ] 1.1 Fix the cart\n").is_none()); + assert!(PlanRepos::from_json("{\"plan_repo\":\"a/b\",\"parts\":[]}").is_none()); + } +} diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index 89185be41..6b00fa7a3 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -26,6 +26,11 @@ static DANGLING: LazyLock = LazyLock::new(|| { static PLACEHOLDER: LazyLock = LazyLock::new(|| Regex::new(r"\{[a-z_][a-z0-9_]*\}").expect("regex")); +/// A list item whose name rendered as nothing: an icon, then straight to +/// the dash ("- πŸ’¬ β€” An acceptance line"), or an empty bold label. +static EMPTY_NAME: LazyLock = + LazyLock::new(|| Regex::new(r"^[-*]\s+[^\w\s`]{1,3}\s+[—–]\s|\*\*\s*\*\*").expect("regex")); + /// Space before punctuation: a value that rendered as nothing. static SPACE_BEFORE_MARK: LazyLock = LazyLock::new(|| Regex::new(r"[^\s]\s+[,.;:!?)]").expect("regex")); @@ -79,6 +84,9 @@ pub fn empty_slot(text: &str) -> Option { if body.contains("``") { return Some(format!("an empty code span: {body}")); } + if EMPTY_NAME.is_match(body) { + return Some(format!("a name left empty: {body}")); + } if let Some(m) = PLACEHOLDER.find(body) { return Some(format!("a placeholder left in ({}): {body}", m.as_str())); } @@ -350,6 +358,26 @@ mod tests { } } + /// A review's "Additional findings" once listed a finding with no file + /// as "πŸ’¬ `` β€” An acceptance line…": the place rendered as nothing. + #[test] + fn a_finding_whose_place_or_name_rendered_as_nothing_is_caught() { + for bad in [ + "- πŸ’¬ `` β€” An acceptance line the change doesn't deliver", + "- πŸ›‘ β€” An acceptance line the change doesn't deliver", + "πŸ›‘ **** (correctness)", + ] { + assert!(person_text(bad).is_some(), "{bad}"); + } + for ok in [ + "- πŸ’¬ An acceptance line the change doesn't deliver", + "- πŸ›‘ `modules/stock_sync/main.tf:169` β€” An acceptance line the change doesn't deliver", + "- [x] 2.1 Write the sync handler β€” done", + ] { + assert_eq!(person_text(ok), None, "{ok}"); + } + } + #[test] fn clipping_never_cuts_a_word() { let title = "Show the gift wrap option on every order in the checkout summary"; diff --git a/services/common/src/run_ending.rs b/services/common/src/run_ending.rs index fe14b6288..9df3d77d4 100644 --- a/services/common/src/run_ending.rs +++ b/services/common/src/run_ending.rs @@ -310,8 +310,21 @@ pub struct Write { status: &'static str, sri: String, ending: Option, + /// A done or waiting ending: written only while the run's own plan owes + /// no repository ([`PLAN_GATE`]). + plan_gate: bool, } +/// The condition every done or waiting ending is written under: the run's +/// plan owes no repository CoderHelm can write to +/// (`plan_repos::OWED_FIELD`, kept on the run by the multi-repository +/// loop). A run whose plan still has tasks in such a repository can't be +/// written as done, waiting or handed off: the write is refused, the run +/// stays where it is, and the plan sweep builds what it owes +/// (`plan_continue`). A stop (an error, a person cancelling or closing it) +/// is not held. +pub const PLAN_GATE: &str = "(attribute_not_exists(#plan_owed) OR #plan_owed = :plan_owed_none)"; + impl Write { pub fn status(&self) -> &'static str { self.status @@ -332,6 +345,11 @@ impl Write { self.ending.as_ref() } + /// Whether the write is held to [`PLAN_GATE`]. + pub fn plan_gated(&self) -> bool { + self.plan_gate + } + /// Adds this write to an update built without a client: `status_value` /// (the status placeholder the expression names) and `:sri` are set, /// and the ending goes in the SET clause as `#run_ending = :run_ending`. @@ -538,6 +556,7 @@ pub fn gate(run_id: &str, end: &RunEnd) -> Write { status, sri: format!("{status}#{run_id}"), ending: Some(AttributeValue::M(m)), + plan_gate: matches!(end, RunEnd::Done(_) | RunEnd::Waiting(_)), } } @@ -547,6 +566,7 @@ pub fn working(w: Working, run_id: &str) -> Write { status: w.status(), sri: format!("{}#{run_id}", w.status()), ending: None, + plan_gate: false, } } @@ -560,6 +580,7 @@ pub fn restored(status: &str, run_id: &str) -> Option { status, sri: format!("{status}#{run_id}"), ending: None, + plan_gate: false, }) } @@ -649,9 +670,19 @@ pub trait EndWrite { impl EndWrite for UpdateItemFluentBuilder { fn run_status(self, status_value: &str, w: &Write) -> Self { - let b = self + let mut b = self .expression_attribute_values(status_value, w.status_attr()) .expression_attribute_values(":sri", w.sri_attr()); + if w.plan_gate { + let cond = match b.get_condition_expression().clone() { + Some(c) if !c.trim().is_empty() => format!("({c}) AND {PLAN_GATE}"), + _ => PLAN_GATE.to_string(), + }; + b = b + .condition_expression(cond) + .expression_attribute_names("#plan_owed", crate::plan_repos::OWED_FIELD) + .expression_attribute_values(":plan_owed_none", AttributeValue::N("0".into())); + } match &w.ending { Some(e) => { let expr = b.get_update_expression().clone().unwrap_or_default(); @@ -1103,6 +1134,114 @@ mod tests { } } + fn offline_update() -> UpdateItemFluentBuilder { + let conf = aws_sdk_dynamodb::Config::builder() + .behavior_version(aws_sdk_dynamodb::config::BehaviorVersion::latest()) + .region(aws_sdk_dynamodb::config::Region::new("us-east-1")) + .build(); + aws_sdk_dynamodb::Client::from_conf(conf) + .update_item() + .table_name("runs") + } + + /// The owner's rule: a run never ends done, waiting or handed off while + /// its own plan has tasks in a repository it can write to. Every such + /// ending goes through `run_status` (the walk above), and `run_status` + /// holds it to the plan gate, on top of any condition the caller had. + #[test] + fn no_done_or_waiting_ending_is_written_while_the_plan_owes_a_repo() { + let done = gate( + "R1", + &delivered( + st::COMPLETED, + 41, + "https://github.com/acme/bookstore-infra/pull/41", + ), + ); + let waiting = gate( + "R1", + &RunEnd::Waiting(Waiting { + on: WaitOn::Person { + who: "a repository admin".into(), + action: "approve pull request #41".into(), + }, + evidence: "the branch rule requires 1 approval from a person".into(), + }), + ); + for w in [&done, &waiting] { + assert!(w.plan_gated()); + let b = offline_update() + .update_expression("SET #s = :s, status_run_id = :sri") + .condition_expression("#s = :was") + .run_status(":s", w); + let cond = b.get_condition_expression().clone().unwrap_or_default(); + assert_eq!(cond, format!("(#s = :was) AND {PLAN_GATE}")); + assert_eq!( + b.get_expression_attribute_names() + .as_ref() + .and_then(|n| n.get("#plan_owed")) + .map(String::as_str), + Some(crate::plan_repos::OWED_FIELD) + ); + let alone = offline_update() + .update_expression("SET #s = :s") + .run_status(":s", w); + assert_eq!(alone.get_condition_expression().as_deref(), Some(PLAN_GATE)); + } + // A stop is never held by the plan: an error or a person's cancel + // is written as it is. + let stopped = gate( + "R1", + &RunEnd::Stopped(Stopped { + reason: Stop::CancelledBy { who: "dana".into() }, + tried: Tried::default(), + }), + ); + assert!(!stopped.plan_gated()); + assert!(!working(Working::Running, "R1").plan_gated()); + } + + /// The only ending writes that don't take `run_status` (and so the plan + /// gate) are these: a stop written into a hand-built expression, and a + /// new job record that has no plan. A new caller fails here until it is + /// read and either moved onto `run_status` or added with its reason. + #[test] + fn every_ending_path_outside_run_status_is_known() { + const KNOWN: &[(&str, &str)] = &[ + ("common/src/run_fail.rs", "a failed run: a stop"), + ( + "gateway/src/routes/run_close.rs", + "a person closing the run: a stop", + ), + ( + "common/src/plugins/run.rs", + "a new plugin job record: no plan", + ), + ( + "worker/src/passes/skill_schedule.rs", + "a new scheduled job record: no plan", + ), + ]; + let mut bad = Vec::new(); + for (path, text) in sources() { + let code = non_test(&text); + let uses = code.contains(".add_to(") + || code.contains("item_fields(") + || code.contains("EndPut"); + if !uses { + continue; + } + let p = path.to_string_lossy().replace('\\', "/"); + if !KNOWN.iter().any(|(k, _)| p.ends_with(k)) { + bad.push(p); + } + } + assert!( + bad.is_empty(), + "an ending written outside run_status (no plan gate): {bad:?}" + ); + } + /// `.run_status(` is this module's: no other type may take the name and /// so slip a write past the walk above. #[test] diff --git a/services/common/src/stub_check.rs b/services/common/src/stub_check.rs new file mode 100644 index 000000000..43f798943 --- /dev/null +++ b/services/common/src/stub_check.rs @@ -0,0 +1,311 @@ +//! A pull request never ships a placeholder in place of what its ticket +//! asks for. +//! +//! A run's plan put a scheduled function's module in an infrastructure +//! repository and the function's code in an API repository. Only the +//! first pull request was opened, and its function was a placeholder file +//! (`modules//placeholder/index.js`): the change looked complete in +//! the repository it was in, and the real code was nowhere. +//! +//! [`stubs`] reads a pull request's diff (each changed file and its patch) +//! and names every place that stands in for real code: a file under a +//! `placeholder` or `stub` folder or named so, an added handler whose body +//! is empty, `throw new Error("not implemented")` and its kin in other +//! languages, and a `TODO` that says the implementation is still to come. +//! Tests, fixtures, mocks and documents are not read: a stub there is the +//! test's own. The ready decision (`ready::decide`) never offers a pull +//! request for review while this finds anything; CoderHelm's coder replaces +//! each one, or, when the real code belongs to another repository of the +//! same plan, that repository is built first and the pull requests are +//! linked. + +use std::sync::LazyLock; + +use regex::Regex; + +/// One place that stands in for real code. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stub { + pub path: String, + /// The head line, when the patch shows it; 0 for the whole file. + pub line: u64, + /// What it is, in plain words. + pub what: String, +} + +impl Stub { + /// One line for the pull request and the coder. + pub fn line(&self) -> String { + let at = if self.line > 0 { + format!("`{}:{}`", self.path, self.line) + } else { + format!("`{}`", self.path) + }; + format!( + "{at} ships {} in place of the code the ticket needs", + self.what + ) + } +} + +static NOT_IMPLEMENTED: LazyLock = LazyLock::new(|| { + Regex::new( + r#"(?i)(throw\s+new\s+\w*Error\(\s*["'`][^"'`]*not\s+(yet\s+)?implemented|unimplemented!\(|todo!\(|raise\s+NotImplementedError|panic\(\s*"[^"]*not\s+implemented)"#, + ) + .expect("regex") +}); + +static TODO_IMPL: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)(//|#|/\*|\*|--)\s*(todo|fixme)\b[^\n]*\b(implement|real (code|handler|logic)|replace (this|the placeholder|the stub))", + ) + .expect("regex") +}); + +static PLACEHOLDER_COMMENT: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)(//|#|/\*|\*|--)\s*(placeholder|stub)\b[^\n]*\b(code|handler|implementation|lambda|function|until|for now|replaced)", + ) + .expect("regex") +}); + +static EMPTY_HANDLER: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)(handler\s*[:=]\s*(async\s*)?(\([^)]*\)|\w+)\s*=>\s*\{\s*\}|function\s+handler\s*\([^)]*\)\s*\{\s*\}|handler\s*[:=]\s*(async\s+)?function\s*\([^)]*\)\s*\{\s*\})", + ) + .expect("regex") +}); + +static PY_HANDLER: LazyLock = + LazyLock::new(|| Regex::new(r"^\s*(async\s+)?def\s+\w*handler\w*\s*\(").expect("regex")); + +/// A path a stub belongs in: tests, fixtures, mocks, documents. +fn not_read(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + let segs: Vec<&str> = p.split('/').collect(); + let name = segs.last().copied().unwrap_or(""); + segs.iter().any(|s| { + matches!( + *s, + "test" + | "tests" + | "__tests__" + | "spec" + | "specs" + | "fixtures" + | "__mocks__" + | "mocks" + | "testdata" + | "e2e" + | "docs" + ) + }) || name.contains(".test.") + || name.contains(".spec.") + || name.contains("_test.") + || name.starts_with("test_") + || [".md", ".mdx", ".txt", ".rst", ".snap"] + .iter() + .any(|x| name.ends_with(x)) +} + +/// A file that is itself a placeholder: under a `placeholder` or `stub` +/// folder, or named so. +fn placeholder_path(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + let segs: Vec<&str> = p.split('/').collect(); + let (dirs, name) = segs.split_at(segs.len().saturating_sub(1)); + let stem = name + .first() + .map(|n| n.split('.').next().unwrap_or(n)) + .unwrap_or(""); + dirs.iter() + .any(|d| matches!(*d, "placeholder" | "placeholders" | "stub" | "stubs")) + || matches!(stem, "placeholder" | "stub") +} + +/// Every place in the diff (`(path, patch)` per changed file) that stands +/// in for real code. See the module comment. +pub fn stubs(files: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, patch) in files { + if not_read(path) { + continue; + } + if placeholder_path(path) { + out.push(Stub { + path: path.clone(), + line: 0, + what: "a placeholder file".into(), + }); + continue; + } + let mut line = 0u64; + let mut py_handler_at: Option = None; + for l in patch.lines() { + if let Some(h) = l.strip_prefix("@@") { + line = h + .split('+') + .nth(1) + .and_then(|p| p.trim().split([',', ' ']).next()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + py_handler_at = None; + continue; + } + let (added, text) = match l.chars().next() { + Some('+') if !l.starts_with("+++") => (true, &l[1..]), + Some('-') | Some('\\') => continue, + _ => (false, l.get(1..).unwrap_or("")), + }; + let here = line; + line += 1; + if !added { + py_handler_at = None; + continue; + } + let what = if NOT_IMPLEMENTED.is_match(text) { + Some("a \"not implemented\" error") + } else if EMPTY_HANDLER.is_match(text) { + Some("an empty handler") + } else if TODO_IMPL.is_match(text) { + Some("a TODO where the implementation goes") + } else if PLACEHOLDER_COMMENT.is_match(text) { + Some("placeholder code") + } else { + None + }; + if let Some(what) = what { + out.push(Stub { + path: path.clone(), + line: here, + what: what.into(), + }); + py_handler_at = None; + continue; + } + let t = text.trim(); + if PY_HANDLER.is_match(text) { + py_handler_at = Some(here); + continue; + } + if let Some(at) = py_handler_at { + if t.is_empty() || t.starts_with('#') || t.starts_with("\"\"\"") { + continue; + } + if matches!(t, "pass" | "..." | "return" | "return None") { + out.push(Stub { + path: path.clone(), + line: at, + what: "an empty handler".into(), + }); + } + py_handler_at = None; + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f(path: &str, added: &[&str]) -> (String, String) { + let mut patch = format!("@@ -0,0 +1,{} @@\n", added.len()); + for a in added { + patch.push('+'); + patch.push_str(a); + patch.push('\n'); + } + (path.to_string(), patch) + } + + #[test] + fn a_placeholder_file_is_found() { + let s = stubs(&[f( + "modules/stock_sync/placeholder/index.js", + &["exports.handler = async () => ({ statusCode: 200 });"], + )]); + assert_eq!(s.len(), 1); + assert_eq!(s[0].line, 0); + assert!(s[0].line().contains("placeholder file"), "{}", s[0].line()); + assert_eq!(crate::rendered::person_text(&s[0].line()), None); + } + + #[test] + fn stand_ins_for_code_are_found_in_each_language() { + for (path, lines) in [ + ( + "src/sync.ts", + vec![ + "export async function run() {", + " throw new Error(\"Not implemented\");", + "}", + ], + ), + ("src/sync.rs", vec!["pub fn run() {", " todo!()", "}"]), + ( + "src/sync.py", + vec!["def run():", " raise NotImplementedError"], + ), + ( + "lambda/index.js", + vec!["exports.handler = async (event) => {}"], + ), + ( + "lambda/index.ts", + vec!["export const handler = async (event: Event) => {};"], + ), + ( + "lambda/handler.py", + vec!["def lambda_handler(event, context):", " pass"], + ), + ( + "src/stock.go", + vec!["// TODO: implement the nightly stock sync"], + ), + ( + "src/stock.js", + vec!["// placeholder handler until the api repo ships"], + ), + ] { + let s = stubs(&[f(path, &lines)]); + assert_eq!(s.len(), 1, "{path}: {s:?}"); + assert!(s[0].line > 0, "{path}"); + } + } + + #[test] + fn real_code_tests_and_form_placeholders_pass() { + let s = stubs(&[ + f( + "lambda/index.js", + &[ + "exports.handler = async (event) => {", + " const rows = await syncStock(event.date);", + " return { synced: rows.length };", + "};", + ], + ), + f( + "lambda/handler.py", + &["def handler(event, context):", " return sync(event)"], + ), + f( + "src/Search.tsx", + &[""], + ), + f("src/styles.css", &["input::placeholder { color: gray; }"]), + f( + "tests/sync.test.js", + &["throw new Error('not implemented')"], + ), + f( + "src/__mocks__/client.ts", + &["export const handler = async () => {};"], + ), + f("docs/sync.md", &["TODO: implement the retries section"]), + ]); + assert!(s.is_empty(), "{s:?}"); + } +} diff --git a/services/common/src/waiting_line.rs b/services/common/src/waiting_line.rs index bd5b49454..5a68beb93 100644 --- a/services/common/src/waiting_line.rs +++ b/services/common/src/waiting_line.rs @@ -10,7 +10,7 @@ //! and the description say the same thing. use crate::draft_hold::{DraftHold, Kind}; -use crate::merge_standing::Standing; +use crate::merge_standing::{approvals_words, Standing}; use crate::preview::{Stage, State as Preview}; /// What [`line`] reads. @@ -46,6 +46,12 @@ fn clause(s: &str) -> String { /// What the pull request waits on, as "Waiting on: …." (or what happened /// to it), from the draft hold first (it holds the pull request before /// anything about merging), then the merge standing. +/// +/// A person is named only from the one state that says a person must act +/// (`DraftHold::needs_person`, `Standing::needs_person`), so this line and +/// the run page's "Needs a person" / "Nothing needed from you" can never +/// disagree: the line names a person exactly when that state does +/// ([`names_a_person`]). fn waiting(i: &Inputs) -> Option { let n = pr(i.pr); if let Some(h) = i.hold { @@ -58,7 +64,13 @@ fn waiting(i: &Inputs) -> Option { Kind::Waiting => format!( "Waiting on: {what} on {n} (CoderHelm checks again by itself and marks it ready)." ), - Kind::Held => format!("Waiting on: a person, {n} stays a draft because {what}."), + Kind::Held if h.needs_person() => { + format!("Waiting on: a person, {n} stays a draft because {what}.") + } + // A hold with no person-only reason is CoderHelm's to settle. + Kind::Held => format!( + "Waiting on: CoderHelm, {n} stays a draft until it settles this: {what} (it checks again by itself)." + ), // GitHub refusing is CoderHelm's to try again, never a person's // wait (`DraftHold::needs_person`). Kind::Failed => format!( @@ -68,20 +80,18 @@ fn waiting(i: &Inputs) -> Option { }); } let s = i.standing?; + // A person only through the typed hand-off (#930). + if s.needs_person && s.person_only().is_some() { + return Some(person_line(s, &n)); + } Some(match s.code.as_str() { - "needs_person_approval" => format!( - "Waiting on: an approving review from a person on {n} (this repo requires one before CoderHelm merges)." - ), - "auto_merge_off" => format!( - "Waiting on: a person on your team to merge {n} (auto-merge is off for this repo)." - ), - "repo_requires_person_review" => format!( - "Waiting on: the branch rules on {n} (they require an approving review from a person, or another rule GitHub enforces)." + "building_plan" => format!( + "Waiting on: CoderHelm building the rest of the plan (its pull request opens linked to {n})." ), "reviewing" => format!("Waiting on: CoderHelm's review of the head of {n}."), "fixing_review" => format!("Waiting on: CoderHelm's fix round for its review of {n}."), "review_changes_requested" => format!( - "Waiting on: a person, CoderHelm's review asks for changes on {n} it could not make (listed on the pull request)." + "Waiting on: CoderHelm's next fix round for the changes its review asked for on {n}." ), "checks_running" => format!("Waiting on: the checks still running on {n}."), "checks_failing" => format!("Waiting on: CoderHelm's fix for the failing checks on {n}."), @@ -90,10 +100,42 @@ fn waiting(i: &Inputs) -> Option { "merging" => format!("Nothing: {n} is approved and CoderHelm merges it."), "merged" => format!("Nothing: {n} is merged; CoderHelm watches the deploy."), "closed" => format!("Nothing: {n} was closed without merging."), - _ => format!("Waiting on: {}", clause(&s.text)) + ".", + _ => format!("Waiting on: CoderHelm, {}.", clause(&s.text)), }) } +/// The line for a standing a person must act on: exactly the rule, and +/// nothing else. "Needs 1 approval from a person (repo rule) on #42." +fn person_line(s: &Standing, n: &str) -> String { + match s.code.as_str() { + "needs_person_approval" => format!( + "Needs {} from a person (repo rule) on {n}.", + approvals_words(s.approvals) + ), + "repo_requires_person_review" if s.approvals > 0 => format!( + "Needs {} from a person (repo rule) on {n}.", + approvals_words(s.approvals) + ), + "repo_requires_person_review" => format!( + "Needs a person: the branch rules on {n} require an approving review from a person, or another rule GitHub enforces (repo rule)." + ), + "auto_merge_off" => { + format!("Needs a person on your team to merge {n} (auto-merge is off for this repo).") + } + _ => format!( + "Needs a person on {n}. {}.", + s.text.trim().trim_end_matches('.') + ), + } +} + +/// Whether `line` names a person as the one who must act. The run page +/// shows "Needs a person" exactly when this is true of its line. +pub fn names_a_person(line: &str) -> bool { + let l = line.to_lowercase(); + l.starts_with("needs ") || l.contains("waiting on: a person") +} + /// Whether the pull request is ready for review, and on what: its checks, /// and its preview when the change has one. None while it is a draft, done /// or not yet checked. @@ -190,7 +232,7 @@ mod tests { }); assert_eq!( l, - "Waiting on: an approving review from a person on #42 (this repo requires one before CoderHelm merges). Ready for review: checks passed, preview checked." + "Needs 1 approval from a person (repo rule) on #42. Ready for review: checks passed, preview checked." ); } @@ -260,6 +302,131 @@ mod tests { ); } + /// Every standing and hold: the line names a person exactly when the + /// state the run page's "Needs a person" reads says so, and never says + /// a person and "nothing needed" at once. + #[test] + fn the_line_and_the_needs_a_person_badge_come_from_one_state() { + use crate::draft_hold::Reason; + let head = "abc1234def"; + let base = Facts { + head: head.into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), head.into())), + auto_merge: true, + ..Default::default() + }; + let mut all = vec![base.clone()]; + for k in 0..12 { + let mut f = base.clone(); + match k { + 0 => f.own_verdict = Some(("REQUEST_CHANGES".into(), head.into())), + 1 => { + f.own_verdict = Some(("REQUEST_CHANGES".into(), head.into())); + f.working = true + } + 2 => f.require_human_approval = true, + 3 => f.blocked_by_rules = true, + 4 => { + f.blocked_by_rules = true; + f.approvals_required = 1 + } + 5 => f.auto_merge = false, + 6 => f.plan_owed = vec!["acme/bookstore-api".into()], + 7 => { + f.plan_person = crate::person_only::admit( + crate::person_only::Want::Grant(crate::person_only::Grantor::OrgOwner), + "Grant the CoderHelm GitHub app write access to acme/bookstore-api", + ) + .ok() + } + 8 => f.conflict = true, + 9 => f.failing = vec!["unit".into()], + 10 => f.merged = true, + _ => f.own_verdict = None, + } + all.push(f); + } + for f in &all { + let s = decide("acme/bookstore-infra", f); + let l = line(&Inputs { + pr: 41, + standing: Some(&s), + checks_passed: true, + ..Default::default() + }); + assert_eq!(names_a_person(&l), s.needs_person, "{}: {l}", s.code); + assert!( + !(l.to_lowercase().contains("a person") && !s.needs_person), + "{}: {l}", + s.code + ); + assert_eq!(crate::rendered::person_text(&l), None, "{}: {l}", s.code); + } + // A held draft names a person only for a person-only reason. + let own = DraftHold::new( + Kind::Held, + vec![Reason::new("The security audit didn't run", "")], + 41, + "", + ) + .unwrap(); + let l = line(&Inputs { + pr: 41, + hold: Some(&own), + ..Default::default() + }); + assert_eq!(names_a_person(&l), own.needs_person(), "{l}"); + assert!(!names_a_person(&l), "{l}"); + } + + #[test] + fn a_repo_rule_approval_reads_exactly_that() { + let s = decide( + "acme/bookstore-infra", + &Facts { + head: "abc1234def".into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), "abc1234def".into())), + auto_merge: true, + blocked_by_rules: true, + approvals_required: 1, + ..Default::default() + }, + ); + let l = line(&Inputs { + pr: 41, + standing: Some(&s), + ..Default::default() + }); + assert_eq!(l, "Needs 1 approval from a person (repo rule) on #41."); + } + + #[test] + fn own_review_changes_never_read_as_a_persons_wait() { + let s = decide( + "acme/bookstore-infra", + &Facts { + head: "abc1234def".into(), + reviewer_on: true, + own_verdict: Some(("REQUEST_CHANGES".into(), "abc1234def".into())), + auto_merge: true, + require_human_approval: true, + ..Default::default() + }, + ); + let l = line(&Inputs { + pr: 41, + standing: Some(&s), + ..Default::default() + }); + assert!( + !l.contains("a person") && !l.contains("could not make"), + "{l}" + ); + assert!(l.starts_with("Waiting on: CoderHelm"), "{l}"); + } + #[test] fn nothing_known_says_nothing() { assert_eq!(line(&Inputs::default()), ""); diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index d9bbb7aa3..8a261077a 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1057,6 +1057,10 @@ pub struct RunDraftHold { /// When it was first held for these reasons (RFC 3339). #[schema(example = "2026-11-06T22:17:25Z")] pub since: Option, + /// A person must act: a reason only a person has (a typed hand-off). + /// False for every hold CoderHelm settles itself. + #[schema(example = true)] + pub needs_person: bool, } /// One reason a pull request stays a draft. @@ -1091,6 +1095,7 @@ pub(crate) fn draft_hold_of(item: &run_search::Item) -> Option { }) .collect(), pr_number: h.pr_number, + needs_person: h.needs_person(), since: Some(h.since).filter(|s| !s.is_empty()), }) } @@ -1101,7 +1106,8 @@ pub struct RunMergeStanding { /// Stable code: `merged`, `closed`, `reviewing`, `fixing_review`, /// `review_changes_requested`, `checks_running`, `checks_failing`, /// `conflict`, `draft`, `auto_merge_off`, `needs_person_approval`, - /// `repo_requires_person_review` or `merging`. + /// `repo_requires_person_review`, `building_plan`, `plan_needs_access` + /// or `merging`. #[schema(example = "auto_merge_off")] pub code: String, /// What is true now, one sentence. @@ -1121,6 +1127,11 @@ pub struct RunMergeStanding { /// or a GitHub URL. Null otherwise. #[schema(example = "/reviewer/config")] pub link: Option, + /// Approving reviews from people the repository's rule requires + /// (`needs_person_approval`, `repo_requires_person_review`). Null when + /// not known. + #[schema(example = 1)] + pub approvals: Option, } /// One preview or end-to-end check on the head of the run's pull request. @@ -1255,6 +1266,7 @@ pub(crate) fn merge_standing_of(item: &run_search::Item) -> Option 0), }) } diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 006b586ff..5411ed69e 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -1917,16 +1917,17 @@ pub(crate) fn base_merge_line(base: &str, outcome: &BaseMerge) -> (Mark, String) BaseMerge::Unresolved { files } if !files.is_empty() => ( Mark::Blocked, format!( - "Merge conflict with `{base}` that needs a person's call: {}. Nothing was pushed; \ - the review of the commit that resolves it starts auto-merge again", + "Merge conflict with `{base}` in {} that the automatic merge couldn't settle. \ + Nothing was pushed; the review of the commit that resolves it starts auto-merge \ + again", code_list(files) ), ), BaseMerge::Unresolved { .. } => ( Mark::Blocked, format!( - "Merge conflict with `{base}` that needs a person's call. Nothing was pushed; \ - the review of the commit that resolves it starts auto-merge again" + "Merge conflict with `{base}` that the automatic merge couldn't settle. Nothing \ + was pushed; the review of the commit that resolves it starts auto-merge again" ), ), BaseMerge::CannotPush => ( diff --git a/services/worker/src/passes/completeness.rs b/services/worker/src/passes/completeness.rs index 5bc3e6ceb..c06a079d1 100644 --- a/services/worker/src/passes/completeness.rs +++ b/services/worker/src/passes/completeness.rs @@ -541,10 +541,21 @@ pub fn merge_order_section(prs: &[Sibling], this: usize) -> String { return String::new(); } let (start, end) = Section::MergeOrder.markers(); - let mut out = format!("{start}\n## Merge order\n"); + let mut out = format!( + "{start}\n## Merge order\nThis pull request is part {} of {} of the ticket's change; merge them in this order.\n", + this + 1, + prs.len() + ); for (i, p) in prs.iter().enumerate() { let me = if i == this { " (this PR)" } else { "" }; - out.push_str(&format!("{}. {}#{}{me}\n", i + 1, p.repo, p.number)); + out.push_str(&format!( + "{}. {}#{} (part {} of {}){me}\n", + i + 1, + p.repo, + p.number, + i + 1, + prs.len() + )); } out.push_str(end); out @@ -1181,9 +1192,14 @@ mod tests { }, ]; let first = merge_order_section(&prs, 0); - assert!(first.contains("## Merge order\n1. acme/infra#12 (this PR)\n2. acme/pipeline#34\n")); + assert!(first.contains("## Merge order\nThis pull request is part 1 of 2 of the ticket's change; merge them in this order.\n1. acme/infra#12 (part 1 of 2) (this PR)\n2. acme/pipeline#34 (part 2 of 2)\n"), "{first}"); let second = merge_order_section(&prs, 1); - assert!(second.contains("1. acme/infra#12\n2. acme/pipeline#34 (this PR)\n")); + assert!( + second.contains( + "1. acme/infra#12 (part 1 of 2)\n2. acme/pipeline#34 (part 2 of 2) (this PR)\n" + ), + "{second}" + ); assert_eq!(merge_order_section(&prs[..1], 0), ""); // Set into a description that has one already: replaced, in place. @@ -1196,7 +1212,7 @@ mod tests { let again = assemble(&rest, &owned); assert_eq!(again.matches("## Merge order").count(), 1); assert!(again.contains("(this PR)\n")); - assert!(again.contains("acme/pipeline#34 (this PR)")); + assert!(again.contains("acme/pipeline#34 (part 2 of 2) (this PR)")); } #[test] diff --git a/services/worker/src/passes/incidents/ae_budget_rounds.rs b/services/worker/src/passes/incidents/ae_budget_rounds.rs index 2f0a33775..1cc909ae1 100644 --- a/services/worker/src/passes/incidents/ae_budget_rounds.rs +++ b/services/worker/src/passes/incidents/ae_budget_rounds.rs @@ -231,7 +231,9 @@ fn self_review_rounds_without_progress_defer_the_findings_and_finish() { assert!(now.contains("## Deferred\n- Retry loop never backs off")); assert!(now.contains(why.as_str())); let note = review_pr::self_review_end_note(&open, why); - assert!(note.contains("deferred"), "{note}"); + // Still open and CoderHelm's to finish: never "deferred" (xj). + assert!(!note.contains("deferred"), "{note}"); + assert!(note.contains("still CoderHelm's to finish"), "{note}"); assert!(note.contains("- Cursor skips tied rows"), "{note}"); assert!(!ownership::hands_back_without_reason(¬e), "{note}"); assert!(!note.contains(OLD_CI), "{note}"); @@ -265,7 +267,9 @@ fn neither_loop_ends_by_waiting_on_a_comment() { let pr = include_str!("../review_pr.rs"); assert!(pr.contains("SelfRound::End(why) => {")); let ended = fn_src(pr, "\nasync fn end_self_review_rounds("); - assert!(ended.contains("own_review::defer_findings(")); + // Never deferred: CoderHelm's own limit, alerted (xj). + assert!(!ended.contains("own_review::defer_findings(")); + assert!(ended.contains("alert_own_limit(")); assert!(ended.contains("ready::request(")); // The ready decision defers a finished run's findings once its rounds // are over, instead of holding them for a person. diff --git a/services/worker/src/passes/incidents/ba_verdict_on_old_commit.rs b/services/worker/src/passes/incidents/ba_verdict_on_old_commit.rs index 1418be310..01e41ccaf 100644 --- a/services/worker/src/passes/incidents/ba_verdict_on_old_commit.rs +++ b/services/worker/src/passes/incidents/ba_verdict_on_old_commit.rs @@ -118,9 +118,7 @@ fn the_page_names_the_one_true_reason_and_asks_a_person_only_for_the_teams_rule( }, ); assert_eq!(key.code, "needs_person_approval"); - assert!(key - .text - .contains("requires an approving review from a person")); + assert!(key.text.contains("requires 1 approval from a person")); // The repository's own branch rules: said as that, with GitHub's page. let rules = merge_standing::decide( &repo, diff --git a/services/worker/src/passes/incidents/bt_proof_answer_closes.rs b/services/worker/src/passes/incidents/bt_proof_answer_closes.rs index fdfc6cbf6..1dd50d803 100644 --- a/services/worker/src/passes/incidents/bt_proof_answer_closes.rs +++ b/services/worker/src/passes/incidents/bt_proof_answer_closes.rs @@ -206,10 +206,11 @@ fn what_is_left_after_every_approach_is_a_note_on_a_ready_pull_request() { let Plan::Unfixed { why } = l.decide(&open, 0.0, 200.0) else { panic!("every approach taken"); }; - // CoderHelm's limit: its note, never a hold on the run. + // CoderHelm's limit: never "completed" over it and never deferred; the + // run stops naming what its review asks (never a person's wait). assert!(matches!( ledger::completion(Some(("REQUEST_CHANGES", HEAD)), HEAD, &l), - Completion::Defer(_) + Completion::Hold(_) )); l.note(&open, &why); let Plan::Settle { @@ -254,11 +255,13 @@ fn what_is_left_after_every_approach_is_a_note_on_a_ready_pull_request() { }, ); assert!(!findings[0].holds_merge()); - // A completion on that verdict completes: nothing more to do. - assert_eq!( + // A "changes requested" verdict on the head never completes over + // CoderHelm's own notes (only a typed person-only reason defers; xj): + // the review reads the head again with them settled. + assert!(matches!( ledger::completion(Some(("REQUEST_CHANGES", HEAD)), HEAD, &l), - Completion::Complete - ); + Completion::Hold(_) + )); // The pull request: the open-findings section goes, the note is listed, // and the ready decision marks it ready. let body = format!( @@ -326,7 +329,9 @@ fn no_coderhelm_limit_holds_the_draft_for_a_person() { let ready_src = include_str!("../ready.rs"); let fix = fn_src(ready_src, "\nasync fn fix_own_findings("); assert!(fix.contains("OwnRound::Later(why)") && fix.contains("f.own_fixing = true")); - // The in-run ending for findings left after every approach lists them - // and finishes, never waiting on a person. - assert!(resume.contains("note_own_findings(state, &msg.team_id, &msg.run_id, &own_open, &why)")); + // The in-run ending for findings left after every approach is + // CoderHelm's own limit through the supervisor's ending: never deferred, + // never a person's wait (xj). + assert!(resume.contains("end_on_own_limit(")); + assert!(!resume.contains("note_own_findings(")); } diff --git a/services/worker/src/passes/incidents/bu_web_change_unchecked.rs b/services/worker/src/passes/incidents/bu_web_change_unchecked.rs index 95e0d8402..471bef290 100644 --- a/services/worker/src/passes/incidents/bu_web_change_unchecked.rs +++ b/services/worker/src/passes/incidents/bu_web_change_unchecked.rs @@ -267,7 +267,7 @@ fn the_run_page_says_what_it_waits_on_in_one_line() { }); assert_eq!( line, - "Waiting on: an approving review from a person on #42 (this repo requires one before CoderHelm merges). Ready for review: checks passed, preview checked." + "Needs 1 approval from a person (repo rule) on #42. Ready for review: checks passed, preview checked." ); } diff --git a/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs b/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs new file mode 100644 index 000000000..9f582c76e --- /dev/null +++ b/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs @@ -0,0 +1,469 @@ +//! xj. The acme bookstore's ticket for a nightly stock sync planned two +//! repositories: `acme/bookstore-infra` (the scheduled function's module) +//! and `acme/bookstore-api` (the function's code, its tests, a migration +//! and its deploy workflow). The run opened a pull request in the infra +//! repository only, whose function was a placeholder file; the API +//! repository's plan check said "unfinished" and the multi-repository loop +//! read that as a failed repository and went on. CoderHelm's own review +//! asked for changes on the infra pull request twice (an acceptance line +//! the change doesn't deliver), a fix round worked for hours on a branch +//! where the fix couldn't live, listed the findings as deferred, and the +//! run ended "Done" while its page said both "Waiting on: a person" and +//! "Nothing needed from you". The review's additional findings rendered as +//! "πŸ’¬ `` β€” An acceptance line…". +//! +//! The invariants, in code: +//! +//! 1. A run never ends done, waiting or handed off while its own plan has +//! tasks in a repository it can write to: every such ending is written +//! under `run_ending::PLAN_GATE` (the run's `plan_owed` count is 0), and +//! a source scan refuses an ending path outside that gate. +//! 2. A pull request is never offered for review while it ships a +//! placeholder in place of what the ticket needs, or while another part +//! of the plan is unbuilt (`common::stub_check`, `ready::offer_blocked`). +//! 3. Only a typed person-only reason defers a finding +//! (`own_review_ledger::typed_settle`); the rest of the plan comes first. +//! 4. Nothing says a person is needed without #930's typed hand-off +//! (`PersonOnly`): the standing, the draft hold and the page's line read +//! it, and a source scan refuses a new untyped claim. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::merge_standing::{decide, Facts as StandingFacts}; +use common::plan_repos::{Next, PlanRepos}; +use common::waiting_line::{line, names_a_person, Inputs}; + +use super::fixture::fn_src; +use crate::passes::own_review_ledger::{typed_settle, Ledger, Settled, Track}; +use crate::passes::ready::{self, Ci, Decision, Facts}; + +const INFRA: &str = "acme/bookstore-infra"; +const API: &str = "acme/bookstore-api"; +const HEAD: &str = "5b1c9e0d2a7f4e3b8c6d1a0f9e8d7c6b5a4f3e2d"; + +/// The plan the run wrote: four infra tasks done, and the API's 25 with +/// four done. +fn tasks() -> String { + let mut t = format!("## {INFRA}\n"); + for i in 1..=4 { + t.push_str(&format!("- [x] 1.{i} Stock sync module, step {i}\n")); + } + t.push_str(&format!("## {API}\n")); + for i in 1..=25 { + let mark = if i <= 4 { "x" } else { " " }; + t.push_str(&format!("- [{mark}] 2.{i} Sync handler, step {i}\n")); + } + t +} + +fn mod_src() -> &'static str { + include_str!("../mod.rs") +} + +#[test] +fn a_two_repo_plan_opens_both_pull_requests_and_finishes_both() { + let plan = PlanRepos::of_tasks(API, &tasks()).unwrap(); + assert_eq!(plan.counts(), (8, 29), "the run page's 8 of 29"); + // Only the infra pull request open: the run owes the API repository and + // builds it next, never finishes. + let one = plan.clone().with_prs([(INFRA, 41)]); + assert_eq!(one.next(), Next::Build(vec![API.to_string()])); + // Both open: done. + let both = one.with_prs([(API, 12)]); + assert_eq!(both.next(), Next::Done); + assert_eq!(both.part_label(INFRA).as_deref(), Some("part 1 of 2")); + assert_eq!(both.part_label(API).as_deref(), Some("part 2 of 2")); + + // The multi-repository loop keeps a repository whose plan check said + // "unfinished" as owed, records the plan where the end gate reads it, + // and takes a fresh step for it before the pull requests are linked. + let src = mod_src(); + let start = src.find("// --- Multi-repo path ---").unwrap(); + let block = &src[start + ..start + + src[start..] + .find("Multi-repo run set to awaiting_ci") + .unwrap()]; + let record = block + .find("plan_continue::record(") + .expect("the plan is recorded"); + let build = block + .find("if let common::plan_repos::Next::Build(owed) = plan_repos.next()") + .expect("an owed repository is built next"); + let link = block.find("pr::link_siblings(").unwrap(); + let ci = block.find("attr_s(\"awaiting_ci\")").unwrap(); + assert!( + record < build && build < link && link < ci, + "record, build, link, then wait on CI" + ); + assert!(block[build..link].contains("send_next_step(")); +} + +#[test] +fn the_pull_requests_name_their_part_and_the_order_they_merge_in() { + let prs = vec![ + crate::passes::completeness::Sibling { + repo: INFRA.into(), + number: 41, + }, + crate::passes::completeness::Sibling { + repo: API.into(), + number: 12, + }, + ]; + let infra = crate::passes::completeness::merge_order_section(&prs, 0); + assert!(infra.contains("part 1 of 2"), "{infra}"); + assert!( + infra.contains("acme/bookstore-api#12 (part 2 of 2)"), + "{infra}" + ); + let api = crate::passes::completeness::merge_order_section(&prs, 1); + assert!(api.contains("This pull request is part 2 of 2"), "{api}"); +} + +#[test] +fn an_own_review_block_whose_fix_is_in_the_other_repo_is_built_there_not_deferred() { + // The fix round's entry point asks the plan first, before the ledger + // decides anything (a round, a deferral, a note). + let src = include_str!("../resume.rs"); + let q = fn_src(src, "pub(crate) async fn queue_own_review_round("); + let plan = q + .find("plan_continue::continue_if_owed(") + .expect("the plan comes first"); + let ledger = q.find("ledger.decide(").unwrap(); + assert!(plan < ledger); + // A draft whose plan still owes the API repository is never offered + // for review, however green and approved: a wait, never a person's. + let f = Facts { + draft: true, + ci: Ci { + green: true, + why: String::new(), + }, + approved: true, + plan_owed: vec![API.into()], + ..Default::default() + }; + match ready::decide(&f) { + Decision::Wait { why, .. } => assert!(why.contains(API), "{why}"), + other => panic!("{other:?}"), + } + // The standing says CoderHelm builds it; nobody is asked. + let s = decide( + INFRA, + &StandingFacts { + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("REQUEST_CHANGES".into(), HEAD.into())), + auto_merge: true, + plan_owed: vec![API.into()], + ..Default::default() + }, + ); + assert_eq!(s.code, "building_plan"); + assert!(!s.needs_person); +} + +#[test] +fn a_placeholder_is_never_offered_for_review() { + let files = vec![( + "modules/stock_sync/placeholder/index.js".to_string(), + "@@ -0,0 +1,3 @@\n+exports.handler = async (event) => {\n+ return { ok: true };\n+};\n" + .to_string(), + )]; + let stubs: Vec = common::stub_check::stubs(&files) + .iter() + .map(common::stub_check::Stub::line) + .collect(); + assert_eq!(stubs.len(), 1); + let f = Facts { + draft: true, + ci: Ci { + green: true, + why: String::new(), + }, + approved: true, + stubs, + ..Default::default() + }; + assert!(matches!(ready::decide(&f), Decision::Wait { .. })); + // The mechanical check sits right before GitHub's ready-for-review, in + // the one place that asks for it. + let src = include_str!("../ready.rs"); + let make = fn_src(src, "async fn make_ready("); + let check = make + .find("offer_blocked(f)") + .expect("checked before marking ready"); + let mark = make.find(concat!(".mark_pr", "_ready(")).unwrap(); + assert!(check < mark); +} + +fn ledger_with(item: &str, settled: Settled) -> Ledger { + Ledger { + findings: vec![Track { + item: item.into(), + settled: Some(settled), + ..Default::default() + }], + ..Default::default() + } +} + +#[test] +fn only_a_typed_person_only_reason_defers() { + const ITEM: &str = + "An acceptance line the change doesn't deliver (`modules/stock_sync/main.tf:169`)"; + // CoderHelm's own note: never deferred. + let noted = ledger_with( + ITEM, + Settled::Noted { + why: "every approach taken".into(), + }, + ); + let own = typed_settle( + ¬ed, + &[], + &[], + &[(ITEM.into(), "every approach taken".into())], + ); + assert!(own.is_err()); + // A "reason" that is no person-gate reason: never deferred. + let untyped = ledger_with( + ITEM, + Settled::Deferred { + reason: "no progress".into(), + what: String::new(), + }, + ); + assert!(typed_settle(&untyped, &[(ITEM.into(), "no progress".into())], &[], &[]).is_err()); + // A credential only a person holds: deferred, typed and named. + let typed = ledger_with( + ITEM, + Settled::Deferred { + reason: "credential".into(), + what: "Add the STOCK_FEED_TOKEN secret in the API repository's settings".into(), + }, + ); + let lines = typed_settle(&typed, &[(ITEM.into(), "credential".into())], &[], &[]).unwrap(); + assert!(lines[0].contains("STOCK_FEED_TOKEN"), "{lines:?}"); +} + +#[test] +fn the_page_never_says_waiting_on_a_person_and_nothing_needed_at_once() { + let base = StandingFacts { + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("REQUEST_CHANGES".into(), HEAD.into())), + auto_merge: true, + require_human_approval: true, + ..Default::default() + }; + let s = decide(INFRA, &base); + let l = line(&Inputs { + pr: 41, + standing: Some(&s), + ..Default::default() + }); + // One state: the badge ("Needs a person" / "Nothing needed from you") + // reads `needs_person`; the line names a person exactly then. + assert!(!s.needs_person); + assert!(!names_a_person(&l), "{l}"); + assert!( + !l.contains("could not make") && !l.contains("a person"), + "{l}" + ); +} + +#[test] +fn a_repo_rule_approval_reads_exactly_that() { + let s = decide( + INFRA, + &StandingFacts { + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), HEAD.into())), + auto_merge: true, + require_human_approval: true, + approvals_required: 1, + ..Default::default() + }, + ); + assert!(s.needs_person && s.person_only().is_some()); + let l = line(&Inputs { + pr: 41, + standing: Some(&s), + ..Default::default() + }); + assert_eq!(l, "Needs 1 approval from a person (repo rule) on #41."); +} + +#[test] +fn an_empty_finding_place_fails_the_guard_and_is_never_rendered() { + assert!(common::rendered::person_text( + "- πŸ’¬ `` β€” An acceptance line the change doesn't deliver" + ) + .is_some()); + let f = crate::passes::review_agent::Finding { + file: String::new(), + line: 0, + severity: "low".into(), + category: "correctness".into(), + title: "An acceptance line the change doesn't deliver".into(), + body: "The ticket asks for the nightly stock sync to run.".into(), + ..Default::default() + }; + let p = crate::passes::review_agent::to_postable(&[f], &HashMap::new(), &HashMap::new()); + let body = format!("#### Additional findings\n{}", p.unanchored_md); + assert!(!body.contains("``"), "{body}"); + assert_eq!(common::rendered::person_text(&body), None, "{body}"); +} + +#[test] +fn a_stuck_run_is_picked_up_by_the_sweep() { + let plan = PlanRepos::of_tasks(API, &tasks()).unwrap(); + let pr = common::run_prs::RunPr { + repo: INFRA.into(), + pr_number: 41, + branch: "coderhelm/stock-sync-bookstore-infra".into(), + url: format!("https://github.com/{INFRA}/pull/41"), + outcome: String::new(), + }; + let item: HashMap = HashMap::from([ + ("team_id".into(), AttributeValue::S("T1".into())), + ("run_id".into(), AttributeValue::S("R1".into())), + ("status".into(), AttributeValue::S("completed".into())), + ( + common::plan_repos::FIELD.into(), + AttributeValue::S(plan.to_json()), + ), + ( + common::run_prs::FIELD.into(), + AttributeValue::L(vec![pr.to_attr()]), + ), + ]); + let read = crate::passes::plan_continue::of_item(&item).unwrap(); + assert_eq!(read.owed(), vec![API.to_string()]); + assert!(crate::passes::plan_continue::wants_continue(&item, &read)); + // The sweep runs on deploy and every 15 minutes. + let recover = include_str!("../recover.rs"); + let sweep = fn_src(recover, "pub async fn self_heal_sweep("); + assert!(sweep.contains("plan_continue::sweep(state)")); +} + +/// Every source file of the three services, outside tests. +fn sources() -> Vec<(String, String)> { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut out = Vec::new(); + let mut stack = vec![ + root.join("common/src"), + root.join("worker/src"), + root.join("gateway/src"), + ]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + if !p.ends_with("incidents") { + stack.push(p); + } + } else if p.extension().is_some_and(|x| x == "rs") { + let text = std::fs::read_to_string(&p).unwrap_or_default(); + let code = text.split("#[cfg(test)]").next().unwrap_or("").to_string(); + out.push((p.to_string_lossy().replace('\\', "/"), code)); + } + } + } + out +} + +/// The owner's rule: no text claims a person is needed without #930's +/// typed hand-off. Each file that writes such a claim either builds it +/// from `PersonOnly` (or the human-only list #930 types it from), or is a +/// prompt or a check that names the rule to a model. A new file with a +/// claim fails here until it goes through the type. +#[test] +fn no_text_claims_a_person_is_needed_without_the_typed_hand_off() { + const CLAIMS: &[&str] = &[ + "waiting on: a person", + "needs a person", + "waits on a person", + "a person must", + "only a person can", + ]; + // Words to a model, or the checks that refuse such claims: never shown + // to a person as their to-do. + const MODEL_OR_CHECK: &[&str] = &[ + "worker/src/passes/person_gate.rs", + "worker/src/passes/fix_location.rs", + "worker/src/passes/supervisor.rs", + "worker/src/passes/outside_work.rs", + "common/src/person_only.rs", + "common/src/rendered.rs", + // The planner's instructions and the human-only words it is given. + "worker/src/passes/habits.rs", + "worker/src/passes/ownership.rs", + // The heading over the plan's questions (each one the person gate + // passed as a question only a person answers), read and written. + "worker/src/passes/description_facts.rs", + "worker/src/passes/completeness.rs", + // The planner's and the reviewer's instructions to their models, + // and the description eval's recorded fixtures. + "worker/src/passes/plan.rs", + "worker/src/passes/description_eval.rs", + "worker/src/passes/review_agent.rs", + // A tool's result read by the model (the team's agent policy asks + // its approver), never a line on a run page. + "worker/src/passes/live_sources.rs", + "common/src/agent_policy/gate.rs", + // The description writer's instructions for manual checks. + "worker/src/passes/pr.rs", + ]; + let typed = [ + "person_only", + "PersonOnly", + "needs_person()", + "HumanOnly", + "person_gate::Reason", + // The ledger's typed accessor (`Ledger::person_of`). + "person_of(", + ]; + let mut bad = Vec::new(); + for (path, code) in sources() { + if MODEL_OR_CHECK.iter().any(|m| path.ends_with(m)) { + continue; + } + let low = code.to_lowercase(); + let claims: Vec<&&str> = CLAIMS + .iter() + .filter(|c| { + low.lines() + .filter(|l| !l.trim_start().starts_with("//")) + // A log line is for CoderHelm's maintainers. + .filter(|l| { + !["info!(", "warn!(", "error!(", "debug!("] + .iter() + .any(|m| l.contains(m)) + }) + .any(|l| { + l.contains(&format!("\"{}", c)) + || l.contains(&format!(" {c}")) && l.contains('"') + }) + }) + .collect(); + if claims.is_empty() { + continue; + } + if !typed.iter().any(|t| code.contains(t)) { + bad.push(format!("{path}: {claims:?}")); + } + } + assert!( + bad.is_empty(), + "a text claims a person is needed without the typed hand-off (common::person_only::PersonOnly):\n{}", + bad.join("\n") + ); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 8f3c6af8b..a3d3c7c32 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1389,6 +1389,7 @@ pub mod ownership; pub(crate) mod person_gate; mod plan; pub mod plan_chat; +pub mod plan_continue; pub(crate) mod plan_coverage; pub mod plan_execute; mod plan_judge; @@ -5595,6 +5596,26 @@ false, .await; let mut pr_results: Vec = Vec::new(); + // The plan, repository by repository: what each part built, and + // what the run still owes (`common::plan_repos`). Kept on the + // run, where the end gate reads it: the run never ends while it + // owes a repository CoderHelm can write to. + let mut plan_repos = common::plan_repos::PlanRepos { + plan_repo: format!("{}/{}", msg.repo_owner, msg.repo_name), + parts: plan_result + .repo_tasks + .iter() + .map(|rt| { + let (done, tasks) = common::plan_repos::count_tasks(&rt.tasks); + common::plan_repos::Part { + repo: format!("{}/{}", rt.owner, rt.name), + tasks, + done, + ..Default::default() + } + }) + .collect(), + }; // Each repo's branch: the team's pattern plus `-{repo}`, or the // branch of the PR already open there for this ticket. @@ -5679,6 +5700,15 @@ false, if let Err(why) = infra_repo::may_open_pr(state, &provider, &full, implement_deadline).await { + // The one reason a person is needed for this part: + // the team's agent permissions, named + // (`plan_repos::Part::person_only`). + if let Some(part) = plan_repos.part_mut(&full) { + part.no_access = format!( + "Allow CoderHelm's coder to open a pull request in {full} in the team's agent permissions ({why})" + ); + part.grantor = "team_admin".into(); + } add_progress_note( state, &msg.team_id, @@ -5755,17 +5785,62 @@ false, } } + // A repository that didn't open its pull request (its plan check + // said unfinished, its step ran out, an error) is still owed: + // never "a failed repository" the run finishes without. + let plan_repos = plan_repos.with_prs( + pr_results + .iter() + .map(|p| (format!("{}/{}", p.repo.0, p.repo.1), p.pr_number)) + .collect::>() + .iter() + .map(|(r, n)| (r.as_str(), *n)), + ); + plan_continue::record(state, &msg.team_id, run_id, &plan_repos).await; + if let common::plan_repos::Next::Build(owed) = plan_repos.next() { + let handoff = send_next_step( + state, + msg, + run_id, + &format!( + "The plan still has tasks in {}: the next step builds them", + owed.join(" and ") + ), + false, + steps::STEP_DELAY_SECS, + ) + .await; + if handoff.continued() { + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + // No step could be queued (the usage limit, the step + // ceiling): the run is never written as done or waiting + // while it owes them (`run_ending::PLAN_GATE`); the plan + // sweep starts it again (`plan_continue::sweep`). + warn!(run_id, owed = ?owed, "The plan still owes repositories and no step could be queued"); + } + if pr_results.is_empty() { close_memory(state, agent_memory.take()).await; return Err("Multi-repo pipeline produced no PRs".into()); } - // Each PR names its siblings and the order they merge in (the - // plan's repository order). - let siblings: Vec<(String, String, u64)> = pr_results + // Each PR names its siblings, which part of the plan it is + // ("part 1 of 2") and the order they merge in (the plan's + // repository order), once every part has its pull request. + let mut siblings: Vec<(String, String, u64)> = pr_results .iter() .map(|p| (p.repo.0.clone(), p.repo.1.clone(), p.pr_number)) .collect(); + let order = |o: &str, n: &str| { + plan_repos + .parts + .iter() + .position(|p| p.repo.eq_ignore_ascii_case(&format!("{o}/{n}"))) + .unwrap_or(usize::MAX) + }; + siblings.sort_by_key(|(o, n, _)| order(o, n)); pr::link_siblings(&github, &siblings).await; // Save checkpoint + set awaiting_ci with all PRs. The run's own diff --git a/services/worker/src/passes/own_problems.rs b/services/worker/src/passes/own_problems.rs index d39d34bf5..0ec5948d2 100644 --- a/services/worker/src/passes/own_problems.rs +++ b/services/worker/src/passes/own_problems.rs @@ -46,6 +46,14 @@ pub async fn record(state: &WorkerState, team_id: &str, run_id: &str, p: &OwnPro add(state, team_id, &[(own_attr(p.subject), 1)]).await; } +/// CoderHelm's own review findings its rounds couldn't finish: an internal +/// alert per finding, never a deferral and never a person's to-do. +pub async fn alert_own_limit(state: &WorkerState, team_id: &str, run_id: &str, lines: &[String]) { + for l in lines { + alert(state, team_id, run_id, "own_review_open", l).await; + } +} + /// An internal alert for CoderHelm's maintainers: never shown to the team /// as a to-do. pub async fn alert(state: &WorkerState, team_id: &str, run_id: &str, kind: &str, text: &str) { diff --git a/services/worker/src/passes/own_review_ledger.rs b/services/worker/src/passes/own_review_ledger.rs index 9896921af..0b63441fc 100644 --- a/services/worker/src/passes/own_review_ledger.rs +++ b/services/worker/src/passes/own_review_ledger.rs @@ -701,6 +701,7 @@ impl Ledger { /// Records `items` as CoderHelm's notes ([`Settled::Noted`]): its own /// rounds left them open for `why`. The pull request lists them and goes /// ready; the review no longer holds the draft on them. + #[cfg(test)] pub fn note(&mut self, items: &[String], why: &str) { for item in items { if self.find_mut(item).is_none() { @@ -796,6 +797,7 @@ fn round_ending(blocked: &[Blocker]) -> RoundEnding { /// The deferred note for findings CoderHelm's own rounds left open (`why`): /// listed on the pull request, which is marked ready. Never a person's /// to-do: it says what CoderHelm did and what is left. +#[cfg(test)] pub fn note_lines(items: &[String], why: &str) -> Vec { items .iter() @@ -869,6 +871,7 @@ pub fn instruction(approach: &Approach, focus: &[String]) -> String { /// The deferred lines for the pull request: each item with its person-gate /// reason, and each item the ticket rules out with its words. +#[cfg(test)] pub fn settled_lines( deferred: &[(String, String)], by_ticket: &[(String, String)], @@ -890,6 +893,65 @@ pub fn settled_lines( .collect() } +/// What a settle comes to under the rule that only a typed person-only +/// reason defers (`common::person_only::PersonOnly`, from the person gate's +/// code and words). `Ok`: the lines to list, every deferral typed (the ones +/// the ticket rules out are settled, not deferred). `Err`: CoderHelm's own +/// lines: a finding whose words name no reason only a person has, or that +/// CoderHelm's rounds left open (a note). Those are never deferred and never +/// a person's: the run keeps its review open as its own limit and its +/// maintainers are alerted. +pub fn typed_settle( + ledger: &Ledger, + deferred: &[(String, String)], + by_ticket: &[(String, String)], + noted: &[(String, String)], +) -> Result, Vec> { + let mut lines = Vec::new(); + let mut own = Vec::new(); + for (item, words) in deferred { + match ledger.person_of(item) { + Some(Ok(p)) => lines.push(format!("{item}: needs a person ({})", p.line())), + Some(Err(o)) => own.push(format!("{item}: {}", o.line())), + None => own.push(format!( + "{item}: CoderHelm's own to finish, no reason only a person has ({words})" + )), + } + } + for (item, why) in noted { + own.push(format!( + "{item}: CoderHelm's own to finish, left open after its rounds ({why})" + )); + } + if !own.is_empty() { + return Err(own); + } + lines.extend( + by_ticket + .iter() + .map(|(i, q)| format!("{i}: not done, the ticket rules it out (\"{q}\")")), + ); + Ok(lines) +} + +impl Ledger { + /// The typed hand-off for `item`'s person-gate reason, when its track + /// claims one: `Err` when the words name CoderHelm's own limit. + pub fn person_of( + &self, + item: &str, + ) -> Option> { + let t = self.findings.iter().find(|t| same_finding(&t.item, item))?; + let (code, what) = match &t.settled { + Some(Settled::Deferred { reason, what }) => (reason.as_str(), what.as_str()), + _ if !t.person_reason.is_empty() => (t.person_reason.as_str(), t.person_what.as_str()), + _ => return None, + }; + let what = if what.trim().is_empty() { item } else { what }; + Some(common::person_only::parse(code, what)) + } +} + /// What the completion guard decides for a run about to be marked /// completed with its pull request, from its own review's latest verdict. #[derive(Debug, Clone, PartialEq, Eq)] @@ -899,13 +961,11 @@ pub enum Completion { /// Its review still asks for changes on the head: the run goes back to /// its checks and its review, not to "completed". Continue(String), - /// It asked for changes on the head after every approach CoderHelm - /// has: CoderHelm's own limit, never a person's to-do. What is open is - /// listed on the pull request as a deferred note with this, and the - /// pull request is marked ready. - Defer(String), - /// A deferred finding has no reason only a person can give: never - /// "completed" on it. + /// Never "completed": a deferred finding has no reason only a person + /// can give, or its review still asks for changes after every approach + /// CoderHelm has. CoderHelm's own limit, never a person's to-do and + /// never deferred: the run stops naming what its review still asks for + /// (`Stop::ReviewOpen`), and its maintainers are alerted. Hold(String), } @@ -928,18 +988,24 @@ pub fn completion(verdict: Option<(&str, &str)>, head: &str, ledger: &Ledger) -> if !changes { return Completion::Complete; } - // What the review still asks for is CoderHelm's own notes, listed on the - // ready pull request: nothing more to do, and nothing approved over. - let noted = ledger + let short = head.get(..7).unwrap_or(head); + // What the review still asks for is only CoderHelm's own notes: never + // "completed" over it, and never deferred (only a person-only reason + // defers). + let noted: Vec<&Track> = ledger .findings .iter() - .any(|t| matches!(t.settled, Some(Settled::Noted { .. }))); - if noted && ledger.findings.iter().all(|t| t.settled.is_some()) { - return Completion::Complete; + .filter(|t| matches!(t.settled, Some(Settled::Noted { .. }))) + .collect(); + if !noted.is_empty() && ledger.findings.iter().all(|t| t.settled.is_some()) { + return Completion::Hold(format!( + "CoderHelm's review still asks for changes on `{short}` on what its own rounds left \ + open: {}", + names(¬ed) + )); } - let short = head.get(..7).unwrap_or(head); if ledger.continues >= MAX_CONTINUES { - return Completion::Defer(format!( + return Completion::Hold(format!( "CoderHelm's review still asks for changes on `{short}` after the run went back to \ its checks {} times", ledger.continues @@ -950,7 +1016,7 @@ pub fn completion(verdict: Option<(&str, &str)>, head: &str, ledger: &Ledger) -> .iter() .find(|t| t.settled.is_none() && Ledger::exhausted(t) && t.person_reason.is_empty()) { - return Completion::Defer(format!( + return Completion::Hold(format!( "CoderHelm's review still asks for changes on `{short}` and every approach on this \ finding was taken: {}", t.item @@ -1196,10 +1262,11 @@ mod tests { Plan::Unfixed { why } => assert!(why.contains("every approach"), "{why}"), other => panic!("{other:?}"), } - // CoderHelm's own limit: listed as its note, never held for a person. + // CoderHelm's own limit: never deferred, never held for a person, + // never "completed": the run stops naming what its review asks. assert!(matches!( completion(Some(("REQUEST_CHANGES", "abcdef1234")), "abcdef1234", &l), - Completion::Defer(_) + Completion::Hold(_) )); } @@ -1334,7 +1401,7 @@ mod tests { }; assert!(matches!( completion(Some(("REQUEST_CHANGES", "h")), "h", &spent), - Completion::Defer(_) + Completion::Hold(_) )); let bad = Ledger { findings: vec![Track { diff --git a/services/worker/src/passes/plan_continue.rs b/services/worker/src/passes/plan_continue.rs new file mode 100644 index 000000000..c1b4cf2b5 --- /dev/null +++ b/services/worker/src/passes/plan_continue.rs @@ -0,0 +1,433 @@ +//! A run builds every repository of its plan before it ends. +//! +//! The run record keeps the plan's repositories (`common::plan_repos`) and +//! the count it still owes (`plan_owed`). Every done or waiting ending is +//! written only while that count is 0 (`common::run_ending::PLAN_GATE`), +//! so a run whose plan still has tasks in a repository CoderHelm can write +//! to can't be written as done, waiting or handed off. This module is what +//! moves such a run on: +//! +//! - [`continue_if_owed`]: called before a fix round on its own review's +//! findings and before any deferral. A finding the rest of the plan would +//! satisfy is never deferred and never a person's: the run builds the +//! repository it owes first, in a fresh step from the plan it already has +//! (never planned again). Repositories whose pull request is open are +//! skipped by their own checkpoints; the new pull request is linked to +//! the others with the order they merge in. +//! - [`sweep`]: on deploy and every sweep, runs that still owe a +//! repository (and runs from before the record kept the plan: finished, +//! with their own review asking for changes) are picked up the same way. +//! +//! Each continuation is claimed on the run (`plan_continues`, bounded by +//! [`MAX_CONTINUES`]), so two deciders never start two steps, and a +//! repository that can't be built ends the run with a typed stop rather +//! than looping. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::plan_repos::{Next, PlanRepos, FIELD, OWED_FIELD}; +use tracing::{info, warn}; + +use super::{attr_n, attr_s, steps}; +use crate::WorkerState; + +/// Continuations of one run's plan, at most. +pub const MAX_CONTINUES: u32 = 4; +/// The run record's count of continuations taken. +pub const CONTINUES_FIELD: &str = "plan_continues"; +/// The code version the sweep last read a run's plan for (runs from before +/// the record kept it are read once per version). +pub const CHECKED_FIELD: &str = "plan_checked_version"; + +/// What the run's plan asks now. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Owed { + /// The plan owes a repository and the run is building it (a step was + /// queued now, or the run is in a step already). + Building, + /// Nothing is owed (or nothing could be started: the caller goes on). + Nothing, +} + +fn s<'a>(item: &'a HashMap, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map_or("", |v| v.as_str()) +} + +fn n(item: &HashMap, k: &str) -> u64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0) +} + +/// The plan as the record keeps it, with the record's pull requests. +pub fn of_item(item: &HashMap) -> Option { + let p = PlanRepos::from_json(s(item, FIELD))?; + let prs = common::run_prs::from_item(item); + Some(p.with_prs(prs.iter().map(|r| (r.repo.as_str(), r.pr_number)))) +} + +/// What a run in `status` with `item`'s plan does: build what it owes when +/// nothing else is building it now. Pure: the sweep and the tests read it. +pub fn wants_continue(item: &HashMap, plan: &PlanRepos) -> bool { + use common::run_status as st; + let status = s(item, "status"); + matches!(plan.next(), Next::Build(_)) + && !st::ended_by_person(status) + && ![st::MERGED, st::RETRIED, st::ARCHIVED].contains(&status) + && !item.contains_key("guard_open") + && n(item, CONTINUES_FIELD) < u64::from(MAX_CONTINUES) +} + +/// The plan of a run from before the record kept it: the task list the run +/// itself wrote (`openspec//tasks.md`, under the repository whose +/// `plan_run.txt` names this run). +async fn plan_from_store( + state: &WorkerState, + item: &HashMap, +) -> Option { + let team_id = s(item, "team_id"); + let ticket = s(item, "ticket_id").to_lowercase(); + let run_id = s(item, "run_id"); + if team_id.is_empty() || ticket.is_empty() || run_id.is_empty() { + return None; + } + let root = format!("teams/{team_id}/runs/{ticket}/openspec/"); + let listed = state + .s3 + .list_objects_v2() + .bucket(&state.config.bucket_name) + .prefix(&root) + .delimiter("/") + .send() + .await + .ok()?; + for p in listed.common_prefixes() { + let Some(prefix) = p.prefix() else { continue }; + let prefix = prefix.trim_end_matches('/'); + let owner = + super::read_s3_text(state, &format!("{prefix}/{}", super::plan::PLAN_RUN_FILE)).await; + if owner.as_deref().map(str::trim) != Some(run_id) { + continue; + } + let tasks = super::read_s3_text(state, &format!("{prefix}/tasks.md")).await?; + let repo = prefix + .rsplit('/') + .next() + .unwrap_or("") + .replacen("__", "/", 1); + return PlanRepos::of_tasks(&repo, &tasks); + } + None +} + +/// Keeps the plan and what it owes on the run. The count is what the end +/// gate reads (`run_ending::PLAN_GATE`). +pub async fn record(state: &WorkerState, team_id: &str, run_id: &str, plan: &PlanRepos) { + let owed = plan.owed().len() as u64; + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #p = :p, #o = :o") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#p", FIELD) + .expression_attribute_names("#o", OWED_FIELD) + .expression_attribute_values(":p", attr_s(&plan.to_json())) + .expression_attribute_values(":o", attr_n(owed)) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the plan's repositories on the run"); + } +} + +/// Claims one continuation: the run goes back to running, once per +/// decider. False when another decision took it, or the bound is reached. +async fn claim(state: &WorkerState, item: &HashMap) -> bool { + let team_id = s(item, "team_id"); + let run_id = s(item, "run_id"); + let was = s(item, "status"); + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :run, status_run_id = :sri, current_pass = :cp, updated_at = :t, \ + #c = if_not_exists(#c, :zero) + :one REMOVE waiting_on, wait_reminded_at", + ) + .condition_expression( + "#s = :was AND attribute_not_exists(guard_open) \ + AND (attribute_not_exists(#c) OR #c < :max)", + ) + .expression_attribute_names("#s", "status") + .expression_attribute_names("#c", CONTINUES_FIELD) + .expression_attribute_values(":run", attr_s(common::run_status::RUNNING)) + .expression_attribute_values( + ":sri", + common::run_ending::working(common::run_ending::Working::Running, run_id).sri_attr(), + ) + .expression_attribute_values(":cp", attr_s("plan")) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":was", attr_s(was)) + .expression_attribute_values(":zero", attr_n(0)) + .expression_attribute_values(":one", attr_n(1)) + .expression_attribute_values(":max", attr_n(u64::from(MAX_CONTINUES))) + .send() + .await; + match res { + Ok(_) => true, + Err(e) => { + if !format!("{e:?}").contains("ConditionalCheckFailed") { + warn!(run_id, error = %e, "Could not claim building the rest of the plan"); + } + false + } + } +} + +/// Starts the step that builds what the plan owes, from the plan the run +/// already has. True when it is queued. +async fn start( + state: &WorkerState, + item: &HashMap, + plan: &PlanRepos, + why: &str, +) -> bool { + let Some((mut msg, _)) = super::recheck::message_of(item) else { + warn!( + run_id = s(item, "run_id"), + "The run's record lacks what a step needs: its plan stays owed" + ); + return false; + }; + // The plan is kept under the repository it was made in (the ticket's). + if let Some((o, r)) = plan.plan_repo.split_once('/') { + msg.repo_owner = o.to_string(); + msg.repo_name = r.to_string(); + } + let run_id = s(item, "run_id").to_string(); + if state.config.ticket_queue_url.is_empty() || !steps::under_ceiling(msg.continuation) { + return false; + } + if let Some(reason) = super::check_budget_exceeded(state, &msg.team_id).await { + info!(run_id, reason = %reason, "The rest of the plan waits for the usage limit"); + return false; + } + if !claim(state, item).await { + return false; + } + super::checkpoint_back_to_plan(state, &msg.team_id, &run_id).await; + steps::save_mark(state, &msg.team_id, &run_id, "", 0, 0).await; + let now_ms = chrono::Utc::now().timestamp_millis().max(0) as u64; + let next = steps::next_message(&msg, &run_id, now_ms); + let step = steps::step_number(next.continuation); + if !super::send_ticket_after(state, &next, steps::STEP_DELAY_SECS as u64).await { + warn!( + run_id, + "The step that builds the rest of the plan couldn't be queued" + ); + return false; + } + steps::mark_queued(state, &msg.team_id, &run_id, step).await; + let line = plan.building_line().unwrap_or_default(); + super::add_progress_note(state, &msg.team_id, &run_id, &format!("{line} ({why})")).await; + info!(run_id, step, owed = ?plan.owed(), "Building the rest of the run's plan"); + true +} + +/// The run's plan, from its record or, for a run from before the record +/// kept it, from the task list it wrote (recorded on the run once read). +pub async fn plan_of( + state: &WorkerState, + item: &HashMap, +) -> Option { + if let Some(p) = of_item(item) { + return Some(p); + } + let p = plan_from_store(state, item).await?; + let prs = common::run_prs::from_item(item); + let p = p.with_prs(prs.iter().map(|r| (r.repo.as_str(), r.pr_number))); + record(state, s(item, "team_id"), s(item, "run_id"), &p).await; + Some(p) +} + +/// Builds what the run's plan owes before anything else about it is +/// decided (see the module comment). +pub async fn continue_if_owed(state: &WorkerState, team_id: &str, run_id: &str, why: &str) -> Owed { + let Ok(out) = 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)) + .consistent_read(true) + .send() + .await + else { + return Owed::Nothing; + }; + let Some(item) = out.item else { + return Owed::Nothing; + }; + continue_item(state, &item, why).await +} + +async fn continue_item( + state: &WorkerState, + item: &HashMap, + why: &str, +) -> Owed { + let Some(plan) = plan_of(state, item).await else { + return Owed::Nothing; + }; + if !matches!(plan.next(), Next::Build(_)) { + return Owed::Nothing; + } + // A step is working on it already. + if [ + common::run_status::RUNNING, + common::run_status::QUEUED, + common::run_status::PENDING, + ] + .contains(&s(item, "status")) + { + return Owed::Building; + } + if wants_continue(item, &plan) && start(state, item, &plan, why).await { + return Owed::Building; + } + Owed::Nothing +} + +/// Runs whose plan still owes a repository, and finished runs from before +/// the record kept the plan whose own review asks for changes: each builds +/// what it owes. Returns how many were started. +pub async fn sweep(state: &WorkerState) -> usize { + let version = super::proof::checks_version(); + let since = + (chrono::Utc::now() - chrono::Duration::days(super::recover::SWEEP_DAYS)).to_rfc3339(); + let filter = super::team_runs::Filter { + expr: "updated_at >= :since AND (#o > :zero OR (attribute_not_exists(#p) \ + AND pr_number > :zero AND #s IN (:done, :old_done, :held, :ci) \ + AND (attribute_not_exists(#cv) OR #cv <> :v)))", + names: vec![ + ("#o", OWED_FIELD), + ("#p", FIELD), + ("#s", "status"), + ("#cv", CHECKED_FIELD), + ], + values: vec![ + (":since", attr_s(&since)), + (":zero", attr_n(0)), + (":done", attr_s(common::run_status::COMPLETED)), + (":old_done", attr_s(common::run_status::SUCCESS)), + // A condition value only, never a status written here. + ( + ":held", + AttributeValue::S(common::run_status::NEEDS_INPUT.to_string()), + ), + (":ci", attr_s(common::run_status::AWAITING_CI)), + (":v", attr_s(version)), + ], + projection: None, + }; + let found = super::team_runs::matching(state, "Plan sweep", &filter).await; + let mut started = 0; + for item in found { + if started >= super::recover::SWEEP_MAX { + break; + } + if !item.contains_key(FIELD) { + // Read once per code version: a run whose plan is one repository + // is not read again. + mark_checked(state, &item, version).await; + } + if continue_item(state, &item, "picked up by the plan sweep").await == Owed::Building { + started += 1; + } + } + if started > 0 { + info!(started, "Plan sweep: runs building the rest of their plan"); + } + started +} + +async fn mark_checked(state: &WorkerState, item: &HashMap, version: &str) { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(s(item, "team_id"))) + .key("run_id", attr_s(s(item, "run_id"))) + .update_expression("SET #cv = :v") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#cv", CHECKED_FIELD) + .expression_attribute_values(":v", attr_s(version)) + .send() + .await; +} + +#[cfg(test)] +mod tests { + use super::*; + + const TASKS: &str = "## acme/bookstore-infra\n- [x] 1.1 Nightly stock sync module\n\ + ## acme/bookstore-api\n- [x] 2.1 Sync handler\n- [ ] 2.2 Handler tests\n"; + + fn item( + status: &str, + plan: &PlanRepos, + prs: &[(&str, u64)], + ) -> HashMap { + let mut m = HashMap::from([ + ("team_id".to_string(), attr_s("T1")), + ("run_id".to_string(), attr_s("R1")), + ("status".to_string(), attr_s(status)), + (FIELD.to_string(), attr_s(&plan.to_json())), + ]); + let list: Vec = prs + .iter() + .map(|(r, n)| common::run_prs::RunPr { + repo: r.to_string(), + pr_number: *n, + branch: "coderhelm/stock-sync".into(), + url: format!("https://github.com/{r}/pull/{n}"), + outcome: String::new(), + }) + .collect(); + m.insert( + common::run_prs::FIELD.to_string(), + AttributeValue::L(list.iter().map(|p| p.to_attr()).collect()), + ); + m + } + + #[test] + fn a_finished_run_that_owes_a_repo_continues_and_one_with_both_prs_does_not() { + let plan = PlanRepos::of_tasks("acme/bookstore-api", TASKS).unwrap(); + let stuck = item("completed", &plan, &[("acme/bookstore-infra", 41)]); + let read = of_item(&stuck).unwrap(); + assert_eq!(read.owed(), vec!["acme/bookstore-api".to_string()]); + assert!(wants_continue(&stuck, &read)); + let both = item( + "completed", + &plan, + &[("acme/bookstore-infra", 41), ("acme/bookstore-api", 12)], + ); + assert!(!wants_continue(&both, &of_item(&both).unwrap())); + // A run a person closed, or one past its bound, is never resumed. + let closed = item("closed", &plan, &[("acme/bookstore-infra", 41)]); + assert!(!wants_continue(&closed, &of_item(&closed).unwrap())); + let mut spent = stuck.clone(); + spent.insert(CONTINUES_FIELD.into(), attr_n(u64::from(MAX_CONTINUES))); + assert!(!wants_continue(&spent, &read)); + } +} diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index fb127a45e..4f6c19588 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -424,6 +424,9 @@ pub struct Candidate { pub owed_proofs: Vec, /// The proof's plan for the head, as kept (`proof_routes`), "" when none. pub proof_plan: String, + /// The run's plan, repository by repository (`plan_repos`), when it + /// spans several. + pub plan: Option, } impl Candidate { @@ -487,6 +490,7 @@ pub fn candidate_of(item: &HashMap) -> Option draft_held: item.contains_key(common::draft_hold::FIELD), owed_proofs: super::own_review_ledger::of_item(item).owed_proofs(), proof_plan: s(common::e2e::proof_routes::FIELD), + plan: super::plan_continue::of_item(item), }; (pr > 0 && c.installation_id > 0 && !c.team_id.is_empty() && !c.run_id.is_empty()).then_some(c) } @@ -808,7 +812,15 @@ async fn perform( .await { super::resume::OwnRound::Fixing => Performed::Started, + // CoderHelm's own limit: alerted, never deferred, never a + // person's. Nothing runs on it now; its review keeps asking + // and the next code version's look takes it again. + super::resume::OwnRound::Own(lines) => { + info!(run_id = %c.run_id, open = lines.len(), "PR watch: CoderHelm's own limit on its review's findings; alerted, not deferred"); + Performed::NotStarted + } super::resume::OwnRound::Defer(lines) => { + let lines = lines.into_lines(); // Every finding left is settled with its own reason (a // person-gate reason, or the ticket's words): listed on // the pull request, and the head reviewed again so its @@ -1105,9 +1117,37 @@ async fn standing( } else { false }; + // The approvals the branch's rules require, read with the pull request + // (not on a look that kept the last one's reads). + let approvals_required = + if known_approval.is_none() && seen.open && (cfg.require_human_approval || seen.blocked) { + let rules = github + .branch_rules(&c.owner, &c.repo, &c.base_branch) + .await + .ok(); + let classic = github + .branch_protection(&c.owner, &c.repo, &c.base_branch) + .await + .ok(); + merge_standing::approvals_required(rules.as_ref(), classic.as_ref()) + } else { + Standing::from_json(&c.standing).map_or(0, |s| s.approvals) + }; + let (plan_owed, plan_person) = match &c.plan { + Some(p) => ( + p.owed(), + p.parts + .iter() + .find_map(common::plan_repos::Part::person_only), + ), + None => (Vec::new(), None), + }; let standing = merge_standing::decide( &format!("{}/{}", c.owner, c.repo), &merge_standing::Facts { + approvals_required, + plan_owed, + plan_person, merged: seen.merged, closed: !seen.open && !seen.merged, draft: seen.draft, @@ -1228,6 +1268,17 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> } } } + // The run's own plan still owes a repository: it builds it before + // anything about this pull request is settled (`plan_continue`). + if act == Act::Nothing && c.plan.as_ref().is_some_and(|p| !p.owed().is_empty()) { + super::plan_continue::continue_if_owed( + state, + &c.team_id, + &c.run_id, + "its pull request waits for the rest of the plan", + ) + .await; + } // Only work an act started now, or a run still in flight, is CoderHelm // working: a finished run whose findings were settled is never shown as // "a fix round is taking them". diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 3d1d666c0..4d31b235e 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -189,6 +189,34 @@ pub struct Facts { /// Each ticket criterion's end-to-end test run on staging and on the /// preview (`e2e_proof`). pub two_way: super::e2e_proof::Standing, + /// Places the diff ships a placeholder or stub in place of real code + /// (`common::stub_check`), one line each. + pub stubs: Vec, + /// Repositories of the run's plan still owed (`common::plan_repos`): + /// the pull requests are offered for review together, once each part + /// is built and linked. + pub plan_owed: Vec, +} + +/// Why the pull request can't be offered for review yet, whatever else is +/// true: the run's plan still owes another repository, or the diff ships a +/// placeholder in place of what the ticket needs. `None` when neither. +/// [`decide`] never marks ready over it, and [`make_ready`] refuses it +/// before GitHub is asked. +pub fn offer_blocked(f: &Facts) -> Option { + if !f.plan_owed.is_empty() { + return Some(format!( + "the rest of the plan is still being built in {}; the pull requests are offered for review together, linked", + f.plan_owed.join(" and ") + )); + } + if !f.stubs.is_empty() { + return Some(format!( + "it ships a placeholder in place of code the ticket needs, and CoderHelm replaces it first: {}", + f.stubs.join("; ") + )); + } + None } /// What a draft waits for while its criteria are proven both ways. @@ -422,7 +450,15 @@ fn own_review_reason(body: &str) -> Option { /// every other reason, once CoderHelm's own attempts are spent, is listed /// as its note and the pull request goes ready. pub fn decide(f: &Facts) -> Decision { - finish(f, decide_raw(f)) + let d = finish(f, decide_raw(f)); + // Never offered for review over a placeholder or an unbuilt part of the + // plan: a draft stays CoderHelm's wait (never a person's hold). + match (offer_blocked(f), &d) { + (Some(why), Decision::Ready { .. } | Decision::Proving { .. }) if f.draft => { + Decision::Wait { why, until: None } + } + _ => d, + } } /// What the decision's reasons come to: the human-only ones hold; the rest @@ -1109,6 +1145,7 @@ pub async fn settle(ctx: &Ctx<'_>) -> Outcome { Err(r) => return retry_or_give_up(ctx, &run_id, &pr_url, r).await, }; ask_for_review(ctx, &mut facts).await; + offer_checks(ctx, &run_id, &mut facts).await; fix_own_findings(ctx, &run_id, &mut facts).await; if !run_id.is_empty() && !facts.closed { facts.prior = run_hold(ctx.state, ctx.team_id, &run_id) @@ -1265,6 +1302,72 @@ pub fn carried_retries(prior: Option<&DraftHold>, head: &str) -> u32 { .map_or(0, |p| p.retried) } +/// What keeps a draft from being offered for review before anything else: +/// the run's plan still owes a repository (built now, `plan_continue`), and +/// the diff's placeholders (`common::stub_check`), which go to CoderHelm's +/// coder as findings of its own. Only a draft is read. +async fn offer_checks(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { + if f.closed || !f.draft { + return; + } + if !run_id.is_empty() { + if let Ok(Some(item)) = ctx + .state + .dynamo + .get_item() + .table_name(&ctx.state.config.runs_table_name) + .key("team_id", super::attr_s(ctx.team_id)) + .key("run_id", super::attr_s(run_id)) + .consistent_read(true) + .send() + .await + .map(|o| o.item) + { + if let Some(plan) = super::plan_continue::of_item(&item) { + f.plan_owed = plan.owed(); + } + } + if !f.plan_owed.is_empty() { + super::plan_continue::continue_if_owed( + ctx.state, + ctx.team_id, + run_id, + "its pull request waits for the rest of the plan", + ) + .await; + return; + } + } + let files = ctx + .github + .list_pull_files(ctx.owner, ctx.repo, ctx.pr) + .await + .unwrap_or_default(); + f.stubs = common::stub_check::stubs(&files) + .iter() + .map(common::stub_check::Stub::line) + .collect(); + if f.stubs.is_empty() || run_id.is_empty() || f.head.is_empty() { + return; + } + // CoderHelm's coder replaces each one: a round of its own, never a + // person's to-do and never deferred. + if matches!( + super::resume::queue_own_review_round( + ctx.state, + ctx.github, + ctx.team_id, + run_id, + &f.head, + &f.stubs, + ) + .await, + super::resume::OwnRound::Fixing | super::resume::OwnRound::Later(_) + ) { + f.own_fixing = true; + } +} + /// Reads what [`decide`] needs. A closed or ready pull request is decided /// from the pull request alone, so nothing with side effects runs for it /// (the failing-test check starts workflow runs, the link check rewrites @@ -1609,7 +1712,19 @@ async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { info!(pr = ctx.pr, run_id, why = %why, "No fix round for the own review's findings this moment; the next look takes them"); f.own_fixing = true; } + // CoderHelm's own limit: never deferred and never a person's hold. + // The draft waits on CoderHelm (alerted), never marked ready over it. + super::resume::OwnRound::Own(lines) => { + info!( + pr = ctx.pr, + run_id, + open = lines.len(), + "CoderHelm's own limit on its review's findings: the draft stays CoderHelm's wait" + ); + f.own_fixing = true; + } super::resume::OwnRound::Defer(lines) => { + let lines = lines.into_lines(); // Every finding left is settled with its own reason (a // person-gate reason, or the ticket's words): listed on the pull // request and holding nothing, so the draft waits only on what @@ -1886,6 +2001,14 @@ async fn make_ready(ctx: &Ctx<'_>, f: &Facts) -> Result<(), Refused> { wait_secs: backoff_secs(ctx.attempt), }); }; + // The mechanical check, right before GitHub is asked: never ready over + // a placeholder or an unbuilt part of the plan. + if let Some(why) = offer_blocked(f) { + return Err(Refused { + what: why, + wait_secs: backoff_secs(ctx.attempt), + }); + } gh.mark_pr_ready(node_id) .await .map(|_| ()) diff --git a/services/worker/src/passes/recover.rs b/services/worker/src/passes/recover.rs index f69b8890d..1a72bb9c6 100644 --- a/services/worker/src/passes/recover.rs +++ b/services/worker/src/passes/recover.rs @@ -683,6 +683,8 @@ pub struct SweepReport { pub redriven: usize, /// Runs waiting on the usage limit started again once it allowed runs. pub woken: usize, + /// Runs that went on to build the rest of their plan. + pub plans: usize, } /// The first start of each release (its code version) sends one self-heal @@ -885,6 +887,9 @@ pub async fn self_heal_sweep(state: &WorkerState) -> SweepReport { // Runs waiting on the usage limit: started again once it allows runs // (raised, cleared, or a new month). report.woken = super::run_wake::wake_limit_waits(state).await; + // Runs whose plan still owes a repository (and finished runs from + // before the record kept the plan): each builds what it owes. + report.plans = super::plan_continue::sweep(state).await; info!( failed = report.failed, waiting = report.waiting, @@ -893,6 +898,7 @@ pub async fn self_heal_sweep(state: &WorkerState) -> SweepReport { skipped = report.skipped, redriven = report.redriven, woken = report.woken, + plans = report.plans, "Self-heal sweep done" ); report diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 3b17af86b..56ff07ad8 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4388,8 +4388,34 @@ pub async fn run( by_ticket, noted, } => { - let lines = - super::own_review_ledger::settled_lines(&deferred, &by_ticket, ¬ed); + // Only a typed person-only reason defers; anything + // else is CoderHelm's own and keeps its review open. + let ledger_now = + super::own_review_ledger::load(state, &msg.team_id, &msg.run_id).await; + let lines = match super::own_review_ledger::typed_settle( + &ledger_now, + &deferred, + &by_ticket, + ¬ed, + ) { + Ok(lines) => lines, + Err(own) => { + end_on_own_limit( + state, + &ticket_msg, + &msg.run_id, + &own, + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + mark_events_processed(state, &msg.run_id, &events).await; + return Ok(()); + } + }; finish_on_own_findings( state, &ticket_msg, @@ -4409,19 +4435,16 @@ pub async fn run( } super::own_review_ledger::Plan::Unfixed { why } => { // CoderHelm's own rounds took every approach they - // have: its limit, never a person's to-do. What is - // left is listed as its note and the pull request - // goes ready for review. - let lines = - note_own_findings(state, &msg.team_id, &msg.run_id, &own_open, &why) - .await; - finish_on_own_findings( + // have: its limit, never a person's to-do and never + // deferred. The run stops naming what its review + // still asks for; its maintainers are alerted. + let own: Vec = + own_open.iter().map(|i| format!("{i}: {why}")).collect(); + end_on_own_limit( state, &ticket_msg, - &github, &msg.run_id, - &lines, - "CoderHelm's notes, each with what its rounds left", + &own, &pr_url, pr_number, &branch, @@ -7370,62 +7393,8 @@ async fn own_review_completion( &head, &l, ); - let body = pr["body"].as_str().unwrap_or(""); let why = match &said { Completion::Continue(why) => why.clone(), - // CoderHelm took every approach it has: what its review still asks - // for is listed as its note and the pull request goes ready for a - // person's review. Its own limit, never a person's to-do. - Completion::Defer(why) => { - let open: Vec = { - let listed = super::own_review::listed(body); - if listed.is_empty() { - l.findings - .iter() - .filter(|t| t.settled.is_none()) - .map(|t| t.item.clone()) - .collect() - } else { - listed - } - }; - let lines = note_own_findings(state, &msg.team_id, run_id, &open, why).await; - let now = super::own_review::defer_findings( - body, - &lines, - "CoderHelm's notes, each with what its rounds left", - ); - if now != body { - if let Err(e) = crate::passes::description::save( - &github, - &msg.repo_owner, - &msg.repo_name, - pr_number, - &now, - ) - .await - { - warn!(run_id, error = %e, "Could not list CoderHelm's notes on the pull request"); - } - } - super::add_progress_note( - state, - &msg.team_id, - run_id, - &super::own_review::finish_reason(&lines, why), - ) - .await; - mark_pr_ready( - state, - &msg.team_id, - &github, - &msg.repo_owner, - &msg.repo_name, - pr_number, - ) - .await; - return Completion::Complete; - } _ => return said, }; l.continues += 1; @@ -7555,11 +7524,27 @@ pub(crate) enum OwnRound { /// still working): the next look takes them. Why, for the log. A wait, /// never a person's to-do. Later(String), - /// Every finding left is settled with its own reason - /// (`own_review_ledger`): a person-gate reason, the ticket's words, or - /// CoderHelm's note on what its own rounds left. The lines, each with - /// its reason, are listed as deferred and the pull request goes ready. - Defer(Vec), + /// Every finding left is settled: each deferred one with a typed + /// person-only reason (`common::person_only::PersonOnly`), or ruled out + /// by the ticket's words. The lines are listed as deferred and the pull + /// request goes ready. Built only by [`typed_settle`] + /// (`own_review_ledger`): no other reason defers. + Defer(Deferred), + /// CoderHelm's own limit (its rounds, its budget, its record): never + /// deferred and never a person's. Its maintainers are alerted, the pull + /// request stays CoderHelm's to finish, and the review keeps asking. + Own(Vec), +} + +/// Lines a pull request lists as deferred, each with a typed person-only +/// reason or the ticket's words: made only from the ledger's typed settle. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Deferred(Vec); + +impl Deferred { + pub(crate) fn into_lines(self) -> Vec { + self.0 + } } /// The record fields that say what a finished run has left for a round on @@ -7740,25 +7725,32 @@ pub(crate) const OWN_FIX_HEAD: &str = "own_fix_head"; /// person has them; nothing queues another. pub(crate) const OWN_REVIEW_HANDED: &str = "own_review_handed"; -/// A finished run's PR is held on its own review's findings (`items`, on -/// `head`): queues one review-fix round for them while the run has rounds -/// left, once per head, under the same budgets as the run's own rounds, and -/// says whether one is on its way. Never promises a round nothing queued. -/// CoderHelm's own rounds left `items` open (`why`): recorded on the -/// ledger as its notes, so the review no longer lists them as holding the -/// draft, and returned as the lines the pull request lists. Never a -/// person's to-do. -async fn note_own_findings( +/// The run ends on its own limit: its review still asks for `own`, every +/// approach was taken, and none of it is a person's. Never "completed" and +/// never deferred: an internal alert for CoderHelm's maintainers, and the +/// supervisor's ending (`wait_for_review`), whose completion guard stops +/// the run naming what its review still asks for (`Stop::ReviewOpen`). +#[allow(clippy::too_many_arguments)] +async fn end_on_own_limit( state: &WorkerState, - team_id: &str, + msg: &TicketMessage, run_id: &str, - items: &[String], - why: &str, -) -> Vec { - let mut l = super::own_review_ledger::load(state, team_id, run_id).await; - l.note(items, why); - super::own_review_ledger::save(state, team_id, run_id, &l).await; - super::own_review_ledger::note_lines(items, why) + own: &[String], + pr_url: &str, + pr_number: u64, + branch: &str, + usage: &TokenUsage, + duration: u64, +) -> Result<(), Box> { + super::own_problems::alert_own_limit(state, &msg.team_id, run_id, own).await; + let reason = format!( + "CoderHelm's review still asks for changes its own rounds couldn't make:\n{}", + own.join("\n") + ); + wait_for_review( + state, msg, run_id, &reason, pr_url, pr_number, branch, usage, duration, + ) + .await } fn n_of(item: &std::collections::HashMap, k: &str) -> u64 { @@ -7768,6 +7760,14 @@ fn n_of(item: &std::collections::HashMap, k: &str) -> u6 .unwrap_or(0) } +/// A finished run's PR is held on its own review's findings (`items`, on +/// `head`): the run's own plan first (a repository it still owes is built), +/// then one review-fix round for them while the run has rounds left, once +/// per head, under the same budgets as the run's own rounds. Says whether +/// one is on its way; never promises a round nothing queued. What +/// CoderHelm's own rounds can't finish is its own limit ([`OwnRound::Own`]): +/// alerted, never deferred and never a person's to-do. Only a typed +/// person-only reason defers ([`OwnRound::Defer`]). pub(crate) async fn queue_own_review_round( state: &WorkerState, github: &GitHubClient, @@ -7776,14 +7776,31 @@ pub(crate) async fn queue_own_review_round( head: &str, items: &[String], ) -> OwnRound { - // Every way out that isn't a round: CoderHelm's own limit, listed on - // the pull request as its note, never held for a person. + // Every way out that isn't a round: CoderHelm's own limit, never + // deferred and never held for a person. Its maintainers are alerted. let note = |why: String| async move { - OwnRound::Defer(note_own_findings(state, team_id, run_id, items, &why).await) + let lines: Vec = items.iter().map(|i| format!("{i}: {why}")).collect(); + super::own_problems::alert_own_limit(state, team_id, run_id, &lines).await; + OwnRound::Own(lines) }; if run_id.is_empty() || items.is_empty() { return OwnRound::Later("no run or nothing listed".into()); } + // The run's own plan comes first: a finding its remaining tasks would + // satisfy is never deferred and never a person's. While the plan owes a + // repository CoderHelm can write to, the run builds it; the review reads + // the linked pull requests after. + match super::plan_continue::continue_if_owed( + state, + team_id, + run_id, + "its own review asks for changes the rest of the plan makes", + ) + .await + { + super::plan_continue::Owed::Building => return OwnRound::Fixing, + super::plan_continue::Owed::Nothing => {} + } let item = match state .dynamo .get_item() @@ -7865,9 +7882,15 @@ pub(crate) async fn queue_own_review_round( noted, } => { super::own_review_ledger::save(state, team_id, run_id, &ledger).await; - return OwnRound::Defer(super::own_review_ledger::settled_lines( - &deferred, &by_ticket, ¬ed, - )); + return match super::own_review_ledger::typed_settle( + &ledger, &deferred, &by_ticket, ¬ed, + ) { + Ok(lines) => OwnRound::Defer(Deferred(lines)), + Err(own) => { + super::own_problems::alert_own_limit(state, team_id, run_id, &own).await; + OwnRound::Own(own) + } + }; } super::own_review_ledger::Plan::Unfixed { why } => { super::own_review_ledger::save(state, team_id, run_id, &ledger).await; @@ -9661,8 +9684,7 @@ async fn wait_on_person( match Box::pin(own_review_completion(state, msg, run_id, pr_number, branch)).await { // Defer: CoderHelm's notes were listed and the pull request // marked ready (`own_review_completion`); the run completes. - super::own_review_ledger::Completion::Complete - | super::own_review_ledger::Completion::Defer(_) => {} + super::own_review_ledger::Completion::Complete => {} super::own_review_ledger::Completion::Continue(_) => return Ok(()), super::own_review_ledger::Completion::Hold(open) => { let why = format!("{reason}\n{open}"); @@ -10056,9 +10078,11 @@ async fn complete_run_with_status( // the run goes on, or ends saying what is open (`wait_on_person`). if status == common::run_status::COMPLETED && pr_number > 0 { match Box::pin(own_review_completion(state, msg, run_id, pr_number, branch)).await { - super::own_review_ledger::Completion::Complete - | super::own_review_ledger::Completion::Defer(_) => {} + super::own_review_ledger::Completion::Complete => {} super::own_review_ledger::Completion::Continue(_) => return Ok(()), + // CoderHelm's own limit: through the supervisor's ending, which + // stops the run naming what its review asks (never a person's + // wait without a human-only reason, never deferred). super::own_review_ledger::Completion::Hold(why) => { return wait_for_review( state, msg, run_id, &why, pr_url, pr_number, branch, usage, duration, diff --git a/services/worker/src/passes/review_acceptance.rs b/services/worker/src/passes/review_acceptance.rs index 957826830..989037d58 100644 --- a/services/worker/src/passes/review_acceptance.rs +++ b/services/worker/src/passes/review_acceptance.rs @@ -94,6 +94,40 @@ pub fn section(criteria: &[String]) -> String { ) } +/// The prompt's section for a pull request that is one part of its +/// ticket's change (a plan across repositories, `common::plan_repos`): an +/// acceptance line another part delivers is met there, and a part not built +/// yet is CoderHelm's to build, never a finding on this pull request. Empty +/// for a single-repository change. +pub fn parts_section( + this_repo: &str, + plan: &common::plan_repos::PlanRepos, + prs: &[common::run_prs::RunPr], +) -> String { + let Some(label) = plan.part_label(this_repo) else { + return String::new(); + }; + let others: Vec = plan + .parts + .iter() + .filter(|p| !p.repo.eq_ignore_ascii_case(this_repo)) + .map(|p| { + let at = plan.part_label(&p.repo).unwrap_or_default(); + match prs.iter().find(|r| r.repo.eq_ignore_ascii_case(&p.repo)) { + Some(r) => format!("- {}#{} ({at})", r.repo, r.pr_number), + None => format!("- {} ({at}, CoderHelm is building it)", p.repo), + } + }) + .collect(); + format!( + "\n\n## THIS PULL REQUEST IS ONE PART OF ITS TICKET\nIt is {label} of the ticket's change. \ + The other parts:\n{}\nAn acceptance line another part delivers is met by that part: report \ + it `met`: \"yes\" and name the part in `why`. A part of the plan not built yet is \ + CoderHelm's to build, never a finding on this pull request.\n", + others.join("\n") + ) +} + fn words(text: &str) -> Vec { let mut w: Vec = text .to_lowercase() @@ -383,4 +417,27 @@ mod tests { generated.push(d("blocks/faq.yaml", "added", "@@ -0,0 +1 @@\n+name: faq\n")); assert!(hand_written_outputs(&[g], &generated).is_empty()); } + + #[test] + fn a_part_of_a_two_repo_change_is_read_with_its_other_part() { + let plan = common::plan_repos::PlanRepos::of_tasks( + "acme/bookstore-api", + "## acme/bookstore-infra\n- [x] 1.1 Module\n## acme/bookstore-api\n- [ ] 2.1 Handler\n", + ) + .unwrap(); + let s = parts_section("acme/bookstore-infra", &plan, &[]); + assert!(s.contains("part 1 of 2"), "{s}"); + assert!( + s.contains("acme/bookstore-api (part 2 of 2, CoderHelm is building it)"), + "{s}" + ); + let pr = common::run_prs::RunPr { + repo: "acme/bookstore-api".into(), + pr_number: 12, + ..Default::default() + }; + assert!(parts_section("acme/bookstore-infra", &plan, &[pr]) + .contains("acme/bookstore-api#12 (part 2 of 2)")); + assert_eq!(parts_section("acme/other", &plan, &[]), ""); + } } diff --git a/services/worker/src/passes/review_agent.rs b/services/worker/src/passes/review_agent.rs index 10a734582..f66effded 100644 --- a/services/worker/src/passes/review_agent.rs +++ b/services/worker/src/passes/review_agent.rs @@ -2648,16 +2648,23 @@ pub fn to_postable( body, }); } else { - let loc = if f.line > 0 { - format!("`{}:{}`", f.file, f.line) - } else { - format!("`{}`", f.file) + // A finding on no file (a ticket's acceptance line, the whole + // change) has no place to name: never an empty `` in its place. + let file = f.file.trim(); + let loc = match (file, f.line) { + ("", _) => String::new(), + (file, 0) => format!("`{file}` β€” "), + (file, line) => format!("`{file}:{line}` β€” "), + }; + let title = match f.title.trim() { + "" => label.trim().trim_end_matches(':').to_string(), + t => t.to_string(), }; unanchored.push_str(&format!( - "- {} {} β€” {}{}\n", + "- {} {}{}{}\n", emoji, loc, - f.title, + title, if holds { "" } else { diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 408f1484a..0b13fae0a 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3500,7 +3500,22 @@ async fn run_once( // The ticket's acceptance lines, which the reviewer reads one by one // against the diff (`review_acceptance`). let ticket_criteria = super::stop_judge::acceptance(&format!("{ticket_context}\n{pr_body}")); - let acceptance_context = super::review_acceptance::section(&ticket_criteria); + let acceptance_context = format!( + "{}{}", + super::review_acceptance::section(&ticket_criteria), + match &own_run { + Some(run_id) => { + parts_context( + state, + &msg.team_id, + run_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + ) + .await + } + None => String::new(), + } + ); let extra_context = format!( "{graph_context}{ci_context}{quality_context}{plan_context}{ticket_context}{acceptance_context}{round_context}" ); @@ -5893,11 +5908,11 @@ async fn claim_self_review_round( } /// The self-review rounds on CoderHelm's own PR ended by the supervisor's -/// rule: what is open is deferred on the pull request with the reason -/// (`own_review::defer_findings`, so it no longer holds the draft), the -/// pull request says so once, and the ready decision takes it (the draft -/// stays only while required checks are red). Never "a comment starts the -/// next round". +/// rule: what is open is CoderHelm's own limit, never deferred (only a +/// typed person-only reason defers) and never a person's to-do. Its +/// maintainers are alerted, the pull request says so once, and the ready +/// decision keeps the draft as CoderHelm's wait. Never "a comment starts +/// the next round". async fn end_self_review_rounds( state: &WorkerState, github: &GitHubClient, @@ -5906,31 +5921,21 @@ async fn end_self_review_rounds( why: &str, ) { if !open.is_empty() { - match github - .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) - .await - { - Ok(p) => { - let body = p["body"].as_str().unwrap_or(""); - let now = super::own_review::defer_findings(body, open, why); - if now != body { - if let Err(e) = crate::passes::description::save( - github, - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - &now, + super::own_problems::alert_own_limit( + state, + &msg.team_id, + "", + &open + .iter() + .map(|f| { + format!( + "{}/{}#{}: {f} ({why})", + msg.repo_owner, msg.repo_name, msg.pr_number ) - .await - { - warn!(pr = msg.pr_number, error = %e, "Could not list the deferred findings on the pull request"); - } - } - } - Err(e) => { - warn!(pr = msg.pr_number, error = %e, "Could not read the pull request to defer the findings") - } - } + }) + .collect::>(), + ) + .await; } if claim_once( state, @@ -5944,10 +5949,10 @@ async fn end_self_review_rounds( { let replier = super::conversation::Replier::new(state, &msg.team_id); let mut facts = review_facts(msg, "") - .state("the self-review rounds ended; the open findings are deferred") + .state("the self-review rounds ended; the open findings are CoderHelm's own to finish") .decision(why.to_string()); for f in open { - facts = facts.decision(format!("Deferred: {f}")); + facts = facts.decision(format!("Still open, CoderHelm's to finish: {f}")); } let _ = Box::pin(crate::passes::conversation::reply_github( &replier, @@ -5962,7 +5967,7 @@ async fn end_self_review_rounds( } info!( pr = msg.pr_number, - why, "Self-review rounds ended β€” open findings deferred" + why, "Self-review rounds ended: open findings are CoderHelm's own limit, alerted" ); super::ready::request(state, msg).await; } @@ -5979,9 +5984,9 @@ pub(crate) fn self_review_end_note(open: &[String], why: &str) -> String { } let list: Vec = open.iter().map(|i| format!("- {i}")).collect(); format!( - "CoderHelm finished its fix rounds on its own review of this pull request ({why}). These \ - findings are deferred, listed under \"Deferred\" in the description with that reason:\n{}\n\n\ - The ready decision takes it from here: the draft is held only while required checks fail.", + "CoderHelm's fix rounds on its own review of this pull request stopped ({why}). These \ + findings are still open and still CoderHelm's to finish; its maintainers were alerted:\n{}\n\n\ + The pull request stays a draft until they are fixed. Nothing is needed from you.", list.join("\n") ) } @@ -6613,16 +6618,22 @@ pub(crate) fn settle_own_findings( Settled::ByTicket { quote } => { format!("Not a change to make: the ticket says \"{quote}\".") } - Settled::Deferred { reason, what } => format!( - "A follow-up only a person can do ({reason}){}.", - if what.is_empty() { - String::new() - } else { - format!(": {what}") - } - ), + // Only through the typed hand-off (#930): see `untyped` below. + Settled::Deferred { .. } => String::new(), Settled::Fixed | Settled::Noted { .. } => String::new(), }; + // A deferral whose reason doesn't type as a person-only one is no + // deferral: the finding stays open and holds, CoderHelm's to finish. + let typed = |line: &str| match ledger.person_of(line) { + Some(Ok(p)) => Some(format!( + "A follow-up only a person can do: {}.", + p.line().trim_end_matches('.') + )), + _ => None, + }; + let untyped = |line: &str| { + matches!(ledger.settled_item(line), Some(Settled::Deferred { .. })) && typed(line).is_none() + }; let mut settled = Vec::new(); for f in findings.iter_mut() { let line = super::own_review::thread_line(&f.file, f.line, &f.title); @@ -6641,11 +6652,21 @@ pub(crate) fn settle_own_findings( settled.push(line); continue; } - super::review_policy::demote(f, &why(s)); + let note = match s { + Settled::Deferred { .. } => match typed(&line) { + Some(n) => n, + None => continue, + }, + other => why(other), + }; + super::review_policy::demote(f, ¬e); settled.push(line); } } own_open.retain(|o| { + if untyped(o) { + return true; + } let s = ledger.settled_item(o); // A settled or noted finding leaves the list that holds the draft, // and its thread holds the merge no more. @@ -6731,6 +6752,28 @@ async fn run_ticket_id(state: &WorkerState, team_id: &str, run_id: &str) -> Stri .unwrap_or_default() } +/// The run's other parts when its plan spans several repositories +/// (`review_acceptance::parts_section`); empty otherwise. +async fn parts_context(state: &WorkerState, team_id: &str, run_id: &str, repo: &str) -> String { + let Ok(Some(item)) = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", super::attr_s(team_id)) + .key("run_id", super::attr_s(run_id)) + .send() + .await + .map(|o| o.item) + else { + return String::new(); + }; + let Some(plan) = super::plan_continue::of_item(&item) else { + return String::new(); + }; + let prs = common::run_prs::from_item(&item); + super::review_acceptance::parts_section(repo, &plan, &prs) +} + /// Newest run for a PR, via the runs-table repo-index GSI. None if untracked. pub(crate) async fn lookup_run_by_pr( state: &WorkerState, From 33b2dd029f4fc9bdaf2f3a234f0d94e721096053 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 3 Dec 2026 13:37:00 -0500 Subject: [PATCH 2/3] Keep a hand-off's words out of a test assertion's message --- services/common/src/plan_repos.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/common/src/plan_repos.rs b/services/common/src/plan_repos.rs index d0709fb12..7b876eeac 100644 --- a/services/common/src/plan_repos.rs +++ b/services/common/src/plan_repos.rs @@ -274,7 +274,8 @@ mod tests { match p.next() { Next::Person(who) => { assert_eq!(who.code(), "grant"); - assert!(who.line().contains("acme/bookstore-api"), "{}", who.line()); + // The hand-off's words stay out of the test's own output. + assert!(who.line().contains("acme/bookstore-api")); } other => panic!("{other:?}"), } From 57505e0e3416467a1d4a59e14ea326fa003bf965 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 3 Dec 2026 15:20:04 -0500 Subject: [PATCH 3/3] A removed placeholder ships nothing, and a claim whose step can't be queued is put back - The placeholder check reads each changed file's status: a file the diff removes ships nothing, and only a file added, renamed or copied under a placeholder path is a placeholder file. A file only changed there is read by the lines it adds. The diff is read in full (every page), and a listing that fails keeps the draft waiting for the next read instead of passing it unread. - The Python handler rule reads the names a function runtime calls (handler, lambda_handler), and a stub or stubs folder is no longer read by its name: generated RPC stubs and no-op hooks are real code. - A plan continuation whose step couldn't be queued puts back what its claim changed (status, its index key, the pass, the wait, the count), so the run is never left running with no step. - A run whose continuations are spent while its plan still owes a repository stops with a typed reason, never waiting behind the end gate. - A task list's section is a repository only under the plan repository's owner: folder headings are not parts. - The waiting line's API example and two comments on deferral now say what the code does. --- docs/api/openapi.json | 2 +- services/common/src/plan_repos.rs | 19 +- services/common/src/stub_check.rs | 137 +++++++++++-- services/gateway/src/routes/api.rs | 6 +- .../incidents/xj_plan_builds_every_repo.rs | 37 +++- services/worker/src/passes/plan_continue.rs | 185 +++++++++++++++++- services/worker/src/passes/ready.rs | 27 ++- services/worker/src/passes/resume.rs | 14 +- 8 files changed, 386 insertions(+), 41 deletions(-) diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 9a8ea2ed4..5fd099816 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -4662,7 +4662,7 @@ ] }, "waiting_line": { - "description": "What the run's pull request waits on, in one plain line, and\nwhether it is ready for review: \"Waiting on: an approving review from\na person on #12 (this repo requires one before CoderHelm merges).\nReady for review: checks passed, preview checked.\" Built from\n`merge_standing`, `draft_hold` and `preview`. Null before the run\nhas a pull request.", + "description": "What the run's pull request waits on, in one plain line, and\nwhether it is ready for review: \"Needs 1 approval from a person\n(repo rule) on #12. Ready for review: checks passed, preview\nchecked.\" Built from\n`merge_standing`, `draft_hold` and `preview`. Null before the run\nhas a pull request.", "examples": [ null ], diff --git a/services/common/src/plan_repos.rs b/services/common/src/plan_repos.rs index 7b876eeac..5a94e2889 100644 --- a/services/common/src/plan_repos.rs +++ b/services/common/src/plan_repos.rs @@ -128,14 +128,23 @@ impl PlanRepos { } /// The plan read from a task list with `## owner/name` sections, one - /// part per section in order; `None` for a single-repository plan. + /// part per section in order; `None` for a single-repository plan. A + /// section is a repository only under the plan repository's owner (a + /// run reaches the repositories of one installation): `## src/api` is a + /// folder heading, never a part. pub fn of_tasks(plan_repo: &str, tasks_md: &str) -> Option { + let owner = plan_repo.split_once('/').map(|(o, _)| o); let mut parts: Vec = Vec::new(); for line in tasks_md.lines() { if let Some(h) = line.strip_prefix("## ") { let h = h.trim(); if h.split_once('/').is_some_and(|(o, n)| { - !o.is_empty() && !n.is_empty() && !n.contains(' ') && !o.contains(' ') + !o.is_empty() + && !n.is_empty() + && !n.contains(' ') + && !o.contains(' ') + && !n.contains('/') + && owner.is_none_or(|w| w.eq_ignore_ascii_case(o)) }) { parts.push(Part { repo: h.to_string(), @@ -302,6 +311,12 @@ mod tests { #[test] fn a_single_repo_plan_is_none() { assert!(PlanRepos::of_tasks("acme/web", "- [ ] 1.1 Fix the cart\n").is_none()); + // Folder headings in a one-repository task list are not parts. + assert!(PlanRepos::of_tasks( + "acme/web", + "## src/api\n- [ ] 1.1 Cart route\n## docs/site\n- [ ] 2.1 Cart page\n" + ) + .is_none()); assert!(PlanRepos::from_json("{\"plan_repo\":\"a/b\",\"parts\":[]}").is_none()); } } diff --git a/services/common/src/stub_check.rs b/services/common/src/stub_check.rs index 43f798943..37d64db1e 100644 --- a/services/common/src/stub_check.rs +++ b/services/common/src/stub_check.rs @@ -7,13 +7,15 @@ //! (`modules//placeholder/index.js`): the change looked complete in //! the repository it was in, and the real code was nowhere. //! -//! [`stubs`] reads a pull request's diff (each changed file and its patch) -//! and names every place that stands in for real code: a file under a -//! `placeholder` or `stub` folder or named so, an added handler whose body -//! is empty, `throw new Error("not implemented")` and its kin in other +//! [`stubs`] reads a pull request's diff (each changed file, its status and +//! its patch) and names every place that stands in for real code: a file +//! the diff adds under a `placeholder` folder or named so, an added handler +//! whose body is empty, `throw new Error("not implemented")` and its kin in other //! languages, and a `TODO` that says the implementation is still to come. //! Tests, fixtures, mocks and documents are not read: a stub there is the -//! test's own. The ready decision (`ready::decide`) never offers a pull +//! test's own. A file the diff removes ships nothing, and a file it only +//! changes is read by the lines it adds, never by its path. The ready +//! decision (`ready::decide`) never offers a pull //! request for review while this finds anything; CoderHelm's coder replaces //! each one, or, when the real code belongs to another repository of the //! same plan, that repository is built first and the pull requests are @@ -23,6 +25,35 @@ use std::sync::LazyLock; use regex::Regex; +/// One file a pull request changes, as GitHub lists it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Changed { + pub path: String, + /// GitHub's status: `added`, `removed`, `modified`, `renamed`, + /// `copied`, `changed` or `unchanged`. + pub status: String, + /// The unified patch; empty when GitHub leaves it out (binary or too + /// large). + pub patch: String, +} + +impl Changed { + /// One entry of GitHub's pull request files listing. + pub fn of_github(f: &serde_json::Value) -> Option { + Some(Changed { + path: f["filename"].as_str()?.to_string(), + status: f["status"].as_str().unwrap_or("").to_string(), + patch: f["patch"].as_str().unwrap_or("").to_string(), + }) + } + + /// The file is new at its path in this diff: added, or renamed or + /// copied into it. + fn new_at_path(&self) -> bool { + matches!(self.status.as_str(), "added" | "renamed" | "copied") + } +} + /// One place that stands in for real code. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stub { @@ -76,8 +107,10 @@ static EMPTY_HANDLER: LazyLock = LazyLock::new(|| { .expect("regex") }); +/// A Python entry point by the names a function runtime calls: a no-op +/// hook such as `error_handler` or an abstract method is real code. static PY_HANDLER: LazyLock = - LazyLock::new(|| Regex::new(r"^\s*(async\s+)?def\s+\w*handler\w*\s*\(").expect("regex")); + LazyLock::new(|| Regex::new(r"^\s*(async\s+)?def\s+(lambda_)?handler\s*\(").expect("regex")); /// A path a stub belongs in: tests, fixtures, mocks, documents. fn not_read(path: &str) -> bool { @@ -108,8 +141,9 @@ fn not_read(path: &str) -> bool { .any(|x| name.ends_with(x)) } -/// A file that is itself a placeholder: under a `placeholder` or `stub` -/// folder, or named so. +/// A file that is itself a placeholder: under a `placeholder` folder, or +/// named so. A `stub` or `stubs` folder is not read by its name: generated +/// RPC stubs are real code. fn placeholder_path(path: &str) -> bool { let p = path.to_ascii_lowercase(); let segs: Vec<&str> = p.split('/').collect(); @@ -119,19 +153,21 @@ fn placeholder_path(path: &str) -> bool { .map(|n| n.split('.').next().unwrap_or(n)) .unwrap_or(""); dirs.iter() - .any(|d| matches!(*d, "placeholder" | "placeholders" | "stub" | "stubs")) - || matches!(stem, "placeholder" | "stub") + .any(|d| matches!(*d, "placeholder" | "placeholders")) + || stem == "placeholder" } -/// Every place in the diff (`(path, patch)` per changed file) that stands -/// in for real code. See the module comment. -pub fn stubs(files: &[(String, String)]) -> Vec { +/// Every place in the diff (one [`Changed`] per file) that stands in for +/// real code. See the module comment. +pub fn stubs(files: &[Changed]) -> Vec { let mut out = Vec::new(); - for (path, patch) in files { - if not_read(path) { + for file in files { + let (path, patch) = (&file.path, &file.patch); + // A removed file ships nothing, whatever its path was. + if file.status == "removed" || not_read(path) { continue; } - if placeholder_path(path) { + if file.new_at_path() && placeholder_path(path) { out.push(Stub { path: path.clone(), line: 0, @@ -210,14 +246,18 @@ pub fn stubs(files: &[(String, String)]) -> Vec { mod tests { use super::*; - fn f(path: &str, added: &[&str]) -> (String, String) { + fn f(path: &str, added: &[&str]) -> Changed { let mut patch = format!("@@ -0,0 +1,{} @@\n", added.len()); for a in added { patch.push('+'); patch.push_str(a); patch.push('\n'); } - (path.to_string(), patch) + Changed { + path: path.to_string(), + status: "added".into(), + patch, + } } #[test] @@ -308,4 +348,65 @@ mod tests { ]); assert!(s.is_empty(), "{s:?}"); } + + #[test] + fn a_removed_placeholder_or_a_changed_file_in_its_folder_is_not_a_stub() { + // The fix for a shipped placeholder removes it and adds the real + // code: the listing still names the removed path. + let removed = Changed { + path: "modules/stock_sync/placeholder/index.js".into(), + status: "removed".into(), + patch: "@@ -1,1 +0,0 @@\n-exports.handler = async () => ({ statusCode: 200 });\n" + .into(), + }; + let real = f( + "modules/stock_sync/index.js", + &["exports.handler = async (event) => syncStock(event.date);"], + ); + // A file already under such a folder, changed only by real lines. + let changed = Changed { + path: "vendor/placeholder/config.js".into(), + status: "modified".into(), + patch: "@@ -3,1 +3,1 @@\n-const RETRIES = 2;\n+const RETRIES = 3;\n".into(), + }; + assert!(stubs(&[removed, real, changed]).is_empty()); + // A file renamed into a placeholder folder is new at its path. + let moved = Changed { + path: "modules/stock_sync/placeholder/index.js".into(), + status: "renamed".into(), + patch: String::new(), + }; + assert_eq!(stubs(&[moved]).len(), 1); + } + + #[test] + fn generated_stubs_and_no_op_hooks_are_real_code() { + let s = stubs(&[ + f( + "src/rpc/stubs/inventory_pb2_grpc.py", + &["class InventoryStub(object):", " pass"], + ), + f( + "src/app/hooks.py", + &["def error_handler(request, exc):", " pass"], + ), + f( + "src/app/base.py", + &[" def handle_handler(self, event):", " ..."], + ), + ]); + assert!(s.is_empty(), "{s:?}"); + } + + #[test] + fn the_github_listing_carries_the_status() { + let v = serde_json::json!({ + "filename": "modules/stock_sync/placeholder/index.js", + "status": "removed", + "patch": "@@ -1 +0,0 @@\n-x\n" + }); + let c = Changed::of_github(&v).unwrap(); + assert_eq!(c.status, "removed"); + assert!(stubs(&[c]).is_empty()); + } } diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 8a261077a..58b537a09 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1599,9 +1599,9 @@ pub struct Run { #[schema(example = json!(null))] pub own_review: Option, /// What the run's pull request waits on, in one plain line, and - /// whether it is ready for review: "Waiting on: an approving review from - /// a person on #12 (this repo requires one before CoderHelm merges). - /// Ready for review: checks passed, preview checked." Built from + /// whether it is ready for review: "Needs 1 approval from a person + /// (repo rule) on #12. Ready for review: checks passed, preview + /// checked." Built from /// `merge_standing`, `draft_hold` and `preview`. Null before the run /// has a pull request. #[schema(example = json!(null))] diff --git a/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs b/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs index 9f582c76e..dff56bf72 100644 --- a/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs +++ b/services/worker/src/passes/incidents/xj_plan_builds_every_repo.rs @@ -167,11 +167,13 @@ fn an_own_review_block_whose_fix_is_in_the_other_repo_is_built_there_not_deferre #[test] fn a_placeholder_is_never_offered_for_review() { - let files = vec![( - "modules/stock_sync/placeholder/index.js".to_string(), - "@@ -0,0 +1,3 @@\n+exports.handler = async (event) => {\n+ return { ok: true };\n+};\n" - .to_string(), - )]; + let files = vec![common::stub_check::Changed { + path: "modules/stock_sync/placeholder/index.js".to_string(), + status: "added".to_string(), + patch: + "@@ -0,0 +1,3 @@\n+exports.handler = async (event) => {\n+ return { ok: true };\n+};\n" + .to_string(), + }]; let stubs: Vec = common::stub_check::stubs(&files) .iter() .map(common::stub_check::Stub::line) @@ -188,6 +190,31 @@ fn a_placeholder_is_never_offered_for_review() { ..Default::default() }; assert!(matches!(ready::decide(&f), Decision::Wait { .. })); + // The fix removes the placeholder and adds the real code: the listing + // still names the removed path, and it is no longer a stub. + let fixed = vec![ + common::stub_check::Changed { + path: "modules/stock_sync/placeholder/index.js".to_string(), + status: "removed".to_string(), + patch: "@@ -1,3 +0,0 @@\n-exports.handler = async (event) => {\n- return { ok: true };\n-};\n" + .to_string(), + }, + common::stub_check::Changed { + path: "modules/stock_sync/index.js".to_string(), + status: "added".to_string(), + patch: "@@ -0,0 +1 @@\n+exports.handler = async (event) => syncStock(event.date);\n" + .to_string(), + }, + ]; + assert!(common::stub_check::stubs(&fixed).is_empty()); + // A diff that couldn't be listed is never offered unread. + let unread = Facts { + stubs: Vec::new(), + diff_unread: true, + ..f.clone() + }; + assert!(ready::offer_blocked(&unread).is_some()); + assert!(matches!(ready::decide(&unread), Decision::Wait { .. })); // The mechanical check sits right before GitHub's ready-for-review, in // the one place that asks for it. let src = include_str!("../ready.rs"); diff --git a/services/worker/src/passes/plan_continue.rs b/services/worker/src/passes/plan_continue.rs index c1b4cf2b5..2b914f445 100644 --- a/services/worker/src/passes/plan_continue.rs +++ b/services/worker/src/passes/plan_continue.rs @@ -149,6 +149,7 @@ pub async fn record(state: &WorkerState, team_id: &str, run_id: &str, plan: &Pla /// Claims one continuation: the run goes back to running, once per /// decider. False when another decision took it, or the bound is reached. +/// A claim whose step can't be queued is put back ([`release`]). async fn claim(state: &WorkerState, item: &HashMap) -> bool { let team_id = s(item, "team_id"); let run_id = s(item, "run_id"); @@ -193,6 +194,137 @@ async fn claim(state: &WorkerState, item: &HashMap) -> b } } +/// What a claim changed, as the record had it before: the update that puts +/// it back (the status and its index key, the pass, the wait and its +/// reminder, and the continuation it counted) and its values. Pure: the +/// tests read it. +pub fn release_update( + item: &HashMap, +) -> (String, Vec<(&'static str, AttributeValue)>) { + let run_id = s(item, "run_id"); + let was = s(item, "status"); + let mut set = vec![ + "#s = :was", + "status_run_id = :was_sri", + "#c = #c - :one", + "updated_at = :t", + ]; + let mut remove = Vec::new(); + let mut values = vec![ + (":was", attr_s(was)), + (":was_sri", common::run_ending::restored_sri(was, run_id)), + (":one", attr_n(1)), + (":t", attr_s(&chrono::Utc::now().to_rfc3339())), + ]; + for (field, set_expr, key) in [ + ("current_pass", "current_pass = :was_cp", ":was_cp"), + ("waiting_on", "waiting_on = :was_wo", ":was_wo"), + ("wait_reminded_at", "wait_reminded_at = :was_wr", ":was_wr"), + ] { + match item.get(field) { + Some(v) => { + set.push(set_expr); + values.push((key, v.clone())); + } + // The claim wrote the pass; the record had none. + None if field == "current_pass" => remove.push(field), + None => {} + } + } + let mut expr = format!("SET {}", set.join(", ")); + if !remove.is_empty() { + expr.push_str(&format!(" REMOVE {}", remove.join(", "))); + } + (expr, values) +} + +/// Puts back a claim whose step couldn't be queued: the run is never left +/// running with no step (the sweep reads a running run as building), and +/// the continuation isn't spent. Only the claim this decider made is put +/// back: the run must still be running on it. +async fn release(state: &WorkerState, item: &HashMap) { + let team_id = s(item, "team_id"); + let run_id = s(item, "run_id"); + let (expr, values) = release_update(item); + let mut req = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression(expr) + .condition_expression("#s = :run AND status_run_id = :claimed AND #c > :zero") + .expression_attribute_names("#s", "status") + .expression_attribute_names("#c", CONTINUES_FIELD) + .expression_attribute_values(":run", attr_s(common::run_status::RUNNING)) + .expression_attribute_values( + ":claimed", + common::run_ending::working(common::run_ending::Working::Running, run_id).sri_attr(), + ) + .expression_attribute_values(":zero", attr_n(0)); + for (k, v) in values { + req = req.expression_attribute_values(k, v); + } + if let Err(e) = req.send().await { + warn!(run_id, error = %e, "Could not put back the claim on the rest of the plan"); + } +} + +/// The run's continuations are spent and its plan still owes a repository +/// it isn't building: it stops with a typed reason instead of waiting +/// forever behind the end gate. Pure: the sweep and the tests read it. +pub fn spent(item: &HashMap, plan: &PlanRepos) -> bool { + use common::run_status as st; + let status = s(item, "status"); + matches!(plan.next(), Next::Build(_)) + && n(item, CONTINUES_FIELD) >= u64::from(MAX_CONTINUES) + && !st::ended_by_person(status) + && ![ + st::MERGED, + st::RETRIED, + st::ARCHIVED, + st::FAILED, + st::RUNNING, + st::QUEUED, + st::PENDING, + ] + .contains(&status) +} + +/// Ends a run whose plan can't be built in its continuations: a typed stop +/// (never gated on the plan), naming the repositories it still owes. +async fn stop_spent(state: &WorkerState, item: &HashMap, plan: &PlanRepos) { + let run_id = s(item, "run_id").to_string(); + let Some((msg, _)) = super::recheck::message_of(item) else { + warn!( + run_id, + "The run's plan can't be built and its record can't be stopped from here" + ); + return; + }; + let owed = plan.owed().join(" and "); + let why = format!( + "The plan still has tasks in {owed}, and {MAX_CONTINUES} steps couldn't build them" + ); + warn!(run_id, owed = %owed, "The plan's continuations are spent: the run stops"); + super::stop_run( + state, + &msg, + &run_id, + &why, + common::run_ending::Stopped { + reason: common::run_ending::Stop::Guard { why: why.clone() }, + tried: common::run_ending::Tried { + steps: vec![format!("{MAX_CONTINUES} steps building {owed}")], + ..Default::default() + }, + }, + &crate::models::TokenUsage::default(), + 0, + ) + .await; +} + /// Starts the step that builds what the plan owes, from the plan the run /// already has. True when it is queued. async fn start( @@ -232,8 +364,9 @@ async fn start( if !super::send_ticket_after(state, &next, steps::STEP_DELAY_SECS as u64).await { warn!( run_id, - "The step that builds the rest of the plan couldn't be queued" + "The step that builds the rest of the plan couldn't be queued: the claim is put back" ); + release(state, item).await; return false; } steps::mark_queued(state, &msg.team_id, &run_id, step).await; @@ -304,6 +437,9 @@ async fn continue_item( if wants_continue(item, &plan) && start(state, item, &plan, why).await { return Owed::Building; } + if spent(item, &plan) { + stop_spent(state, item, &plan).await; + } Owed::Nothing } @@ -426,8 +562,49 @@ mod tests { // A run a person closed, or one past its bound, is never resumed. let closed = item("closed", &plan, &[("acme/bookstore-infra", 41)]); assert!(!wants_continue(&closed, &of_item(&closed).unwrap())); - let mut spent = stuck.clone(); - spent.insert(CONTINUES_FIELD.into(), attr_n(u64::from(MAX_CONTINUES))); - assert!(!wants_continue(&spent, &read)); + let mut used = stuck.clone(); + used.insert(CONTINUES_FIELD.into(), attr_n(u64::from(MAX_CONTINUES))); + assert!(!wants_continue(&used, &read)); + // Past its bound it stops with a typed reason, once: never while a + // step is on it, and never again once failed. + assert!(spent(&used, &read)); + assert!(!spent(&stuck, &read)); + for status in ["running", "queued", "failed", "closed"] { + let mut other = used.clone(); + other.insert("status".into(), attr_s(status)); + assert!(!spent(&other, &read), "{status}"); + } + } + + #[test] + fn a_claim_whose_step_isnt_queued_is_put_back_as_the_record_had_it() { + let plan = PlanRepos::of_tasks("acme/bookstore-api", TASKS).unwrap(); + let mut waiting = item("needs_input", &plan, &[("acme/bookstore-infra", 41)]); + waiting.insert("waiting_on".into(), attr_s("a person's answer")); + waiting.insert("current_pass".into(), attr_s("review")); + let (expr, values) = release_update(&waiting); + assert!(expr.starts_with("SET #s = :was, status_run_id = :was_sri, #c = #c - :one")); + assert!(expr.contains("waiting_on = :was_wo")); + assert!(expr.contains("current_pass = :was_cp")); + assert!(!expr.contains("REMOVE")); + let v: HashMap<_, _> = values.into_iter().collect(); + assert_eq!(v[":was"], attr_s("needs_input")); + assert_eq!(v[":was_sri"], attr_s("needs_input#R1")); + assert_eq!(v[":was_wo"], attr_s("a person's answer")); + assert_eq!(v[":was_cp"], attr_s("review")); + // A record without a pass gets none back; no wait is invented. + let done = item("completed", &plan, &[("acme/bookstore-infra", 41)]); + let (expr, values) = release_update(&done); + assert!(expr.ends_with(" REMOVE current_pass"), "{expr}"); + assert!(!expr.contains("waiting_on")); + assert!(values + .iter() + .any(|(k, v)| *k == ":was" && *v == attr_s("completed"))); + // The release runs on the failed send, before `start` says false. + let src = include_str!("plan_continue.rs"); + let send = src.find("if !super::send_ticket_after(").unwrap(); + let back = src[send..].find("release(state, item).await;").unwrap(); + let no = src[send..].find("return false;").unwrap(); + assert!(back < no); } } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 4d31b235e..e0ead6c5d 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -192,6 +192,9 @@ pub struct Facts { /// Places the diff ships a placeholder or stub in place of real code /// (`common::stub_check`), one line each. pub stubs: Vec, + /// The diff couldn't be listed to look for placeholders: the draft + /// waits for the next read, never offered unread. + pub diff_unread: bool, /// Repositories of the run's plan still owed (`common::plan_repos`): /// the pull requests are offered for review together, once each part /// is built and linked. @@ -216,6 +219,12 @@ pub fn offer_blocked(f: &Facts) -> Option { f.stubs.join("; ") )); } + if f.diff_unread { + return Some( + "its changed files couldn't be read to check it ships no placeholder; CoderHelm reads them again on the next pass" + .into(), + ); + } None } @@ -1338,11 +1347,23 @@ async fn offer_checks(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { return; } } - let files = ctx + // Every changed file with its status (a removed placeholder ships + // nothing), every page of them. + let files: Vec = match ctx .github - .list_pull_files(ctx.owner, ctx.repo, ctx.pr) + .list_pull_files_all(ctx.owner, ctx.repo, ctx.pr) .await - .unwrap_or_default(); + { + Ok(v) => v + .iter() + .filter_map(common::stub_check::Changed::of_github) + .collect(), + Err(e) => { + warn!(pr = ctx.pr, error = %e, "Could not list the pull request's files to look for placeholders: it waits for the next read"); + f.diff_unread = true; + return; + } + }; f.stubs = common::stub_check::stubs(&files) .iter() .map(common::stub_check::Stub::line) diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 56ff07ad8..c9cbeda16 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4365,8 +4365,10 @@ pub async fn run( } else { // Own review findings, by the supervisor's rule: another round // while the rounds make progress (up to twice the cap), a round - // without progress changes approach, and when the rounds end - // what is open is deferred and the run finishes. + // without progress changes approach. When the rounds end, a + // finding with a typed person-only reason is deferred; anything + // else is CoderHelm's own limit (`end_on_own_limit`), alerted + // and never deferred. // Each finding is tracked on its own (`own_review_ledger`): a // round a tool or a guard blocked is not a stall, a stalled // finding climbs its own ladder, a finding the ticket rules out @@ -9635,7 +9637,8 @@ async fn wait_on_person( ) -> Result<(), Box> { // The supervisor's rule: only a need on the human-only list waits on a // person. Everything else the run finishes: its pull request carries - // what is left, deferred and named, and the run is completed; or, when + // what is left, named, and the run is completed (its own review's + // leftovers are held by `own_review_completion` first); or, when // its own checks are still red after every fix and revert // (`hand_off_red_ci`), it failed with exactly what fails. let red = red_ci_blocks_completion(state, &msg.team_id, run_id).await; @@ -9682,8 +9685,9 @@ async fn wait_on_person( // every approach it ends naming what its review still asks for. if pr_number > 0 { match Box::pin(own_review_completion(state, msg, run_id, pr_number, branch)).await { - // Defer: CoderHelm's notes were listed and the pull request - // marked ready (`own_review_completion`); the run completes. + // Its review doesn't ask for changes on the head, and every + // deferred finding has a typed person-only reason + // (`own_review_completion`): the run completes. super::own_review_ledger::Completion::Complete => {} super::own_review_ledger::Completion::Continue(_) => return Ok(()), super::own_review_ledger::Completion::Hold(open) => {