From a37d0105d5739ea0748e147213a217df3dc78911 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 12 Nov 2026 01:18:34 -0500 Subject: [PATCH] PR bodies fit GitHub's limit; a refused PR waits with GitHub's words; Retry opens it from the work --- services/common/src/lib.rs | 2 + services/common/src/pr_body_fit.rs | 737 ++++++++++++++++ services/common/src/security_fixes.rs | 863 +++++++++++++++++++ services/common/src/upgrade_notes.rs | 80 +- services/worker/src/clients/github.rs | 210 ++++- services/worker/src/passes/mod.rs | 146 +++- services/worker/src/passes/pr.rs | 144 +++- services/worker/src/passes/security_fixes.rs | 126 ++- services/worker/src/passes/stop_pr.rs | 298 ++++++- 9 files changed, 2534 insertions(+), 72 deletions(-) create mode 100644 services/common/src/pr_body_fit.rs diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 549a6c875..d4edec81a 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -143,6 +143,8 @@ mod model_call_sites; pub mod own_pr; /// Paginated DynamoDB lookups (follow LastEvaluatedKey to a match). pub mod paged; +/// Every body CoderHelm sends GitHub fits GitHub's limit. +pub mod pr_body_fit; /// What happened to a PR Coderhelm opened, read from GitHub. pub mod pr_outcome; pub mod run_prs; diff --git a/services/common/src/pr_body_fit.rs b/services/common/src/pr_body_fit.rs new file mode 100644 index 000000000..e8d7098e0 --- /dev/null +++ b/services/common/src/pr_body_fit.rs @@ -0,0 +1,737 @@ +//! Every body CoderHelm sends GitHub fits GitHub's limit. +//! +//! GitHub refuses a pull request, issue or comment body over 65,536 +//! characters (`422 Validation Failed: body is too long`). A bundled +//! security fix of 55 packages and 229 advisories wrote a description far +//! over that, and the run that had done all of its work ended without its +//! pull request. +//! +//! [`fit`] keeps what a reader and CoderHelm need and shrinks the long +//! parts. Kept as written: the text before the first `## ` heading (the +//! ticket line, the draft status, the "Not yet verified" block), every +//! section CoderHelm or a reviewer reads first (Summary, Not finished, CI +//! failing, Not yet verified, Verification, Open items, Proof, Risk), a +//! dependency fix run's account (its `### Dependency fix run` block under +//! What to check: the bumps applied, the ones deferred with why, the +//! sandbox's checks and the cost), every `## ` heading (so a section rewritten in place later is still found), and +//! every line holding an HTML comment (the markers CoderHelm parses later). +//! Shrunk, largest section first and a step at a time: nested detail under +//! a list item, then long lists (capped, with "and N more"), then a whole +//! section's text (a line saying where the full detail is). Only a body +//! whose kept parts alone are over the limit is cut further, and even then +//! its markers stay. + +use std::fmt::Write as _; + +/// GitHub's limit for a pull request, issue or comment body, in characters. +pub const GITHUB_BODY_MAX: usize = 65_536; + +/// What [`fit`] aims for, in bytes: a byte count is never below the +/// character count GitHub measures, and the room left covers the notice. +pub const BODY_TARGET: usize = 64_000; + +/// GitHub's limit for a pull request or issue title, in characters. +pub const GITHUB_TITLE_MAX: usize = 256; + +/// The sections kept as written, by the start of their heading. +const KEPT: [&str; 11] = [ + "summary", + "not finished", + "ci failing", + "not yet verified", + "verification", + "open items", + "proof", + "risk", + "why it stopped", + "what you can do", + "dependency fix run", +]; + +/// The notice a shortened body ends with. +pub const SHORTENED: &str = "Some lists here are shortened to fit GitHub's limit for a description"; + +/// True when GitHub takes `body` as it is. +pub fn fits(body: &str) -> bool { + body.chars().count() <= GITHUB_BODY_MAX +} + +/// `title` within GitHub's title limit. +pub fn fit_title(title: &str) -> String { + if title.chars().count() <= GITHUB_TITLE_MAX { + return title.to_string(); + } + let mut out: String = title.chars().take(GITHUB_TITLE_MAX - 3).collect(); + out.push_str("..."); + out +} + +/// `body` within GitHub's limit (as it is when it already fits). +pub fn fit(body: &str) -> String { + fit_to(body, BODY_TARGET, None) +} + +/// [`fit`], with `more` (a link) named where detail is left out. +pub fn fit_with_link(body: &str, more: &str) -> String { + fit_to( + body, + BODY_TARGET, + Some(more).filter(|m| !m.trim().is_empty()), + ) +} + +/// `body` within `target` bytes, shrunk as the module says. +pub fn fit_to(body: &str, target: usize, more: Option<&str>) -> String { + if body.len() <= target { + return body.to_string(); + } + let notice = match more { + Some(m) => format!("\n\n_{SHORTENED}. Full detail: {m}_\n"), + None => format!("\n\n_{SHORTENED}._\n"), + }; + let budget = target.saturating_sub(notice.len()).max(1); + let mut doc = Doc::parse(body); + let and_more = |n: usize| match more { + Some(m) => format!("- and {n} more (full list: {m})"), + None => format!("- and {n} more"), + }; + // Each step applies to one section at a time, largest first, until the + // body fits: the kept sections only after every other one is a stub. + for kept_too in [false, true] { + for level in LEVELS { + loop { + if doc.len() <= budget { + return doc.render() + ¬ice; + } + let Some(i) = doc.largest_shrinkable(kept_too, level) else { + break; + }; + let section = &mut doc.sections[i]; + section.lines = shrink(§ion.lines, level, &and_more, more); + section.levels_done = section.levels_done.max(level.rank + 1); + } + } + } + // Only the text before the first heading is left over the limit: cut it, + // keeping every marker. + let rendered = doc.render(); + cut_keeping_markers(&rendered, budget) + ¬ice +} + +/// One step of shrinking. +#[derive(Clone, Copy)] +struct Level { + rank: u8, + /// Nested lines kept under a list item (and lines under a `###`). + children: usize, + /// Top-level items kept in a list (items, table rows, `###` blocks). + items: usize, + /// The section's text becomes one line. + stub: bool, +} + +const LEVELS: [Level; 6] = [ + Level { + rank: 0, + children: 6, + items: 60, + stub: false, + }, + Level { + rank: 1, + children: 2, + items: 30, + stub: false, + }, + Level { + rank: 2, + children: 0, + items: 15, + stub: false, + }, + Level { + rank: 3, + children: 0, + items: 6, + stub: false, + }, + Level { + rank: 4, + children: 0, + items: 2, + stub: false, + }, + Level { + rank: 5, + children: 0, + items: 0, + stub: true, + }, +]; + +struct Section { + /// The `## ` line, or `None` for the text before the first one. + heading: Option, + lines: Vec, + kept: bool, + levels_done: u8, +} + +impl Section { + fn len(&self) -> usize { + self.heading.as_ref().map_or(0, |h| h.len() + 1) + + self.lines.iter().map(|l| l.len() + 1).sum::() + } +} + +struct Doc { + sections: Vec
, + trailing_newline: bool, +} + +fn is_heading2(line: &str) -> bool { + line.starts_with("## ") +} + +fn is_marker(line: &str) -> bool { + line.contains(""; + const UNFINISHED_END: &str = ""; + + /// A body like the bundled security fix's: the ticket line, the + /// draft status block, the kept sections, and long per-package detail. + fn big_body(packages: usize, advisories: usize) -> String { + let mut s = String::from("Source ticket: SEC-1\n\n\n> [!WARNING]\n> **Not yet verified**\n> - **Waiting on CI:** build \n\n\n"); + s.push_str(&format!("{UNFINISHED_START}\n## Not finished\n- **Why it stopped:** a check errored.\n{UNFINISHED_END}\n\n")); + s.push_str("## Summary\n\nFixes advisories in many packages.\n\n| Package | Version |\n| --- | --- |\n"); + for p in 0..packages { + s.push_str(&format!("| `pkg-{p}` | 1.0.0 to 2.0.0 |\n")); + } + s.push_str("\n## Advisory\n\n"); + for a in 0..advisories { + s.push_str(&format!("- GHSA-{a:04}-xxxx-yyyy, CVE-2026-{a:05} · CVSS 7.5 · CWE-400 · published 2026-01-01\n - https://github.com/advisories/GHSA-{a:04}-xxxx-yyyy\n - https://nvd.nist.gov/vuln/detail/CVE-2026-{a:05}\n")); + } + s.push_str("\n## Reachability\n\n"); + for a in 0..advisories { + s.push_str(&format!("- GHSA-{a:04}: **Unknown**. The package is loaded by the server at start and its parser is called on request bodies.\n")); + for l in 0..6 { + s.push_str(&format!( + " - `src/module_{a}/file_{l}.ts:{l}` const value = parse(input, options)\n" + )); + } + } + s.push_str("\n## What to check\n\n"); + for p in 0..packages { + s.push_str(&format!("### `pkg-{p}` 1.0.0 to 2.0.0 (major version)\n\n- Release notes: read from GitHub releases (2.0.0).\n- Breaking changes found: 3\n - removed `parse()`\n - requires Node 20\n - default timeout is 5s\n- Where the code uses what changed:\n - `src/a.ts:10` (`parse`): not changed here: check it still works with the new version\n\n")); + } + s.push_str("**Tests**: CI runs on this pull request; this line is updated when it ends.\n"); + s.push_str( + "\n## Proof\n\nCI runs on this pull request; it stays a draft until CI passes.\n", + ); + s.push_str("\n## Verification\n\n- [ ] CI passes\n\n\n"); + s + } + + fn marker_lines(s: &str) -> Vec { + s.lines() + .filter(|l| l.contains("\n"); + body.push_str(&"plain text that never ends\n".repeat(6000)); + body.push_str("\n## Summary\nx\n"); + let out = fit(&body); + assert!(fits(&out)); + assert!(out.contains("")); + assert!(out.contains("")); + assert!(out.starts_with("Source ticket: T-1")); + } + + /// Random bodies of every size: the result always fits, keeps every + /// marker and heading, and a body that fits is never changed. + #[test] + fn any_size_fits_and_keeps_its_markers() { + let mut rng = rand::rngs::StdRng::seed_from_u64(7); + for round in 0..120 { + let mut s = String::from("Closes #12\n\n\n> draft\n"); + let sections = rng.random_range(1..12); + for k in 0..sections { + let name = [ + "Summary", + "Changes", + "Advisory", + "What to check", + "Verification", + "Open items", + "Files", + ][rng.random_range(0..7)]; + s.push_str(&format!("\n## {name} {k}\n\n")); + if rng.random_bool(0.2) { + s.push_str(&format!("\n")); + } + let big = rng.random_bool(0.3); + let items = rng.random_range(0..(if big { 3000 } else { 40 })); + for i in 0..items { + match rng.random_range(0..5) { + 0 => s.push_str(&format!("### block {i}\n- a\n- b\n\n")), + 1 => s.push_str(&format!("| r{i} | v |\n")), + 2 => s.push_str(&format!( + "- item {i} {}\n - child\n - child two\n", + "w".repeat(rng.random_range(0..200)) + )), + 3 => s.push_str("```\ncode line\n```\n"), + _ => s.push_str(&format!("text {i}\n")), + } + } + } + let out = fit(&s); + assert!(fits(&out), "round {round}: {} chars", out.chars().count()); + if s.len() <= BODY_TARGET { + assert_eq!(out, s, "round {round}"); + } + let mut want = marker_lines(&s); + let mut got = marker_lines(&out); + want.sort(); + got.sort(); + assert_eq!(got, want, "round {round}"); + assert_eq!(headings(&out), headings(&s), "round {round}"); + } + } + + /// A dependency fix run's account, as `dep_fix::DepRun::report_md` + /// writes it. + fn dep_report(applied: usize, deferred: usize) -> String { + let mut s = String::from("### Dependency fix run\n\n"); + s.push_str(&format!("**Applied ({applied}):**\n")); + for i in 0..applied { + s.push_str(&format!( + "- `pkg-{i}` 1.0.0 to 1.0.{i} (package.json; same version line)\n" + )); + } + s.push_str(&format!( + "\n**Deferred ({deferred}), the findings stay open:**\n" + )); + for i in 0..deferred { + s.push_str(&format!( + "- `big-{i}` 1.0.0 to 2.0.0: a major version for a finding that is not reachable\n" + )); + } + s.push_str("\n**Checks run in the sandbox:**\n- test: passes with these bumps\n- lint: fails on the base branch too (not caused by this change; not fixed here)\n"); + s.push_str("\n**Cost:** 4 sandbox probe(s); model $0.42 by batch:\n- batch 1: 2 probe(s), 30 applied, 0 deferred, 1200 tokens, $0.20\n"); + s + } + + #[test] + fn a_dependency_fix_runs_account_stays_whole_in_a_fitted_body() { + let report = dep_report(40, 15); + let body = big_body(55, 229).replace( + "## What to check\n\n", + &format!("## What to check\n\n{report}\n"), + ); + assert!(!fits(&body)); + for target in [BODY_TARGET, 20_000, 12_000] { + let out = fit_to(&body, target, None); + assert!(out.contains(report.trim_end()), "target {target}: {out}"); + assert_eq!(marker_lines(&out), marker_lines(&body), "target {target}"); + assert_eq!(headings(&out), headings(&body), "target {target}"); + } + // The packages beside it are what shrinks. + let out = fit_to(&body, 12_000, None); + assert!(out.matches("### `pkg-").count() < 55); + } + + #[test] + fn titles_stay_within_githubs_limit() { + assert_eq!(fit_title("fix(deps): x"), "fix(deps): x"); + let t = fit_title(&"é".repeat(400)); + assert_eq!(t.chars().count(), GITHUB_TITLE_MAX); + } +} diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index 5ef7778f1..72dd983fc 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -3080,6 +3080,576 @@ pub fn pr_body_with( members: &[(&Finding, &FindingState)], change: &str, check: &crate::upgrade_notes::WhatToCheck, +) -> String { + pr_body_linked(unit, members, change, check, &BodyLinks::default()) +} + +/// Where a security pull request's description points for what it leaves +/// out. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BodyLinks { + /// The dashboard's finding page without its id + /// (`https://app.example.com/security/detail?id=`): each finding's + /// advisory, affected path, reachability and evidence, in full. + pub finding: String, + /// Every package's notes and every advisory in one document, when the + /// run kept one (`openspec/specs//security-detail.md` on the + /// pull request's branch). + pub detail: String, +} + +/// A bundle of more than this many packages gets the short description: +/// the packages to look at first in full, the rest summed up by tier. +pub const SHORT_BODY_FROM: usize = 10; + +/// True when a unit's description is the short one. +pub fn uses_short_body(unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> bool { + unit.bumps.len() > SHORT_BODY_FROM || members.len() > 4 * SHORT_BODY_FROM +} + +/// The relative path, on the pull request's branch, of a ticket's full +/// detail document. +pub fn detail_path(ticket: &str) -> String { + format!( + "openspec/specs/{}/security-detail.md", + ticket.to_lowercase() + ) +} + +/// [`pr_body_with`], pointing at `links` for what it leaves out. A bundle +/// over [`SHORT_BODY_FROM`] packages gets the short description; whatever +/// it is, it fits GitHub's limit for a description. +pub fn pr_body_linked( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, + links: &BodyLinks, +) -> String { + let body = if uses_short_body(unit, members) { + short_body(unit, members, change, check, links) + } else { + full_body(unit, members, change, check) + }; + let more = if !links.detail.is_empty() { + links.detail.as_str() + } else { + "" + }; + crate::pr_body_fit::fit_with_link(&body, more) +} + +/// Every package's notes and every advisory, as one document: what a short +/// description leaves out. Kept on the pull request's branch. +pub fn detail_doc( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, +) -> String { + let full = full_body(unit, members, change, check); + // The description's marker stays in the description only. + let full = full.replace(MARKER, ""); + format!( + "# Security updates: full detail\n\nThe pull request for branch `{}` lists the packages \ + to look at first; this file lists every package and advisory. Written by CoderHelm when \ + the pull request opened; the pull request's own description has its CI state.\n\n{}\n", + unit.branch, + full.trim() + ) +} + +/// Each package's tier: its findings' most urgent. +fn package_tiers(unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> Vec> { + unit.bumps + .iter() + .map(|b| { + members + .iter() + .filter(|(f, _)| f.package.eq_ignore_ascii_case(&b.package)) + .filter_map(|(f, _)| f.tier) + .min() + }) + .collect() +} + +/// The bumps in the order a person should look at them: P0 and P1 first, +/// then majors that need a look (breaking changes, call sites, notes not +/// read), then majors, then the rest by tier; the package name breaks ties. +pub fn bumps_by_priority( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + check: &crate::upgrade_notes::WhatToCheck, +) -> Vec { + let tiers = package_tiers(unit, members); + let mut order: Vec = (0..unit.bumps.len()).collect(); + order.sort_by_key(|&i| { + let b = &unit.bumps[i]; + let urgent = matches!(tiers[i], Some(Tier::P0 | Tier::P1)); + let eyes = crate::upgrade_notes::needs_eyes(b, check); + let sites = + crate::upgrade_notes::notes_for(check, &b.package).map_or(0, |n| n.call_sites.len()); + ( + !urgent, + !eyes, + !b.major, + tiers[i].unwrap_or(Tier::P3), + std::cmp::Reverse(sites), + b.package.to_ascii_lowercase(), + ) + }); + order +} + +/// True when a bump belongs in the short description in full. +fn shown_in_full(b: &Bump, tier: Option, check: &crate::upgrade_notes::WhatToCheck) -> bool { + matches!(tier, Some(Tier::P0 | Tier::P1)) || crate::upgrade_notes::needs_eyes(b, check) +} + +/// At most this many packages in full in a short description. +const SHORT_SHOWN: usize = 10; +/// Each list under a package in a short description, at most. +const SHORT_CAP: usize = 5; + +fn package_cell(b: &Bump, members: &[(&Finding, &FindingState)], links: &BodyLinks) -> String { + let id = members + .iter() + .find(|(f, _)| f.package.eq_ignore_ascii_case(&b.package)) + .map(|(f, _)| f.id.as_str()) + .unwrap_or(""); + let name = format!("`{}`", b.package.replace('|', "\\|")); + if links.finding.is_empty() || id.is_empty() { + name + } else { + format!("[{name}]({}{id})", links.finding) + } +} + +/// The short description: the bump table (every package, most urgent +/// first, each linked to its finding page), the advisories and evidence +/// that matter most, "What to check" for the packages to look at first, +/// the rest by tier with counts, Proof and Closes as usual. +fn short_body( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, + links: &BodyLinks, +) -> String { + let mut s = String::new(); + let tiers = package_tiers(unit, members); + let order = bumps_by_priority(unit, members, check); + let top = members + .iter() + .filter_map(|(f, _)| f.tier) + .min() + .unwrap_or(Tier::P3); + let due = members + .iter() + .filter_map(|(f, _)| parse_time(&f.due_at)) + .min() + .map(|d| format!(", due {}", d.format("%b %-d"))) + .unwrap_or_default(); + let advisories = primaries(members).len(); + let majors = unit.bumps.iter().filter(|b| b.major).count(); + let where_all = if !links.detail.is_empty() { + format!( + "Every package and advisory, in full: [security-detail.md]({}).", + links.detail + ) + } else if !links.finding.is_empty() { + "Each package links to its finding page in CoderHelm: its advisories, reachability and \ + evidence in full." + .to_string() + } else { + String::new() + }; + s.push_str(&format!( + "## Summary\n\nFixes {advisories} advisor{} in {} packages ({majors} major version{}). \ + {}{due}.\n\n{where_all}\n\n", + if advisories == 1 { "y" } else { "ies" }, + unit.bumps.len(), + if majors == 1 { "" } else { "s" }, + top.as_str(), + )); + // The table: every bump, most urgent first, ids capped per row. + let cell = |s: &str| s.replace('|', "\\|").replace('\n', " "); + s.push_str("| Package | Version | Advisories | Reachability | Due |\n| --- | --- | --- | --- | --- |\n"); + for &i in &order { + let b = &unit.bumps[i]; + let mine: Vec<&Finding> = members + .iter() + .map(|(f, _)| *f) + .filter(|f| f.package.eq_ignore_ascii_case(&b.package)) + .collect(); + let mut ids: Vec<&str> = mine.iter().map(|f| f.advisory.primary.as_str()).collect(); + ids.sort(); + ids.dedup(); + let shown_ids = if ids.len() > 3 { + format!("{} and {} more", ids[..3].join(", "), ids.len() - 3) + } else { + ids.join(", ") + }; + let verdict = mine + .iter() + .map(|f| f.verdict) + .min_by_key(|v| verdict_rank(*v)) + .map(verdict_words) + .unwrap_or("Unknown"); + let due = mine + .iter() + .filter_map(|f| parse_time(&f.due_at)) + .min() + .map(|d| d.format("%b %-d").to_string()) + .unwrap_or_default(); + s.push_str(&format!( + "| {} | {} to {}{} | {} | {} | {}{} |\n", + package_cell(b, members, links), + cell(&b.from), + cell(&b.to), + if b.major { " (major)" } else { "" }, + cell(&shown_ids), + verdict, + tiers[i] + .map(|t| format!("{} ", t.as_str())) + .unwrap_or_default(), + due + )); + } + s.push('\n'); + + // The advisories that matter most: P0 and P1, exploited, malware. + let mut ranked: Vec<&(&Finding, &FindingState)> = members.iter().collect(); + ranked.sort_by_key(|(f, _)| { + ( + !(f.advisory.kev || f.advisory.malware), + f.tier.unwrap_or(Tier::P3), + verdict_rank(f.verdict), + f.advisory.primary.clone(), + ) + }); + s.push_str("## Advisory\n\n"); + let urgent: Vec<&&(&Finding, &FindingState)> = ranked + .iter() + .filter(|(f, _)| { + matches!(f.tier, Some(Tier::P0 | Tier::P1)) || f.advisory.kev || f.advisory.malware + }) + .take(20) + .collect(); + for (f, st) in urgent.iter().map(|p| (p.0, p.1)) { + s.push_str(&format!("- {}\n", advisory_facts(f, st))); + if let Some(u) = f.advisory.urls.first() { + s.push_str(&format!(" - {u}\n")); + } + } + let left = members.len() - urgent.len(); + if left > 0 { + let mut by_tier: Vec = vec![]; + for t in Tier::ALL { + let n = ranked.iter().filter(|(f, _)| f.tier == Some(t)).count() + - urgent.iter().filter(|(f, _)| f.tier == Some(t)).count(); + if n > 0 { + by_tier.push(format!("{n} {}", t.as_str())); + } + } + s.push_str(&format!( + "- {}{left} more ({}): their ids are in the table above{}.\n", + if urgent.is_empty() { "" } else { "and " }, + if by_tier.is_empty() { + "tier not set".to_string() + } else { + by_tier.join(", ") + }, + if links.finding.is_empty() { + "" + } else { + ", each package linked to its finding page" + } + )); + } + + // Reachability: what is reachable, with its evidence, then the counts. + s.push_str("\n## Reachability\n\n"); + let reachable: Vec<&(&Finding, &FindingState)> = ranked + .iter() + .copied() + .filter(|(f, _)| f.verdict == Verdict::Reachable) + .collect(); + for (f, _) in reachable.iter().take(10) { + let summary = f + .evidence + .as_ref() + .map(|e| e.summary.trim().to_string()) + .unwrap_or_default(); + s.push_str(&format!( + "- {} in `{}`: **Reachable**. {}\n", + f.advisory.primary, + f.package, + crate::truncate_str(&summary, 400) + )); + if let Some(e) = &f.evidence { + for l in e.lines.iter().take(2) { + s.push_str(&format!( + " - `{}:{}` {}\n", + l.file, + l.line, + crate::truncate_str(l.text.trim(), 160) + )); + } + } + } + if reachable.len() > 10 { + s.push_str(&format!("- and {} more reachable\n", reachable.len() - 10)); + } + let count = |v: &[Verdict]| { + members + .iter() + .filter(|(f, _)| v.contains(&f.verdict)) + .count() + }; + let others = [ + (count(&[Verdict::NotReachable]), "present, not reachable"), + (count(&[Verdict::NotLoaded]), "not loaded at runtime"), + (count(&[Verdict::Unknown, Verdict::Pending]), "unknown"), + ]; + let said: Vec = others + .iter() + .filter(|(n, _)| *n > 0) + .map(|(n, w)| format!("{n} {w}")) + .collect(); + if !said.is_empty() { + s.push_str(&format!( + "- {}: {}.\n", + if reachable.is_empty() { + "All advisories" + } else { + "The others" + }, + said.join(", ") + )); + } + + s.push_str("\n## Change\n\nThe bumps are in the table above.\n"); + let change = change.trim(); + if !change.is_empty() { + s.push('\n'); + s.push_str(crate::truncate_str(change, 6_000)); + if change.len() > 6_000 { + s.push_str("\n\n(The run's account is longer; shortened here.)"); + } + s.push('\n'); + } + s.push('\n'); + + // What to check: the packages to look at first, then the rest by tier. + let first: Vec = order + .iter() + .copied() + .filter(|&i| shown_in_full(&unit.bumps[i], tiers[i], check)) + .collect(); + let shown: Vec<&Bump> = first + .iter() + .take(SHORT_SHOWN) + .map(|&i| &unit.bumps[i]) + .collect(); + let intro = + format!( + "The packages to look at first: P0 and P1 fixes, and major versions whose release notes \ + list breaking changes, whose changed APIs this code uses, or whose notes weren't found. \ + {} of {} {} below{}{}", + shown.len(), + unit.bumps.len(), + if shown.len() == 1 { "is" } else { "are" }, + if first.len() > shown.len() { + format!(" ({} more need a look, listed after them)", first.len() - shown.len()) + } else { + String::new() + }, + if where_all.is_empty() { + ".".to_string() + } else { + format!(". {where_all}") + } + ); + let mut rest = String::new(); + let later: Vec = order + .iter() + .copied() + .filter(|i| !shown.iter().any(|b| std::ptr::eq(*b, &unit.bumps[*i]))) + .collect(); + if !later.is_empty() { + rest.push_str(&format!( + "
The other {} packages, by tier\n\n", + later.len() + )); + let mut groups: Vec<(String, Vec)> = vec![]; + let needs: Vec = later + .iter() + .copied() + .filter(|i| first.contains(i)) + .collect(); + if !needs.is_empty() { + groups.push(("Also need a look".into(), needs.clone())); + } + for t in Tier::ALL { + let g: Vec = later + .iter() + .copied() + .filter(|i| !needs.contains(i) && tiers[*i] == Some(t)) + .collect(); + if !g.is_empty() { + groups.push((t.as_str().to_string(), g)); + } + } + let unset: Vec = later + .iter() + .copied() + .filter(|i| !needs.contains(i) && tiers[*i].is_none()) + .collect(); + if !unset.is_empty() { + groups.push(("Tier not set".into(), unset)); + } + for (name, g) in groups { + let majors = g.iter().filter(|&&i| unit.bumps[i].major).count(); + let names: Vec = g + .iter() + .take(25) + .map(|&i| { + let b = &unit.bumps[i]; + format!( + "`{}` {} to {}{}", + b.package, + b.from, + b.to, + if b.major { " (major)" } else { "" } + ) + }) + .collect(); + rest.push_str(&format!( + "- **{name}**: {} package{}{}: {}{}\n", + g.len(), + if g.len() == 1 { "" } else { "s" }, + if majors > 0 { + format!(", {majors} major") + } else { + String::new() + }, + names.join(", "), + if g.len() > 25 { + format!(", and {} more", g.len() - 25) + } else { + String::new() + } + )); + } + rest.push_str("\n
\n"); + } + s.push_str(&crate::upgrade_notes::what_to_check_short( + &shown, check, SHORT_CAP, &intro, &rest, + )); + s.push_str(&proof_and_closes(members, check, 25)); + s +} + +fn verdict_words(v: Verdict) -> &'static str { + match v { + Verdict::Reachable => "Reachable", + Verdict::NotReachable => "Present, not reachable", + Verdict::NotLoaded => "Not loaded at runtime", + Verdict::Unknown | Verdict::Pending => "Unknown", + } +} + +/// One advisory's facts on one line: its ids, score, exploited, malware, +/// weaknesses and when it was published. +fn advisory_facts(f: &Finding, st: &FindingState) -> String { + let a = &f.advisory; + let mut facts = vec![a.ids.join(", ")]; + let sc = score(f, st); + match a.cvss { + Some(c) => facts.push(format!("CVSS {}", fmt_num(c))), + None if sc > 0.0 => facts.push(format!("severity {}", severity_word(sc))), + None => {} + } + if let Some(e) = a.epss { + facts.push(format!("EPSS {}", fmt_num(e))); + } + if a.kev { + facts.push(match &a.kev_due { + Some(d) => format!( + "on CISA's exploited list (due {})", + d.get(..10).unwrap_or(d) + ), + None => "on CISA's exploited list".to_string(), + }); + } + if a.malware { + facts.push("malicious package".into()); + } + if !a.cwe.is_empty() { + facts.push(a.cwe.join(", ")); + } + if let Some(p) = &a.published_at { + facts.push(format!("published {}", p.get(..10).unwrap_or(p))); + } + facts.join(" · ") +} + +/// Proof (where CI stands, never a pass it didn't have), Closes (at most +/// `cap` alerts listed), the data's credit and the description's marker. +fn proof_and_closes( + members: &[(&Finding, &FindingState)], + check: &crate::upgrade_notes::WhatToCheck, + cap: usize, +) -> String { + let mut s = String::new(); + let ci = match check.ci.state.as_str() { + "passing" => "CI passes on this pull request.".to_string(), + "failing" => format!( + "CI fails on this pull request ({}), so it stays a draft until that is fixed.", + if check.ci.failing.is_empty() { + "see its checks".to_string() + } else { + check + .ci + .failing + .iter() + .map(|c| format!("`{c}`")) + .collect::>() + .join(", ") + } + ), + _ => "CI runs on this pull request; it stays a draft until CI passes.".to_string(), + }; + s.push_str(&format!("\n## Proof\n\n{ci} After it merges, the dependency list is read again and the advisory clears from Security.\n")); + s.push_str("\n## Closes\n\n"); + let alerts: Vec<&AlertRef> = members + .iter() + .filter_map(|(f, _)| f.dependabot_alert.as_ref()) + .collect(); + for a in alerts.iter().take(cap) { + s.push_str(&format!("- Dependabot alert [#{}]({})\n", a.number, a.url)); + } + if alerts.len() > cap { + s.push_str(&format!( + "- and {} more Dependabot alerts\n", + alerts.len() - cap + )); + } + if alerts.is_empty() { + s.push_str("- No Dependabot alert is open for these.\n"); + } + s.push_str(&format!("\n{ATTRIBUTION}\n\n{MARKER}\n")); + s +} + +/// The description in full: every advisory, every affected path, every +/// piece of evidence and every package's notes. +fn full_body( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, ) -> String { let mut s = String::new(); let top = members @@ -8164,4 +8734,297 @@ mod tests { assert_eq!(p["pr_count"], 1); assert_eq!(p["would_open"].as_array().unwrap().len(), 2); } + + /// The bundle that failed at its very end: 55 packages, 37 of them + /// majors, 229 advisories, every package's notes read. The full + /// description was several times GitHub's limit; the short one fits, + /// lists the P0 and P1 packages and the majors that need a look first, + /// sums up the rest by tier and links the full list. + fn big_bundle() -> ( + FixUnit, + Vec<(Finding, FindingState)>, + crate::upgrade_notes::WhatToCheck, + ) { + use crate::upgrade_notes::{CallSite, PackageNotes, WhatToCheck}; + let mut unit = FixUnit { + repo: "acme/api".into(), + ecosystem: "npm".into(), + bundle: true, + ticket: "SEC-ABC123".into(), + branch: "coderhelm/security-updates-2026-11-12-abc123".into(), + ..Default::default() + }; + let mut fs: Vec<(Finding, FindingState)> = vec![]; + let mut notes: Vec = vec![]; + let mut n = 0; + for p in 0..55 { + let pkg = format!("@scope/package-number-{p:02}"); + let major = p < 37; + unit.bumps.push(Bump { + package: pkg.clone(), + from: "1.4.2".into(), + to: if major { + "2.0.1".into() + } else { + "1.4.9".into() + }, + major, + manifest: "package.json".into(), + }); + let tier = match p { + 0..=1 => Tier::P0, + 2..=5 => Tier::P1, + _ if p % 2 == 0 => Tier::P2, + _ => Tier::P3, + }; + let count = if p < 9 { 5 } else { 4 }; + for _ in 0..count { + if n == 229 { + break; + } + let id = format!("{n:04}-wxyz-abcd"); + let (mut f, st) = adv_finding( + &id, + &pkg, + "1.4.2", + Some("2.0.1"), + tier, + "2026-12-10T00:00:00Z", + ); + f.repo = unit.repo.clone(); + f.advisory.title = "Prototype pollution in the request parser allows a crafted body to change defaults".into(); + f.advisory.ids.push(format!("CVE-2026-{n:05}")); + f.advisory.cvss = Some(8.1); + f.advisory.cwe = vec!["CWE-1321".into()]; + f.advisory.urls = (0..3) + .map(|k| format!("https://github.com/advisories/GHSA-{id}-{k}")) + .collect(); + f.path = vec![ + "@nestjs/core".into(), + "@nestjs/platform-express".into(), + pkg.clone(), + ]; + f.verdict = if n % 3 == 0 { + Verdict::Reachable + } else { + Verdict::Unknown + }; + f.evidence = Some(Evidence { + summary: "The server loads the package at start and passes request bodies to its parser on every call.".into(), + lines: (0..8).map(|l| EvidenceLine { file: format!("src/modules/area-{p}/handler-{l}.ts"), line: 10 + l, text: "const parsed = parser.parse(request.body, { strict: false })".into() }).collect(), + checked: "Followed the import from main.ts through the module graph.".into(), + confidence: "medium".into(), + }); + f.dependabot_alert = Some(AlertRef { + number: 100 + n as u64, + url: format!( + "https://github.com/acme/api/security/dependabot/{}", + 100 + n + ), + }); + fs.push((f, st)); + n += 1; + } + notes.push(PackageNotes { + package: pkg.clone(), + source: "the GitHub releases of acme/package".into(), + versions: vec!["2.0.0".into(), "2.0.1".into()], + breaking: if major { (0..9).map(|k| format!("Breaking change {k}: the option `legacyMode` is removed and the default timeout changes from 30s to 5s.")).collect() } else { vec![] }, + apis: vec!["parse".into()], + call_sites: if major { (0..14).map(|k| CallSite { api: "parse".into(), file: format!("src/modules/area-{p}/use-{k}.ts"), line: 40 + k, text: String::new() }).collect() } else { vec![] }, + lockfile: "pnpm-lock.yaml".into(), + lock_command: "pnpm install --lockfile-only".into(), + ..Default::default() + }); + } + assert_eq!(n, 229); + let check = WhatToCheck { + notes, + files: (0..60) + .map(|i| format!("src/modules/area-{i}/module.ts")) + .collect(), + ..Default::default() + }; + (unit, fs, check) + } + + #[test] + fn a_55_package_bundle_fits_and_lists_what_to_look_at_first() { + let (unit, fs, check) = big_bundle(); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let change = + "Raised the direct ranges and added overrides for transitive copies. ".repeat(40); + // The description before: every advisory, path, piece of evidence + // and package note, over GitHub's limit. + let before = full_body(&unit, &pairs, &change, &check); + assert!( + before.chars().count() > crate::pr_body_fit::GITHUB_BODY_MAX, + "{}", + before.len() + ); + let links = BodyLinks { + finding: "https://app.example.com/security/detail?id=".into(), + detail: "https://github.com/acme/api/blob/coderhelm/security-updates-2026-11-12-abc123/openspec/specs/sec-abc123/security-detail.md".into(), + }; + let body = pr_body_linked(&unit, &pairs, &change, &check, &links); + assert!( + crate::pr_body_fit::fits(&body), + "{} chars", + body.chars().count() + ); + assert!( + body.len() <= crate::pr_body_fit::BODY_TARGET, + "{}", + body.len() + ); + // No shortening pass was needed: the short description fits as written. + assert!(!body.contains(crate::pr_body_fit::SHORTENED), "{body}"); + for h in [ + "## Summary", + "## Advisory", + "## Reachability", + "## Change", + "## What to check", + "## Proof", + "## Closes", + ] { + assert!( + body.contains(&format!("\n{h}")) || body.starts_with(h), + "{h}" + ); + } + assert!(body.contains(MARKER)); + assert!( + body.contains("Fixes 229 advisories in 55 packages (37 major versions)."), + "{body}" + ); + // Every package is in the table, each linked to its finding page. + for b in &unit.bumps { + assert!( + body.contains(&format!( + "[`{}`](https://app.example.com/security/detail?id=", + b.package + )), + "{}", + b.package + ); + } + assert!(body.contains(&links.detail)); + // What to check: the P0 and P1 packages first, then majors. + let wtc = &body[body.find("## What to check").unwrap()..body.find("## Proof").unwrap()]; + let order: Vec = wtc + .lines() + .filter_map(|l| l.strip_prefix("### `@scope/package-number-")) + .map(|l| l[..2].parse().unwrap()) + .collect(); + assert_eq!(&order[..6], &[0, 1, 2, 3, 4, 5], "{order:?}"); + assert!( + order.iter().all(|p| *p < 37), + "only P0, P1 and majors in full: {order:?}" + ); + assert!( + wtc.contains("
The other 45 packages, by tier"), + "{wtc}" + ); + assert!( + wtc.contains("- **Also need a look**: 27 packages, 27 major"), + "{wtc}" + ); + assert!(wtc.contains("- **P2**: 9 packages"), "{wtc}"); + assert!(wtc.contains("- **P3**: 9 packages"), "{wtc}"); + assert!( + wtc.contains(" - and 4 more\n"), + "lists capped under each package" + ); + // Advisories: the P0 and P1 ones, then the rest counted. + assert!( + body.contains( + "- and 209 more (10 P1, 102 P2, 97 P3): their ids are in the table above" + ), + "{body}" + ); + assert!(body.contains("- and 204 more Dependabot alerts")); + // The full detail document keeps every package and advisory. + let doc = detail_doc(&unit, &pairs, &change, &check); + for b in &unit.bumps { + assert!(doc.contains(&format!("### `{}`", b.package))); + } + assert!(!doc.contains(MARKER)); + } + + /// A dependency fix run's account (#634: the bumps applied, the ones + /// deferred with why, the sandbox's checks, the cost) is in the short + /// description's "What to check" whole, and in the full detail. + #[test] + fn the_short_bundle_body_keeps_the_dependency_fix_runs_account() { + let (unit, fs, mut check) = big_bundle(); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let mut report = String::from("### Dependency fix run\n\n**Applied (40):**\n"); + for i in 0..40 { + report.push_str(&format!( + "- `@scope/package-number-{i:02}` 1.0.0 to 1.0.1 (package.json; same version line)\n" + )); + } + report.push_str("\n**Deferred (15), the findings stay open:**\n"); + for i in 40..55 { + report.push_str(&format!( + "- `@scope/package-number-{i:02}` 1.0.0 to 2.0.0: a major version for a finding that is not reachable\n" + )); + } + report.push_str("\n**Checks run in the sandbox:**\n- test: passes with these bumps\n\n**Cost:** 3 sandbox probe(s); model $0.31\n"); + check.dep_report = report.clone(); + let links = BodyLinks { + finding: "https://app.example.com/security/detail?id=".into(), + detail: String::new(), + }; + let change = + "Raised the direct ranges and added overrides for transitive copies. ".repeat(40); + assert!(uses_short_body(&unit, &pairs)); + let body = pr_body_linked(&unit, &pairs, &change, &check, &links); + assert!(crate::pr_body_fit::fits(&body)); + assert!(body.contains(MARKER)); + let wtc = &body[body.find("## What to check").unwrap()..body.find("## Proof").unwrap()]; + assert!( + wtc.starts_with(&format!("## What to check\n\n{}", report.trim())), + "{wtc}" + ); + // Over the limit anyway, the account is what stays. + let fitted = crate::pr_body_fit::fit_to(&body, 20_000, None); + assert!(fitted.contains(report.trim()), "{fitted}"); + assert!(fitted.contains(MARKER)); + let doc = detail_doc(&unit, &pairs, &change, &check); + assert!(doc.contains(report.trim())); + } + + /// CI ending rewrites "What to check" and Proof in place on the short + /// description, which then still fits. + #[test] + fn the_short_bundle_body_takes_the_ci_rewrite_in_place() { + let (unit, fs, mut check) = big_bundle(); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let links = BodyLinks::default(); + let body = format!( + "\n> Draft until CI passes.\n\n{}", + pr_body_linked(&unit, &pairs, "Bumped.", &check, &links) + ); + check.ci = crate::upgrade_notes::CiState { + state: "failing".into(), + failing: vec!["test".into()], + checks: vec!["build".into(), "test".into()], + }; + let fresh = pr_body_linked(&unit, &pairs, "Bumped.", &check, &links); + let next = crate::upgrade_notes::replace_sections( + &body, + &fresh, + &["## What to check", "## Proof"], + ); + assert!( + next.contains("CI fails on this pull request: `test`"), + "{next}" + ); + assert!(next.contains("## Proof\n\nCI fails on this pull request (`test`)")); + assert!(next.starts_with("")); + assert!(crate::pr_body_fit::fits(&next)); + assert_eq!(next.matches("## What to check").count(), 1); + } } diff --git a/services/common/src/upgrade_notes.rs b/services/common/src/upgrade_notes.rs index 58e621599..0d964d2d6 100644 --- a/services/common/src/upgrade_notes.rs +++ b/services/common/src/upgrade_notes.rs @@ -1017,10 +1017,70 @@ pub fn what_to_check(bumps: &[Bump], w: &WhatToCheck) -> String { s.push_str("\n\n"); } for b in bumps { - let n = w - .notes - .iter() - .find(|n| n.package.eq_ignore_ascii_case(&b.package)); + s.push_str(&package_check(b, w, usize::MAX)); + } + s.push_str(&check_footer(w)); + s +} + +/// The notes read for a bump's package, if any. +pub fn notes_for<'a>(w: &'a WhatToCheck, package: &str) -> Option<&'a PackageNotes> { + w.notes + .iter() + .find(|n| n.package.eq_ignore_ascii_case(package)) +} + +/// A major version a person has to look at: its notes list breaking +/// changes, the code uses what changed, or its notes weren't read. +pub fn needs_eyes(b: &Bump, w: &WhatToCheck) -> bool { + b.major + && notes_for(w, &b.package) + .is_none_or(|n| !n.read() || !n.breaking.is_empty() || !n.call_sites.is_empty()) +} + +/// A bundle's section when it is too long to list every package: the +/// packages in `shown` with their notes (each list at most `cap` long), +/// `intro` above them and `rest` (what the others are, already written) +/// below, then the files and the tests as usual. A dependency fix run's +/// account comes first, whole, as in [`what_to_check`]. +pub fn what_to_check_short( + shown: &[&Bump], + w: &WhatToCheck, + cap: usize, + intro: &str, + rest: &str, +) -> String { + let mut s = String::from("## What to check\n\n"); + if !w.dep_report.trim().is_empty() { + s.push_str(w.dep_report.trim()); + s.push_str("\n\n"); + } + if !intro.trim().is_empty() { + s.push_str(intro.trim()); + s.push_str("\n\n"); + } + for b in shown { + s.push_str(&package_check(b, w, cap)); + } + if !rest.trim().is_empty() { + s.push_str(rest.trim_end()); + s.push_str("\n\n"); + } + s.push_str(&check_footer(w)); + s +} + +/// One package's part of the section: its notes, what changed, where the +/// code uses it, its lockfile. Each list at most `cap` long. +fn package_check(b: &Bump, w: &WhatToCheck, cap: usize) -> String { + let mut s = String::new(); + let more = |s: &mut String, n: usize| { + if n > cap { + s.push_str(&format!(" - and {} more\n", n - cap)); + } + }; + { + let n = notes_for(w, &b.package); s.push_str(&format!( "### `{}` {} to {}{}\n\n", b.package, @@ -1039,13 +1099,14 @@ pub fn what_to_check(bumps: &[Bump], w: &WhatToCheck) -> String { s.push_str("- Breaking changes found: none in the notes.\n"); } else { s.push_str(&format!("- Breaking changes found: {}\n", n.breaking.len())); - for line in &n.breaking { + for line in n.breaking.iter().take(cap) { s.push_str(&format!(" - {line}\n")); } + more(&mut s, n.breaking.len()); } if !n.call_sites.is_empty() { s.push_str("- Where the code uses what changed:\n"); - for c in &n.call_sites { + for c in n.call_sites.iter().take(cap) { let touched = w.files.iter().any(|f| f == &c.file); s.push_str(&format!( " - `{}:{}` (`{}`): {}\n", @@ -1059,6 +1120,7 @@ pub fn what_to_check(bumps: &[Bump], w: &WhatToCheck) -> String { } )); } + more(&mut s, n.call_sites.len()); } else if !n.apis.is_empty() { s.push_str(&format!( "- No use of {} was found in the code.\n", @@ -1094,6 +1156,12 @@ pub fn what_to_check(bumps: &[Bump], w: &WhatToCheck) -> String { } s.push('\n'); } + s +} + +/// The section's end: the files the pull request touches, and the tests. +fn check_footer(w: &WhatToCheck) -> String { + let mut s = String::new(); if !w.files.is_empty() { s.push_str(&format!("**Files touched** ({}):\n", w.files.len())); for f in w.files.iter().take(40) { diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 8ca50052c..dd8b47210 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -90,6 +90,42 @@ async fn ok_or_body( } } +/// A write's JSON as GitHub takes it: a `body` (and each inline comment's +/// `body`) within GitHub's 65,536-character limit, fitted by +/// `common::pr_body_fit` (required sections and CoderHelm's markers kept, +/// long lists shortened), and a `title` within its 256. Every POST, PATCH +/// and review PUT this client sends goes through here, so no caller can +/// send a body GitHub refuses for its size. +pub fn bounded_payload(v: &serde_json::Value) -> serde_json::Value { + use common::pr_body_fit as fit; + let mut out = v.clone(); + let Some(o) = out.as_object_mut() else { + return out; + }; + if let Some(b) = o.get("body").and_then(|b| b.as_str()) { + if !fit::fits(b) || b.len() > fit::BODY_TARGET { + let fitted = fit::fit(b); + o.insert("body".into(), serde_json::Value::String(fitted)); + } + } + if let Some(t) = o.get("title").and_then(|t| t.as_str()) { + if t.chars().count() > fit::GITHUB_TITLE_MAX { + let fitted = fit::fit_title(t); + o.insert("title".into(), serde_json::Value::String(fitted)); + } + } + if let Some(cs) = o.get_mut("comments").and_then(|c| c.as_array_mut()) { + for c in cs { + if let Some(b) = c.get("body").and_then(|b| b.as_str()) { + if b.len() > fit::BODY_TARGET { + c["body"] = serde_json::Value::String(fit::fit(b)); + } + } + } + } + out +} + /// GitHub refused a request for its rate limit (primary or secondary). The /// message is the usual status line, so string checks still match; the wait /// is how long GitHub asked for. @@ -873,7 +909,7 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; - let mut req = self.http.post(url).json(body); + let mut req = self.http.post(url).json(&bounded_payload(body)); for (k, v) in headers { req = req.header(k, v); } @@ -887,7 +923,7 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; - let mut req = self.http.patch(url).json(body); + let mut req = self.http.patch(url).json(&bounded_payload(body)); for (k, v) in headers { req = req.header(k, v); } @@ -3566,7 +3602,7 @@ impl GitHubClient { let mut req = self .http .put(&url) - .json(&serde_json::json!({ "body": body })); + .json(&bounded_payload(&serde_json::json!({ "body": body }))); for (k, v) in headers { req = req.header(k, v); } @@ -4397,7 +4433,7 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result<(), Box> { let headers = self.auth_headers().await?; - let mut req = self.http.post(url).json(body); + let mut req = self.http.post(url).json(&bounded_payload(body)); for (k, v) in headers { req = req.header(k, v); } @@ -5470,3 +5506,169 @@ mod reopen_tests { assert!(!closed_by_a_bot(&json!({}))); } } + +#[cfg(test)] +mod body_limit_tests { + use super::*; + use common::pr_body_fit::{fits, GITHUB_BODY_MAX, GITHUB_TITLE_MAX}; + use serde_json::json; + + fn huge_body() -> String { + let mut s = String::from( + "Source ticket: SEC-1\n\n## Summary\n\nFixes 229 advisories.\n\n## Advisory\n\n", + ); + for i in 0..3000 { + s.push_str(&format!( + "- GHSA-{i:04}-aaaa-bbbb · CVSS 7.5 · CWE-400 · published 2026-01-01\n" + )); + } + s.push_str("\n## Verification\n\n- [ ] CI passes\n\n\n"); + s + } + + /// A client whose token is already cached: no app key needed. + fn client() -> GitHubClient { + let c = GitHubClient::new("1", "test-key", 0, &reqwest::Client::new()).unwrap(); + *c.token_cache.lock().unwrap() = Some(CachedToken { + token: "t".into(), + expires_at: GitHubClient::now_epoch() + 3600, + permissions: Default::default(), + }); + c + } + + /// A server that keeps each request's body and answers `{"number": 7}`. + async fn capture() -> (String, std::sync::Arc>>) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let kept = seen.clone(); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut raw = Vec::new(); + let mut buf = vec![0u8; 1 << 16]; + // Headers, then the body to its Content-Length. + loop { + let n = sock.read(&mut buf).await.unwrap_or(0); + if n == 0 { + break; + } + raw.extend_from_slice(&buf[..n]); + let text = String::from_utf8_lossy(&raw).to_string(); + if let Some(h) = text.find("\r\n\r\n") { + let len = text[..h] + .lines() + .find_map(|l| { + let l = l.to_ascii_lowercase(); + l.strip_prefix("content-length:") + .map(|v| v.trim().parse::().unwrap_or(0)) + }) + .unwrap_or(0); + if raw.len() >= h + 4 + len { + kept.lock() + .unwrap() + .push(String::from_utf8_lossy(&raw[h + 4..]).to_string()); + break; + } + } + } + let body = "{\"number\":7}"; + let head = format!("HTTP/1.1 201 Created\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", body.len()); + let _ = sock.write_all(head.as_bytes()).await; + let _ = sock.write_all(body.as_bytes()).await; + let _ = sock.shutdown().await; + } + }); + (format!("http://{addr}"), seen) + } + + /// What reaches GitHub for a pull request, a description update, an + /// issue and a comment is never over GitHub's limit, whatever the + /// caller wrote; required sections and markers stay. + #[tokio::test] + async fn no_write_sends_a_body_over_githubs_limit() { + let body = huge_body(); + assert!(body.chars().count() > 2 * GITHUB_BODY_MAX); + let (base, seen) = capture().await; + let c = client(); + let pr = json!({"title": "t".repeat(400), "body": body, "head": "b", "base": "main", "draft": true}); + let made = c + .post(&format!("{base}/repos/o/r/pulls"), &pr) + .await + .unwrap(); + assert_eq!(made["number"], 7); + c.patch(&format!("{base}/repos/o/r/pulls/7"), &json!({"body": body})) + .await + .unwrap(); + c.post( + &format!("{base}/repos/o/r/issues/7/comments"), + &json!({"body": body}), + ) + .await + .unwrap(); + c.post_empty( + &format!("{base}/repos/o/r/issues"), + &json!({"title": "x", "body": body}), + ) + .await + .unwrap(); + let sent = seen.lock().unwrap().clone(); + assert_eq!(sent.len(), 4); + for raw in sent { + let v: serde_json::Value = serde_json::from_str(&raw).unwrap(); + let b = v["body"].as_str().unwrap(); + assert!(fits(b), "{} chars sent", b.chars().count()); + assert!(b.starts_with("Source ticket: SEC-1")); + assert!(b.contains("## Summary\n\nFixes 229 advisories.")); + assert!(b.contains("## Verification\n\n- [ ] CI passes")); + assert!(b.contains("")); + if let Some(t) = v["title"].as_str() { + assert!(t.chars().count() <= GITHUB_TITLE_MAX); + } + } + } + + #[test] + fn a_body_within_the_limit_is_sent_unchanged() { + let p = json!({"title": "fix: x", "body": "Closes #4\n\n## Summary\nx"}); + assert_eq!(bounded_payload(&p), p); + let p = json!({"sha": "abc", "force": false}); + assert_eq!(bounded_payload(&p), p); + } + + /// Every method that writes a body sends it through `post`, `patch` or + /// `post_empty`, which bound it: none builds its own request around it. + #[test] + fn every_body_write_goes_through_the_bound() { + let src = include_str!("github.rs"); + for f in [ + "pub async fn create_pull_request(", + "pub async fn update_pr_body(", + "pub async fn create_issue(", + "pub async fn create_issue_comment(", + "pub async fn edit_issue_comment(", + "pub async fn create_pr_review(", + "pub async fn create_pr_review_inline(", + ] { + let at = src.find(f).unwrap_or_else(|| panic!("{f} is gone")); + let rest = &src[at..]; + let end = rest[1..] + .find("\n pub async fn ") + .map_or(rest.len(), |i| i + 1); + let body = &rest[..end]; + assert!( + body.contains("self.post(") || body.contains("self.patch("), + "{f} sends its body some other way" + ); + } + for send in ["async fn post(", "async fn patch(", "async fn post_empty("] { + let at = src.find(send).unwrap(); + let rest = &src[at..at + 600]; + assert!(rest.contains("bounded_payload(body)"), "{send}"); + } + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 9559a7b32..c8a1972aa 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1469,11 +1469,22 @@ pub async fn orchestrate_ticket( match stop_pr::open(state, &msg, &run_id, branch, &sanitize_error(&err_msg)) .await { - Ok(pr_url) => { - info!( - run_id, - pr_url, "Opened a draft PR for a run stopped after its work" - ); + // Named only when GitHub gave it a number: a + // refused pull request waits on a person with + // GitHub's reason, and is never logged as opened. + Ok(stopped) => { + match &stopped { + stop_pr::Stopped::Opened { number, url } => info!( + run_id, + pr_number = number, + pr_url = %url, + "{} (stopped after its work)", + stop_pr::stop_line(&stopped) + ), + stop_pr::Stopped::Refused { .. } => { + warn!(run_id, "{}", stop_pr::stop_line(&stopped)) + } + } true } Err(e) => { @@ -1570,11 +1581,19 @@ pub async fn orchestrate_ticket( "The step reached its time limit and the run couldn't continue in a fresh step: {why}." ); match stop_pr::open(state, &msg, &run_id, branch, &reason).await { - Ok(pr_url) => { - info!( - run_id, - pr_url, "Opened a draft PR for a run stopped at its time limit" - ); + Ok(stopped) => { + match &stopped { + stop_pr::Stopped::Opened { number, url } => info!( + run_id, + pr_number = number, + pr_url = %url, + "{} (stopped at its time limit)", + stop_pr::stop_line(&stopped) + ), + stop_pr::Stopped::Refused { .. } => { + warn!(run_id, "{}", stop_pr::stop_line(&stopped)) + } + } true } Err(e) => { @@ -2216,6 +2235,16 @@ async fn run_passes( // --- Checkpoint Resume: skip expensive passes if we've already completed them --- let checkpoint = load_checkpoint(state, &msg.team_id, run_id).await; + // A person's Retry of a run that finished its work (implemented, its + // branch kept, stopped after: the pull request GitHub refused, a check) + // goes on from that work: the earlier run's checkpoint becomes this + // run's, so the retry opens the pull request from the branch without + // implementing again. Only with the earlier plan, which the retry takes + // up below. + let checkpoint = match checkpoint { + Some(c) => Some(c), + None => inherited_checkpoint(state, msg, run_id, &github, usage).await, + }; let can_skip_implement = checkpoint.as_ref().is_some_and(|(last_pass, branch, _)| { !branch.is_empty() && matches!( @@ -11812,6 +11841,55 @@ pub(crate) async fn save_checkpoint( } /// Load an existing checkpoint for a run (if any). +/// The checkpoint a Retry takes up from the run it retries: one that says +/// the work was implemented (`implement` or a pass after it), on a branch. +/// A run stopped before its work finished implements again, as before. +pub(crate) fn retry_checkpoint(prev: Option<(String, String, u8)>) -> Option<(String, String, u8)> { + prev.filter(|(last, branch, _)| { + !branch.is_empty() + && matches!( + last.as_str(), + "implement" | "security" | "pr" | "test" | "review" + ) + }) +} + +/// A Retry (`resume_from`) of a run whose work was done: that run's +/// checkpoint, saved as this run's (so a continuation of this run keeps +/// it), when the earlier plan and the branch are still there. +async fn inherited_checkpoint( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + usage: &TokenUsage, +) -> Option<(String, String, u8)> { + let prev = msg + .resume_from + .as_deref() + .filter(|r| !msg.same_run() && !r.is_empty() && *r != run_id)?; + let (last, branch, cycle) = retry_checkpoint(load_checkpoint(state, &msg.team_id, prev).await)?; + // The plan the work was made against, and the branch holding it. + load_run_plan(state, msg, prev).await?; + github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch) + .await + .ok() + .filter(|head| !head.is_empty())?; + save_checkpoint(state, &msg.team_id, run_id, &last, &branch, cycle, usage).await; + info!(run_id, retried = %prev, last_pass = %last, branch = %branch, "Retry: going on from the earlier run's finished work"); + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Retry: the work on `{branch}` is done; going on from it to the checks and the pull request" + ), + ) + .await; + Some((last, branch, cycle)) +} + async fn load_checkpoint( state: &WorkerState, team_id: &str, @@ -13131,4 +13209,52 @@ mod retry_resume_tests { assert_eq!(back.resume_from.as_deref(), Some("01RUN")); assert!(!back.retry_of_run); } + + /// The run that did all 24 tasks and stopped when GitHub refused its + /// pull request: Retry goes on from its checkpoint (the work, the + /// branch) to the checks and the pull request, never implementing + /// again. A run stopped before its work finished implements again. + #[test] + fn a_retry_of_finished_work_opens_the_pull_request_from_the_branch() { + use super::retry_checkpoint; + let branch = "coderhelm/security-updates-2026-11-12-abc123".to_string(); + // The run record's error: Retry takes up that run (not a plan error). + let error = "HTTP status client error (422 Unprocessable Entity) for url \ + (https://api.github.com/repos/acme/api/pulls): body is too long"; + assert!(common::run_status::retry_resumes("done", error)); + for last in ["implement", "security", "pr", "test", "review"] { + assert_eq!( + retry_checkpoint(Some((last.into(), branch.clone(), 0))), + Some((last.into(), branch.clone(), 0)), + "{last}" + ); + } + for last in ["implement_started", "plan", "triage", ""] { + assert_eq!( + retry_checkpoint(Some((last.into(), branch.clone(), 0))), + None, + "{last}" + ); + } + assert_eq!( + retry_checkpoint(Some(("implement".into(), String::new(), 0))), + None + ); + assert_eq!(retry_checkpoint(None), None); + // The run uses it before deciding whether to implement, and the + // pull request pass finds the branch's open pull request (the + // stopped run's draft) and writes its description in place. + let src = include_str!("mod.rs"); + let run = &src[src.find("async fn run_passes(").unwrap()..]; + let inherit = run + .find("None => inherited_checkpoint(state, msg, run_id, &github, usage).await") + .expect("Retry takes up the checkpoint"); + let skip = run.find("let can_skip_implement = checkpoint").unwrap(); + assert!(inherit < skip); + let pr = include_str!("pr.rs"); + assert!(pr.contains(".find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch)")); + assert!(pr.contains( + "super::security_fixes::on_pr_opened(state, github, msg, number, &url).await;\n }\n (number, url, nid)" + )); + } } diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 2a49e3612..05c2a30e7 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -645,6 +645,12 @@ Return ONLY the markdown body text."#, { warn!(pr_number = number, error = %e, "Could not update the existing PR's description"); } + // A security fix whose pull request an earlier attempt opened (a + // stopped run's draft, then Retry): its findings learn the pull + // request now, as they would have when it opened. + if common::security_fixes::is_ticket(&msg.ticket_id) { + super::security_fixes::on_pr_opened(state, github, msg, number, &url).await; + } (number, url, nid) } else if let Some(pr_data) = reopen_prior_pr(github, msg, branch).await { let number = pr_data @@ -689,8 +695,11 @@ Return ONLY the markdown body text."#, warn!(branch, error = %e, "Squash before PR failed — proceeding with full history"); } - // Create draft PR — CI triggers on PR creation, and we'll mark it ready after tests/review pass - let pr_data = github + // Create draft PR — CI triggers on PR creation, and we'll mark it ready after tests/review pass. + // The client fits the body to GitHub's limit; a refusal of the + // body or title anyway is tried once more with the body shortened + // harder, then said in GitHub's own plain words. + let pr_data = match github .create_pull_request( &msg.repo_owner, &msg.repo_name, @@ -700,7 +709,38 @@ Return ONLY the markdown body text."#, &msg.base_branch, true, ) - .await?; + .await + { + Ok(p) => p, + Err(e) if is_validation_refusal(&e.to_string()) => { + warn!(branch, error = %e, "GitHub refused the pull request; trying once more with a shorter description"); + let shorter = common::pr_body_fit::fit_to( + &full_body, + common::pr_body_fit::BODY_TARGET / 2, + None, + ); + github + .create_pull_request( + &msg.repo_owner, + &msg.repo_name, + &title, + &shorter, + branch, + &msg.base_branch, + true, + ) + .await + .map_err(|e| -> Box { + let text = e.to_string(); + if is_validation_refusal(&text) { + refusal_words("open the pull request", &text).into() + } else { + e + } + })? + } + Err(e) => return Err(e), + }; let number = pr_data .get("number") @@ -1305,6 +1345,58 @@ fn writer_system(voice_block: &str, standards_block: &str, team_instructions: &s ) } +/// True when GitHub refused a write as invalid (422 Validation Failed: a +/// body or title too long, a field it doesn't take), not for its rate +/// limit or an outage: those keep their own error so the run waits. +pub fn is_validation_refusal(err: &str) -> bool { + err.contains("422") && err.contains("Validation Failed") +} + +/// GitHub's refusal, in plain words: "GitHub refused to {what}: body is too +/// long (maximum is 65536 characters)". Read from the JSON GitHub answers +/// with (its most specific message per field); the status line when there +/// is none. +pub fn refusal_words(what: &str, err: &str) -> String { + let json = err + .find('{') + .and_then(|i| serde_json::from_str::(&err[i..]).ok()); + let mut said: Vec = vec![]; + if let Some(v) = &json { + for e in v["errors"].as_array().into_iter().flatten() { + let m = e["message"] + .as_str() + .map(String::from) + .or_else(|| { + let field = e["field"].as_str()?; + let code = e["code"].as_str().unwrap_or("invalid"); + Some(format!("{field} is {}", code.replace('_', " "))) + }) + .unwrap_or_default(); + let m = m.trim().to_string(); + if m.is_empty() { + continue; + } + // "body is too long" and "body is too long (maximum is ...)": + // the longer one says it all. + if let Some(i) = said.iter().position(|s| m.starts_with(s.as_str())) { + said[i] = m; + } else if !said.iter().any(|s| s.starts_with(&m)) { + said.push(m); + } + } + if said.is_empty() { + if let Some(m) = v["message"].as_str() { + said.push(m.to_string()); + } + } + } + if said.is_empty() { + let line = err.split(" for url").next().unwrap_or(err); + said.push(common::truncate_str(line.trim(), 300).to_string()); + } + format!("GitHub refused to {what}: {}", said.join("; ")) +} + /// The PR's title: the team's template, or `{ticket}: {title}` (cut to 72 /// characters) as always. pub(crate) fn pr_title( @@ -2112,6 +2204,52 @@ mod check_results_tests { } } +#[cfg(test)] +mod refusal_tests { + use super::{is_validation_refusal, refusal_words}; + + /// The error the run ended with, as the client raised it. + pub const TOO_LONG: &str = "HTTP status client error (422 Unprocessable Entity) for url (https://api.github.com/repos/acme/api/pulls): {\"message\":\"Validation Failed\",\"errors\":[{\"resource\":\"Issue\",\"code\":\"custom\",\"field\":\"body\",\"message\":\"body is too long\"},{\"resource\":\"Issue\",\"code\":\"custom\",\"field\":\"body\",\"message\":\"body is too long (maximum is 65536 characters)\"}],\"documentation_url\":\"https://docs.github.com/rest/pulls/pulls#create-a-pull-request\",\"status\":\"422\"}"; + + #[test] + fn githubs_refusal_reads_in_plain_words() { + assert!(is_validation_refusal(TOO_LONG)); + assert_eq!( + refusal_words("open the pull request", TOO_LONG), + "GitHub refused to open the pull request: body is too long (maximum is 65536 characters)" + ); + let exists = "HTTP status client error (422 Unprocessable Entity) for url (u): {\"message\":\"Validation Failed\",\"errors\":[{\"resource\":\"PullRequest\",\"code\":\"custom\",\"message\":\"A pull request already exists for acme:b.\"}]}"; + assert_eq!( + refusal_words("open the pull request", exists), + "GitHub refused to open the pull request: A pull request already exists for acme:b." + ); + let coded = "422 {\"message\":\"Validation Failed\",\"errors\":[{\"resource\":\"PullRequest\",\"field\":\"head\",\"code\":\"invalid\"}]}"; + assert!(refusal_words("open the pull request", coded).ends_with("head is invalid")); + // A rate limit or an outage is not a refusal: it keeps its own error. + assert!(!is_validation_refusal("GitHub API error 429: rate limit")); + assert!(!is_validation_refusal( + "HTTP status server error (502 Bad Gateway)" + )); + } + + /// The pull request pass tries once more with a shorter description, + /// then fails with GitHub's words, never the raw HTTP line. + #[test] + fn a_refused_create_is_retried_once_then_said_plainly() { + let src = include_str!("pr.rs"); + let at = src.find("Create draft PR").unwrap(); + let create = &src[at..at + 2400]; + assert_eq!( + create.matches(".create_pull_request(").count(), + 2, + "{create}" + ); + assert!(create.contains("is_validation_refusal(&e.to_string())")); + assert!(create.contains("BODY_TARGET / 2")); + assert!(create.contains("refusal_words(\"open the pull request\"")); + } +} + #[cfg(test)] mod refresh_tests { use super::{ diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index 5df47e8cd..c549428d4 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -2996,7 +2996,8 @@ async fn refresh_pr( Some(pr), ) .await; - let body = sec::pr_body_with(unit, &pairs, &change, &check); + let links = body_links(cx.state, item.as_ref()); + let body = sec::pr_body_linked(unit, &pairs, &change, &check, &links); if let Err(e) = cx.gh.update_pr_body(o, n, pr, &body).await { warn!(repo = %unit.repo, pr, error = %e, "security: could not write the bundle's description"); } @@ -4135,19 +4136,111 @@ pub async fn pr_body(state: &WorkerState, msg: &TicketMessage, change: &str) -> .await; let members = unit_findings(state, &msg.team_id, &unit).await; let pairs: Vec<(&Finding, &FindingState)> = members.iter().map(|(f, s)| (f, s)).collect(); - let notes = ticket_item(state, &msg.team_id, &msg.ticket_id) - .await - .map(|i| s(&i, "notes")) - .unwrap_or_default(); - let mut check = match github(state, msg.installation_id) { - Ok(gh) => what_to_check(&gh, &unit, ¬es, None).await, - Err(_) => common::upgrade_notes::WhatToCheck::from_notes(¬es), + let item = ticket_item(state, &msg.team_id, &msg.ticket_id).await; + let notes = item.as_ref().map(|i| s(i, "notes")).unwrap_or_default(); + let gh = github(state, msg.installation_id).ok(); + let mut check = match &gh { + Some(gh) => what_to_check(gh, &unit, ¬es, None).await, + None => common::upgrade_notes::WhatToCheck::from_notes(¬es), }; - check.dep_report = ticket_item(state, &msg.team_id, &msg.ticket_id) - .await - .map(|i| s(&i, "dep_report")) + check.dep_report = item + .as_ref() + .map(|i| s(i, "dep_report")) .unwrap_or_default(); - Some(sec::pr_body_with(&unit, &pairs, change, &check)) + let mut links = body_links(state, item.as_ref()); + // A bundle too long to describe in full keeps its full detail on its + // branch, beside the plan CoderHelm commits there, when the team lets + // CoderHelm commit those files. + if sec::uses_short_body(&unit, &pairs) { + if let Some(gh) = &gh { + if let Some(url) = keep_detail(state, gh, msg, &unit, &pairs, change, &check).await { + links.detail = url; + } + } + } + Some(sec::pr_body_linked(&unit, &pairs, change, &check, &links)) +} + +/// Where a security description points for what it leaves out: each +/// finding's page in CoderHelm, and the full detail kept on the branch (its +/// link recorded on the ticket when it was written). +fn body_links(state: &WorkerState, item: Option<&Item>) -> sec::BodyLinks { + sec::BodyLinks { + finding: format!( + "{}/security/detail?id=", + super::skills::app_url(&state.config.stage) + ), + detail: item.map(|i| s(i, "detail_url")).unwrap_or_default(), + } +} + +/// The link to a file on a branch on GitHub. +pub fn blob_url(repo: &str, branch: &str, path: &str) -> String { + format!("https://github.com/{repo}/blob/{branch}/{path}") +} + +/// Writes the full detail of a bundle (every package's notes, every +/// advisory) to `openspec/specs//security-detail.md` on its branch, +/// where CoderHelm keeps the run's plan, and records its link on the +/// ticket. Only when the team lets CoderHelm commit those files +/// (`commit_openspec`); a file already as written is left alone. +async fn keep_detail( + state: &WorkerState, + gh: &GitHubClient, + msg: &TicketMessage, + unit: &FixUnit, + pairs: &[(&Finding, &FindingState)], + change: &str, + check: &common::upgrade_notes::WhatToCheck, +) -> Option { + if unit.branch.is_empty() + || !super::load_workflow_setting(state, &msg.team_id, "commit_openspec").await + { + return None; + } + let (o, n) = unit.repo.split_once('/')?; + let path = sec::detail_path(&msg.ticket_id); + let doc = sec::detail_doc(unit, pairs, change, check); + let same = gh + .read_file(o, n, &path, &unit.branch) + .await + .is_ok_and(|now| now == doc); + if !same { + let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; + let message = conventions.commit_message( + &super::ticket_tokens(msg), + &format!("Add the full detail of {}", msg.ticket_id), + ); + if let Err(e) = gh + .batch_write( + o, + n, + &unit.branch, + &message, + &[crate::clients::github::FileOp::Write { + path: path.clone(), + content: doc, + }], + ) + .await + { + warn!(repo = %unit.repo, error = %e, "security: could not keep the full detail on the branch"); + return None; + } + } + let url = blob_url(&unit.repo, &unit.branch, &path); + let _ = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(&msg.team_id)) + .key("sk", attr_s(&sec::ticket_sk(&msg.ticket_id))) + .update_expression("SET detail_url = :u") + .condition_expression("attribute_exists(sk)") + .expression_attribute_values(":u", attr_s(&url)) + .send() + .await; + Some(url) } /// Keeps a ticket's upgrade notes. @@ -4274,7 +4367,10 @@ async fn refresh_ci_sections(cx: &Ctx<'_>, repo: &str, number: u64, ticket: &str let members = unit_findings(cx.state, cx.team_id, &unit).await; let pairs: Vec<(&Finding, &FindingState)> = members.iter().map(|(f, st)| (f, st)).collect(); let check = what_to_check(&cx.gh, &unit, ¬es, Some(number)).await; - let fresh = sec::pr_body_with(&unit, &pairs, &change, &check); + // The same links as when it opened: the rewritten sections are the + // short ones a bundle's description carries. + let links = body_links(cx.state, item.as_ref()); + let fresh = sec::pr_body_linked(&unit, &pairs, &change, &check, &links); let next = common::upgrade_notes::replace_sections(body, &fresh, &["## What to check", "## Proof"]); if next != body { @@ -4314,6 +4410,10 @@ pub async fn on_pr_opened( }; let mut carded = false; for (f, st) in members.iter_mut() { + // Told already (the pull request was there before this run). + if f.pr.as_ref().is_some_and(|p| p.number == number) { + continue; + } f.status = Status::PrOpen; f.pr = Some(sec::PrRef { number, diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index 23c3a3ae0..eed53e834 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -181,6 +181,49 @@ async fn progress( } } +/// What [`open`] did for a stopped run with work on its branch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stopped { + /// The draft pull request is open (or was already), and the run waits + /// for its review. + Opened { number: u64, url: String }, + /// GitHub refused the pull request, twice: the run waits on a person + /// with GitHub's reason in plain words, and nothing claims a pull + /// request it doesn't have. + Refused { why: String }, +} + +/// The pull request GitHub answered a create with: its number and link, or +/// why there is none in plain words. A create GitHub refused, or an answer +/// without a number, is never taken for an open pull request. +pub fn created(answer: Result) -> Result<(u64, String), String> { + match answer { + Ok(p) => match (p["number"].as_u64(), p["html_url"].as_str()) { + (Some(n), Some(u)) if n > 0 && !u.trim().is_empty() => Ok((n, u.to_string())), + _ => Err( + "GitHub answered the request to open the pull request without a pull \ + request number" + .to_string(), + ), + }, + Err(e) => Err(super::pr::refusal_words( + "open the pull request", + &e.to_string(), + )), + } +} + +/// The log line for a stopped run's pull request: it names a pull request +/// only when there is one. +pub fn stop_line(s: &Stopped) -> String { + match s { + Stopped::Opened { number, .. } => { + format!("Opened draft pull request #{number} for the stopped run") + } + Stopped::Refused { why } => format!("No pull request for the stopped run: {why}"), + } +} + /// Opens (or finds) the draft pull request for a stopped run's branch and /// records it on the run. Errors when the branch holds no work. pub async fn open( @@ -189,7 +232,7 @@ pub async fn open( run_id: &str, branch: &str, reason: &str, -) -> Result { +) -> Result { // Handing the work to a person is the stop judge's call: it either // names what blocks, or the draft carries its assumption as an open item. let mut usage = crate::models::TokenUsage::default(); @@ -218,7 +261,7 @@ pub async fn open_with( items: &[super::proof::Finding], notify: bool, judged: &super::stop_judge::Judged, -) -> Result { +) -> Result { let mut with_assumption = items.to_vec(); if let Some(a) = judged.assumption() { with_assumption.push(super::proof::Finding { @@ -317,7 +360,10 @@ pub async fn open_with( .await?; let (number, url) = match existing { Some(p) => { - let number = p["number"].as_u64().unwrap_or(0); + let number = p["number"] + .as_u64() + .filter(|n| *n > 0) + .ok_or("GitHub listed the branch's pull request without its number")?; // The pull request already open says what is not finished too. if !unfinished.is_empty() { let now = with_unfinished(p["body"].as_str().unwrap_or(""), &unfinished); @@ -345,21 +391,56 @@ pub async fn open_with( let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; let title = super::pr::pr_title(&conventions, &super::ticket_tokens(msg), msg); - let p = github - .create_pull_request( - &msg.repo_owner, - &msg.repo_name, - common::truncate_str(&title, 72), + let title = common::truncate_str(&title, 72); + // Refused once: once more with the body shortened harder, then + // the run waits with GitHub's reason, never claiming a pull + // request it doesn't have. + let mut answer = created( + github + .create_pull_request( + &msg.repo_owner, + &msg.repo_name, + title, + &draft_body, + branch, + &msg.base_branch, + true, + ) + .await, + ); + if let Err(first) = &answer { + tracing::warn!(run_id, error = %first, "GitHub refused the stopped run's pull request; trying once more"); + let shorter = common::pr_body_fit::fit_to( &draft_body, - branch, - &msg.base_branch, - true, - ) - .await?; - ( - p["number"].as_u64().unwrap_or(0), - p["html_url"].as_str().unwrap_or("").to_string(), - ) + common::pr_body_fit::BODY_TARGET / 2, + None, + ); + answer = created( + github + .create_pull_request( + &msg.repo_owner, + &msg.repo_name, + title, + &shorter, + branch, + &msg.base_branch, + true, + ) + .await, + ); + } + match answer { + Ok(p) => p, + Err(why) => { + let hand_back = hand_back.as_ref().expect("checked above"); + record_refused(state, msg, run_id, branch, reason, &why, judged, hand_back) + .await; + if notify { + super::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; + } + return Ok(Stopped::Refused { why }); + } + } } }; let now = chrono::Utc::now().to_rfc3339(); @@ -410,7 +491,76 @@ pub async fn open_with( if notify { super::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; } - Ok(url) + Ok(Stopped::Opened { number, url }) +} + +/// What a stopped run waits for when GitHub refused its pull request: a +/// person, with GitHub's words and what Retry does. +pub fn refused_wait(why: &str) -> WaitingOn { + WaitingOn::action( + "Open the pull request", + &format!( + "The work is done and on the branch, but {why}. Press Retry: CoderHelm opens the \ + pull request from the branch without doing the work again." + ), + "", + ) + .unwrap_or_default() +} + +/// Records a stopped run whose pull request GitHub refused: it waits on a +/// person (never failed, never "Review pull request #0"), with the branch +/// kept and GitHub's reason as its error. Only a run the supervisor already +/// hands back gets here (`hand_back`, a reason on the human-only list); a +/// run it ships opens its pull request in [`ship`]. +#[allow(clippy::too_many_arguments)] +async fn record_refused( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + branch: &str, + reason: &str, + why: &str, + judged: &super::stop_judge::Judged, + hand_back: &common::handback::HandBack, +) { + // The stop judge's hold, when it named one, goes with GitHub's words. + let why = match judged.hold_words() { + Some(h) => format!("{why}. Blocked on: {h}"), + None => why.to_string(), + }; + let why = why.as_str(); + let wait = refused_wait(why); + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", super::attr_s(&msg.team_id)) + .key("run_id", super::attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, branch = :b, \ + error_message = :em, updated_at = :t, current_pass = :cp", + ) + .condition_expression(common::run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":cp", super::attr_s("done")) + .needs_input(run_id, &wait, hand_back) + .expression_attribute_values(":b", super::attr_s(branch)) + .expression_attribute_values(":em", super::attr_s(&format!("{reason} {why}."))) + .expression_attribute_values(":t", super::attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if let Err(e) = res { + tracing::warn!(run_id, error = %e, "Could not record the refused pull request on the run"); + } + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Stopped after the work; no pull request: {why}"), + ) + .await; } /// The "Deferred" section of a run that shipped with tasks left: what @@ -453,7 +603,7 @@ async fn ship( open_text: &str, stop: &super::outcome::Stop, progress: &Progress, -) -> Result { +) -> Result { if let Some(mut plan) = super::run_plan_files(state, msg).await { let defer: Vec<(String, String)> = progress .remaining @@ -478,7 +628,10 @@ async fn ship( .await?; let (number, url) = match existing { Some(p) => { - let number = p["number"].as_u64().unwrap_or(0); + let number = p["number"] + .as_u64() + .filter(|n| *n > 0) + .ok_or("GitHub listed the branch's pull request without its number")?; let body = p["body"].as_str().unwrap_or(""); let now = if body.contains("## Deferred") { body.to_string() @@ -503,21 +656,21 @@ async fn ship( open_text, &deferred, ); - let p = github - .create_pull_request( - &msg.repo_owner, - &msg.repo_name, - common::truncate_str(&title, 72), - &body, - branch, - &msg.base_branch, - true, - ) - .await?; - ( - p["number"].as_u64().unwrap_or(0), - p["html_url"].as_str().unwrap_or("").to_string(), - ) + // Named only when GitHub gave it a number; a refusal is the + // error, in GitHub's words. + created( + github + .create_pull_request( + &msg.repo_owner, + &msg.repo_name, + common::truncate_str(&title, 72), + &body, + branch, + &msg.base_branch, + true, + ) + .await, + )? } }; let usage = crate::models::TokenUsage::default(); @@ -572,7 +725,7 @@ async fn ship( super::run_guard::Progress::PrOpen, ) .await; - Ok(url) + Ok(Stopped::Opened { number, url }) } /// The body of a pull request a run shipped with work deferred: the ticket @@ -695,6 +848,79 @@ mod tests { } } + const TOO_LONG: &str = "HTTP status client error (422 Unprocessable Entity) for url (https://api.github.com/repos/acme/api/pulls): {\"message\":\"Validation Failed\",\"errors\":[{\"resource\":\"Issue\",\"code\":\"custom\",\"field\":\"body\",\"message\":\"body is too long\"},{\"resource\":\"Issue\",\"code\":\"custom\",\"field\":\"body\",\"message\":\"body is too long (maximum is 65536 characters)\"}],\"status\":\"422\"}"; + + /// A create GitHub refused, or answered without a number, is never an + /// open pull request: the stop names none and waits with GitHub's words. + #[test] + fn a_refused_create_never_claims_a_pull_request() { + let refused = created(Err(TOO_LONG.into())).unwrap_err(); + assert_eq!( + refused, + "GitHub refused to open the pull request: body is too long (maximum is 65536 characters)" + ); + for answer in [ + serde_json::json!({}), + serde_json::json!({"number": 0, "html_url": "https://github.com/acme/api/pull/0"}), + serde_json::json!({"number": 12}), + ] { + assert!(created(Ok(answer.clone())).is_err(), "{answer}"); + } + assert_eq!( + created(Ok( + serde_json::json!({"number": 602, "html_url": "https://github.com/acme/api/pull/602"}) + )), + Ok((602, "https://github.com/acme/api/pull/602".to_string())) + ); + let line = stop_line(&Stopped::Refused { + why: refused.clone(), + }); + assert!(!line.contains("Opened") && !line.contains('#'), "{line}"); + assert!(line.contains("body is too long (maximum is 65536 characters)")); + let line = stop_line(&Stopped::Opened { + number: 602, + url: "u".into(), + }); + assert_eq!(line, "Opened draft pull request #602 for the stopped run"); + // The run waits on a person, with GitHub's words and what Retry does. + let w = refused_wait(&refused); + assert_eq!(w.action, "Open the pull request"); + assert!(w + .detail + .contains("body is too long (maximum is 65536 characters)")); + assert!(w.detail.contains("Press Retry")); + assert!(!w.detail.contains("HTTP status")); + } + + /// The stop path: a refused create is tried once more, shorter, and + /// then recorded as a wait; the log names a pull request only from + /// `Stopped::Opened`, never from a create that failed. + #[test] + fn the_stop_path_logs_only_a_pull_request_it_has() { + let src = include_str!("stop_pr.rs"); + let open_with = &src[src.find("pub async fn open_with(").unwrap() + ..src + .find("/// What a stopped run waits for when GitHub refused") + .unwrap()]; + assert_eq!(open_with.matches(".create_pull_request(").count(), 2); + assert!(open_with.contains("record_refused(")); + assert!(open_with.contains("Ok(Stopped::Refused { why })")); + assert!( + !open_with.contains("as_u64().unwrap_or(0)"), + "no pull request #0" + ); + let run = include_str!("mod.rs"); + assert!( + !run.contains("pr_url, \"Opened a draft PR"), + "the old line logged a link it didn't check" + ); + assert_eq!( + run.matches("stop_pr::Stopped::Opened { number, url } => info!(") + .count(), + 2 + ); + } + #[test] fn an_open_pull_request_gets_the_section_once() { let nf = not_finished(