diff --git a/coderhelm-jira/src/index.js b/coderhelm-jira/src/index.js index 10ae86b45..d2daf3b23 100644 --- a/coderhelm-jira/src/index.js +++ b/coderhelm-jira/src/index.js @@ -7,6 +7,7 @@ const { GATEWAY_URL } = require("./gateway"); const { existingComments } = require("./comments"); const { postReply, parentIdOf } = require("./thread-reply"); const { versionFields } = require("./version"); +const { relatedTickets } = require("./related"); /** Jira's comment calls as the app, for a threaded reply (see thread-reply.js). */ const jiraComments = { @@ -23,6 +24,14 @@ const jiraComments = { // see whether Jira's comment events carry a parent id. let loggedCommentKeys = false; +/** A related ticket's summary, status and description, read as the app. */ +async function readRelatedIssue(key) { + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${key}?fields=summary,description,status`); + if (!res.ok) return null; + const full = await res.json(); + return full.fields || null; +} + /** The parts of a Jira user CoderHelm keeps: account id, name, email. */ function jiraUser(u) { return { accountId: u.accountId, displayName: u.displayName, emailAddress: u.emailAddress }; @@ -188,7 +197,7 @@ exports.handler = async (event, context) => { let fields = {}; if (issue.id) { try { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment`); + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment,issuelinks`); if (res.ok) { const full = await res.json(); fields = full.fields || {}; @@ -238,6 +247,9 @@ exports.handler = async (event, context) => { // What people already wrote on the ticket: the run that starts reads it // before it plans (the gateway keeps each comment once, by its id). comments: existingComments(fields), + // The tickets linked to this one and the ones its text names: their + // acceptance criteria are part of the change (see related.js). + related: await relatedTickets(issue.key, fields, readRelatedIssue), user: requester(event.atlassianId, fields), coderhelm: { repo_owner: repoOwner || undefined, diff --git a/coderhelm-jira/src/related.js b/coderhelm-jira/src/related.js new file mode 100644 index 000000000..41bf5f470 --- /dev/null +++ b/coderhelm-jira/src/related.js @@ -0,0 +1,81 @@ +/** + * The tickets related to the one CoderHelm works on: its issue links ("relates + * to", "blocks", "is cloned by") and the tickets its description names. Their + * acceptance criteria are part of the change, so the run reads them before it + * plans and checks them before the pull request is called ready. + * + * A pull request was once closed by a person who expected a linked ticket's + * pull request to cover it; that pull request had never read the linked + * ticket, and the button it was about still pointed to the old address. + */ + +/** The most related tickets sent with one ticket event. */ +const MAX_RELATED = 6; + +/** The most characters of one related ticket's description sent. */ +const MAX_BODY_CHARS = 8000; + +/** Ticket keys a text names (`ABC-123`), in order, without repeats. */ +function keysInText(text, own) { + const out = []; + const re = /(^|[^A-Za-z0-9-])([A-Z][A-Z0-9]+-\d+)(?![A-Za-z0-9])/g; + let m; + while ((m = re.exec(text || "")) !== null) { + const key = m[2]; + if (key !== own && !out.includes(key)) out.push(key); + } + return out; +} + +/** + * The related tickets' keys with how each relates, issue links first. + * @param {string} own The ticket's own key. + * @param {object} fields The ticket's fields (with `issuelinks` and `description`). + * @returns {{key: string, relation: string}[]} + */ +function relatedKeys(own, fields) { + const out = []; + for (const l of (fields && fields.issuelinks) || []) { + const other = l.outwardIssue || l.inwardIssue; + if (!other || !other.key || other.key === own) continue; + const type = l.type || {}; + const relation = (l.outwardIssue ? type.outward : type.inward) || type.name || "relates to"; + if (!out.some((r) => r.key === other.key)) out.push({ key: other.key, relation }); + } + const text = typeof fields?.description === "string" ? fields.description : JSON.stringify(fields?.description || ""); + for (const key of keysInText(text, own)) { + if (!out.some((r) => r.key === key)) out.push({ key, relation: "named in the ticket" }); + } + return out.slice(0, MAX_RELATED); +} + +/** + * Each related ticket with its summary, status and description (the + * gateway reads the description's words), read as the app. + * @param {string} own The ticket's own key. + * @param {object} fields The ticket's fields. + * @param {(key: string) => Promise} readIssue The issue's fields, or null. + */ +async function relatedTickets(own, fields, readIssue) { + const out = []; + for (const { key, relation } of relatedKeys(own, fields)) { + let f = null; + try { + f = await readIssue(key); + } catch (e) { + f = null; + } + if (!f) continue; + const body = typeof f.description === "string" ? f.description : JSON.stringify(f.description || ""); + out.push({ + key, + relation, + summary: f.summary || "", + status: (f.status && f.status.name) || "", + description: body.slice(0, MAX_BODY_CHARS), + }); + } + return out; +} + +module.exports = { keysInText, relatedKeys, relatedTickets, MAX_RELATED }; diff --git a/coderhelm-jira/test/related.test.js b/coderhelm-jira/test/related.test.js new file mode 100644 index 000000000..0901fb412 --- /dev/null +++ b/coderhelm-jira/test/related.test.js @@ -0,0 +1,37 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { keysInText, relatedKeys, relatedTickets, MAX_RELATED } = require("../src/related"); + +test("keys named in a text, without the ticket's own", () => { + assert.deepEqual(keysInText("See ABC-2 and XY-3, not ABC-1 or abc-4. ABC-2 again.", "ABC-1"), ["ABC-2", "XY-3"]); +}); + +test("issue links come first, with how they relate, then keys in the description", () => { + const fields = { + issuelinks: [ + { type: { name: "Relates", inward: "relates to", outward: "relates to" }, outwardIssue: { key: "ABC-2" } }, + { type: { name: "Blocks", inward: "is blocked by", outward: "blocks" }, inwardIssue: { key: "ABC-3" } }, + ], + description: { type: "doc", content: [{ type: "text", text: "Also covers ABC-4 and ABC-2." }] }, + }; + assert.deepEqual(relatedKeys("ABC-1", fields), [ + { key: "ABC-2", relation: "relates to" }, + { key: "ABC-3", relation: "is blocked by" }, + { key: "ABC-4", relation: "named in the ticket" }, + ]); +}); + +test("each related ticket is read with its summary and description; an unreadable one is left out", async () => { + const fields = { issuelinks: [{ type: { outward: "relates to" }, outwardIssue: { key: "ABC-2" } }, { type: { outward: "relates to" }, outwardIssue: { key: "ABC-9" } }] }; + const read = async (key) => (key === "ABC-2" ? { summary: "Point the drawer button to the new page", status: { name: "Closed" }, description: "Acceptance criteria\n- The drawer Register button links to /new/register" } : null); + const got = await relatedTickets("ABC-1", fields, read); + assert.equal(got.length, 1); + assert.equal(got[0].key, "ABC-2"); + assert.equal(got[0].status, "Closed"); + assert.match(got[0].description, /links to \/new\/register/); +}); + +test("at most a handful are sent", () => { + const links = Array.from({ length: 10 }, (_, i) => ({ type: { outward: "relates to" }, outwardIssue: { key: `ABC-${i + 2}` } })); + assert.equal(relatedKeys("ABC-1", { issuelinks: links }).length, MAX_RELATED); +}); diff --git a/docs/incidents/bz_ticket_answer_decides.md b/docs/incidents/bz_ticket_answer_decides.md new file mode 100644 index 000000000..277fa660f --- /dev/null +++ b/docs/incidents/bz_ticket_answer_decides.md @@ -0,0 +1,5 @@ +# bz. `bz_ticket_answer_decides` + +**What happened:** A run asked on its ticket for a page's heading and intro copy, with a proposed default. The product owner answered on the ticket to skip both and use the title. That run applied the answer as a round on its own pull request. Two days later a new run on the same ticket opened a new pull request: the comment was already marked handled, so the new run never read it, built the intro anyway and listed it under "Decisions pending product input". + +**The guarantee:** Every answer and instruction people wrote on the ticket is a decision for every run on it, whichever run handled it. It is merged into the run's answers before triage and planning, read again at each boundary, and given to every coder round and every feedback and resume round. Wherever a description is written, an item the answers settle is taken out of the pending lists and listed under "Decided on the ticket", and an answer that goes against an acceptance criterion gets one line saying so. The decisions are kept per installation, so one team's never reach another's description. diff --git a/docs/incidents/ca_related_ticket_covered.md b/docs/incidents/ca_related_ticket_covered.md new file mode 100644 index 000000000..045de2a1c --- /dev/null +++ b/docs/incidents/ca_related_ticket_covered.md @@ -0,0 +1,5 @@ +# ca. `ca_related_ticket_covered` + +**What happened:** A ticket's pull request was closed by a person who expected a linked ticket's pull request to cover it. The pull request that was kept never read the linked ticket: when it was called ready, the drawer's Register button still pointed to the old address. + +**The guarantee:** The Jira app sends the ticket's issue links and the tickets its text names, with their summaries and descriptions. The gateway keeps them on the run's message, the planner reads their acceptance criteria as part of the change, and the run keeps them. Before the pull request is called ready, each address a pull request closed in favor of this one moved is checked on the head's files, each link criterion is checked on the preview page, and anything else is listed as not covered with why, in the description's "Related tickets" section. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 42463647e..0da16f4ea 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -239,6 +239,9 @@ pub mod problems; /// Where this deployment's dashboard and API are (links, redirects, webhooks). pub mod public_urls; pub mod registry_check; +/// Linked tickets and pull requests closed in favor of this one: their criteria are +/// part of the change and checked before it is called ready. +pub mod related_tickets; /// What CoderHelm says back to a person, written from the thread and the run's records. pub mod reply_compose; /// Who asked for a run: one identity per person, for per-person analytics. @@ -293,6 +296,9 @@ pub mod stop_rules; /// A team's run and PR-reviewed counts, each added exactly once. pub mod team_counts; pub mod ticket_comments; +/// What a person answered on the ticket is a decision in every run on it; a +/// description never lists an answered item as pending. +pub mod ticket_decisions; /// A ticket's comments as CoderHelm read them, and whether its work is done. pub mod ticket_state; /// A team's monthly token limits: new tokens, cache read, cache write. diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 4d494d418..941e0b017 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -1147,6 +1147,11 @@ pub struct TicketMessage { /// planner doesn't ask them again (see `run_questions`). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub answers: Vec, + /// The tickets linked to this one (Jira issue links, tickets its text + /// names), as the Jira app sends them: their acceptance criteria are + /// part of the change (`related_tickets`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub related: Vec, /// The id the new run takes, when whoever sent the ticket named it /// first (answering on the dashboard links the asking run to the run /// that picks the answers up). A continuation keeps its own id. @@ -1253,6 +1258,7 @@ impl Default for TicketMessage { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, } } diff --git a/services/common/src/related_tickets.rs b/services/common/src/related_tickets.rs new file mode 100644 index 000000000..7b946ef8b --- /dev/null +++ b/services/common/src/related_tickets.rs @@ -0,0 +1,645 @@ +//! The tickets and pull requests related to a run's ticket are part of its +//! work, and the pull request says which of their criteria it covers. +//! +//! The failure this was written for: a ticket's pull request was closed by +//! a person who expected another ticket's pull request to cover it (the +//! tickets were linked in Jira). That pull request never read the linked +//! ticket: the drawer's Register button still pointed to the old address +//! when it was called ready. +//! +//! Now: +//! +//! - The Jira app sends the ticket's issue links and the tickets its text +//! names, each with its summary and description ([`Related`]); the +//! gateway keeps them on the run's message. +//! - [`criteria`] reads a ticket's acceptance criteria from its text; the +//! planner is given every related ticket's ([`plan_note`]) and the run +//! keeps them ([`Criterion`]). +//! - A pull request closed in favor of this one (it links this pull +//! request and was closed without merging) brings its own change: +//! [`moved_links`] reads the addresses it replaced, and [`check_source`] +//! says whether this pull request's head made the same move. +//! - Before the pull request is called ready, each criterion is checked +//! where it can be: an address change on the head's files, a link on the +//! preview page ([`link_expectation`], [`check_page`]). One that can't be +//! checked is listed as not covered, with why. [`section`] is what the +//! description shows. + +use serde::{Deserialize, Serialize}; + +/// The marker of the description's related-tickets section. +pub const MARKER: &str = ""; + +/// A ticket related to the run's ticket, as the Jira app sends it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Related { + pub key: String, + /// How it relates ("relates to", "blocks", "is cloned by", "named in + /// the ticket"). + #[serde(default)] + pub relation: String, + #[serde(default)] + pub summary: String, + /// Its description as plain text. + #[serde(default)] + pub body: String, + #[serde(default)] + pub status: String, +} + +/// One acceptance criterion this pull request takes on from a related +/// ticket or a pull request closed in favor of it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Criterion { + /// Where it comes from: a ticket key or `#123`. + pub from: String, + pub text: String, +} + +/// What checking a criterion found. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum Verdict { + /// Covered, with what showed it. + Covered(String), + /// Not covered, with why (what was found, or why it couldn't be + /// checked). + NotCovered(String), +} + +/// The related tickets a Jira app event carries (`related`: key, +/// relation, summary, status, description as a document or text). +pub fn from_payload(payload: &serde_json::Value) -> Vec { + payload["related"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| { + let key = r["key"].as_str()?.trim().to_string(); + if key.is_empty() { + return None; + } + let s = |k: &str| r[k].as_str().unwrap_or("").trim().to_string(); + Some(Related { + key, + relation: s("relation"), + summary: s("summary"), + body: crate::jira_text::body_text(&r["description"]), + status: s("status"), + }) + }) + .take(8) + .collect() +} + +/// Ticket keys a text names (`ABC-123`), without `own` and without +/// repeats, in the order they appear. +pub fn keys_in_text(text: &str, own: &str) -> Vec { + let mut out: Vec = Vec::new(); + let b = text.as_bytes(); + let mut i = 0; + while i < b.len() { + let start_ok = i == 0 || !(b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'-'); + if start_ok && b[i].is_ascii_uppercase() { + let mut j = i; + while j < b.len() && (b[j].is_ascii_uppercase() || b[j].is_ascii_digit()) { + j += 1; + } + if j - i >= 2 && j < b.len() && b[j] == b'-' { + let mut k = j + 1; + while k < b.len() && b[k].is_ascii_digit() { + k += 1; + } + let end_ok = k == b.len() || !b[k].is_ascii_alphanumeric(); + if k > j + 1 && end_ok { + let key = &text[i..k]; + if !key.eq_ignore_ascii_case(own) && !out.iter().any(|o| o == key) { + out.push(key.to_string()); + } + i = k; + continue; + } + } + i = j.max(i + 1); + continue; + } + i += 1; + } + out +} + +fn is_heading(line: &str) -> bool { + let t = line.trim(); + t.starts_with('#') + || (t.starts_with("**") && t.ends_with("**")) + || (t.ends_with(':') && t.len() < 60 && !t.starts_with('-') && !t.starts_with('*')) +} + +fn criteria_heading(line: &str) -> bool { + let t = line.to_ascii_lowercase(); + t.contains("acceptance criteria") + || t.contains("acceptance criterion") + || t.contains("definition of done") + || t.trim() + .trim_start_matches('#') + .trim() + .trim_end_matches(':') + == "ac" +} + +fn item(line: &str) -> Option<&str> { + let t = line.trim_start(); + for p in ["- [ ] ", "- [x] ", "- ", "* ", "+ ", "• "] { + if let Some(r) = t.strip_prefix(p) { + return Some(r.trim()); + } + } + let d = t.chars().take_while(|c| c.is_ascii_digit()).count(); + if d > 0 && (t[d..].starts_with(". ") || t[d..].starts_with(") ")) { + return Some(t[d + 2..].trim()); + } + None +} + +/// A ticket's acceptance criteria: the items under its "Acceptance +/// criteria" (or "Definition of done") heading. With no such heading, the +/// items of its text when it is a list of what must be true, else nothing. +pub fn criteria(text: &str) -> Vec { + let lines: Vec<&str> = text.lines().collect(); + let mut out = Vec::new(); + if let Some(at) = lines.iter().position(|l| criteria_heading(l)) { + // "Acceptance criteria: the button links to /x" on one line. + if let Some((_, rest)) = lines[at].split_once(':') { + let rest = rest.trim(); + if rest.len() > 8 { + out.push(rest.to_string()); + } + } + let rest = &lines[at + 1..]; + for (k, l) in rest.iter().enumerate() { + if let Some(i) = item(l) { + if !i.is_empty() { + out.push(i.to_string()); + } + } else if l.trim().is_empty() { + // A blank line ends the list unless more items follow it. + let next = rest[k + 1..].iter().find(|n| !n.trim().is_empty()); + if !out.is_empty() && next.is_none_or(|n| item(n).is_none()) { + break; + } + } else if is_heading(l) || !out.is_empty() { + break; + } + } + return out; + } + lines + .iter() + .filter_map(|l| item(l)) + .filter(|i| { + let i = i.to_ascii_lowercase(); + [ + " should ", + " must ", + "links to", + "points to", + "goes to", + "opens ", + ] + .iter() + .any(|w| i.contains(w)) + }) + .map(str::to_string) + .collect() +} + +/// Every related ticket's criteria; a ticket with none brings its summary +/// as the one thing it asks for. +pub fn fold(related: &[Related]) -> Vec { + let mut out = Vec::new(); + for r in related { + let mut c = criteria(&r.body); + if c.is_empty() && !r.summary.trim().is_empty() { + c.push(r.summary.trim().to_string()); + } + for text in c { + out.push(Criterion { + from: r.key.clone(), + text, + }); + } + } + out +} + +/// What the planner reads about the related tickets: their criteria are +/// part of this change unless the plan says why one isn't. +pub fn plan_note(related: &[Related]) -> String { + if related.is_empty() { + return String::new(); + } + let mut s = String::from( + "\n\n## Related tickets\nThese tickets are linked to this one. Their acceptance criteria are \ + part of this change: plan a task for each, or say in the plan why one is not this \ + change's.\n", + ); + for r in related { + s.push_str(&format!( + "- {} ({}): {}\n", + r.key, + if r.relation.is_empty() { + "related" + } else { + &r.relation + }, + r.summary.trim() + )); + let mut c = criteria(&r.body); + if c.is_empty() { + c = r + .body + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .take(6) + .map(str::to_string) + .collect(); + } + for line in c.iter().take(12) { + s.push_str(&format!(" - {}\n", crate::truncate_str(line, 300))); + } + } + s +} + +fn is_addr_char(c: char) -> bool { + c.is_ascii_alphanumeric() || "-._~:/?#[]@!$&'()*+,;=%".contains(c) +} + +/// The addresses in a line: `https://` links and site paths (`/a/b`). +pub fn addresses(line: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = line; + while let Some(i) = rest.find("https://").or_else(|| rest.find("http://")) { + let tail = &rest[i..]; + let end = tail.find(|c: char| !is_addr_char(c)).unwrap_or(tail.len()); + let a = tail[..end].trim_end_matches(['.', ',', ';', ')', '\'', '"']); + out.push(a.to_string()); + rest = &tail[end..]; + } + // Quoted site paths: "/venue/register", '/x', `/x`. + for q in ['"', '\'', '`'] { + let parts: Vec<&str> = line.split(q).collect(); + for (k, p) in parts.iter().enumerate() { + if k % 2 == 1 + && p.starts_with('/') + && !p.starts_with("//") + && p.len() > 1 + && p.chars().all(is_addr_char) + && !out.iter().any(|o| o == p) + { + out.push(p.to_string()); + } + } + } + out +} + +/// An address one change replaced with another in one file: the pull +/// request closed in favor of this one moved `from` to `to` in `path`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MovedLink { + pub path: String, + pub from: String, + pub to: String, +} + +/// The addresses a patch replaced: a removed line's address whose line was +/// replaced by one with a different address, in the same hunk. +pub fn moved_links(path: &str, patch: &str) -> Vec { + let mut out = Vec::new(); + let mut removed: Vec = Vec::new(); + let mut added: Vec = Vec::new(); + let mut flush = |removed: &mut Vec, added: &mut Vec| { + for (r, a) in removed.iter().zip(added.iter()) { + if r != a { + let m = MovedLink { + path: path.to_string(), + from: r.clone(), + to: a.clone(), + }; + if !out.contains(&m) { + out.push(m); + } + } + } + removed.clear(); + added.clear(); + }; + for line in patch.lines() { + if line.starts_with("+++") || line.starts_with("---") { + continue; + } + if let Some(l) = line.strip_prefix('-') { + if !added.is_empty() { + flush(&mut removed, &mut added); + } + removed.extend(addresses(l)); + } else if let Some(l) = line.strip_prefix('+') { + added.extend(addresses(l)); + } else { + flush(&mut removed, &mut added); + } + } + flush(&mut removed, &mut added); + out +} + +/// Whether this pull request's head made the move: `content` is the file +/// at the head (`None` when it doesn't exist there). +pub fn check_source(m: &MovedLink, content: Option<&str>) -> Verdict { + match content { + None => Verdict::NotCovered(format!( + "`{}` is not on this branch; the closed pull request changed `{}` to `{}` there", + m.path, m.from, m.to + )), + Some(c) if c.contains(&m.from) && !c.contains(&m.to) => Verdict::NotCovered(format!( + "`{}` still uses `{}`; the closed pull request changed it to `{}`", + m.path, m.from, m.to + )), + Some(c) if c.contains(&m.from) => Verdict::NotCovered(format!( + "`{}` uses `{}` but still also `{}`", + m.path, m.to, m.from + )), + Some(c) if c.contains(&m.to) => Verdict::Covered(format!("`{}` uses `{}`", m.path, m.to)), + Some(_) => Verdict::NotCovered(format!( + "`{}` has neither `{}` nor `{}`: the link moved somewhere this check doesn't read", + m.path, m.from, m.to + )), + } +} + +/// A criterion that names a control and where it goes: "the Register +/// button links to /camps/register". +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LinkExpectation { + /// The control's visible text. + pub label: String, + pub target: String, +} + +/// The control and address a criterion names, when it names both. +pub fn link_expectation(text: &str) -> Option { + let target = addresses(text).into_iter().next().or_else(|| { + text.split_whitespace() + .map(|w| w.trim_matches(|c: char| ",.;:()".contains(c))) + .find(|w| w.starts_with('/') && w.len() > 1 && w.chars().all(is_addr_char)) + .map(str::to_string) + })?; + // A quoted label first ("Register"), else the word before "button" or + // "link". + let quoted = ['"', '“', '\''].iter().find_map(|q| { + let close = if *q == '“' { '”' } else { *q }; + let start = text.find(*q)? + q.len_utf8(); + let end = text[start..].find(close)? + start; + let l = text[start..end].trim(); + (!l.is_empty() && !l.starts_with('/') && !l.starts_with("http") && l.len() < 40) + .then(|| l.to_string()) + }); + let label = quoted.or_else(|| { + let words: Vec<&str> = text.split_whitespace().collect(); + words.iter().enumerate().find_map(|(i, w)| { + let w = w.to_ascii_lowercase(); + (i > 0 && (w.starts_with("button") || w.starts_with("link") || w.starts_with("cta"))) + .then(|| { + words[i - 1] + .trim_matches(|c: char| !c.is_alphanumeric()) + .to_string() + }) + .filter(|l| { + !l.is_empty() && !["the", "a", "an"].contains(&l.to_ascii_lowercase().as_str()) + }) + }) + })?; + Some(LinkExpectation { label, target }) +} + +fn strip_tags(s: &str) -> String { + let mut out = String::new(); + let mut in_tag = false; + for c in s.chars() { + match c { + '<' => in_tag = true, + '>' => in_tag = false, + _ if !in_tag => out.push(c), + _ => {} + } + } + out.split_whitespace().collect::>().join(" ") +} + +fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + let at = tag.find(&format!("{name}="))? + name.len() + 1; + let rest = &tag[at..]; + let q = rest.chars().next()?; + if q == '"' || q == '\'' { + let end = rest[1..].find(q)? + 1; + Some(&rest[1..end]) + } else { + let end = rest + .find(|c: char| c.is_whitespace() || c == '>') + .unwrap_or(rest.len()); + Some(&rest[..end]) + } +} + +fn same_target(href: &str, target: &str) -> bool { + let norm = |s: &str| s.trim_end_matches('/').to_ascii_lowercase(); + let (h, t) = (norm(href), norm(target)); + h == t || h.ends_with(&t) || (t.ends_with(&h) && !h.is_empty() && h.starts_with('/')) +} + +/// What the preview page's HTML says about a link expectation: the links +/// whose text is the label, and where they go. `None` when no link with +/// that text is on the page (it is drawn later, or in a drawer the page +/// opens): the page alone can't say. +pub fn check_page(page: &str, html: &str, e: &LinkExpectation) -> Option { + let lower = html.to_ascii_lowercase(); + let label = e.label.to_ascii_lowercase(); + let mut seen: Vec = Vec::new(); + let mut from = 0; + while let Some(i) = lower[from..].find("').map(|j| start + j) else { + break; + }; + let Some(close) = lower[tag_end..].find("").map(|j| tag_end + j) else { + break; + }; + let text = strip_tags(&html[tag_end + 1..close]).to_ascii_lowercase(); + let tag = &html[start..=tag_end]; + if text.contains(&label) + || attr(tag, "aria-label").is_some_and(|a| a.to_ascii_lowercase().contains(&label)) + { + if let Some(href) = attr(tag, "href") { + if same_target(href, &e.target) { + return Some(Verdict::Covered(format!( + "on {page}, the \"{}\" link goes to `{href}`", + e.label + ))); + } + seen.push(href.to_string()); + } + } + from = close + 4; + } + seen.first().map(|h| { + Verdict::NotCovered(format!( + "on {page}, the \"{}\" link goes to `{h}`, not `{}`", + e.label, e.target + )) + }) +} + +/// The description's related-tickets section: each criterion with what +/// checking it found. +pub fn section(results: &[(Criterion, Verdict)]) -> String { + if results.is_empty() { + return String::new(); + } + let mut s = format!("{MARKER}\n### Related tickets\n"); + for (c, v) in results { + let text = crate::truncate_str(c.text.trim(), 160); + match v { + Verdict::Covered(how) => { + s.push_str(&format!("- {}: {text}: covered ({how})\n", c.from)) + } + Verdict::NotCovered(why) => { + s.push_str(&format!("- {}: {text}: **not covered**: {why}\n", c.from)) + } + } + } + s +} + +/// `body` with its related-tickets section replaced by `section` (added at +/// the end when it has none; taken out when `section` is empty). +pub fn with_section(body: &str, section: &str) -> String { + let mut out: Vec<&str> = Vec::new(); + let mut skipping = false; + for line in body.lines() { + if line.trim() == MARKER { + skipping = true; + continue; + } + if skipping { + if line.trim() == "### Related tickets" || line.starts_with("- ") { + continue; + } + skipping = false; + } + out.push(line); + } + let kept = out.join("\n"); + if section.is_empty() { + return kept; + } + format!("{}\n\n{}\n", kept.trim_end(), section.trim_end()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn related_tickets_come_from_the_app_event() { + let p = serde_json::json!({"related": [ + {"key": "ABC-2", "relation": "relates to", "summary": "Drawer button", "status": "Closed", + "description": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Links to /new\"}]}]}"}, + {"relation": "no key"} + ]}); + let r = from_payload(&p); + assert_eq!(r.len(), 1); + assert_eq!(r[0].key, "ABC-2"); + assert!(r[0].body.contains("Links to /new"), "{}", r[0].body); + assert!(from_payload(&serde_json::json!({})).is_empty()); + } + + #[test] + fn keys_named_in_text() { + assert_eq!( + keys_in_text( + "See ABC-12 and XY-3; not ABC-12 again, not abc-1, not OWN-1.", + "OWN-1" + ), + vec!["ABC-12", "XY-3"] + ); + } + + #[test] + fn criteria_under_their_heading() { + let t = "What & why\nChange the button.\n\nAcceptance criteria\n- The Register button links to /camps/register\n- Opens in the same tab\n\nNotes\n- not this\n"; + assert_eq!( + criteria(t), + vec![ + "The Register button links to /camps/register", + "Opens in the same tab" + ] + ); + } + + #[test] + fn a_moved_link_is_read_from_the_patch_and_checked_on_the_head() { + let patch = "@@ -10,3 +10,3 @@\n \n- \n+ \n \n"; + let m = moved_links("src/drawer.tsx", patch); + assert_eq!(m.len(), 1); + assert_eq!(m[0].from, "/old/register"); + assert_eq!(m[0].to, "/camps/register"); + let old = ""; + assert!(matches!( + check_source(&m[0], Some(old)), + Verdict::NotCovered(_) + )); + let new = ""; + assert!(matches!( + check_source(&m[0], Some(new)), + Verdict::Covered(_) + )); + } + + #[test] + fn a_link_criterion_is_checked_on_the_page() { + let e = + link_expectation("The drawer's \"Register\" button links to /camps/register").unwrap(); + assert_eq!(e.label, "Register"); + assert_eq!(e.target, "/camps/register"); + let old = r#""#; + assert!(matches!( + check_page("the preview", old, &e), + Some(Verdict::NotCovered(_)) + )); + let new = r#"Register"#; + assert!(matches!( + check_page("the preview", new, &e), + Some(Verdict::Covered(_)) + )); + assert_eq!(check_page("the preview", "

nothing

", &e), None); + } + + #[test] + fn the_section_replaces_itself() { + let c = Criterion { + from: "ABC-2".into(), + text: "Register links to /x".into(), + }; + let s1 = section(&[(c.clone(), Verdict::NotCovered("not checked".into()))]); + let b1 = with_section("## Summary\nx\n", &s1); + let s2 = section(&[(c, Verdict::Covered("ok".into()))]); + let b2 = with_section(&b1, &s2); + assert_eq!(b2.matches(MARKER).count(), 1, "{b2}"); + assert!( + b2.contains("covered (ok)") && !b2.contains("not checked"), + "{b2}" + ); + assert!(b2.starts_with("## Summary")); + } +} diff --git a/services/common/src/ticket_decisions.rs b/services/common/src/ticket_decisions.rs new file mode 100644 index 000000000..2c88fe8a3 --- /dev/null +++ b/services/common/src/ticket_decisions.rs @@ -0,0 +1,560 @@ +//! What a person answered on the ticket is a decision, in every run and on +//! every pull request for it. +//! +//! The failure this was written for: a run asked on its ticket for the +//! page's heading and intro copy, with a proposed default. The product +//! owner answered on the ticket ("Skip the heading and intro copy. Just use +//! the title."). That run took the answer as a round on its own pull +//! request. Two days later a new run on the same ticket opened a new pull +//! request: the answer was already marked handled, so the new run never +//! read it, built the intro anyway and listed it under "Decisions pending +//! product input". +//! +//! Now: +//! +//! - [`from_comments`]: every answer and instruction a person wrote on the +//! ticket is a decision for every run on it, whichever run handled it. +//! The worker merges them into the run's answers before triage and +//! planning, and before each round. +//! - [`settle`]: a description never lists an answered item as pending. An +//! item under a pending heading ("pending", "open questions", "awaiting +//! product") that an answer settles ([`answers_item`]: it shares the +//! question's words) is taken out, and the answer is listed under +//! "Decided on the ticket". When an answer goes against an acceptance +//! criterion of the ticket, one line says so ([`conflict`]). +//! - [`remember`] keeps a ticket's decisions for the description writer +//! (`description::save`), which knows the ticket from the description's +//! own "Ticket:" line ([`ticket_of`]). + +use crate::run_questions::Answer; +use crate::ticket_comments::{Class, Comment}; +use std::collections::{HashMap, HashSet}; +use std::sync::Mutex; + +/// The heading the answered items are listed under. +pub const DECIDED_HEADING: &str = "### Decided on the ticket"; + +/// Every answer or instruction a person wrote on the ticket, whatever run +/// read it and whatever state it is in, as answers (oldest first). +pub fn from_comments(comments: &[Comment]) -> Vec { + let mut sorted: Vec<&Comment> = comments + .iter() + .filter(|c| matches!(c.class, Some(Class::Answer) | Some(Class::Instruction))) + .filter(|c| !c.text.trim().is_empty()) + .collect(); + sorted.sort_by(|a, b| a.at.cmp(&b.at)); + sorted + .into_iter() + .map(|c| Answer { + question_id: format!("ticket-comment-{}", c.comment_id), + question: c.question.trim().to_string(), + answer: c.text.trim().to_string(), + author: c.author.clone(), + answered_at: c.at.clone(), + decision: String::new(), + }) + .collect() +} + +const STOP: &[&str] = &[ + "the", + "and", + "for", + "per", + "with", + "this", + "that", + "what", + "which", + "are", + "is", + "be", + "to", + "of", + "in", + "on", + "or", + "a", + "an", + "it", + "its", + "as", + "by", + "at", + "we", + "i", + "you", + "do", + "does", + "should", + "would", + "could", + "will", + "can", + "one", + "plus", + "default", + "proposed", + "building", + "now", + "different", + "answer", + "changes", + "change", + "use", + "using", + "final", + "pending", + "product", + "input", + "decision", + "decide", + "until", + "awaiting", + "yes", + "no", + "not", + "just", + "only", + "skip", +]; + +/// The words that carry meaning: lowercase, letters and digits, two or +/// more characters, no filler. +fn words(text: &str) -> HashSet { + text.split(|c: char| !c.is_alphanumeric()) + .map(|w| w.to_ascii_lowercase()) + .filter(|w| w.len() >= 2 && !STOP.contains(&w.as_str())) + .collect() +} + +/// Whether `a` settles the pending `item`: its question shares at least +/// two meaningful words with the item and half of the shorter's. +pub fn answers_item(item: &str, a: &Answer) -> bool { + let asked = if a.question.trim().is_empty() { + &a.answer + } else { + &a.question + }; + // The question's first sentence is what was asked; the rest is the + // proposal around it. + let head = asked.split(['?', '\n']).next().unwrap_or(asked).to_string(); + let q = words(&head); + let i = words(item); + if q.is_empty() || i.is_empty() { + return false; + } + let shared = q.intersection(&i).count(); + shared >= 2 && shared * 2 >= q.len().min(i.len()) +} + +/// Whether a heading names items that wait on someone's decision. +pub fn pending_heading(line: &str) -> bool { + let h = line + .trim() + .trim_start_matches('#') + .trim() + .trim_matches('*') + .trim() + .to_ascii_lowercase(); + if h.is_empty() || h.len() > 80 { + return false; + } + [ + "pending", + "open question", + "awaiting", + "needs product", + "product input", + "to decide", + "undecided", + "decisions needed", + "needs a decision", + "unresolved", + ] + .iter() + .any(|k| h.contains(k)) +} + +fn is_heading(line: &str) -> bool { + let t = line.trim(); + t.starts_with('#') || (t.starts_with("**") && t.ends_with("**") && t.len() > 4) +} + +fn list_item(line: &str) -> Option<&str> { + let t = line.trim_start(); + for p in ["- [ ] ", "- [x] ", "- ", "* ", "+ "] { + if let Some(rest) = t.strip_prefix(p) { + return Some(rest); + } + } + let digits = t.chars().take_while(|c| c.is_ascii_digit()).count(); + if digits > 0 && t[digits..].starts_with(". ") { + return Some(&t[digits + 2..]); + } + None +} + +/// Words that say an answer takes something out or does without it. +const WITHOUT: &[&str] = &[ + "skip", + "drop", + "remove", + "without", + "don't", + "do not", + "no ", + "omit", + "leave out", + "just use", + "only use", + "instead", +]; + +/// The one line on an answer that goes against an acceptance criterion: +/// the answer does without something a criterion asks for (they share two +/// meaningful words). `None` when no criterion is at odds with it. +pub fn conflict(a: &Answer, criteria: &[String]) -> Option { + let said = a.answer.to_ascii_lowercase(); + if !WITHOUT.iter().any(|w| said.contains(w)) { + return None; + } + let aw = words(&a.answer); + criteria.iter().find_map(|c| { + let shared = words(c).intersection(&aw).count(); + (shared >= 2).then(|| { + format!( + "The answer on the ticket (\"{}\") goes against the acceptance criterion \"{}\"; \ + the change follows the answer.", + crate::truncate_str(first_line(&a.answer), 120), + crate::truncate_str(c.trim(), 120) + ) + }) + }) +} + +fn first_line(s: &str) -> &str { + s.lines().next().unwrap_or(s).trim() +} + +/// A description with every answered item taken out of its pending lists. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Settled { + pub body: String, + /// The pending items taken out. + pub removed: Vec, +} + +/// Takes every item an answer settles out of the description's pending +/// sections (and a pending heading left with no item), and lists the +/// answers that settled them under [`DECIDED_HEADING`] with, for an answer +/// against an acceptance criterion, the one line that says so. +pub fn settle(body: &str, answers: &[Answer], criteria: &[String]) -> Settled { + if answers.is_empty() { + return Settled { + body: body.to_string(), + removed: Vec::new(), + }; + } + let lines: Vec<&str> = body.lines().collect(); + let mut keep = vec![true; lines.len()]; + let mut removed = Vec::new(); + let mut used: Vec = Vec::new(); + let mut i = 0; + while i < lines.len() { + if !(is_heading(lines[i]) && pending_heading(lines[i])) { + i += 1; + continue; + } + let head = i; + let mut items_left = 0; + let mut taken = 0; + let mut j = i + 1; + while j < lines.len() && !is_heading(lines[j]) { + if let Some(item) = list_item(lines[j]) { + match answers.iter().position(|a| answers_item(item, a)) { + Some(k) => { + keep[j] = false; + taken += 1; + removed.push(item.trim().to_string()); + if !used.contains(&k) { + used.push(k); + } + // The item's continuation lines go with it. + let mut c = j + 1; + while c < lines.len() + && !lines[c].trim().is_empty() + && list_item(lines[c]).is_none() + && !is_heading(lines[c]) + && lines[c].starts_with(" ") + { + keep[c] = false; + c += 1; + } + j = c; + continue; + } + None => items_left += 1, + } + } + j += 1; + } + if items_left == 0 && taken > 0 { + keep[head] = false; + // The blank lines and prose of an emptied section go too. + for (k, line) in lines.iter().enumerate().take(j).skip(head + 1) { + if list_item(line).is_none() { + keep[k] = false; + } + } + } + i = j; + } + if used.is_empty() { + return Settled { + body: body.to_string(), + removed, + }; + } + let mut out: Vec = lines + .iter() + .zip(&keep) + .filter(|(_, k)| **k) + .map(|(l, _)| l.to_string()) + .collect(); + let mut decided: Vec = Vec::new(); + for k in used { + let a = &answers[k]; + let asked = if a.question.is_empty() { + String::new() + } else { + format!( + "{}: ", + crate::truncate_str(a.question.split('?').next().unwrap_or("").trim(), 100) + ) + }; + let by = if a.author.trim().is_empty() { + String::new() + } else { + format!(" ({})", a.author.trim()) + }; + decided.push(format!( + "- {asked}\"{}\"{by}", + crate::truncate_str(first_line(&a.answer), 160) + )); + if let Some(c) = conflict(a, criteria) { + decided.push(format!("- {c}")); + } + } + match out.iter().position(|l| l.trim() == DECIDED_HEADING) { + Some(at) => { + let mut at = at + 1; + for d in decided { + if !out.contains(&d) { + out.insert(at, d); + at += 1; + } + } + } + None => { + while out.last().is_some_and(|l| l.trim().is_empty()) { + out.pop(); + } + out.push(String::new()); + out.push(DECIDED_HEADING.to_string()); + out.extend(decided); + } + } + let mut body_out = out.join("\n"); + if body.ends_with('\n') { + body_out.push('\n'); + } + Settled { + body: body_out, + removed, + } +} + +/// The ticket key a description names on its "Ticket:" line. +pub fn ticket_of(body: &str) -> Option { + for line in body.lines() { + let Some(rest) = line.trim().strip_prefix("Ticket:") else { + continue; + }; + let rest = rest.trim().trim_start_matches('['); + let key: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '#') + .collect(); + if !key.is_empty() { + return Some(key.to_ascii_uppercase()); + } + } + None +} + +/// A ticket's decisions and acceptance criteria, as the worker last read +/// them, for [`settle`] where a description is written. +#[derive(Debug, Clone, Default)] +pub struct Known { + pub answers: Vec, + pub criteria: Vec, +} + +static KNOWN: Mutex>> = Mutex::new(None); + +/// The most tickets kept in memory at once. +const MAX_KNOWN: usize = 64; + +/// The key of a ticket's decisions: the GitHub App installation the run +/// writes with, its repository and the ticket. One team's decisions are +/// read back only by writes made with that team's own installation. +fn known_key(installation: u64, repo: &str, ticket: &str) -> String { + format!( + "{installation}:{}@{}", + repo.to_ascii_lowercase(), + ticket.to_ascii_uppercase() + ) +} + +/// Keeps `ticket`'s decisions for the descriptions written in `repo` with +/// `installation`. +pub fn remember(installation: u64, repo: &str, ticket: &str, known: Known) { + if ticket.trim().is_empty() { + return; + } + if let Ok(mut m) = KNOWN.lock() { + let m = m.get_or_insert_with(HashMap::new); + if m.len() >= MAX_KNOWN { + m.clear(); + } + m.insert(known_key(installation, repo, ticket), known); + } +} + +/// What [`remember`] kept for `ticket` in `repo`. +pub fn recall(installation: u64, repo: &str, ticket: &str) -> Option { + KNOWN + .lock() + .ok()? + .as_ref()? + .get(&known_key(installation, repo, ticket)) + .cloned() +} + +/// [`settle`] with what is known for the ticket the description names. +pub fn settle_known(installation: u64, repo: &str, body: &str) -> Settled { + let none = || Settled { + body: body.to_string(), + removed: Vec::new(), + }; + let Some(ticket) = ticket_of(body) else { + return none(); + }; + let Some(k) = recall(installation, repo, &ticket) else { + return none(); + }; + settle(body, &k.answers, &k.criteria) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn answer(q: &str, a: &str) -> Answer { + Answer { + question: q.into(), + answer: a.into(), + author: "a-person".into(), + ..Default::default() + } + } + + #[test] + fn an_answered_item_leaves_the_pending_list() { + let body = "## Summary\nAdds the page.\n\n### Decisions pending product input\n- Final heading and intro copy per venue: built with the default for now.\n- Analytics event names\n\n## Testing\n- unit tests\n"; + let a = answer( + "Final heading and intro copy per venue? Proposed default: '{Venue} Camp Registration'.", + "Skip the heading and intro copy. Just use the title", + ); + let s = settle(body, &[a], &[]); + assert!( + !s.body.contains("intro copy per venue: built"), + "{}", + s.body + ); + assert!(s.body.contains("Analytics event names")); + assert!(s.body.contains("### Decisions pending product input")); + assert!(s.body.contains(DECIDED_HEADING)); + assert_eq!(s.removed.len(), 1); + } + + #[test] + fn an_emptied_pending_section_goes() { + let body = "## Summary\nx\n\n**Open questions**\n- Heading and intro copy for each venue\n\n## Testing\n- ok\n"; + let a = answer( + "Heading and intro copy per venue?", + "Skip both, use the title", + ); + let s = settle(body, &[a], &[]); + assert!(!s.body.contains("Open questions"), "{}", s.body); + assert!(s.body.contains("## Testing")); + } + + #[test] + fn an_unrelated_answer_changes_nothing() { + let body = "### Pending\n- Analytics event names\n"; + let s = settle(body, &[answer("Which venue goes first?", "Venue A")], &[]); + assert_eq!(s.body, body); + } + + #[test] + fn an_answer_against_a_criterion_is_said_in_one_line() { + let a = answer( + "Heading and intro copy?", + "Skip the heading and intro copy. Just use the title", + ); + let c = conflict( + &a, + &["Each page shows a heading and intro copy above the portal".into()], + ) + .unwrap(); + assert!(c.contains("goes against the acceptance criterion"), "{c}"); + assert_eq!(c.lines().count(), 1); + assert!(conflict(&a, &["The portal loads at phone width".into()]).is_none()); + } + + #[test] + fn the_ticket_comes_from_the_description() { + assert_eq!( + ticket_of("Ticket: [ABC-12](https://x.atlassian.net/browse/ABC-12)\n").as_deref(), + Some("ABC-12") + ); + assert_eq!(ticket_of("no ticket").as_deref(), None); + } + + #[test] + fn every_answer_and_instruction_counts_whatever_run_handled_it() { + use crate::ticket_comments::State; + let c = |id: &str, class: Class, at: &str| Comment { + ticket_id: "ABC-1".into(), + comment_id: id.into(), + author: "a-person".into(), + text: format!("text {id}"), + at: at.into(), + run_id: "an-earlier-run".into(), + state: State::Handled, + class: Some(class), + ..Default::default() + }; + let got = from_comments(&[ + c("2", Class::Instruction, "2026-01-02"), + c("1", Class::Answer, "2026-01-01"), + c("3", Class::NotForCoderhelm, "2026-01-03"), + ]); + assert_eq!( + got.iter().map(|a| a.answer.as_str()).collect::>(), + ["text 1", "text 2"] + ); + } +} diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index c358db57a..4d6efec7a 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -794,6 +794,9 @@ async fn process_jira_payload( requester, image_attachments, ticket_type: common::messages::ticket_type_of_jira(issue), + // The tickets linked to this one: their criteria are part of the + // change (`related_tickets`). + related: common::related_tickets::from_payload(payload), ..Default::default() }); diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index eee30381b..6ed9a1099 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -323,6 +323,7 @@ mod tests { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }); let json = serde_json::to_string(&msg).unwrap(); diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 8ed0fe504..3ff00e23b 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -61,6 +61,21 @@ pub async fn save( number: u64, body: &str, ) -> Result<(), Error> { + // An item a person answered on the ticket is a decision, never pending + // (`ticket_decisions`). + let settled = common::ticket_decisions::settle_known( + github.installation_id(), + &format!("{owner}/{repo}"), + body, + ); + if !settled.removed.is_empty() { + warn!( + pr_number = number, + items = ?settled.removed, + "The description listed answered items as pending; moved to the decisions" + ); + } + let body = settled.body.as_str(); let body = clean(body); // The final review, as its reader would read it: no running check as a // result, nothing CoderHelm can do handed to a person, nothing said diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 15f40dca2..b3d55beb8 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1791,6 +1791,7 @@ pub(super) fn internal_ticket( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: Some(run_id.to_string()), } } @@ -2010,6 +2011,7 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }; enqueue(state, crate::models::WorkerMessage::Ticket(ticket)).await?; diff --git a/services/worker/src/passes/e2e_attribution.rs b/services/worker/src/passes/e2e_attribution.rs index 33689f4d4..8c27c3428 100644 --- a/services/worker/src/passes/e2e_attribution.rs +++ b/services/worker/src/passes/e2e_attribution.rs @@ -498,6 +498,7 @@ async fn start_fix( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }; let Ok(body) = serde_json::to_string(&crate::models::WorkerMessage::Ticket(ticket)) else { diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 87e1c6d40..b8ff844e4 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -726,6 +726,22 @@ Rules: comments = formatted, ci_failures = ci_failure_block, ); + // What people answered on the ticket is settled for this round too, and + // the description it may rewrite never lists it as pending. + let ticket_answers = super::ticket_comments::know_decisions( + state, + msg.installation_id, + &msg.team_id, + &ticket.0, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + "", + &[], + ) + .await; + let prompt = format!( + "{prompt}{}", + common::run_questions::answers_note(&ticket_answers) + ); // The branch update was done before this round and its answer is added // to the reply for the agent. let prompt = match &update_reply { @@ -3474,6 +3490,7 @@ async fn handle_wrong_repo( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }); @@ -4080,6 +4097,7 @@ fn run_ticket_message( coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, } } diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index d60fbf597..9d89c9dd0 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -277,6 +277,9 @@ pub async fn run( // (the snapshot reflects the branch, so the partial code is already visible). // A ticket update on an open PR uses the same slot: the branch already // holds work, and the agent must change it to match the new ticket. + // What people answered on the ticket is settled for every round, the + // build and each fix: never built against, never asked again. + let answers_note = common::run_questions::answers_note(&msg.answers); let continuation_note = if let Some(note) = msg.ticket_update_note.as_deref() { note } else if msg.continuation > 0 || msg.retry_of_run { @@ -329,6 +332,7 @@ pub async fn run( let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; let tokens = super::ticket_tokens(msg); let commit_hint = conventions.commit_hint(&tokens); + let issue_with_answers = format!("{issue_source_block}{answers_note}"); let prompt = task_prompt(&TaskPrompt { simple: complexity == "simple", number: msg.issue_number, @@ -338,7 +342,7 @@ pub async fn run( openspec: &openspec_block, files_hint: &files_hint, feedback: &feedback_section, - issue: &issue_source_block, + issue: &issue_with_answers, commit: &commit_hint, }); diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs index 0acdebea9..3199c88c5 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -335,6 +335,7 @@ const CACHES: &[(&str, &str)] = &[ ("common/src/hybrid/client.rs::FAILING", "installation id"), ("common/src/knowledge/search.rs::C", "S3 key under `{team}/knowledge/`, checked by owns_key before the lookup"), ("common/src/knowledge/sources/pace.rs::GATES", "provider rate gate; no data"), + ("common/src/ticket_decisions.rs::KNOWN", "installation id plus `owner/repo@ticket`: read back only by description writes made with that installation"), ("common/src/reply_compose.rs::CACHE", "thread key plus a hash of the whole prompt it was written from"), ("common/src/review_check.rs::REFUSED", "installation id"), ("common/src/usage.rs::P", "model prices; install-wide config"), diff --git a/services/worker/src/passes/incidents/bz_ticket_answer_decides.rs b/services/worker/src/passes/incidents/bz_ticket_answer_decides.rs new file mode 100644 index 000000000..e9a2fe7c2 --- /dev/null +++ b/services/worker/src/passes/incidents/bz_ticket_answer_decides.rs @@ -0,0 +1,123 @@ +//! bz. A run asked on its ticket for a page's heading and intro copy, with +//! a proposed default. The product owner answered on the ticket: "Skip the +//! heading and intro copy. Just use the title." That run took the answer +//! as a round on its own pull request. Two days later a new run on the +//! same ticket opened a new pull request: the comment was already marked +//! handled, so the new run never read it, built the intro anyway and +//! listed it under "Decisions pending product input". +//! +//! Guarantee: every answer and instruction people wrote on the ticket is +//! a decision for every run on it, whichever run handled it: merged into +//! the run's answers before triage and planning, read again at each +//! boundary, and given to every coder round (the build and each fix) and +//! every feedback and resume round. Wherever a description is written +//! (`description::save`), an item the answers settle is taken out of the +//! pending lists and listed under "Decided on the ticket"; an answer that +//! goes against an acceptance criterion gets one line saying so. + +use common::run_questions::Answer; +use common::ticket_comments::{Class, Comment, State}; +use common::ticket_decisions::{ + from_comments, remember, settle, settle_known, Known, DECIDED_HEADING, +}; + +const QUESTION: &str = "Final heading and intro copy per venue? Proposed default: '{Venue} \ + Camp Registration' plus one portal sentence. I am building the default now; a different \ + answer changes it in src/utils/camp-portal-copy.ts."; + +/// The answer as it was kept: handled by the earlier run. +fn handled_answer() -> Comment { + Comment { + ticket_id: "ABC-76".into(), + comment_id: "98054".into(), + author: "a-product-owner".into(), + text: "Skip the H1 and intro copy. Just use the title\n Register for Camps | Example Site" + .into(), + at: "2026-01-14T16:16:36Z".into(), + run_id: "an-earlier-run".into(), + state: State::Handled, + class: Some(Class::Answer), + question: QUESTION.into(), + outcome: "applied as a round on the earlier pull request".into(), + handled_by: "an-earlier-run".into(), + ..Default::default() + } +} + +const DESCRIPTION: &str = "Ticket: [ABC-76](https://example.atlassian.net/browse/ABC-76) + +## Summary +Embeds the camp portal on the four registration pages. + +### Decisions pending product input +- Final H1 and intro copy per venue: built with the default '{Venue} Camp Registration' and one portal sentence until product confirms. +- Whether the portal opens in a new tab on phones + +## Testing +- Unit tests for the route and the embed +"; + +#[test] +fn an_answer_an_earlier_run_handled_is_still_the_answer() { + let answers = from_comments(&[handled_answer()]); + assert_eq!(answers.len(), 1); + assert_eq!(answers[0].question, QUESTION); + assert!(answers[0].answer.starts_with("Skip the H1")); + // The planner reads it as a resolved decision. + let note = common::run_questions::answers_note(&answers); + assert!(note.contains("Skip the H1"), "{note}"); +} + +#[test] +fn the_description_never_lists_an_answered_item_as_pending() { + let answers: Vec = from_comments(&[handled_answer()]); + let criteria = vec!["Each page shows an H1 and intro copy above the portal".to_string()]; + let s = settle(DESCRIPTION, &answers, &criteria); + assert!(!s.body.contains("until product confirms"), "{}", s.body); + // The unanswered item stays pending. + assert!(s.body.contains("opens in a new tab on phones")); + assert!(s.body.contains(DECIDED_HEADING)); + assert!(s.body.contains("Skip the H1 and intro copy")); + // The answer against the criterion is said in one line. + let conflict = s + .body + .lines() + .find(|l| l.contains("goes against the acceptance criterion")) + .expect("one line on the conflict"); + assert!(conflict.contains("H1 and intro copy above the portal")); +} + +#[test] +fn every_description_write_settles_with_what_the_run_knows() { + remember( + 7, + "acme/site", + "ABC-76", + Known { + answers: from_comments(&[handled_answer()]), + criteria: Vec::new(), + }, + ); + let s = settle_known(7, "acme/site", DESCRIPTION); + assert_eq!(s.removed.len(), 1); + // Another repository's description is not this ticket's. + assert!(settle_known(7, "acme/other", DESCRIPTION) + .removed + .is_empty()); + // Nor is another installation's (another team's). + assert!(settle_known(8, "acme/site", DESCRIPTION).removed.is_empty()); + + let save = include_str!("../description.rs"); + let at = save.find("pub async fn save(").unwrap(); + assert!(save[at..at + 900].contains("ticket_decisions::settle_known(")); + // Before triage and planning, at each boundary, and in the rounds that + // run outside the first step. + let passes = include_str!("../mod.rs"); + assert!( + passes.contains("ticket_comments::earlier_answers(state, &msg.team_id, &msg.ticket_id)") + ); + assert!(passes.contains("msg.answers = ticket_comments::know_decisions(")); + assert!(include_str!("../resume.rs").contains("super::ticket_comments::know_decisions(")); + assert!(include_str!("../feedback.rs").contains("super::ticket_comments::know_decisions(")); + assert!(include_str!("../implement.rs").contains("answers_note(&msg.answers)")); +} diff --git a/services/worker/src/passes/incidents/ca_related_ticket_covered.rs b/services/worker/src/passes/incidents/ca_related_ticket_covered.rs new file mode 100644 index 000000000..338c1d7ad --- /dev/null +++ b/services/worker/src/passes/incidents/ca_related_ticket_covered.rs @@ -0,0 +1,122 @@ +//! ca. A ticket's pull request was closed by a person who expected a +//! linked ticket's pull request to cover it. The pull request that was +//! kept never read the linked ticket: when it was called ready, the +//! drawer's Register button still pointed to the old address. +//! +//! Guarantee: the Jira app sends the ticket's issue links and the tickets +//! its text names, with their summaries and descriptions; the gateway +//! keeps them on the run's message, the planner reads their acceptance +//! criteria as part of the change, and the run keeps them. Before the pull +//! request is called ready, each address a pull request closed in favor of +//! this one moved is checked on the head's files, each link criterion is +//! checked on the preview page, and anything else is listed as not covered +//! with why, in the description's "Related tickets" section. + +use crate::passes::related::closed_in_favor; +use common::related_tickets::{ + check_page, check_source, criteria, fold, from_payload, link_expectation, moved_links, + plan_note, section, with_section, Verdict, MARKER, +}; +use serde_json::json; + +const DRAWER: &str = "src/components/nav/register-drawer.tsx"; + +/// The closed pull request's change: the drawer button to the new page. +const CLOSED_PATCH: &str = "@@ -18,7 +18,7 @@ export function RegisterDrawer() { + return ( + +- ++ + + ); +"; + +#[test] +fn the_linked_ticket_reaches_the_plan() { + let event = json!({"related": [{ + "key": "ABC-98", + "relation": "relates to", + "summary": "Drawer Register button goes to the new registration page", + "status": "Closed", + "description": "Acceptance criteria\n- The drawer's \"Register\" button links to /venue-a/summer-camps/register\n" + }]}); + let related = from_payload(&event); + assert_eq!(related.len(), 1); + let c = fold(&related); + assert_eq!(c.len(), 1); + assert_eq!(c[0].from, "ABC-98"); + let note = plan_note(&related); + assert!(note.contains("ABC-98 (relates to)"), "{note}"); + assert!(note.contains("links to /venue-a/summer-camps/register")); + assert_eq!( + criteria("Acceptance criteria\n- one\n- two\n\nNotes\n- not one"), + ["one", "two"] + ); +} + +#[test] +fn the_head_still_pointing_at_the_old_address_is_not_covered() { + let timeline = json!([{"event": "cross-referenced", "source": {"issue": { + "number": 1531, "title": "Drawer Register button to the new page", "state": "closed", + "pull_request": {"merged_at": null}, "repository": {"full_name": "acme/site"}}}}]); + assert_eq!(closed_in_favor(&timeline, "acme/site")[0].0, 1531); + let moves = moved_links(DRAWER, CLOSED_PATCH); + assert_eq!(moves.len(), 1); + let head = ""; + let v = check_source(&moves[0], Some(head)); + match &v { + Verdict::NotCovered(why) => assert!(why.contains("still uses"), "{why}"), + other => panic!("{other:?}"), + } + let fixed = ""; + assert!(matches!( + check_source(&moves[0], Some(fixed)), + Verdict::Covered(_) + )); +} + +#[test] +fn a_link_criterion_is_checked_on_the_preview_and_the_rest_is_listed() { + let e = link_expectation( + "The drawer's \"Register\" button links to /venue-a/summer-camps/register", + ) + .unwrap(); + let old = r#""#; + assert!(matches!( + check_page("the preview", old, &e), + Some(Verdict::NotCovered(_)) + )); + let c = fold(&from_payload( + &json!({"related": [{"key": "ABC-98", "description": + "Acceptance criteria\n- The drawer's \"Register\" button links to /venue-a/summer-camps/register"}]}), + )); + let s = section(&[( + c[0].clone(), + Verdict::NotCovered("not checked: no preview".into()), + )]); + assert!(s.starts_with(MARKER)); + assert!( + s.contains("**not covered**: not checked: no preview"), + "{s}" + ); + let body = with_section("## Summary\nx\n", &s); + assert_eq!(with_section(&body, &s).matches(MARKER).count(), 1); +} + +#[test] +fn ready_checks_them_and_the_jira_app_sends_them() { + let ready = include_str!("../ready.rs"); + assert!(ready.contains("related_section(ctx, &pr, f.preview.as_ref())")); + let passes = include_str!("../mod.rs"); + assert!(passes.contains("related::keep(state, &msg.team_id, run_id, &msg.related)")); + let plan = include_str!("../plan.rs"); + assert_eq!( + plan.matches("related_tickets::plan_note(&msg.related)") + .count(), + 2 + ); + let gateway = include_str!("../../../../gateway/src/routes/jira_webhook.rs"); + assert!(gateway.contains("related: common::related_tickets::from_payload(payload)")); + let app = include_str!("../../../../../coderhelm-jira/src/index.js"); + assert!(app.contains("issuelinks") && app.contains("relatedTickets(issue.key, fields")); +} diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 13e2f3398..fe1d6c0af 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -135,6 +135,7 @@ impl StartEnv for WorkerEnv<'_> { coder_learning: String::new(), person_direction: None, answers: Vec::new(), + related: Vec::new(), new_run_id: None, }); let body = serde_json::to_string(&msg).map_err(|e| e.to_string())?; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 66c58ea2e..f9f4c3d3c 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1350,6 +1350,7 @@ pub mod quarantine_work; /// Whether a finished run's pull request leaves draft, decided in one place. pub mod ready; pub mod recheck; +pub mod related; pub mod relay_retry; pub mod release_notes; pub mod release_plan; @@ -1900,6 +1901,18 @@ async fn read_ticket_comments( ) -> Result<(), Box> { let read = ticket_comments::at_boundary(state, msg, run_id, usage).await; common::run_questions::merge(&mut msg.answers, &read.folded); + // Before the next build or round and before any description: the + // ticket's answers are decisions, never pending items. + msg.answers = ticket_comments::know_decisions( + state, + msg.installation_id, + &msg.team_id, + &msg.ticket_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &msg.body, + &msg.answers, + ) + .await; if read.stopped { // The text `orchestrate_ticket` reads as a person's cancel. return Err("Run cancelled by user".into()); @@ -2146,6 +2159,15 @@ async fn run_passes( .map(common::ticket_state::decision_answer) .collect(); common::run_questions::merge(&mut msg.answers, &decided); + // And every answer people wrote on the ticket itself, whichever earlier + // run handled it: an answer handled by the run before this one is + // still the answer (a new run once built what an answer had ruled out + // and listed it as pending). + let earlier = ticket_comments::earlier_answers(state, &msg.team_id, &msg.ticket_id).await; + common::run_questions::merge(&mut msg.answers, &earlier); + // The linked tickets' acceptance criteria are this run's too: kept so + // the pull request is checked against them before it is called ready. + related::keep(state, &msg.team_id, run_id, &msg.related).await; // What people wrote on the ticket itself: before this run started // (context for the plan) and since its last step. Read here, before // the run spends more work, and again at each boundary below. diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 40e1dedf3..8b4f74812 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -474,9 +474,12 @@ Then the ```fix_location.json block described above."#, Some(h) if !h.trim().is_empty() => format!("{prompt}{h}"), _ => prompt, }; + // The tickets linked to this one: their acceptance criteria are part + // of the change (`related_tickets`). let prompt = format!( - "{prompt}{}", - common::run_questions::answers_note(&msg.answers) + "{prompt}{}{}", + common::run_questions::answers_note(&msg.answers), + common::related_tickets::plan_note(&msg.related) ); // One part of a numbered series: the other parts' pull requests, so // the plan builds on them (see `series`). @@ -901,9 +904,10 @@ Then the ```fix_location.json block described above."#, super::plan_judge::prompt( &msg.title, &format!( - "{}{}", + "{}{}{}", msg.body, - common::run_questions::answers_note(&msg.answers) + common::run_questions::answers_note(&msg.answers), + common::related_tickets::plan_note(&msg.related) ), history_note, &live.as_ref().map(|l| l.connected()).unwrap_or_default(), diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index ba0e17208..837125fca 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1247,6 +1247,15 @@ async fn gather(ctx: &Ctx<'_>) -> Result { f.draft = pr["draft"].as_bool().unwrap_or(f.draft); f.body = pr["body"].as_str().unwrap_or("").to_string(); f.title = pr["title"].as_str().unwrap_or("").to_string(); + // Before it is called ready: each criterion of the linked tickets, and + // each address a pull request closed in favor of this one moved, is + // checked where it can be or listed as not covered with why. + if f.draft && !f.closed { + let section = related_section(ctx, &pr, f.preview.as_ref()).await; + if !section.is_empty() || f.body.contains(common::related_tickets::MARKER) { + f.body = common::related_tickets::with_section(&f.body, §ion); + } + } f.security = f.body.contains(common::security_fixes::MARKER); if reads_ci(&f) { let sha = pr["head"]["sha"].as_str().unwrap_or(""); @@ -1280,6 +1289,40 @@ async fn gather(ctx: &Ctx<'_>) -> Result { Ok(f) } +/// The description's related-tickets section for the head +/// (`passes::related`): empty when the run took on no criterion and no +/// pull request was closed in favor of this one. +async fn related_section( + ctx: &Ctx<'_>, + pr: &serde_json::Value, + preview: Option<&common::preview::State>, +) -> String { + let run_id = if ctx.run_id.is_empty() { + super::review_pr::lookup_run_by_pr(ctx.state, ctx.team_id, ctx.owner, ctx.repo, ctx.pr) + .await + .unwrap_or_default() + } else { + ctx.run_id.clone() + }; + let criteria = if run_id.is_empty() { + Vec::new() + } else { + super::related::kept(ctx.state, ctx.team_id, &run_id).await + }; + let results = super::related::check( + ctx.state, + ctx.github, + ctx.owner, + ctx.repo, + ctx.pr, + pr["head"]["sha"].as_str().unwrap_or(""), + preview.map(|p| p.url.as_str()).unwrap_or(""), + &criteria, + ) + .await; + common::related_tickets::section(&results) +} + /// The head's preview, moved on now (`preview::advance`): its labels added, /// its checks read. None for a pull request no run of CoderHelm's opened. async fn preview_of(ctx: &Ctx<'_>, pr: &serde_json::Value) -> Option { diff --git a/services/worker/src/passes/related.rs b/services/worker/src/passes/related.rs new file mode 100644 index 000000000..e388918dd --- /dev/null +++ b/services/worker/src/passes/related.rs @@ -0,0 +1,215 @@ +//! The worker's side of related tickets (`common::related_tickets`): the +//! run keeps the criteria it took on from linked tickets, and before its +//! pull request is called ready each one, and each address change of a +//! pull request closed in favor of it, is checked where it can be, or +//! listed as not covered with why. + +use crate::clients::github::GitHubClient; +use crate::passes::attr_s; +use crate::WorkerState; +use common::related_tickets::{self as rt, Criterion, Verdict}; +use tracing::warn; + +/// The run record's field holding the criteria taken on from related +/// tickets (JSON). +pub const FIELD: &str = "related_criteria"; + +/// Keeps the criteria of `related` on the run (nothing when none). +pub async fn keep(state: &WorkerState, team_id: &str, run_id: &str, related: &[rt::Related]) { + let criteria = rt::fold(related); + if criteria.is_empty() { + return; + } + let Ok(json) = serde_json::to_string(&criteria) else { + return; + }; + if let Err(e) = 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 #f = :v") + .expression_attribute_names("#f", FIELD) + .expression_attribute_values(":v", attr_s(&json)) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the related tickets' criteria"); + } +} + +/// The criteria the run took on from related tickets. +pub async fn kept(state: &WorkerState, team_id: &str, run_id: &str) -> Vec { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("#f") + .expression_attribute_names("#f", FIELD) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get(FIELD).and_then(|v| v.as_s().ok()).cloned()) + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() +} + +/// The pull requests in a timeline that were closed in favor of this one: +/// in this repository, they link this pull request and were closed without +/// merging. (number, title). +pub fn closed_in_favor(timeline: &serde_json::Value, repo_full: &str) -> Vec<(u64, String)> { + let mut out: Vec<(u64, String)> = Vec::new(); + for e in timeline.as_array().into_iter().flatten() { + if e["event"].as_str() != Some("cross-referenced") { + continue; + } + let i = &e["source"]["issue"]; + let same_repo = i["repository"]["full_name"] + .as_str() + .is_none_or(|r| r.eq_ignore_ascii_case(repo_full)); + let closed_unmerged = i["state"].as_str() == Some("closed") + && i["pull_request"].is_object() + && i["pull_request"]["merged_at"].is_null(); + if let (true, true, Some(n)) = (same_repo, closed_unmerged, i["number"].as_u64()) { + if !out.iter().any(|(m, _)| *m == n) { + out.push((n, i["title"].as_str().unwrap_or("").to_string())); + } + } + } + out +} + +/// The most closed pull requests and address moves read for one check. +const MAX_CLOSED: usize = 3; +const MAX_MOVES: usize = 8; + +/// Every criterion with what checking it found: the address moves of the +/// pull requests closed in favor of this one, on the head's files; the +/// related tickets' link criteria, on the preview page; anything else +/// listed as not covered with why. +#[allow(clippy::too_many_arguments)] +pub async fn check( + state: &WorkerState, + gh: &GitHubClient, + owner: &str, + repo: &str, + pr: u64, + head: &str, + preview_url: &str, + criteria: &[Criterion], +) -> Vec<(Criterion, Verdict)> { + let mut out = Vec::new(); + let timeline = gh + .list_issue_timeline(owner, repo, pr) + .await + .unwrap_or_default(); + for (n, title) in closed_in_favor(&timeline, &format!("{owner}/{repo}")) + .into_iter() + .take(MAX_CLOSED) + { + let files = gh.list_pull_files(owner, repo, n).await.unwrap_or_default(); + let moves: Vec = files + .iter() + .flat_map(|(path, patch)| rt::moved_links(path, patch)) + .take(MAX_MOVES) + .collect(); + if moves.is_empty() { + out.push(( + Criterion { + from: format!("#{n}"), + text: title.clone(), + }, + Verdict::NotCovered( + "closed in favor of this pull request; not checked: its change moves no \ + address this check can compare" + .into(), + ), + )); + continue; + } + for m in moves { + let content = gh + .read_file_if_exists(owner, repo, &m.path, head) + .await + .ok() + .flatten(); + let v = rt::check_source(&m, content.as_deref()); + out.push(( + Criterion { + from: format!("#{n}"), + text: format!("`{}` goes to `{}` ({})", m.path, m.to, title.trim()), + }, + v, + )); + } + } + let wants_page = criteria + .iter() + .any(|c| rt::link_expectation(&c.text).is_some()); + let page = if wants_page && preview_url.starts_with("https://") { + fetch(state, preview_url).await + } else { + None + }; + for c in criteria { + let v = match (rt::link_expectation(&c.text), &page) { + (Some(e), Some(html)) => rt::check_page("the preview", html, &e).unwrap_or_else(|| { + Verdict::NotCovered(format!( + "not checked: the preview page shows no \"{}\" link (it may open in a drawer or \ + load later)", + e.label + )) + }), + (Some(_), None) => { + Verdict::NotCovered("not checked: no preview of this pull request to load".into()) + } + (None, _) => Verdict::NotCovered( + "not checked: it names no link or address a check can load".into(), + ), + }; + out.push((c.clone(), v)); + } + out +} + +/// The preview page's HTML (a page of at most 2 MB), `None` when it can't +/// be loaded. +async fn fetch(state: &WorkerState, url: &str) -> Option { + let resp = state + .http + .get(url) + .timeout(std::time::Duration::from_secs(20)) + .send() + .await + .ok()?; + if !resp.status().is_success() { + return None; + } + let text = resp.text().await.ok()?; + Some(text.chars().take(2_000_000).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_pull_request_closed_unmerged_that_links_this_one_is_in_favor_of_it() { + let t = json!([ + {"event": "cross-referenced", "source": {"issue": {"number": 12, "title": "Point the drawer button to the new page", "state": "closed", "pull_request": {"merged_at": null}, "repository": {"full_name": "acme/site"}}}}, + {"event": "cross-referenced", "source": {"issue": {"number": 13, "state": "closed", "pull_request": {"merged_at": "2026-01-01"}, "repository": {"full_name": "acme/site"}}}}, + {"event": "cross-referenced", "source": {"issue": {"number": 14, "state": "open", "pull_request": {"merged_at": null}, "repository": {"full_name": "acme/site"}}}}, + {"event": "cross-referenced", "source": {"issue": {"number": 15, "state": "closed", "repository": {"full_name": "acme/site"}}}}, + {"event": "labeled"} + ]); + assert_eq!( + closed_in_favor(&t, "acme/site"), + vec![(12, "Point the drawer button to the new page".to_string())] + ); + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 913770c8f..6075a29f5 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3955,7 +3955,19 @@ async fn fix_context( .await, coder_learning: String::new(), person_direction: None, - answers: Vec::new(), + // What people answered on the ticket: every fix and review round + // builds with it, and the description never lists it as pending. + answers: super::ticket_comments::know_decisions( + state, + msg.installation_id, + &msg.team_id, + t.ticket_id, + &format!("{}/{}", t.owner, t.repo), + "", + &[], + ) + .await, + related: Vec::new(), new_run_id: None, }; diff --git a/services/worker/src/passes/ticket_comments.rs b/services/worker/src/passes/ticket_comments.rs index 47ce8bdbb..425731da3 100644 --- a/services/worker/src/passes/ticket_comments.rs +++ b/services/worker/src/passes/ticket_comments.rs @@ -33,6 +33,54 @@ use common::ticket_comments::{self as tc, Action, Comment, Settled, Source, Stag use common::ticket_state::{Intent, Note}; use tracing::{info, warn}; +/// Every answer and instruction people wrote on the ticket, whatever run +/// handled it (`common::ticket_decisions::from_comments`): a new run on the +/// ticket starts from them, never from the question again. +pub async fn earlier_answers(state: &WorkerState, team_id: &str, ticket_id: &str) -> Vec { + match store(state).of_ticket(team_id, ticket_id).await { + Ok(c) => common::ticket_decisions::from_comments(&c), + Err(e) => { + warn!(ticket_id, error = %e, "Could not read the ticket's earlier answers"); + Vec::new() + } + } +} + +/// Keeps the ticket's decisions and acceptance criteria where the +/// description is written (`description::save`), so no description lists +/// an answered item as pending. `answers`: those already in hand; the +/// ticket's own are read and added. +pub async fn know_decisions( + state: &WorkerState, + installation_id: u64, + team_id: &str, + ticket_id: &str, + repo: &str, + ticket_body: &str, + answers: &[Answer], +) -> Vec { + let mut all = answers.to_vec(); + common::run_questions::merge(&mut all, &earlier_answers(state, team_id, ticket_id).await); + // A caller without the ticket's text keeps the criteria read before. + let criteria = if ticket_body.trim().is_empty() { + common::ticket_decisions::recall(installation_id, repo, ticket_id) + .map(|k| k.criteria) + .unwrap_or_default() + } else { + common::related_tickets::criteria(ticket_body) + }; + common::ticket_decisions::remember( + installation_id, + repo, + ticket_id, + common::ticket_decisions::Known { + answers: all.clone(), + criteria, + }, + ); + all +} + /// What a boundary read gives the run. #[derive(Debug, Default)] pub struct Read {