diff --git a/docs/self-host/github-app.md b/docs/self-host/github-app.md index 66123f1a0..f916288da 100644 --- a/docs/self-host/github-app.md +++ b/docs/self-host/github-app.md @@ -31,7 +31,7 @@ It uses GitHub's [manifest flow](https://docs.github.com/en/apps/sharing-github- | Pull requests | write | Open and update pull requests; post reviews | | Issues | write | Read assigned issues; post progress | | Checks | write | Read CI results to fix failures; show the "CoderHelm review" check on a pull request's commit from the moment CoderHelm accepts anything on it (a push, a reply, a re-review, an edited description), saying what it is doing, until it ends, linking to the session page; a reply that is only answered leaves the commit showing the standing verdict | -| Actions | read | Read workflow runs and logs | +| Actions | write | Read workflow runs and logs; start a workflow a step needs (a deploy, an end-to-end run) with `workflow_dispatch`. Read is required; write is optional: without it CoderHelm adds the label that starts a workflow where the workflow has one, and otherwise the step waits | | Commit statuses | read | CI that reports statuses instead of checks | | Workflows | write | Change workflow files when a task asks for it | | Metadata | read | Repository list and details | @@ -51,6 +51,8 @@ An app created before security fixes keeps working without **Dependabot alerts: With CoderHelm's hosted app (hybrid installs), each token asks only for the permissions your installation has granted: one added to the app later is left out until an owner accepts it on the installation, and a token never fails for it. Accepting it takes effect within an hour, when the next token is issued. +An app created before CoderHelm asked for **Actions: write** keeps working with **Actions: read**. Setup checks warns about it once, on the install's setup page, never on a pull request: set Actions to write on the app's Permissions and events page and accept the new permission on each installation. Until then CoderHelm starts workflows through their labels where they have one (adding a label needs only pull request write). + An app created before CoderHelm asked for **Checks: write** keeps working with **Checks: read**: reviews are posted as before, but pull requests don't show the "CoderHelm review" check. Setup checks warns about it until you set Checks to write on the app's Permissions and events page and accept the new permission on each installation. ## URLs it uses diff --git a/installer/lib/github-app.mjs b/installer/lib/github-app.mjs index 3e3926131..2fda1aa46 100644 --- a/installer/lib/github-app.mjs +++ b/installer/lib/github-app.mjs @@ -22,8 +22,11 @@ export const PERMISSIONS = { // check on a pull request while it is reviewed. Only read is required // (REQUIRED_PERMISSIONS): reviews work without the check. checks: "write", - // Read workflow runs and their logs (CI fixes). - actions: "read", + // Read workflow runs and their logs (CI fixes), and start a workflow a + // step needs (workflow_dispatch: a deploy, an end-to-end run that has no + // label to start it). Only read is required (REQUIRED_PERMISSIONS): + // without write, CoderHelm starts what a label starts and lists the rest. + actions: "write", // Read commit statuses (CI that reports statuses, not checks). statuses: "read", // Change workflow files when a task asks for it. @@ -56,6 +59,7 @@ export const OPTIONAL_WHY = { deployments: "Without Deployments, what shipped where is worked out from workflow names instead of GitHub's deployments.", repository_advisories: "Without Repository security advisories, security fixes don't see a repository's own advisories and private vulnerability reports.", code_quality: "Without Code quality, reviews don't see GitHub's code quality findings on the changed files.", + actions: "Without Actions: write, CoderHelm can't start a workflow itself (a deploy, an end-to-end run): it adds the label that starts one where the workflow has one, and otherwise the step waits.", }; /** @@ -64,8 +68,9 @@ export const OPTIONAL_WHY = { * (services/gateway/src/routes/setup_checks.rs REQUIRED_PERMISSIONS). */ export const REQUIRED_PERMISSIONS = (() => { - const out = { ...PERMISSIONS, checks: "read" }; - for (const k of Object.keys(OPTIONAL_WHY)) if (k !== "checks") delete out[k]; + // Checks and Actions: read is required, write is optional. + const out = { ...PERMISSIONS, checks: "read", actions: "read" }; + for (const k of Object.keys(OPTIONAL_WHY)) if (k !== "checks" && k !== "actions") delete out[k]; return out; })(); diff --git a/installer/test/checks.test.mjs b/installer/test/checks.test.mjs index a7891a22c..0daeabdd6 100644 --- a/installer/test/checks.test.mjs +++ b/installer/test/checks.test.mjs @@ -254,8 +254,10 @@ test("GitHub: no app, refused keys, missing permissions, wrong webhook, bad secr // Every optional permission a new app asks for warns with what it limits. for (const [key, why] of Object.entries(OPTIONAL_WHY)) { - const lacking = { ...APP, permissions: { ...PERMISSIONS, [key]: key === "checks" ? "read" : undefined } }; - if (key !== "checks") delete lacking.permissions[key]; + // Checks and Actions: read is required, only write is optional. + const readOnly = key === "checks" || key === "actions"; + const lacking = { ...APP, permissions: { ...PERMISSIONS, [key]: readOnly ? "read" : undefined } }; + if (!readOnly) delete lacking.permissions[key]; const r = (await C.checkGithubApp({ fetchImpl: github({ "/app": json(200, lacking) }).fetchImpl }, SECRET, "https://helm.example.org")).find((x) => x.id === "github_permissions"); assert.equal(r.status, C.WARN, key); assert.ok(r.why.includes(why), `${key}: ${r.why}`); diff --git a/installer/test/installer.test.mjs b/installer/test/installer.test.mjs index e7fa84f3a..8dc21eb63 100644 --- a/installer/test/installer.test.mjs +++ b/installer/test/installer.test.mjs @@ -11,7 +11,7 @@ import path from "node:path"; import http from "node:http"; import { main } from "../lib/cli.mjs"; import * as cmd from "../lib/commands.mjs"; -import { buildManifest, convertCode, EVENTS, formPage, newAppUrl, PERMISSIONS, runManifestFlow, secretKeysFromApp } from "../lib/github-app.mjs"; +import { buildManifest, convertCode, EVENTS, formPage, newAppUrl, PERMISSIONS, REQUIRED_PERMISSIONS, runManifestFlow, secretKeysFromApp } from "../lib/github-app.mjs"; import { parseSums, verifySums } from "../lib/release.mjs"; import { initialSecret, hasGithubApp } from "../lib/secrets.mjs"; import { checkPrereqs } from "../lib/prereqs.mjs"; @@ -213,9 +213,12 @@ test("manifest: URLs, permissions and events", () => { assert.deepEqual(m.default_events, EVENTS); // Security fixes: Dependabot alerts and the advisory events are asked for. assert.equal(m.default_permissions.vulnerability_alerts, "read"); - for (const k of ["deployments", "repository_advisories", "code_quality", "actions", "statuses"]) { + for (const k of ["deployments", "repository_advisories", "code_quality", "statuses"]) { assert.equal(m.default_permissions[k], "read", k); } + // Starting a workflow a step needs (workflow_dispatch); read stays required. + assert.equal(m.default_permissions.actions, "write"); + assert.equal(REQUIRED_PERMISSIONS.actions, "read"); assert.equal(m.default_permissions.checks, "write"); assert.equal(m.default_permissions.workflows, "write"); assert.ok(m.default_events.includes("dependabot_alert")); diff --git a/services/common/src/comment_style.rs b/services/common/src/comment_style.rs new file mode 100644 index 000000000..c0443d9d1 --- /dev/null +++ b/services/common/src/comment_style.rs @@ -0,0 +1,540 @@ +//! How a CoderHelm comment reads: a senior engineer's short note. +//! +//! A pull request once got a comment that was one long line listing a +//! dozen deploy workflows (Lambdas, for a web page change) with their file +//! paths, then the release plan pasted in ("1. Deploy the change to +//! production. How: wait for ... CoderHelm does this after the merge."). A +//! second comment pasted the outside-work plan ("Done outside the code: +//! ...; CoderHelm does the other 4 step(s) itself"), asked a person to read +//! an end-to-end result and to run a flow in two browsers, repeated the same +//! missing permission under each item, and ended with "This replaces what I +//! wrote at 03:28 UTC" and a History block. The owner: "they don't make +//! sense", "sounds like a bot", "super spammy". +//! +//! Every comment goes through [`render`] and then [`lint`] before the +//! conversation layer writes it (`conversation::speak_with`): +//! +//! - [`render`] cleans what a writer upstream got wrong, deterministically: +//! history blocks and "This replaces what I wrote" go, pasted plan lines +//! ("How:", "After step", "Gate:", "How it deploys", "Done outside the +//! code", "CoderHelm does ... itself") go, template plurals ("step(s)") +//! are written out, workflow file paths in parentheses go, a sentence +//! said once is not said again, collapsed sections go (details belong in +//! the pull request description), and the note is cut to [`MAX_LINES`] +//! lines of at most [`MAX_LINE_CHARS`] characters. +//! - [`lint`] is the check: a text that still breaks a rule is never +//! posted; the layer keeps quiet and logs the defect. + +/// Lines a comment shows, at most. +pub const MAX_LINES: usize = 5; +/// Characters one line holds, at most. +pub const MAX_LINE_CHARS: usize = 320; + +/// The line that closes a comment cut to [`MAX_LINES`]. +pub fn more_line(markdown: bool) -> &'static str { + if markdown { + "The rest is in the pull request description." + } else { + "The rest is on the run page." + } +} + +/// Words that never appear in a comment, and why. +pub const BANNED: &[(&str, &str)] = &[ + ( + "This replaces what I wrote", + "names an earlier version of itself", + ), + ("History:", "carries a history block"), + ("Retried at ", "carries a history line"), + ("How it deploys", "carries a deploy map"), + ("Done outside the code", "pastes plan status"), + ("CoderHelm does the other", "pastes plan status"), + ("CoderHelm does this after", "pastes plan status"), + (" How: ", "pastes plan text"), + ("After step ", "pastes plan text"), + ("Gate: ", "pastes plan text"), + ( + "
", + "folds details into a comment (they go in the description)", + ), +]; + +/// What breaks the style. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Problem { + /// More than [`MAX_LINES`] lines. + TooManyLines(usize), + /// A line longer than [`MAX_LINE_CHARS`] (its number, 1-based). + LongLine(usize), + /// A banned phrase, and why. + Banned(&'static str, &'static str), + /// A template plural such as "step(s)". + TemplatePlural(String), + /// More than one workflow file path, or a list of file paths. + PathDump(usize), + /// The same sentence twice. + Repeated(String), + /// An arrow glyph. + Arrow, +} + +impl std::fmt::Display for Problem { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Problem::TooManyLines(n) => write!(f, "{n} lines (at most {MAX_LINES})"), + Problem::LongLine(n) => write!(f, "line {n} is over {MAX_LINE_CHARS} characters"), + Problem::Banned(p, why) => write!(f, "\"{p}\": {why}"), + Problem::TemplatePlural(w) => write!(f, "template plural \"{w}\""), + Problem::PathDump(n) => write!(f, "{n} file paths"), + Problem::Repeated(s) => write!(f, "says \"{s}\" twice"), + Problem::Arrow => write!(f, "an arrow glyph"), + } + } +} + +/// Lines a reader sees: not empty, not a hidden marker, not a quote of a +/// person's comment (a reply opens on one). +fn shown_lines(text: &str) -> Vec<&str> { + text.lines() + .map(str::trim_end) + .filter(|l| !l.trim().is_empty()) + .filter(|l| !l.trim_start().starts_with(""; /// The settings-table sort key prefix of what CoderHelm said on a thread /// that can't carry a hidden marker (a Jira ticket). pub const SK_PREFIX: &str = "CONVERSATION#"; -/// New comments on one thread within this window, at most [`RATE_MAX_NEW`]. -pub const RATE_WINDOW_MS: i64 = 10 * 60 * 1000; -pub const RATE_MAX_NEW: usize = 3; -/// History lines a comment keeps. -pub const MAX_HISTORY: usize = 6; /// What a person wrote, quoted in an acknowledgement, in characters. const QUOTE_CHARS: usize = 90; /// In [`Say::answers`]: the text answers everyone who wrote since. @@ -138,6 +138,10 @@ pub struct Say { pub asks: Vec, /// People's comments (ids) the body already answers itself. pub answers: Vec, + /// A status that needs nothing from anyone (progress, work CoderHelm + /// does itself): it goes on the run page and in the description, never + /// in a comment. A comment that said it before is updated to drop it. + pub nobody: bool, } impl Say { @@ -207,6 +211,18 @@ impl Say { self } + /// Marks a status that needs nothing from anyone ([`Say::nobody`]). + pub fn for_nobody(mut self) -> Say { + self.nobody = true; + self + } + + /// Whether this is a status or a note: it lives in the thread's one + /// status comment. + pub fn is_status(&self) -> bool { + matches!(self.kind, Kind::Status | Kind::Note) + } + fn gist_or_first(&self) -> String { let g = if self.gist.trim().is_empty() { first_sentence(&visible(&self.body)) @@ -248,6 +264,26 @@ pub struct Meta { /// When it was first posted (ms). #[serde(default)] pub first_ms: i64, + /// The status comment's parts, newest first: one per slot that has + /// something for a person or a reviewer. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub parts: Vec, + /// Hidden as outdated (it says nothing anyone needs now). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub hidden: bool, + /// An earlier status comment folded into the live one: never edited + /// again. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub outdated: bool, +} + +/// One part of the thread's status comment: what one slot says now. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Part { + pub slot: String, + pub body: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asks: Vec, } /// One of CoderHelm's own comments on the thread. @@ -260,6 +296,9 @@ pub struct Said { /// What it says now (without its marker), when known. #[serde(default)] pub body: String, + /// The tracker's global id (GitHub's node id), for hiding it. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub node_id: String, } /// A person's comment on the thread. @@ -305,24 +344,6 @@ impl View { out } - fn latest_in(&self, slot: &str) -> Option<&Said> { - self.said - .iter() - .filter(|s| s.meta.slot == slot) - .max_by_key(|s| s.at_ms) - } - - fn latest(&self) -> Option<&Said> { - self.said.iter().max_by_key(|s| s.at_ms) - } - - fn new_since(&self, since_ms: i64) -> usize { - self.said - .iter() - .filter(|s| s.meta.first_ms.max(1) >= since_ms && s.meta.first_ms > 0) - .count() - } - /// Records what was just written, so a second say in the same run reads /// it without asking the tracker again. pub fn remember(&mut self, id: &str, at_ms: i64, meta: &Meta) { @@ -332,10 +353,37 @@ impl View { at_ms, meta: meta.clone(), body: String::new(), + node_id: String::new(), }); } + + /// The thread's one live status comment: CoderHelm's newest status or + /// note that wasn't folded into another. + pub fn live_status(&self) -> Option<&Said> { + self.said + .iter() + .filter(|s| matches!(s.meta.kind, Kind::Status | Kind::Note) && !s.meta.outdated) + .max_by_key(|s| (s.at_ms, s.id.clone())) + } + + /// CoderHelm's other status comments on the thread: folded into the + /// live one ([`FOLD_LINE`]) and hidden as outdated. + pub fn to_fold(&self, live: &str) -> Vec<&Said> { + self.said + .iter() + .filter(|s| s.id != live) + .filter(|s| matches!(s.meta.kind, Kind::Status | Kind::Note) && !s.meta.outdated) + .collect() + } } +/// What an earlier status comment says once folded into the live one. +pub const FOLD_LINE: &str = "Outdated. The current status is in CoderHelm's latest comment."; + +/// What the live status comment says when nothing is needed from anyone +/// any more (then it is hidden). +pub const NOTHING_NOW: &str = "Nothing is needed from anyone here now."; + /// What [`decide`] chose. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Decision { @@ -696,7 +744,7 @@ pub fn decide(view: &View, say: &Say, place: &Place, now_ms: i64) -> Decision { .iter() .map(|q| cut_words(&one_line(q), 200)) .collect(); - let mut meta = Meta { + let meta = Meta { slot: say.slot.clone(), kind: say.kind, fp: fp.clone(), @@ -705,10 +753,10 @@ pub fn decide(view: &View, say: &Say, place: &Place, now_ms: i64) -> Decision { answered: Vec::new(), history: Vec::new(), first_ms: now_ms, + ..Default::default() }; let unheard = say.unanswered(view); let answered_any = !say.answers.is_empty(); - let prev = view.latest_in(&say.slot); // A question already asked, with nobody answering since: still waiting. if !asks.is_empty() && unheard.is_empty() && !answered_any { @@ -765,117 +813,122 @@ pub fn decide(view: &View, say: &Say, place: &Place, now_ms: i64) -> Decision { }; } - // People wrote since CoderHelm last spoke, or this answers them: a - // reply to their comment, never a bare new one. - if !unheard.is_empty() || say.kind == Kind::Reply { - let mut text = body.clone(); - if let Some(p) = prev.filter(|p| p.meta.fp != fp && !p.meta.gist.is_empty()) { - text = format!("{text}\n\n{}", changed_line(&p.meta.gist, p.at_ms)); - } + // People wrote since CoderHelm last spoke, or this answers them: a reply + // beneath their comment (every person's comment is acknowledged), never + // a bare new status. A status for nobody answers nobody. + if say.kind == Kind::Reply || (!unheard.is_empty() && !say.nobody) { if let Some(to) = targets.last().cloned() { return Decision::Reply { how: how_for(place, &to), to, others: targets, ack: String::new(), - text: shape(&text, place.budget(), markdown), + text: body, meta, }; } - return Decision::Post { - body: shape(&text, place.budget(), markdown), - meta, - }; + return Decision::Post { body, meta }; } + let _ = now_ms; + status_decision(view, say, place, meta) +} - if let Some(p) = prev { - let same = p.meta.fp == fp; - if same && now_ms - p.at_ms < 60_000 && say.kind != Kind::Status { - return Decision::Quiet { - why: "said the same a moment ago".into(), - }; - } - if same && say.kind == Kind::Note { - return Decision::Quiet { - why: "already said on this thread, and nothing changed".into(), - }; +/// A status or a note, in the thread's one status comment: each slot's part +/// replaced by what it says now, a part that needs nothing from anyone +/// dropped, the whole laid out by `comment_style`. No comment yet and +/// nothing for anyone: nothing is posted (the run page and the description +/// carry it). The text unchanged: nothing is written. +fn status_decision(view: &View, say: &Say, place: &Place, mut meta: Meta) -> Decision { + let markdown = place.markdown(); + let part_body = if say.nobody { + String::new() + } else { + // Work a person was not to get never reaches the comment (the same + // check `sink_decision` makes on every comment). + let sunk = crate::person_gate::sink(&shape(&say.body, place.budget(), markdown)); + if sunk.defect() { + tracing::error!( + thread = %place.key(), + slot = %say.slot, + taken_out = sunk.sent_back.len(), + items = ?sunk.sent_back, + "person gate defect: a status handed people work CoderHelm can do; taken out before posting" + ); } - // A status keeps one live comment: a retry of the same thing, or a - // state that moved on, rewrites it, naming what it said before. - if say.kind == Kind::Status { - let mut history = p.meta.history.clone(); - meta.first_ms = p.meta.first_ms; - meta.answered = p.meta.answered.clone(); - let text = if same { - history.push(format!("Retried at {}; same result.", clock(now_ms))); - body.clone() - } else { - history.push(format!("{}: {}", clock(p.at_ms), p.meta.gist)); - format!("{body}\n\n{}", changed_line(&p.meta.gist, p.at_ms)) - }; - let keep = history.len().saturating_sub(MAX_HISTORY); - history.drain(..keep); - meta.history = history; - return Decision::Edit { - id: p.id.clone(), - body: with_history(&text, &meta.history, place.budget(), markdown), - meta, - }; + crate::comment_style::render(&sunk.text, markdown) + }; + let live = view.live_status(); + let mut parts: Vec = live.map(|l| l.meta.parts.clone()).unwrap_or_default(); + // A comment written before parts existed: what it asked a person is kept + // (cleaned); the rest was status, replaced by this one. + if let Some(l) = live.filter(|l| l.meta.parts.is_empty() && !l.meta.asks.is_empty()) { + let old = crate::comment_style::render(&l.body, markdown); + if !old.is_empty() && l.meta.slot != say.slot { + parts.push(Part { + slot: l.meta.slot.clone(), + body: old, + asks: l.meta.asks.clone(), + }); } - // A note with new information is posted below. } - - // The same meaning already on the thread under another slot. - if view.said.iter().any(|s| s.meta.fp == fp) { - return Decision::Quiet { - why: "already said on this thread, and nothing changed".into(), - }; + parts.retain(|p| p.slot != say.slot); + if !part_body.is_empty() { + parts.insert( + 0, + Part { + slot: say.slot.clone(), + body: part_body, + asks: meta.asks.clone(), + }, + ); } - - // Too many new comments lately: the newest one takes the update. - if view.new_since(now_ms - RATE_WINDOW_MS) >= RATE_MAX_NEW { - if let Some(l) = view.latest() { - let mut m = l.meta.clone(); - m.history - .push(format!("{}: {}", clock(now_ms), say.gist_or_first())); - let keep = m.history.len().saturating_sub(MAX_HISTORY); - m.history.drain(..keep); - return Decision::Edit { - id: l.id.clone(), - body: with_history(&body, &m.history, place.budget(), markdown), - meta: Meta { fp, ..m }, - }; + let joined = parts + .iter() + .map(|p| p.body.as_str()) + .collect::>() + .join("\n"); + let combined = crate::comment_style::render(&joined, markdown); + let mut asks: Vec = Vec::new(); + for p in &parts { + for a in &p.asks { + if !asks.contains(a) { + asks.push(a.clone()); + } } } - - Decision::Post { body, meta } -} - -/// The line that says an earlier comment is replaced, and what it said. -pub fn changed_line(gist: &str, at_ms: i64) -> String { - format!( - "This replaces what I wrote at {} (\"{}\").", - clock(at_ms), - gist.trim().trim_end_matches('.') - ) -} - -fn with_history(body: &str, history: &[String], budget: usize, markdown: bool) -> String { - if history.is_empty() { - return shape(body, budget, markdown); - } - let lines = if markdown { - history - .iter() - .map(|h| format!("- {h}")) - .collect::>() - .join("\n") + meta.asks = asks; + meta.parts = parts; + meta.history = Vec::new(); + meta.hidden = combined.is_empty(); + let body = if combined.is_empty() { + NOTHING_NOW.to_string() } else { - history.join(" ") + combined }; - let tail = format!("\n\nHistory:\n{lines}"); - let room = budget.saturating_sub(tail.chars().count()); - format!("{}{tail}", shape(body, room, markdown)) + meta.fp = fingerprint(&body); + meta.gist = cut_words(&first_sentence(&body), 160); + let Some(l) = live else { + if meta.hidden { + return Decision::Quiet { + why: "needs nothing from anyone: it is on the run page and in the description" + .into(), + }; + } + return Decision::Post { body, meta }; + }; + meta.first_ms = l.meta.first_ms; + meta.answered = l.meta.answered.clone(); + let folds = !view.to_fold(&l.id).is_empty(); + if l.meta.fp == meta.fp && l.meta.hidden == meta.hidden && !folds { + return Decision::Quiet { + why: "the status comment already says this".into(), + }; + } + Decision::Edit { + id: l.id.clone(), + body, + meta, + } } /// `HH:MM UTC` of a time in ms. @@ -908,6 +961,13 @@ pub trait Channel: Send + Sync { let _ = (to, content); Err("no reactions here".into()) } + /// Hides CoderHelm's own comment as outdated (`hidden`), or shows it + /// again. Trackers without hiding say so; the comment's text already + /// says it is outdated. + async fn hide(&self, said: &Said, hidden: bool) -> Result<(), String> { + let _ = (said, hidden); + Err("no hiding here".into()) + } } /// Reads the thread, decides, and writes at most one comment. @@ -966,6 +1026,114 @@ pub fn sink_decision(decision: Decision, thread: &str) -> Decision { } } +/// The house style, the last step before writing: every comment is laid +/// out by `comment_style::render` and held to `comment_style::lint`. A new +/// comment left with nothing to say is not posted; one that still breaks +/// the style is not posted and is logged as a defect of its writer. +pub fn style_decision(decision: Decision, place: &Place) -> Decision { + let markdown = place.markdown(); + let check = |text: &str, max: usize| -> Result { + let out = crate::comment_style::render_within(text, markdown, max); + let problems = crate::comment_style::lint(&out); + if problems.is_empty() { + Ok(out) + } else { + Err(problems + .iter() + .map(ToString::to_string) + .collect::>() + .join("; ")) + } + }; + let defect = |why: String| { + tracing::error!(thread = %place.key(), problems = %why, "comment style defect: a comment broke the style after rendering; not posted"); + Decision::Quiet { + why: format!("the comment breaks the comment style: {why}"), + } + }; + match decision { + Decision::Post { body, meta } => match check(&body, crate::comment_style::MAX_LINES) { + Ok(b) if b.is_empty() => Decision::Quiet { + why: "nothing left to say after the house style".into(), + }, + Ok(body) => Decision::Post { body, meta }, + Err(why) => defect(why), + }, + Decision::Edit { id, body, meta } => match check(&body, crate::comment_style::MAX_LINES) { + Ok(b) if b.is_empty() => Decision::Edit { + id, + body: NOTHING_NOW.to_string(), + meta: Meta { + hidden: true, + ..meta + }, + }, + Ok(body) => Decision::Edit { id, body, meta }, + Err(why) => defect(why), + }, + Decision::Reply { + to, + others, + how, + ack, + text, + meta, + } => { + // The reply opens with one line naming the person; the + // acknowledgement takes one more. + let room = crate::comment_style::MAX_LINES - 1 - usize::from(!ack.trim().is_empty()); + match check(&text, room) { + Ok(text) => Decision::Reply { + to, + others, + how, + ack: crate::comment_style::render_within(&ack, markdown, 1), + text, + meta, + }, + Err(why) => defect(why), + } + } + d => d, + } +} + +/// After the status comment `written` was written: CoderHelm's earlier +/// status comments on the thread are folded into it (rewritten to +/// [`FOLD_LINE`] and hidden as outdated; never deleted), and it is hidden +/// when it says nothing anyone needs, or shown again when it does. +async fn tidy_status(ch: &dyn Channel, view: &View, written: &str, meta: &Meta) { + let place = ch.place(); + for old in view.to_fold(written) { + let folded = Meta { + outdated: true, + hidden: true, + parts: Vec::new(), + asks: Vec::new(), + ..old.meta.clone() + }; + if let Err(e) = ch.edit(&old.id, FOLD_LINE, &folded).await { + tracing::warn!(thread = %place.key(), comment = %old.id, error = %e, "Could not fold an earlier status comment"); + continue; + } + if let Err(e) = ch.hide(old, true).await { + tracing::info!(thread = %place.key(), comment = %old.id, error = %e, "Could not hide an earlier status comment; its text says it is outdated"); + } + } + let was = view.said.iter().find(|s| s.id == written); + let was_hidden = was.is_some_and(|s| s.meta.hidden); + if meta.hidden != was_hidden || (meta.hidden && was.is_none()) { + let said = was.cloned().unwrap_or_else(|| Said { + id: written.to_string(), + meta: meta.clone(), + ..Default::default() + }); + if let Err(e) = ch.hide(&said, meta.hidden).await { + tracing::info!(thread = %place.key(), comment = %written, error = %e, "Could not change whether the status comment is hidden"); + } + } +} + /// [`speak`] for a reply to a person: when the guards decide to answer /// someone, `compose` writes the words from the thread and the run's /// records (`crate::reply_compose`), held to the same guards. @@ -991,7 +1159,7 @@ pub async fn speak_with( if let Some(c) = compose { decision = Box::pin(crate::reply_compose::apply(c, &view, say, &place, decision)).await; } - let decision = sink_decision(decision, &place.key()); + let decision = style_decision(sink_decision(decision, &place.key()), &place); match decision { Decision::Quiet { why } => { tracing::info!(thread = %place.key(), slot = %say.slot, why = %why, "Nothing new to say on the thread"); @@ -999,13 +1167,22 @@ pub async fn speak_with( } Decision::Edit { id, body, meta } => { let written = ch.edit(&id, &body, &meta).await?; + if say.is_status() { + tidy_status(ch, &view, &written, &meta).await; + } Ok(if written == id { Spoke::Edited(id) } else { Spoke::Posted(written) }) } - Decision::Post { body, meta } => Ok(Spoke::Posted(ch.create(&body, &meta).await?)), + Decision::Post { body, meta } => { + let id = ch.create(&body, &meta).await?; + if say.is_status() { + tidy_status(ch, &view, &id, &meta).await; + } + Ok(Spoke::Posted(id)) + } Decision::React { to, content } => { for h in &to { if let Err(e) = ch.react(h, &content).await { @@ -1028,11 +1205,20 @@ pub async fn speak_with( let _ = ch.react(h, "eyes").await; } } - let body = shape( - &reply_body(&to, &others, how, &ack, &text), - place.budget(), - place.markdown(), - ); + // Laid out already (`style_decision`): no collapsed section added. + let body = no_arrows(&reply_body(&to, &others, how, &ack, &text)); + let problems = crate::comment_style::lint(&body); + if !problems.is_empty() { + let why = problems + .iter() + .map(ToString::to_string) + .collect::>() + .join("; "); + tracing::error!(thread = %place.key(), slot = %say.slot, problems = %why, "comment style defect: a reply broke the style after rendering; not posted"); + return Ok(Spoke::Quiet(format!( + "the reply breaks the comment style: {why}" + ))); + } let id = ch.reply(&to, how, &body, &meta).await?; // An answer closes what they asked: a thumbs up on their // comments. @@ -1096,30 +1282,16 @@ async fn judged( let Decision::Post { body, meta } = decision else { return decision; }; + // A status never reaches here as a new comment while one exists: the + // model may only keep a reply-less post quiet. match v.action.as_str() { "quiet" => Decision::Quiet { why: "the model read it as a repeat of what is already on the thread".into(), }, - "edit" => match view.latest() { - Some(l) => { - let mut m = meta; - m.history = l.meta.history.clone(); - m.history - .push(format!("{}: {}", clock(l.at_ms), l.meta.gist)); - m.first_ms = l.meta.first_ms; - let keep = m.history.len().saturating_sub(MAX_HISTORY); - m.history.drain(..keep); - let text = format!("{body}\n\n{}", changed_line(&l.meta.gist, l.at_ms)); - let _ = now_ms; - Decision::Edit { - id: l.id.clone(), - body: with_history(&text, &m.history, place.budget(), place.markdown()), - meta: m, - } - } - None => Decision::Post { body, meta }, - }, - _ => Decision::Post { body, meta }, + _ => { + let _ = (place, now_ms); + Decision::Post { body, meta } + } } } @@ -1685,6 +1857,7 @@ mod tests { ..Default::default() }, body: String::new(), + node_id: format!("N{id}"), } } @@ -1699,21 +1872,15 @@ mod tests { } #[test] - fn an_identical_retry_edits_and_never_posts() { + fn an_identical_retry_writes_nothing() { let body = "Already being fixed in #41. CoderHelm didn't build a second fix."; let view = View { said: vec![said("100", "run", body, T0)], heard: vec![], }; + // The status comment already says it: no edit, no "Retried at". let d = decide(&view, &Say::status("run", body), &gh(), T0 + 3_600_000); - match d { - Decision::Edit { id, body, meta } => { - assert_eq!(id, "100"); - assert!(body.contains("same result"), "{body}"); - assert_eq!(meta.history.len(), 1); - } - other => panic!("{other:?}"), - } + assert!(matches!(d, Decision::Quiet { .. }), "{d:?}"); // A note that repeats is not said at all. let d = decide(&view, &Say::note("run", body), &gh(), T0 + 3_600_000); assert!(matches!(d, Decision::Quiet { .. }), "{d:?}"); @@ -1732,7 +1899,7 @@ mod tests { } #[test] - fn a_status_that_moves_on_edits_one_comment_and_says_what_changed() { + fn a_status_that_moves_on_edits_one_comment_with_only_what_is_true_now() { let view = View { said: vec![said("100", "run", "Started work on this ticket.", T0)], heard: vec![], @@ -1747,13 +1914,13 @@ mod tests { panic!("{d:?}") }; assert_eq!(id, "100"); - assert!(body.starts_with("Opened #52"), "{body}"); - assert!(body.contains("This replaces what I wrote at"), "{body}"); - assert!(meta.history[0].contains("Started work on this ticket")); + assert_eq!(body, "Opened #52 for this ticket."); + assert!(meta.history.is_empty(), "{meta:?}"); + assert_eq!(meta.parts.len(), 1); } #[test] - fn a_contradiction_states_what_changed() { + fn a_changed_status_never_names_its_earlier_version() { let view = View { said: vec![said( "100", @@ -1772,11 +1939,8 @@ mod tests { let Decision::Edit { body, .. } = d else { panic!("{d:?}") }; - assert!( - body.contains("This replaces what I wrote at") - && body.contains("Already being fixed in #41"), - "{body}" - ); + assert_eq!(body, "The run failed: the sandbox could not start."); + assert!(!body.contains("This replaces") && !body.contains("History")); } #[test] @@ -1800,7 +1964,7 @@ mod tests { }; let d = decide( &view, - &Say::status("run", "Changed the orders endpoint and opened #52."), + &Say::reply_all("run", "Changed the orders endpoint and opened #52."), &gh(), T0 + 2_000, ); @@ -1925,7 +2089,7 @@ mod tests { // Something to say: a reply that quotes and names them. let d = decide( &view, - &Say::status("run", "Covered the empty case in #52."), + &Say::reply_all("run", "Covered the empty case in #52."), &gh(), T0 + 1, ); @@ -1959,7 +2123,7 @@ mod tests { }; let d = decide( &view, - &Say::status("run", "Switched to the staging bucket."), + &Say::reply_all("run", "Switched to the staging bucket."), &Place::jira("ABC-1"), T0 + 1, ); @@ -2048,7 +2212,7 @@ mod tests { } #[test] - fn new_comments_are_rate_limited_into_an_edit() { + fn every_status_and_note_goes_in_one_comment() { let mut view = View::default(); for (i, s) in ["a", "b", "c"].iter().enumerate() { view.said.push(said( @@ -2068,6 +2232,17 @@ mod tests { matches!(d, Decision::Edit { ref id, .. } if id == "2"), "{d:?}" ); + // The two older ones are folded into it. + let folded: Vec<&str> = view.to_fold("2").iter().map(|s| s.id.as_str()).collect(); + assert_eq!(folded, vec!["0", "1"]); + // On a fresh thread a status is posted once. + let d = decide( + &View::default(), + &Say::note("d", "Something else entirely."), + &gh(), + T0, + ); + assert!(matches!(d, Decision::Post { .. }), "{d:?}"); } #[test] @@ -2306,6 +2481,13 @@ mod tests { .push(format!("react {} {content}", to.id)); Ok(()) } + async fn hide(&self, said: &Said, hidden: bool) -> Result<(), String> { + self.log + .lock() + .unwrap() + .push(format!("hide {} {hidden}", said.id)); + Ok(()) + } } struct Model(Judged); @@ -2333,7 +2515,8 @@ mod tests { 1, "{log:?}" ); - assert_eq!(log.iter().filter(|l| l.starts_with("edit")).count(), 2); + // Nothing changed: nothing is rewritten either. + assert_eq!(log.iter().filter(|l| l.starts_with("edit")).count(), 0); } #[tokio::test] @@ -2357,7 +2540,7 @@ mod tests { let out = speak( &ch, Some(&quiet), - &Say::status("run", "Pushed the docs change to #52."), + &Say::reply("run", "Pushed the docs change to #52.", Vec::new()), T0 + 20, ) .await @@ -2391,7 +2574,7 @@ mod tests { speak( &ch2, Some(&good), - &Say::status("run", "Pushed the docs change to #52."), + &Say::reply("run", "Pushed the docs change to #52.", Vec::new()), T0 + 20, ) .await @@ -2403,4 +2586,135 @@ mod tests { "{l:?}" ); } + + /// The deploy and outside-work comments a pull request got, with generic + /// names, as CoderHelm's own status comments on the thread. + fn spammed_thread() -> View { + let deploy = Said { + body: crate::comment_style::tests_fixtures::DEPLOY_BEFORE.to_string(), + ..said("500", "release_steps", "x", T0) + }; + let outside = Said { + body: crate::comment_style::tests_fixtures::OUTSIDE_BEFORE.to_string(), + ..said("501", "also_outside", "y", T0 + 1_000) + }; + View { + said: vec![deploy, outside], + heard: vec![], + } + } + + #[tokio::test] + async fn the_spammed_pull_request_ends_with_one_short_comment() { + let ch = Fake { + view: std::sync::Mutex::new(spammed_thread()), + log: Default::default(), + }; + // The outside-work status again: its only person items are testing, + // which is CoderHelm's own work, and the rest is plan status. + let out = speak( + &ch, + None, + &Say::status( + "also_outside", + crate::comment_style::tests_fixtures::OUTSIDE_BEFORE, + ), + T0 + 5_000, + ) + .await + .unwrap(); + let log = ch.log.lock().unwrap().clone(); + assert!(!log.iter().any(|l| l.starts_with("create")), "{log:?}"); + // The live comment now says nothing is needed and is hidden; the + // older one is folded and hidden; nothing is deleted. + assert!( + matches!(out, Spoke::Edited(ref id) if id == "501"), + "{out:?}" + ); + assert!(log.contains(&format!("edit 501: {NOTHING_NOW}")), "{log:?}"); + assert!(log.contains(&format!("edit 500: {FOLD_LINE}")), "{log:?}"); + assert!(log.contains(&"hide 500 true".to_string()), "{log:?}"); + assert!(log.contains(&"hide 501 true".to_string()), "{log:?}"); + // A later status for nobody writes nothing more. + let n = log.len(); + let out = speak( + &ch, + None, + &Say::status("run", "Working on it.").for_nobody(), + T0 + 6_000, + ) + .await + .unwrap(); + assert!(matches!(out, Spoke::Quiet(_)), "{out:?}"); + assert_eq!(ch.log.lock().unwrap().len(), n); + } + + #[tokio::test] + async fn a_real_person_item_is_one_short_line_in_the_one_comment() { + let ch = Fake { + view: std::sync::Mutex::new(spammed_thread()), + log: Default::default(), + }; + let body = "Done outside the code: Open the PR ready for review.\nCoderHelm does the other 4 step(s) itself.\n**Needed from you:** One paid registration on real devices. CoderHelm cannot: No real devices or payment method. (QA)"; + speak(&ch, None, &Say::status("also_outside", body), T0 + 5_000) + .await + .unwrap(); + let log = ch.log.lock().unwrap().clone(); + let edit = log.iter().find(|l| l.starts_with("edit 501:")).unwrap(); + let text = edit.trim_start_matches("edit 501: "); + assert!(crate::comment_style::lint(text).is_empty(), "{text}"); + assert_eq!(text.lines().count(), 1, "{text}"); + assert!( + text.contains("One paid registration on real devices"), + "{text}" + ); + assert!(!log.iter().any(|l| l.starts_with("create")), "{log:?}"); + assert!(!log.contains(&"hide 501 true".to_string()), "{log:?}"); + } + + #[test] + fn a_status_for_nobody_is_never_posted() { + let d = decide( + &View::default(), + &Say::status("run", "Working on it: planning.").for_nobody(), + &gh(), + T0, + ); + assert!(matches!(d, Decision::Quiet { .. }), "{d:?}"); + // Text the style empties (plan status only) is status for nobody too. + let d = decide( + &View::default(), + &Say::status( + "release_steps", + crate::comment_style::tests_fixtures::DEPLOY_BEFORE, + ), + &gh(), + T0, + ); + assert!(matches!(d, Decision::Quiet { .. }), "{d:?}"); + } + + #[test] + fn every_written_comment_keeps_the_style() { + let long = (1..=12) + .map(|i| format!("- Line {i} with some words in it for the reader.")) + .collect::>() + .join("\n"); + for d in [ + decide(&View::default(), &Say::status("run", &long), &gh(), T0), + decide( + &View::default(), + &Say::status("run", "Took 3 attempt(s)."), + &gh(), + T0, + ), + ] { + match style_decision(d, &gh()) { + Decision::Post { body, .. } => { + assert!(crate::comment_style::lint(&body).is_empty(), "{body}") + } + other => panic!("{other:?}"), + } + } + } } diff --git a/services/common/src/conversation_io.rs b/services/common/src/conversation_io.rs index ac468c74e..4037d652d 100644 --- a/services/common/src/conversation_io.rs +++ b/services/common/src/conversation_io.rs @@ -48,6 +48,7 @@ pub fn view_from_github(comments: &[Value]) -> View { at_ms: at, meta, body: conversation::strip_marker(body), + node_id: c["node_id"].as_str().unwrap_or("").to_string(), }); } continue; @@ -143,6 +144,7 @@ impl JiraChannel<'_> { meta: meta.clone(), // Kept short: enough to rewrite a question as answered. body: crate::truncate_str(body, 4_000).to_string(), + node_id: String::new(), }); let drop = said.len().saturating_sub(conversation::MAX_SAID); said.drain(..drop); @@ -382,6 +384,36 @@ impl GithubRest<'_> { } } +/// GitHub's GraphQL request that hides a comment as outdated +/// (`minimizeComment`, classifier OUTDATED) or shows it again +/// (`unminimizeComment`). Only CoderHelm's own comments are ever passed. +pub fn hide_request(node_id: &str, hidden: bool) -> Value { + if hidden { + json!({ + "query": "mutation($id: ID!) { minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) { minimizedComment { isMinimized } } }", + "variables": { "id": node_id }, + }) + } else { + json!({ + "query": "mutation($id: ID!) { unminimizeComment(input: {subjectId: $id}) { unminimizedComment { isMinimized } } }", + "variables": { "id": node_id }, + }) + } +} + +/// The error in a GraphQL answer, when it has one. +pub fn graphql_error(v: &Value) -> Option { + v["errors"] + .as_array() + .filter(|e| !e.is_empty()) + .map(|errs| { + errs.iter() + .filter_map(|e| e["message"].as_str()) + .collect::>() + .join("; ") + }) +} + fn id_of(v: &Value) -> String { match &v["id"] { Value::Number(n) => n.to_string(), @@ -461,6 +493,20 @@ impl Channel for GithubRest<'_> { .await?; Ok(id.to_string()) } + + async fn hide(&self, said: &Said, hidden: bool) -> Result<(), String> { + if said.node_id.is_empty() { + return Err("no node id for the comment".into()); + } + let v = self + .call( + self.http + .post("https://api.github.com/graphql") + .json(&hide_request(&said.node_id, hidden)), + ) + .await?; + graphql_error(&v).map_or(Ok(()), Err) + } } #[cfg(test)] diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e42b58ffb..07ce9a481 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -190,6 +190,9 @@ pub mod pr_steps; pub mod pr_template; pub mod run_prs; // review_stats: time-ordered review records for analytics +/// How a comment reads: the renderer and lint every comment passes before +/// it is posted (short, plain, no pasted plans, no history). +pub mod comment_style; /// What people write on a ticket while a run works on it: kept, acknowledged, acted on. /// One engineer's voice per ticket and per pull request: every comment /// CoderHelm writes reads the thread first, then stays quiet, edits its own diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index e592bd87e..7d68edfa2 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -460,6 +460,56 @@ fn names_deploy(t: &str) -> bool { any(t, &["deploy", "release to", "publish to production"]) } +/// Whether the item asks a person to test: run a flow or a suite, read an +/// end-to-end result, check a preview in a browser. Testing is CoderHelm's +/// own work, whatever stopped it (a missing permission is an install item, +/// said once in setup checks, never a tester's chore on a pull request). +fn asks_testing(a: &Ask) -> bool { + let t = one_line(&a.text).to_lowercase(); + let t = t + .trim_start_matches("after merging: ") + .trim_start_matches("before merging: ") + .trim_start_matches(['-', '*', ' ']); + let verb = t.split_whitespace().next().unwrap_or(""); + let testing_verb = matches!( + verb, + "run" + | "rerun" + | "re-run" + | "read" + | "check" + | "confirm" + | "verify" + | "test" + | "try" + | "open" + | "watch" + ); + testing_verb + && any( + t, + &[ + "e2e", + "end-to-end", + "end to end", + "chromium", + "webkit", + "firefox", + "safari", + "playwright", + "cypress", + "browser", + "smoke test", + "test result", + "the tests", + "the test suite", + "the spec", + "the flow", + "preview", + ], + ) +} + /// Whether the item's action is adding labels to a pull request. fn adds_labels(a: &Ask) -> bool { let t = one_line(&a.text).to_lowercase(); @@ -854,6 +904,10 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { if adds_labels(a) { return Outcome::Do(Work::Own(one_line(&a.text))); } + // Testing is never a person's item. + if asks_testing(a) { + return Outcome::Do(Work::Own(one_line(&a.text))); + } if a.kind == Kind::Attempt { let cause = one_line(&a.why_not).to_lowercase(); // Refused a workflow start, with a label that starts the same run: @@ -1459,6 +1513,22 @@ pub fn prompt_section() -> String { mod tests { use super::*; + /// Reading an end-to-end result or running a flow in browsers is + /// CoderHelm's work, even when a missing permission stopped it. + #[test] + fn testing_is_never_a_persons_item() { + let text = "**Needed from you:**\n\ +1. Read the Deploy Preview e2e result. CoderHelm could not: CoderHelm's GitHub App is not allowed to start workflows in this repository\n\ +2. Run the sign-up flow inside the frame in a fresh browser context in Chromium and WebKit. CoderHelm could not: CoderHelm's GitHub App is not allowed to start workflows in this repository\n"; + let sunk = sink(text); + assert_eq!(sunk.sent_back.len(), 2, "{sunk:?}"); + assert!(sunk.human.is_empty(), "{sunk:?}"); + assert!(!sunk.text.contains("e2e"), "{}", sunk.text); + // A real person item stays. + let keep = "**Needed from you:**\n1. One paid registration on real devices. CoderHelm cannot: No real devices or payment method. (QA)\n"; + assert_eq!(sink(keep).human.len(), 1, "{:?}", sink(keep)); + } + fn assumption(topic: &str, text: &str) -> Ask { Ask { kind: Kind::Assumption, diff --git a/services/common/src/run_questions.rs b/services/common/src/run_questions.rs index 36398a2b1..37b0d444e 100644 --- a/services/common/src/run_questions.rs +++ b/services/common/src/run_questions.rs @@ -394,38 +394,31 @@ pub fn reply(author: &str, answers: &[Answer], asked_at: Option<&str>, markdown: } else { author.trim() }; + // Short, like every comment: one line saying who answered and where, + // then one line per answer. + let link = asked_at.filter(|u| !u.is_empty()).map(|url| { + if markdown { + format!(" (in reply to [CoderHelm's questions]({url}))") + } else { + format!(" (in reply to CoderHelm's questions: {url})") + } + }); let mut out = if markdown { - format!("**{who} answered in CoderHelm:**\n\n") + format!("**{who} answered in CoderHelm**") } else { - format!("{who} answered in CoderHelm:\n\n") + format!("{who} answered in CoderHelm") }; + out.push_str(&link.unwrap_or_default()); + out.push_str(". CoderHelm is continuing the work with these answers."); for a in answers { + let q = one_line(&a.question); + let ans = one_line(&a.answer); if markdown { - let quoted = a - .question - .lines() - .map(|l| format!("> {l}")) - .collect::>() - .join("\n"); - out.push_str(&format!("{quoted}\n\n{}\n\n", a.answer)); + out.push_str(&format!("\n- {q} {ans}")); } else { - out.push_str(&format!( - "Q: {}\n\nA: {}\n\n", - one_line(&a.question), - a.answer - )); + out.push_str(&format!("\nQ: {q} A: {ans}")); } } - if let Some(url) = asked_at.filter(|u| !u.is_empty()) { - if markdown { - out.push_str(&format!( - "_In reply to [CoderHelm's questions]({url})._\n\n" - )); - } else { - out.push_str(&format!("In reply to CoderHelm's questions: {url}\n\n")); - } - } - out.push_str("CoderHelm is continuing the work with these answers."); out } @@ -905,12 +898,16 @@ mod tests { fn the_reply_names_who_answered() { let a = [answer("Which page?", "The pricing page.")]; let md = reply("Pat Doe", &a, Some("https://example.com/c/1"), true); - assert!(md.starts_with("**Pat Doe answered in CoderHelm:**")); - assert!(md.contains("> Which page?\n\nThe pricing page.")); + assert!(md.starts_with("**Pat Doe answered in CoderHelm**")); + assert!(md.contains("\n- Which page? The pricing page."), "{md}"); assert!(md.contains("(https://example.com/c/1)")); let plain = reply("", &a, None, false); - assert!(plain.starts_with("Someone on the team answered in CoderHelm:")); - assert!(plain.contains("Q: Which page?\n\nA: The pricing page.")); + assert!(plain.starts_with("Someone on the team answered in CoderHelm")); + assert!( + plain.contains("\nQ: Which page? A: The pricing page."), + "{plain}" + ); + assert!(crate::comment_style::lint(&md).is_empty(), "{md}"); assert!(!plain.contains("**")); } diff --git a/services/gateway/src/routes/run_answer.rs b/services/gateway/src/routes/run_answer.rs index e953cc87e..c1216c6e9 100644 --- a/services/gateway/src/routes/run_answer.rs +++ b/services/gateway/src/routes/run_answer.rs @@ -896,9 +896,12 @@ mod tests { assert_eq!(posted.len(), 1); assert_eq!(posted[0]["issueKey"], "ABC-7"); let text = posted[0]["comment"].as_str().unwrap(); - assert!(text.starts_with("Pat Doe answered in CoderHelm:"), "{text}"); + assert!(text.starts_with("Pat Doe answered in CoderHelm"), "{text}"); assert!(text.contains("Q: Which environments get the new limit?")); - assert!(text.contains("A: Production only.\nStaging keeps 100.")); + assert!( + text.contains("A: Production only. Staging keeps 100."), + "{text}" + ); assert!(text.contains("focusedCommentId=10001")); assert!(!text.contains("What is the new limit?")); // And its address is kept on the run. diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index 0922475de..1858a2692 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -201,6 +201,12 @@ pub const OPTIONAL_PERMISSIONS: &[(&str, &str, &str, &str)] = &[ "Code quality", "Without Code quality, reviews don't see GitHub's code quality findings on the changed files.", ), + ( + "actions", + "write", + "Actions", + "Without Actions: write, CoderHelm can't start a workflow itself (a deploy, an end-to-end run): it adds the label that starts one where the workflow has one, and otherwise the step waits.", + ), ]; /// Events a new app subscribes to that CoderHelm works without (security @@ -2884,9 +2890,9 @@ mod tests { fn each_missing_optional_permission_warns_with_the_feature_it_limits() { for (key, need, name, why) in OPTIONAL_PERMISSIONS { let mut a = full(); - if *key == "checks" { + if *key == "checks" || *key == "actions" { // Read is required; only write is optional. - a["permissions"]["checks"] = json!("read"); + a["permissions"][*key] = json!("read"); } else { a["permissions"].as_object_mut().unwrap().remove(*key); } diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 2c2dab564..ade11d8e2 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3446,6 +3446,26 @@ impl GitHubClient { self.get(&url).await } + /// Hides one of CoderHelm's own comments as outdated, or shows it again + /// (`common::conversation_io::hide_request`). Only the conversation + /// layer calls it, for comments that carry CoderHelm's marker. + pub async fn hide_own_comment( + &self, + node_id: &str, + hidden: bool, + ) -> Result<(), Box> { + let v = self + .post( + &format!("{API_BASE}/graphql"), + &common::conversation_io::hide_request(node_id, hidden), + ) + .await?; + match common::conversation_io::graphql_error(&v) { + Some(e) => Err(e.into()), + None => Ok(()), + } + } + /// One GraphQL query, refused unless it only reads. pub async fn graphql_read( &self, diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 90cf6fcbd..522bd2881 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -801,8 +801,15 @@ async fn publish_status( } let mut comment_id = None; if let Some(id) = record.status_comment_id { - match crate::passes::conversation::edit_own(github, owner, repo, id, "merge-status", body) - .await + match crate::passes::conversation::edit_own( + github, + owner, + repo, + msg.pr_number, + "merge-status", + body, + ) + .await { Ok(_) => comment_id = Some(id), Err(e) => { diff --git a/services/worker/src/passes/conversation.rs b/services/worker/src/passes/conversation.rs index dfa990793..abbac2d33 100644 --- a/services/worker/src/passes/conversation.rs +++ b/services/worker/src/passes/conversation.rs @@ -161,6 +161,16 @@ impl Channel for GithubThread<'_> { remember(&self.place().key(), id, meta); Ok(id.to_string()) } + + async fn hide(&self, said: &common::conversation::Said, hidden: bool) -> Result<(), String> { + if said.node_id.is_empty() { + return Err("no node id for the comment".into()); + } + self.gh + .hide_own_comment(&said.node_id, hidden) + .await + .map_err(|e| e.to_string()) + } } /// GitHub's shape of a written comment, for callers that read `id` and @@ -306,51 +316,40 @@ impl Composer for Replier<'_> { } } -/// Rewrites a status comment a pass keeps by its own id (`slot` names it): -/// laid out like every other comment, and marked as CoderHelm's. +/// Updates a status a pass keeps (`slot` names it) on issue or pull request +/// `number`. It goes through the layer like every other status: into the +/// thread's one status comment, edited in place and held to the comment +/// style; a pass's own comment id is never written to directly, so no pass +/// can keep a second status comment beside it. pub async fn edit_own( gh: &GitHubClient, owner: &str, repo: &str, - comment_id: u64, + number: u64, slot: &str, body: &str, ) -> Result { - edit_own_asking(gh, owner, repo, comment_id, slot, body, &[]).await + edit_own_asking(gh, owner, repo, number, slot, body, &[]).await } -/// [`edit_own`] for a comment that asks `asks`. +/// [`edit_own`] for a status that asks `asks`. pub async fn edit_own_asking( gh: &GitHubClient, owner: &str, repo: &str, - comment_id: u64, + number: u64, slot: &str, body: &str, asks: &[String], ) -> Result { - let place = Place::github(owner, repo, 0); - let shaped = conversation::shape(body, place.budget(), true); - let meta = Meta { - slot: slot.to_string(), - fp: conversation::fingerprint(body), - gist: conversation::cut_words(&conversation::visible(body), 160), - first_ms: chrono::Utc::now().timestamp_millis(), - asks: conversation::merge_questions(asks) - .iter() - .map(|q| conversation::cut_words(q, 200)) - .collect(), - ..Default::default() - }; - let v = gh - .edit_issue_comment( - owner, - repo, - comment_id, - &conversation::with_marker(&shaped, &meta), - ) - .await?; - Ok(v) + github( + gh, + owner, + repo, + number, + Say::status(slot, body).asks(asks.to_vec()), + ) + .await } /// What CoderHelm last replied in each review thread (this process), so a @@ -428,6 +427,7 @@ pub fn review_thread( at_ms: at, meta: Meta::default(), body: body.to_string(), + node_id: String::new(), }); } } diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index b206cdf11..15f40dca2 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1165,12 +1165,12 @@ pub(crate) fn rescued_note(workflow: &str, sha: &str, tests: &[String]) -> Strin async fn note_rescued(st: &Store<'_>, gh: &GitHubClient, msg: &TestIngest, run: &Run, pr: u64) { let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); let body = rescued_note(&run.workflow, &run.sha, &run.quarantined_tests); - if let Ok(Some(id)) = st.pr_note(&msg.team_id, &repo, pr).await { + if let Ok(Some(_)) = st.pr_note(&msg.team_id, &repo, pr).await { if crate::passes::conversation::edit_own( gh, &msg.repo_owner, &msg.repo_name, - id, + pr, "e2e-rescued", &body, ) diff --git a/services/worker/src/passes/health_check.rs b/services/worker/src/passes/health_check.rs index 27461abb0..aeecb2476 100644 --- a/services/worker/src/passes/health_check.rs +++ b/services/worker/src/passes/health_check.rs @@ -986,12 +986,12 @@ async fn upsert_comment(github: &GitHubClient, msg: &HealthCheckMessage, body: & let res = match existing { // Already says this (an approval wait seen again): nothing to edit. Some((_, true)) => return, - Some((Some(id), false)) => { + Some((Some(_), false)) => { crate::passes::conversation::edit_own( github, &msg.repo_owner, &msg.repo_name, - id, + msg.pr_number, &format!("health:{}", msg.merge_sha), body, ) diff --git a/services/worker/src/passes/incidents/be_one_voice_on_retry.rs b/services/worker/src/passes/incidents/be_one_voice_on_retry.rs index 240960268..271a86300 100644 --- a/services/worker/src/passes/incidents/be_one_voice_on_retry.rs +++ b/services/worker/src/passes/incidents/be_one_voice_on_retry.rs @@ -65,15 +65,14 @@ fn a_retry_with_nothing_new_keeps_the_covered_decision_and_edits_the_comment() { ..Default::default() }, body: note.clone(), + node_id: String::new(), }], heard: vec![], }; + // The comment already says it: nothing is written, no "Retried at". match decide(&view, &earlier, &Place::jira("ABC-12"), T0 + 3_600_000) { - Decision::Edit { id, body, .. } => { - assert_eq!(id, "10001"); - assert!(body.contains("same result"), "{body}"); - } - other => panic!("a retry posted again: {other:?}"), + Decision::Quiet { .. } => {} + other => panic!("a retry wrote again: {other:?}"), } // A person asking for more decides afresh. diff --git a/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs b/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs index cf95d2508..dcc8a3a06 100644 --- a/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs +++ b/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs @@ -346,8 +346,17 @@ fn the_run_does_its_steps_and_asks_once_for_the_release_and_the_device_checkout( ] { assert!(!note.contains(never), "`{never}` in:\n{note}"); } - assert!(note.starts_with("Done outside the code: "), "{note}"); - assert!(note.contains("**Needed from you:**\n1. "), "{note}"); + // Only what a person must do: no pasted plan status, and it keeps the + // comment style once rendered. + assert!(!note.contains("Done outside the code"), "{note}"); + assert!(!note.contains("step(s)"), "{note}"); + assert!(note.starts_with("**Needed from you:**"), "{note}"); + let shown = common::comment_style::render(¬e, true); + assert!( + common::comment_style::lint(&shown).is_empty(), + "{shown}\n{:?}", + common::comment_style::lint(&shown) + ); assert_eq!( person_gate::sink(¬e).sent_back, Vec::::new(), @@ -452,7 +461,7 @@ fn a_tool_failure_is_one_diagnosis_one_report_and_never_a_persons() { fn a_failed_attempt_reaches_a_person_only_for_a_permission_or_a_credential() { let attempt = |why: &str| person_gate::Ask { kind: Kind::Attempt, - text: "Confirm 'Deploy Preview' ran".into(), + text: "Start the release workflow on the merge commit".into(), why_not: why.into(), ..Default::default() }; @@ -473,6 +482,13 @@ fn a_failed_attempt_reaches_a_person_only_for_a_permission_or_a_credential() { &ctx, ); assert!(matches!(refused, Outcome::Human(_)), "{refused:?}"); + // Testing stopped by the same refusal is still CoderHelm's: the + // permission is said once in setup checks, never as a tester's chore. + let testing = person_gate::Ask { + text: "Confirm 'Deploy Preview' ran".into(), + ..attempt("CoderHelm's GitHub App is not allowed to start workflows in this repository") + }; + assert_eq!(person_gate::decide(&testing, &ctx).class(), Class::Do); // A step that names a workflow called "Deploy ..." is not a deploy. let read = person_gate::Ask { kind: Kind::Step, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 60ce9fec3..c8bc38aa5 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -2052,18 +2052,20 @@ async fn run_passes( msg.team_instructions = load_team_instructions(state, &msg.team_id, &msg.repo_owner, &msg.repo_name).await; - // Post "working on it" comment only for GitHub-sourced tickets. + // Progress is status for nobody: it is on the run page, never a comment + // (the layer drops a "run" status an earlier attempt left on the issue). let mut progress_comment_id: Option = None; if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - let resp = crate::passes::conversation::github( + crate::passes::conversation::github( &github, &msg.repo_owner, &msg.repo_name, msg.issue_number, - common::conversation::Say::status("run", format_progress("triage", run_id)), + common::conversation::Say::status("run", format_progress("triage", run_id)) + .for_nobody(), ) .await?; - progress_comment_id = resp["id"].as_u64(); + progress_comment_id = Some(msg.issue_number); } // The ticket's history with CoderHelm: earlier runs, how their PRs @@ -9038,8 +9040,10 @@ async fn report_also_outside( if let Some(c) = decision.outside_change.as_ref() { person_gate::record_counts(state, &msg.team_id, run_id, &outside_work::counts(c)).await; } - // The ticket gets the short note (what was done, the one thing needed); - // the full report stays on the run page and the pull request. + // The ticket gets only what a person must do; with nothing for anyone + // the comment says nothing (the conversation layer drops it from the + // status comment), and the full report stays on the run page and the + // pull request. let ticket = decision .outside_change .as_ref() @@ -9293,7 +9297,7 @@ async fn post_ticket_notice( github, &msg.repo_owner, &msg.repo_name, - earlier.comment_id, + msg.issue_number, key, github_body, asks, @@ -12556,21 +12560,21 @@ fn format_progress(current_phase: &str, run_id: &str) -> String { ) } -/// Update the progress comment on the GitHub issue. +/// Progress on a GitHub issue (`issue`): status for nobody, so the layer +/// keeps it off the thread (and drops an earlier one). async fn update_progress_comment( github: &crate::clients::github::GitHubClient, owner: &str, repo: &str, - comment_id: Option, + issue: Option, phase: &str, run_id: &str, ) { - if let Some(cid) = comment_id { - let body = format_progress(phase, run_id); - if let Err(e) = - crate::passes::conversation::edit_own(github, owner, repo, cid, "run", &body).await - { - tracing::warn!(error = %e, "Failed to update progress comment"); + if let Some(n) = issue { + let say = + common::conversation::Say::status("run", format_progress(phase, run_id)).for_nobody(); + if let Err(e) = crate::passes::conversation::github(github, owner, repo, n, say).await { + tracing::warn!(error = %e, "Failed to update progress on the issue"); } } } diff --git a/services/worker/src/passes/outside_exec.rs b/services/worker/src/passes/outside_exec.rs index 2ea547e46..78d5f6492 100644 --- a/services/worker/src/passes/outside_exec.rs +++ b/services/worker/src/passes/outside_exec.rs @@ -1137,7 +1137,15 @@ async fn runs_step( } else { format!("{} was skipped", v.skipped.join(", ")) }; - match a.e2e.iter().find(|r| r.startable()).cloned() { + // A route its label starts first: adding a label needs only the pull + // request write the app has, never Actions: write. + match a + .e2e + .iter() + .filter(|r| r.startable()) + .min_by_key(|r| !matches!(r.trigger, outside_work::Trigger::Label(_))) + .cloned() + { Some(r) => { let label = match &r.trigger { outside_work::Trigger::Label(l) => Some(l.clone()), diff --git a/services/worker/src/passes/outside_work.rs b/services/worker/src/passes/outside_work.rs index f271fbc0d..97eb00cce 100644 --- a/services/worker/src/passes/outside_work.rs +++ b/services/worker/src/passes/outside_work.rs @@ -1990,70 +1990,25 @@ pub fn note_markdown(c: &OutsideChange) -> String { out } -/// The ticket's comment for the outside work, in the plain style: what -/// CoderHelm did, what it does next, and the one thing needed from a person -/// (if any). The full report (every step, its evidence) is on the run page -/// and the pull request, never dumped into the ticket. +/// The ticket's comment for the outside work: only what a person must do, +/// one line each (who, what, why), or nothing when nobody has to act. What +/// CoderHelm did and does next is status for nobody: it stays on the run +/// page and in the pull request description, never pasted into a comment +/// ("Done outside the code: ...", "CoderHelm does the other N steps"). pub fn ticket_note(c: &OutsideChange) -> String { let steps = steps_now(c, c.placed.is_some()); - let done: Vec = steps - .iter() - .filter(|s| matches!(s.state, State::Done { .. })) - .map(|s| short(&s.what)) - .collect(); let needed = pr_steps::needed(&steps); - let approvals: Vec<&Step> = steps - .iter() - .filter(|s| matches!(s.state, State::Approval { .. })) - .collect(); - let next = steps - .iter() - .filter(|s| { - matches!(s.state, State::Waiting { .. } | State::Failed { .. }) && !s.needs_person() - }) - .count(); - let mut out = String::new(); - if !done.is_empty() { - out.push_str(&format!("Done outside the code: {}.\n", done.join("; "))); - } - if next > 0 || !approvals.is_empty() { - out.push_str(&format!( - "CoderHelm does the other {} step(s) itself{}.\n", - next, - if approvals.is_empty() { - String::new() - } else { - "; the production release waits for one approval after the merge".to_string() - } - )); - } - // An approval the release waits on is one of these, said once. - let asks = needed; - match asks.len() { - 0 => out.push_str(&format!( - "**Needed from you:** {}\n", - pr_steps::NOTHING_NEEDED - )), - 1 => out.push_str(&format!("**Needed from you:** {}\n", asks[0])), + match needed.len() { + 0 => String::new(), + 1 => format!("**Needed from you:** {}\n", needed[0]), _ => { - out.push_str("**Needed from you:**\n"); - for (i, a) in asks.iter().enumerate() { - out.push_str(&format!("{}. {a}\n", i + 1)); + let mut out = String::from("**Needed from you:**\n"); + for a in &needed { + out.push_str(&format!("- {a}\n")); } + out } } - out -} - -fn sentence(s: &str) -> String { - one_line(s).trim_end_matches(['.', ';']).to_string() -} - -fn short(s: &str) -> String { - let t = sentence(s); - let t = t.split(" (").next().unwrap_or(&t).to_string(); - let t = t.split(", then").next().unwrap_or(&t).to_string(); - common::truncate_str(&t, 90).to_string() } // ── Requirements a person holds, for the plan check ───────────────────────── diff --git a/services/worker/src/passes/person_gate.rs b/services/worker/src/passes/person_gate.rs index 60ae813ca..29edc30cd 100644 --- a/services/worker/src/passes/person_gate.rs +++ b/services/worker/src/passes/person_gate.rs @@ -230,6 +230,8 @@ mod tests { ("src/passes/settle.rs", "person_gate::decide"), // The ticket and the pull request's note for outside work. ("src/passes/outside_work.rs", "needed("), + // A release step only a person can unblock. + ("src/passes/release_run.rs", "person_gate::sink("), // Questions put to a person before a run stops. ("../common/src/stop_rules/screen.rs", "person_gate::"), // The judge's assumptions. @@ -258,6 +260,9 @@ mod tests { "fix_location.rs", "proof.rs", "person_gate.rs", + // Lays out text the gate already passed (and names the words in its + // checks). + "comment_style.rs", ]; fn rs_files(dir: &std::path::Path, out: &mut Vec) { diff --git a/services/worker/src/passes/release_plan.rs b/services/worker/src/passes/release_plan.rs index 6e8c2be64..f1027831b 100644 --- a/services/worker/src/passes/release_plan.rs +++ b/services/worker/src/passes/release_plan.rs @@ -1926,15 +1926,20 @@ fn gate_words(tool: &str) -> &'static str { /// The release lines, numbered, for the ticket note and the PR. pub fn note_lines(r: &Release, steps: &[Step], m: &Mechanics) -> Vec { let mut out = Vec::new(); - if !m.deploys.is_empty() { - out.push(format!( - "How it deploys: {}.", - m.deploys + // Only the deploys this release waits on: a repository's other deploy + // workflows (another service, another app) are not this change's. + let relevant: Vec = m + .deploys + .iter() + .filter(|d| { + steps .iter() - .map(Deploy::line) - .collect::>() - .join("; ") - )); + .any(|s| !s.workflow.is_empty() && s.workflow == d.file) + }) + .map(Deploy::line) + .collect(); + if !relevant.is_empty() { + out.push(format!("How it deploys: {}.", relevant.join("; "))); } for i in &r.impact { let env = i diff --git a/services/worker/src/passes/release_run.rs b/services/worker/src/passes/release_run.rs index ea75de802..fdb5d845a 100644 --- a/services/worker/src/passes/release_run.rs +++ b/services/worker/src/passes/release_run.rs @@ -95,6 +95,24 @@ impl Record { } } +/// The release steps a person must unblock (no workflow deploys an +/// environment, ...), one line each: what, and the grant that lifts it. +pub fn person_lines(steps: &[Step]) -> Vec { + steps + .iter() + .filter(|s| s.status == Status::NoAccess) + .map(|s| { + let what = s.what.split_whitespace().collect::>().join(" "); + let why = s.detail.split_whitespace().collect::>().join(" "); + format!( + "- {}: {}.", + what.trim_end_matches('.'), + why.trim_end_matches('.') + ) + }) + .collect() +} + fn record_sk(owner: &str, repo: &str, pr: u64) -> String { format!("RELEASE#{owner}/{repo}#{pr:06}") } @@ -293,38 +311,42 @@ pub async fn after_pr( if planned.steps.is_empty() { return; } - let lines = planned.lines(); - let body = lines - .iter() - .map(|l| { - if l.starts_with(|c: char| c.is_ascii_digit()) { - l.clone() - } else { - format!("- {l}") - } - }) - .collect::>() - .join("\n"); let title = "Release steps (done by CoderHelm)"; super::add_progress_note( state, &msg.team_id, run_id, - &format!("{title}: {} step(s) armed", planned.steps.len()), - ) - .await; - super::post_ticket_notice( - state, - msg, - run_id, - github, - NOTICE_RELEASE, - &format!("**{title}**\n\n{body}"), - &super::fix_location::jira_text(&body), - title, - &[], + &format!( + "{title}: {} {} armed (listed in the pull request description)", + planned.steps.len(), + if planned.steps.len() == 1 { + "step" + } else { + "steps" + } + ), ) .await; + // The steps are CoderHelm's own work: they live in the description and + // on the run page. Only a step nobody can do until a person grants + // something is said on the ticket, one line each. + let asks = person_lines(&planned.steps); + let sunk = common::person_gate::sink(&format!("**Needed from you:**\n{}", asks.join("\n"))); + if !asks.is_empty() && !sunk.human.is_empty() { + let body = sunk.text; + super::post_ticket_notice( + state, + msg, + run_id, + github, + NOTICE_RELEASE, + &body, + &super::fix_location::jira_text(&body), + title, + &[], + ) + .await; + } arm( state, &msg.team_id, diff --git a/services/worker/src/passes/reply_eval.rs b/services/worker/src/passes/reply_eval.rs index b286ebde0..3fdf4ebe5 100644 --- a/services/worker/src/passes/reply_eval.rs +++ b/services/worker/src/passes/reply_eval.rs @@ -174,6 +174,7 @@ fn said(id: &str, slot: &str, body: &str, asks: &[&str], at_ms: i64) -> Said { ..Default::default() }, body: body.into(), + node_id: String::new(), } } diff --git a/services/worker/src/passes/ticket_comments.rs b/services/worker/src/passes/ticket_comments.rs index fc3dfd2db..47ce8bdbb 100644 --- a/services/worker/src/passes/ticket_comments.rs +++ b/services/worker/src/passes/ticket_comments.rs @@ -1018,6 +1018,7 @@ mod tests { ..Default::default() }, body: String::new(), + node_id: String::new(), }]; let mut reply = comment("2", "Yes.", Class::Instruction); reply.class = None;