diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 18d2c348e..2c0ad4268 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -6286,7 +6286,7 @@ "detail": { "description": "Why, or what is still open. May be empty.", "examples": [ - "Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there." + "Open on the pull request: the link check couldn't reach /pricing. Push a fix or comment on it, and CoderHelm picks it up from there." ], "type": "string" }, diff --git a/docs/incidents/wz_waits_go_on_by_themselves.md b/docs/incidents/wz_waits_go_on_by_themselves.md new file mode 100644 index 000000000..feb2af3b4 --- /dev/null +++ b/docs/incidents/wz_waits_go_on_by_themselves.md @@ -0,0 +1,5 @@ +# wz. `wz_waits_go_on_by_themselves` + +**What happened:** A second pass over what CoderHelm showed people found texts that still handed people work CoderHelm does, or promised what didn't happen. A run stopped for a person said "Look at what stopped the run, put it right, then press Retry", and a comment on its ticket was only kept as context, so a person's answer left the run waiting. A merged-ticket stop told people to reply on the ticket as if the reply started a run. A wrong-repo note said "set the repo and re-run" without saying where, after a reason cut in the middle of a word. A tests-and-scope note quoted the coding model's instruction ("Put it back with `restore_file` (omit `from_ref`)"). A fix round wrote that it had no tool to edit the pull request's description and that someone had to paste in the new sections. An outside-change report asked a person to add pull request labels CoderHelm adds itself, and to "run the command yourself". The updater said "press Update again" when AWS was busy, and the access check said to delete a failed stack and press Update again. + +**The guarantee:** A run that waits on a person goes on by itself when what it waits for arrives: a comment or reply on its ticket, access granted on GitHub or a repository turned on, or the usage limit raised or reset by a new month. A change it waited for that closed and is reopened takes the run back to waiting, and its merge lets it go on. An answered approval resumes the same run. An alert run resumes when its alert fires again and closes when it clears; its wait says what to do first, then Retry on the run page. Its action names the one thing to do, where, and that the run goes on by itself; only a decision about the run itself (an approval, a person's own stop) waits for that decision. Notes a person reads never carry the coding model's instructions. Every fix round can have the description rebuilt. Pull request labels are CoderHelm's to add. The updater waits out a busy stack or AWS throttling and starts the update again by itself, and a failed stack in another account gets one action for an AWS admin. Tests hold each text to `common::rendered::person_text`. diff --git a/lambda/tests/test_updater_access.py b/lambda/tests/test_updater_access.py index 4d52897b6..cca276059 100644 --- a/lambda/tests/test_updater_access.py +++ b/lambda/tests/test_updater_access.py @@ -706,11 +706,18 @@ def test_a_policy_that_differs_is_never_skipped(self): u.native_poll(self.store, self.env, base.NOW) self.assertEqual(len(self.sent), 1, "told once") - def test_an_update_while_stuck_is_refused_in_words(self): + def test_an_update_while_stuck_waits_and_starts_by_itself(self): + # Not a refusal that asks for another press: the update waits like + # one AWS throttled, and starts by itself once the rollback is done. self.release(json.loads(base.TEMPLATE)) u.fetch_template = lambda url, opener=None: json.dumps(json.loads(base.TEMPLATE)).encode() - with self.assertRaisesRegex(ValueError, "still stuck"): + with self.assertRaises(u.AwsBusy) as busy: u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.assertIn("earlier update's rollback", busy.exception.cause) + self.assertNotIn("press update", busy.exception.cause.lower()) + # Its failure record, if AWS stays busy past the bound, asks nothing. + d = u.explain_failure(busy.exception.cause, "v1.1.0", "v1.0.0", u.PREPARE, retry_at=base.NOW) + self.assertTrue(d["fix"].startswith("Nothing to do: CoderHelm starts it again by itself"), d["fix"]) def test_an_update_whose_rollback_stops_ends_rolled_back_once_recovered(self): self.release(json.loads(base.TEMPLATE)) diff --git a/lambda/tests/test_updater_busy.py b/lambda/tests/test_updater_busy.py index ff15a4288..60bfada55 100644 --- a/lambda/tests/test_updater_busy.py +++ b/lambda/tests/test_updater_busy.py @@ -279,6 +279,37 @@ def test_the_status_route_answers_while_aws_is_busy(self): row = next(h for h in r["history"] if h["id"] == hid) self.assertEqual((row["status"], row["reason"]), ("preparing", "AWS is busy, retrying (attempt 1)")) + def test_a_busy_stack_waits_and_the_update_starts_by_itself(self): + # "AWS is still working on the install's stack; press Update again + # once it has finished": now a wait, tried again by itself. + self.cfn.stack_status = "UPDATE_IN_PROGRESS" + r = u.handle({"action": "update_now", "version": "v1.1.0", "actor": ADMIN}, ROLE_ENV, self.store, NOW, + fetch=lambda repo: [], probe=lambda env, p: {"results": []}) + self.assertEqual(r["request"]["status"], "waiting") + self.assertTrue(no_press(r["request"]["waiting_for"])) + later = NOW + u.BUSY_LIMIT + timedelta(minutes=1) + req = u.follow_request(self.store, ROLE_ENV, later) + row = self.store.get(req["failed_id"]) + self.assertIn("still working on the install's stack", row["summary"]) + self.assertTrue(row["fix"].startswith("Nothing to do: CoderHelm starts it again by itself"), row["fix"]) + self.assertTrue(no_press(row["reason"])) + self.cfn.stack_status = "UPDATE_COMPLETE" + req = u.follow_request(self.store, ROLE_ENV, later + u.BUSY_RETRY_AFTER) + self.assertEqual(req["status"], "started") + + def test_an_update_rolled_back_for_throttling_starts_again_by_itself(self): + hid = self.prepared() + later = NOW + timedelta(minutes=20) + u.native_finish(self.store, ROLE_ENV, later, hid, "rolled_back", + "Resource handler returned message: Rate exceeded (Service: Lambda, Status Code: 429)") + row = self.store.get(hid) + at = later + u.BUSY_RETRY_AFTER + self.assertEqual(row["retry_at"], at.isoformat()) + self.assertEqual(row["fix"], f"Nothing to do: CoderHelm starts it again by itself at {at.strftime('%H:%M')} UTC.") + self.assertTrue(no_press(row["reason"])) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual((req["status"], req["version"], req["failed_id"]), ("waiting", "v1.1.0", hid)) + def test_no_throttling_message_hands_the_retry_to_a_person(self): raw = "ClientError: An error occurred (Throttling) when calling the DescribeChangeSet operation: Rate exceeded" for phase in (u.PREPARE, u.ROLLED_BACK): diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 96e0dd0a7..bb6462a25 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -545,6 +545,27 @@ def busy_why(e): return f"{type(e).__name__}: {str(e)[:250]}" +STACK_BUSY = "AWS is still working on the install's stack" + + +def stack_busy_why(st): + """What a stack that can't take a change yet says, for the update's wait + and its failure record: still working, or finishing an earlier rollback + (which CoderHelm finishes by itself).""" + if st == STUCK: + return f"{STACK_BUSY} ({st}): CoderHelm is finishing an earlier update's rollback by itself" + return f"{STACK_BUSY} ({st})" + + +def busy_text(raw): + """True when `raw` (an error's text) says AWS turned calls away for being + busy, or its stack was still working: never the release, and never a + person's job to press again.""" + low = (raw or "").lower() + return ("rate exceeded" in low or "throttl" in low or "too many requests" in low + or STACK_BUSY.lower() in low or throttled(Exception(raw or ""))) + + def retry_time(at): if isinstance(at, str): try: @@ -2563,11 +2584,15 @@ def native_propose(store, env, version, mode, extra=None, cfn=None, opener=None) raise ValueError(f"{version} is not a version this install ran before, so it can't be rolled back to") stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0] st = stack.get("StackStatus") or "" + if (st == STUCK or st.endswith("_IN_PROGRESS")) and mode == "update": + # Not a refusal: a wait like AWS throttling, tried again by itself + # (busy_request) until the stack is free. + raise AwsBusy(stack_busy_why(st)) if st == STUCK: raise ValueError("the install's stack is still stuck after an earlier update's rollback stopped; CoderHelm finishes " - "that rollback by itself (Settings, System says how far it is), then press Update again") + "that rollback by itself first (Settings, System says how far it is)") if st.endswith("_IN_PROGRESS"): - raise ValueError(f"AWS is still working on the install's stack ({st}); press Update again once it has finished") + raise ValueError(f"AWS is still working on the install's stack ({st}); this change can start once it has finished") overrides = {} if mode == "domain" and extra: attach = extra.get("DOMAIN_ACTION") != "remove" @@ -5867,15 +5892,23 @@ def _cause(raw, access=None, phase=None, retry_at=None): if m or "accessdenied" in low or "access denied" in low: return ("CoderHelm's update role isn't allowed to do something this release needs", _NEXT_RELEASE + " If that one fails the same way, send the technical details to CoderHelm support.") - if "rate exceeded" in low or "throttl" in low or "too many requests" in low or throttled(Exception(text)): + if STACK_BUSY.lower() in low: + # The stack was still busy for the whole wait: tried again by itself. + what = f"AWS was still working on the install's stack for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm waited" + if retry_at: + return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") + return (what, "It wasn't the release or the install: run the same change again once the stack has finished.") + if busy_text(text): # Never the release, and never a person's job to press again. if phase == PREPARE: what = f"AWS was busy and kept turning calls away for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm retried" - if retry_at: - return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") - return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") - return ("AWS was busy and turned some calls away", - "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") + else: + what = "AWS was busy and turned some calls away" + if retry_at: + return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") + # Only a rollback or a switch a person started ends here (an update + # always gets its own retry: native_finish, busy_request). + return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") if "limitexceeded" in low or "limit exceeded" in low or "quota" in low: return ("your AWS account reached one of its limits", "Raise the limit the technical details name (AWS console, Service Quotas) or remove what you don't use, then press Update again.") @@ -5935,6 +5968,14 @@ def native_finish(store, env, now, hid, status, reason, phase=None): if status != "succeeded": entry = store.get(hid, {}) or {} phase = phase or (ROLLED_BACK if status == "rolled_back" else STOPPED) + if phase in (PREPARE, ROLLED_BACK) and not entry.get("retry_at") and busy_text(str(reason or "")): + # AWS turned calls away and the stack is back as it was: the + # update starts again by itself, never a person's press. + at = busy_retry_at(entry, now) + if at: + entry["retry_at"] = at.isoformat() + store.put(hid, entry) + busy_retry_later(store, now, entry, at, hid) access = entry.get("access") denied = deploy_role_denied(reason) if phase != PREPARE else "" if denied or PREFLIGHT_MARK.lower() in str(reason or "").lower(): diff --git a/services/common/src/change_wait.rs b/services/common/src/change_wait.rs index 45006682a..4b18ced3e 100644 --- a/services/common/src/change_wait.rs +++ b/services/common/src/change_wait.rs @@ -252,6 +252,48 @@ pub fn settle(pr: Option<(&str, bool)>, dep_run_status: Option<&str>) -> Settled } } +/// What a run that stopped because its dependency closed does when the +/// dependency's pull request moves again: reopened, it waits for the merge +/// again; merged, it goes on as any merge does. `None` while it stays +/// closed (or can't be read). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AfterClose { + Reopened, + Merged, +} + +/// [`AfterClose`] for the dependency's pull request as GitHub gives it. +pub fn after_close(pr: Option<(&str, bool)>) -> Option { + match pr { + Some((_, true)) => Some(AfterClose::Merged), + Some(("open", false)) => Some(AfterClose::Reopened), + _ => None, + } +} + +/// What the stopped run asks of a person: reopen the change (the run then +/// waits for it again by itself) or change the ticket (a new run starts by +/// itself). +pub fn closed_action(dep: &Dependency) -> String { + format!( + "Reopen {} {CLOSED_ASK} the run goes back to waiting for its merge by itself once it is \ + reopened, and a change to the ticket starts a new run by itself", + dep.label() + ) +} + +/// The words of [`closed_action`] after the change's label. +const CLOSED_ASK: &str = "on GitHub, or change this ticket;"; + +/// Whether a run's wait, by its action, is the stop [`closed_action`] +/// wrote: its change closed without merging. A run keeps the change it +/// waited on after it went on, so a later wait of another kind (a question, +/// an approval, a person's own stop) is never read as the change closing. +pub fn waits_on_close(action: &str) -> bool { + let a = action.split_whitespace().collect::>().join(" "); + a.starts_with("Reopen ") && a.contains(CLOSED_ASK) +} + /// The reason a run stops when its dependency closed without merging. pub fn closed_reason(dep: &Dependency) -> String { format!( @@ -265,6 +307,53 @@ pub fn stuck_line(dep: &Dependency, why: &str) -> String { format!("Still waiting for {}: {why}.", dep.label()) } +#[cfg(test)] +mod after_close_tests { + use super::*; + + #[test] + fn a_reopened_or_merged_change_takes_the_run_back() { + assert_eq!( + after_close(Some(("open", false))), + Some(AfterClose::Reopened) + ); + assert_eq!( + after_close(Some(("closed", true))), + Some(AfterClose::Merged) + ); + assert_eq!(after_close(Some(("closed", false))), None); + assert_eq!(after_close(None), None); + let a = closed_action(&Dependency::default()); + assert!(!a.contains("press Retry"), "{a}"); + assert_eq!(crate::rendered::person_text(&a), None, "{a}"); + } + + #[test] + fn only_the_closed_change_stop_is_read_as_its_change_closing() { + let dep = Dependency { + ticket: "WEB-7".into(), + repo: "acme/bookstore-web".into(), + pr: 12, + ..Default::default() + }; + assert!(waits_on_close(&closed_action(&dep))); + assert!(waits_on_close(&closed_action(&Dependency::default()))); + // As the wait stores it: one line, cut to its limit. + let stored: String = closed_action(&dep).chars().take(200).collect(); + assert!(waits_on_close(&stored), "{stored}"); + for other in [ + "Write the product decision in a comment on the ticket; the run continues by itself \ + when the comment arrives", + crate::run_wake::APPROVAL_ACTION, + "Decide whether the run goes on: press Retry on the run in CoderHelm to start it \ + again, or leave it stopped", + "", + ] { + assert!(!waits_on_close(other), "{other}"); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/common/src/description_handoff.rs b/services/common/src/description_handoff.rs index 7cdc5b044..73f2f5dea 100644 --- a/services/common/src/description_handoff.rs +++ b/services/common/src/description_handoff.rs @@ -5,11 +5,15 @@ //! corrections for a person to make. The description stayed wrong. //! //! The description is CoderHelm's: after every push it is rebuilt from the -//! branch (`worker::passes::description`). A round has no tool that writes -//! it and needs none, so the round is told that ([`ROUND_NOTE`]) and its -//! account is checked ([`handoffs`]): a sentence that says the description -//! can't be edited, or leaves an edit of it to a person, is taken out -//! ([`scrub`]) and the rebuild runs, whether or not the round pushed code. +//! branch (`worker::passes::description`). Every fix round has the +//! `update_pr_description` tool, with the guard of the description writer: +//! a round CoderHelm started asks for the rebuild through it, and a +//! person's round has their wording applied. The round is told so +//! ([`ROUND_NOTE`]) and its account is checked ([`handoffs`]): a sentence +//! that says the description can't be edited, or leaves an edit of it to a +//! person ("someone needs to paste in the replacement sections"), is taken +//! out ([`scrub`]) and the rebuild runs, whether or not the round pushed +//! code. //! //! The check is narrow on purpose. It reads one sentence at a time and needs //! both the description as the thing edited and either an inability or a @@ -21,12 +25,13 @@ use std::sync::OnceLock; use regex::Regex; /// What every fix round is told about the description. -pub const ROUND_NOTE: &str = "The pull request's description is kept by CoderHelm: right after \ +pub const ROUND_NOTE: &str = "The pull request's description is kept by CoderHelm: after \ this round it is rebuilt from the branch as it stands (the versions the lockfile resolves, \ - the counts, the changes, the verification and the open items). You have no tool that writes \ - it and need none. When a finding says the description is wrong, fix what is wrong in the \ - code if anything is, and say in your account which statement was wrong; never write that \ - you cannot edit the description, and never leave an edit of it to a person."; + the counts, the changes, the verification and the open items). When a finding says the \ + description is wrong, fix what is wrong in the code if anything is, then call \ + `update_pr_description` with which statement is wrong: CoderHelm rebuilds the description \ + from the branch when the round ends. Never write that you cannot edit the description, and \ + never leave an edit of it to a person."; /// What replaces a handed-off edit in a round's account. pub const REBUILT: &str = @@ -40,6 +45,9 @@ const EDIT: &str = r"(?:edit|update|change|modify|rewrite|fix|correct|amend|touc const EDITED: &str = r"(?:edited|updated|changed|modified|rewritten|fixed|corrected|amended|adjusted|revised)"; const CANNOT: &str = r"(?:can't|cannot|can not|couldn't|could not|won't be able to|am unable to|was unable to|unable to|am not able to|not able to|have no way to|no way to|don't have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|do not have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|have no (?:tool|tools|access|permission|ability) to|lack (?:a |the )?(?:tool|tools|access|permission|ability) to)"; +/// "I have no tool that edits the PR description": the tool named by what it +/// does, not "to edit". +const NO_TOOL_THAT: &str = r"(?:have no|don't have (?:a|any)|do not have (?:a|any)|there is no|there's no|lack (?:a|any)) (?:tool|tools|way) (?:that|which|to) (?:edits?|updates?|changes?|writes?|rewrites?|modif(?:y|ies))"; const PERSON: &str = r"(?:you|someone|somebody|a person|a human|a maintainer|the maintainer|the author|a reviewer|the reviewer|the team|a teammate)"; fn patterns() -> &'static [Regex] { @@ -58,6 +66,10 @@ fn patterns() -> &'static [Regex] { r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{0,60}?\b(?:needs?|requires?|will need|still needs?) (?:a |to be )?(?:manual|manually|hand|human)".to_string(), // "The description must be updated by hand." format!(r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{{0,60}}?\b{EDITED} (?:by hand|manually|by a person|by someone|by a maintainer|by the author)"), + // "I have no tool that edits the PR description." + format!(r"(?i)\b{NO_TOOL_THAT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "Someone needs to paste in the replacement sections below." + format!(r"(?i)\b{PERSON}(?:'ll| will| would| should| must| may| can)?(?: need to| needs to| have to| has to)?\s+(?:please\s+)?(?:manually\s+)?(?:paste|copy)\b[^.;!?]{{0,40}}?\b(?:section|sections|text|replacement|description|body)"), // "I left the description corrections for you." format!(r"(?i)\b(?:left|leave|leaving)\b[^.;!?]{{0,50}}?\b(?:description|pr body|pull request body)\b[^.;!?]{{0,50}}?\b(?:for|to) {PERSON}"), ] @@ -156,6 +168,8 @@ mod tests { "I left the description corrections for the author.", "Someone should fix the headline in the PR body.", "I can\u{2019}t edit the PR description from here.", + "I have no tool that edits the PR description, so someone needs to paste in the replacement sections below.", + "Someone needs to paste in the replacement sections below.", ] { assert_eq!(handoffs(s), vec![s.to_string()], "{s}"); } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 70ace29c2..ad502ba73 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -382,6 +382,8 @@ pub mod run_round; pub mod run_status; /// What a run waiting on a person is waiting for: never nothing. pub mod run_wait; +/// A run that waits on a person goes on by itself when the input arrives. +pub mod run_wake; /// Proof that a repository builds and starts after its dependencies change: /// what to run (found in its CI and manifests), the sandbox script, and what /// the bumps are blamed for. diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index a0c107f89..1a41ea236 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -269,7 +269,9 @@ impl PermissionCheck { } else { format!("The update stack {stack} failed in AWS ({status}: {reason}).") }, - fix: "Open the stack's Events tab for the cause, delete the failed stack, then press Update again.".into(), + // CoderHelm's role in the account only reads: it can't delete + // or create a stack there, so one AWS admin action is named. + fix: stack_failed_fix(status, &stack, a, &self.region), }), UpdateStack::Found { status, .. } if status.ends_with("_IN_PROGRESS") => Some(Problem { code: "stack_in_progress", @@ -410,6 +412,45 @@ fn failed(status: &str) -> bool { status.contains("FAILED") || status.contains("ROLLBACK") } +/// The one thing an AWS admin does for an update stack left failed in +/// account `account`: a stack that never finished creating +/// (`ROLLBACK_COMPLETE`, `CREATE_FAILED`) is deleted and created again; one +/// whose update rolled back still works and is updated again. CoderHelm's +/// read-only role there can't do either, and this page checks again by +/// itself once the stack is done. +pub fn stack_failed_fix(status: &str, stack: &str, account: &str, region: &str) -> String { + let at = if region.is_empty() { + format!("account {account}") + } else { + format!("account {account} ({region})") + }; + if status.ends_with("_IN_PROGRESS") { + // A rollback still running takes no update or delete yet. + format!( + "AWS is still rolling back the stack {stack} in {at} ({status}); nothing to do until \ + it finishes. This page checks again by itself." + ) + } else if status == "UPDATE_ROLLBACK_FAILED" { + format!( + "An AWS admin in {at} continues the rollback of the stack {stack} (CloudFormation, \ + Stack actions, Continue update rollback). This page checks again by itself once the \ + stack is back." + ) + } else if status.starts_with("UPDATE_") { + format!( + "An AWS admin in {at} runs this page's one-click update again on the stack {stack}; its \ + Events tab names what failed the last time. This page checks again by itself once \ + the stack reaches UPDATE_COMPLETE." + ) + } else { + format!( + "An AWS admin in {at} deletes the stack {stack} in CloudFormation (its Events tab names \ + what failed) and creates it again with this page's one-click update. This page checks \ + again by itself once the stack reaches CREATE_COMPLETE." + ) + } +} + /// Pure: the simulator's answers folded into a check. pub fn apply_simulation(c: &mut PermissionCheck, results: &[Simulated]) { c.method = "simulate".into(); @@ -972,6 +1013,37 @@ mod tests { let p = c.problem(true).unwrap(); assert_eq!(p.code, "stack_failed"); assert!(p.message.contains("cannot be found")); + // One action for an AWS admin, never "press Update again". + assert!(p.fix.starts_with("An AWS admin in account 111122223333")); + assert!(p.fix.contains("deletes the stack")); + assert!(!p.fix.to_lowercase().contains("press update")); + assert_eq!(crate::rendered::person_text(&p.fix), None); + for status in ["UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_FAILED"] { + let f = stack_failed_fix( + status, + "CoderHelmLogReaderUpdate", + "111122223333", + "us-east-1", + ); + assert!(!f.contains("deletes")); + assert_eq!(crate::rendered::person_text(&f), None); + } + // A rollback still running: no update, no delete, only a wait. + for status in [ + "UPDATE_ROLLBACK_IN_PROGRESS", + "ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", + ] { + let f = stack_failed_fix( + status, + "CoderHelmLogReaderUpdate", + "111122223333", + "us-east-1", + ); + assert!(!f.contains("deletes") && !f.contains("update again")); + assert!(f.contains("checks again by itself")); + assert_eq!(crate::rendered::person_text(&f), None); + } c.update_stack = UpdateStack::NotFound; assert!(c.problem(false).is_none()); let p = c.problem(true).unwrap(); diff --git a/services/common/src/merged_ticket.rs b/services/common/src/merged_ticket.rs index 985c31a79..cc8b60251 100644 --- a/services/common/src/merged_ticket.rs +++ b/services/common/src/merged_ticket.rs @@ -295,16 +295,18 @@ fn where_when(pr: &MergedPr) -> String { format!("{into}{on}") } -/// How a person runs the ticket anyway. +/// How a person runs the ticket anyway. A reply that asks for work starts +/// the run by itself (the worker reads it: `jira_comment`), with the merge +/// check off for that merge. fn how(source: &TicketSource) -> &'static str { match source { TicketSource::Jira => { - "press Retry on this run in CoderHelm, or reply on the ticket with what is still to \ - do" + "reply on the ticket with what is still to do (a reply that asks for work starts the \ + run by itself), or press Retry on this run in CoderHelm" } _ => { - "press Retry on this run in CoderHelm, or mention @coderhelm on the issue with what \ - is still to do" + "mention @coderhelm on the issue with what is still to do (that comment starts the \ + run by itself), or press Retry on this run in CoderHelm" } } } @@ -432,15 +434,17 @@ pub fn replace_note(instructions: &str, carried: Option<&str>, fresh: Option<&st with_note(&base, fresh) } -/// What the run's wait asks for. +/// What the run's wait asks for: a reply is the answer, and the waiting +/// run goes on by itself when it arrives (`run_wake`). pub fn wait_action(source: &TicketSource) -> &'static str { match source { TicketSource::Jira => { - "Press Retry to run the ticket anyway, or reply on the ticket with what is still to do" + "Reply on the ticket with what is still to do, or that it should be built anyway; the \ + run continues by itself when the reply arrives" } _ => { - "Press Retry to run the issue anyway, or mention @coderhelm on the issue with what is \ - still to do" + "Comment on the issue with what is still to do, or that it should be built anyway; \ + the run continues by itself when the comment arrives" } } } @@ -774,7 +778,10 @@ mod tests { "{jira}" ); assert!(jira.contains("press Retry on this run"), "{jira}"); - assert!(jira.contains("reply on the ticket"), "{jira}"); + assert!( + jira.contains("reply on the ticket with what is still to do (a reply that asks for work starts the run by itself)"), + "{jira}" + ); assert!(!jira.contains("reopen"), "{jira}"); let bare = MergedPr { base: String::new(), @@ -820,7 +827,12 @@ mod tests { let part = partial_note(&both, "They add the index.", &["the CSV export".into()]); assert!(part.contains("acme/app#30 merged into `develop` on 2026-11-10, after acme/app#12, and together they already do part of this ticket: They add the index."), "{part}"); assert!(part.contains("adds to acme/app#30."), "{part}"); - assert!(wait_action(&TicketSource::Github).contains("mention @coderhelm")); - assert!(wait_action(&TicketSource::Jira).contains("reply on the ticket")); + assert!(wait_action(&TicketSource::Github).contains("Comment on the issue")); + assert!(wait_action(&TicketSource::Jira).starts_with("Reply on the ticket")); + for s in [TicketSource::Jira, TicketSource::Github] { + let a = wait_action(&s); + assert!(a.contains("the run continues by itself"), "{a}"); + assert_eq!(crate::rendered::person_text(a), None, "{a}"); + } } } diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 0d8d6e0a1..ca92be404 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -387,6 +387,17 @@ pub struct JiraCommentMessage { pub context_hash: String, #[serde(default)] pub action: Option>, + /// The ticket's run waits on a person and a comment answers its wait + /// (`run_wake::wakes`): the comment resumes it, whatever its words, + /// unless it only reports status or says the work is done elsewhere. + /// `None` from a gateway that didn't say: a `needs_input` or `failed` + /// run is then taken as waiting for the answer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resumes: Option, + /// What the waiting run asked for (its wait's action), so the comment + /// is read as the answer to it. + #[serde(default)] + pub waiting_for: String, } /// A lesson job (gateway on a closed PR, or the feedback pass on a comment). diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index 5d688d699..fb09938d4 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -522,13 +522,38 @@ fn asks_testing(a: &Ask) -> bool { } /// Whether the item's action is adding labels to a pull request. -fn adds_labels(a: &Ask) -> bool { +/// CoderHelm adds labels itself through the issues API, whatever workflow a +/// label starts (a preview deploy, an end-to-end run): a label that starts +/// a deploy needs no deploy permission. Only a label that releases to +/// production stays the team's call: one whose item names production, a +/// release or a publish in any word (`deploy-prod`, `release`, `prod`). +pub fn adds_labels(a: &Ask) -> bool { let t = one_line(&a.text).to_lowercase(); let t = t .trim_start_matches("after merging: ") .trim_start_matches("before merging: "); - (t.starts_with("add pr label") || t.starts_with("add labels") || t.starts_with("add the label")) - && !t.contains("deploy") + [ + "add pr label", + "add labels", + "add label", + "add the label", + "add the pr label", + "apply the label", + "apply labels", + "label the pr", + "label the pull request", + ] + .iter() + .any(|p| t.starts_with(p)) + && !releases(t) +} + +/// Whether a label item's words name a release to production: a word (split +/// on anything but letters and digits) that is or starts with `prod`, or +/// one that names a release or a publish. +fn releases(t: &str) -> bool { + t.split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| w.starts_with("prod") || w.starts_with("release") || w.starts_with("publish")) } /// Whether the item's action is a deploy: its words start with one, or the @@ -1958,4 +1983,28 @@ mod tests { assert!(!paid_action(t), "{t}"); } } + + #[test] + fn a_label_that_releases_to_production_stays_the_teams_call() { + let ask = |t: &str| Ask { + text: t.into(), + ..Default::default() + }; + for t in [ + "Add the label `deploy-preview` to start the preview", + "Add label e2e-run", + "Before merging: add the PR label `needs-qa`", + ] { + assert!(adds_labels(&ask(t)), "{t}"); + } + for t in [ + "Add label deploy-prod", + "Add the `release` label", + "Add the label CI:DEPLOY_PRODUCTION", + "After merging: apply the label publish-npm", + "Add the label to ship to production", + ] { + assert!(!adds_labels(&ask(t)), "{t}"); + } + } } diff --git a/services/common/src/pr_steps.rs b/services/common/src/pr_steps.rs index 81f4447cf..3b87ff85b 100644 --- a/services/common/src/pr_steps.rs +++ b/services/common/src/pr_steps.rs @@ -171,6 +171,33 @@ pub fn is_command(how: &str) -> bool { .contains(&first) } +/// `unblock` as the one way to let CoderHelm: an alternative that hands the +/// step back to the reader ("..., or run the command yourself", "or a +/// person runs the command") is taken out. The step's line already says +/// what to run; the unblock is what lets CoderHelm run it. +pub fn one_way(unblock: &str) -> String { + let t = one_line(unblock); + // ASCII-only, so an offset found here is a char boundary in `t`. + let low = t.to_ascii_lowercase(); + let cut = [ + ", or run the command yourself", + " or run the command yourself", + ", or run it yourself", + " or run it yourself", + ", or a person runs the command", + " or a person runs the command", + ", or do it yourself", + " or do it yourself", + ] + .iter() + .filter_map(|p| low.find(p)) + .min(); + match cut { + Some(i) => t[..i].trim_end_matches([',', ';', ' ']).to_string(), + None => t, + } +} + /// `text` without the names of CoderHelm's own tools. pub fn plain(text: &str) -> String { let mut t = one_line(text); @@ -197,7 +224,8 @@ pub fn plain_error(raw: &str) -> (String, String) { return match crate::github_grants::Denial::from_error("POST", raw, "actions", "write") { Some(d) => ( d.line(), - "an organization owner accepts Actions: write for the app once for the install, or a person runs the command".into(), + "an organization owner accepts Actions: write for the app once for the install" + .into(), ), None => ( crate::github_grants::install_item( @@ -374,7 +402,10 @@ impl Step { sentence_part(cause) ); if !unblock.trim().is_empty() { - t.push_str(&format!(" To let it: {}.", sentence_part(unblock))); + t.push_str(&format!( + " To let it: {}.", + sentence_part(&one_way(unblock)) + )); } t } @@ -389,7 +420,10 @@ impl Step { // "none: ..." is a reason there is no way, not a way. if !unblock.trim().is_empty() && !unblock.trim().to_lowercase().starts_with("none") { - t.push_str(&format!(" To let it: {}.", sentence_part(&plain(unblock)))); + t.push_str(&format!( + " To let it: {}.", + sentence_part(&plain(&one_way(unblock))) + )); } t } @@ -550,7 +584,7 @@ mod tests { let failed = deploy(State::Failed { cause, unblock }); assert_eq!( failed.line(), - "After merging: Deploy the staging admin app: run `cd apps/admin && npm run deploy:staging`. CoderHelm could not: GitHub answered 403 to `POST /repos/acme/site/actions/workflows/test.yml/dispatches`: the GitHub App needs Actions: write. To let it: an organization owner accepts Actions: write for the app once for the install, or a person runs the command." + "After merging: Deploy the staging admin app: run `cd apps/admin && npm run deploy:staging`. CoderHelm could not: GitHub answered 403 to `POST /repos/acme/site/actions/workflows/test.yml/dispatches`: the GitHub App needs Actions: write. To let it: an organization owner accepts Actions: write for the app once for the install." ); let done = deploy(State::Done { evidence: "the deploy workflow passed".into(), diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index 2b8a8fda1..e95e51cee 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -112,6 +112,41 @@ const HANDOFFS: &[(&str, &str)] = &[ ("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"), + ( + "and re-run", + "the run starts by itself once the change is made", + ), + ("put it right", "names no one action"), + ( + "press update again", + "the updater tries again by itself, or names an AWS admin's one action", + ), + ( + "delete the failed stack, then", + "one action for an AWS admin, never a chore list", + ), + ("add pr label", "CoderHelm adds labels itself"), + ( + "no tool that edits", + "the description is CoderHelm's to rebuild", + ), + ( + "paste in the replacement", + "the description is CoderHelm's to rebuild", + ), +]; + +/// Words written for the coding model, never for a person: CoderHelm's own +/// tool arguments and the model's evidence lines. A refusal the coder reads +/// ("Put it back with `restore_file` (omit `from_ref`)") is said to a person +/// as what is wrong, never as the instruction (`habits_check::fixing_note`). +const MODEL_FACING: &[(&str, &str)] = &[ + ("(omit code)", "a tool's argument"), + ("in your evidence", "an instruction to the coding model"), + ( + "put it back with code", + "a tool call the coding model makes", + ), ]; /// A raw internal name a reader can't use: a bracketed snake_case key @@ -143,6 +178,11 @@ pub fn person_text(text: &str) -> Option { return Some(format!("a hand-off (\"{p}\": {why}): {body}")); } } + for (p, why) in MODEL_FACING { + if low.contains(p) { + return Some(format!("words for the model (\"{p}\": {why}): {body}")); + } + } if body.contains("(s)") { return Some(format!("a template plural: {body}")); } @@ -270,6 +310,38 @@ mod tests { } } + /// The texts the second sweep found, each held here so it can't come + /// back: a wait that ends in "then press Retry" or names no action, a + /// note that quotes the coding model's instructions, a hand-off of + /// labels or of the description, and the updater's "press Update + /// again". + #[test] + fn the_second_sweeps_texts_are_caught() { + for bad in [ + "Look at what stopped the run, put it right, then press Retry", + "Give CoderHelm the access the run needs, then press Retry", + "If the work belongs in a different repo, set the repo and re-run.", + "This ticket is for acme/bookstore-docs. Turn it on in Repositories and re-run.", + "Tests and scope check found 1 item, fixing: `package.json` was changed and is no task of the plan. Put it back with `restore_file` (omit `from_ref`), or say why in your Evidence.", + "I have no tool that edits the PR description, so someone needs to paste in the replacement sections below.", + "1. Add PR labels e2e:checkout and CI:E2E, sending the existing labels too.", + "Give the app Actions: write (GitHub, Settings), or run the command yourself.", + "AWS is still working on the install's stack; press Update again once it has finished.", + "Open the stack's Events tab for the cause, delete the failed stack, then press Update again.", + ] { + assert!(person_text(bad).is_some(), "{bad}"); + } + for ok in [ + "Write the product decision in a comment on the ticket; the run continues by itself when the comment arrives", + "Decide whether the run goes on: press Retry on the run in CoderHelm to start it again, or leave it stopped", + "Tests and scope check found 1 item; CoderHelm is fixing it now. `package.json` was changed and is no task of the plan.", + "Nothing to do: CoderHelm starts it again by itself at 14:30 UTC.", + "An AWS admin in account 111122223333 deletes the stack CoderHelmLogReaderUpdate in CloudFormation and creates it again with this page's one-click update.", + ] { + 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"; diff --git a/services/common/src/run_fail.rs b/services/common/src/run_fail.rs index b3cd37b61..2ab10aed0 100644 --- a/services/common/src/run_fail.rs +++ b/services/common/src/run_fail.rs @@ -100,6 +100,10 @@ pub struct RunFailure<'a> { /// Numbers added to fields in the same write (tokens, cost): what this /// invocation used, on top of what earlier ones recorded. pub add: Vec<(&'static str, AttributeValue)>, + /// The run is an alert's: it has no ticket thread, so a wait's action + /// says what to do first and then Retry on the run page + /// (`run_wake::for_alert`). + pub alert: bool, } /// The status-index sort key of a failed run. @@ -168,12 +172,20 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { ("#detail".to_string(), rr::FIELD_ERROR_DETAIL.to_string()), ("#kind".to_string(), rr::FIELD_ERROR_KIND.to_string()), ]); + // What the person does: an alert run has no thread to comment on. + let action_of = |needs: &rr::NeedsYou| { + if f.alert { + crate::run_wake::for_alert(&needs.action) + } else { + needs.action.clone() + } + }; // A wait on a person, through the gate with what they do. let needs_you = |needs: &rr::NeedsYou| { - let wait = crate::run_wait::WaitingOn::action(&needs.action, &needs.detail, "") + let wait = crate::run_wait::WaitingOn::action(&action_of(needs), &needs.detail, "") .unwrap_or_else(|| { crate::run_wait::WaitingOn::fixed( - "Look at what stopped the run, then press Retry", + "Put right what the error below names, then say so in a comment on the ticket; the run continues by itself when the comment arrives", &needs.detail, "", ) @@ -208,7 +220,7 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { } Ending::NeedsYou(c, needs) => { let (w, wo) = needs_you(&needs); - let said = format!("{} {}.", needs.detail, needs.action); + let said = format!("{} {}.", needs.detail, action_of(&needs)); ( w, needs.detail.clone(), @@ -222,7 +234,7 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { Cause::NeedsYou { needs, .. } => { let kind = needs.kind; let (w, wo) = needs_you(needs); - let said = format!("{} {}.", needs.detail, needs.action); + let said = format!("{} {}.", needs.detail, action_of(needs)); ( w, needs.detail.clone(), diff --git a/services/common/src/run_recovery.rs b/services/common/src/run_recovery.rs index d740b6228..9d840b99c 100644 --- a/services/common/src/run_recovery.rs +++ b/services/common/src/run_recovery.rs @@ -731,7 +731,9 @@ pub enum Next { #[derive(Debug, Clone, PartialEq, Eq)] pub struct NeedsYou { pub why: HumanOnly, - /// One action ("Restore the branch `main` in acme/site, then press Retry"). + /// One action, ending in how the run goes on by itself ("Restore the + /// branch `main` in acme/site, then say so in a comment on the ticket; + /// the run continues by itself when the comment arrives": `run_wake`). pub action: String, /// Why, in plain words. pub detail: String, @@ -757,7 +759,9 @@ pub fn next(c: &Classified, ledger: &Ledger, mark: &str) -> Next { Next::NeedsYou(NeedsYou { kind: c.kind, why: HumanOnly::Unrepaired, - action: "Press Retry once the service is answering again".into(), + action: crate::run_wake::by_comment( + "Check that the service the error below names answers again", + ), detail: format!( "{} CoderHelm tried again {repeats} times with longer waits each time and \ it still didn't answer.", @@ -809,7 +813,7 @@ pub fn unknown_stop(c: &Classified, retries: usize) -> NeedsYou { NeedsYou { kind: c.kind, why: HumanOnly::Unrepaired, - action: "Look at what stopped the run, put it right, then press Retry".into(), + action: unrepaired_action(), detail: format!( "CoderHelm met an error it doesn't know how to repair, {tried}: {}", c.plain @@ -830,27 +834,51 @@ pub fn usage_limit(reason: &str) -> NeedsYou { needs_person(&c) } +/// The action for an error CoderHelm couldn't get past by itself: the one +/// thing the error names, put right by a person, and how the run goes on. +fn unrepaired_action() -> String { + crate::run_wake::by_comment( + "Put right what the error below names (CoderHelm can't change it from the run)", + ) +} + +/// What a person does for a wait on `why`, and how the run goes on: by +/// itself, when what it waits for arrives (`run_wake`). Only an approval and +/// a person's own stop of the run are decisions the run waits for where +/// they are made. +pub fn person_action(why: HumanOnly) -> String { + use crate::run_wake::by_comment; + match why { + HumanOnly::Credential => by_comment("Add the credential the error below names"), + HumanOnly::MissingAccess => "Give the CoderHelm GitHub app the access the error below \ + names (on GitHub: Settings, Installed GitHub Apps, CoderHelm, Repository access); the run \ + continues by itself once GitHub reports the access, or when a comment on the \ + ticket says it is given" + .to_string(), + HumanOnly::ProductDecision => "Write the product decision in a comment on the ticket; \ + the run continues by itself when the comment arrives" + .to_string(), + HumanOnly::AmbiguousTicket => "Say in a comment on the ticket which reading is meant; \ + the run continues by itself when the comment arrives" + .to_string(), + HumanOnly::HeldByAnother => by_comment("Finish or hand over the other work on this ticket"), + HumanOnly::UsageLimit => "Raise or clear the team's usage limit in Settings; the run \ + continues by itself once the new limit is saved and allows it" + .to_string(), + HumanOnly::Approval => crate::run_wake::APPROVAL_ACTION.to_string(), + HumanOnly::PersonAction => "Decide whether the run goes on: press Retry on the run in \ + CoderHelm to start it again, or leave it stopped" + .to_string(), + HumanOnly::Unrepaired => unrepaired_action(), + } +} + fn needs_person(c: &Classified) -> NeedsYou { let why = c.person.unwrap_or(HumanOnly::Unrepaired); - let action = match why { - HumanOnly::Credential => "Add the credential the run needs, then press Retry", - HumanOnly::MissingAccess => "Give CoderHelm the access the run needs, then press Retry", - HumanOnly::ProductDecision => "Make the product decision on the ticket, then press Retry", - HumanOnly::AmbiguousTicket => "Say on the ticket which reading is meant, then press Retry", - HumanOnly::HeldByAnother => { - "Finish or hand over the other work on this ticket, then press Retry" - } - HumanOnly::UsageLimit => { - "Raise or clear the team's usage limit in Settings, then press Retry" - } - HumanOnly::Approval => "Answer the approval the team's agent policy asks for", - HumanOnly::PersonAction => "Look at the run's last action, then press Retry", - HumanOnly::Unrepaired => "Look at what stopped the run, put it right, then press Retry", - }; NeedsYou { kind: c.kind, why, - action: action.into(), + action: person_action(why), detail: c.plain.clone(), } } @@ -862,28 +890,28 @@ fn unrepaired(c: &Classified, repair: &Repair, tried: usize) -> NeedsYou { repo, base, head, - } if head.is_empty() && !base.is_empty() => format!( - "Restore the branch `{base}` in {owner}/{repo} or set the repository's default branch, \ - then press Retry" + } if head.is_empty() && !base.is_empty() => crate::run_wake::by_comment(&format!( + "Restore the branch `{base}` in {owner}/{repo}, or set the repository's default \ + branch on GitHub" + )), + Repair::MissingRef { owner, repo, .. } if !owner.is_empty() => crate::run_wake::by_comment( + &format!("Restore the branch the error below names in {owner}/{repo} on GitHub"), ), Repair::MissingRef { .. } => { - "Check the run's branches on GitHub, then press Retry".to_string() - } - Repair::BranchBehind { .. } => { - "Resolve the conflicts with the base branch on the pull request, then press Retry" - .to_string() - } - Repair::ClosedOwnPr { .. } => { - "Reopen the pull request, or press Retry to start a new one".to_string() - } - Repair::MissingLabel { name, .. } => { - format!("Create the label `{name}` in the repository, then press Retry") - } - Repair::ExpiredToken => { - "Check the CoderHelm GitHub app's installation (reinstall it if it was removed), then \ - press Retry" - .to_string() + crate::run_wake::by_comment("Restore the branch the error below names on GitHub") } + Repair::BranchBehind { .. } => crate::run_wake::by_comment( + "Resolve the conflicts with the base branch on the pull request", + ), + Repair::ClosedOwnPr { .. } => "Decide whether the work goes on: reopen the pull request \ + on GitHub to go on with it, or press Retry on the run in CoderHelm to start a new one" + .to_string(), + Repair::MissingLabel { name, .. } => crate::run_wake::by_comment(&format!( + "Create the label `{name}` in the repository (GitHub, Issues, Labels)" + )), + Repair::ExpiredToken => "Install the CoderHelm GitHub app again on GitHub if it was \ + removed or suspended; the run continues by itself once GitHub reports the install" + .to_string(), }; NeedsYou { kind: c.kind, diff --git a/services/common/src/run_wake.rs b/services/common/src/run_wake.rs new file mode 100644 index 000000000..a1f9e948f --- /dev/null +++ b/services/common/src/run_wake.rs @@ -0,0 +1,408 @@ +//! A run that waits on a person goes on by itself once the person's input +//! arrives. +//! +//! A run that stopped for a person used to say "... then press Retry", and +//! a comment on its ticket was only kept as context for some later run. The +//! person answered and the run went on waiting. Now what the run waits for +//! wakes it, the way a person's Retry would (`POST /api/runs/{id}/retry`): +//! +//! - [`Wake::Comment`]: a person's comment or reply on the run's ticket +//! (a Jira comment, or a comment on the GitHub issue); +//! - [`Wake::Access`]: GitHub reports access granted to the CoderHelm app +//! (a repository added to its installation, a permission accepted, the +//! app installed again); +//! - [`Wake::Limit`]: the team's usage limit raised or cleared so runs may +//! start again, or a new month that resets it (the worker's 15-minute +//! sweep reads each waiting team's limit: `passes::run_wake`); +//! - [`Wake::Approval`]: the approval the run's agent policy asked for was +//! answered: the same run goes on, so the one-time grant (kept for that +//! run) applies ([`approval_resumes`]); +//! - an alert run (no ticket thread): the alert firing again resumes it, +//! and the alert clearing closes it ([`alert_wake`], [`for_alert`]). +//! +//! Every wait names one of these in its action ([`CONTINUES`]), so what a +//! person reads is what happens. Only a decision a person makes about the +//! run itself (an approval its policy asks for, or a person's own stop or +//! draft of it) waits for that decision, where it is made: a comment never +//! restarts a run a person stopped. +//! +//! A wake marks the waiting run superseded before it queues the new run. If +//! the queue refuses, [`put_back`] writes the run back to waiting (only +//! while it still holds that wake's write), so the next event, sweep or +//! Retry finds it again instead of a superseded run with no successor. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; + +use crate::handback::HumanOnly; + +/// What a waiting run's action ends with: the run goes on by itself. +pub const CONTINUES: &str = "the run continues by itself when the comment arrives"; + +/// The action of a wait a comment on the ticket answers: `what` a person +/// does, then that a comment says so, then that the run goes on by itself. +pub fn by_comment(what: &str) -> String { + format!( + "{}, then say so in a comment on the ticket; {CONTINUES}", + what.trim().trim_end_matches('.') + ) +} + +/// What wakes a waiting run. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Wake { + /// A person's comment or reply on the run's ticket. + Comment, + /// Access granted to the CoderHelm GitHub app. + Access, + /// The team's usage limit raised or cleared, or reset by a new month. + Limit, + /// The approval the run waited for was answered. + Approval, +} + +/// What a run waiting on its agent policy's approval asks. The answer +/// resumes the same run by itself (the grant is kept for that run). +pub const APPROVAL_ACTION: &str = "Answer the approval request this run is waiting on (Agents, \ + Approvals, or the link sent with it); the run goes on by itself once it is answered"; + +/// The status of a run that waits on a person. +pub const WAITING: &str = "needs_input"; + +/// Whether `wake` starts a run that waits on a person for `why` (the wait's +/// `handback`; `None` when the wait names none). A comment answers every +/// wait but the three a comment can't settle: the usage limit (only the +/// setting lifts it), an approval the team's policy asks for (answered +/// where the policy asks), and a person's own action on the run (a stop, a +/// PR put back to draft: only that person's Retry or ready undoes it). +pub fn wakes(why: Option, wake: Wake) -> bool { + match wake { + Wake::Comment => !matches!( + why, + Some(HumanOnly::UsageLimit | HumanOnly::Approval | HumanOnly::PersonAction) + ), + Wake::Access => matches!(why, Some(HumanOnly::MissingAccess | HumanOnly::Credential)), + Wake::Limit => why == Some(HumanOnly::UsageLimit), + Wake::Approval => why == Some(HumanOnly::Approval), + } +} + +/// Whether the answer to approval `approval_id` resumes the run with +/// `status` that waited on `handback` for `waited_for` (its +/// `policy_approval`): only that run, only while it still waits. +pub fn approval_resumes(status: &str, handback: &str, waited_for: &str, approval_id: &str) -> bool { + !approval_id.is_empty() + && waited_for == approval_id + && wakes_run(status, handback, Wake::Approval) +} + +/// What an alert's delivery does to its run that waits on a person. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlertWake { + /// The alert fired again: the run goes on, as Retry would. + Resume, + /// The alert cleared by itself: nothing is left to fix, the run closes. + Close, +} + +/// [`AlertWake`] for a run with `status` waiting on `handback`, when its +/// alert fires again (`cleared` false) or clears. `None` for a run that +/// doesn't wait, or waits on the usage limit or an approval (only those +/// lift it; a clear still closes it). +pub fn alert_wake(status: &str, handback: &str, cleared: bool) -> Option { + if status != WAITING { + return None; + } + if cleared { + return Some(AlertWake::Close); + } + wakes(HumanOnly::from_code(handback), Wake::Comment).then_some(AlertWake::Resume) +} + +/// What an alert run's wait asks: an alert has no ticket thread, so a +/// comment can't answer it. The person does what `action` names, then +/// presses Retry on the run page; the run also goes on by itself when the +/// alert fires again, and closes by itself when it clears. +pub fn for_alert(action: &str) -> String { + let what = match action.find(", then say so in a comment on the ticket") { + Some(i) => &action[..i], + None => match action.find("; the run continues by itself") { + Some(i) => &action[..i], + None => action, + }, + }; + // No thread to comment on: the decision is the person's to act on. + let what = what + .replace("Say in a comment on the ticket ", "Decide ") + .replace(" in a comment on the ticket", ""); + let what = what.trim().trim_end_matches('.'); + format!( + "{what}. Once that is done, press Retry on the run page; the run also goes on by itself \ + when the alert fires again, and closes by itself when it clears" + ) +} + +/// [`wakes`] for a run with `status` whose wait recorded `handback` (its +/// code, `HumanOnly::code`): only a run that waits on a person is woken. +pub fn wakes_run(status: &str, handback: &str, wake: Wake) -> bool { + status == WAITING && wakes(HumanOnly::from_code(handback), wake) +} + +/// Whether a run waiting for access in `repo` (`owner/name`, the run's own; +/// empty when it has none) is the one access granted to `added` repositories +/// wakes: its own repository was added, or its wait names one that was. +/// Access granted without a repository list (a permission accepted, the app +/// installed again) wakes every run waiting for access. +pub fn access_reaches(repo: &str, wait_text: &str, added: &[String]) -> bool { + if added.is_empty() { + return true; + } + let text = wait_text.to_ascii_lowercase(); + added.iter().any(|a| { + let a = a.trim().to_ascii_lowercase(); + !a.is_empty() && (repo.eq_ignore_ascii_case(&a) || text.contains(&a)) + }) +} + +/// The write that undoes a wake whose new run couldn't be queued: the run +/// `item` (as read before the wake) goes back to waiting with the status +/// key ([`crate::run_ending::restored_sri`]) and ending it had, only while it still holds the wake's own write +/// (`woken_sri`, the status key it set, and `woken_at`, its `updated_at`). +#[derive(Debug, Clone, PartialEq)] +pub struct PutBack { + pub update: String, + pub condition: &'static str, + pub values: Vec<(&'static str, AttributeValue)>, +} + +/// [`PutBack`] for `item` after a wake that wrote `woken_sri` at `woken_at`. +pub fn put_back_write( + item: &HashMap, + woken_sri: AttributeValue, + woken_at: &str, +) -> PutBack { + let run_id = item + .get("run_id") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or(""); + // Only a waiting run is woken, so its key was the waiting one. + let mut values = vec![ + (":waiting", AttributeValue::S(WAITING.into())), + (":sri", crate::run_ending::restored_sri(WAITING, run_id)), + (":woken_sri", woken_sri), + (":woken_at", AttributeValue::S(woken_at.into())), + (":now", AttributeValue::S(chrono::Utc::now().to_rfc3339())), + ]; + let ending = crate::run_ending::FIELD_ENDING; + let update = match item.get(ending) { + Some(e) => { + values.push((":ending", e.clone())); + format!( + "SET #s = :waiting, status_run_id = :sri, updated_at = :now, {ending} = :ending" + ) + } + None => { + format!("SET #s = :waiting, status_run_id = :sri, updated_at = :now REMOVE {ending}") + } + }; + PutBack { + update, + condition: "status_run_id = :woken_sri AND updated_at = :woken_at", + values, + } +} + +/// Puts the woken run `item` back to waiting after its new run couldn't be +/// queued ([`put_back_write`]). Returns whether it was put back; `false` +/// when something else moved it meanwhile (a Retry, another wake). +pub async fn put_back( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + item: &HashMap, + woken_sri: AttributeValue, + woken_at: &str, +) -> bool { + let key = |k: &str| { + item.get(k) + .cloned() + .unwrap_or_else(|| AttributeValue::S(String::new())) + }; + let w = put_back_write(item, woken_sri, woken_at); + let mut req = dynamo + .update_item() + .table_name(table) + .key("team_id", key("team_id")) + .key("run_id", key("run_id")) + .update_expression(w.update) + .condition_expression(w.condition) + .expression_attribute_names("#s", "status"); + for (k, v) in w.values { + req = req.expression_attribute_values(k, v); + } + match req.send().await { + Ok(_) => true, + Err(e) => { + tracing::warn!(error = %e, "A woken run couldn't be put back to waiting"); + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_comment_wakes_every_wait_a_comment_can_answer() { + for why in [ + HumanOnly::ProductDecision, + HumanOnly::AmbiguousTicket, + HumanOnly::Credential, + HumanOnly::MissingAccess, + HumanOnly::HeldByAnother, + HumanOnly::Unrepaired, + ] { + assert!(wakes(Some(why), Wake::Comment), "{why:?}"); + } + assert!(wakes(None, Wake::Comment)); + assert!(!wakes(Some(HumanOnly::UsageLimit), Wake::Comment)); + assert!(!wakes(Some(HumanOnly::Approval), Wake::Comment)); + } + + #[test] + fn a_comment_never_restarts_a_run_a_person_stopped_or_drafted() { + assert!(!wakes(Some(HumanOnly::PersonAction), Wake::Comment)); + assert!(!wakes_run("needs_input", "person_action", Wake::Comment)); + assert_eq!(alert_wake("needs_input", "person_action", false), None); + assert_eq!( + alert_wake("needs_input", "person_action", true), + Some(AlertWake::Close) + ); + } + + #[test] + fn a_wake_whose_run_was_not_queued_goes_back_to_waiting() { + let s = |v: &str| AttributeValue::S(v.into()); + let ending = AttributeValue::M(HashMap::from([("kind".to_string(), s("waiting"))])); + let item = HashMap::from([ + ("team_id".to_string(), s("T1")), + ("run_id".to_string(), s("01A")), + ("status".to_string(), s("needs_input")), + ("status_run_id".to_string(), s("needs_input#01A")), + (crate::run_ending::FIELD_ENDING.to_string(), ending.clone()), + ]); + let w = put_back_write(&item, s("superseded#01A"), "2026-03-02T10:00:00Z"); + let val = |k: &str| { + w.values + .iter() + .find(|(n, _)| *n == k) + .map(|(_, v)| v.clone()) + }; + assert_eq!(val(":waiting"), Some(s(WAITING))); + assert_eq!(val(":sri"), Some(s("needs_input#01A")), "the key it had"); + assert_eq!(val(":ending"), Some(ending), "the ending it had"); + assert_eq!(val(":woken_sri"), Some(s("superseded#01A"))); + assert!(w + .update + .starts_with("SET #s = :waiting, status_run_id = :sri")); + // Only the wake's own write is undone: a Retry or another wake that + // moved the run meanwhile wrote another key or time. + assert!(w.condition.contains("status_run_id = :woken_sri")); + assert!(w.condition.contains("updated_at = :woken_at")); + + let mut bare = item.clone(); + bare.remove(crate::run_ending::FIELD_ENDING); + bare.remove("status_run_id"); + let w = put_back_write(&bare, s("superseded#01A"), "t"); + assert!(w.update.ends_with("REMOVE run_ending"), "{}", w.update); + assert!(w + .values + .iter() + .any(|(n, v)| *n == ":sri" && *v == s("needs_input#01A"))); + } + + #[test] + fn access_and_the_limit_wake_only_their_own_waits() { + assert!(wakes(Some(HumanOnly::MissingAccess), Wake::Access)); + assert!(wakes(Some(HumanOnly::Credential), Wake::Access)); + assert!(!wakes(Some(HumanOnly::ProductDecision), Wake::Access)); + assert!(wakes(Some(HumanOnly::UsageLimit), Wake::Limit)); + assert!(!wakes(Some(HumanOnly::MissingAccess), Wake::Limit)); + assert!(wakes_run("needs_input", "usage_limit", Wake::Limit)); + assert!(!wakes_run("completed", "usage_limit", Wake::Limit)); + assert!(wakes_run("needs_input", "", Wake::Comment)); + } + + #[test] + fn access_to_a_repository_wakes_the_runs_that_wait_for_it() { + let added = vec!["acme/bookstore-web".to_string()]; + assert!(access_reaches("acme/bookstore-web", "", &added)); + assert!(access_reaches( + "", + "This ticket is for acme/bookstore-web, which isn't connected", + &added + )); + assert!(!access_reaches("acme/bookstore-api", "", &added)); + assert!(access_reaches("acme/bookstore-api", "", &[])); + } + + #[test] + fn an_answer_resumes_only_the_run_that_waited_for_it() { + assert!(approval_resumes("needs_input", "approval", "ap1", "ap1")); + assert!(!approval_resumes("needs_input", "approval", "ap1", "ap2")); + assert!(!approval_resumes("completed", "approval", "ap1", "ap1")); + assert!(!approval_resumes( + "needs_input", + "product_decision", + "ap1", + "ap1" + )); + assert!(!approval_resumes("needs_input", "approval", "", "")); + } + + #[test] + fn an_alert_firing_again_resumes_and_clearing_closes() { + let w = "needs_input"; + assert_eq!( + alert_wake(w, "unrepaired_error", false), + Some(AlertWake::Resume) + ); + assert_eq!(alert_wake(w, "usage_limit", false), None); + assert_eq!(alert_wake(w, "usage_limit", true), Some(AlertWake::Close)); + assert_eq!(alert_wake("running", "", true), None); + let a = for_alert(&by_comment( + "Restore the branch `main` in acme/bookstore-ops", + )); + assert_eq!( + a, + "Restore the branch `main` in acme/bookstore-ops. Once that is done, press Retry on \ + the run page; the run also goes on by itself when the alert fires again, and closes \ + by itself when it clears" + ); + assert_eq!(crate::rendered::person_text(&a), None, "{a}"); + let c = for_alert("Say in a comment on the ticket which reading is meant; the run continues by itself when the comment arrives"); + assert!( + c.starts_with("Decide which reading is meant. Once that is done"), + "{c}" + ); + assert!(!c.contains("comment"), "{c}"); + let b = for_alert("Raise or clear the team's usage limit in Settings; the run continues by itself once the new limit is saved and allows it"); + assert!( + b.starts_with("Raise or clear the team's usage limit in Settings. Once"), + "{b}" + ); + } + + #[test] + fn the_action_says_the_run_goes_on_by_itself() { + let a = by_comment("Restore the branch `main` in acme/bookstore-web."); + assert_eq!( + a, + "Restore the branch `main` in acme/bookstore-web, then say so in a comment on the \ + ticket; the run continues by itself when the comment arrives" + ); + assert_eq!(crate::rendered::person_text(&a), None, "{a}"); + } +} diff --git a/services/gateway/src/routes/agent_policy.rs b/services/gateway/src/routes/agent_policy.rs index 261b2b67b..3e48ed9a4 100644 --- a/services/gateway/src/routes/agent_policy.rs +++ b/services/gateway/src/routes/agent_policy.rs @@ -931,6 +931,8 @@ pub async fn decide( ) .await .map_err(decide_error)?; + // The run that waited for this answer goes on by itself (`run_wake`). + super::run_wake::approval_answered(&state, &claims.team_id, &a.run_id, &a.id).await; Ok(Json(json!({ "approval": a }))) } @@ -1282,14 +1284,17 @@ pub async fn link_answer( ) .await { - Ok(_) => page( - StatusCode::OK, - "Approval recorded", - &format!( + Ok(a) => { + super::run_wake::approval_answered(&state, &c.team_id, &a.run_id, &a.id).await; + page( + StatusCode::OK, + "Approval recorded", + &format!( "

{}

The agent carries on with your answer. You can close this page.

", if approve { "Approved once." } else { "Denied." } ), - ), + ) + } Err(e) => page( StatusCode::CONFLICT, "Approval", diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 260134662..08fceabfe 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -832,7 +832,16 @@ async fn handle_notification( episodes::post_cleared(&posting, &route.team_id, old).await; } let opens_episode = matches!(decision, Some(Decision::Opened | Decision::Reopened(_))); - let decided = decide(state, msg, route, rule, &alert, &tid).await; + // The alert fired again while its run waits on a person: that + // run goes on (`run_wake`), and no second run starts. + let decided = if route.enabled + && super::run_wake::alert_delivery(state, &route.team_id, &tid, false).await + { + info!(topic = %msg.topic_arn, ticket = %tid, "Alert fired again: its waiting run goes on"); + Ok(Outcome::RunStarted) + } else { + decide(state, msg, route, rule, &alert, &tid).await + }; if decided.is_err() && opens_episode { // SNS retries this delivery: let it open the episode again. forget_episode( @@ -848,6 +857,8 @@ async fn handle_notification( } Plan::Recover => { let fp = alert.recovers.as_deref().unwrap_or_default(); + // Its run waiting on a person has nothing left to fix. + super::run_wake::alert_delivery(state, &route.team_id, &ticket_id(fp), true).await; let opened = alert_notify::close_open_alert( &state.dynamo, &state.config.settings_table_name, diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index fd89bbffb..0feadf306 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -975,7 +975,7 @@ pub struct RunWaitingOn { pub action: String, /// Why, or what is still open. May be empty. #[schema( - example = "Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there." + example = "Open on the pull request: the link check couldn't reach /pricing. Push a fix or comment on it, and CoderHelm picks it up from there." )] pub detail: String, /// Where to do it (the pull request, the ticket), when known. @@ -2862,6 +2862,29 @@ pub(crate) async fn retry_message( state: &AppState, claims: &Claims, item: &std::collections::HashMap, +) -> Result { + retry_message_as( + state, + &claims.team_id, + claims + .github_login + .clone() + .unwrap_or_else(|| claims.email.clone()), + common::requester::Requester::member(claims.github_login.as_deref(), &claims.email), + item, + ) + .await +} + +/// [`retry_message`] for `team_id`, started for `sender` (who `requester` +/// names): a person's Retry, or CoderHelm itself when what a waiting run +/// waited for arrived (`run_wake`). +pub(crate) async fn retry_message_as( + state: &AppState, + team_id: &str, + sender: String, + requester: Option, + item: &std::collections::HashMap, ) -> Result { let repo = item .get("repo") @@ -2880,7 +2903,7 @@ pub(crate) async fn retry_message( .and_then(|n| n.parse::().ok()) .unwrap_or(0); if installation_id == 0 { - installation_id = get_team_installation_id(state, &claims.team_id).await?; + installation_id = get_team_installation_id(state, team_id).await?; } let issue_number = item .get("issue_number") @@ -2925,7 +2948,7 @@ pub(crate) async fn retry_message( }; Ok(TicketMessage { - team_id: claims.team_id.clone(), + team_id: team_id.to_string(), installation_id, source, ticket_id: ticket_id.to_string(), @@ -2939,14 +2962,8 @@ pub(crate) async fn retry_message( repo_owner: retry_owner, repo_name: retry_name, issue_number, - sender: claims - .github_login - .clone() - .unwrap_or_else(|| claims.email.clone()), - requester: common::requester::Requester::member( - claims.github_login.as_deref(), - &claims.email, - ), + sender, + requester, image_attachments: item .get("image_attachments") .and_then(|v| v.as_s().ok()) @@ -4881,6 +4898,19 @@ pub async fn update_repo( })?; } + // A run that waited for this repository to be turned on goes on by + // itself (`run_wake`). + if enabled { + super::run_wake::wake_team( + &state, + &claims.team_id, + common::run_wake::Wake::Access, + std::slice::from_ref(&repo), + &format!("{repo} was turned on for runs"), + ) + .await; + } + // When enabling a repo, trigger onboarding to generate voice, instructions, etc. if enabled { let installation_id = get_team_installation_id(&state, &claims.team_id).await?; @@ -5968,6 +5998,7 @@ pub async fn update_budget( })?; // Knowledge sources the limit stopped look for room now. super::knowledge_sources::resume_budget_stopped(&state, &claims.team_id).await; + wake_after_limit(&state, &claims.team_id).await; return Ok(StatusCode::OK); } @@ -5991,10 +6022,29 @@ pub async fn update_budget( StatusCode::INTERNAL_SERVER_ERROR })?; super::knowledge_sources::resume_budget_stopped(&state, &claims.team_id).await; + wake_after_limit(&state, &claims.team_id).await; Ok(StatusCode::OK) } +/// The limits were saved: when they now allow runs, the runs that waited +/// for the limit go on by themselves (`run_wake`). +async fn wake_after_limit(state: &AppState, team_id: &str) { + if super::github_webhook::check_run_budget(state, team_id) + .await + .is_none() + { + super::run_wake::wake_team( + state, + team_id, + common::run_wake::Wake::Limit, + &[], + "the team's usage limit allowed runs again", + ) + .await; + } +} + /// GET /api/usage — token usage for the current month + configured limits. #[utoipa::path( get, diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 67fe6870c..efb171bd2 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -428,6 +428,20 @@ async fn route( let team = resolve_team_by_installation(state, installation_id) .await .unwrap_or_default(); + // Access granted on GitHub: the runs that waited for it go on by + // themselves (`run_wake`). + if let Some(added) = super::run_wake::access_granted(event_type, payload) { + if !team.is_empty() && r.is_ok() { + super::run_wake::wake_team( + state, + &team, + common::run_wake::Wake::Access, + &added, + "GitHub reported the access granted", + ) + .await; + } + } d.target = team.clone(); return (r, team); } diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index a3a0db0b4..58b5cdd31 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -807,6 +807,7 @@ async fn process_jira_payload( ..Default::default() }, ))), + ..Default::default() }); let result = send_to_queue(state, &state.config.ticket_queue_url, &message).await; let repo_display = format!("{}/{}", pr.repo_owner, pr.repo_name); @@ -1430,6 +1431,10 @@ async fn handle_jira_comment( let expected_keys = super::trigger_gate::expected_attachment_keys(team_id, ticket_key, payload); let context_hash = common::ticket_context_hash(&fresh_title, &fresh_body, &expected_keys); + // A run that waits on a person: this comment is the answer, and the run + // it starts takes up the waiting run's plan and branch, as Retry does + // (`run_wake`). + let (resumes, waiting_for) = super::run_wake::comment_wakes(run_item); // What the comment would start if it asks for work: feedback on the // run's PR while that PR is open, otherwise a run with the comment as // added context. The worker reads the comment first and decides. @@ -1479,6 +1484,11 @@ async fn handle_jira_comment( .unwrap_or_default() }, ticket_type: common::messages::ticket_type_of_jira(issue), + resume_from: if resumes { + super::run_wake::resumed_from(run_item) + } else { + None + }, ..Default::default() }) }; @@ -1497,6 +1507,8 @@ async fn handle_jira_comment( comment: comment_body.to_string(), context_hash, action: Some(Box::new(action)), + resumes: Some(resumes), + waiting_for, }); info!( team_id, diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 5d11c1073..21817c6d9 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -97,6 +97,7 @@ pub mod run_outputs; pub mod run_search; pub mod run_start; pub mod run_trigger; +pub mod run_wake; pub mod scorecard; pub mod search; pub mod security; diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs new file mode 100644 index 000000000..291bb6d1c --- /dev/null +++ b/services/gateway/src/routes/run_wake.rs @@ -0,0 +1,575 @@ +//! Runs that wait on a person, started again by themselves when what they +//! wait for arrives (`common::run_wake`). +//! +//! - A comment or reply on the ticket: the webhooks send it to the worker +//! with [`comment_wakes`] (the run waits for it) and a ticket run that +//! takes up the waiting run's plan and branch ([`resumed_from`]), the way +//! Retry does. The worker reads the comment and starts that run. +//! - Access granted on GitHub (a repository added to the app's +//! installation, a permission accepted, the app installed again) or a +//! repository turned on for runs: [`wake_team`] with `Wake::Access`. +//! - The team's usage limit raised or cleared: [`wake_team`] with +//! `Wake::Limit`. +//! +//! - The approval an agent policy asked for answered: the same run goes on +//! with the work it kept ([`approval_answered`]), so the one-time grant +//! applies. +//! - An alert run (no ticket thread): the alert firing again resumes its +//! waiting run, and the alert clearing closes it ([`alert_delivery`]). +//! +//! A woken run is the same start as a person's Retry: the ticket again, +//! with the waiting run's plan and branch when its plan wasn't what stopped +//! it, and the waiting run marked as superseded by the new one. Only a run +//! still waiting is woken (a conditional write), so two events never start +//! two runs. A run whose new run couldn't be queued is put back to waiting +//! (`common::run_wake::put_back`), so a later event or a Retry starts it. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::run_ending::EndWrite; +use common::run_wait::WaitingOn; +use common::run_wake::{self, Wake}; +use serde_json::Value; +use tracing::{info, warn}; + +use crate::models::WorkerMessage; +use crate::AppState; + +type Item = HashMap; + +fn text<'a>(item: &'a Item, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|s| s.as_str()) + .unwrap_or("") +} + +/// Whether a comment on the ticket of the run `item` resumes it, and what +/// the run waits for (its wait's action), for the worker's reading of the +/// comment. +pub fn comment_wakes(item: &Item) -> (bool, String) { + let wait = WaitingOn::of_item(item).unwrap_or_default(); + let resumes = run_wake::wakes_run(text(item, "status"), &wait.handback, Wake::Comment); + (resumes, if resumes { wait.action } else { String::new() }) +} + +/// The run a ticket run started for a waiting run takes up (its plan and +/// branch), as Retry does: unless the plan was what stopped it +/// (`run_status::retry_resumes`). +pub fn resumed_from(item: &Item) -> Option { + let run_id = text(item, "run_id"); + let error = format!("{} {}", text(item, "error_message"), text(item, "error")); + (!run_id.is_empty() && common::run_status::retry_resumes(text(item, "current_pass"), &error)) + .then(|| run_id.to_string()) +} + +/// What GitHub's installation event grants: the repositories added (`Some` +/// with their full names), or access without a list (a permission +/// accepted, the app installed again or unsuspended: `Some` and empty). +/// `None` for an event that grants nothing. +pub fn access_granted(event_type: &str, payload: &Value) -> Option> { + let action = payload["action"].as_str().unwrap_or(""); + match (event_type, action) { + ("installation_repositories", "added") => Some( + payload["repositories_added"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r["full_name"].as_str().map(str::to_string)) + .collect::>(), + ) + .filter(|v| !v.is_empty()), + ("installation", "created" | "new_permissions_accepted" | "unsuspend") => Some(Vec::new()), + _ => None, + } +} + +/// The waiting runs of a team that `wake` starts again: waiting on a person +/// for what `wake` brings, and (for access) for one of `added` when it +/// names repositories. +pub fn woken<'a>(runs: &'a [Item], wake: Wake, added: &[String]) -> Vec<&'a Item> { + runs.iter() + .filter(|i| { + let wait = WaitingOn::of_item(i).unwrap_or_default(); + run_wake::wakes_run(text(i, "status"), &wait.handback, wake) + && (wake != Wake::Access + || run_wake::access_reaches( + text(i, "repo"), + &format!("{} {}", wait.action, wait.detail), + added, + )) + }) + .collect() +} + +/// Most waiting runs one event starts again. +const MAX_WOKEN: usize = 25; + +/// The team's runs that wait on a person, newest first. +async fn waiting_runs(state: &AppState, team_id: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut start: Option = None; + for _ in 0..10 { + let page = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("status-index") + .key_condition_expression("team_id = :tid AND begins_with(status_run_id, :p)") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":p", AttributeValue::S(format!("{}#", run_wake::WAITING))) + .scan_index_forward(false) + .limit(100) + .set_exclusive_start_key(start.take()) + .send() + .await; + let page = match page { + Ok(p) => p, + Err(e) => { + warn!(team_id, error = %e, "Could not read the team's waiting runs"); + break; + } + }; + out.extend(page.items().iter().cloned()); + match page.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => break, + } + } + out +} + +/// Starts again every run of `team_id` that waits for what `wake` brings +/// (`added`: the repositories access was granted to, empty for access +/// without a list). `what`: what arrived, for the waiting run's ending. +/// Returns how many runs were started. +pub async fn wake_team( + state: &AppState, + team_id: &str, + wake: Wake, + added: &[String], + what: &str, +) -> usize { + let runs = waiting_runs(state, team_id).await; + let mut started = 0; + for item in woken(&runs, wake, added).into_iter().take(MAX_WOKEN) { + if wake_one(state, team_id, item, what).await { + started += 1; + } + } + if started > 0 { + info!(team_id, wake = ?wake, started, what, "Waiting runs started again by themselves"); + } + started +} + +/// Starts the waiting run `item` again as a person's Retry would, after the +/// run is marked superseded (only while it still waits): a security fix +/// run as a new request for its unit's findings as they stand now (the +/// Retry's own decision, `security::retry_event`), any other run as its +/// ticket again. When the new run can't be queued, the waiting run is put +/// back to waiting (`common::run_wake::put_back`). +async fn wake_one(state: &AppState, team_id: &str, item: &Item, what: &str) -> bool { + let run_id = text(item, "run_id").to_string(); + let ticket_id = text(item, "ticket_id").to_string(); + let start = match super::security::retry_event(state, team_id, &ticket_id, "CoderHelm").await { + Some(event) => Start::Security(event), + None => { + let mut ticket = match super::api::retry_message_as( + state, + team_id, + "CoderHelm".to_string(), + None, + item, + ) + .await + { + Ok(t) => t, + Err(_) => { + warn!( + run_id, + "A waiting run's ticket couldn't be read to start it again" + ); + return false; + } + }; + ticket.resume_from = resumed_from(item); + match serde_json::to_string(&WorkerMessage::Ticket(ticket)) { + Ok(b) => Start::Ticket(b), + Err(e) => { + warn!(run_id, error = %e, "Could not serialize the woken run's ticket"); + return false; + } + } + } + }; + let woken = common::run_ending::gate( + &run_id, + &common::run_ending::superseded(&format!( + "the run CoderHelm started by itself when {what}" + )), + ); + let woken_at = chrono::Utc::now().to_rfc3339(); + // Only a run still waiting: a second event, or a person's Retry + // meanwhile, already started it. + let ended = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.clone())) + .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .run_status(":s", &woken) + .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) + .expression_attribute_values(":t", AttributeValue::S(woken_at.clone())) + .send() + .await; + if ended.is_err() { + info!(run_id, "Waiting run already moved on — not started again"); + return false; + } + let queued = match start { + Start::Security(event) => super::security::queue_retry(state, event).await.is_ok(), + Start::Ticket(body) => { + super::api::delete_ticket_lock(state, team_id, &ticket_id).await; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(run_id, error = %e, "Could not queue the woken run's ticket"); + false + } + } + } + }; + if queued { + info!(run_id, what, "Waiting run started again by itself"); + return true; + } + // Back to waiting, so the next event or a Retry starts it. + run_wake::put_back( + &state.dynamo, + &state.config.runs_table_name, + item, + woken.sri_attr(), + &woken_at, + ) + .await; + false +} + +/// What a woken run is started again with. +enum Start { + /// A security fix run's new request for its unit's findings. + Security(crate::models::SecurityEventMessage), + /// The ticket message, serialized for the queue. + Ticket(String), +} + +/// A run of the team by id. +async fn run_item(state: &AppState, team_id: &str, run_id: &str) -> Option { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .consistent_read(true) + .send() + .await + .ok()? + .item +} + +/// The newest run of `ticket_id`, whatever its status. +async fn newest_of_ticket(state: &AppState, team_id: &str, ticket_id: &str) -> Option { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .ok()?; + out.items() + .iter() + .max_by(|a, b| text(a, "run_id").cmp(text(b, "run_id"))) + .cloned() +} + +/// The answer to approval `approval_id` sends the run that waited for it +/// on: the work it kept, as the same run, after the run is marked working +/// again (only while it still waits for this approval). A run that kept no +/// work starts again as Retry would. `true` when the run went on. +pub async fn approval_answered( + state: &AppState, + team_id: &str, + run_id: &str, + approval_id: &str, +) -> bool { + if run_id.is_empty() { + return false; + } + let Some(item) = run_item(state, team_id, run_id).await else { + return false; + }; + let wait = WaitingOn::of_item(&item).unwrap_or_default(); + if !run_wake::approval_resumes( + text(&item, "status"), + &wait.handback, + text(&item, "policy_approval"), + approval_id, + ) { + return false; + } + let kept = text(&item, common::run_recovery::FIELD_RESUME_MESSAGE).to_string(); + if kept.is_empty() { + return wake_one( + state, + team_id, + &item, + "the approval it waited for was answered", + ) + .await; + } + let back = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t REMOVE waiting_on", + ) + .condition_expression("#status = :waiting AND policy_approval = :a") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &common::run_ending::working(common::run_ending::Working::Queued, run_id), + ) + .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) + .expression_attribute_values(":a", AttributeValue::S(approval_id.to_string())) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await; + if back.is_err() { + return false; + } + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(kept) + .send() + .await + { + Ok(_) => { + info!(run_id, approval_id, "Approval answered: the run goes on"); + true + } + Err(e) => { + warn!(run_id, error = %e, "Could not send the approved run on"); + false + } + } +} + +/// An alert delivery for the alert whose run's ticket is `ticket_id`: +/// firing again (`cleared` false) resumes its waiting run as Retry would; +/// clearing closes it, since nothing is left to fix. `true` when the run +/// moved (a firing then starts no second run). +pub async fn alert_delivery( + state: &AppState, + team_id: &str, + ticket_id: &str, + cleared: bool, +) -> bool { + let Some(item) = newest_of_ticket(state, team_id, ticket_id).await else { + return false; + }; + let wait = WaitingOn::of_item(&item).unwrap_or_default(); + match run_wake::alert_wake(text(&item, "status"), &wait.handback, cleared) { + Some(run_wake::AlertWake::Resume) => { + wake_one(state, team_id, &item, "its alert fired again").await + } + Some(run_wake::AlertWake::Close) => close_cleared(state, team_id, &item).await, + None => false, + } +} + +/// Closes a waiting alert run whose alert cleared by itself. +async fn close_cleared(state: &AppState, team_id: &str, item: &Item) -> bool { + let run_id = text(item, "run_id").to_string(); + let why = "the alert cleared by itself, so nothing is left to fix"; + let closed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.clone())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t, \ + progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", + ) + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &common::run_ending::gate( + &run_id, + &common::run_ending::RunEnd::Stopped(common::run_ending::Stopped { + reason: common::run_ending::Stop::ClosedBy { + who: "CoderHelm".into(), + why: why.into(), + }, + tried: Default::default(), + }), + ), + ) + .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values( + ":n", + AttributeValue::L(vec![AttributeValue::M(HashMap::from([ + ( + "message".to_string(), + AttributeValue::S(format!("Closed: {why}.")), + ), + ( + "timestamp".to_string(), + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ), + ]))]), + ) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await; + if closed.is_ok() { + info!(run_id, "Alert cleared: its waiting run closed"); + } + closed.is_ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn run(id: &str, status: &str, handback: &str, repo: &str, action: &str) -> Item { + let wait = WaitingOn { + action: action.into(), + handback: handback.into(), + ..Default::default() + }; + HashMap::from([ + ("run_id".to_string(), AttributeValue::S(id.into())), + ("status".to_string(), AttributeValue::S(status.into())), + ("repo".to_string(), AttributeValue::S(repo.into())), + ( + "current_pass".to_string(), + AttributeValue::S("implement".into()), + ), + ( + common::run_wait::FIELD_WAITING_ON.to_string(), + wait.to_attr(), + ), + ]) + } + + #[test] + fn a_comment_resumes_a_run_waiting_on_its_answer() { + let r = run( + "01A", + "needs_input", + "product_decision", + "acme/bookstore-web", + "Write the product decision in a comment on the ticket", + ); + let (resumes, waiting_for) = comment_wakes(&r); + assert!(resumes); + assert!(waiting_for.starts_with("Write the product decision")); + // Retry's rule: the plan and branch are taken up after planning. + assert_eq!(resumed_from(&r).as_deref(), Some("01A")); + let limit = run("01B", "needs_input", "usage_limit", "", "Raise the limit"); + assert_eq!(comment_wakes(&limit), (false, String::new())); + let done = run("01C", "completed", "", "", "x"); + assert!(!comment_wakes(&done).0); + } + + #[test] + fn access_granted_wakes_the_runs_waiting_for_it() { + let runs = vec![ + run( + "01A", + "needs_input", + "missing_access", + "acme/bookstore-web", + "Give access", + ), + run( + "01B", + "needs_input", + "missing_access", + "acme/bookstore-api", + "Give access", + ), + run( + "01C", + "needs_input", + "product_decision", + "acme/bookstore-web", + "Decide", + ), + run( + "01D", + "needs_input", + "usage_limit", + "acme/bookstore-web", + "Raise", + ), + ]; + let added = vec!["acme/bookstore-web".to_string()]; + let ids = |v: Vec<&Item>| { + v.iter() + .map(|i| text(i, "run_id").to_string()) + .collect::>() + }; + assert_eq!(ids(woken(&runs, Wake::Access, &added)), vec!["01A"]); + assert_eq!(ids(woken(&runs, Wake::Access, &[])), vec!["01A", "01B"]); + assert_eq!(ids(woken(&runs, Wake::Limit, &[])), vec!["01D"]); + } + + #[test] + fn githubs_installation_events_say_what_access_they_grant() { + let added = + json!({"action": "added", "repositories_added": [{"full_name": "acme/bookstore-web"}]}); + assert_eq!( + access_granted("installation_repositories", &added), + Some(vec!["acme/bookstore-web".to_string()]) + ); + let removed = json!({"action": "removed", "repositories_removed": [{"full_name": "acme/bookstore-web"}]}); + assert_eq!(access_granted("installation_repositories", &removed), None); + for action in ["created", "new_permissions_accepted", "unsuspend"] { + assert_eq!( + access_granted("installation", &json!({ "action": action })), + Some(vec![]) + ); + } + assert_eq!( + access_granted("installation", &json!({"action": "deleted"})), + None + ); + } +} diff --git a/services/gateway/src/routes/ticket_comments.rs b/services/gateway/src/routes/ticket_comments.rs index 0713f403b..89068f77c 100644 --- a/services/gateway/src/routes/ticket_comments.rs +++ b/services/gateway/src/routes/ticket_comments.rs @@ -159,6 +159,7 @@ pub async fn receive(state: &AppState, inc: &Incoming<'_>) -> Result { @@ -376,7 +377,9 @@ pub async fn on_github_issue_comment( let name = payload["repository"]["name"].as_str().unwrap_or(""); let ticket_id = format!("GH-{number}"); let Some(run) = working_run(state, team_id, &ticket_id).await else { - return false; + // No run works on the issue: one that waits on a person for this + // answer goes on by itself (`run_wake`). + return answer_waiting_run(state, payload, installation_id, team_id, &ticket_id).await; }; if !run.repo.eq_ignore_ascii_case(&format!("{owner}/{name}")) { return false; @@ -431,6 +434,189 @@ pub async fn on_github_issue_comment( .is_ok() } +/// A person's comment on a GitHub issue whose newest run waits on a person +/// for it: kept, and sent to the worker with the issue's run that takes up +/// the waiting run (its plan and branch, as Retry does), so the run goes on +/// by itself. `false` when the issue's newest run doesn't wait for a +/// comment, or the commenter has no standing. +async fn answer_waiting_run( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, + ticket_id: &str, +) -> bool { + let owner = payload["repository"]["owner"]["login"] + .as_str() + .unwrap_or(""); + let name = payload["repository"]["name"].as_str().unwrap_or(""); + let Some(item) = newest_run(state, team_id, ticket_id, &format!("{owner}/{name}")).await else { + return false; + }; + let (resumes, waiting_for) = super::run_wake::comment_wakes(&item); + if !resumes { + return false; + } + let user = &payload["comment"]["user"]; + let author = user["login"].as_str().unwrap_or(""); + let kind = user["type"].as_str().unwrap_or(""); + let text = payload["comment"]["body"].as_str().unwrap_or(""); + if !tc::is_person(Source::Github, author, kind, text) { + return false; + } + if !super::github_webhook::may_start_work( + state, + team_id, + installation_id, + payload, + &payload["comment"], + "comment", + ) + .await + { + return false; + } + let id = payload["comment"]["id"] + .as_u64() + .map(|i| i.to_string()) + .unwrap_or_default(); + let issue = &payload["issue"]; + let field = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let run_id = field("run_id"); + // Kept as context for the run it starts, which reads the issue's + // comments; the worker reads this one first. + keep( + state, + &Incoming { + team_id, + installation_id, + source: Source::Github, + ticket_id, + comment_id: &id, + author, + author_kind: kind, + text, + ..Default::default() + }, + ) + .await; + let message = WorkerMessage::JiraComment(JiraCommentMessage { + team_id: team_id.to_string(), + installation_id, + ticket_id: ticket_id.to_string(), + title: issue["title"].as_str().unwrap_or("").to_string(), + run_id: run_id.clone(), + run_status: field("status"), + pr_number: 0, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + author: author.to_string(), + comment: text.to_string(), + context_hash: String::new(), + action: Some(Box::new(WorkerMessage::Ticket(answer_run( + team_id, + installation_id, + payload, + super::run_wake::resumed_from(&item), + )))), + resumes: Some(true), + waiting_for, + }); + let body = match serde_json::to_string(&message) { + Ok(b) => b, + Err(e) => { + warn!(error = %e, "Could not serialize the answer to a waiting run"); + return false; + } + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + info!( + ticket_id, + run_id, "Comment on a waiting run's issue: the run goes on" + ); + true + } + Err(e) => { + warn!(ticket_id, error = %e, "Could not send the answer to a waiting run"); + false + } + } +} + +/// The issue's run an answer to its waiting run starts: the issue as a +/// ticket, its commenter as the one asking, and the waiting run to take up. +pub fn answer_run( + team_id: &str, + installation_id: u64, + payload: &Value, + resume_from: Option, +) -> crate::models::TicketMessage { + let issue = &payload["issue"]; + let repo = &payload["repository"]; + let login = payload["comment"]["user"]["login"].as_str().unwrap_or(""); + crate::models::TicketMessage { + team_id: team_id.to_string(), + installation_id, + source: crate::models::TicketSource::Github, + ticket_id: format!("GH-{}", issue["number"].as_u64().unwrap_or(0)), + title: issue["title"].as_str().unwrap_or("").to_string(), + body: issue["body"].as_str().unwrap_or("").to_string(), + repo_owner: repo["owner"]["login"].as_str().unwrap_or("").to_string(), + repo_name: repo["name"].as_str().unwrap_or("").to_string(), + issue_number: issue["number"].as_u64().unwrap_or(0), + sender: login.to_string(), + requester: common::requester::Requester::github(login), + ticket_type: common::messages::ticket_type_of_github(issue), + resume_from, + ..Default::default() + } +} + +/// The issue's newest run in `repo`, whatever its status. +async fn newest_run( + state: &AppState, + team_id: &str, + ticket_id: &str, + repo: &str, +) -> Option> { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .map_err(|e| warn!(ticket_id, error = %e, "Could not look up the issue's runs")) + .ok()?; + let s = |i: &std::collections::HashMap, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + out.items() + .iter() + .filter(|i| s(i, "repo").eq_ignore_ascii_case(repo)) + .max_by_key(|i| s(i, "run_id")) + .cloned() +} + /// The ticket's run that is working now. struct WorkingRun { run_id: String, diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index d2f4394bb..ba1cd4322 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -605,6 +605,52 @@ pub fn claim_stop(run_id: &str) -> Option { .flatten() } +/// Keeps the work a loop stopped for an unanswered approval on its run +/// (`run_recovery::FIELD_RESUME_MESSAGE`), as the same run: the answer +/// sends it again (`gateway::routes::run_wake::approval_answered`), and the +/// one-time grant, kept for that run, lets the call through. +pub async fn keep_for_answer( + state: &WorkerState, + team_id: &str, + run_id: &str, + raw: &serde_json::Value, +) { + if run_id.is_empty() { + return; + } + let again = resume_as_same_run(raw, run_id); + let Ok(body) = serde_json::to_string(&again) else { + return; + }; + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key( + "team_id", + aws_sdk_dynamodb::types::AttributeValue::S(team_id.to_string()), + ) + .key( + "run_id", + aws_sdk_dynamodb::types::AttributeValue::S(run_id.to_string()), + ) + .update_expression("SET #m = :m") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#m", common::run_recovery::FIELD_RESUME_MESSAGE) + .expression_attribute_values(":m", aws_sdk_dynamodb::types::AttributeValue::S(body)) + .send() + .await; +} + +/// `raw` sent again as the same run: a ticket message continues `run_id`. +pub fn resume_as_same_run(raw: &serde_json::Value, run_id: &str) -> serde_json::Value { + let mut again = raw.clone(); + if again.get("type").and_then(|t| t.as_str()) == Some("ticket") { + again["continuation_run_id"] = serde_json::json!(run_id); + } + again +} + /// Ends a run a loop stopped: queued (agents paused; it resumes when the /// pause ends) or waiting for input (an approval nobody answered), with the /// note on the run. Never overwrites a run a person cancelled or closed. @@ -668,7 +714,7 @@ async fn write_run_stop( .needs_input( run_id, &WaitingOn::fixed( - "Answer the approval request this run is waiting on, then press Retry", + common::run_wake::APPROVAL_ACTION, &stop.note(), "", ), diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 3d3cbe014..2f2600a80 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -295,6 +295,14 @@ async fn handle_sqs(state: Arc, event: LambdaEvent) -> Re if let Some(step) = &admitted.step { passes::github_admission::release(&state, step).await; } + // A loop stopped for an approval nobody answered yet: keep the work + // on the run (as the same run, so the one-time grant applies) for + // the answer to send again (`gateway::routes::run_wake`). + if let (Some((common::agent_policy::Stop::TimedOut { .. }, run_id)), Some((team, _, _))) = + (&stopped, &work) + { + agent::policy::keep_for_answer(&state, team, run_id, &raw).await; + } // A loop stopped because agents were paused mid-run: keep the work // (as the same run) to pick up again when the pause ends. if let (Some((common::agent_policy::Stop::Paused { .. }, run_id)), Some((team, label, _))) = diff --git a/services/worker/src/passes/change_wait.rs b/services/worker/src/passes/change_wait.rs index 1e7c94395..ce7f13ff6 100644 --- a/services/worker/src/passes/change_wait.rs +++ b/services/worker/src/passes/change_wait.rs @@ -262,6 +262,11 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { None => {} } } + // Runs that stopped because their change closed: reopened, they wait + // for it again; merged, they go on (the 15-minute sweep reads them). + if team.is_none() { + out.resumed += check_closed(state).await; + } info!( waiting = out.waiting, resumed = out.resumed, @@ -271,6 +276,114 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { out } +/// Every run that stopped because the change it waited for closed: when +/// that change is reopened the run waits for it again, and when it merged +/// the run goes on. Returns how many went back. +async fn check_closed(state: &WorkerState) -> usize { + let filter = super::team_runs::Filter { + expr: "#s = :n AND attribute_exists(#w)", + names: vec![("#s", "status"), ("#w", cw::FIELD)], + values: vec![(":n", attr_s(common::run_wake::WAITING))], + projection: None, + }; + let items = super::team_runs::matching(state, "Runs whose change closed", &filter).await; + let mut back = 0; + for item in items { + if s(&item, "status") != common::run_status::NEEDS_INPUT { + continue; + } + // Only a run whose wait is the closed change's stop: a run that went + // on after its change merged keeps the field, and a later wait of + // another kind is that wait's to end. + let wait = common::run_wait::WaitingOn::of_item(&item).unwrap_or_default(); + if !cw::waits_on_close(&wait.action) { + continue; + } + let Some(dep) = Dependency::from_json(s(&item, cw::FIELD)) else { + continue; + }; + let Some((o, r)) = dep.repo.split_once('/') else { + continue; + }; + if dep.pr == 0 { + continue; + } + let Ok(gh) = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + n(&item, "installation_id"), + &state.http, + ) else { + continue; + }; + let pr = gh.get_pull_request(o, r, dep.pr).await.ok(); + let moved = cw::after_close(pr.as_ref().map(|p| { + ( + p["state"].as_str().unwrap_or("closed"), + p["merged"].as_bool().unwrap_or(false), + ) + })); + let Some(moved) = moved else { + continue; + }; + let team_id = s(&item, "team_id"); + let run_id = s(&item, "run_id"); + let line = cw::note(&dep); + // Back to waiting, only while it still waits on a person. + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, error_message = :em, current_pass = :cp, \ + updated_at = :t REMOVE waiting_on", + ) + .condition_expression("#s = :n") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(AWAITING_CHANGE)) + .expression_attribute_values( + ":sri", + common::run_ending::working(common::run_ending::Working::AwaitingChange, run_id) + .sri_attr(), + ) + .expression_attribute_values(":n", attr_s(common::run_wake::WAITING)) + .expression_attribute_values(":em", attr_s(&line)) + .expression_attribute_values(":cp", attr_s("waiting")) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if res.is_err() { + continue; + } + add_progress_note( + state, + team_id, + run_id, + &match moved { + cw::AfterClose::Reopened => { + format!( + "{} was reopened: the run waits for it to merge again", + dep.label() + ) + } + cw::AfterClose::Merged => { + format!("{} merged after all: the run goes on", dep.label()) + } + }, + ) + .await; + back += 1; + if moved == cw::AfterClose::Merged { + if let Some(now) = record(state, team_id, run_id).await { + check_one(state, &now).await; + } + } + } + back +} + /// `Some(true)`: resumed; `Some(false)`: stopped for a person; `None`: /// still waiting. async fn check_one(state: &WorkerState, item: &HashMap) -> Option { @@ -344,10 +457,7 @@ async fn check_one(state: &WorkerState, item: &HashMap) let needs = common::run_recovery::NeedsYou { kind: common::run_recovery::Kind::NeedsPerson, why: common::handback::HumanOnly::ProductDecision, - action: format!( - "Reopen and merge {}, or change this ticket, then press Retry", - dep.label() - ), + action: cw::closed_action(&dep), detail: reason, }; super::recover::stop_for_person( diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index 597b2578d..89667f131 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -1740,6 +1740,7 @@ pub async fn implement_result( outside_plan: Vec::new(), refused: Vec::new(), owed: Vec::new(), + description_rebuild: false, evidence: super::proof::RunEvidence { notes: run.report_md(), checks: run diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 72017b930..3a7312112 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -2605,8 +2605,10 @@ fn suite_passed(evidence: &[String]) -> bool { .is_some_and(|l| l.starts_with("Full test suite passed")) } -/// The tool a person's comment reaches the PR description through. -fn update_description_tool() -> ToolDefinition { +/// The tool a person's comment reaches the PR description through. A fix +/// round CoderHelm started itself has it too (`implement`): there it asks +/// for the description to be rebuilt from the branch. +pub(crate) fn update_description_tool() -> ToolDefinition { ToolDefinition { name: "update_pr_description".to_string(), description: "Change this pull request's description as the person asked (remove a \ @@ -2632,7 +2634,7 @@ fn update_description_tool() -> ToolDefinition { /// What people asked to change in the PR description this round, and /// whether the person who asked may have it changed. -struct DescriptionRequests { +pub(crate) struct DescriptionRequests { allowed: bool, /// A person triggered the round (false: CoderHelm's own review or a /// follow-up it sent itself). @@ -2648,7 +2650,7 @@ impl DescriptionRequests { Self::for_round(allowed, true) } - fn for_round(allowed: bool, person: bool) -> Self { + pub(crate) fn for_round(allowed: bool, person: bool) -> Self { Self { allowed, person, @@ -2659,12 +2661,12 @@ impl DescriptionRequests { /// The round asked for a rebuild from the branch (no person's words to /// apply). - fn wants_rebuild(&self) -> bool { + pub(crate) fn wants_rebuild(&self) -> bool { self.rebuild.load(std::sync::atomic::Ordering::Relaxed) } /// Records one request and says what happens with it. - fn ask(&self, change: &str) -> String { + pub(crate) fn ask(&self, change: &str) -> String { let change = change.split_whitespace().collect::>().join(" "); if change.is_empty() { return "Say what to change in the description.".to_string(); @@ -4837,7 +4839,9 @@ mod description_request_tests { .contains("never answer that you cannot edit the description")); // The round's instructions and the tool are in every round. let src = include_str!("feedback.rs"); - let run = &src[..src.find("\nfn update_description_tool()").unwrap()]; + let run = &src[..src + .find("\npub(crate) fn update_description_tool()") + .unwrap()]; assert!(run.contains("tools.push(update_description_tool());\n let mut full_system")); assert!(run.contains("common::description_handoff::ROUND_NOTE")); } diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 5ae036c26..5c24c9a4b 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -878,6 +878,41 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { out } +/// The run page's note for a fix round on the check's items: what each item +/// is, in a person's words (its first sentence), never the instructions the +/// coding model gets for it (which name CoderHelm's own tools and arguments: +/// "Put it back with `restore_file` (omit `from_ref`)", "say why in your +/// Evidence"). Those stay in [`fix_feedback`]. +pub fn fixing_note(lines: &[String]) -> String { + let items: Vec = lines.iter().map(|l| person_line(l)).collect(); + let n = items.len(); + common::rendered::clip( + &format!( + "Tests and scope check found {}; CoderHelm is fixing {} now. {}", + if n == 1 { + "1 item".to_string() + } else { + format!("{n} items") + }, + if n == 1 { "it" } else { "them" }, + items.join(" ") + ), + 700, + ) +} + +/// One blocking line as a person reads it: its first sentence, which says +/// what is wrong; what follows is the model's instruction. +pub fn person_line(line: &str) -> String { + let first = line + .split(". ") + .next() + .unwrap_or(line) + .trim() + .trim_end_matches('.'); + format!("{first}.") +} + /// The fix round's instructions. pub fn fix_feedback(lines: &[String]) -> String { format!( @@ -1952,17 +1987,7 @@ async fn check_and_fix( }; w.ledger.update(|l| l.habits.start_fix(licence)); w.save_ledger().await; - super::add_progress_note( - w.state, - &w.msg.team_id, - w.run_id, - &format!( - "Tests and scope check found {} item(s), fixing: {}", - blocking.len(), - common::truncate_str(&blocking.join(" "), 600) - ), - ) - .await; + super::add_progress_note(w.state, &w.msg.team_id, w.run_id, &fixing_note(&blocking)).await; let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; let fixed = super::implement::run( w.state, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 36383da83..58b2daec0 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -119,6 +119,10 @@ pub struct ImplementResult { /// counts as cut short, and the round continues in a fresh step that /// runs them first ([`owed_first`]). pub owed: Vec, + /// A fix round asked for the pull request's description to be rebuilt + /// (`update_pr_description`): the round's caller rebuilds it from the + /// branch, whether or not the round pushed code. + pub description_rebuild: bool, } /// The name an owed `run_checks` call carries in [`ImplementResult::owed`]. @@ -717,6 +721,14 @@ pub async fn run( ); tools.push(super::github_history::tool()); full_system.push_str(super::github_history::prompt_line()); + // A fix round on the pull request has the same description tool a + // person's comment round has, with the same guard: a round CoderHelm + // started (no person's wording) gets the description rebuilt from the + // branch, never an edit a person has to paste in. + let description = review_feedback.map(|_| { + tools.push(super::feedback::update_description_tool()); + super::feedback::DescriptionRequests::for_round(false, false) + }); // The code graph: exact structural lookups so the coder (and CI fixes, // which run through here) KNOWS who calls what it's changing. A repo // without a graph yet gets its first build queued here. @@ -939,6 +951,7 @@ pub async fn run( team_id: &msg.team_id, script_repos, script_runs: std::sync::atomic::AtomicUsize::new(0), + description, }; // Attach the ticket's design mockups as images — the implementer must SEE @@ -1376,6 +1389,10 @@ pub async fn run( // A file this round (or the rounds before it) changed and then put // back leaves no commit of its own on the pull request. super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch).await; + let description_rebuild = executor + .description + .as_ref() + .is_some_and(|d| d.wants_rebuild()); // How much the build explored before its first write, and whether it // started from the code map: kept on the run to compare runs with and // without one. @@ -1409,6 +1426,7 @@ pub async fn run( // Run by the settle stage, after the coder. audits: Vec::new(), }, + description_rebuild, }) } @@ -4250,6 +4268,9 @@ struct CombinedWriteToolExecutor<'a> { script_repos: Vec, /// Skill scripts this pass ran. script_runs: std::sync::atomic::AtomicUsize, + /// What a fix round asked of the pull request's description (`None` + /// outside a fix round: there is no description to change yet). + description: Option, } #[async_trait::async_trait] @@ -4261,6 +4282,13 @@ impl<'a> ToolExecutor for CombinedWriteToolExecutor<'a> { ) -> Result> { // Every call counts toward the exploration before the first write. self.write_executor.explore.counter.call(); + if name == "update_pr_description" { + if let Some(d) = &self.description { + return Ok(serde_json::json!( + d.ask(input["change"].as_str().unwrap_or("")) + )); + } + } if name == "bash" { if let Some(out) = self.bash_with_tools(input).await? { return Ok(out); diff --git a/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs b/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs index e003d5e1b..b010ca223 100644 --- a/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs +++ b/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs @@ -70,7 +70,11 @@ async fn an_unclassified_error_is_tried_once_then_needs_you_never_failed() { assert!(!w.run_to_end(6).await); let n = w.stopped.clone().expect("stopped for a person"); assert_eq!(n.why, common::handback::HumanOnly::Unrepaired); - assert!(n.action.contains("press Retry")); + assert!( + n.action.contains("the run continues by itself"), + "{}", + n.action + ); assert!(n.detail.contains("tried again once")); assert_eq!(rr::classify(odd).kind, Kind::Unknown); // The one failed-status write never writes it as failed. diff --git a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs new file mode 100644 index 000000000..234046405 --- /dev/null +++ b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs @@ -0,0 +1,306 @@ +//! wz. The second pass of the same sweep (`wx`) found texts that still +//! handed people work CoderHelm does, or promised what didn't happen. A run +//! stopped for a person said "Look at what stopped the run, put it right, +//! then press Retry", and a comment on its ticket was only kept as context: +//! the person answered and the run went on waiting. A merged-ticket stop +//! said "reply on the ticket" as if a reply started a run. A wrong-repo +//! note said "set the repo and re-run" without saying where, after a reason +//! cut mid-word. A tests-and-scope note quoted the coding model's own +//! instruction ("Put it back with `restore_file` (omit `from_ref`)"). A fix +//! round wrote that it had "no tool that edits the PR description, so +//! someone needs to paste in the replacement sections". An outside-change +//! report asked a person to add pull request labels CoderHelm adds itself, +//! and to "run the command yourself". The updater said "press Update +//! again" when AWS was busy, and the access check said to delete a failed +//! stack and press Update again. +//! +//! Guarantees: a run that waits on a person goes on by itself when what it +//! waits for arrives: a comment or reply on its ticket, access granted on +//! GitHub or a repository turned on, the usage limit raised +//! (`common::run_wake`). Its action names the one thing to do and where, +//! and says so. Notes a person reads never carry the model's instructions. +//! Every fix round can ask for the description to be rebuilt. Labels are +//! CoderHelm's. The updater waits out a busy stack or AWS throttling and +//! starts the update again itself; a failed stack in another account gets +//! one action for an AWS admin. `rendered::person_text` holds each text. + +use common::handback::HumanOnly; +use common::rendered::person_text; +use common::run_recovery::{person_action, unknown_stop, Classified, Kind}; + +const RUN_RECOVERY: &str = include_str!("../../../../common/src/run_recovery.rs"); +const RUN_FAIL: &str = include_str!("../../../../common/src/run_fail.rs"); +const JIRA_WEBHOOK: &str = include_str!("../../../../gateway/src/routes/jira_webhook.rs"); +const TICKET_COMMENTS: &str = include_str!("../../../../gateway/src/routes/ticket_comments.rs"); +const GITHUB_WEBHOOK: &str = include_str!("../../../../gateway/src/routes/github_webhook.rs"); +const API: &str = include_str!("../../../../gateway/src/routes/api.rs"); +const IMPLEMENT: &str = include_str!("../implement.rs"); +const RESUME: &str = include_str!("../resume.rs"); +const PERMISSIONS: &str = include_str!("../../../../common/src/live/permissions.rs"); +const UPDATER: &str = include_str!("../../../../../lambda/updater/handler.py"); +const RECOVER: &str = include_str!("../recover.rs"); +const PASSES_MOD: &str = include_str!("../mod.rs"); +const CHANGE_WAIT: &str = include_str!("../change_wait.rs"); +const POLICY: &str = include_str!("../../agent/policy.rs"); +const MAIN: &str = include_str!("../../main.rs"); +const AGENT_POLICY_ROUTES: &str = include_str!("../../../../gateway/src/routes/agent_policy.rs"); +const ALERTS: &str = include_str!("../../../../gateway/src/routes/alerts.rs"); + +#[test] +fn a_wait_says_the_run_goes_on_by_itself() { + for why in common::handback::HUMAN_ONLY { + let a = person_action(*why); + assert_eq!(person_text(&a), None, "{why:?}: {a}"); + assert!(!a.contains("then press Retry"), "{why:?}: {a}"); + match why { + // A decision about the run itself, made where it is made. + HumanOnly::Approval | HumanOnly::PersonAction => {} + _ => assert!(a.contains("continues by itself"), "{why:?}: {a}"), + } + } + let odd = Classified { + kind: Kind::Unknown, + repair: None, + person: None, + plain: "The frobnicator answered something nobody expected.".into(), + signature: "s".into(), + }; + let n = unknown_stop(&odd, 1); + assert!(!n.action.contains("put it right"), "{}", n.action); + assert!( + n.action.contains("the run continues by itself"), + "{}", + n.action + ); + for src in [RUN_RECOVERY, RUN_FAIL] { + assert!(!src.contains("then press Retry\"")); + assert!(!src.contains("put it right, then")); + } +} + +#[test] +fn a_comment_on_a_waiting_run_resumes_it() { + use crate::passes::jira_comment::{decide_waiting, Act, ActionKind}; + use common::ticket_state::Intent; + // "Done, I granted the access", "use the second reading", a question + // back: each resumes the run that waits for it. + for intent in [ + None, + Some(Intent::NewRequirement), + Some(Intent::Other), + Some(Intent::Question), + ] { + assert_eq!(decide_waiting(intent, true, ActionKind::Run), Act::Dispatch); + } + // Which runs a comment wakes: the gateway reads the run's wait. + assert!(common::run_wake::wakes_run( + "needs_input", + HumanOnly::ProductDecision.code(), + common::run_wake::Wake::Comment + )); + assert!(!common::run_wake::wakes_run( + "needs_input", + HumanOnly::UsageLimit.code(), + common::run_wake::Wake::Comment + )); + // Jira: the comment is sent with the wait, and the run it starts takes + // up the waiting run as Retry does. + assert!(JIRA_WEBHOOK.contains("super::run_wake::comment_wakes(run_item)")); + assert!(JIRA_WEBHOOK.contains("super::run_wake::resumed_from(run_item)")); + assert!(JIRA_WEBHOOK.contains("resumes: Some(resumes),")); + // GitHub: a plain comment on the issue of a waiting run, mention or not. + assert!(TICKET_COMMENTS.contains( + "return answer_waiting_run(state, payload, installation_id, team_id, &ticket_id).await;" + )); + // Access granted and the limit raised wake the runs that waited. + assert!(GITHUB_WEBHOOK.contains("super::run_wake::access_granted(event_type, payload)")); + assert!(API.contains("common::run_wake::Wake::Access,")); + assert!(API.contains("wake_after_limit(&state, &claims.team_id).await;")); +} + +#[test] +fn a_merged_ticket_promises_only_what_a_reply_does() { + use common::messages::TicketSource; + for s in [TicketSource::Jira, TicketSource::Github] { + let a = common::merged_ticket::wait_action(&s); + assert!(a.contains("the run continues by itself"), "{a}"); + assert_eq!(person_text(a), None, "{a}"); + } +} + +#[test] +fn the_wrong_repo_note_names_the_place_and_cuts_at_a_word() { + let why = "it holds the storefront's Next.js components for the bookstore's search page and \ + the shared product card with its price, cover image and stock badge, which the \ + ticket names, while the api repository only serves the search results as JSON \ + through the catalog endpoint and its pagination helpers, and the docs repository \ + only describes the search page for the bookstore's editors"; + let n = crate::passes::repo_pick::no_changes_repo_note("acme/bookstore-web", why); + assert_eq!(person_text(&n), None, "{n}"); + assert!(n.contains("`Repo: owner/name`"), "{n}"); + assert!(n.contains("by itself"), "{n}"); + assert!(!n.contains("set the repo and re-run"), "{n}"); + let quoted = n.split("Why that repo: ").nth(1).unwrap(); + let quoted = quoted.split(" If the work").next().unwrap(); + assert!(quoted.ends_with('…'), "{quoted}"); + let kept = quoted.trim_end_matches('…'); + assert!( + why[kept.len()..].starts_with(' '), + "cut inside a word: {quoted}" + ); +} + +#[test] +fn a_fix_note_says_what_is_wrong_never_the_models_instruction() { + let blocking = vec![ + "`package.json` was changed and is no task of the plan. Put it back with `restore_file` \ + (omit `from_ref`), or, when the change truly needs it, say why in your Evidence on a \ + line `Outside the plan: package.json: `." + .to_string(), + "`src/search/card.tsx` is only reformatted: the fix changes nothing in it. Put it back \ + with `restore_file` (omit `from_ref`)." + .to_string(), + ]; + let note = crate::passes::habits_check::fixing_note(&blocking); + assert_eq!( + note, + "Tests and scope check found 2 items; CoderHelm is fixing them now. `package.json` was \ + changed and is no task of the plan. `src/search/card.tsx` is only reformatted: the fix \ + changes nothing in it." + ); + assert_eq!(person_text(¬e), None, "{note}"); + // The model still gets its instructions. + let fb = crate::passes::habits_check::fix_feedback(&blocking); + assert!(fb.contains("restore_file")); + // The old note is caught. + assert!(person_text(&format!("fixing: {}", blocking[0])).is_some()); +} + +#[test] +fn every_fix_round_can_have_the_description_rebuilt() { + // The fix round has the description tool, with the writer's guard. + assert!(IMPLEMENT.contains("tools.push(super::feedback::update_description_tool());")); + assert!(IMPLEMENT.contains("super::feedback::DescriptionRequests::for_round(false, false)")); + assert!(RESUME.contains("let rebuild_description = handed_off || r.description_rebuild;")); + assert!(common::description_handoff::ROUND_NOTE.contains("update_pr_description")); + assert!(!common::description_handoff::ROUND_NOTE.contains("You have no tool")); + // The live sentence is caught and the description rebuilt. + let live = "I've corrected the docs. I have no tool that edits the PR description, so \ + someone needs to paste in the replacement sections below."; + let (round_summary, handed_off) = crate::passes::description::round_account(live); + assert!(handed_off); + assert!(!round_summary.contains("paste")); + assert!(person_text(live).is_some()); +} + +#[test] +fn labels_are_coderhelms_and_one_way_is_named() { + use common::pr_steps::{State, Step}; + let labels = Step { + what: "Add PR labels e2e:checkout and CI:E2E, sending the existing labels too, so the \ + preview deploy runs the checkout spec" + .into(), + how: String::new(), + when: Default::default(), + owner: "a repository admin".into(), + state: State::Person { + why: "labels".into(), + unblock: String::new(), + }, + }; + assert!(!labels.needs_person(), "{}", labels.line()); + let start = Step { + what: "Start the staging deploy workflow".into(), + how: "gh workflow run deploy-staging.yml".into(), + when: Default::default(), + owner: "a repository admin".into(), + state: State::Person { + why: "the GitHub app may not start workflows".into(), + unblock: "give the app \"Actions: write\" (GitHub, Settings, Installed GitHub Apps, \ + CoderHelm, Permissions), or run the command yourself" + .into(), + }, + }; + let line = start.line(); + assert!(!line.contains("yourself"), "{line}"); + assert!(line.contains("Actions: write"), "{line}"); +} + +#[test] +fn the_updater_waits_out_aws_and_names_one_admin_action() { + assert!(!UPDATER.contains("press Update again once it has finished")); + assert!(UPDATER.contains("raise AwsBusy(stack_busy_why(st))")); + assert!(!PERMISSIONS.contains("delete the failed stack, then press Update again")); + let fix = common::live::permissions::stack_failed_fix( + "ROLLBACK_COMPLETE", + "CoderHelmLogReaderUpdate", + "111122223333", + "us-east-1", + ); + assert!(fix.starts_with("An AWS admin in account 111122223333")); + assert_eq!(person_text(&fix), None); + // The API's own example no longer hands the ready mark to a person. + assert!(!API.contains("Mark it ready once")); +} + +/// The month resets the usage limit: the 15-minute sweep reads each waiting +/// team's limit and starts its waiting runs once it allows runs. +#[test] +fn a_limit_wait_wakes_when_the_limit_allows_runs_again() { + assert!(RECOVER.contains("report.woken = super::run_wake::wake_limit_waits(state).await;")); + let src = include_str!("../run_wake.rs"); + assert!(src.contains("super::check_budget_exceeded(state, &team).await.is_some()")); +} + +/// A change that closed: reopened, the run waits for it again; merged, it +/// goes on; a changed ticket starts a new run. Never "press Retry". +#[test] +fn a_reopened_change_takes_its_run_back() { + assert!(!CHANGE_WAIT.contains("then press Retry")); + assert!(CHANGE_WAIT.contains("action: cw::closed_action(&dep),")); + assert!(CHANGE_WAIT.contains("out.resumed += check_closed(state).await;")); + assert_eq!( + common::change_wait::after_close(Some(("open", false))), + Some(common::change_wait::AfterClose::Reopened) + ); +} + +/// An answer to the approval resumes the same run with the work it kept. +#[test] +fn an_answered_approval_resumes_the_run_that_waited() { + assert!(!POLICY.contains("then press Retry")); + assert!(POLICY.contains("common::run_wake::APPROVAL_ACTION")); + assert!(MAIN.contains("agent::policy::keep_for_answer(&state, team, run_id, &raw).await;")); + assert_eq!( + AGENT_POLICY_ROUTES + .matches("super::run_wake::approval_answered(") + .count(), + 2, + "both ways of answering (the dashboard and the signed link)" + ); + let again = crate::agent::policy::resume_as_same_run( + &serde_json::json!({"type": "ticket", "ticket_id": "WEB-7"}), + "01RUN", + ); + assert_eq!(again["continuation_run_id"], "01RUN"); + assert_eq!(person_text(common::run_wake::APPROVAL_ACTION), None); +} + +/// An alert run has no thread: firing again resumes it, clearing closes +/// it, and its wait says what to do first. +#[test] +fn an_alert_run_resumes_or_closes_with_its_alert() { + assert!(ALERTS.contains("super::run_wake::alert_delivery(state, &route.team_id, &tid, false)")); + assert!(ALERTS + .contains("super::run_wake::alert_delivery(state, &route.team_id, &ticket_id(fp), true)")); + assert!(PASSES_MOD.contains("common::run_wake::for_alert(&wait.action)")); + assert!(PASSES_MOD.contains("alert: matches!(msg.source, TicketSource::Alert),")); + assert!(RECOVER.contains("alert: matches!(msg.source, crate::models::TicketSource::Alert),")); + let a = common::run_wake::for_alert(&person_action(HumanOnly::Unrepaired)); + assert!( + a.contains("Once that is done, press Retry on the run page"), + "{a}" + ); + assert!(!a.contains("comment"), "{a}"); + assert_eq!(person_text(&a), None, "{a}"); +} diff --git a/services/worker/src/passes/jira_comment.rs b/services/worker/src/passes/jira_comment.rs index 8990cb6d5..ab19cf80d 100644 --- a/services/worker/src/passes/jira_comment.rs +++ b/services/worker/src/passes/jira_comment.rs @@ -16,6 +16,11 @@ //! //! Every comment read is kept on the ticket's record, so the next plan sees //! what people wrote. +//! +//! A comment on a run that waits on a person is that person's answer +//! (`common::run_wake`): it resumes the run, whatever words it uses, unless +//! it only reports status or says the work is done elsewhere. A question +//! back is read by the resumed run, which asks again only if it must. use crate::agent::provider::ModelProvider; use crate::models::{JiraCommentMessage, TokenUsage, WorkerMessage}; @@ -54,26 +59,37 @@ fn action_kind(a: Option<&WorkerMessage>) -> ActionKind { } } +/// Whether the comment answers a run that waits for it: the gateway says so +/// for a run that waits on a person (`common::run_wake::wakes`); a message +/// that doesn't say takes a `needs_input` or `failed` run as waiting. +pub fn waits_for_answer(resumes: Option, run_status: &str) -> bool { + resumes.unwrap_or(matches!(run_status, "needs_input" | "failed")) +} + /// Whether a comment that starts a run is a person's direction for it: it -/// asks for the work, or it answers CoderHelm's own question on a waiting -/// run (whatever words it uses). -pub fn is_direction(intent: Option, run_status: &str) -> bool { - let waiting_for_answer = matches!( - run_status, - "needs_input" | "needs_outside_change" | "failed" - ); +/// asks for the work, or it answers a waiting run (whatever words it uses). +pub fn is_direction(intent: Option, waiting: bool, run_status: &str) -> bool { + let waiting_for_answer = waiting || run_status == "needs_outside_change"; match intent { Some(Intent::NewRequirement) => true, - None | Some(Intent::Other) => waiting_for_answer, + None | Some(Intent::Other | Intent::Question) => waiting_for_answer, _ => false, } } -/// The decision. `intent` is `None` when the model couldn't read the comment: -/// feedback on an open PR (which reads it again) and an answer to -/// CoderHelm's own question still go ahead; nothing else starts a run. +/// The decision for a run with `run_status` (see [`decide_waiting`]). +#[cfg(test)] pub fn decide(intent: Option, run_status: &str, action: ActionKind) -> Act { - let waiting_for_answer = matches!(run_status, "needs_input" | "failed"); + decide_waiting(intent, waits_for_answer(None, run_status), action) +} + +/// The decision. `intent` is `None` when the model couldn't read the comment: +/// feedback on an open PR (which reads it again) and an answer to a waiting +/// run still go ahead; nothing else starts a run. `waiting`: the run waits +/// for this person's answer, so any reply but a status report or "done +/// elsewhere" resumes it. +pub fn decide_waiting(intent: Option, waiting: bool, action: ActionKind) -> Act { + let waiting_for_answer = waiting; match (intent, action) { (_, ActionKind::None) => match intent { Some(Intent::FixElsewhereInfo) => Act::Elsewhere { @@ -85,6 +101,9 @@ pub fn decide(intent: Option, run_status: &str, action: ActionKind) -> A (None, ActionKind::Run) if waiting_for_answer => Act::Dispatch, (None, ActionKind::Run) => Act::Nothing, (Some(Intent::NewRequirement), _) => Act::Dispatch, + (Some(Intent::Question | Intent::Other), ActionKind::Run) if waiting_for_answer => { + Act::Dispatch + } (Some(Intent::Question), ActionKind::Feedback) => Act::Dispatch, (Some(Intent::Question), _) => Act::Nothing, (Some(Intent::FixElsewhereInfo), kind) => Act::Elsewhere { @@ -96,8 +115,9 @@ pub fn decide(intent: Option, run_status: &str, action: ActionKind) -> A pub const SYSTEM: &str = "You read one comment a person wrote on a ticket that an automated \ coding agent (CoderHelm) already worked on, and say what the comment is. \ - new_requirement: it asks for new or different work in the code, or answers the agent's \ - question with details it needs to do the work. \ + new_requirement: it asks for new or different work in the code, answers the agent's \ + question with details it needs to do the work, or says the person did what the agent was \ + waiting for (granted access, added a credential, restored a branch, made the decision). \ fix_elsewhere_info: it says the issue was fixed, or belongs, somewhere other than the code \ (a setting or data in another system, a manual change), or that it is resolved or no longer \ needed. \ @@ -120,7 +140,15 @@ pub fn schema() -> serde_json::Value { } pub fn prompt(msg: &JiraCommentMessage) -> String { + let waiting_for; let state = match msg.run_status.as_str() { + "needs_input" if !msg.waiting_for.trim().is_empty() => { + waiting_for = format!( + "CoderHelm's run is waiting on a person for this: {}", + common::truncate_str(msg.waiting_for.trim(), 600) + ); + waiting_for.as_str() + } "needs_input" => "CoderHelm asked a question on the ticket and is waiting for an answer.", "failed" => "CoderHelm's last run on the ticket failed.", "needs_outside_change" => { @@ -365,7 +393,8 @@ pub async fn run( let mut usage = TokenUsage::default(); let intent = classify(state, &provider, &msg, &mut usage).await; let kind = action_kind(msg.action.as_deref()); - let act = decide(intent, &msg.run_status, kind); + let waiting = waits_for_answer(msg.resumes, &msg.run_status); + let act = decide_waiting(intent, waiting, kind); info!( ticket_id = %msg.ticket_id, run_status = %msg.run_status, @@ -379,7 +408,7 @@ pub async fn run( intent: intent.unwrap_or(Intent::Other), at: chrono::Utc::now().to_rfc3339(), }; - let direction = is_direction(intent, &msg.run_status) + let direction = is_direction(intent, waiting, &msg.run_status) .then(|| format!("{}: {}", note.author, common::truncate_str(¬e.text, 600))); match act { Act::Dispatch => { @@ -488,8 +517,9 @@ mod tests { decide(Some(Intent::StatusOnly), "completed", kind), Act::Nothing ); + assert_eq!(decide(Some(Intent::Other), "completed", kind), Act::Nothing); assert_eq!( - decide(Some(Intent::Other), "needs_input", kind), + decide(Some(Intent::StatusOnly), "needs_input", kind), Act::Nothing ); } @@ -548,15 +578,59 @@ mod direction_tests { #[test] fn an_answer_to_a_waiting_run_is_a_direction() { - assert!(is_direction(Some(Intent::NewRequirement), "completed")); + assert!(is_direction( + Some(Intent::NewRequirement), + false, + "completed" + )); assert!( - is_direction(None, "needs_input"), + is_direction(None, true, "needs_input"), "unread answer to our question" ); - assert!(is_direction(Some(Intent::Other), "needs_outside_change")); - assert!(!is_direction(None, "completed")); - assert!(!is_direction(Some(Intent::Question), "needs_input")); - assert!(!is_direction(Some(Intent::StatusOnly), "needs_input")); - assert!(!is_direction(Some(Intent::FixElsewhereInfo), "needs_input")); + assert!(is_direction( + Some(Intent::Other), + false, + "needs_outside_change" + )); + assert!(!is_direction(None, false, "completed")); + assert!(is_direction(Some(Intent::Question), true, "needs_input")); + assert!(!is_direction(Some(Intent::StatusOnly), true, "needs_input")); + assert!(!is_direction( + Some(Intent::FixElsewhereInfo), + true, + "needs_input" + )); + } + + /// A run waiting on a person: the person's reply resumes it, whatever + /// its words ("done, access granted", "use the second reading", a + /// question back). A wait a comment can't answer (the usage limit, an + /// approval) isn't resumed by one. + #[test] + fn a_reply_to_a_waiting_run_resumes_it() { + for intent in [ + None, + Some(Intent::NewRequirement), + Some(Intent::Other), + Some(Intent::Question), + ] { + assert_eq!( + decide_waiting(intent, true, ActionKind::Run), + Act::Dispatch, + "{intent:?}" + ); + } + assert_eq!( + decide_waiting(Some(Intent::StatusOnly), true, ActionKind::Run), + Act::Nothing + ); + assert!(waits_for_answer(Some(true), "needs_input")); + assert!(!waits_for_answer(Some(false), "needs_input")); + assert!(waits_for_answer(None, "needs_input")); + assert!(!waits_for_answer(None, "completed")); + assert_eq!( + decide_waiting(Some(Intent::Other), false, ActionKind::Run), + Act::Nothing + ); } } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 007e218c6..7d979ad4e 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1479,6 +1479,7 @@ pub(crate) mod run_files; pub mod run_guard; pub(crate) mod run_lists; pub mod run_map; +pub mod run_wake; pub(crate) mod scope_ledger; mod security; pub mod security_fixes; @@ -4620,6 +4621,7 @@ false, outside_plan: Vec::new(), refused: Vec::new(), owed: Vec::new(), + description_rebuild: false, // The first attempt's lookups weren't kept; the proof check's // fix round can make them again. evidence: proof::RunEvidence { @@ -8426,6 +8428,7 @@ async fn run_repo_pipeline( outside_plan: Vec::new(), refused: Vec::new(), owed: Vec::new(), + description_rebuild: false, evidence: proof::RunEvidence { ci_gates: checks::kinds_from(&ci_commands), ci_commands, @@ -10380,7 +10383,7 @@ fn wait_on_ticket( questions, None, WaitingOn::fixed( - "Add the missing detail to the ticket, then press Retry", + "Add the missing detail to the ticket, or write it in a comment there; the run continues by itself when the ticket changes or the comment arrives", what, &ticket, ), @@ -10405,6 +10408,18 @@ async fn mark_run_needs_input( // question or blocker when it names one, else what this stop asks for // (a question about the ticket, a decision, access, a pull request // someone else holds). + // An alert run has no ticket thread: its wait says what to do first, + // then Retry on the run page (`run_wake::for_alert`). + let alerted; + let wait = if matches!(msg.source, TicketSource::Alert) { + alerted = WaitingOn { + action: common::run_wake::for_alert(&wait.action), + ..wait.clone() + }; + &alerted + } else { + wait + }; let hand_back = supervisor::HandBack::of_judged(judged).unwrap_or_else(|| { supervisor::HandBack::new(asked_for, &wait.line()) .unwrap_or(supervisor::HandBack::of(asked_for)) @@ -10486,7 +10501,11 @@ pub(crate) async fn mark_run_stopped_by_guard( .expression_attribute_names("#s", "status") .needs_input( run_id, - &WaitingOn::fixed("Give CoderHelm what it needs, then press Retry", reason, ""), + &WaitingOn::fixed( + "Give CoderHelm what the reason below names, then say so in a comment on the ticket; the run continues by itself when the comment arrives", + reason, + "", + ), &hand_back, ) .expression_attribute_values(":em", attr_s(reason)) @@ -10550,7 +10569,7 @@ async fn stop_run_repo_not_enabled( } } let wait = WaitingOn::fixed( - "Turn the repository on for runs in CoderHelm, then press Retry", + "Turn the repository on for runs in CoderHelm's Repositories page; the run continues by itself once it is on", message, "", ); @@ -11151,6 +11170,7 @@ async fn end_with( only_from: None, extra, add: usage_adds(&delta), + alert: matches!(msg.source, TicketSource::Alert), }; // The ending is decided once (`common::run_fail::update`): only an // error the self-heal sweep resumes is parked as `failed` with its diff --git a/services/worker/src/passes/recover.rs b/services/worker/src/passes/recover.rs index f7ad99c8d..d4587ea3d 100644 --- a/services/worker/src/passes/recover.rs +++ b/services/worker/src/passes/recover.rs @@ -590,6 +590,7 @@ pub async fn stop_for_person( only_from: None, extra: vec![("duration_s", attr_n(duration))], add: super::usage_adds(&delta), + alert: matches!(msg.source, crate::models::TicketSource::Alert), }; match common::run_fail::fail_run( &state.dynamo, @@ -660,6 +661,8 @@ pub struct SweepReport { pub skipped: usize, /// Runs waiting on CI with nothing set to look again, picked back up. pub redriven: usize, + /// Runs waiting on the usage limit started again once it allowed runs. + pub woken: usize, } /// The first start of each release (its code version) sends one self-heal @@ -851,6 +854,9 @@ pub async fn self_heal_sweep(state: &WorkerState) -> SweepReport { super::change_wait::check_all(state, None).await; // Runs waiting on CI with no check left to look at them again. report.redriven = super::resume::redrive_parked_waits(state).await; + // Runs waiting on the usage limit: started again once it allows runs + // (raised, cleared, or a new month). + report.woken = super::run_wake::wake_limit_waits(state).await; info!( failed = report.failed, waiting = report.waiting, @@ -858,6 +864,7 @@ pub async fn self_heal_sweep(state: &WorkerState) -> SweepReport { handed = report.handed, skipped = report.skipped, redriven = report.redriven, + woken = report.woken, "Self-heal sweep done" ); report diff --git a/services/worker/src/passes/repo_pick.rs b/services/worker/src/passes/repo_pick.rs index 625ff6d15..07489c044 100644 --- a/services/worker/src/passes/repo_pick.rs +++ b/services/worker/src/passes/repo_pick.rs @@ -43,33 +43,57 @@ pub fn pin_state(pin: &str, repos: &[TeamRepo]) -> PinState { } } +/// The ticket names a repository that is connected but not on for runs: the +/// run waits, and goes on by itself once the repository is turned on +/// (`run_wake`, from the Repositories switch). pub fn not_enabled_message(repo: &str) -> String { format!( "This ticket is for {repo}, which isn't turned on for CoderHelm runs. \ - Turn it on in Repositories and re-run." + Turn it on in CoderHelm's Repositories page; the run continues by itself once it is on." ) } +/// The ticket names a repository CoderHelm's GitHub app can't reach: the run +/// waits, and goes on by itself once GitHub reports the access. pub fn not_connected_message(repo: &str) -> String { format!( - "This ticket is for {repo}, which isn't connected to CoderHelm. \ - Connect it in Repositories and re-run." + "This ticket is for {repo}, which isn't connected to CoderHelm. Give the CoderHelm \ + GitHub app access to it on GitHub (Settings, Installed GitHub Apps, CoderHelm, \ + Repository access); the run continues by itself once GitHub reports the access." ) } +/// The longest "why that repo" a note quotes. +pub const MAX_PICK_WHY_CHARS: usize = 300; + +/// What a ticket writes to name its repository: a line the repo pick reads +/// first ([`ticket_named_repo`]). +pub fn repo_line(repo: &str) -> String { + format!("`Repo: {repo}`") +} + /// Note appended when the plan finds nothing to change in a repo CoderHelm /// picked itself, so the reader can tell a wrong-repo pick from a done ticket. +/// It names the one place a person sets the repository: a `Repo:` line in +/// the ticket's description, which the pick reads first. Editing the ticket +/// starts a new run by itself (the ticket's content changed). pub fn no_changes_repo_note(repo: &str, why: &str) -> String { - let why = why.trim(); + let why = common::rendered::clip(why.trim(), MAX_PICK_WHY_CHARS); + let set = format!( + "If the work belongs in a different repository, add a line {} to the ticket's \ + description; CoderHelm starts a new run there by itself when the ticket changes.", + repo_line("owner/name") + ); if why.is_empty() { - format!( - "CoderHelm picked {repo} for this ticket and looked there. \ - If the work belongs in a different repo, set the repo and re-run." - ) + format!("CoderHelm picked {repo} for this ticket and looked there. {set}") } else { + let why = if why.ends_with(['.', '!', '?', '…']) { + why + } else { + format!("{why}.") + }; format!( - "CoderHelm picked {repo} for this ticket and looked there. Why that repo: {why} \ - If the work belongs in a different repo, set the repo and re-run." + "CoderHelm picked {repo} for this ticket and looked there. Why that repo: {why} {set}" ) } } @@ -420,7 +444,8 @@ mod tests { assert_eq!( not_enabled_message("Acme/handbook-docs"), "This ticket is for Acme/handbook-docs, which isn't turned on for CoderHelm runs. \ - Turn it on in Repositories and re-run." + Turn it on in CoderHelm's Repositories page; the run continues by itself once it is \ + on." ); } @@ -569,7 +594,49 @@ mod tests { let n = no_changes_repo_note("Acme/api", "the ticket is about the billing endpoint."); assert!(n.contains("Acme/api")); assert!(n.contains("billing endpoint")); - assert!(n.contains("re-run")); + assert!( + n.contains("add a line `Repo: owner/name` to the ticket's description"), + "{n}" + ); + assert!(n.contains("starts a new run there by itself"), "{n}"); + assert_eq!(common::rendered::person_text(&n), None, "{n}"); + // The line the note names is the one the pick reads. + let repos = vec![TeamRepo { + full_name: "Acme/web".into(), + enabled: true, + }]; + assert_eq!( + ticket_named_repo( + "Fix the footer", + "Repo: Acme/web\nThe footer is off.", + &repos + ), + Some("Acme/web".to_string()) + ); + } + + /// A long "why" is cut at a word, never mid-word, and the note still + /// ends with where to set the repository. + #[test] + fn a_long_pick_reason_is_cut_at_a_word() { + let why = "The ticket asks for a change to the storefront's search results page, which \ + lives in the web repository's search components and the shared product card \ + that renders each result with its price, cover image and the stock badge for \ + bookstore titles, so the web repository fits the Next.js components the ticket \ + names better than the api repository does"; + let n = no_changes_repo_note("Acme/web", why); + let quoted = n + .split("Why that repo: ") + .nth(1) + .and_then(|r| r.split(" If the work").next()) + .unwrap(); + assert!(quoted.ends_with('…'), "{quoted}"); + let kept = quoted.trim_end_matches('…'); + assert!( + why[kept.len()..].starts_with(' '), + "cut inside a word: {quoted}" + ); + assert!(quoted.chars().count() <= MAX_PICK_WHY_CHARS + 1, "{quoted}"); } fn run( diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 655f8faf8..3b17af86b 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -5169,6 +5169,9 @@ async fn run_fix_round( warn!(run_id = %msg.run_id, "A fix round handed the description to a person; rebuilding it from the branch"); r.evidence.notes = account; } + // The round asked for the description through its tool, or + // handed it to a person: either way it is rebuilt now. + let rebuild_description = handed_off || r.description_rebuild; *refused = std::mem::take(&mut r.refused); let outside_plan = std::mem::take(&mut r.outside_plan); // What this round was asked and looked up reaches the next one. @@ -5224,7 +5227,7 @@ async fn run_fix_round( ) .await; } - if files > 0 || handed_off { + if files > 0 || rebuild_description { let _ = super::description::head_moved( &super::description::Moved { state, @@ -5259,7 +5262,7 @@ async fn run_fix_round( } super::round::Landed::Nothing => { super::round::clear(state, &msg.team_id, &msg.run_id).await; - if handed_off { + if rebuild_description { let _ = super::description::head_moved( &super::description::Moved { state, diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index d8a5a5692..8b337987e 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -1663,6 +1663,7 @@ async fn review_eval_live_ticket_comments() { comment: case.comment.clone(), context_hash: String::new(), action: None, + ..Default::default() }; let v = crate::agent::anthropic::converse_json( &client, diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 951602a28..ddebb088f 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1114,6 +1114,7 @@ async fn finish_open_pr(state: &WorkerState, team_id: &str, run_id: &str, reason only_from: None, extra: Vec::new(), add: Vec::new(), + alert: false, }; match common::run_fail::fail_run( &state.dynamo, diff --git a/services/worker/src/passes/run_wake.rs b/services/worker/src/passes/run_wake.rs new file mode 100644 index 000000000..9e0c57560 --- /dev/null +++ b/services/worker/src/passes/run_wake.rs @@ -0,0 +1,252 @@ +//! The worker's side of `common::run_wake`: runs waiting on the team's +//! usage limit go on by themselves once the limit allows runs again, +//! whether a person raised it or a new month reset it. +//! +//! The 15-minute sweep (`recover::self_heal_sweep`) reads every run waiting +//! on the usage limit, asks each team's limit once, and starts every such +//! run of a team whose limit allows runs again, the way Retry does: the +//! ticket again, taking up the waiting run's plan and branch, with the +//! waiting run marked superseded by one conditional write (only while it +//! still waits), so two sweeps never start two runs. A run whose new run +//! couldn't be queued is put back to waiting (`run_wake::put_back`), so the +//! next sweep starts it. + +use std::collections::{HashMap, HashSet}; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::run_ending::EndWrite; +use common::run_wait::WaitingOn; +use common::run_wake::{self, Wake}; +use tracing::{info, warn}; + +use super::attr_s; +use crate::models::{TicketMessage, TicketSource, WorkerMessage}; +use crate::WorkerState; + +type Item = HashMap; + +fn s<'a>(item: &'a Item, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|x| x.as_str()) + .unwrap_or("") +} + +fn n(item: &Item, k: &str) -> u64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|x| x.parse().ok()) + .unwrap_or(0) +} + +/// Most waiting runs one sweep starts again. +const MAX_WOKEN: usize = 50; + +/// The runs in `items` that wait on the usage limit, by team. +pub fn limit_waits(items: &[Item]) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + for i in items { + let wait = WaitingOn::of_item(i).unwrap_or_default(); + if run_wake::wakes_run(s(i, "status"), &wait.handback, Wake::Limit) { + out.entry(s(i, "team_id").to_string()).or_default().push(i); + } + } + out +} + +/// The ticket a waiting run starts again with, from its record, as a +/// person's Retry builds it: the same ticket, the waiting run's plan and +/// branch taken up unless the plan was what stopped it, and the repository +/// picked again for a Jira ticket. +pub fn retry_ticket(item: &Item) -> Option { + let run_id = s(item, "run_id"); + let (owner, name) = s(item, "repo").split_once('/')?; + let source = match s(item, "ticket_source") { + "jira" => TicketSource::Jira, + "alert" => TicketSource::Alert, + _ => TicketSource::Github, + }; + let (owner, name) = if matches!(source, TicketSource::Jira) { + (String::new(), String::new()) + } else { + (owner.to_string(), name.to_string()) + }; + let error = format!("{} {}", s(item, "error_message"), s(item, "error")); + Some(TicketMessage { + team_id: s(item, "team_id").to_string(), + installation_id: n(item, "installation_id"), + ticket_id: s(item, "ticket_id").to_string(), + title: s(item, "title").to_string(), + body: if matches!(source, TicketSource::Github) { + String::new() + } else { + s(item, "ticket_body").to_string() + }, + source, + repo_owner: owner, + repo_name: name, + issue_number: n(item, "issue_number"), + sender: "CoderHelm".to_string(), + resume_from: common::run_status::retry_resumes(s(item, "current_pass"), &error) + .then(|| run_id.to_string()), + ..Default::default() + }) +} + +/// Starts the waiting run `item` again (see [`retry_ticket`]), after it is +/// marked superseded while it still waits. `what`: what arrived. +pub async fn wake_item(state: &WorkerState, item: &Item, what: &str) -> bool { + let team_id = s(item, "team_id"); + let run_id = s(item, "run_id"); + let Some(ticket) = retry_ticket(item) else { + return false; + }; + let ticket_id = ticket.ticket_id.clone(); + let Ok(body) = serde_json::to_string(&WorkerMessage::Ticket(ticket)) else { + return false; + }; + let woken = common::run_ending::gate( + run_id, + &common::run_ending::superseded(&format!( + "the run CoderHelm started by itself when {what}" + )), + ); + let woken_at = chrono::Utc::now().to_rfc3339(); + let ended = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #s = :s, status_run_id = :sri, updated_at = :t") + .condition_expression("#s = :waiting") + .expression_attribute_names("#s", "status") + .run_status(":s", &woken) + .expression_attribute_values(":waiting", attr_s(run_wake::WAITING)) + .expression_attribute_values(":t", attr_s(&woken_at)) + .send() + .await; + if ended.is_err() { + return false; + } + super::release_ticket_lock(state, team_id, &ticket_id).await; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + info!(run_id, what, "Waiting run started again by itself"); + true + } + Err(e) => { + warn!(run_id, error = %e, "Could not queue the woken run"); + // Back to waiting, so the next sweep starts it. + run_wake::put_back( + &state.dynamo, + &state.config.runs_table_name, + item, + woken.sri_attr(), + &woken_at, + ) + .await; + false + } + } +} + +/// Every run waiting on the usage limit whose team's limit now allows runs +/// (raised, cleared, or reset by a new month) starts again. Returns how +/// many started. +pub async fn wake_limit_waits(state: &WorkerState) -> usize { + let filter = super::team_runs::Filter { + expr: "#s = :w", + names: vec![("#s", "status")], + values: vec![(":w", attr_s(run_wake::WAITING))], + projection: None, + }; + let items = super::team_runs::matching(state, "Runs waiting on the usage limit", &filter).await; + let mut started = 0; + let mut full: HashSet = HashSet::new(); + for (team, runs) in limit_waits(&items) { + if super::check_budget_exceeded(state, &team).await.is_some() { + full.insert(team); + continue; + } + for item in runs { + if started >= MAX_WOKEN { + break; + } + if wake_item(state, item, "the team's usage limit allowed runs again").await { + started += 1; + } + } + } + if started > 0 || !full.is_empty() { + info!( + started, + still_over = full.len(), + "Runs waiting on the usage limit read" + ); + } + started +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(team: &str, id: &str, status: &str, handback: &str, source: &str) -> Item { + let wait = WaitingOn { + action: "Raise or clear the team's usage limit in Settings".into(), + handback: handback.into(), + ..Default::default() + }; + HashMap::from([ + ("team_id".into(), attr_s(team)), + ("run_id".into(), attr_s(id)), + ("status".into(), attr_s(status)), + ("repo".into(), attr_s("acme/bookstore-web")), + ("ticket_id".into(), attr_s("WEB-7")), + ("ticket_source".into(), attr_s(source)), + ("ticket_body".into(), attr_s("Show the cover image")), + ("current_pass".into(), attr_s("implement")), + (common::run_wait::FIELD_WAITING_ON.into(), wait.to_attr()), + ]) + } + + #[test] + fn only_runs_waiting_on_the_limit_are_read_by_team() { + let items = vec![ + run("T1", "01A", "needs_input", "usage_limit", "jira"), + run("T1", "01B", "needs_input", "product_decision", "jira"), + run("T2", "01C", "needs_input", "usage_limit", "github"), + run("T2", "01D", "completed", "usage_limit", "github"), + ]; + let by_team = limit_waits(&items); + let ids = |t: &str| -> Vec<&str> { by_team[t].iter().map(|i| s(i, "run_id")).collect() }; + assert_eq!(ids("T1"), vec!["01A"]); + assert_eq!(ids("T2"), vec!["01C"]); + } + + #[test] + fn a_woken_run_starts_as_retry_would() { + let t = retry_ticket(&run("T1", "01A", "needs_input", "usage_limit", "jira")).unwrap(); + assert_eq!(t.ticket_id, "WEB-7"); + assert_eq!(t.resume_from.as_deref(), Some("01A")); + assert!( + t.repo_owner.is_empty(), + "a Jira ticket picks its repo again" + ); + assert_eq!(t.body, "Show the cover image"); + let g = retry_ticket(&run("T1", "01B", "needs_input", "usage_limit", "github")).unwrap(); + assert_eq!( + (g.repo_owner.as_str(), g.repo_name.as_str()), + ("acme", "bookstore-web") + ); + assert!(g.body.is_empty(), "GitHub reads the issue again"); + } +} diff --git a/services/worker/src/passes/triage.rs b/services/worker/src/passes/triage.rs index 2314a7c83..b569eff0a 100644 --- a/services/worker/src/passes/triage.rs +++ b/services/worker/src/passes/triage.rs @@ -875,13 +875,8 @@ fn pick_reason(response: &str) -> String { .filter(|l| !l.is_empty()) .collect(); lines.pop(); - let joined = lines.join(" "); - let capped = common::truncate_str(&joined, 400); - if capped.len() < joined.len() { - format!("{capped}…") - } else { - capped.to_string() - } + // Cut at a word ("fits the Next.js compon…" was cut mid-word). + common::rendered::clip(&lines.join(" "), 400) } /// Scan the response from the LAST line upward for a line that names one of