From dbb818890eab58ee7a5f5f6f3d7239a442f3b5b2 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 11:47:15 -0500 Subject: [PATCH 1/2] A description gets a final review before it is posted, follows the repository's template, and a run delivers its change whatever outside work it needs A pull request description showed six checks as "still running when this was written" and never changed them, asked a person for deploy credentials in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id, and listed running and did-not-run checks on one line. The repository's template only guided the first draft. - Final review in the one save (common::pr_review): a running check reads Running and is never a result; nothing the gate does not let through reaches a person; nothing said twice; no filler; no raw id beside a name; running and did-not-run said apart. - Running checks render as Running, the conclusion says they are still running, and the stamp marks the description for a rebuild until they end, so the checks step, the watch and the end of the run replace them. - The reviewer guide gives way to the lead (it said Read first and Rollback again); its own lines keep running apart from did-not-run. - A staging deploy the repository lets CoderHelm start (a dispatchable or labelled workflow) is CoderHelm's step (outside_work::own_startable). - The repository's pull request template is the visible structure: its headings in order, filled with CoderHelm's content (common::pr_template, pr_body::render_templated); the rebuild reads it, cached per repository. - A plan with code is implemented and its pull request opened whatever outside work it needs (route_for_plan), and a run whose pull request is open ends completed, with person-only items listed once under Needed from you and on the run page. - Incident case bl replays the posted description with neutral names. --- docs/incidents.md | 1 + services/common/src/lib.rs | 4 + services/common/src/pr_body.rs | 254 +++++++++-- services/common/src/pr_facts.rs | 31 +- services/common/src/pr_layout.rs | 23 +- services/common/src/pr_review.rs | 381 +++++++++++++++++ services/common/src/pr_template.rs | 299 +++++++++++++ services/worker/src/passes/description.rs | 77 +++- .../worker/src/passes/description_eval.rs | 3 +- .../worker/src/passes/description_facts.rs | 35 +- services/worker/src/passes/fix_location.rs | 21 + .../incidents/av_description_from_facts.rs | 2 +- .../incidents/bl_description_final_review.rs | 403 ++++++++++++++++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/outside_exec.rs | 3 + services/worker/src/passes/outside_work.rs | 40 ++ services/worker/src/passes/pr.rs | 40 +- services/worker/src/passes/resume.rs | 42 +- services/worker/src/passes/reviewer_guide.rs | 38 +- 19 files changed, 1614 insertions(+), 84 deletions(-) create mode 100644 services/common/src/pr_review.rs create mode 100644 services/common/src/pr_template.rs create mode 100644 services/worker/src/passes/incidents/bl_description_final_review.rs diff --git a/docs/incidents.md b/docs/incidents.md index 775c06be5..1712de2d0 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -89,6 +89,7 @@ pipeline still calls it there. | bi. `bi_own_review_finishes` | A run's own review asked for changes; its fix rounds were blocked by a refused edit, checks skipped for time and a tool input error, the loop called that "no progress" at its cap of two, deferred a one-line config omission and a placeholder line, and marked the run completed while the run page said a fix round was taking them. The finding contradicted a comment on the ticket, and an outside step asked a person to add labels. | Each finding is tracked on its own: a blocked round is not a stall and the next one removes the block; a stalled finding climbs its own ladder; a finding the ticket, its comments or the plan rule out is settled by their words; only a person-gate reason defers one. A run is never completed while its own review asks for changes on the head or with a deferred item lacking such a reason. A finished run's card never says it is working. CoderHelm adds pull request labels itself. | | bj. `bj_release_through_a_busy_hour` | Two repositories' Security pages read hundreds of findings "in a pull request" for two days, through two releases meant to give them back. The sweep that compares findings with GitHub logged only when it changed something, so a sweep that found every pull request still open left no trace; and while GitHub's budget was low it was held before its first read, three sweeps in a row. Both pull requests were in fact open. | Every sweep leaves one line with what it read, what GitHub said (open, merged, closed, unanswered), what it changed and what it left. A held budget slows the release and never stops it: a few reads a sweep go on a small allowance of their own (`github_budget::caller::FLOOR`), in a turn that reaches every pull request within a few sweeps. | | bk. `bk_owns_the_outside_work` | A run with its pull request open ended waiting on people and its ticket comment handed over work CoderHelm could do: reading workflow runs, a lint, page checks (all failing on one 400 because a page check written as the confirm "query" was sent to the CMS's GROQ API), the production release (a tag after one approval), a review look, and a step number the ticket never showed; it opened on a raw Jira account id and counted nothing as handed over. | Each outside step's action comes from its own words; a failed attempt reaches a person only for a permission or credential in its own cause; a tool failure is diagnosed and reported once and its steps take another way; the release is one approval; a run waits on a person only with a gate-approved item and nothing it can still do; every comment, description, chat message and outside report passes the sink check; replies show names, never account ids; the team's history replays with no doable item reaching a person. | +| bl. `bl_description_final_review` | A pull request description showed six checks as "still running when this was written" in its results and never changed them, asked a person for deploy credentials or to run the staging deploy in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id beside its name, and listed still-running and did-not-run checks on one line. The repository's template only guided the first draft. A run could also end as needing an outside change instead of delivering the code. | Every description passes a final review in the one save (`common::pr_review`): a running check reads Running and is never a result, and the stamp keeps the description rebuilt until the checks end; nothing the gate does not let through reaches a person, and a staging deploy the repository lets CoderHelm start is CoderHelm's step; nothing is said twice; no filler; no raw id beside a name; running and did-not-run are said apart. The repository's template is the visible structure, filled with CoderHelm's content (`common::pr_template`). A plan with code is implemented and its pull request opened whatever outside work it needs, and the run ends delivered with only person-only items listed once under Needed from you. | ## Adding a case diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 4f9c3fc6b..6ee355c08 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -180,9 +180,13 @@ pub mod pr_layout; pub mod pr_outcome; /// The last read of a description before it is saved, verified. pub mod pr_reader; +/// The final read of a description before it is posted. +pub mod pr_review; /// The work around a pull request that is not in its diff, each step with /// one owner and one state. pub mod pr_steps; +/// A repository's pull request template as the description's structure. +pub mod pr_template; pub mod run_prs; // review_stats: time-ordered review records for analytics /// What people write on a ticket while a run works on it: kept, acknowledged, acted on. diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index cb48d18d1..5b3de6a5f 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -188,10 +188,16 @@ impl Level { #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Outcome { Failed, + /// Still running: shown as running, never as a result, and replaced + /// when it ends (the stamp marks the description for a rebuild). + Running, NotRun, Passed, } +/// How a row still running reads. +pub const RUNNING: &str = "Running"; + #[derive(Debug, Clone, PartialEq, Eq)] pub struct Row { pub check: String, @@ -209,6 +215,8 @@ impl Row { (Outcome::Passed, false) => format!("Passed; {d}"), (Outcome::Failed, true) => "Failed".into(), (Outcome::Failed, false) => format!("Failed: {d}"), + (Outcome::Running, true) => format!("{RUNNING}; updated here when it ends"), + (Outcome::Running, false) => format!("{RUNNING}; {d}"), (Outcome::NotRun, true) => "Not run: nothing reported it".into(), (Outcome::NotRun, false) => format!("Not run: {d}"), } @@ -689,11 +697,20 @@ pub fn table_rows(rows: &[Row]) -> Vec { let rest = sorted.split_off(MAX_ROWS - 1); let failed = rest.iter().filter(|r| r.outcome == Outcome::Failed).count(); let not_run = rest.iter().filter(|r| r.outcome == Outcome::NotRun).count(); + let running = rest + .iter() + .filter(|r| r.outcome == Outcome::Running) + .count(); let (outcome, detail) = if failed > 0 { ( Outcome::Failed, format!("{failed} of them; all are listed in {EVIDENCE}"), ) + } else if running > 0 { + ( + Outcome::Running, + format!("{running} of them; updated here when they end"), + ) } else if not_run > 0 { ( Outcome::NotRun, @@ -750,8 +767,57 @@ fn screens_markdown(s: &Screens) -> String { } } -/// The body's parts, rendered. -pub fn render(b: &Body) -> Rendered { +/// The visible part's blocks, each rendered on its own (empty when the +/// body has none): what [`render`] lays out in its fixed order and +/// [`render_templated`] lays into a repository's template. +#[derive(Debug, Clone, Default)] +struct Blocks { + header: String, + alert: String, + summary: String, + /// With its `### Needed from you` heading. + needed: String, + /// With its `### Review focus` heading. + focus: String, + deps: String, + risk: String, + rollback: String, + /// With its `### Verification` heading. + verification: String, + screens: String, +} + +impl Blocks { + /// The blocks in the fixed order. + fn in_order(&self) -> Vec<&str> { + [ + &self.alert, + &self.summary, + &self.needed, + &self.focus, + &self.deps, + &self.risk, + &self.rollback, + &self.verification, + &self.screens, + ] + .into_iter() + .map(String::as_str) + .filter(|b| !b.is_empty()) + .collect() + } +} + +/// A block without its `### ` heading line. +fn under_heading(block: &str) -> String { + match block.split_once('\n') { + Some((first, rest)) if first.starts_with("### ") => rest.trim().to_string(), + _ => block.trim().to_string(), + } +} + +fn blocks(b: &Body) -> Blocks { + let mut out = Blocks::default(); let mut v: Vec = Vec::new(); let ticket = b.ticket.as_ref().filter(|t| !t.key.trim().is_empty()); v.push(format!( @@ -763,7 +829,7 @@ pub fn render(b: &Body) -> Rendered { if !label.is_empty() && label != NOTES { v.push(format!("{LABEL_START}{label} -->")); } - let mut blocks: Vec = Vec::new(); + out.header = v.join("\n"); // An alert when merging without an action breaks something, or when // the risk is High and nobody is asked for anything. let alert = if !b.alert.trim().is_empty() { @@ -777,9 +843,9 @@ pub fn render(b: &Body) -> Rendered { String::new() }; if !alert.is_empty() { - blocks.push(format!("> [!IMPORTANT]\n> {alert}.")); + out.alert = format!("> [!IMPORTANT]\n> {alert}."); } - blocks.push(summary_paragraph(&b.summary, ticket, &b.outside)); + out.summary = summary_paragraph(&b.summary, ticket, &b.outside); if !b.needed.is_empty() { let mut s = String::from("### Needed from you\n\n"); let items: Vec = b @@ -790,19 +856,19 @@ pub fn render(b: &Body) -> Rendered { .collect(); let loose = items.iter().any(|i| i.contains('\n')); s.push_str(&items.join(if loose { "\n\n" } else { "\n" })); - blocks.push(s); + out.needed = s; } let focus = focus_markdown(&b.focus); - blocks.push(format!( + out.focus = format!( "### Review focus\n\n{}", focus .iter() .map(|f| format!("- {f}")) .collect::>() .join("\n") - )); + ); if !b.dep_rows.is_empty() { - blocks.push(table( + out.deps = table( &["Package", "Change", "Why it matters"], &b.dep_rows .iter() @@ -815,7 +881,7 @@ pub fn render(b: &Body) -> Rendered { ] }) .collect::>(), - )); + ); } let risk = part(&b.risk); let risk = if risk.chars().count() < 10 { @@ -823,18 +889,14 @@ pub fn render(b: &Body) -> Rendered { } else { risk }; - blocks.push(format!( - "**Risk:** {}. {}.", - b.level.word(), - upper_first(&risk) - )); + out.risk = format!("**Risk:** {}. {}.", b.level.word(), upper_first(&risk)); let rollback = part(&b.rollback); let rollback = if rollback.is_empty() { "Revert this pull request; nothing outside the code changes with it".to_string() } else { upper_first(&rollback) }; - blocks.push(format!("**Rollback:** {rollback}.")); + out.rollback = format!("**Rollback:** {rollback}."); let lead_in = if !b.results_of.is_empty() && b.results_of != b.head { format!( "Results below are for {}; the head is now {}.", @@ -854,14 +916,151 @@ pub fn render(b: &Body) -> Rendered { .map(|r| vec![one_line(&r.check), r.result()]) .collect::>(), )); - blocks.push(verification); + out.verification = verification; if let Some(s) = &b.screens { - blocks.push(screens_markdown(s)); + out.screens = screens_markdown(s); } - let mut visible = v.join("\n"); + out +} + +/// The body's parts, rendered. +pub fn render(b: &Body) -> Rendered { + let bl = blocks(b); + let mut visible = bl.header.clone(); visible.push('\n'); - visible.push_str(&blocks.join("\n\n")); + visible.push_str(&bl.in_order().join("\n\n")); + finish(b, visible) +} +/// The body laid into a repository's template (`pr_template`): the +/// template's headings, in its order, each filled with what it asks for; +/// what a person must do and the review focus after the first section. +/// `written` is the text the writer wrote (its sections are read by +/// heading). Returns the rendering and the written sections' titles it put +/// in sight, so they are not said again below. With a template of no +/// headings it is [`render`]. +pub fn render_templated(b: &Body, template: &str, written: &str) -> (Rendered, Vec) { + use crate::pr_template::{self as tpl, Slot}; + let sections = tpl::sections(template); + if sections.is_empty() { + return (render(b), Vec::new()); + } + let bl = blocks(b); + let own = tpl::written_sections(written); + let mut used: Vec = Vec::new(); + let mut by_title = |title: &str, also: &[&str]| -> Option { + let found = own + .iter() + .find(|(t, x)| t.eq_ignore_ascii_case(title) && !x.trim().is_empty()) + .or_else(|| { + own.iter().find(|(t, x)| { + let l = t.to_lowercase(); + !x.trim().is_empty() && also.iter().any(|a| l.contains(a)) + }) + })?; + used.push(found.0.clone()); + Some(found.1.clone()) + }; + let ticket = b.ticket.as_ref().filter(|t| !t.key.trim().is_empty()); + let slots: Vec = sections.iter().map(tpl::slot).collect(); + let has = |s: Slot| slots.contains(&s); + let mut out: Vec = Vec::new(); + if !bl.alert.is_empty() { + out.push(bl.alert.clone()); + } + // The summary opens the body; a template without a section for it gets + // it above its first heading. + if !has(Slot::Summary) { + out.push(bl.summary.clone()); + } + let review_block = |out: &mut Vec| { + if !bl.needed.is_empty() { + out.push(bl.needed.clone()); + } + if !has(Slot::Review) { + out.push(bl.focus.clone()); + } + if !bl.deps.is_empty() { + out.push(bl.deps.clone()); + } + }; + if !has(Slot::Summary) { + review_block(&mut out); + } + let mut placed_review = !has(Slot::Summary); + for (s, slot) in sections.iter().zip(slots.iter().copied()) { + let fill = match slot { + Slot::Summary => { + // The writer's own words for it are what the summary was + // read from: not said again below. + let _ = by_title(&s.title, &[]); + bl.summary.clone() + } + Slot::Testing => under_heading(&bl.verification), + Slot::Risk => format!("{}\n\n{}", bl.risk, bl.rollback), + Slot::Screens => { + if bl.screens.is_empty() { + "No screenshot: nothing in this change shows on a page.".to_string() + } else { + bl.screens.clone() + } + } + Slot::Ticket => match ticket { + Some(t) => format!("Ticket: {}", t.link()), + None => by_title(&s.title, &[]) + .unwrap_or_else(|| "No ticket names this change.".to_string()), + }, + Slot::Review => under_heading(&bl.focus), + Slot::Checklist => { + by_title(&s.title, &["checklist"]).unwrap_or_else(|| tpl::boxes(s).join("\n")) + } + Slot::Changes => by_title(&s.title, &["change"]) + .unwrap_or_else(|| "Listed under Implementation notes below.".to_string()), + Slot::Other => by_title(&s.title, &[]).unwrap_or_else(|| { + let own: Vec = s + .lines + .iter() + .filter(|l| !l.trim().is_empty()) + .cloned() + .collect(); + if own.is_empty() { + "Nothing for this change.".to_string() + } else { + own.join("\n") + } + }), + }; + out.push(format!("{}\n\n{}", s.heading(), fill.trim())); + if !placed_review { + review_block(&mut out); + placed_review = true; + } + } + if !has(Slot::Risk) { + out.push(bl.risk.clone()); + out.push(bl.rollback.clone()); + } + if !has(Slot::Testing) { + out.push(bl.verification.clone()); + } + if !has(Slot::Screens) && !bl.screens.is_empty() { + out.push(bl.screens.clone()); + } + let mut visible = format!("{}\n{}\n", bl.header, tpl::MARK); + visible.push_str( + &out.into_iter() + .filter(|x| !x.trim().is_empty()) + .collect::>() + .join("\n\n"), + ); + used.sort(); + used.dedup(); + (finish(b, visible), used) +} + +/// The generated parts below the visible one. +fn finish(b: &Body, visible: String) -> Rendered { + let ticket = b.ticket.as_ref().filter(|t| !t.key.trim().is_empty()); let footer = { let from = ticket .map(|t| format!(" from {}", t.link())) @@ -1008,10 +1207,12 @@ pub fn defects(body: &str, head: &str) -> Vec { if seen.matches("> [!").count() > 1 { d.push("more than one alert".into()); } - // Headings: only these three, in this order. + // Headings: only these three, in this order; a body laid into the + // repository's template has the template's headings. + let templated = body.contains(crate::pr_template::MARK); let allowed = ["Needed from you", "Review focus", "Verification"]; let mut last = 0usize; - for l in &lines { + for l in lines.iter().filter(|_| !templated) { let t = l.trim(); if t.starts_with('#') { let h = t.trim_start_matches('#').trim(); @@ -1021,7 +1222,10 @@ pub fn defects(body: &str, head: &str) -> Vec { } } } - for h in ["Review focus", "Verification"] { + for h in ["Review focus", "Verification"] + .iter() + .filter(|_| !templated) + { if !seen.contains(&format!("### {h}\n")) { d.push(format!("no {h} section")); } @@ -1180,9 +1384,9 @@ pub fn defects(body: &str, head: &str) -> Vec { if seen_pass { d.push(format!("a failed row after a passed one: {r}")); } - } else if !result.starts_with("Not run: ") { + } else if !result.starts_with("Not run: ") && !result.starts_with(RUNNING) { d.push(format!( - "a result that is not Passed, Failed or Not run: {r}" + "a result that is not Passed, Failed, Running or Not run: {r}" )); } } diff --git a/services/common/src/pr_facts.rs b/services/common/src/pr_facts.rs index 524085d3c..8ede27984 100644 --- a/services/common/src/pr_facts.rs +++ b/services/common/src/pr_facts.rs @@ -686,10 +686,22 @@ pub fn conclusion(f: &Facts) -> String { parts.push("all checks on this head passed".to_string()); } else if f.checks.is_empty() { parts.push("no check has reported on this head yet".to_string()); + } else { + let running = f + .checks + .iter() + .filter(|c| c.outcome == Outcome::Running) + .count(); + if running > 0 { + parts.push(format!( + "{} still running on this head; this is updated when {}", + plural(running, "check is", "checks are"), + if running == 1 { "it ends" } else { "they end" } + )); + } } - if parts.is_empty() { - return "nothing is out of the ordinary".to_string(); - } + // Nothing to conclude is said by saying nothing: a sentence that + // carries no fact is filler (`pr_review`). parts.join("; ") } @@ -791,10 +803,12 @@ pub fn rows(f: &Facts) -> Vec { outcome: O::Failed, detail: log, }), + // Running is never a result: it is said as running, and the + // description is rebuilt when it ends (`description::with_stamp`). Outcome::Running => ci.push(Row { check, - outcome: O::NotRun, - detail: "still running when this was written".into(), + outcome: O::Running, + detail: String::new(), }), Outcome::DidNotRun => {} } @@ -1170,6 +1184,8 @@ fn conclusion_with_signoffs(f: &Facts) -> String { let c = conclusion(f); if notes.is_empty() { c + } else if c.is_empty() { + format!("your merge decision also signs off: {}", notes.join("; ")) } else { format!( "{c}. Your merge decision also signs off: {}", @@ -1228,12 +1244,13 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { .iter() .find(|s| is_look(s)) .map(|s| { - sentence_part( + // A page is named by its name; its raw id stays in the evidence. + sentence_part(&crate::pr_review::without_raw_ids( s.what .trim_start() .trim_start_matches("Look at") .trim_start(), - ) + )) }) .unwrap_or_default(); let see_it = match (f.preview_url.starts_with("https://"), look.is_empty()) { diff --git a/services/common/src/pr_layout.rs b/services/common/src/pr_layout.rs index 916380a94..d6e5c2f69 100644 --- a/services/common/src/pr_layout.rs +++ b/services/common/src/pr_layout.rs @@ -33,11 +33,20 @@ const FOLD_CLOSE: &str = ""; /// something is wrong. const VISIBLE_BLOCKS: &[&str] = &["draft-status", "objections", "open-findings", "unfinished"]; -/// Blocks an earlier shape of the description wrote that the lead replaces. -const SUPERSEDED: &[(&str, &str)] = &[( - "", - "", -)]; +/// Blocks an earlier shape of the description wrote that the lead replaces: +/// the old open-steps block, and the reviewer guide, whose file to read +/// first, way back and checks the lead already says (a description showed +/// "Read first" and "Look first", "Rollback" and "Roll back"). +const SUPERSEDED: &[(&str, &str)] = &[ + ( + "", + "", + ), + ( + "", + "", + ), +]; fn is_fold_line(line: &str) -> bool { let t = line.trim(); @@ -639,7 +648,6 @@ mod tests { let flat = unfold(&once); for l in [ "* `src/export/poller.rs`: the retry loop.", - "* **Roll back:** revert this pull request.", "**Low**: one module.", "- The staging secret is not set.", "", @@ -649,6 +657,9 @@ mod tests { assert!(flat.lines().any(|x| x == l), "lost: {l}\n{flat}"); } assert!(!flat.contains("
"), "{flat}"); + // The reviewer guide says what the lead says: it gives way to it. + assert!(!flat.contains("**Roll back:**"), "{flat}"); + assert!(!flat.contains("For the reviewer"), "{flat}"); } #[test] diff --git a/services/common/src/pr_review.rs b/services/common/src/pr_review.rs new file mode 100644 index 000000000..b3275e7f7 --- /dev/null +++ b/services/common/src/pr_review.rs @@ -0,0 +1,381 @@ +//! The last read of a pull request description before it is posted. +//! +//! A description CoderHelm posted showed six checks as "still running when +//! this was written" in its results table and never changed them; asked a +//! person to deploy staging when the repository starts that deploy from a +//! label CoderHelm adds itself; said the file to read first and the way +//! back twice each (its lead and an older "For the reviewer" block); closed +//! the review focus with "CoderHelm's conclusion: nothing is out of the +//! ordinary"; named a content page by its raw document id next to its +//! name; and listed checks still running beside checks that did not run as +//! one "Not verified" line. Each writer was right by itself; nothing read +//! the result as its reader would. +//! +//! [`review`] is that read. It runs on every description CoderHelm writes +//! or rewrites (`worker::passes::description::save`, the one write), is +//! pure and deterministic, and fixes what it finds rather than reporting +//! it: +//! +//! - a check still running is never a result: it reads "Running" and the +//! description is rebuilt when it ends (the stamp says so); +//! - an item for a person the gate does not let through is taken out +//! (`person_gate::sink`): what CoderHelm can do is its own work; +//! - a line said twice is said once; +//! - a sentence that carries no fact is dropped; +//! - a raw id next to the name of what it identifies goes; +//! - a "Not verified" line keeps what is still running apart from what did +//! not run. +//! +//! [`template_missing`] checks a description laid into the repository's +//! template (`pr_template`) has each of its headings. + +/// What the review found and fixed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// A check still running shown as a result. + RunningAsResult, + /// An item for a person CoderHelm can do itself. + PersonItem, + /// A line said again. + Duplicate, + /// A sentence that says nothing. + Filler, + /// A raw id where a name exists. + RawId, + /// Still running and did not run on one line. + Mixed, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Finding { + pub kind: Kind, + pub said: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reviewed { + pub body: String, + pub findings: Vec, +} + +/// What a frozen running row said. +const FROZEN: &str = "still running when this was written"; + +/// Sentences that carry no fact, as CoderHelm's conclusion or alone. +const FILLER: &[&str] = &[ + "nothing is out of the ordinary", + "everything looks good", + "nothing to note", + "no concerns", +]; + +fn one_line(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +fn is_hex(s: &str) -> bool { + !s.is_empty() && s.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// A raw id: a UUID, or a long token of letters and digits with no word in +/// it (a document or record id). +pub fn is_raw_id(token: &str) -> bool { + let t = token.trim(); + let parts: Vec<&str> = t.split('-').collect(); + if parts.len() == 5 + && [8, 4, 4, 4, 12] + .iter() + .zip(&parts) + .all(|(n, p)| p.len() == *n && is_hex(p)) + { + return true; + } + t.len() >= 20 + && t.chars().all(|c| c.is_ascii_alphanumeric()) + && t.chars().any(|c| c.is_ascii_digit()) + && t.chars().any(|c| c.is_ascii_alphabetic()) +} + +/// `line` without the parenthesised raw ids that follow a name: "Events +/// page (0f3c2a1b-...)" is "Events page". An id in code, in a link, or +/// with no name before it stays. +pub fn without_raw_ids(line: &str) -> String { + let mut out = line.to_string(); + let mut from = 0; + while let Some(rel) = out[from..].find('(') { + let a = from + rel; + let Some(b_rel) = out[a..].find(')') else { + break; + }; + let b = a + b_rel; + let inner = out[a + 1..b].trim(); + let id = inner + .strip_prefix("id ") + .or_else(|| inner.strip_prefix("id: ")) + .or_else(|| inner.strip_prefix("ID ")) + .unwrap_or(inner); + let before = out[..a].trim_end(); + let named = before + .chars() + .last() + .is_some_and(|c| c.is_alphanumeric() || c == '\'' || c == '"'); + let link = out[..a].ends_with(']'); + let ticks = out[..a].matches('`').count() % 2 == 1; + if named && !link && !ticks && is_raw_id(id) { + let start = before.len(); + out.replace_range(start..b + 1, ""); + from = start; + } else { + from = a + 1; + } + } + out +} + +/// A line as compared for a repeat: no list mark, no emphasis, the way +/// back named one way. +fn norm(line: &str) -> String { + let t = line + .trim() + .trim_start_matches(['-', '*', '>']) + .trim() + .replace("**", "") + .replace('`', "") + .to_lowercase(); + let t = t + .replace("roll back:", "rollback:") + .replace("look first:", "read first:"); + one_line(&t).trim_end_matches('.').to_string() +} + +/// Whether a line is prose a reader reads (not a table, code fence, +/// heading, comment or fold line). +fn is_prose(line: &str) -> bool { + let t = line.trim(); + !(t.is_empty() + || t.starts_with('|') + || t.starts_with('#') + || t.starts_with(""; + +/// One section of a template. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Section { + /// `##` and the like, as the template writes it. + pub level: String, + pub title: String, + /// The template's own lines under the heading, comments taken out. + pub lines: Vec, +} + +impl Section { + pub fn heading(&self) -> String { + format!("{} {}", self.level, self.title) + } +} + +/// What a section asks for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Slot { + Summary, + Changes, + Testing, + Risk, + Screens, + Ticket, + Checklist, + Review, + /// Anything else: the writer's words under that heading. + Other, +} + +fn has_any(t: &str, words: &[&str]) -> bool { + let w: Vec<&str> = t + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| !w.is_empty()) + .collect(); + words.iter().any(|x| { + if x.contains(' ') { + t.contains(x) + } else { + w.iter().any(|y| y == x || y.strip_suffix('s') == Some(x)) + } + }) +} + +/// What a heading asks for. +pub fn slot(s: &Section) -> Slot { + let t = s.title.to_lowercase(); + let boxes = s.lines.iter().any(|l| is_box(l)); + if has_any(&t, &["checklist", "check list"]) || (boxes && has_any(&t, &["before", "author"])) { + return Slot::Checklist; + } + if has_any( + &t, + &[ + "screenshot", + "screen", + "recording", + "video", + "visual", + "demo", + ], + ) { + return Slot::Screens; + } + if has_any( + &t, + &[ + "test", + "testing", + "tested", + "verification", + "verify", + "qa", + "validation", + "how to check", + ], + ) { + return Slot::Testing; + } + if has_any(&t, &["risk", "rollback", "roll back", "impact", "rollout"]) { + return Slot::Risk; + } + if has_any( + &t, + &[ + "ticket", + "issue", + "issues", + "related", + "link", + "jira", + "reference", + "closes", + "fixes", + ], + ) { + return Slot::Ticket; + } + if has_any(&t, &["reviewer", "review"]) { + return Slot::Review; + } + if has_any(&t, &["change", "changed", "implementation", "detail"]) { + return Slot::Changes; + } + if has_any( + &t, + &[ + "summary", + "description", + "what", + "overview", + "context", + "why", + "purpose", + "background", + "motivation", + "about", + ], + ) { + return Slot::Summary; + } + if boxes { + return Slot::Checklist; + } + Slot::Other +} + +fn is_box(l: &str) -> bool { + let t = l.trim_start(); + t.starts_with("- [ ]") || t.starts_with("- [x]") || t.starts_with("* [ ]") +} + +fn without_comments(text: &str) -> String { + let mut t = text.to_string(); + while let Some(a) = t.find("") { + Some(b) => t.replace_range(a..a + b + 3, ""), + None => { + t.truncate(a); + break; + } + } + } + t +} + +fn heading_of(line: &str) -> Option<(String, String)> { + let t = line.trim(); + if !t.starts_with('#') { + return None; + } + let hashes = t.chars().take_while(|c| *c == '#').count(); + if hashes > 4 { + return None; + } + let title = t[hashes..].trim().trim_matches('*').trim(); + (!title.is_empty() && t[hashes..].starts_with(' ')) + .then(|| ("#".repeat(hashes), title.to_string())) +} + +/// The sections of a template, in its order. Empty when it has no heading +/// (a template of prose alone gives no structure to fill). +pub fn sections(template: &str) -> Vec
{ + let text = without_comments(template); + let mut out: Vec
= Vec::new(); + let mut in_code = false; + for l in text.lines() { + if l.trim_start().starts_with("```") { + in_code = !in_code; + } + if !in_code { + if let Some((level, title)) = heading_of(l) { + out.push(Section { + level, + title, + lines: Vec::new(), + }); + continue; + } + } + if let Some(s) = out.last_mut() { + if !l.trim().is_empty() || !s.lines.is_empty() { + s.lines.push(l.trim_end().to_string()); + } + } + } + for s in &mut out { + while s.lines.last().is_some_and(|l| l.trim().is_empty()) { + s.lines.pop(); + } + } + out +} + +/// The sections a writer wrote, by heading: `(title, text under it)`. +pub fn written_sections(text: &str) -> Vec<(String, String)> { + let mut out: Vec<(String, Vec)> = Vec::new(); + let mut in_code = false; + for l in text.lines() { + if l.trim_start().starts_with("```") { + in_code = !in_code; + } + if !in_code { + if let Some((_, title)) = heading_of(l) { + out.push((title, Vec::new())); + continue; + } + } + if let Some((_, lines)) = out.last_mut() { + lines.push(l.to_string()); + } + } + out.into_iter() + .map(|(t, l)| (t, l.join("\n").trim().to_string())) + .collect() +} + +/// The checklist lines of a template section, as the template has them. +pub fn boxes(s: &Section) -> Vec { + s.lines.iter().filter(|l| is_box(l)).cloned().collect() +} + +/// The template's headings a visible part lacks, in the template's order. +pub fn missing(template: &str, visible: &str) -> Vec { + let have: Vec = visible + .lines() + .filter_map(heading_of) + .map(|(_, t)| t.to_lowercase()) + .collect(); + sections(template) + .into_iter() + .filter(|s| !have.contains(&s.title.to_lowercase())) + .map(|s| s.heading()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + const T: &str = "## Description\n\n\n## Type of change\n- [ ] Bug fix\n- [ ] New feature\n\n## How has this been tested?\n\n## Screenshots\n\n## Checklist\n- [ ] I have read the contributing guide\n- [ ] Tests pass locally\n"; + + #[test] + fn a_templates_sections_are_read_in_order_with_what_each_asks_for() { + let s = sections(T); + let got: Vec<(String, Slot)> = s.iter().map(|x| (x.title.clone(), slot(x))).collect(); + assert_eq!( + got, + vec![ + ("Description".into(), Slot::Summary), + ("Type of change".into(), Slot::Changes), + ("How has this been tested?".into(), Slot::Testing), + ("Screenshots".into(), Slot::Screens), + ("Checklist".into(), Slot::Checklist), + ] + ); + assert!(s[0].lines.is_empty(), "comments are not content"); + assert_eq!(boxes(&s[4]).len(), 2); + assert!(sections("Just say what it does.").is_empty()); + } + + #[test] + fn missing_headings_are_named() { + let v = "## Description\nx\n## Checklist\n- [ ] a"; + assert_eq!( + missing(T, v), + vec![ + "## Type of change".to_string(), + "## How has this been tested?".to_string(), + "## Screenshots".to_string() + ] + ); + } +} diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 8d9a32dc0..efda5d367 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -62,9 +62,21 @@ pub async fn save( body: &str, ) -> Result<(), Error> { let body = clean(body); + // The final review, as its reader would read it: no running check as a + // result, nothing CoderHelm can do handed to a person, nothing said + // twice, no filler, no raw id where a name exists (`pr_review`). + let reviewed = common::pr_review::review(&body); + for f in &reviewed.findings { + warn!( + pr_number = number, + kind = ?f.kind, + said = %common::truncate_str(&f.said, 200), + "The final review of the description fixed what a writer left" + ); + } // The last word before people read it: an item for a person the gate // does not let through is taken out, and logged as the writer's defect. - let sunk = common::person_gate::sink(&body); + let sunk = common::person_gate::sink(&reviewed.body); if sunk.defect() { tracing::error!( pr = number, @@ -274,12 +286,36 @@ pub fn stamp_of(body: &str) -> Option<&str> { /// The stamp's head and, when it carries one, the digest of the text the /// fact check read. fn stamp_parts(body: &str) -> Option<(&str, Option<&str>)> { + stamp_all(body).map(|(h, d, _)| (h, d)) +} + +/// The stamp's word for a description built while checks on its head were +/// still running: it is not current until they end and it is rebuilt. +const CHECKS_RUNNING: &str = "checks-running"; + +/// The stamp's head, digest, and whether checks were running when it was +/// built. +fn stamp_all(body: &str) -> Option<(&str, Option<&str>, bool)> { let at = body.rfind(STAMP_START)? + STAMP_START.len(); let rest = &body[at..]; let inner = rest[..rest.find(STAMP_END)?].trim(); let mut parts = inner.split_whitespace(); let head = parts.next().filter(|h| !h.is_empty())?; - Some((head, parts.next())) + let digest = parts.next(); + let running = parts.any(|p| p == CHECKS_RUNNING); + Some((head, digest, running)) +} + +/// Whether the description shows a check on its head as still running. +pub fn shows_running(body: &str) -> bool { + common::pr_body::in_sight(body).lines().any(|l| { + let t = l.trim(); + t.starts_with('|') + && t.trim_end_matches('|') + .rsplit(" | ") + .next() + .is_some_and(|r| r.trim().starts_with(common::pr_body::RUNNING)) + }) } fn without_stamp(body: &str) -> String { @@ -309,8 +345,15 @@ pub fn with_stamp(body: &str, head: &str) -> String { } let digest = checked_digest(&body); let head = head.get(..STAMP_SHA).unwrap_or(head); + // Built while checks ran: the next reconcile builds it again, so the + // running rows are replaced by their results when the checks end. + let running = if shows_running(&body) { + format!(" {CHECKS_RUNNING}") + } else { + String::new() + }; format!( - "{}\n\n{STAMP_START}{head} {digest}{STAMP_END}", + "{}\n\n{STAMP_START}{head} {digest}{running}{STAMP_END}", body.trim_end() ) } @@ -320,13 +363,15 @@ fn same_head(stamped: &str, head: &str) -> bool { stamped == head || (stamped.len() >= 7 && head.starts_with(stamped)) } -/// Whether the description was built for `head` and the text the fact check -/// read is still the text that is there. A stamp from before the digest -/// answers for its head alone. +/// Whether the description was built for `head`, the text the fact check +/// read is still the text that is there, and no check was running when it +/// was built (a description showing running checks is rebuilt until they +/// end). A stamp from before the digest answers for its head alone. pub fn is_current(body: &str, head: &str) -> bool { - match stamp_parts(body) { - Some((h, digest)) => { + match stamp_all(body) { + Some((h, digest, running)) => { !head.is_empty() + && !running && same_head(h, head) && digest.is_none_or(|d| d == checked_digest(body)) } @@ -722,11 +767,18 @@ async fn build( Some(r) => ask_reader(state, r, &facts, &base).await, None => None, }; - let shaped = super::description_facts::shape( + // The repository's template, when it has one, is the + // description's structure (`pr_template`). + let template = match pr["base"]["ref"].as_str() { + Some(base_ref) => super::pr::fetch_pr_template(github, owner, repo, base_ref).await, + None => None, + }; + let shaped = super::description_facts::shape_for( &base, pr["title"].as_str().unwrap_or(""), facts, reply.as_deref(), + template.as_deref(), ); note_corrections(number, &shaped.corrections); tracing::info!( @@ -988,6 +1040,7 @@ mod tests { }; let save = body_of("\npub async fn save(", "\npub async fn save_checked("); assert!(save.contains("clean(body)")); + assert!(save.contains("pr_review::review("), "the final review"); assert!(save.contains("pr_layout::layout(")); let checked = body_of("\npub async fn save_checked(", "\nfn note_corrections("); assert!(checked.contains("pr_claims::enforce(")); @@ -996,7 +1049,8 @@ mod tests { for step in [ "facts_of(", "ask_reader(", - "description_facts::shape(", + "fetch_pr_template(", + "description_facts::shape_for(", "with_stamp(", "save(github", "resolve_own_description_threads(", @@ -1018,7 +1072,8 @@ mod tests { continue; } assert!( - !code.contains("description_facts::shape("), + !code.contains("description_facts::shape(") + && !code.contains("description_facts::shape_for("), "{path} shapes a description outside the rebuild" ); } diff --git a/services/worker/src/passes/description_eval.rs b/services/worker/src/passes/description_eval.rs index 63c78d843..a384ab6b2 100644 --- a/services/worker/src/passes/description_eval.rs +++ b/services/worker/src/passes/description_eval.rs @@ -449,6 +449,8 @@ pub fn ticket_case() -> Case { "make ship", "### Needed from you", "**Check:**", + // The reviewer guide says what the lead says: it gives way. + "**Roll back:**", ], in_sight: vec![ "Retries a timed-out export poll three times before giving up (OPS-41).", @@ -457,7 +459,6 @@ pub fn ticket_case() -> Case { ], collapsed: vec![ "* `src/export/poller.rs`: the retry loop and its limit.", - "* **Roll back:** revert this pull request.", "How to check: `cargo test -p export`.", "Source ticket: OPS-41", ], diff --git a/services/worker/src/passes/description_facts.rs b/services/worker/src/passes/description_facts.rs index 34d33d9fe..685613e03 100644 --- a/services/worker/src/passes/description_facts.rs +++ b/services/worker/src/passes/description_facts.rs @@ -137,7 +137,11 @@ fn section<'a>(body: &'a str, names: &[&str]) -> Vec<&'a str> { /// What the description itself says the change is: the first sentences of /// its Summary. pub fn summary_of(body: &str) -> String { - let lines = section(body, &["summary"]); + // A template's "Description" is its summary. + let lines = match section(body, &["summary"]) { + l if l.iter().any(|x| !x.trim().is_empty()) => l, + _ => section(body, &["description"]), + }; let para: Vec<&str> = lines .iter() .map(|l| l.trim()) @@ -475,8 +479,24 @@ pub fn written(body: &str) -> String { /// `body` (as it stands, in any earlier shape) in its final shape for /// `facts`. `reply` is the reader pass's answer when a model was asked. -/// Shaping twice gives the same text. -pub fn shape(body: &str, title: &str, mut facts: Facts, reply: Option<&str>) -> Shaped { +/// Shaping twice gives the same text. The eval and the incident cases +/// shape with no template; the rebuild calls [`shape_for`]. +#[cfg(test)] +pub fn shape(body: &str, title: &str, facts: Facts, reply: Option<&str>) -> Shaped { + shape_for(body, title, facts, reply, None) +} + +/// [`shape`], laid into the repository's pull request `template` when it +/// has one: its headings are the visible structure and CoderHelm's content +/// fills them (`pr_body::render_templated`); the written sections that went +/// into sight are not said again below. +pub fn shape_for( + body: &str, + title: &str, + mut facts: Facts, + reply: Option<&str>, + template: Option<&str>, +) -> Shaped { let prior = Slots::from_body(body, &facts); // What a person ticked stays ticked. let ticked = common::pr_body::ticked_ids(body); @@ -552,7 +572,14 @@ pub fn shape(body: &str, title: &str, mut facts: Facts, reply: Option<&str>) -> let checked = pr_reader::without_sections(&checked, &slots.drop); // 3. The visible part, the generated blocks below it and the steps and // evidence, from the facts; the written text goes in the first fold. - let r = common::pr_body::render(&common::pr_facts::body_of(&facts, &ticked)); + let b = common::pr_facts::body_of(&facts, &ticked); + let (r, checked) = match template.filter(|t| !common::pr_template::sections(t).is_empty()) { + Some(t) => { + let (r, used) = common::pr_body::render_templated(&b, t, &written(&checked)); + (r, pr_reader::without_sections(&checked, &used)) + } + None => (common::pr_body::render(&b), checked), + }; // The head is named once, in the Verification lead-in. let short = format!("on `{}`", facts.short_head()); let own_checks: Vec = facts diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index 2c165fe73..2cd2fd018 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -650,10 +650,26 @@ pub fn route_for_plan(decision: Option<&FixDecision>, tasks: &str) -> Route { { Route::Code } + // Something outside the code never replaces the code change the + // plan makes: a plan with tasks is implemented and its pull request + // opened, and the outside part rides along (done by CoderHelm where + // it can, the rest listed once for a person). A run once ended with + // "do this, then I'll do it" and no pull request. + Route::OutsideOnly if plans_code(tasks) => Route::CodeAndOutside, r => r, } } +/// Whether a plan's tasks change code: anything but the sentinels that say +/// it changes none. +pub fn plans_code(tasks: &str) -> bool { + let t = tasks.trim_start(); + !t.is_empty() + && !t.starts_with(NO_CODE_CHANGE) + && !t.starts_with("NO_CHANGES_NEEDED:") + && !t.starts_with("CLARIFICATION_NEEDED:") +} + /// The report as Jira shows it: the Jira app turns each paragraph into one /// plain-text paragraph (no markdown, single newlines become spaces), so /// every line becomes its own paragraph and the emphasis marks go. @@ -1933,6 +1949,11 @@ mod tests { let d = parse(fixture::PLANNER_REPLY).unwrap(); let tasks = "NO_CODE_CHANGE: the term's setting is off"; assert_eq!(route_for_plan(Some(&d), tasks), Route::OutsideOnly); + // A plan with code to change is implemented whatever else it needs. + assert_eq!( + route_for_plan(Some(&d), "- [ ] a.rs: x"), + Route::CodeAndOutside + ); } #[test] diff --git a/services/worker/src/passes/incidents/av_description_from_facts.rs b/services/worker/src/passes/incidents/av_description_from_facts.rs index a23809d27..5d5a645f0 100644 --- a/services/worker/src/passes/incidents/av_description_from_facts.rs +++ b/services/worker/src/passes/incidents/av_description_from_facts.rs @@ -239,7 +239,7 @@ fn a_rebuild_resolves_coderhelms_own_thread_about_the_description() { let build = fn_src(src, "\nasync fn build("); assert!(build.contains("resolve_own_description_threads(")); // Every description takes the one path: facts, check, lead, layout. - assert!(build.contains("description_facts::shape(")); + assert!(build.contains("description_facts::shape_for(")); let save = fn_src(src, "\npub async fn save("); assert!(save.contains("pr_layout::layout(")); let pr = include_str!("../pr.rs"); diff --git a/services/worker/src/passes/incidents/bl_description_final_review.rs b/services/worker/src/passes/incidents/bl_description_final_review.rs new file mode 100644 index 000000000..30b2f1534 --- /dev/null +++ b/services/worker/src/passes/incidents/bl_description_final_review.rs @@ -0,0 +1,403 @@ +//! bl. A ticket asked for a Studio warning when a hero subtitle runs past +//! 160 characters. CoderHelm made the change and opened the pull request, +//! and its description read: +//! +//! - six checks as "Not run: still running when this was written", in the +//! results table, never changed when they finished; +//! - "Needed from you: give CoderHelm the deploy credentials for this +//! environment or run `cd apps/studio && npm run deploy:staging` once ... +//! Why a person: a credential only a person holds", in a repository that +//! deploys staging from a pull request label CoderHelm adds itself, and +//! with no attempt behind the credential claim; +//! - the file to read first twice ("Read first" and "Look first") and the +//! way back twice ("Rollback" and "Roll back"), from its lead and an older +//! "For the reviewer" block; +//! - "CoderHelm's conclusion: nothing is out of the ordinary"; +//! - a Studio page by its raw document id beside its name; +//! - "Not verified on ...: ... (still running); ... (did not run)" as one +//! line. +//! +//! The repository has a pull request template; the description's own +//! layout came first and the template's sections were folded away. +//! +//! What let it through: each writer was right alone and nothing read the +//! result as its reader would; the stamp that says a description is current +//! named only the head, so checks ending on that head never rebuilt it; the +//! gate made every deploy a person could not be shown to own a credential +//! item; the template only guided the model's first draft. +//! +//! Guarantee: every description passes a final review before it is posted +//! (`common::pr_review`, run in `description::save`): a running check reads +//! "Running" and is never a result, and the stamp keeps the description +//! rebuilt until the checks end; a deploy the repository lets CoderHelm +//! start is CoderHelm's (`outside_work::own_startable`); nothing is said +//! twice; no filler; no raw id beside a name; running and did-not-run are +//! said apart; the repository's template is the visible structure +//! (`common::pr_template`). And a run that needs something outside the code +//! still makes the change, opens the pull request and ends delivered, with +//! what only a person can do listed once under "Needed from you". + +use common::pr_facts::Why; +use common::pr_review::{self, Kind}; + +use super::fixture::*; +use crate::passes::description; +use crate::passes::description_facts::{self, Inputs}; +use crate::passes::fix_location::{self, FixDecision, FixLocation, OutsideChange, Route as Way}; +use crate::passes::outside_work::{self as ow, Abilities, Confirm, NoteStep, Route, Trigger}; +use crate::passes::pr_risk; +use crate::passes::reviewer_guide::{Check, State}; + +const HEAD: &str = "6de2414a0b1c2d3e4f5061728394a5b6c7d8e9f0"; +const PAGE_ID: &str = "0f3c2a1b-9d8e-4c7b-a6f5-e4d3c2b1a0f9"; +const DEPLOY: &str = "cd apps/studio && npm run deploy:staging"; + +/// The description as it was posted (names made up), lead and old block. +fn posted_before() -> String { + format!( + "Adds a Studio warning on the Hero block subtitle when it is longer than 160 characters (OPS-88). + +### Needed from you + +- [ ] **Person on the team**, before merge: Give CoderHelm the deploy credentials for this environment or run the command below once. Why a person: a credential only a person holds. + + ```sh + {DEPLOY} + ``` + +### Review focus + +- Approach: decide whether this does what OPS-88 asks. CoderHelm's conclusion: nothing is out of the ordinary. +- Read first: `apps/studio/schemaTypes/blocks/hero-block-validation.ts` (the largest change to code, 20 added lines); then the other 2 files. +- See it: Studio: Events page ({PAGE_ID}), hero Sub Title field. + +**For the reviewer** +* **Look first:** `apps/studio/schemaTypes/blocks/hero-block-validation.ts`, the largest change to code (20 added lines). +* **Roll back:** revert this pull request; nothing outside the code changes with it. +* **Not verified on `6de2414`:** `Test Coverage Report` (still running); `E2E after staging deploy` (did not run). + +**Risk:** Low. One schema file and its test. + +**Rollback:** Revert this pull request; nothing outside the code changes with it. + +### Verification + +On 6de2414 (head of this PR): + +| Check | Result | +|---|---| +| Test Coverage Report (CI) | Not run: still running when this was written | +| Lint (CI) | Not run: still running when this was written | +" + ) +} + +/// What the old description was wrong about, as it said it. +const OLD: &[&str] = &[ + "still running when this was written", + "nothing is out of the ordinary", + PAGE_ID, + "Give CoderHelm the deploy credentials", + "(still running); ", +]; + +fn files() -> Vec<(String, String, String)> { + let patch = |n: usize| format!("@@ -1 +1,{n} @@\n{}", "+line\n".repeat(n)); + vec![ + ( + "apps/studio/schemaTypes/blocks/hero-block-validation.ts".into(), + "added".into(), + patch(20), + ), + ( + "apps/studio/schemaTypes/blocks/hero-block.ts".into(), + "modified".into(), + patch(3), + ), + ( + "apps/studio/schemaTypes/blocks/hero-block-validation.test.ts".into(), + "added".into(), + patch(12), + ), + ] +} + +fn checks(state: State) -> Vec { + [ + "Test Coverage Report", + "Lint", + "Type check", + "Unit tests", + "Build", + "Studio build", + ] + .iter() + .map(|n| Check { + name: n.to_string(), + url: format!("https://ci.example.com/{}", n.replace(' ', "-")), + state, + }) + .collect() +} + +/// The run's outside work, as the planner wrote it: the staging deploy +/// handed to a person, and the page to look at by its id. +fn the_note() -> OutsideChange { + OutsideChange { + system: "the Studio on staging".into(), + change: "Deploy the Studio so the warning shows to editors".into(), + steps: vec![NoteStep { + step: "Deploy the Studio schema to staging".into(), + by: "person".into(), + owner: "a person on the team".into(), + how: DEPLOY.into(), + kind: "deploy".into(), + target: "staging".into(), + why_person: "the repository has no deploy workflow CoderHelm can start".into(), + reason: "credential".into(), + ..Default::default() + }], + confirm: Some(Confirm { + query: "*[_type == \"heroBlock\"][0]{_type, \"len\": length(subTitle)}".into(), + expect: "{_type: heroBlock, len: 392}".into(), + page: format!("Studio: Events page ({PAGE_ID}), hero Sub Title field"), + result: "[{\"_type\":\"heroBlock\",\"len\":392}]".into(), + ..Default::default() + }), + ..Default::default() + } +} + +/// The repository: staging deploys when a label is on the pull request. +fn the_repo() -> Abilities { + Abilities { + deploys: vec![Route { + name: "Deploy staging".into(), + file: ".github/workflows/deploy-staging.yml".into(), + command: String::new(), + trigger: Trigger::Label("deploy-staging".into()), + }], + ..Default::default() + } +} + +const WRITTEN: &str = "## Description\n\nAdds a Studio warning on the Hero block subtitle past 160 characters.\n\n## Changes\n\n* `apps/studio/schemaTypes/blocks/hero-block-validation.ts`: the length rule.\n* `apps/studio/schemaTypes/blocks/hero-block.ts`: uses it.\n\n## Type of change\n\n- [x] New feature\n"; + +const TEMPLATE: &str = "## Description\n\n\n## Type of change\n- [ ] Bug fix\n- [ ] New feature\n\n## How has this been tested?\n\n## Checklist\n- [ ] I have read the contributing guide\n"; + +/// The body as the run builds it now: the executor's pass over the steps, +/// the facts of the head, the shape, and the one save's review. +fn built(state: State, template: Option<&str>) -> (String, common::pr_facts::Facts) { + let mut c = the_note(); + ow::classify(&mut c); + ow::own_startable(&mut c, &the_repo()); + let files = files(); + let floor = pr_risk::floor(&files, &std::collections::HashMap::new()); + let checks = checks(state); + let f = description_facts::facts(&Inputs { + head: HEAD, + body: WRITTEN, + files: &files, + floor: &floor, + checks: Some(&checks), + why: Some(Why { + reference: "OPS-88".into(), + title: "Warn on long hero subtitles".into(), + url: String::new(), + }), + dependency: None, + outside: Some(&c), + run_url: "https://app.example.com/runs/detail?id=run-88", + notes: vec![], + evidence: vec![], + repo_url: "https://github.com/acme/site", + }); + let shaped = description_facts::shape_for( + WRITTEN, + "OPS-88: Warn on long hero subtitles", + f, + None, + template, + ); + let body = description::with_stamp(&shaped.body, HEAD); + (saved(&body), shaped.facts) +} + +/// What `description::save` writes. +fn saved(body: &str) -> String { + let reviewed = pr_review::review(&description::clean(body)); + let sunk = common::person_gate::sink(&reviewed.body); + common::pr_layout::layout(&sunk.text) +} + +/// 1. The posted text through the final review: each defect is found and +/// fixed. +#[test] +fn the_final_review_fixes_the_posted_description() { + let r = pr_review::review(&posted_before()); + let kinds: Vec = r.findings.iter().map(|f| f.kind).collect(); + for k in [ + Kind::RunningAsResult, + Kind::Filler, + Kind::RawId, + Kind::Duplicate, + Kind::Mixed, + ] { + assert!(kinds.contains(&k), "{k:?} not found: {:#?}", r.findings); + } + let end = Ending { + status: "completed".into(), + pr: Some(88), + draft: false, + words: vec![r.body.clone()], + }; + for old in [OLD[0], OLD[1], OLD[2], OLD[4]] { + end.never_says(old); + } + assert!(end.says("| Lint (CI) | Running; updated here when it ends |")); + assert!(end.says("**Still running on `6de2414`:** `Test Coverage Report`")); + assert_eq!( + r.body + .matches("revert this pull request; nothing outside") + .count() + + r.body + .matches("Revert this pull request; nothing outside") + .count(), + 1, + "{}", + r.body + ); + assert!(end.says("See it: Studio: Events page, hero Sub Title field.")); +} + +/// 2. The run's own build: no running check as a result, rebuilt until the +/// checks end, the deploy CoderHelm's, no filler, no raw id, nothing +/// twice. +#[test] +fn the_description_is_built_with_nothing_frozen_doable_or_said_twice() { + let (body, facts) = built(State::Running, None); + let end = Ending { + status: "awaiting_ci".into(), + pr: Some(88), + draft: false, + words: vec![body.clone()], + }; + for old in OLD { + end.never_says(old); + } + end.never_says("### Needed from you"); + end.never_says("For the reviewer"); + assert!( + end.says("| Lint (CI) | Running; updated here when it ends |"), + "{body}" + ); + assert!( + end.says("6 checks are still running on this head"), + "{body}" + ); + // Built while checks ran: not current, so the next reconcile (the + // checks step, the watch, the end of the run) builds it again. + assert!(body.contains("checks-running"), "{body}"); + assert!(!description::is_current(&body, HEAD)); + // Once they pass, the rows are results and the description is current. + let (done, _) = built(State::Passed, None); + assert!(!done.contains("Running"), "{done}"); + assert!(description::is_current(&done, HEAD)); + // The deploy is CoderHelm's, on the label route; nothing for a person. + assert!(common::pr_facts::needed_items(&facts).is_empty()); + let deploy = facts + .steps + .iter() + .find(|s| s.what.contains("Deploy the Studio")) + .expect("the deploy step"); + assert!(deploy.owner.eq_ignore_ascii_case("coderhelm"), "{deploy:?}"); + // The final review has nothing left to fix in it. + assert!( + pr_review::review(&body).findings.is_empty(), + "{:#?}", + pr_review::review(&body).findings + ); + // And the save runs it, for every writer. + let src = include_str!("../description.rs"); + assert!(fn_src(src, "\npub async fn save(").contains("pr_review::review(")); + assert!(fn_src(src, "\npub fn is_current(").contains("running")); +} + +/// 3. The repository's template is the visible structure, filled with +/// CoderHelm's content, and nothing is said twice below it. +#[test] +fn the_template_is_the_structure() { + let (body, _) = built(State::Passed, Some(TEMPLATE)); + assert!( + pr_review::template_missing(&body, TEMPLATE).is_empty(), + "{body}" + ); + let seen = common::pr_body::in_sight(&body); + let at = |h: &str| { + seen.find(h) + .unwrap_or_else(|| panic!("{h} not in sight:\n{seen}")) + }; + assert!(at("## Description") < at("## Type of change")); + assert!(at("## Type of change") < at("## How has this been tested?")); + assert!(at("## How has this been tested?") < at("## Checklist")); + // The summary under Description, the review focus after it, the checks + // under the testing section, the writer's ticked box kept. + assert!(at("## Description") < at("Adds a Studio warning")); + assert!(at("### Review focus") < at("## Type of change")); + assert!(at("## How has this been tested?") < at("| Check | Result |")); + assert!(seen.contains("- [x] New feature"), "{seen}"); + assert!( + seen.contains("- [ ] I have read the contributing guide"), + "{seen}" + ); + // The written Type of change is not said again in the fold. + assert_eq!(body.matches("- [x] New feature").count(), 1, "{body}"); + // And the rebuild reads the template. + let src = include_str!("../description.rs"); + assert!(fn_src(src, "\nasync fn build(").contains("fetch_pr_template(")); +} + +/// 4. Something outside the code never replaces the change: the plan's +/// code is implemented and its pull request opened, and the run ends +/// delivered with what only a person can do listed once. +#[test] +fn outside_work_never_stops_the_change_or_the_pull_request() { + let outside = FixDecision { + fix_location: FixLocation::OutsideCode, + cause: "Editors need the warning in the Studio.".into(), + outside_change: Some(the_note()), + ..Default::default() + }; + let tasks = "- [ ] apps/studio/schemaTypes/blocks/hero-block-validation.ts: the length rule"; + assert_eq!( + fix_location::route_for_plan(Some(&outside), tasks), + Way::CodeAndOutside, + "the code is made and the pull request opened" + ); + // A plan with nothing to change in the code still reports. + assert_eq!( + fix_location::route_for_plan(Some(&outside), "NO_CODE_CHANGE: data only"), + Way::OutsideOnly + ); + // A person-only step stays, listed once, and the run still completes. + let mut c = the_note(); + c.steps.push(NoteStep { + step: "Confirm the new limit with the vendor by phone".into(), + by: "person".into(), + owner: "the account manager".into(), + kind: "other".into(), + why_person: "a phone call is outside every system CoderHelm reaches".into(), + reason: "outside_reach".into(), + ..Default::default() + }); + ow::classify(&mut c); + ow::own_startable(&mut c, &the_repo()); + let left = ow::left(&c); + assert_eq!(left.human.len(), 1, "{left:?}"); + let resume = include_str!("../resume.rs"); + let end = fn_src(resume, "\nfn end_status("); + assert!(!end.contains("STATUS_OUTSIDE"), "{end}"); + assert!(end.contains("COMPLETED"), "{end}"); + let done = fn_src(resume, "\nasync fn set_run_complete("); + assert!(done.contains("Delivered: the pull request is open")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index d47aa93f0..26cf04540 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -51,6 +51,7 @@ mod bh_round_checks_and_scope; mod bi_own_review_finishes; mod bj_release_through_a_busy_hour; mod bk_owns_the_outside_work; +mod bl_description_final_review; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/outside_exec.rs b/services/worker/src/passes/outside_exec.rs index 1938e2b17..cc10c03cf 100644 --- a/services/worker/src/passes/outside_exec.rs +++ b/services/worker/src/passes/outside_exec.rs @@ -211,6 +211,9 @@ pub async fn execute( // One executor: a step a person was to do that the gate finds // CoderHelm's is done here, like the rest. p.moved = outside_work::classify(c); + // A deploy the repository lets it start is its own, whoever the plan + // named (`outside_work::own_startable`). + p.moved += outside_work::own_startable(c, a); let snapshot = c.clone(); for i in 0..c.steps.len() { let s = &mut c.steps[i]; diff --git a/services/worker/src/passes/outside_work.rs b/services/worker/src/passes/outside_work.rs index 19f2d4bed..69571f81c 100644 --- a/services/worker/src/passes/outside_work.rs +++ b/services/worker/src/passes/outside_work.rs @@ -2095,6 +2095,46 @@ pub fn classify(c: &mut OutsideChange) -> usize { moved } +/// A staging deploy a person was to run that the repository lets CoderHelm +/// start itself (a workflow it can dispatch, or one a pull request label +/// starts) becomes CoderHelm's step on that route. A description once asked +/// a person for "the deploy credentials, or run `npm run deploy:staging` +/// once" while the repository deployed staging from a label CoderHelm adds: +/// CoderHelm never asks for what it can start, and a credential is claimed +/// only by an attempt that failed for one. A production deploy stays with +/// the release steps and their approval. Returns how many moved. +pub fn own_startable(c: &mut OutsideChange, a: &Abilities) -> usize { + let mut moved = 0; + for s in c.steps.iter_mut() { + if s.doer() != Doer::Person || s.done || !s.is_deploy() || s.is_production() { + continue; + } + let text = format!("{} {}", s.step, s.how); + let Some(r) = a + .deploys + .iter() + .filter(|r| r.startable() && !(s.is_production() && is_staging_route(r))) + .find(|r| r.named_in(&text)) + .or_else(|| a.startable_deploy()) + else { + continue; + }; + if !r.named_in(&text) { + s.how = r.file.clone(); + } + s.by = "coderhelm".to_string(); + s.tool = match &r.trigger { + Trigger::Label(_) => "add_labels".to_string(), + _ => "start_workflow".to_string(), + }; + s.why_person.clear(); + s.grant.clear(); + s.reason.clear(); + moved += 1; + } + moved +} + /// The tool a step's words name, for a step moved to CoderHelm. fn tool_named(text: &str) -> String { let t = text.to_lowercase(); diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index a1d54c775..4b878d120 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -2251,8 +2251,44 @@ fn keeps_ticket_line(old: &str, new: &str) -> bool { } } -/// Try to fetch a PR template from common locations in the repo. -async fn fetch_pr_template( +/// How long a repository's template is kept between reads: every rebuild of +/// a description lays it into the template, and rebuilds come often while +/// checks run. +const TEMPLATE_TTL: std::time::Duration = std::time::Duration::from_secs(600); + +type TemplateCache = std::collections::HashMap)>; + +fn template_cache() -> &'static std::sync::Mutex { + static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + CACHE.get_or_init(Default::default) +} + +/// The repository's pull request template, from its common locations: the +/// first draft is written to it, and every rebuild lays the description into +/// it (`common::pr_template`). Kept for a few minutes per repository and +/// branch. +pub(crate) async fn fetch_pr_template( + github: &GitHubClient, + owner: &str, + repo: &str, + base_branch: &str, +) -> Option { + let key = format!("{owner}/{repo}@{base_branch}").to_lowercase(); + if let Ok(c) = template_cache().lock() { + if let Some((at, t)) = c.get(&key) { + if at.elapsed() < TEMPLATE_TTL { + return t.clone(); + } + } + } + let found = read_pr_template(github, owner, repo, base_branch).await; + if let Ok(mut c) = template_cache().lock() { + c.insert(key, (std::time::Instant::now(), found.clone())); + } + found +} + +async fn read_pr_template( github: &GitHubClient, owner: &str, repo: &str, diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 36d02f03e..01a7f18f4 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -8257,18 +8257,23 @@ async fn set_run_complete( return; } let status = end_status(&undone.left); - if status != common::run_status::COMPLETED { + if !undone.left.human.is_empty() { + // Delivered: the pull request is open with the work; what only a + // person can do is listed once, under "Needed from you", there and + // on the ticket. The run does not wait on it. super::add_progress_note( state, team_id, run_id, &format!( - "Waiting on a person for {} item(s) only a person can do; the pull request and the ticket name each once", - undone.left.human.len() + "Delivered: the pull request is open. Needed from a person ({}), listed once under \"Needed from you\": {}", + undone.left.human.len(), + undone.left.human.join("; ") ), ) .await; - } else if !undone.left.doable.is_empty() { + } + if !undone.left.doable.is_empty() { super::add_progress_note( state, team_id, @@ -8317,16 +8322,20 @@ async fn set_run_complete( } } -/// How a run whose CI passed ends: completed, or (with requirements left -/// that need access CoderHelm lacks) needing that outside change. +/// How a run whose CI passed ends: completed. The work was asked for and +/// its pull request is open, so the run is delivered; what is left for a +/// person (only what the gate let through: `may_wait_on_person` counts +/// them) is attached to it under "Needed from you", never a waiting status +/// that reads as "do this, then I'll do it". fn end_status(left: &super::outside_work::Left) -> &'static str { - // Waiting on a person needs at least one item the gate let through and - // nothing CoderHelm can still do. - if common::person_gate::may_wait_on_person(left.human.len(), left.doable.len()) { - super::fix_location::STATUS_OUTSIDE - } else { - "completed" + let waiting = common::person_gate::may_wait_on_person(left.human.len(), left.doable.len()); + if waiting { + tracing::info!( + items = left.human.len(), + "Delivered with items only a person can do, listed on the pull request" + ); } + common::run_status::COMPLETED } #[cfg(test)] @@ -8334,17 +8343,16 @@ mod end_status_tests { use super::end_status; #[test] - fn a_requirement_left_for_a_person_keeps_the_run_from_completing() { + fn a_requirement_left_for_a_person_never_keeps_the_delivered_run_open() { use crate::passes::outside_work::Left; assert_eq!(end_status(&Left::default()), "completed"); let human = Left { human: vec!["1. Replace the hero on production".to_string()], doable: Vec::new(), }; - assert_eq!( - end_status(&human), - crate::passes::fix_location::STATUS_OUTSIDE - ); + // The pull request is open with the work: delivered, with the item + // attached to it. + assert_eq!(end_status(&human), "completed"); // Never waits on a person while CoderHelm holds steps it can do. let both = Left { doable: vec!["Read the preview run".to_string()], diff --git a/services/worker/src/passes/reviewer_guide.rs b/services/worker/src/passes/reviewer_guide.rs index 25495dbe9..680281e77 100644 --- a/services/worker/src/passes/reviewer_guide.rs +++ b/services/worker/src/passes/reviewer_guide.rs @@ -254,12 +254,27 @@ pub fn verified_lines(checks: &[Check], head: &str) -> Vec { short(head) )); } + // Still running is not "not verified": it is said apart, as running, + // and the section is rebuilt when it ends. + let running: Vec = checks + .iter() + .filter(|c| c.state == State::Running) + .map(linked) + .collect(); + if !running.is_empty() { + out.push(format!( + "**Still running on `{}`:** {}; updated here when {}.", + short(head), + running.join(", "), + if running.len() == 1 { + "it ends" + } else { + "they end" + } + )); + } let mut not: Vec = Vec::new(); - for (state, word) in [ - (State::Failed, "failed"), - (State::Running, "still running"), - (State::DidNotRun, "did not run"), - ] { + for (state, word) in [(State::Failed, "failed"), (State::DidNotRun, "did not run")] { let names: Vec = checks .iter() .filter(|c| c.state == state) @@ -479,16 +494,19 @@ mod tests { ]}); let checks = checks_of(&listing); let lines = verified_lines(&checks, HEAD); - assert_eq!(lines.len(), 2); + assert_eq!(lines.len(), 3); assert_eq!( lines[0], "**Verified by:** [`unit`](https://github.com/acme/shop/actions/runs/7/job/4), \ [`lint`](https://github.com/acme/shop/actions/runs/7/job/4) passed on `0a1b2c3`." ); - assert!(lines[1].starts_with("**Not verified on `0a1b2c3`:**")); - assert!(lines[1].contains("job/5) (failed)"), "{}", lines[1]); - assert!(lines[1].contains("job/3) (still running)"), "{}", lines[1]); - assert!(lines[1].contains("job/14) (did not run)"), "{}", lines[1]); + // Still running is said apart from what did not verify the change. + assert!(lines[1].starts_with("**Still running on `0a1b2c3`:**")); + assert!(lines[1].contains("job/3)"), "{}", lines[1]); + assert!(lines[2].starts_with("**Not verified on `0a1b2c3`:**")); + assert!(lines[2].contains("job/5) (failed)"), "{}", lines[2]); + assert!(!lines[2].contains("still running"), "{}", lines[2]); + assert!(lines[2].contains("job/14) (did not run)"), "{}", lines[2]); // A check that did not pass is never among the verified. assert!(!lines[0].contains("e2e") && !lines[0].contains("types")); } From 55ee1841c7a44d08977e29d6ed86588cde56c80d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 12:23:15 -0500 Subject: [PATCH 2/2] A deploy CoderHelm can start is found, started and recorded, and feedback about outside work keeps the code change - Detection: a staging deploy job a pull request label starts, or a dispatchable staging workflow, is a deploy route even when it is not the CMS's; label conditions are read with or without spaces; a run line that runs a package deploy script counts. A production-only route is never taken for staging. - The gate is told: classify_with sets person_gate::Context::can_deploy from the repository's routes, and a deploy CoderHelm can start and has not tried is never a person's credential item (an attempt whose own cause is a listed reason still is). The executor classifies with it. - Executed, not reworded: next_action gives the moved step its route's action (label or dispatch); record_end records the run that ended on the step, which the resume saves on the run. - Feedback: a person saying part of the fix is outside the code keeps the open pull request and its code when the plan coded (route_for_feedback), records the outside part on the run's decision and lists it on the pull request; only a pull request with no code to keep is closed as before. - Incident bl: three cases for the above. --- docs/incidents.md | 2 +- services/common/src/person_gate.rs | 15 +- services/worker/src/passes/feedback.rs | 100 ++++++++-- services/worker/src/passes/fix_location.rs | 47 +++++ .../incidents/bl_description_final_review.rs | 185 +++++++++++++++++- services/worker/src/passes/outside_exec.rs | 63 ++++-- services/worker/src/passes/outside_work.rs | 155 ++++++++++++++- 7 files changed, 515 insertions(+), 52 deletions(-) diff --git a/docs/incidents.md b/docs/incidents.md index 1712de2d0..7093f4415 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -89,7 +89,7 @@ pipeline still calls it there. | bi. `bi_own_review_finishes` | A run's own review asked for changes; its fix rounds were blocked by a refused edit, checks skipped for time and a tool input error, the loop called that "no progress" at its cap of two, deferred a one-line config omission and a placeholder line, and marked the run completed while the run page said a fix round was taking them. The finding contradicted a comment on the ticket, and an outside step asked a person to add labels. | Each finding is tracked on its own: a blocked round is not a stall and the next one removes the block; a stalled finding climbs its own ladder; a finding the ticket, its comments or the plan rule out is settled by their words; only a person-gate reason defers one. A run is never completed while its own review asks for changes on the head or with a deferred item lacking such a reason. A finished run's card never says it is working. CoderHelm adds pull request labels itself. | | bj. `bj_release_through_a_busy_hour` | Two repositories' Security pages read hundreds of findings "in a pull request" for two days, through two releases meant to give them back. The sweep that compares findings with GitHub logged only when it changed something, so a sweep that found every pull request still open left no trace; and while GitHub's budget was low it was held before its first read, three sweeps in a row. Both pull requests were in fact open. | Every sweep leaves one line with what it read, what GitHub said (open, merged, closed, unanswered), what it changed and what it left. A held budget slows the release and never stops it: a few reads a sweep go on a small allowance of their own (`github_budget::caller::FLOOR`), in a turn that reaches every pull request within a few sweeps. | | bk. `bk_owns_the_outside_work` | A run with its pull request open ended waiting on people and its ticket comment handed over work CoderHelm could do: reading workflow runs, a lint, page checks (all failing on one 400 because a page check written as the confirm "query" was sent to the CMS's GROQ API), the production release (a tag after one approval), a review look, and a step number the ticket never showed; it opened on a raw Jira account id and counted nothing as handed over. | Each outside step's action comes from its own words; a failed attempt reaches a person only for a permission or credential in its own cause; a tool failure is diagnosed and reported once and its steps take another way; the release is one approval; a run waits on a person only with a gate-approved item and nothing it can still do; every comment, description, chat message and outside report passes the sink check; replies show names, never account ids; the team's history replays with no doable item reaching a person. | -| bl. `bl_description_final_review` | A pull request description showed six checks as "still running when this was written" in its results and never changed them, asked a person for deploy credentials or to run the staging deploy in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id beside its name, and listed still-running and did-not-run checks on one line. The repository's template only guided the first draft. A run could also end as needing an outside change instead of delivering the code. | Every description passes a final review in the one save (`common::pr_review`): a running check reads Running and is never a result, and the stamp keeps the description rebuilt until the checks end; nothing the gate does not let through reaches a person, and a staging deploy the repository lets CoderHelm start is CoderHelm's step; nothing is said twice; no filler; no raw id beside a name; running and did-not-run are said apart. The repository's template is the visible structure, filled with CoderHelm's content (`common::pr_template`). A plan with code is implemented and its pull request opened whatever outside work it needs, and the run ends delivered with only person-only items listed once under Needed from you. | +| bl. `bl_description_final_review` | A pull request description showed six checks as "still running when this was written" in its results and never changed them, asked a person for deploy credentials or to run the staging deploy in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id beside its name, and listed still-running and did-not-run checks on one line. The repository's template only guided the first draft. A run could also end as needing an outside change instead of delivering the code. | Every description passes a final review in the one save (`common::pr_review`): a running check reads Running and is never a result, and the stamp keeps the description rebuilt until the checks end; nothing the gate does not let through reaches a person, and a staging deploy the repository lets CoderHelm start (a dispatchable workflow, or a job a pull request label starts) is CoderHelm's step: the gate is told it can deploy, and the executor adds the label or dispatches, waits for the run and records its end; nothing is said twice; no filler; no raw id beside a name; running and did-not-run are said apart. The repository's template is the visible structure, filled with CoderHelm's content (`common::pr_template`). A plan with code is implemented and its pull request opened whatever outside work it needs, a person's feedback that part of the fix is outside the code keeps the code and its open pull request with the outside part attached, and the run ends delivered with only person-only items listed once under Needed from you. | ## Adding a case diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index daf45ebdc..e592bd87e 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -976,10 +976,17 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { /// A deploy: CoderHelm runs it when it holds the credentials; else the one /// missing thing is said once. fn deploy_item(a: &Ask, t: &str, ctx: &Context) -> Outcome { - if ctx.can_deploy { - if let Some(c) = command_in(a) { - return Outcome::Do(Work::Command(c)); - } + // A deploy CoderHelm can start (a workflow it dispatches or one a label + // starts, or credentials it holds) is its own: never a credential item + // for a person while it has not tried. An attempt whose own cause is a + // listed reason still reaches a person. + let tried_and_refused = + a.kind == Kind::Attempt && reason_in(&one_line(&a.why_not).to_lowercase()).is_some(); + if ctx.can_deploy && !tried_and_refused { + return Outcome::Do(match command_in(a) { + Some(c) => Work::Command(c), + None => Work::Own(one_line(&a.text)), + }); } let reason = reason_in(t).unwrap_or(Reason::Credential); let missing = match reason { diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index ba224d0ce..6935b81f0 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -63,25 +63,36 @@ pub async fn run( if let Some(judgment) = super::lessons::check_comment(state, &provider, &github, &msg, &mut usage).await { - info!(run_id = %msg.run_id, "Feedback says the fix is outside the code — lesson recorded, no code change"); - let closed = close_own_pr_outside( - state, - &github, - &OwnPr { - team_id: &msg.team_id, - run_id: &msg.run_id, - owner: &msg.repo_owner, - repo: &msg.repo_name, - pr_number: msg.pr_number, - }, - &judgment.where_, - &judgment.lesson, - ) - .await; - if !closed { - finish_without_change(state, &msg).await; + // Part of the fix outside the code never undoes the code change: a + // pull request that carries the plan's code stays open, with the + // outside part attached (`fix_location::route_for_feedback`). + if keep_code_with_outside(state, &github, &msg, &judgment.where_, &judgment.lesson).await { + if !judgment.also_wants_code_change { + finish_without_change(state, &msg).await; + return Ok(()); + } + info!(run_id = %msg.run_id, "Feedback also asks for a code change — handled as feedback"); + } else { + info!(run_id = %msg.run_id, "Feedback says the fix is outside the code — lesson recorded, no code change"); + let closed = close_own_pr_outside( + state, + &github, + &OwnPr { + team_id: &msg.team_id, + run_id: &msg.run_id, + owner: &msg.repo_owner, + repo: &msg.repo_name, + pr_number: msg.pr_number, + }, + &judgment.where_, + &judgment.lesson, + ) + .await; + if !closed { + finish_without_change(state, &msg).await; + } + return Ok(()); } - return Ok(()); } if !ensure_pr_open(state, &github, &mut msg).await { @@ -3772,6 +3783,59 @@ async fn finish_without_change(state: &WorkerState, msg: &FeedbackMessage) { } } +/// A person said part of the fix is outside the code: when the run's plan +/// coded and its pull request carries that code, the pull request stays +/// open, the outside part is recorded on the run's decision and listed on +/// the pull request (done by CoderHelm where it can, the rest once under +/// "Needed from you"), and true is returned. False when there is no code to +/// keep: the caller closes the pull request as before. +async fn keep_code_with_outside( + state: &WorkerState, + github: &GitHubClient, + msg: &FeedbackMessage, + where_: &str, + cause: &str, +) -> bool { + use super::fix_location::{self, Route}; + let Ok(pr) = github + .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + else { + return false; + }; + if pr["state"].as_str() != Some("open") { + return false; + } + let changed = pr["changed_files"].as_u64().unwrap_or(0); + let record = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", super::attr_s(&msg.team_id)) + .key("run_id", super::attr_s(&msg.run_id)) + .send() + .await + .ok() + .and_then(|o| o.item) + .unwrap_or_default(); + let planned = super::outside_exec::decision_of(&record); + if fix_location::route_for_feedback(planned.as_ref(), changed) != Route::CodeAndOutside { + return false; + } + let d = fix_location::with_outside_part(planned.as_ref(), where_, cause); + super::outside_exec::save(state, &msg.team_id, &msg.run_id, &d).await; + super::outside_exec::refresh_pr(github, &msg.repo_owner, &msg.repo_name, msg.pr_number, &d) + .await; + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + "A person said part of the fix is outside the code: the code change stays in the open pull request, and the outside part is listed on it", + ) + .await; + true +} + /// While a run is awaiting CI or running, the resume flow owns CI fixing /// (budget, stall detection, scope guard); feedback must not fix CI too. fn resume_owns_ci(run_status: &str) -> bool { diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index 2cd2fd018..48f809b0e 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -660,6 +660,53 @@ pub fn route_for_plan(decision: Option<&FixDecision>, tasks: &str) -> Route { } } +/// How a run goes on when a person's feedback says (part of) the fix is +/// outside the code: the code change stays and its pull request stays open +/// whenever the plan changed code and the pull request carries it, with the +/// outside part attached ([`Route::CodeAndOutside`], as [`route_for_plan`] +/// routes a plan); only a pull request that changes nothing the plan +/// decided as code is closed ([`Route::OutsideOnly`]). +pub fn route_for_feedback(planned: Option<&FixDecision>, pr_changed_files: u64) -> Route { + let planned_code = match planned { + Some(d) => matches!(route(Some(d)), Route::Code | Route::CodeAndOutside), + // A run that opened a pull request with no recorded decision coded + // what its plan named. + None => true, + }; + if pr_changed_files > 0 && planned_code { + Route::CodeAndOutside + } else { + Route::OutsideOnly + } +} + +/// `planned` with the outside part a person named added: the location is +/// both, and the outside change is the planner's when it had one, else +/// what the person said. +pub fn with_outside_part(planned: Option<&FixDecision>, where_: &str, cause: &str) -> FixDecision { + let mut d = planned.cloned().unwrap_or_default(); + d.fix_location = FixLocation::Both; + let usable = d + .outside_change + .as_ref() + .is_some_and(OutsideChange::is_usable); + if !usable { + d.outside_change = Some(OutsideChange { + system: if where_.trim().is_empty() { + "the system that holds this data".to_string() + } else { + where_.trim().to_string() + }, + change: cause.trim().to_string(), + ..Default::default() + }); + } + if d.cause.trim().is_empty() { + d.cause = cause.trim().to_string(); + } + d +} + /// Whether a plan's tasks change code: anything but the sentinels that say /// it changes none. pub fn plans_code(tasks: &str) -> bool { diff --git a/services/worker/src/passes/incidents/bl_description_final_review.rs b/services/worker/src/passes/incidents/bl_description_final_review.rs index 30b2f1534..a2caf963b 100644 --- a/services/worker/src/passes/incidents/bl_description_final_review.rs +++ b/services/worker/src/passes/incidents/bl_description_final_review.rs @@ -189,8 +189,7 @@ const TEMPLATE: &str = "## Description\n\n\n## Type of chan /// the facts of the head, the shape, and the one save's review. fn built(state: State, template: Option<&str>) -> (String, common::pr_facts::Facts) { let mut c = the_note(); - ow::classify(&mut c); - ow::own_startable(&mut c, &the_repo()); + ow::classify_with(&mut c, &the_repo()); let files = files(); let floor = pr_risk::floor(&files, &std::collections::HashMap::new()); let checks = checks(state); @@ -390,8 +389,7 @@ fn outside_work_never_stops_the_change_or_the_pull_request() { reason: "outside_reach".into(), ..Default::default() }); - ow::classify(&mut c); - ow::own_startable(&mut c, &the_repo()); + ow::classify_with(&mut c, &the_repo()); let left = ow::left(&c); assert_eq!(left.human.len(), 1, "{left:?}"); let resume = include_str!("../resume.rs"); @@ -401,3 +399,182 @@ fn outside_work_never_stops_the_change_or_the_pull_request() { let done = fn_src(resume, "\nasync fn set_run_complete("); assert!(done.contains("Delivered: the pull request is open")); } + +/// The repository's files: a staging deploy job a pull request label +/// starts (no dispatch), the package script it runs, and a production +/// deploy that is dispatched. +fn label_repo() -> Abilities { + let files: Vec<(String, String)> = vec![ + ( + ".github/workflows/deploy-staging.yml".into(), + "name: Deploy staging\non:\n pull_request:\n types: [labeled, synchronize]\njobs:\n deploy:\n if: contains(github.event.pull_request.labels.*.name, 'deploy-staging')\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - run: npm ci\n - run: cd apps/studio && npm run deploy:staging\n".into(), + ), + ( + ".github/workflows/deploy-production.yml".into(), + "name: Deploy production\non:\n workflow_dispatch:\njobs:\n deploy:\n runs-on: ubuntu-latest\n steps:\n - run: npm run deploy:production\n".into(), + ), + ( + "apps/studio/package.json".into(), + "{\"scripts\": {\"deploy:staging\": \"node scripts/ship.js --env staging\", \"deploy:production\": \"node scripts/ship.js --env production\"}}".into(), + ), + ]; + let tree: Vec = files.iter().map(|(p, _)| p.clone()).collect(); + ow::abilities(&tree, &files, &[], false) +} + +/// 5. A staging deploy defined by a label-triggered job is found, the gate +/// is told CoderHelm can deploy, and the step is CoderHelm's: never a +/// credential item while it has not tried. +#[test] +fn a_label_triggered_staging_deploy_job_is_coderhelms() { + let a = label_repo(); + let staging = a + .deploys + .iter() + .find(|r| r.file.ends_with("deploy-staging.yml")) + .expect("the label-triggered staging deploy is found"); + assert_eq!(staging.trigger, Trigger::Label("deploy-staging".into())); + assert!(staging.startable()); + assert!(a.can_deploy(ow::Target::Staging)); + // The gate, told what the repository lets CoderHelm do. + let mut c = the_note(); + let ask = ow::step_now(&c, 0, true).unwrap().ask(); + let ctx = common::person_gate::Context { + can_deploy: a.can_deploy(ow::Target::Staging), + ..Default::default() + }; + assert!(!matches!( + common::person_gate::decide(&ask, &ctx), + common::person_gate::Outcome::Human(_) + )); + // Without that knowledge it was a credential item: the old failure. + assert!(matches!( + common::person_gate::decide(&ask, &common::person_gate::Context::default()), + common::person_gate::Outcome::Human(_) + )); + assert_eq!(ow::classify_with(&mut c, &a), 1); + let s = &c.steps[0]; + assert_eq!(s.doer(), ow::Doer::CoderHelm); + assert!(s.reason.is_empty() && s.why_person.is_empty()); + assert!(ow::left(&c).human.is_empty()); + // A failed attempt whose own cause is a credential still reaches a + // person: the gate says what the attempt found, not a guess. + let tried = common::person_gate::Ask { + kind: common::person_gate::Kind::Attempt, + text: "Deploy the Studio schema to staging".into(), + how: DEPLOY.into(), + why_not: "the deploy token is missing; provide the token in the sandbox secrets".into(), + ..Default::default() + }; + assert!(matches!( + common::person_gate::decide(&tried, &ctx), + common::person_gate::Outcome::Human(_) + )); +} + +/// 6. "CoderHelm does this on its next step" is true: the executor's next +/// action for the step adds the label that starts the job, the run it +/// starts is waited for, and its end is recorded on the step and the +/// run's decision. +#[test] +fn the_deploy_step_is_executed_not_only_reworded() { + use crate::passes::outside_exec::{self, record_end, START_WORKFLOW}; + let a = label_repo(); + let mut c = the_note(); + ow::classify_with(&mut c, &a); + let snapshot = c.clone(); + let action = outside_exec::next_action(&c.steps[0], &a, &snapshot).expect("it is done now"); + let route = match &action { + ow::Action::Label(l, r) => { + assert_eq!(l, "deploy-staging"); + r.clone() + } + other => panic!("not started: {other:?}"), + }; + assert!(route.file.ends_with("deploy-staging.yml")); + let (tool, args) = outside_exec::gate_args(&c.steps[0], &action, "acme/site", "feat").unwrap(); + assert_eq!(tool, START_WORKFLOW); + assert_eq!(args["label"], "deploy-staging"); + // Started: the step waits on the job, and says so. + c.steps[0].run = Some(ow::StepRun { + state: outside_exec::RUNNING.into(), + workflow: route.file.clone(), + ..Default::default() + }); + c.steps[0].result = format!( + "added `deploy-staging` to #88, which starts {}", + route.line() + ); + let st = ow::step_now(&c, 0, true).unwrap(); + assert!( + matches!(&st.state, common::pr_steps::State::Waiting { on } if on.contains("workflow it started ends")), + "{st:?}" + ); + assert!( + outside_exec::next_action(&c.steps[0], &a, &c.clone()).is_some(), + "polled again" + ); + // Ended: recorded, done, nothing left. + let run = serde_json::json!({"id": 4242, "html_url": "https://github.com/acme/site/actions/runs/4242", "head_sha": "6de2414"}); + assert!(record_end(&mut c.steps[0], &route, &run, "success", vec![]).is_none()); + let s = &c.steps[0]; + assert!(s.done); + assert_eq!(s.run.as_ref().unwrap().workflow_run_id, 4242); + assert!(s.result.contains("concluded `success`"), "{}", s.result); + assert!(matches!( + ow::step_now(&c, 0, true).unwrap().state, + common::pr_steps::State::Done { .. } + )); + assert!(ow::left(&c).doable.is_empty() && ow::left(&c).human.is_empty()); + assert!(outside_exec::next_action(&c.steps[0], &a, &c.clone()).is_none()); + // The executor runs this path, and the resume saves it on the run. + let src = include_str!("../outside_exec.rs"); + let exec = fn_src(src, "\npub async fn execute("); + assert!(exec.contains("outside_work::classify_with(") && exec.contains("next_action(")); + let start = fn_src(src, "\nasync fn start("); + assert!(start.contains(".add_labels(") && start.contains("poll(cx, s, r, until, p)")); + assert!(fn_src(src, "\nasync fn finish(").contains("record_end(")); + let resume = fn_src(src, "\npub async fn on_resume("); + assert!(resume.contains("save(state") && resume.contains("refresh_pr(")); +} + +/// 7. A person saying part of the fix is outside the code keeps the code +/// change and its open pull request, with the outside part attached. +#[test] +fn feedback_naming_outside_work_keeps_the_code_change() { + let coded = FixDecision { + fix_location: FixLocation::Code, + cause: "Editors need the warning in the Studio.".into(), + ..Default::default() + }; + assert_eq!( + fix_location::route_for_feedback(Some(&coded), 3), + Way::CodeAndOutside + ); + assert_eq!( + fix_location::route_for_feedback(None, 3), + Way::CodeAndOutside + ); + // Nothing coded to keep: closed as before. + assert_eq!( + fix_location::route_for_feedback(Some(&coded), 0), + Way::OutsideOnly + ); + let d = fix_location::with_outside_part( + Some(&coded), + "the CMS", + "Set the limit field on the hero type", + ); + assert_eq!(d.fix_location, FixLocation::Both); + assert_eq!(fix_location::route(Some(&d)), Way::CodeAndOutside); + assert_eq!(d.outside_change.as_ref().unwrap().system, "the CMS"); + // The feedback pass keeps the code before it would close anything. + let fb = include_str!("../feedback.rs"); + let keep = fb.find("keep_code_with_outside(state").expect("kept"); + let close = fb + .find("let closed = close_own_pr_outside(") + .expect("closed"); + assert!(keep < close); + let body = fn_src(fb, "\nasync fn keep_code_with_outside("); + assert!(body.contains("route_for_feedback(") && body.contains("refresh_pr(")); +} diff --git a/services/worker/src/passes/outside_exec.rs b/services/worker/src/passes/outside_exec.rs index cc10c03cf..d863f1acd 100644 --- a/services/worker/src/passes/outside_exec.rs +++ b/services/worker/src/passes/outside_exec.rs @@ -210,10 +210,9 @@ pub async fn execute( }); // One executor: a step a person was to do that the gate finds // CoderHelm's is done here, like the rest. - p.moved = outside_work::classify(c); - // A deploy the repository lets it start is its own, whoever the plan - // named (`outside_work::own_startable`). - p.moved += outside_work::own_startable(c, a); + // With what the repository lets it do: a deploy it can start is its own, + // whoever the plan named (`outside_work::classify_with`). + p.moved = outside_work::classify_with(c, a); let snapshot = c.clone(); for i in 0..c.steps.len() { let s = &mut c.steps[i]; @@ -235,7 +234,9 @@ pub async fn execute( continue; } p.changed = true; - let action = outside_work::action_for(s, a, &snapshot); + let Some(action) = next_action(s, a, &snapshot) else { + continue; + }; let running = s.run.as_ref().is_some_and(|r| r.state == RUNNING); if running { if let Some(Action::Dispatch(r) | Action::Label(_, r)) = Some(action.clone()) { @@ -261,6 +262,21 @@ pub async fn execute( p } +/// What the executor does with a step now: `None` when the step is not +/// CoderHelm's, is done, or ended earlier without being done. A deploy +/// moved to CoderHelm (`outside_work::classify_with`) gets its route's +/// action here: the label added or the workflow dispatched, then waited +/// for and its result recorded ([`record_end`]). +pub fn next_action(s: &NoteStep, a: &Abilities, c: &OutsideChange) -> Option { + if s.doer() != Doer::CoderHelm || s.done { + return None; + } + if !s.result.trim().is_empty() && !outside_work::under_way(s) { + return None; + } + Some(outside_work::action_for(s, a, c)) +} + /// Whether later steps wait for this one when it isn't done: a deploy (the /// content after it needs its fields) or a content change (the confirm and /// the tests read it). @@ -722,7 +738,6 @@ async fn finish( p: &mut Progress, ) { let id = run["id"].as_u64().unwrap_or(0); - let url = run["html_url"].as_str().unwrap_or_default().to_string(); let ok = conclusion == "success"; let failing = if ok { Vec::new() @@ -733,6 +748,25 @@ async fn finish( .map(|l| failing_tests(&l)) .unwrap_or_default() }; + if let Some(f) = record_end(s, r, run, conclusion, failing) { + p.failed_e2e = Some(f); + } + info!(run_id = cx.run_id, workflow = %r.file, conclusion, "Outside step's workflow ended"); +} + +/// A started workflow ended: the step records the run, its conclusion and +/// result line (done on success), and a failed end-to-end run is returned +/// for the CI fix round. +pub fn record_end( + s: &mut NoteStep, + r: &Route, + run: &Value, + conclusion: &str, + failing: Vec, +) -> Option { + let id = run["id"].as_u64().unwrap_or(0); + let url = run["html_url"].as_str().unwrap_or_default().to_string(); + let ok = conclusion == "success"; s.done = ok; s.run = Some(StepRun { state: if ok { DONE } else { FAILED }.to_string(), @@ -744,16 +778,13 @@ async fn finish( ..s.run.clone().unwrap_or_default() }); s.result = report_line(r, &url, conclusion, &failing); - if !ok && s.step_kind() == StepKind::E2e { - p.failed_e2e = Some(FailedRun { - workflow_run_id: id, - workflow: r.name.clone(), - url, - head_sha: run["head_sha"].as_str().unwrap_or_default().to_string(), - failing, - }); - } - info!(run_id = cx.run_id, workflow = %r.file, conclusion, "Outside step's workflow ended"); + (!ok && s.step_kind() == StepKind::E2e).then(|| FailedRun { + workflow_run_id: id, + workflow: r.name.clone(), + url, + head_sha: run["head_sha"].as_str().unwrap_or_default().to_string(), + failing, + }) } /// The step's result line for a finished run. diff --git a/services/worker/src/passes/outside_work.rs b/services/worker/src/passes/outside_work.rs index 69571f81c..f271fbc0d 100644 --- a/services/worker/src/passes/outside_work.rs +++ b/services/worker/src/passes/outside_work.rs @@ -286,25 +286,88 @@ fn workflow_name(text: &str) -> Option { .filter(|n| !n.is_empty()) } -/// The label a workflow runs on, when it runs on a labelled pull request. +/// The label a workflow runs on, when it runs on a labelled pull request: +/// `github.event.label.name == 'x'` or `contains(...labels.*.name, 'x')`, +/// with or without spaces, at the workflow's or a job's `if:`. fn workflow_label(text: &str) -> Option { if !text.contains("labeled") { return None; } - for pat in ["github.event.label.name == ", "labels.*.name, "] { - if let Some(i) = text.find(pat) { - let rest = &text[i + pat.len()..]; - let q = rest.chars().next()?; + for pat in ["label.name", "labels.*.name"] { + let mut from = 0; + while let Some(i) = text[from..].find(pat) { + let at = from + i + pat.len(); + from = at; + let rest = text[at..].trim_start_matches([' ', '=', ',', '\t']); + let Some(q) = rest.chars().next() else { + break; + }; if q == '\'' || q == '"' { let inner = &rest[1..]; - let end = inner.find(q)?; - return Some(inner[..end].to_string()); + if let Some(end) = inner.find(q) { + let l = inner[..end].trim(); + if !l.is_empty() { + return Some(l.to_string()); + } + } } } } None } +/// The package scripts that deploy (`deploy`, `deploy:staging`, or any +/// script whose command deploys), by name. +fn deploy_scripts(files: &[(String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, text) in files { + if path.rsplit('/').next() != Some("package.json") { + continue; + } + let Ok(v) = serde_json::from_str::(text) else { + continue; + }; + for (name, cmd) in v["scripts"].as_object().into_iter().flatten() { + let cmd = cmd.as_str().unwrap_or("").to_lowercase(); + if name.to_lowercase().starts_with("deploy") || cmd.contains("deploy") { + out.push(name.clone()); + } + } + } + out +} + +/// A deploy a workflow runs that is not the CMS's: a `run` line that +/// deploys, or that runs a package script that does. Only for a workflow +/// about staging or a preview, so a production deploy is never taken for +/// the staging one. +fn staging_deploy_command(path: &str, text: &str, scripts: &[String]) -> Option { + let about = format!("{path} {}", workflow_name(text).unwrap_or_default()).to_lowercase() + + &workflow_label(text).unwrap_or_default().to_lowercase(); + let staging = ["staging", "stage", "preview"] + .iter() + .any(|w| about.contains(w)); + if !staging { + return None; + } + text.lines() + .map(str::trim) + .filter(|l| !l.starts_with('#')) + .map(|l| l.trim_start_matches("- ").trim()) + .filter_map(|l| l.strip_prefix("run:").map(str::trim)) + .find(|l| { + let c = l.to_lowercase(); + c.contains("deploy") + || scripts.iter().any(|s| { + let s = s.to_lowercase(); + c.contains(&format!("run {s}")) + || c.contains(&format!("pnpm {s}")) + || c.contains(&format!("yarn {s}")) + }) + }) + .map(str::to_string) +} + /// The command a workflow runs that deploys the studio or schema: a `run` /// line that deploys, never the words "deploy" and "studio" somewhere in /// the file. A test workflow that only mentions both once started for a @@ -363,6 +426,7 @@ fn route_for(path: &str, text: &str, command: &str) -> Route { pub fn routes(tree: &[String], files: &[(String, String)]) -> (Vec, Vec) { let mut deploys = Vec::new(); let mut e2e = Vec::new(); + let scripts = deploy_scripts(files); for (path, text) in files { let workflow = path.starts_with(".github/workflows/") && (path.ends_with(".yml") || path.ends_with(".yaml")); @@ -370,6 +434,13 @@ pub fn routes(tree: &[String], files: &[(String, String)]) -> (Vec, Vec Option<&Route> { - self.deploys.iter().find(|r| r.startable()) + self.deploys + .iter() + .find(|r| r.startable() && !is_production_route(r)) + } + + /// Whether CoderHelm can start a deploy to `target` itself: a workflow + /// it dispatches or one a pull request label starts. What the gate is + /// told (`person_gate::Context::can_deploy`). + pub fn can_deploy(&self, target: Target) -> bool { + self.deploys.iter().any(|r| { + r.startable() + && match target { + Target::Staging => !is_production_route(r), + Target::Production => !is_staging_route(r), + } + }) } fn startable_e2e(&self) -> Option<&Route> { @@ -2113,7 +2199,7 @@ pub fn own_startable(c: &mut OutsideChange, a: &Abilities) -> usize { let Some(r) = a .deploys .iter() - .filter(|r| r.startable() && !(s.is_production() && is_staging_route(r))) + .filter(|r| r.startable() && !is_production_route(r)) .find(|r| r.named_in(&text)) .or_else(|| a.startable_deploy()) else { @@ -2135,6 +2221,45 @@ pub fn own_startable(c: &mut OutsideChange, a: &Abilities) -> usize { moved } +/// [`classify`] with what the repository lets CoderHelm do: each person +/// step goes through the gate with `can_deploy` read from the repository's +/// deploy routes, so a deploy CoderHelm can start (and has not tried) is +/// never a person's credential item; it becomes CoderHelm's step on that +/// route ([`own_startable`]) and the executor starts it. Returns how many +/// steps moved. +pub fn classify_with(c: &mut OutsideChange, a: &Abilities) -> usize { + let mut moved = classify(c); + for i in 0..c.steps.len() { + let s = &c.steps[i]; + if s.doer() != Doer::Person || s.done || !s.is_deploy() { + continue; + } + let ctx = common::person_gate::Context { + can_deploy: a.can_deploy(s.target()), + ..Default::default() + }; + let human = step_now(c, i, true).is_some_and(|st| { + matches!( + common::person_gate::decide(&st.ask(), &ctx), + common::person_gate::Outcome::Human(_) + ) + }); + if human || s.is_production() { + continue; + } + let one = OutsideChange { + steps: vec![c.steps[i].clone()], + ..Default::default() + }; + let mut one = one; + if own_startable(&mut one, a) == 1 { + c.steps[i] = one.steps.remove(0); + moved += 1; + } + } + moved +} + /// The tool a step's words name, for a step moved to CoderHelm. fn tool_named(text: &str) -> String { let t = text.to_lowercase(); @@ -2504,6 +2629,18 @@ pub fn check_action(s: &NoteStep, a: &Abilities, c: &OutsideChange) -> Action { } /// Whether a route deploys staging. +/// A route that deploys production only: never started for staging. +fn is_production_route(r: &Route) -> bool { + let t = format!("{} {} {}", r.name, r.file, r.command).to_lowercase(); + let label = match &r.trigger { + Trigger::Label(l) => l.to_lowercase(), + _ => String::new(), + }; + (t.contains("prod") || label.contains("prod")) + && !t.contains("staging") + && !label.contains("staging") +} + fn is_staging_route(r: &Route) -> bool { format!("{} {} {}", r.name, r.file, r.command) .to_lowercase()