From 3d0ddc4ab9a1acd97adbcf713032bb3a9b625212 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 13:55:36 -0400 Subject: [PATCH] Runs: say how each run was started and by whom (trigger on the runs API) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runs list and a run now carry `trigger` {kind, label, ref, ref_url, by}, worked out on the server from the run's own fields: ticket_source, the ticket id's prefix (E2E-FIX-, E2E-GEN-, LOG-, ALERT-), requester_* or the older sender, and the plan a ticket came from. Coderhelm's own work reads "Started by Coderhelm · flaky test" with a link to the test instead of its internal ticket id. Alerts and log findings link to the event and the finding; Jira tickets to the team's site; GitHub issues to the issue. GET /api/runs takes `started_by` (jira, github, coderhelm, alert, plan, dashboard, chat), applied while it scans like the other filters. Plans: when a plan's task opens a GitHub issue or a Jira ticket, the worker records the link (settings PLAN_TICKET#...) before the label that starts the run, copies the plan's id, title and runner onto the run it starts, and marks a run that started first (a Jira webhook can win). --- docs/api/openapi.json | 88 ++- services/gateway/src/routes/api.rs | 39 +- services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/run_search.rs | 57 ++ services/gateway/src/routes/run_trigger.rs | 738 +++++++++++++++++++++ services/worker/src/passes/mod.rs | 26 + services/worker/src/passes/plan_execute.rs | 207 ++++++ 7 files changed, 1150 insertions(+), 6 deletions(-) create mode 100644 services/gateway/src/routes/run_trigger.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 44f947611..ef3e20536 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3111,6 +3111,10 @@ "minimum": 0, "type": "integer" }, + "trigger": { + "$ref": "#/components/schemas/RunTrigger", + "description": "How the run was started and by whom (as in the runs list)." + }, "updated_at": { "description": "When it last changed (RFC 3339).", "examples": [ @@ -3132,7 +3136,8 @@ "applied_standards", "sign_in_prompts", "questions", - "answers" + "answers", + "trigger" ], "type": "object" }, @@ -3461,8 +3466,66 @@ "integer", "null" ] + }, + "trigger": { + "$ref": "#/components/schemas/RunTrigger", + "description": "How the run was started and by whom, worked out from the fields\nabove and what started it. Show this instead of an internal\n`ticket_id` such as `E2E-FIX-…`." } }, + "required": [ + "trigger" + ], + "type": "object" + }, + "RunTrigger": { + "description": "How a run was started, in words, with a link to what started it.", + "properties": { + "by": { + "description": "The person who started it, when a person did: a name, GitHub login\nor email. Null for CoderHelm's own work.", + "examples": [ + "Dana Reyes" + ], + "type": [ + "string", + "null" + ] + }, + "kind": { + "$ref": "#/components/schemas/TriggerKind", + "description": "The group: `jira`, `github`, `coderhelm`, `alert`, `plan`,\n`dashboard` or `chat`. Treat a value you don't know as `coderhelm`." + }, + "label": { + "description": "What started it, to show as is: `Jira`, `GitHub issue`, `Alert`,\n`Plan`, `Started by Coderhelm · flaky test`, `Dashboard · log finding`.", + "examples": [ + "Jira" + ], + "type": "string" + }, + "ref": { + "description": "The thing that started it, when it has a name people know: a ticket\nkey, `#42`, a plan's or an alert's title, a log group.", + "examples": [ + "WEB-42" + ], + "type": [ + "string", + "null" + ] + }, + "ref_url": { + "description": "Where that thing is: a full URL (GitHub, Jira) or a dashboard path\nstarting with `/` (a test, a log finding, an alert, a plan).", + "examples": [ + "https://acme.atlassian.net/browse/WEB-42" + ], + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind", + "label" + ], "type": "object" }, "RunsPage": { @@ -3845,6 +3908,19 @@ ], "type": "object" }, + "TriggerKind": { + "description": "The group a run's start belongs to, which the runs list filters on.", + "enum": [ + "jira", + "github", + "coderhelm", + "alert", + "plan", + "dashboard", + "chat" + ], + "type": "string" + }, "UpdateEndpointBody": { "description": "Changes to an endpoint. Only the fields sent change.", "properties": { @@ -5788,6 +5864,16 @@ "schema": { "type": "string" } + }, + { + "description": "Comma-separated ways the run was started (`trigger.kind`): `jira`,\n`github`, `coderhelm`, `alert`, `plan`, `dashboard`, `chat`.", + "example": "coderhelm,alert", + "in": "query", + "name": "started_by", + "required": false, + "schema": { + "type": "string" + } } ], "responses": { diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index ab5dfd4c4..c01595078 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use tracing::{error, info, warn}; use super::run_search; +use super::run_trigger; use crate::auth::jwt; use crate::middleware::auth::SESSION_TTL_SECS; use crate::models::{ @@ -678,6 +679,10 @@ pub struct RunsQuery { /// One repo, `owner/name` (exact, case-insensitive). #[param(example = "acme/web")] repo: Option, + /// Comma-separated ways the run was started (`trigger.kind`): `jira`, + /// `github`, `coderhelm`, `alert`, `plan`, `dashboard`, `chat`. + #[param(example = "coderhelm,alert")] + started_by: Option, } /// One run in a list. @@ -728,6 +733,10 @@ pub struct RunSummary { /// When the run started (RFC 3339). #[schema(example = "2026-10-22T14:03:11Z")] pub created_at: Option, + /// How the run was started and by whom, worked out from the fields + /// above and what started it. Show this instead of an internal + /// `ticket_id` such as `E2E-FIX-…`. + pub trigger: run_trigger::RunTrigger, } /// A page of runs. @@ -776,7 +785,8 @@ pub async fn list_runs( params.status.as_deref(), params.source.as_deref(), ) - .with_repo(params.repo.as_deref()); + .with_repo(params.repo.as_deref()) + .with_started_by(params.started_by.as_deref()); let mut start = params.cursor.as_deref().filter(|c| c.len() <= 64).map(|c| { std::collections::HashMap::from([ ("team_id".to_string(), attr_s(&claims.team_id)), @@ -844,9 +854,11 @@ pub async fn list_runs( .and_then(|v| v.as_n().ok()) .and_then(|n| n.parse::().ok()) }; + let lookups = run_trigger::load_lookups(&state, &claims.team_id, matched.iter()).await; let runs: Vec = matched .iter() .map(|item| RunSummary { + trigger: run_trigger::trigger(item, &lookups), run_id: str_of(item, "run_id"), status: str_of(item, "status"), ticket_source: str_of(item, "ticket_source"), @@ -1030,6 +1042,8 @@ pub struct Run { /// The run that picked the answers up and continued the work. #[schema(example = json!(null))] pub continued_run_id: Option, + /// How the run was started and by whom (as in the runs list). + pub trigger: run_trigger::RunTrigger, } /// A question a run asked a person. @@ -1196,6 +1210,7 @@ pub async fn get_run( (tokens_in, tokens_out, cache_read, cache_write, cost_usd) }; + let lookups = run_trigger::load_lookups(&state, &claims.team_id, [item]).await; Ok(Json(run_of( item, &run_id, @@ -1206,6 +1221,7 @@ pub async fn get_run( cache_write, cost_usd, }, + &lookups, ))) } @@ -1219,7 +1235,12 @@ struct RunUsage { } /// The run `get_run` answers with, from its row in the runs table. -fn run_of(item: &run_search::Item, run_id: &str, usage: RunUsage) -> Run { +fn run_of( + item: &run_search::Item, + run_id: &str, + usage: RunUsage, + lookups: &run_trigger::Lookups, +) -> Run { let RunUsage { tokens_in, tokens_out, @@ -1258,6 +1279,7 @@ fn run_of(item: &run_search::Item, run_id: &str, usage: RunUsage) -> Run { }; let asked = run_asked(item); Run { + trigger: run_trigger::trigger(item, lookups), run_id: run_id.to_string(), status: st("status"), ticket_source: st("ticket_source"), @@ -5513,15 +5535,21 @@ mod tests { cache_write: 0, cost_usd: 0.0, }; - let run = - serde_json::to_value(run_of(&item, "01JB8X6F4M2C9QZ3T7V5W1K0HA", usage())).unwrap(); + let run = serde_json::to_value(run_of( + &item, + "01JB8X6F4M2C9QZ3T7V5W1K0HA", + usage(), + &Default::default(), + )) + .unwrap(); assert_eq!(run["run_id"], "01JB8X6F4M2C9QZ3T7V5W1K0HA"); assert_eq!(run["status"], "completed"); // The id comes from the request, so a row without the attribute // still answers with it. let bare = std::collections::HashMap::from([("status".to_string(), A::S("running".into()))]); - let run = serde_json::to_value(run_of(&bare, "01JB8Y", usage())).unwrap(); + let run = + serde_json::to_value(run_of(&bare, "01JB8Y", usage(), &Default::default())).unwrap(); assert_eq!(run["run_id"], "01JB8Y"); assert_eq!(run["questions"], json!([])); assert_eq!(run["answers"], json!([])); @@ -5564,6 +5592,7 @@ mod tests { cache_write: 0, cost_usd: 0.0, }, + &Default::default(), )) .unwrap(); assert_eq!( diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 7d92928c8..abaf9ac90 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -51,6 +51,7 @@ pub mod roles; pub mod run_answer; pub mod run_close; pub mod run_search; +pub mod run_trigger; pub mod search; pub mod setup; pub mod setup_checks; diff --git a/services/gateway/src/routes/run_search.rs b/services/gateway/src/routes/run_search.rs index b7b5c74e2..e6d17c34c 100644 --- a/services/gateway/src/routes/run_search.rs +++ b/services/gateway/src/routes/run_search.rs @@ -34,6 +34,16 @@ pub const LIST_ATTRS: &[&str] = &[ "duration_s", "current_pass", "created_at", + // How the run started (see `run_trigger`). + "issue_number", + "sender", + "requester_key", + "requester_name", + "requester_email", + "plan_id", + "plan_title", + "plan_by", + "plugin_id", ]; #[derive(Debug, Default)] @@ -45,6 +55,8 @@ pub struct RunFilter { source: Option, /// One repo to keep, lowercased (exact match). repo: Option, + /// How the run started; empty keeps every kind. + started_by: Vec, } impl RunFilter { @@ -71,9 +83,22 @@ impl RunFilter { statuses, source, repo: None, + started_by: Vec::new(), } } + /// Keep only runs started one of these ways (comma-separated + /// `run_trigger::TriggerKind` words). Unknown words are ignored; when + /// none is known, every run is kept. + pub fn with_started_by(mut self, started_by: Option<&str>) -> Self { + self.started_by = started_by + .unwrap_or("") + .split(',') + .filter_map(super::run_trigger::TriggerKind::parse) + .collect(); + self + } + /// Keep only runs of one repo (`owner/name`, any case). Empty keeps all. pub fn with_repo(mut self, repo: Option<&str>) -> Self { self.repo = repo @@ -102,6 +127,10 @@ impl RunFilter { return false; } } + if !self.started_by.is_empty() && !self.started_by.contains(&super::run_trigger::kind(item)) + { + return false; + } if self.terms.is_empty() { return true; } @@ -345,4 +374,32 @@ mod tests { assert_eq!(found.len(), 5); assert_eq!(read, 10); } + + #[test] + fn keeps_runs_started_the_chosen_ways() { + // `run` makes Jira runs. + let jira = run("1", "completed", "ABC-1", "Login", "acme/web", None); + let mut flaky = run( + "2", + "completed", + "E2E-FIX-abc", + "Fix flaky test: x", + "acme/web", + None, + ); + flaky.insert("ticket_source".into(), AttributeValue::S("alert".into())); + let mut plan = run("3", "completed", "ABC-3", "Task", "acme/web", None); + plan.insert("plan_id".into(), AttributeValue::S("p1".into())); + + let f = RunFilter::new(None, None, None).with_started_by(Some("coderhelm,plans")); + assert!(!f.matches(&jira)); + assert!(f.matches(&flaky)); + assert!(f.matches(&plan)); + let j = RunFilter::new(None, None, None).with_started_by(Some("jira")); + assert!(j.matches(&jira)); + assert!(!j.matches(&plan), "a plan's Jira ticket is the plan's"); + // Unknown words keep everything. + let any = RunFilter::new(None, None, None).with_started_by(Some("nope")); + assert!(any.matches(&jira) && any.matches(&flaky)); + } } diff --git a/services/gateway/src/routes/run_trigger.rs b/services/gateway/src/routes/run_trigger.rs new file mode 100644 index 000000000..597ac5d4a --- /dev/null +++ b/services/gateway/src/routes/run_trigger.rs @@ -0,0 +1,738 @@ +//! How a run was started and by whom, for the runs list and a run's page. +//! +//! Runs don't record "how they started" as one field: a run carries +//! `ticket_source` (`github`, `jira`, `alert` or `plugin`), a ticket id whose +//! prefix says which part of CoderHelm made it (`E2E-FIX-`, `LOG-`, +//! `ALERT-`), who asked (`requester_*`, or the free-text `sender` on older +//! runs) and, for runs of a plan's task, `plan_id`. [`kind`] reads those +//! fields alone, so the runs list can filter on it while it scans; [`trigger`] +//! adds the words and the link, using a few records looked up once per page +//! ([`Lookups`]): the alert or log finding behind a ticket, Jira user names, +//! and the team's Jira site. + +use std::collections::{HashMap, HashSet}; + +use aws_sdk_dynamodb::types::{AttributeValue, KeysAndAttributes}; +use common::requester::{self, Requester}; +use tracing::warn; + +use super::run_search::Item; +use crate::AppState; + +/// Ticket id of a flaky test CoderHelm fixes (`E2E-FIX-`). +const E2E_FIX: &str = "E2E-FIX-"; +/// Ticket id of a new test CoderHelm writes (`E2E-GEN-`). +const E2E_GEN: &str = "E2E-GEN-"; +/// Ticket id of an alert (`ALERT-`). +const ALERT: &str = "ALERT-"; + +/// The group a run's start belongs to, which the runs list filters on. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)] +#[serde(rename_all = "lowercase")] +pub enum TriggerKind { + /// A Jira ticket. + Jira, + /// A GitHub issue. + Github, + /// CoderHelm's own work: a flaky test, a new test, a log finding it + /// picked up, a scheduled or release plugin run. + Coderhelm, + /// A monitoring alert. + Alert, + /// A task of a plan. + Plan, + /// A person in the dashboard: a log finding they sent, a plugin they ran. + Dashboard, + /// A message in Slack or Microsoft Teams. + Chat, +} + +impl TriggerKind { + /// From a `started_by` filter value; unknown words are `None`. + pub fn parse(s: &str) -> Option { + Some(match s.trim().to_ascii_lowercase().as_str() { + "jira" => TriggerKind::Jira, + "github" => TriggerKind::Github, + "coderhelm" => TriggerKind::Coderhelm, + "alert" | "alerts" => TriggerKind::Alert, + "plan" | "plans" => TriggerKind::Plan, + "dashboard" => TriggerKind::Dashboard, + "chat" | "slack" | "teams" => TriggerKind::Chat, + _ => return None, + }) + } +} + +/// How a run was started, in words, with a link to what started it. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)] +pub struct RunTrigger { + /// The group: `jira`, `github`, `coderhelm`, `alert`, `plan`, + /// `dashboard` or `chat`. Treat a value you don't know as `coderhelm`. + #[schema(example = "jira")] + pub kind: TriggerKind, + /// What started it, to show as is: `Jira`, `GitHub issue`, `Alert`, + /// `Plan`, `Started by Coderhelm · flaky test`, `Dashboard · log finding`. + #[schema(example = "Jira")] + pub label: String, + /// The thing that started it, when it has a name people know: a ticket + /// key, `#42`, a plan's or an alert's title, a log group. + #[schema(example = "WEB-42")] + pub r#ref: Option, + /// Where that thing is: a full URL (GitHub, Jira) or a dashboard path + /// starting with `/` (a test, a log finding, an alert, a plan). + #[schema(example = "https://acme.atlassian.net/browse/WEB-42")] + pub ref_url: Option, + /// The person who started it, when a person did: a name, GitHub login + /// or email. Null for CoderHelm's own work. + #[schema(example = "Dana Reyes")] + pub by: Option, +} + +fn s<'a>(item: &'a Item, key: &str) -> &'a str { + item.get(key) + .and_then(|v| v.as_s().ok()) + .map(|s| s.as_str()) + .unwrap_or("") +} + +fn n(item: &Item, key: &str) -> u64 { + item.get(key) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0) +} + +/// Senders that name a part of CoderHelm, not a person. +fn is_system_sender(sender: &str) -> bool { + let s = sender.trim().to_ascii_lowercase(); + matches!( + s.as_str(), + "" | "e2e" + | "alert" + | "scheduled" + | "schedule" + | "release" + | "system" + | "log finding" + | "jira" + ) +} + +/// Who asked, as the run recorded it. +fn requester_of(item: &Item) -> Option { + Requester::from_run( + s(item, "requester_key"), + s(item, "requester_name"), + s(item, "requester_email"), + s(item, "sender"), + ) +} + +/// A log finding's run that CoderHelm started on its own (automatic fixes). +fn log_fix_is_automatic(item: &Item) -> bool { + match s(item, "requester_key") { + "" => is_system_sender(s(item, "sender")), + key => key.starts_with(requester::CODERHELM), + } +} + +/// The group a run's start belongs to, from the run's own fields. +pub fn kind(item: &Item) -> TriggerKind { + let source = s(item, "ticket_source"); + let ticket = s(item, "ticket_id"); + let key = s(item, "requester_key"); + if !s(item, "plan_id").is_empty() { + return TriggerKind::Plan; + } + if source == "plugin" { + return if s(item, "sender").contains('@') { + TriggerKind::Dashboard + } else { + TriggerKind::Coderhelm + }; + } + if ticket.starts_with(E2E_FIX) || ticket.starts_with(E2E_GEN) { + return TriggerKind::Coderhelm; + } + if common::log_findings::is_log_ticket(ticket) { + return if log_fix_is_automatic(item) { + TriggerKind::Coderhelm + } else { + TriggerKind::Dashboard + }; + } + if key.starts_with("slack:") || key.starts_with("teams:") { + return TriggerKind::Chat; + } + if key == format!("{}{}", requester::CODERHELM, requester::SCHEDULED) + || s(item, "sender").eq_ignore_ascii_case(requester::SCHEDULED) + { + return TriggerKind::Coderhelm; + } + if source == "alert" || ticket.starts_with(ALERT) { + return TriggerKind::Alert; + } + if source == "jira" { + return TriggerKind::Jira; + } + TriggerKind::Github +} + +/// Records looked up for one page of runs. +#[derive(Debug, Default)] +pub struct Lookups { + /// The team's Jira site, `https://.atlassian.net`. + pub jira_site: Option, + /// Settings-table items by sort key: `LOG_TICKET#`, `ALERT_TICKET#`, + /// `JIRAUSER#`. + pub records: HashMap, +} + +impl Lookups { + fn record(&self, sk: &str) -> Option<&Item> { + self.records.get(sk) + } +} + +fn log_ticket_sk(ticket: &str) -> String { + format!("LOG_TICKET#{ticket}") +} + +fn alert_ticket_sk(ticket: &str) -> String { + format!("ALERT_TICKET#{ticket}") +} + +/// The Jira account id behind a run's requester, when that is all it has. +fn jira_account(item: &Item) -> Option { + let r = requester_of(item)?; + if !r.name.is_empty() { + return None; + } + r.jira_id().map(str::to_string) +} + +/// The settings-table records [`trigger`] reads for these runs. +pub fn lookup_keys<'a>(items: impl IntoIterator) -> Vec { + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for item in items { + let ticket = s(item, "ticket_id"); + let mut keys = Vec::new(); + if common::log_findings::is_log_ticket(ticket) { + keys.push(log_ticket_sk(ticket)); + } else if ticket.starts_with(ALERT) { + keys.push(alert_ticket_sk(ticket)); + } + if let Some(id) = jira_account(item) { + keys.push(requester::jira_user_sk(&id)); + } + for k in keys { + if seen.insert(k.clone()) { + out.push(k); + } + } + } + out +} + +/// Reads the records [`trigger`] needs for these runs: one batch read of the +/// settings table (100 keys a call) and, when a Jira run is among them, the +/// team's Jira site. A record that can't be read leaves its link out. +pub async fn load_lookups<'a>( + state: &AppState, + team_id: &str, + items: impl IntoIterator + Clone, +) -> Lookups { + let mut out = Lookups::default(); + let keys = lookup_keys(items.clone()); + for chunk in keys.chunks(100) { + let mut ka = KeysAndAttributes::builder(); + for sk in chunk { + ka = ka.keys(HashMap::from([ + ("pk".to_string(), AttributeValue::S(team_id.to_string())), + ("sk".to_string(), AttributeValue::S(sk.clone())), + ])); + } + let Ok(ka) = ka.build() else { continue }; + let mut request = HashMap::from([(state.config.settings_table_name.clone(), ka)]); + // Unprocessed keys come back under load: one more try, then without. + for _ in 0..2 { + match state + .dynamo + .batch_get_item() + .set_request_items(Some(request.clone())) + .send() + .await + { + Ok(res) => { + for item in res + .responses() + .and_then(|r| r.get(&state.config.settings_table_name)) + .into_iter() + .flatten() + { + let sk = s(item, "sk").to_string(); + out.records.insert(sk, item.clone()); + } + match res.unprocessed_keys().filter(|u| !u.is_empty()) { + Some(left) => request = left.clone(), + None => break, + } + } + Err(e) => { + warn!(team_id, error = %e, "Could not read what started the runs"); + break; + } + } + } + } + if items.into_iter().any(|i| s(i, "ticket_source") == "jira") { + out.jira_site = state + .dynamo + .get_item() + .table_name(&state.config.jira_config_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S("JIRA#config".into())) + .projection_expression("site_url") + .send() + .await + .ok() + .and_then(|r| r.item) + .map(|i| s(&i, "site_url").trim_end_matches('/').to_string()) + .filter(|u| u.starts_with("https://")); + } + out +} + +/// The person who started the run, in words, or `None` for CoderHelm's own +/// work and runs that recorded no one. +pub fn person(item: &Item, lookups: &Lookups) -> Option { + let r = requester_of(item)?; + if r.is_coderhelm() { + return None; + } + if s(item, "requester_key").is_empty() && is_system_sender(s(item, "sender")) { + return None; + } + if !r.name.is_empty() && !requester::is_jira_account_id(&r.name) { + return Some(r.name); + } + if let Some(id) = r.jira_id() { + return lookups + .record(&requester::jira_user_sk(id)) + .map(|u| s(u, "name").trim().to_string()) + .filter(|n| !n.is_empty()); + } + if let Some(login) = r.key.strip_prefix("github:") { + return Some(login.to_string()); + } + if !r.email.is_empty() { + return Some(r.email); + } + r.key + .strip_prefix("email:") + .or_else(|| r.key.strip_prefix("name:")) + .map(str::to_string) +} + +/// The issue number of a GitHub run: `issue_number`, or the number in +/// `GH-42` / `owner/name#42`. +fn issue_number(item: &Item) -> Option { + let n = n(item, "issue_number"); + if n > 0 { + return Some(n); + } + let ticket = s(item, "ticket_id"); + ticket + .rsplit_once(['-', '#']) + .and_then(|(_, d)| d.parse::().ok()) + .filter(|n| *n > 0) +} + +fn q(v: &str) -> String { + urlencoding::encode(v).into_owned() +} + +fn some(v: &str) -> Option { + let v = v.trim(); + (!v.is_empty()).then(|| v.to_string()) +} + +/// How a run was started, in words and with a link. +pub fn trigger(item: &Item, lookups: &Lookups) -> RunTrigger { + let kind = kind(item); + let ticket = s(item, "ticket_id"); + let by = person(item, lookups); + let t = |label: &str, r: Option, url: Option, by: Option| RunTrigger { + kind, + label: label.to_string(), + r#ref: r, + ref_url: url, + by, + }; + match kind { + TriggerKind::Plan => t( + "Plan", + some(s(item, "plan_title")), + Some(format!("/plans/detail?id={}", q(s(item, "plan_id")))), + some(s(item, "plan_by")).or(by), + ), + TriggerKind::Coderhelm | TriggerKind::Dashboard if s(item, "ticket_source") == "plugin" => { + let plugin = some(s(item, "plugin_id")) + .or_else(|| ticket.strip_prefix("plugin:").and_then(some)); + let url = plugin + .as_deref() + .map(|p| format!("/plugins/plugin?id={}", q(p))); + if kind == TriggerKind::Coderhelm { + t("Started by Coderhelm · plugin", plugin, url, None) + } else { + t("Dashboard · plugin", plugin, url, by) + } + } + _ if ticket.starts_with(E2E_FIX) => t( + "Started by Coderhelm · flaky test", + None, + Some(format!("/tests/test?id={}", q(&ticket[E2E_FIX.len()..]))), + None, + ), + _ if ticket.starts_with(E2E_GEN) => t( + "Started by Coderhelm · new test", + None, + Some("/tests".to_string()), + None, + ), + _ if common::log_findings::is_log_ticket(ticket) => { + let rec = lookups.record(&log_ticket_sk(ticket)); + let url = rec + .map(|r| s(r, "rec_id")) + .filter(|id| !id.is_empty()) + .map(|id| format!("/logs?finding={}", q(id))) + .unwrap_or_else(|| "/logs".to_string()); + let group = rec.and_then(|r| some(s(r, "log_group"))); + if kind == TriggerKind::Coderhelm { + t("Started by Coderhelm · log finding", group, Some(url), None) + } else { + t("Dashboard · log finding", group, Some(url), by) + } + } + TriggerKind::Coderhelm => t("Started by Coderhelm · scheduled", None, None, None), + TriggerKind::Alert => { + let rec = lookups.record(&alert_ticket_sk(ticket)); + let url = rec + .map(|r| s(r, "alert_id")) + .filter(|id| !id.is_empty()) + .map(|id| format!("/alerts/detail?id={}", q(id))) + .unwrap_or_else(|| "/alerts".to_string()); + let name = rec + .and_then(|r| some(s(r, "title"))) + .or_else(|| some(s(item, "title"))); + t("Alert", name, Some(url), None) + } + TriggerKind::Jira => t( + "Jira", + some(ticket), + lookups + .jira_site + .as_deref() + .filter(|_| !ticket.is_empty()) + .map(|site| format!("{site}/browse/{}", q(ticket))), + by, + ), + TriggerKind::Chat => t( + if s(item, "requester_key").starts_with("teams:") { + "Teams" + } else { + "Slack" + }, + None, + None, + by, + ), + TriggerKind::Dashboard => t("Dashboard", None, None, by), + TriggerKind::Github => { + let repo = s(item, "repo"); + match issue_number(item) { + Some(num) => t( + "GitHub issue", + Some(format!("#{num}")), + (repo.split_once('/').is_some()) + .then(|| format!("https://github.com/{repo}/issues/{num}")), + by, + ), + None => t("GitHub", some(ticket), None, by), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(fields: &[(&str, &str)]) -> Item { + fields + .iter() + .map(|(k, v)| { + let v = if *k == "issue_number" { + AttributeValue::N((*v).into()) + } else { + AttributeValue::S((*v).into()) + }; + (k.to_string(), v) + }) + .collect() + } + + fn rec(fields: &[(&str, &str)]) -> Item { + run(fields) + } + + #[test] + fn jira_ticket_with_a_named_person_and_the_site() { + let item = run(&[ + ("ticket_source", "jira"), + ("ticket_id", "WEB-42"), + ("requester_key", "jira:5b10ac8d82e05b22cc7d4ef5"), + ("requester_name", "Dana Reyes"), + ]); + let l = Lookups { + jira_site: Some("https://acme.atlassian.net".into()), + ..Default::default() + }; + let tr = trigger(&item, &l); + assert_eq!(tr.kind, TriggerKind::Jira); + assert_eq!(tr.label, "Jira"); + assert_eq!(tr.r#ref.as_deref(), Some("WEB-42")); + assert_eq!( + tr.ref_url.as_deref(), + Some("https://acme.atlassian.net/browse/WEB-42") + ); + assert_eq!(tr.by.as_deref(), Some("Dana Reyes")); + } + + #[test] + fn jira_account_id_only_reads_the_name_it_was_seen_with() { + let item = run(&[ + ("ticket_source", "jira"), + ("ticket_id", "WEB-7"), + ("sender", "5b10ac8d82e05b22cc7d4ef5"), + ]); + assert_eq!( + lookup_keys([&item]), + vec!["JIRAUSER#5b10ac8d82e05b22cc7d4ef5".to_string()] + ); + let mut l = Lookups::default(); + assert_eq!(trigger(&item, &l).by, None); + l.records.insert( + "JIRAUSER#5b10ac8d82e05b22cc7d4ef5".into(), + rec(&[("name", "Sam Ito")]), + ); + let tr = trigger(&item, &l); + assert_eq!(tr.by.as_deref(), Some("Sam Ito")); + // No site known: no link, the key still shows. + assert_eq!(tr.ref_url, None); + assert_eq!(tr.r#ref.as_deref(), Some("WEB-7")); + } + + #[test] + fn github_issue_links_to_the_issue() { + let item = run(&[ + ("ticket_source", "github"), + ("ticket_id", "GH-42"), + ("repo", "acme/web"), + ("issue_number", "42"), + ("sender", "octocat"), + ("requester_key", "github:octocat"), + ]); + let tr = trigger(&item, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Github); + assert_eq!(tr.label, "GitHub issue"); + assert_eq!(tr.r#ref.as_deref(), Some("#42")); + assert_eq!( + tr.ref_url.as_deref(), + Some("https://github.com/acme/web/issues/42") + ); + assert_eq!(tr.by.as_deref(), Some("octocat")); + } + + #[test] + fn github_number_from_the_ticket_id_on_older_runs() { + let item = run(&[("ticket_id", "acme/web#318"), ("repo", "acme/web")]); + let tr = trigger(&item, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Github); + assert_eq!(tr.r#ref.as_deref(), Some("#318")); + } + + #[test] + fn flaky_test_fix_never_shows_its_internal_id() { + let item = run(&[ + ("ticket_source", "alert"), + ("ticket_id", "E2E-FIX-a7f51433483adf820849"), + ("sender", "e2e"), + ("requester_key", "coderhelm:e2e"), + ("title", "Fix flaky test: checkout works"), + ]); + let tr = trigger(&item, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Coderhelm); + assert_eq!(tr.label, "Started by Coderhelm · flaky test"); + assert_eq!(tr.r#ref, None); + assert_eq!( + tr.ref_url.as_deref(), + Some("/tests/test?id=a7f51433483adf820849") + ); + assert_eq!(tr.by, None); + // The alert source alone doesn't make it an alert. + assert_ne!(kind(&item), TriggerKind::Alert); + } + + #[test] + fn new_test_is_coderhelm() { + let item = run(&[("ticket_source", "alert"), ("ticket_id", "E2E-GEN-01ABC")]); + let tr = trigger(&item, &Lookups::default()); + assert_eq!(tr.label, "Started by Coderhelm · new test"); + assert_eq!(tr.ref_url.as_deref(), Some("/tests")); + } + + #[test] + fn log_finding_automatic_or_by_a_person() { + let auto = run(&[ + ("ticket_source", "alert"), + ("ticket_id", "LOG-1A2B3C4D"), + ("sender", "log finding"), + ("requester_key", "coderhelm:log_finding"), + ]); + let mut l = Lookups::default(); + l.records.insert( + "LOG_TICKET#LOG-1A2B3C4D".into(), + rec(&[("rec_id", "rec-9"), ("log_group", "/aws/lambda/api")]), + ); + let tr = trigger(&auto, &l); + assert_eq!(tr.kind, TriggerKind::Coderhelm); + assert_eq!(tr.label, "Started by Coderhelm · log finding"); + assert_eq!(tr.r#ref.as_deref(), Some("/aws/lambda/api")); + assert_eq!(tr.ref_url.as_deref(), Some("/logs?finding=rec-9")); + + let person = run(&[ + ("ticket_source", "alert"), + ("ticket_id", "LOG-1A2B3C4D"), + ("sender", "dev@acme.test"), + ("requester_key", "email:dev@acme.test"), + ("requester_email", "dev@acme.test"), + ]); + let tr = trigger(&person, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Dashboard); + assert_eq!(tr.label, "Dashboard · log finding"); + assert_eq!(tr.ref_url.as_deref(), Some("/logs")); + assert_eq!(tr.by.as_deref(), Some("dev@acme.test")); + assert_eq!(lookup_keys([&person]), vec!["LOG_TICKET#LOG-1A2B3C4D"]); + } + + #[test] + fn alert_names_the_alarm_and_links_the_event() { + let item = run(&[ + ("ticket_source", "alert"), + ("ticket_id", "ALERT-3f9c2a71"), + ("sender", "alert"), + ("requester_key", "coderhelm:alert"), + ("title", "ALARM: api-5xx"), + ]); + let mut l = Lookups::default(); + assert_eq!( + trigger(&item, &l).ref_url.as_deref(), + Some("/alerts"), + "an expired record still links somewhere" + ); + l.records.insert( + "ALERT_TICKET#ALERT-3f9c2a71".into(), + rec(&[("alert_id", "ev 1"), ("title", "api-5xx")]), + ); + let tr = trigger(&item, &l); + assert_eq!(tr.kind, TriggerKind::Alert); + assert_eq!(tr.label, "Alert"); + assert_eq!(tr.r#ref.as_deref(), Some("api-5xx")); + assert_eq!(tr.ref_url.as_deref(), Some("/alerts/detail?id=ev%201")); + assert_eq!(tr.by, None); + } + + #[test] + fn plan_task_names_the_plan_and_who_ran_it() { + let item = run(&[ + ("ticket_source", "github"), + ("ticket_id", "GH-9"), + ("repo", "acme/web"), + ("sender", "coderhelm-app[bot]"), + ("plan_id", "p1"), + ("plan_title", "Rate limits"), + ("plan_by", "dana@acme.test"), + ]); + let tr = trigger(&item, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Plan); + assert_eq!(tr.label, "Plan"); + assert_eq!(tr.r#ref.as_deref(), Some("Rate limits")); + assert_eq!(tr.ref_url.as_deref(), Some("/plans/detail?id=p1")); + assert_eq!(tr.by.as_deref(), Some("dana@acme.test")); + } + + #[test] + fn plugin_by_a_person_or_by_a_release() { + let manual = run(&[ + ("ticket_source", "plugin"), + ("ticket_id", "plugin:release-notes"), + ("plugin_id", "release-notes"), + ("sender", "dev@acme.test"), + ]); + let tr = trigger(&manual, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Dashboard); + assert_eq!(tr.label, "Dashboard · plugin"); + assert_eq!(tr.r#ref.as_deref(), Some("release-notes")); + assert_eq!( + tr.ref_url.as_deref(), + Some("/plugins/plugin?id=release-notes") + ); + assert_eq!(tr.by.as_deref(), Some("dev@acme.test")); + + let release = run(&[ + ("ticket_source", "plugin"), + ("ticket_id", "plugin:release-notes"), + ("sender", "release"), + ]); + let tr = trigger(&release, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Coderhelm); + assert_eq!(tr.label, "Started by Coderhelm · plugin"); + assert_eq!(tr.by, None); + } + + #[test] + fn scheduled_and_chat() { + let sched = run(&[("ticket_source", "github"), ("sender", "scheduled")]); + assert_eq!(kind(&sched), TriggerKind::Coderhelm); + let slack = run(&[ + ("ticket_source", "github"), + ("requester_key", "slack:u123"), + ("requester_name", "Ana"), + ]); + let tr = trigger(&slack, &Lookups::default()); + assert_eq!(tr.kind, TriggerKind::Chat); + assert_eq!(tr.label, "Slack"); + assert_eq!(tr.by.as_deref(), Some("Ana")); + } + + #[test] + fn parse_filter_words() { + assert_eq!(TriggerKind::parse("Alerts"), Some(TriggerKind::Alert)); + assert_eq!(TriggerKind::parse("plans"), Some(TriggerKind::Plan)); + assert_eq!(TriggerKind::parse("nope"), None); + for k in [ + TriggerKind::Jira, + TriggerKind::Github, + TriggerKind::Coderhelm, + TriggerKind::Alert, + TriggerKind::Plan, + TriggerKind::Dashboard, + TriggerKind::Chat, + ] { + let word = serde_json::to_value(k).unwrap(); + assert_eq!(TriggerKind::parse(word.as_str().unwrap()), Some(k)); + } + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 8c72ea94b..976ec6073 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -4685,6 +4685,32 @@ async fn create_run_record( put = put.item("requester_email", attr_s(&r.email)); } } + // A ticket a plan's task opened: the run says which plan (see + // plan_execute::link_ticket_to_plan, which also covers a run that + // starts before the link is written). + let plan_ticket = match msg.source { + TicketSource::Github if msg.issue_number > 0 => Some(plan_execute::PlanTicket::Github { + repo: &repo, + issue_number: msg.issue_number, + }), + TicketSource::Jira if !msg.ticket_id.is_empty() => { + Some(plan_execute::PlanTicket::Jira(&msg.ticket_id)) + } + _ => None, + }; + if let Some(ticket) = plan_ticket { + if let Some((plan_id, title, by)) = + plan_execute::plan_of_ticket(state, &msg.team_id, &ticket).await + { + put = put.item("plan_id", attr_s(&plan_id)); + if !title.is_empty() { + put = put.item("plan_title", attr_s(&title)); + } + if !by.is_empty() { + put = put.item("plan_by", attr_s(&by)); + } + } + } put.send().await?; self::webhooks::emit_run(state, &msg.team_id, run_id, "running").await; diff --git a/services/worker/src/passes/plan_execute.rs b/services/worker/src/passes/plan_execute.rs index 927f72942..6723be327 100644 --- a/services/worker/src/passes/plan_execute.rs +++ b/services/worker/src/passes/plan_execute.rs @@ -132,6 +132,14 @@ pub async fn run( Ok(resp) if resp.status().is_success() => { let body: serde_json::Value = resp.json().await.unwrap_or_default(); let ticket_key = body["key"].as_str().unwrap_or("UNKNOWN"); + link_ticket_to_plan( + state, + &msg.team_id, + &msg.plan_id, + task_id, + PlanTicket::Jira(ticket_key), + ) + .await; let ticket_url = if let Some(ref site) = jira_site_url { format!("{}/browse/{}", site.trim_end_matches('/'), ticket_key) } else { @@ -183,6 +191,19 @@ pub async fn run( .await { Ok((issue_number, issue_url)) => { + // Before the label: the label starts the run, and the + // run reads this to say it came from the plan. + link_ticket_to_plan( + state, + &msg.team_id, + &msg.plan_id, + task_id, + PlanTicket::Github { + repo: task_repo, + issue_number, + }, + ) + .await; // Label the issue FIRST to trigger the ticket pipeline if let Err(e) = github .add_label(owner, repo, issue_number, "coderhelm") @@ -273,6 +294,171 @@ pub async fn run( // ── Helpers ─────────────────────────────────────────────────────────────────── +/// The ticket a plan's task opened. +pub(crate) enum PlanTicket<'a> { + /// A GitHub issue in `owner/name`. + Github { repo: &'a str, issue_number: u64 }, + /// A Jira ticket key. + Jira(&'a str), +} + +impl PlanTicket<'_> { + /// Settings-table sort key of the link from the ticket to its plan task. + pub(crate) fn sk(&self) -> String { + match self { + PlanTicket::Github { repo, issue_number } => { + format!("PLAN_TICKET#github#{}#{issue_number}", repo.to_lowercase()) + } + PlanTicket::Jira(key) => format!("PLAN_TICKET#jira#{}", key.to_uppercase()), + } + } + + /// The ticket id runs of this ticket carry. + fn ticket_id(&self) -> String { + match self { + PlanTicket::Github { issue_number, .. } => format!("GH-{issue_number}"), + PlanTicket::Jira(key) => key.to_string(), + } + } + + /// The repo a run must be in to be this ticket's (GitHub numbers repeat + /// across repos; a Jira ticket's run can be in any repo). + fn repo(&self) -> Option { + match self { + PlanTicket::Github { repo, .. } => Some(repo.to_lowercase()), + PlanTicket::Jira(_) => None, + } + } +} + +/// The plan a run's ticket came from: `(plan_id, plan_title, plan_by)`. +pub(crate) async fn plan_of_ticket( + state: &WorkerState, + team_id: &str, + ticket: &PlanTicket<'_>, +) -> Option<(String, String, String)> { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(ticket.sk())) + .send() + .await + .ok()? + .item?; + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let plan_id = s("plan_id"); + (!plan_id.is_empty()).then(|| (plan_id, s("plan_title"), s("plan_by"))) +} + +/// Records that a ticket came from a plan's task, so the runs it starts say +/// "Plan · " instead of naming the bot that opened the issue. Also +/// marks a run that already started for it (a Jira webhook can beat this). +/// Best effort: a failure leaves the run labelled by its ticket's source. +async fn link_ticket_to_plan( + state: &WorkerState, + team_id: &str, + plan_id: &str, + task_id: &str, + ticket: PlanTicket<'_>, +) { + if matches!(ticket, PlanTicket::Jira(k) if k.is_empty() || k == "UNKNOWN") { + return; + } + let plan = state + .dynamo + .get_item() + .table_name(&state.config.plans_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(format!("PLAN#{plan_id}"))) + .projection_expression("title, executed_by") + .send() + .await + .ok() + .and_then(|r| r.item); + let field = |k: &str| { + plan.as_ref() + .and_then(|i| i.get(k)) + .and_then(|v| v.as_s().ok()) + .map(|s| common::truncate_str(s, 300).to_string()) + .unwrap_or_default() + }; + let (title, by) = (field("title"), field("executed_by")); + let mut put = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", AttributeValue::S(team_id.to_string())) + .item("sk", AttributeValue::S(ticket.sk())) + .item("plan_id", AttributeValue::S(plan_id.to_string())) + .item("task_id", AttributeValue::S(task_id.to_string())); + if !title.is_empty() { + put = put.item("plan_title", AttributeValue::S(title.clone())); + } + if !by.is_empty() { + put = put.item("plan_by", AttributeValue::S(by.clone())); + } + if let Err(e) = put.send().await { + tracing::warn!(team_id, plan_id, task_id, error = %e, "Could not link the ticket to its plan"); + return; + } + // A run that started before the link was written. + let Ok(found) = 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.ticket_id())) + .send() + .await + else { + return; + }; + let want_repo = ticket.repo(); + for item in found.items() { + let s = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).map(|s| s.as_str()); + if want_repo + .as_deref() + .is_some_and(|r| s("repo").map(str::to_lowercase).as_deref() != Some(r)) + { + continue; + } + let Some(run_id) = s("run_id") else { continue }; + let mut update = 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())) + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":p", AttributeValue::S(plan_id.to_string())); + let mut set = vec!["plan_id = :p"]; + if !title.is_empty() { + set.push("plan_title = :pt"); + update = update.expression_attribute_values(":pt", AttributeValue::S(title.clone())); + } + if !by.is_empty() { + set.push("plan_by = :pb"); + update = update.expression_attribute_values(":pb", AttributeValue::S(by.clone())); + } + if let Err(e) = update + .update_expression(format!("SET {}", set.join(", "))) + .send() + .await + { + tracing::warn!(team_id, run_id, error = %e, "Could not mark the run as the plan's"); + } + } +} + async fn get_install_id( state: &WorkerState, team_id: &str, @@ -617,6 +803,14 @@ pub async fn continue_tasks( Ok(resp) if resp.status().is_success() => { let body: serde_json::Value = resp.json().await.unwrap_or_default(); let ticket_key = body["key"].as_str().unwrap_or("UNKNOWN"); + link_ticket_to_plan( + state, + &msg.team_id, + &msg.plan_id, + task_id, + PlanTicket::Jira(ticket_key), + ) + .await; let ticket_url = if let Some(ref site) = jira_site_url { format!("{}/browse/{}", site.trim_end_matches('/'), ticket_key) } else { @@ -664,6 +858,19 @@ pub async fn continue_tasks( .await { Ok((issue_number, issue_url)) => { + // Before the label: the label starts the run, and the + // run reads this to say it came from the plan. + link_ticket_to_plan( + state, + &msg.team_id, + &msg.plan_id, + task_id, + PlanTicket::Github { + repo: task_repo, + issue_number, + }, + ) + .await; if let Err(e) = github .add_label(owner, repo, issue_number, "coderhelm") .await