Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/incidents/wx_texts_say_what_happened.md
Original file line number Diff line number Diff line change
@@ -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.
32 changes: 30 additions & 2 deletions lambda/stuck-run-cleanup/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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 = (
Expand Down
15 changes: 15 additions & 0 deletions lambda/tests/test_stuck_run_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion services/common/src/comment_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)") {
Expand Down
3 changes: 2 additions & 1 deletion services/common/src/draft_hold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ pub struct Reason {

fn one_line(s: &str, max: usize) -> String {
let s = s.split_whitespace().collect::<Vec<_>>().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 {
Expand Down
14 changes: 4 additions & 10 deletions services/common/src/git_conventions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down
210 changes: 210 additions & 0 deletions services/common/src/rendered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -91,10 +97,214 @@ pub fn empty_slot(text: &str) -> Option<String> {
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<Regex> =
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<Regex> =
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<String> {
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::<Vec<_>>()
.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(
Expand Down
3 changes: 1 addition & 2 deletions services/common/src/review_activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 1 addition & 2 deletions services/common/src/review_overview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 1 addition & 5 deletions services/common/src/review_supersede.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,11 +459,7 @@ fn first_line(body: &str) -> String {
.find(|l| !l.is_empty() && !l.starts_with("<!--"))
.unwrap_or("");
let line = line.trim_matches('*').trim();
if line.chars().count() <= 140 {
return line.to_string();
}
let cut: String = line.chars().take(139).collect();
format!("{}…", cut.trim_end())
crate::rendered::clip(line, 140)
}

/// What brings the full review a carry rests on back in sight, when an
Expand Down
Loading