From 05fa80a7ffc8b6702999002347de32d99961701b Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 14:14:36 -0500 Subject: [PATCH] Statuses say what happened and hand a person only what only a person can do A pull request CoderHelm marks ready itself no longer tells a person to mark it ready; a draft GitHub keeps refusing says CoderHelm tries again, and its waiting line no longer waits on a person. A wait on a pull request drops an API error's JSON body. Reminders are sentences, the plan check note drops the planner's key, notes write plurals out, and text cut to fit is cut at a word. common::rendered::person_text holds these texts in tests; incident case wx_texts_say_what_happened. --- docs/incidents/wx_texts_say_what_happened.md | 5 + lambda/stuck-run-cleanup/handler.py | 32 ++- lambda/tests/test_stuck_run_cleanup.py | 15 ++ services/common/src/comment_style.rs | 2 +- services/common/src/draft_hold.rs | 3 +- services/common/src/git_conventions.rs | 14 +- services/common/src/rendered.rs | 210 ++++++++++++++++++ services/common/src/review_activity.rs | 3 +- services/common/src/review_overview.rs | 3 +- services/common/src/review_supersede.rs | 6 +- services/common/src/run_wait.rs | 31 ++- services/common/src/waiting_line.rs | 9 +- services/gateway/src/routes/chat_work.rs | 7 +- services/gateway/src/routes/run_activity.rs | 6 +- .../src/passes/incidents/s_silent_draft.rs | 5 +- .../incidents/wx_texts_say_what_happened.rs | 148 ++++++++++++ services/worker/src/passes/log_evidence.rs | 4 +- services/worker/src/passes/mod.rs | 9 + services/worker/src/passes/plan.rs | 13 +- services/worker/src/passes/plan_judge.rs | 10 + services/worker/src/passes/ready.rs | 21 +- services/worker/src/passes/webhooks.rs | 9 +- 22 files changed, 504 insertions(+), 61 deletions(-) create mode 100644 docs/incidents/wx_texts_say_what_happened.md create mode 100644 services/worker/src/passes/incidents/wx_texts_say_what_happened.rs diff --git a/docs/incidents/wx_texts_say_what_happened.md b/docs/incidents/wx_texts_say_what_happened.md new file mode 100644 index 000000000..efae27159 --- /dev/null +++ b/docs/incidents/wx_texts_say_what_happened.md @@ -0,0 +1,5 @@ +# wx. `wx_texts_say_what_happened` + +**What happened:** A sweep of what CoderHelm had shown people on one install found the same kinds of words again and again. A pull request CoderHelm meant to mark ready itself said "or mark it ready yourself". One that GitHub kept refusing to take out of draft told a person to mark it ready on GitHub while CoderHelm was already trying again on its own, and the run's waiting line said it waited on a person. A wait on a pull request pasted GitHub's raw error body, JSON and all, and ended with "Mark it ready once that is dealt with". Reminders ran four clauses together with colons. A plan check note showed the planner's internal key in brackets. Notes said "1 lookups answered" and "3 file(s)". Pull request titles, review headings and file notes were cut in the middle of a word. + +**The guarantee:** A status a person reads says what happened and what CoderHelm does next, and hands a person only what only a person can do; tests hold those texts to one check (`common::rendered::person_text`). Text cut to fit is cut at a word and ends in "…". An API error's JSON never reaches a reader. Every progress note writes its plurals out. diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index ef5077c2d..d8ad85a70 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -169,6 +169,32 @@ def _cut(text): return text if len(text) <= REASON_CHARS else text[: REASON_CHARS - 1].rstrip() + "…" +def without_json(text): + """`text` with any raw JSON object or array taken out, as + common::rendered::without_json does: an API error's body never reaches + the reader. A bracket holding no `"key":` is prose and is kept.""" + out, span, depth = [], [], 0 + for c in str(text or ""): + if depth == 0 and c not in "{[": + out.append(c) + continue + if c in "{[": + depth += 1 + elif c in "}]": + depth = max(0, depth - 1) + span.append(c) + if depth == 0: + chunk = "".join(span) + if '":' not in chunk: + out.append(chunk) + span = [] + chunk = "".join(span) + if '":' not in chunk: + out.append(chunk) + joined = " ".join("".join(out).split()).replace(" .", ".").replace(" ,", ",") + return joined.replace(":.", ".").replace(",.", ".").strip().rstrip(":,; ") + + def outside_change_reason(report): """The headline and finding of a run's outside-change report (markdown: a bold headline, then "**What I found:** ..."), as one line.""" @@ -225,9 +251,11 @@ def named_wait(run, now_iso): number = 0 action = f"Review pull request #{number}" if number > 0 else "Review the pull request" if reason: + # An API error's JSON body is no reading for a person, and the + # pull request's draft state is CoderHelm's to change. detail = ( - f"Open on the pull request: {reason.rstrip('.')}. Mark it ready once that is dealt " - "with, push a fix or comment on it, and CoderHelm picks it up from there." + f"Open on the pull request: {without_json(reason).rstrip('.')}. Push a fix or " + "comment on it, and CoderHelm picks it up from there." ) else: detail = ( diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index d32235242..1b4b17923 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -419,6 +419,21 @@ def test_without_a_pull_request_it_waits_for_a_retry(self): "**What I checked**\n- [code] read settings.ts" ) + def test_a_pull_request_wait_hands_nothing_back_and_shows_no_json(self): + run = { + "pr_number": "12", + "pr_url": "https://github.com/acme/bookstore/pull/12", + "error_message": 'GitHub refused the pull request: Validation Failed: {"message":"Validation Failed","errors":[{"field":"title"}],"status":"422"}.', + } + detail = sweep.named_wait(run, "now")["detail"] + self.assertEqual( + detail, + "Open on the pull request: GitHub refused the pull request: Validation Failed. " + "Push a fix or comment on it, and CoderHelm picks it up from there.", + ) + self.assertNotIn("Mark it ready", detail) + self.assertNotIn('"', detail) + def test_the_reason_is_read_from_the_last_stop_note(self): wait = sweep.named_wait({"progress_notes": self.NOTES}, "now") self.assertEqual( diff --git a/services/common/src/comment_style.rs b/services/common/src/comment_style.rs index 421adbac9..944f82f21 100644 --- a/services/common/src/comment_style.rs +++ b/services/common/src/comment_style.rs @@ -291,7 +291,7 @@ fn bare_heading(l: &str) -> bool { /// Writes out "step(s)": "1 step(s)" is "1 step", any other count (or none) /// "steps". -fn fix_plurals(line: &str) -> String { +pub fn fix_plurals(line: &str) -> String { let mut out = String::new(); let mut rest = line; while let Some(i) = rest.find("(s)") { diff --git a/services/common/src/draft_hold.rs b/services/common/src/draft_hold.rs index 5f0bf1aff..eb81dae6c 100644 --- a/services/common/src/draft_hold.rs +++ b/services/common/src/draft_hold.rs @@ -72,7 +72,8 @@ pub struct Reason { fn one_line(s: &str, max: usize) -> String { let s = s.split_whitespace().collect::>().join(" "); - crate::truncate_str(&s, max).to_string() + // Cut at a word, with "…", never mid-word with nothing to say so. + crate::rendered::clip_bytes(&s, max) } impl Reason { diff --git a/services/common/src/git_conventions.rs b/services/common/src/git_conventions.rs index ec5d627a9..da6f5f779 100644 --- a/services/common/src/git_conventions.rs +++ b/services/common/src/git_conventions.rs @@ -35,7 +35,7 @@ pub const MAX_TEMPLATE_CHARS: usize = 120; pub const MAX_BRANCH_CHARS: usize = 100; /// Longest commit subject line produced. pub const MAX_COMMIT_CHARS: usize = 72; -/// Longest PR title produced (longer ones end in "..."). +/// Longest PR title produced (longer ones are cut at a word, ending in "…"). pub const MAX_PR_TITLE_CHARS: usize = 72; /// Longest `{slug}`. pub const MAX_SLUG_CHARS: usize = 40; @@ -708,16 +708,10 @@ pub fn commit(template: &str, tokens: &Tokens) -> String { } /// The PR title for `template`: one line; past [`MAX_PR_TITLE_CHARS`] it is -/// cut and ends in "...". +/// cut at a word and ends in "…", never in the middle of a word. pub fn pr_title(template: &str, tokens: &Tokens) -> String { let line = render(template, tokens, |v| v.replace(['\n', '\r'], " ")); - let line = line.trim(); - if line.chars().count() > MAX_PR_TITLE_CHARS { - let head: String = line.chars().take(MAX_PR_TITLE_CHARS - 3).collect(); - format!("{}...", head.trim_end()) - } else { - line.to_string() - } + crate::rendered::clip(&line, MAX_PR_TITLE_CHARS) } /// Whether `name` is a valid git branch name (the rules of @@ -928,7 +922,7 @@ mod tests { assert!(c.starts_with("ABC-1: word word")); let p = pr_title("{ticket}: {title}", &t); assert_eq!(p.chars().count(), MAX_PR_TITLE_CHARS.min(p.chars().count())); - assert!(p.ends_with("...")); + assert!(p.ends_with("word…"), "{p}"); } #[test] diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index 35befab53..2b8a8fda1 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -5,6 +5,12 @@ //! status a review shows (its comments, its check, its session) is held to //! [`empty_slot`] in tests, and a reply a model rewrote that fails it falls //! back to the text CoderHelm wrote (`reply_compose::finish`). +//! +//! A status a person reads is also held to [`person_text`]: it never hands +//! them work CoderHelm does itself ("mark it ready yourself", "press +//! Resume"), never shows an internal key or a template plural, and never +//! runs clauses together. Text cut to fit is cut at a word ([`clip`]), and +//! an API error's JSON body never reaches the reader ([`without_json`]). use std::sync::LazyLock; @@ -91,10 +97,214 @@ pub fn empty_slot(text: &str) -> Option { None } +/// Work handed to a person that CoderHelm does itself, or that names no +/// one action: "mark it ready yourself", "press Resume", "follow the +/// runbook". Each pattern is matched on the prose, case-insensitively. +const HANDOFFS: &[(&str, &str)] = &[ + ("yourself", "asks a person to do it themselves"), + ("press resume", "CoderHelm resumes its own work"), + ("then press retry", "a retry CoderHelm can start itself"), + ( + "mark it ready once", + "CoderHelm marks its own pull requests ready", + ), + ("re-review", "CoderHelm reviews a new head by itself"), + ("follow the runbook", "names no one action"), + ("update link", "a link the reader has to find"), + ("set the repo and re-run", "names no place to do it"), +]; + +/// A raw internal name a reader can't use: a bracketed snake_case key +/// ("[cursor_readers] ..."). +static BRACKET_KEY: LazyLock = + LazyLock::new(|| Regex::new(r"\[[a-z]+(?:_[a-z0-9]+)+\]").expect("regex")); + +/// Several "for: x: y: z" clauses run together in one line. +static RUN_ON: LazyLock = + LazyLock::new(|| Regex::new(r"[^:\n]{1,80}: [^:\n]{1,200}: [^:\n]{1,200}: ").expect("regex")); + +/// What in `text` a person shouldn't be shown, or `None`: an empty slot +/// ([`empty_slot`]), a hand-off of work CoderHelm does itself, a template +/// plural ("file(s)"), a bracketed internal key, or clauses run together +/// with colons. Code spans are taken out first, so a command or a name in +/// backticks never trips it. +pub fn person_text(text: &str) -> Option { + if let Some(gap) = empty_slot(text) { + return Some(gap); + } + for line in prose(text) { + let body = line.trim(); + if body.is_empty() { + continue; + } + let low = body.to_lowercase(); + for (p, why) in HANDOFFS { + if low.contains(p) { + return Some(format!("a hand-off (\"{p}\": {why}): {body}")); + } + } + if body.contains("(s)") { + return Some(format!("a template plural: {body}")); + } + if let Some(m) = BRACKET_KEY.find(body) { + return Some(format!("an internal key ({}): {body}", m.as_str())); + } + if RUN_ON.is_match(body) { + return Some(format!("clauses run together with colons: {body}")); + } + } + None +} + +/// `text` cut to at most `max` characters at a word boundary, ending in +/// "…" when anything was cut: never "chec..." for a word cut in half. +/// A single word longer than `max` is cut at `max - 1` characters. +pub fn clip(text: &str, max: usize) -> String { + let text = text.trim(); + if text.chars().count() <= max { + return text.to_string(); + } + let room = max.saturating_sub(1); + let at = text.char_indices().nth(room).map_or(text.len(), |(i, _)| i); + at_word(text, at) +} + +/// [`clip`] for a field bounded in bytes: at most `max` bytes, "…" +/// included, cut at a word boundary on a char boundary. +pub fn clip_bytes(text: &str, max: usize) -> String { + let text = text.trim(); + if text.len() <= max { + return text.to_string(); + } + let at = crate::truncate_str(text, max.saturating_sub('…'.len_utf8())).len(); + at_word(text, at) +} + +/// `text[..at]` taken back to the last whole word, plus "…". +fn at_word(text: &str, at: usize) -> String { + let head = &text[..at]; + let inside_a_word = text[at..] + .chars() + .next() + .is_some_and(|c| !c.is_whitespace()); + let cut = if inside_a_word { + match head.rfind(char::is_whitespace) { + Some(i) if i > 0 => &head[..i], + _ => head, + } + } else { + head + }; + let cut = cut.trim_end_matches(|c: char| c.is_whitespace() || ",;:-(".contains(c)); + format!("{cut}…") +} + +/// `text` with any raw JSON object or array taken out: an API error such as +/// `Validation Failed: {"message":"...","errors":[...]}` reads as +/// "Validation Failed". Text without JSON is returned as it was. +pub fn without_json(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut depth = 0usize; + let mut span = String::new(); + for c in text.chars() { + if depth == 0 && c != '{' && c != '[' { + out.push(c); + continue; + } + if c == '{' || c == '[' { + depth += 1; + } else if c == '}' || c == ']' { + depth = depth.saturating_sub(1); + } + span.push(c); + if depth == 0 { + // A bracket that holds no `"key":` is prose ("[draft]"): kept. + if !span.contains("\":") { + out.push_str(&span); + } + span.clear(); + } + } + if !span.contains("\":") { + out.push_str(&span); + } + let out = out + .split_whitespace() + .collect::>() + .join(" ") + .replace(" .", ".") + .replace(" ,", ",") + .replace(":.", ".") + .replace(",.", "."); + out.trim() + .trim_end_matches(|c: char| c == ':' || c == ',' || c == ';' || c.is_whitespace()) + .to_string() +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_handoff_or_a_raw_key_is_caught() { + for bad in [ + "Fix them on this branch, or mark it ready yourself if they're fine.", + "Mark it ready once that is dealt with, push a fix or comment on it.", + "The work is saved, and Resume continues from there. Press Resume.", + "Turn ApplyMaintenance on (the account's Update link), or follow the runbook.", + "If the work belongs in a different repo, set the repo and re-run.", + "CoderHelm made 1 fix attempt(s) without getting it green.", + "Plan check: 1 left open: [cursor_readers] The plan changes a column.", + "Reminder: still waiting after 24 hours for: Review it: The checks failed: lint", + ] { + assert!(person_text(bad).is_some(), "{bad}"); + } + for ok in [ + "CoderHelm marks it ready once CI is green and its review approves.", + "A repository admin grants the app Actions: write in GitHub's app settings.", + "Run `npm run deploy -- --yourself` from the repo root.", + "Still waiting after 24 hours. Review pull request #12: the lint check failed.", + "Draft items are listed under [draft] in the description.", + ] { + assert_eq!(person_text(ok), None, "{ok}"); + } + } + + #[test] + fn clipping_never_cuts_a_word() { + let title = "Show the gift wrap option on every order in the checkout summary"; + let c = clip(title, 50); + assert!(c.chars().count() <= 50, "{c}"); + assert!(c.ends_with('…'), "{c}"); + let kept = c.trim_end_matches('…'); + assert!(title.starts_with(kept), "{c}"); + assert!( + title[kept.len()..].starts_with(' '), + "cut inside a word: {c}" + ); + assert_eq!(clip("Short title", 50), "Short title"); + assert_eq!(clip("abcdefghij", 5), "abcd…"); + // A cut right at a space keeps the whole last word. + assert_eq!(clip("one two three", 8), "one two…"); + let b = clip_bytes("café crème brûlée au chocolat", 16); + assert!(b.len() <= 16, "{b}"); + assert_eq!(b, "café crème…"); + } + + #[test] + fn json_in_an_error_is_taken_out() { + let raw = "GitHub refused the pull request: Validation Failed: {\"message\":\"Validation Failed\",\"errors\":[{\"field\":\"title\"}],\"status\":\"422\"}."; + assert_eq!( + without_json(raw), + "GitHub refused the pull request: Validation Failed." + ); + assert_eq!( + without_json("Checks [draft] pending"), + "Checks [draft] pending" + ); + assert_eq!(without_json("plain words"), "plain words"); + } + #[test] fn the_incident_text_is_caught() { assert!(empty_slot( diff --git a/services/common/src/review_activity.rs b/services/common/src/review_activity.rs index 116aba7b5..70d5fae45 100644 --- a/services/common/src/review_activity.rs +++ b/services/common/src/review_activity.rs @@ -73,8 +73,7 @@ pub fn clean(text: &str, max: usize) -> String { if scrubbed.len() <= max { return scrubbed; } - let cut = crate::truncate_str(&scrubbed, max.saturating_sub('…'.len_utf8())); - format!("{}…", cut.trim_end()) + crate::rendered::clip_bytes(&scrubbed, max) } fn str_of<'a>(input: &'a Value, key: &str) -> &'a str { diff --git a/services/common/src/review_overview.rs b/services/common/src/review_overview.rs index de6af5b5f..388078deb 100644 --- a/services/common/src/review_overview.rs +++ b/services/common/src/review_overview.rs @@ -106,8 +106,7 @@ fn line(text: &str, max: usize) -> String { if one.len() <= max { return one; } - let cut = crate::truncate_str(&one, max.saturating_sub('…'.len_utf8())); - format!("{}…", cut.trim_end()) + crate::rendered::clip_bytes(&one, max) } /// Pure: what a file's row says when the model wrote nothing for it. diff --git a/services/common/src/review_supersede.rs b/services/common/src/review_supersede.rs index 28c7f76b2..b6bc2de2f 100644 --- a/services/common/src/review_supersede.rs +++ b/services/common/src/review_supersede.rs @@ -459,11 +459,7 @@ fn first_line(body: &str) -> String { .find(|l| !l.is_empty() && !l.starts_with("