From 87a04cb68867cd0a09adcfeee28a05e7a8a4c8c9 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 18:17:56 -0500 Subject: [PATCH 1/3] A comment written on a ticket while a run works is kept, acknowledged and acted on A run asked three questions on its ticket, proposed defaults and kept building. A person answered on the ticket twenty minutes later. The gateway logged that a run was in progress and dropped the comment: nothing acknowledged it, the run never saw it, and its notes kept saying it went on without the answers. Comments written before any run existed were dropped too, and nothing read them when the run started. Every ticket source now goes through one path (common::ticket_comments): - The gateway keeps the comment once per comment id (a webhook delivered twice is one comment), acknowledges it on the ticket the first time it is seen while a run works (a reaction on GitHub, one short reply in Jira; never for CoderHelm's own comments or other bots), notes it on the run page and tells the worker at once. - The run reads its open comments together when it starts and at its plan, implement, test and pull request boundaries. Answers and instructions go into the plan while it is being made. Once the plan is final they become one feedback round on the pull request when the step ends: the code changes where the plan put the choice, the pull request says what changed, and the ticket is told. A comment that says to stop ends the run at once. - Each comment is claimed in one conditional write before anything is done with it, so it is acted on once. One nobody read stays open for what comes next: the next step, a round on the finished run's pull request, the ticket started again (a run that ended waiting or failed), or the next run on the ticket (a run a person stopped). - Comments written before the run started are read at its first boundary: a Jira ticket's come with its event from the Jira app, a GitHub issue's are read by the run. They are context and never stop the run. Incident case aq_comment_during_run. --- coderhelm-jira/src/comments.js | 35 + coderhelm-jira/src/index.js | 10 +- coderhelm-jira/test/comments.test.js | 40 + docs/incidents.md | 1 + services/common/src/lib.rs | 2 + services/common/src/ticket_comments.rs | 1402 +++++++++++++++++ services/gateway/src/routes/github_webhook.rs | 18 +- services/gateway/src/routes/jira_webhook.rs | 81 +- services/gateway/src/routes/mod.rs | 1 + .../gateway/src/routes/ticket_comments.rs | 624 ++++++++ services/worker/src/main.rs | 10 +- .../passes/incidents/aq_comment_during_run.rs | 288 ++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/jira_comment.rs | 47 +- services/worker/src/passes/mod.rs | 43 +- services/worker/src/passes/ticket_comments.rs | 1056 +++++++++++++ 16 files changed, 3637 insertions(+), 22 deletions(-) create mode 100644 coderhelm-jira/src/comments.js create mode 100644 coderhelm-jira/test/comments.test.js create mode 100644 services/common/src/ticket_comments.rs create mode 100644 services/gateway/src/routes/ticket_comments.rs create mode 100644 services/worker/src/passes/incidents/aq_comment_during_run.rs create mode 100644 services/worker/src/passes/ticket_comments.rs diff --git a/coderhelm-jira/src/comments.js b/coderhelm-jira/src/comments.js new file mode 100644 index 000000000..b5b48ab7d --- /dev/null +++ b/coderhelm-jira/src/comments.js @@ -0,0 +1,35 @@ +/** + * The comments already on a ticket, as CoderHelm reads them when a run starts + * on it: context people gave before the work began. + * + * Jira returns a ticket's comments in its `comment` field (oldest first). The + * gateway keeps each one once, by its id, so sending the same comment with a + * later event changes nothing. It also leaves out the app's own comments (by + * the author's account type and name), so they are passed through as they are. + */ + +/** The most comments sent with one ticket event: the newest ones. */ +const MAX_COMMENTS = 20; + +/** + * @param {object} fields The ticket's fields, as the issue REST API returns them. + * @returns {{id: string, author: {displayName: string, accountType: string}, body: string}[]} + */ +function existingComments(fields) { + const all = (fields && fields.comment && fields.comment.comments) || []; + if (!Array.isArray(all)) return []; + return all + .filter((c) => c && c.id && c.body) + .slice(-MAX_COMMENTS) + .map((c) => ({ + id: String(c.id), + author: { + displayName: (c.author && c.author.displayName) || "", + accountType: (c.author && c.author.accountType) || "", + }, + // A comment body is a document (JSON); the gateway reads its words. + body: typeof c.body === "string" ? c.body : JSON.stringify(c.body), + })); +} + +module.exports = { existingComments, MAX_COMMENTS }; diff --git a/coderhelm-jira/src/index.js b/coderhelm-jira/src/index.js index ccb59f6d0..ccf248058 100644 --- a/coderhelm-jira/src/index.js +++ b/coderhelm-jira/src/index.js @@ -3,6 +3,7 @@ const { fetch } = api; const { storage } = api; const { route } = api; const { GATEWAY_URL } = require("./gateway"); +const { existingComments } = require("./comments"); /** The parts of a Jira user CoderHelm keeps: account id, name, email. */ function jiraUser(u) { @@ -134,7 +135,9 @@ exports.handler = async (event, context) => { comment: { id: comment.id, body: commentBody, - author: { ...jiraUser(author), displayName: authorName }, + // accountType tells a person ("atlassian") from an app ("app"): the + // gateway never reads an app's comment as a person's. + author: { ...jiraUser(author), displayName: authorName, accountType: author.accountType }, }, image_attachments: imageAttachments, coderhelm: { @@ -159,7 +162,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`); + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment`); if (res.ok) { const full = await res.json(); fields = full.fields || {}; @@ -206,6 +209,9 @@ exports.handler = async (event, context) => { }, }, image_attachments: imageAttachments, + // 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), user: requester(event.atlassianId, fields), coderhelm: { repo_owner: repoOwner || undefined, diff --git a/coderhelm-jira/test/comments.test.js b/coderhelm-jira/test/comments.test.js new file mode 100644 index 000000000..8588c1324 --- /dev/null +++ b/coderhelm-jira/test/comments.test.js @@ -0,0 +1,40 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { existingComments, MAX_COMMENTS } = require("../src/comments"); + +const doc = (text) => ({ type: "doc", version: 1, content: [{ type: "paragraph", content: [{ type: "text", text }] }] }); + +test("sends a ticket's comments with their id, author and body", () => { + const fields = { + comment: { + comments: [ + { id: "10001", author: { displayName: "Pat Doe", accountType: "atlassian" }, body: doc("Production only.") }, + { id: 10002, author: { displayName: "Coderhelm", accountType: "app" }, body: "Questions only a person can answer" }, + ], + }, + }; + const got = existingComments(fields); + assert.equal(got.length, 2); + assert.deepEqual(got[0].author, { displayName: "Pat Doe", accountType: "atlassian" }); + assert.equal(got[0].id, "10001"); + assert.equal(JSON.parse(got[0].body).content[0].content[0].text, "Production only."); + assert.equal(got[1].id, "10002"); + assert.equal(got[1].author.accountType, "app"); + assert.equal(got[1].body, "Questions only a person can answer"); +}); + +test("a ticket without comments, or without the field, sends none", () => { + assert.deepEqual(existingComments({}), []); + assert.deepEqual(existingComments(undefined), []); + assert.deepEqual(existingComments({ comment: {} }), []); + assert.deepEqual(existingComments({ comment: { comments: "x" } }), []); + assert.deepEqual(existingComments({ comment: { comments: [null, { id: "1" }, { body: "no id" }] } }), []); +}); + +test("only the newest comments are sent", () => { + const comments = Array.from({ length: 50 }, (_, i) => ({ id: String(i), author: {}, body: "x" })); + const got = existingComments({ comment: { comments } }); + assert.equal(got.length, MAX_COMMENTS); + assert.equal(got[got.length - 1].id, "49"); + assert.deepEqual(got[0].author, { displayName: "", accountType: "" }); +}); diff --git a/docs/incidents.md b/docs/incidents.md index 6e4a8c33e..e4d9ee1af 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -70,6 +70,7 @@ pipeline still calls it there. | an. `an_six_database_findings` | Security, Infrastructure showed six database findings, every one a one-command runbook with no pull request although the databases were in the team's code. The same CVE stood on an operating system update, an Aurora PostgreSQL patch and a MySQL upgrade. A database with a Terraform-generated identifier and an Aurora cluster defined through a module were "not found in code". A patch and an upgrade pending on one cluster were unrelated rows, an update on a second instance was dropped, and the account was read one page deep. | An advisory is attached only where it applies (service, engine, version range, kind of action, date); an action AWS publishes with no CVE list gets none. An action is named for what it means on its ARN. One database's pending actions are one ordered set of rows. The defining code is found from stack records, resource type and attributes, module calls and variable files, graded, and a guess never becomes a pull request. An update with a code equivalent is a pull request on the line that sets the value; one that cannot be expressed in code stays a complete runbook and says why. A change that would replace a database is refused. | | ao. `ao_stopped_log_finding` | Two log findings of one production service stayed on the Logs page as Critical and New, each with "Create fix PR" and "Not started automatically: not sure the repo is ...; check it and start the fix", a day and a half after their error had stopped: 735 matching lines in one six-hour window, then none while the service wrote its usual volume. The team had fixed the cause the day before. Only time closed a finding (three days without a line), so a problem that was over read as a live emergency that needed a person. | Every analysis counts each open finding's own lines on its own log group and keeps the count with the lines the group wrote. Two analyses in a row with no matching line at the service's usual volume make the finding stopped: shown and counted as stopped, never New or a live critical, with no automatic fix and no stale "choose a repo" reason. When the service itself went quiet nobody can tell, and it stays as it was. A burst that stopped after a change in its repo resolves after one day instead of three, with that evidence in the reason; an error that keeps coming back keeps its longer period. Seen again, it is live again and its fix may start. Evidence for the repo that couldn't be weighed is weighed again next sweep and never put to a person. | | ap. `ap_closed_pr_keeps_findings` | An admin closed CoderHelm's dependency fix pull request for a repository to start again and cancelled its fix run. On the Security page every checkbox for that repository was off, the header's too, with nothing to say why: 274 findings still read "in a pull request" a day later. The pull request webhook recorded the close on the run and never told the findings, cancelling a run wrote only the run, and the one comparison with GitHub was the last step of the scheduled sweep, behind the time every team's sources and triage left, reading a failed request as "still open". | A finding is `pr_open` only while its pull request is open and `fixing` only while its run works (`common::security_release`). A pull request closed unmerged gives its findings back with who closed it and when, a cancelled or closed run releases what it claimed, a reopened pull request takes its findings back, and a merge fixes them: on the webhook or the person's action, and again on every sweep, first for each team and on a clock of its own, bounded and in turn, so a missed webhook and records stale from before heal within a sweep. A person asking for a fix always gets one; automatic fixes wait a week after a person said no. Retry on the run is a new request from the findings as they are now and opens a new pull request. GitHub not answering is never read as open, closed or merged. | +| aq. `aq_comment_during_run` | A run asked three questions on its ticket, proposed defaults and kept building. A person answered on the ticket twenty minutes later; the gateway logged that a run was in progress and dropped the comment. Nothing acknowledged it, the run never saw it, and its notes kept saying it went on without the answers. Comments written before any run existed were dropped too, and nothing read them when the run started. | A person who writes on a ticket CoderHelm is working on gets an acknowledgement, and what they wrote is acted on. The comment is kept once per comment id and acknowledged once (a reaction on GitHub, one short reply in Jira; never for CoderHelm's own comments or other bots). The run reads its open comments together at its next step boundary: answers and instructions go into the plan while it is being made; once the plan is final they become one round on the pull request when the step ends, where the code changes in the place the plan put the choice, and the ticket is told; a comment that says to stop ends the run at once. A comment nobody read yet stays open for what comes next (the next step, the round on the finished run's pull request, the ticket started again, or the next run), and comments written before a run started are read at its first boundary. | | ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | | bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | | bc. `bc_stays_through_merge_and_deploy` | Pull requests were left as they were after their runs finished: one conflicted after its base moved, one went red a day later on a commit status no event carries, and one merged by a person had its production deploy fail with nothing watching. | A finished run's pull request is looked at on completion and by the sweep: a conflict starts the conflict round once per base commit, red checks not red on the base go to the fix loop once per head, and a merge by anyone gets its merge commit's deploy watched once. A deploy of CoderHelm's own change that fails on checks passing before the merge gets a revert pull request with the failing jobs as evidence, ready for the team's approval and never merged by CoderHelm; files changed again since are never overwritten. | diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 812c4f266..92e79c006 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -230,6 +230,8 @@ pub mod stop_judge; pub mod stop_rules; /// A team's run and PR-reviewed counts, each added exactly once. pub mod team_counts; +/// What people write on a ticket while a run works on it: kept, acknowledged, acted on. +pub mod ticket_comments; /// 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/ticket_comments.rs b/services/common/src/ticket_comments.rs new file mode 100644 index 000000000..9dcce83a0 --- /dev/null +++ b/services/common/src/ticket_comments.rs @@ -0,0 +1,1402 @@ +//! What a person writes on a ticket while CoderHelm works on it is kept, +//! acknowledged and acted on. +//! +//! A run once asked three questions on its ticket, proposed defaults and +//! kept building. A person answered on the ticket twenty minutes later. The +//! gateway logged that a run was in progress and dropped the comment: +//! nothing acknowledged it, the run never saw it, and its notes kept saying +//! it went on without the answers. +//! +//! Every ticket source now goes through one path: +//! +//! 1. The gateway keeps the comment ([`Store::record`]), once per comment +//! id, so a webhook delivered twice is one comment. A comment that +//! arrives while a run works is acknowledged on the ticket ([`ack_for`]: +//! a reaction where the source has them, otherwise one short reply), and +//! never when CoderHelm or another bot wrote it ([`is_person`]). +//! 2. The run reads its open comments at its next step boundary, all of +//! them together, and the model says what each is ([`Class`]). +//! [`decide`] says what happens for the run's [`Stage`]: an answer or an +//! instruction is folded into the plan while planning, becomes a round +//! on the pull request once the code is being built, and a comment that +//! says to stop ends the run at once. +//! 3. A comment is settled in one conditional write ([`Store::settle`]) +//! before anything is done with it, so two readers never act on it +//! twice, and one that nobody read stays open for whatever comes next: +//! the end of the step, the next step, a round on the finished run's +//! pull request, or the next run on the ticket. +//! 4. Comments written before the run started are kept the same way and +//! read at its first boundary. They are context: one of them never +//! stops a run that started after it. + +use crate::run_questions::Answer; +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +/// The settings-table sort key prefix of a ticket's comments. +pub const SK_PREFIX: &str = "TICKETCOMMENT#"; +/// Days a comment's record is kept. +pub const KEEP_DAYS: i64 = 90; +/// Days a comment written while no run worked on the ticket is kept: it is +/// only context for a run that starts soon after. +pub const KEEP_DAYS_NO_RUN: i64 = 30; + +/// How long a comment's record is kept, in days. +pub fn keep_days(c: &Comment) -> i64 { + if c.during_run() { + KEEP_DAYS + } else { + KEEP_DAYS_NO_RUN + } +} +/// A comment's text as kept, in characters. +pub const MAX_TEXT_CHARS: usize = 4_000; +/// Comments read together at most; the oldest open ones first. +pub const MAX_BURST: usize = 20; +/// Run-record field: the questions the run told the ticket about and kept +/// building without (JSON list of strings). +pub const FIELD_ASKED: &str = "ticket_questions"; +/// Run-record field read (never written) here: the questions a run that +/// stopped to ask kept as asked (`run_questions::Asked`). +pub const FIELD_STOPPED_TO_ASK: &str = crate::run_questions::FIELD_QUESTIONS; +/// The question an instruction (not an answer to a question) is kept under +/// when it is folded into the plan. +pub const COMMENT_QUESTION: &str = "A person's comment on the ticket"; +/// How CoderHelm's acknowledgement on a ticket starts. A comment that +/// starts this way is its own, whoever the tracker says wrote it. +pub const ACK_OPENING: &str = "Got it."; + +/// Where the ticket lives. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Source { + #[default] + Jira, + Github, +} + +impl Source { + pub fn as_str(self) -> &'static str { + match self { + Source::Jira => "jira", + Source::Github => "github", + } + } +} + +/// Where a comment stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + /// Kept, nothing done with it yet. + #[default] + Pending, + /// Read while the code was being built: it becomes a round on the pull + /// request when the step ends. + Deferred, + /// Acted on (or left alone on purpose); `outcome` says which. + Handled, +} + +impl State { + pub fn as_str(self) -> &'static str { + match self { + State::Pending => "pending", + State::Deferred => "deferred", + State::Handled => "handled", + } + } + + pub fn parse(s: &str) -> State { + match s { + "deferred" => State::Deferred, + "handled" => State::Handled, + _ => State::Pending, + } + } +} + +/// What a comment is, as the model read it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Class { + /// Answers one of the run's open questions. + Answer, + /// A new instruction or a correction for this ticket. + Instruction, + /// Says to stop the work. + Stop, + /// Not for CoderHelm (people talking to each other, a status note). + NotForCoderhelm, +} + +impl Class { + pub fn parse(s: &str) -> Option { + match s + .trim() + .to_ascii_lowercase() + .replace(['-', ' '], "_") + .as_str() + { + "answer" => Some(Class::Answer), + "instruction" | "correction" | "new_instruction" => Some(Class::Instruction), + "stop" => Some(Class::Stop), + "not_for_coderhelm" | "not_for_us" | "other" => Some(Class::NotForCoderhelm), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Class::Answer => "answer", + Class::Instruction => "instruction", + Class::Stop => "stop", + Class::NotForCoderhelm => "not_for_coderhelm", + } + } +} + +/// One comment a person wrote on a ticket. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Comment { + pub ticket_id: String, + pub source: Source, + /// The comment's id in its tracker. + pub comment_id: String, + pub author: String, + pub text: String, + /// When CoderHelm received it (RFC 3339). + pub at: String, + /// The run that was working when it arrived; empty when none was (a + /// comment written before the run started). + #[serde(default)] + pub run_id: String, + #[serde(default)] + pub state: State, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub class: Option, + /// The open question it answers, as asked; empty otherwise. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub question: String, + /// What CoderHelm did with it, in one line. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub outcome: String, + /// The run that settled it. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub handled_by: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub handled_at: String, +} + +impl Comment { + /// Whether a run was working when the comment arrived. Only such a + /// comment can stop a run. + pub fn during_run(&self) -> bool { + !self.run_id.is_empty() + } + + pub fn is_open(&self) -> bool { + self.state != State::Handled + } +} + +/// The sort key of every comment on `ticket_id`. +pub fn prefix(ticket_id: &str) -> String { + format!("{SK_PREFIX}{}#", ticket_id.to_ascii_uppercase()) +} + +/// The sort key of one comment: the same comment always has the same key. +pub fn sk(ticket_id: &str, source: Source, comment_id: &str) -> String { + format!("{}{}-{}", prefix(ticket_id), source.as_str(), comment_id) +} + +/// The id a comment is kept under: the tracker's own, else one made from +/// who wrote it and what it says, so the same delivery is still one record. +pub fn comment_id(given: &str, author: &str, text: &str) -> String { + let given = given.trim(); + if !given.is_empty() { + return given.to_string(); + } + use sha2::{Digest, Sha256}; + let mut h = Sha256::new(); + h.update(author.trim().as_bytes()); + h.update([0]); + h.update(text.trim().as_bytes()); + format!("h{}", &hex::encode(h.finalize())[..16]) +} + +/// Whether a person wrote the comment. CoderHelm's own comments and other +/// bots' never count: `kind` is the tracker's account type (`Bot` on +/// GitHub, `app` in Jira), and a Jira comment under CoderHelm's name or +/// starting with its acknowledgement is its own. +pub fn is_person(source: Source, author: &str, kind: &str, text: &str) -> bool { + let name = author.trim().to_ascii_lowercase(); + let kind = kind.trim().to_ascii_lowercase(); + if matches!(kind.as_str(), "bot" | "app") || name.ends_with("[bot]") { + return false; + } + if text.trim_start().starts_with(ACK_OPENING) { + return false; + } + match source { + // Jira shows the app by its display name. + Source::Jira => !name.contains("coderhelm"), + // On GitHub a person whose login contains the word is still a + // person; the app's own account is a Bot (above). + Source::Github => true, + } +} + +/// How a comment is acknowledged on the ticket. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Ack { + /// A reaction on the comment (GitHub). + Reaction, + /// One short reply (Jira has no reactions an app can add). + Reply, + None, +} + +/// The acknowledgement for a comment: only for a person's, only while a run +/// works on the ticket, and only the first time the comment is seen. +pub fn ack_for(source: Source, person: bool, newly_recorded: bool, run_working: bool) -> Ack { + if !person || !newly_recorded || !run_working { + return Ack::None; + } + match source { + Source::Github => Ack::Reaction, + Source::Jira => Ack::Reply, + } +} + +/// The one short reply on a ticket without reactions. +pub fn ack_reply() -> String { + format!( + "{ACK_OPENING} I'm working on this ticket now. I read this comment at my next step and \ + act on it." + ) +} + +/// Whether a run in this status is working on the ticket. +pub fn run_working(status: &str) -> bool { + matches!(status, "running" | "queued" | "awaiting_ci") +} + +/// Where the run is when its comments are read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Stage { + /// Triage or planning: the plan isn't final. + Planning, + /// The plan is final and the code is being written or checked. + Building, + /// The work is built: the pull request is being opened, reviewed or + /// its checks watched by the run's own step. + Reviewing, + /// One step ended and the next hasn't started. + BetweenSteps, + /// The run ended. `pr_open`: its pull request is open. `waiting`: it + /// ended waiting on a person or failed, with no pull request. + Finished { pr_open: bool, waiting: bool }, + /// A person stopped the run. + Cancelled, +} + +/// The stage of a run from its record. `in_step`: read by the run's own +/// step at a boundary (the run is working whatever the record says about +/// a status another writer set a moment ago). +pub fn stage_of( + status: &str, + current_pass: &str, + pr_open: bool, + in_step: bool, + stale: bool, +) -> Stage { + if crate::run_status::ended_by_person(status) { + return Stage::Cancelled; + } + match status { + "running" | "queued" if !stale => { + if !in_step { + return Stage::BetweenSteps; + } + match current_pass.trim().to_ascii_lowercase().as_str() { + "" | "triage" | "plan" => Stage::Planning, + "pr" | "review" | "checks" | "ready" | "await_merge" => Stage::Reviewing, + _ => Stage::Building, + } + } + "awaiting_ci" | "completed" | "success" if pr_open => Stage::Finished { + pr_open: true, + waiting: false, + }, + // A run left `running` long after its worker stopped is a failed + // run nobody marked yet. + "running" | "queued" | "needs_input" | "needs_outside_change" | "failed" => { + Stage::Finished { + pr_open: false, + waiting: true, + } + } + _ => Stage::Finished { + pr_open: false, + waiting: false, + }, + } +} + +/// What is done with a comment. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Action { + /// End the run now. + Stop, + /// Into the plan: the planner reads it word for word. + Fold, + /// Kept for the round on the pull request when this step ends. + Defer, + /// A feedback round on the open pull request, now. + Round, + /// Start the ticket again with it (the run ended waiting or failed). + Restart, + /// Kept on the ticket's record: the next run on the ticket reads it. + Keep, + /// Not for CoderHelm: left as it is, no reply. + Leave, + /// Nothing yet: the next step reads it. + Wait, +} + +/// What happens with a comment of `class` at `stage`. `during_run`: it +/// arrived while a run worked (only then can it stop one). `deferred`: an +/// earlier boundary already kept it for the pull request. +pub fn decide(class: Class, stage: Stage, during_run: bool, deferred: bool) -> Action { + let working = matches!( + stage, + Stage::Planning | Stage::Building | Stage::Reviewing | Stage::BetweenSteps + ); + match class { + Class::NotForCoderhelm => return Action::Leave, + Class::Stop if during_run && working => return Action::Stop, + _ => {} + } + match stage { + Stage::BetweenSteps => Action::Wait, + Stage::Planning if deferred => Action::Wait, + Stage::Planning => Action::Fold, + Stage::Building | Stage::Reviewing if deferred => Action::Wait, + Stage::Building | Stage::Reviewing => Action::Defer, + Stage::Finished { pr_open: true, .. } => Action::Round, + // A stop written to a run that already ended has nothing to stop. + Stage::Finished { waiting: true, .. } if class != Class::Stop => Action::Restart, + Stage::Finished { .. } | Stage::Cancelled => Action::Keep, + } +} + +// ── Reading: one model call for every unread comment ────────────────── + +pub const SYSTEM: &str = "You read the comments people wrote on a ticket that an automated \ + coding agent (CoderHelm) is working on, and say what each one is. \ + answer: it answers one of the agent's open questions (give that question's number), in any \ + wording, including a short choice such as \"the second option\" or \"yes, production only\". \ + instruction: it asks for new or different work on this ticket, corrects the plan, or gives \ + the agent a fact it needs for the work. \ + stop: it tells the agent to stop working on this ticket (\"stop\", \"hold off\", \"don't \ + build this\", \"cancel\"). A request to stop doing one thing inside the work (\"stop adding \ + tests\") is an instruction, not stop. \ + not_for_coderhelm: people talking to each other, a status note (\"moved to QA\"), thanks, \ + or anything else that asks nothing of the agent and tells it nothing about the work. \ + Judge each comment as a whole. When in doubt between instruction and not_for_coderhelm, \ + choose instruction only if the agent's work on this ticket would change."; + +pub fn schema() -> Value { + json!({ + "type": "object", + "properties": { + "comments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "n": {"type": "integer"}, + "class": {"type": "string", "enum": ["answer", "instruction", "stop", "not_for_coderhelm"]}, + "question": {"type": "integer"}, + "reason": {"type": "string"} + }, + "required": ["n", "class", "question", "reason"], + "additionalProperties": false + } + } + }, + "required": ["comments"], + "additionalProperties": false + }) +} + +/// The prompt: the ticket, the run's open questions (numbered from 1) and +/// the comments (numbered from 1). +pub fn prompt(title: &str, questions: &[String], comments: &[Comment]) -> String { + let mut out = format!( + "## Ticket\n{}\n\n## The agent's open questions\n", + title.trim() + ); + if questions.is_empty() { + out.push_str("(none)\n"); + } + for (i, q) in questions.iter().enumerate() { + out.push_str(&format!("{}. {}\n", i + 1, one_line(q, 600))); + } + out.push_str("\n## The comments\n"); + for (i, c) in comments.iter().enumerate() { + out.push_str(&format!( + "### Comment {} (by {})\n{}\n\n", + i + 1, + if c.author.trim().is_empty() { + "a person" + } else { + c.author.trim() + }, + crate::truncate_str(c.text.trim(), MAX_TEXT_CHARS) + )); + } + out.push_str( + "For each comment give its number (n), its class, and the number of the open question \ + it answers (0 when it answers none).\n", + ); + out +} + +/// One comment as read: its class and the open question it answers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reading { + pub class: Class, + pub question: String, +} + +/// The reading of each comment from the model's reply, in the comments' +/// order. A comment the reply leaves out or names no class for reads as +/// [`unread`]; an answer that names no open question is an instruction. +pub fn readings(reply: &Value, questions: &[String], comments: usize) -> Vec { + let mut out: Vec = (0..comments).map(|_| unread()).collect(); + for item in reply["comments"].as_array().into_iter().flatten() { + let n = item["n"].as_u64().unwrap_or(0) as usize; + if n == 0 || n > comments { + continue; + } + let Some(class) = Class::parse(item["class"].as_str().unwrap_or("")) else { + continue; + }; + let q = item["question"].as_u64().unwrap_or(0) as usize; + let question = match q { + 0 => String::new(), + n => questions.get(n - 1).cloned().unwrap_or_default(), + }; + out[n - 1] = match class { + Class::Answer if question.is_empty() => Reading { + class: Class::Instruction, + question, + }, + Class::Answer => Reading { class, question }, + _ => Reading { + class, + question: String::new(), + }, + }; + } + out +} + +/// A comment the model couldn't read: an instruction, so the planner or +/// the round on the pull request reads it again. Never a stop. +pub fn unread() -> Reading { + Reading { + class: Class::Instruction, + question: String::new(), + } +} + +// ── What a comment becomes ──────────────────────────────────────────── + +/// The comment as the planner reads it: an answer to the question it +/// answers, or a person's comment on the ticket. +pub fn as_answer(c: &Comment) -> Answer { + Answer { + question_id: format!("ticket-comment-{}", c.comment_id), + question: if c.question.trim().is_empty() { + COMMENT_QUESTION.to_string() + } else { + c.question.clone() + }, + answer: crate::truncate_str(c.text.trim(), crate::run_questions::MAX_ANSWER_CHARS) + .to_string(), + author: c.author.clone(), + answered_at: c.at.clone(), + ..Default::default() + } +} + +/// What the round on the pull request is asked to do with the comments. +pub fn round_body(comments: &[Comment]) -> String { + let mut out = String::from( + "People wrote on the ticket while this run was working, after its plan was final. \ + Apply each of these on this pull request.\n", + ); + for c in comments { + let who = who(c); + let text = crate::truncate_str(c.text.trim(), MAX_TEXT_CHARS); + if c.class == Some(Class::Answer) && !c.question.trim().is_empty() { + out.push_str(&format!( + "\n### Answer from {who} to the run's question\n\ + Question: {}\nAnswer: {text}\n\ + The run asked this on the ticket, built its own default and went on. Where \ + this answer differs from the default that was built, change the code in the \ + place the plan put that choice (and its tests). Where it matches, change \ + nothing.\n", + one_line(&c.question, 600) + )); + } else { + out.push_str(&format!( + "\n### Comment from {who}\n{text}\n\ + Read it as an instruction or correction for this ticket's work and apply it \ + to the code on this pull request.\n" + )); + } + } + out.push_str( + "\nSay in the pull request, for each one, what changed because of it, or that the code \ + already matched it.\n", + ); + crate::truncate_str(&out, crate::run_round::MAX_FEEDBACK_CHARS).to_string() +} + +/// The direction a restarted run carries ("author: words"), from the +/// comments that start it. +pub fn direction(comments: &[Comment]) -> String { + comments + .iter() + .map(|c| format!("{}: {}", who(c), one_line(&c.text, 600))) + .collect::>() + .join("\n") +} + +/// The one line kept on the comment and shown on the run for what was done. +pub fn outcome(action: Action, c: &Comment, pr: Option<&str>) -> String { + let what = match (c.class, c.question.trim().is_empty()) { + (Some(Class::Answer), false) => { + format!("an answer to \"{}\"", one_line(&c.question, 160)) + } + (Some(Class::Stop), _) => "a request to stop".to_string(), + (Some(Class::NotForCoderhelm), _) => "not for CoderHelm".to_string(), + _ => "an instruction for this ticket".to_string(), + }; + let pr = pr.filter(|p| !p.is_empty()).unwrap_or("the pull request"); + let did = match action { + Action::Stop => "stopped the run".to_string(), + Action::Fold => "folded into the plan before any code was written".to_string(), + Action::Defer => { + "the plan is final, so it is applied as a round on the pull request when this step \ + ends" + .to_string() + } + Action::Round => format!("applying it as a round on {pr}"), + Action::Restart => "started the ticket again with it".to_string(), + Action::Keep => { + "kept on the ticket's record; the next run on this ticket reads it".to_string() + } + Action::Leave => "left as it is".to_string(), + Action::Wait => "the next step reads it".to_string(), + }; + format!("Read {}'s comment as {what}: {did}.", who(c)) +} + +/// The note the run page shows when a comment arrives during a run. +pub fn received_note(c: &Comment, ack: Ack) -> String { + let acked = match ack { + Ack::Reaction => " Acknowledged there with a reaction.", + Ack::Reply => " Acknowledged there with a reply.", + Ack::None => "", + }; + format!( + "{} commented on the ticket: \"{}\".{acked} The run reads it at its next step.", + who(c), + one_line(&c.text, 300) + ) +} + +/// What CoderHelm says on the ticket about the comments it acted on (one +/// comment for all of them); `None` when there is nothing to say (every +/// one was left alone, folded quietly into the plan, or is still waiting). +pub fn ticket_reply(done: &[(Action, Comment)], pr: Option<&str>) -> Option { + let said: Vec = done + .iter() + .filter(|(a, _)| matches!(a, Action::Stop | Action::Round | Action::Restart)) + .map(|(a, c)| { + let pr = pr.filter(|p| !p.is_empty()).unwrap_or("the pull request"); + match (a, c.class, c.question.trim().is_empty()) { + (Action::Stop, _, _) => format!( + "{} asked me to stop, so I stopped the run. What is built so far stays on \ + its branch. Assign the ticket again, or reply here, and I take it up from \ + there.", + who(c) + ), + (Action::Round, Some(Class::Answer), false) => format!( + "{}'s answer to \"{}\": I built my default for this before the answer came. \ + I'm now changing the code where that choice lives to match the answer, on \ + {pr}, and I say there what changed.", + who(c), + one_line(&c.question, 200) + ), + (Action::Round, _, _) => format!( + "{}'s comment (\"{}\"): I'm applying it on {pr} now, and I say there what \ + changed.", + who(c), + one_line(&c.text, 160) + ), + _ => format!( + "{}'s comment (\"{}\"): I'm starting the work on this ticket again with it.", + who(c), + one_line(&c.text, 160) + ), + } + }) + .collect(); + (!said.is_empty()).then(|| said.join("\n\n")) +} + +fn who(c: &Comment) -> &str { + if c.author.trim().is_empty() { + "A person" + } else { + c.author.trim() + } +} + +fn one_line(s: &str, max: usize) -> String { + let flat = s.split_whitespace().collect::>().join(" "); + crate::truncate_str(&flat, max).to_string() +} + +/// The open comments of a ticket, oldest first, at most [`MAX_BURST`]. +pub fn open(mut all: Vec) -> Vec { + all.retain(Comment::is_open); + all.sort_by(|a, b| a.at.cmp(&b.at).then(a.comment_id.cmp(&b.comment_id))); + all.truncate(MAX_BURST); + all +} + +// ── Where comments are kept ─────────────────────────────────────────── + +/// Where ticket comments are kept. DynamoDB in production ([`Dynamo`]); a +/// map in tests ([`Memory`]). +#[async_trait::async_trait] +pub trait Store: Send + Sync { + /// Keeps a new comment. `Ok(false)` when it is already kept (the same + /// comment delivered again): nothing is written. + async fn record(&self, team_id: &str, c: &Comment) -> Result; + /// Every comment kept for the ticket. + async fn of_ticket(&self, team_id: &str, ticket_id: &str) -> Result, String>; + /// Writes `c` only while the kept comment is still in state `from`. + /// `Ok(false)` when another reader settled it first. + async fn settle(&self, team_id: &str, c: &Comment, from: State) -> Result; +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn brief(e: impl std::fmt::Debug) -> String { + format!("{e:?}").chars().take(300).collect() +} + +/// Ticket comments on the settings table (`pk` = team, `sk` = [`sk`]). +pub struct Dynamo<'a> { + pub client: &'a aws_sdk_dynamodb::Client, + pub table: &'a str, +} + +#[async_trait::async_trait] +impl Store for Dynamo<'_> { + async fn record(&self, team_id: &str, c: &Comment) -> Result { + let doc = serde_json::to_string(c).map_err(brief)?; + let now = chrono::Utc::now(); + let res = self + .client + .put_item() + .table_name(self.table) + .item("pk", s(team_id)) + .item("sk", s(&sk(&c.ticket_id, c.source, &c.comment_id))) + .item("comment_state", s(c.state.as_str())) + .item("doc", s(&doc)) + .item("updated_at", s(&now.to_rfc3339())) + // The settings table expires items on `ttl`. + .item( + "ttl", + AttributeValue::N( + (now + chrono::Duration::days(keep_days(c))) + .timestamp() + .to_string(), + ), + ) + .condition_expression("attribute_not_exists(pk)") + .send() + .await; + match res { + Ok(_) => Ok(true), + Err(e) if brief(&e).contains("ConditionalCheckFailed") => Ok(false), + Err(e) => Err(brief(e)), + } + } + + async fn of_ticket(&self, team_id: &str, ticket_id: &str) -> Result, String> { + let mut out = Vec::new(); + let mut start = None; + loop { + let page = self + .client + .query() + .table_name(self.table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", s(team_id)) + .expression_attribute_values(":p", s(&prefix(ticket_id))) + .consistent_read(true) + .set_exclusive_start_key(start) + .send() + .await + .map_err(brief)?; + for item in page.items() { + let Some(mut c) = item + .get("doc") + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str::(d).ok()) + else { + continue; + }; + // The state attribute is what conditional writes check. + if let Some(st) = item.get("comment_state").and_then(|v| v.as_s().ok()) { + c.state = State::parse(st); + } + out.push(c); + } + start = page.last_evaluated_key().cloned(); + if start.is_none() { + break; + } + } + Ok(out) + } + + async fn settle(&self, team_id: &str, c: &Comment, from: State) -> Result { + let doc = serde_json::to_string(c).map_err(brief)?; + let res = self + .client + .update_item() + .table_name(self.table) + .key("pk", s(team_id)) + .key("sk", s(&sk(&c.ticket_id, c.source, &c.comment_id))) + .update_expression("SET comment_state = :to, doc = :doc, updated_at = :t") + .condition_expression("comment_state = :from") + .expression_attribute_values(":to", s(c.state.as_str())) + .expression_attribute_values(":from", s(from.as_str())) + .expression_attribute_values(":doc", s(&doc)) + .expression_attribute_values(":t", s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + match res { + Ok(_) => Ok(true), + Err(e) if brief(&e).contains("ConditionalCheckFailed") => Ok(false), + Err(e) => Err(brief(e)), + } + } +} + +/// Comments in memory, with the same semantics as [`Dynamo`]: a comment is +/// kept once, and a settle is conditional on the state it was read in. +#[derive(Default)] +pub struct Memory { + pub items: std::sync::Mutex>, +} + +impl Memory { + pub fn all(&self, team_id: &str, ticket_id: &str) -> Vec { + let p = prefix(ticket_id); + self.items + .lock() + .unwrap() + .iter() + .filter(|((pk, sk), _)| pk == team_id && sk.starts_with(&p)) + .map(|(_, c)| c.clone()) + .collect() + } +} + +#[async_trait::async_trait] +impl Store for Memory { + async fn record(&self, team_id: &str, c: &Comment) -> Result { + let key = ( + team_id.to_string(), + sk(&c.ticket_id, c.source, &c.comment_id), + ); + let mut items = self.items.lock().unwrap(); + if items.contains_key(&key) { + return Ok(false); + } + items.insert(key, c.clone()); + Ok(true) + } + + async fn of_ticket(&self, team_id: &str, ticket_id: &str) -> Result, String> { + Ok(self.all(team_id, ticket_id)) + } + + async fn settle(&self, team_id: &str, c: &Comment, from: State) -> Result { + let key = ( + team_id.to_string(), + sk(&c.ticket_id, c.source, &c.comment_id), + ); + let mut items = self.items.lock().unwrap(); + match items.get_mut(&key) { + Some(kept) if kept.state == from => { + *kept = c.clone(); + Ok(true) + } + _ => Ok(false), + } + } +} + +// ── Reading a ticket's open comments, as one unit ───────────────────── + +/// What a read of a ticket's open comments settled, by what is done with +/// each. The caller does the work (sends the round, stops the run); every +/// comment here was claimed in the store first, so no other reader acts on +/// it too. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Settled { + pub done: Vec<(Action, Comment)>, +} + +impl Settled { + pub fn with(&self, action: Action) -> Vec { + self.done + .iter() + .filter(|(a, _)| *a == action) + .map(|(_, c)| c.clone()) + .collect() + } + + pub fn stopped(&self) -> bool { + self.done.iter().any(|(a, _)| *a == Action::Stop) + } +} + +/// Gives each open, unread comment its reading (kept in the store, so a +/// later reader doesn't ask the model again). `read` is the model's reading +/// of the unread ones, in order; missing ones read as [`unread`]. +pub async fn keep_readings( + store: &dyn Store, + team_id: &str, + open: &mut [Comment], + read: &[Reading], +) { + let mut next = read.iter(); + for c in open.iter_mut().filter(|c| c.class.is_none()) { + let r = next.next().cloned().unwrap_or_else(unread); + c.class = Some(r.class); + c.question = r.question; + // Best effort: a reader that loses this write reads the comment + // again at its own boundary. + let _ = store.settle(team_id, c, c.state).await; + } +} + +/// Settles every open comment for `stage`: decides what happens with each +/// ([`decide`]) and claims it in the store. Comments that wait stay as they +/// are. When one says to stop, only it is settled: the rest stay open for +/// the next run on the ticket. +pub async fn settle_open( + store: &dyn Store, + team_id: &str, + run_id: &str, + open: &[Comment], + stage: Stage, + pr: Option<&str>, +) -> Settled { + let now = chrono::Utc::now().to_rfc3339(); + let planned: Vec<(Action, &Comment)> = open + .iter() + .map(|c| { + let class = c.class.unwrap_or(Class::Instruction); + ( + decide(class, stage, c.during_run(), c.state == State::Deferred), + c, + ) + }) + .collect(); + let stop = planned.iter().any(|(a, _)| *a == Action::Stop); + let mut out = Settled::default(); + for (action, c) in planned { + if action == Action::Wait || (stop && action != Action::Stop) { + continue; + } + let mut next = c.clone(); + next.outcome = outcome(action, c, pr); + next.handled_by = run_id.to_string(); + next.handled_at = now.clone(); + next.state = if action == Action::Defer { + State::Deferred + } else { + State::Handled + }; + match store.settle(team_id, &next, c.state).await { + Ok(true) => out.done.push((action, next)), + // Another reader settled it first: it acts, this one doesn't. + Ok(false) => {} + Err(e) => { + tracing::warn!(ticket_id = %c.ticket_id, error = %e, "Could not settle a ticket comment; it stays open") + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn comment(id: &str, text: &str) -> Comment { + Comment { + ticket_id: "ABC-1".into(), + source: Source::Jira, + comment_id: id.into(), + author: "Pat Doe".into(), + text: text.into(), + at: format!("2026-01-01T00:00:{:0>2}Z", id), + run_id: "01RUN".into(), + ..Default::default() + } + } + + const WORKING: [Stage; 4] = [ + Stage::Planning, + Stage::Building, + Stage::Reviewing, + Stage::BetweenSteps, + ]; + + #[tokio::test] + async fn a_comment_is_kept_once_whatever_the_webhook_delivers() { + let store = Memory::default(); + let c = comment("1", "Production only."); + assert!(store.record("TEAM#1", &c).await.unwrap()); + // The same delivery again, and again after the run read it. + assert!(!store.record("TEAM#1", &c).await.unwrap()); + let mut read = c.clone(); + read.state = State::Handled; + assert!(store.settle("TEAM#1", &read, State::Pending).await.unwrap()); + assert!(!store.record("TEAM#1", &c).await.unwrap()); + let kept = store.all("TEAM#1", "ABC-1"); + assert_eq!(kept.len(), 1); + assert_eq!( + kept[0].state, + State::Handled, + "a redelivery never reopens it" + ); + // Another ticket, another team and another source are other comments. + assert!(store.record("TEAM#2", &c).await.unwrap()); + let mut gh = c.clone(); + gh.source = Source::Github; + assert!(store.record("TEAM#1", &gh).await.unwrap()); + } + + #[test] + fn the_key_is_the_comment_id_and_a_missing_id_is_still_one_key() { + assert_eq!( + sk("abc-1", Source::Jira, "10042"), + "TICKETCOMMENT#ABC-1#jira-10042" + ); + assert!(sk("ABC-1", Source::Jira, "1").starts_with(&prefix("abc-1"))); + // ABC-1's prefix never matches ABC-10's comments. + assert!(!sk("ABC-10", Source::Jira, "1").starts_with(&prefix("ABC-1"))); + assert_eq!(comment_id(" 77 ", "a", "b"), "77"); + let made = comment_id("", "Pat Doe", "Production only."); + assert_eq!(made, comment_id("", "Pat Doe", " Production only. ")); + assert_ne!(made, comment_id("", "Pat Doe", "Staging too.")); + } + + #[test] + fn only_a_persons_comment_counts() { + assert!(is_person( + Source::Jira, + "Pat Doe", + "atlassian", + "Production only." + )); + // CoderHelm's own comments, by name, by account type and by text. + assert!(!is_person(Source::Jira, "CoderHelm", "app", "Questions")); + assert!(!is_person(Source::Jira, "Coderhelm for Jira", "", "x")); + assert!(!is_person(Source::Jira, "Automation", "app", "x")); + assert!(!is_person(Source::Jira, "Renamed App", "", &ack_reply())); + assert!(!is_person(Source::Github, "coderhelm[bot]", "Bot", "x")); + assert!(!is_person(Source::Github, "ci-reporter[bot]", "", "x")); + assert!(!is_person(Source::Github, "some-app", "Bot", "x")); + // A person whose GitHub login contains the word is a person. + assert!(is_person(Source::Github, "coderhelm-fan", "User", "x")); + } + + #[test] + fn one_acknowledgement_per_comment_and_none_for_bots() { + assert_eq!(ack_for(Source::Github, true, true, true), Ack::Reaction); + assert_eq!(ack_for(Source::Jira, true, true, true), Ack::Reply); + for source in [Source::Github, Source::Jira] { + // Delivered again: no second acknowledgement. + assert_eq!(ack_for(source, true, false, true), Ack::None); + // CoderHelm's own comment or another bot's. + assert_eq!(ack_for(source, false, true, true), Ack::None); + // No run is working: the comment is context for the next run. + assert_eq!(ack_for(source, true, true, false), Ack::None); + } + // The reply is short, and is itself never read as a person's. + assert!(ack_reply().len() < 120); + assert!(!is_person(Source::Jira, "Someone", "", &ack_reply())); + } + + #[test] + fn the_stage_comes_from_the_run_record() { + assert_eq!( + stage_of("running", "triage", false, true, false), + Stage::Planning + ); + assert_eq!( + stage_of("running", "plan", false, true, false), + Stage::Planning + ); + assert_eq!(stage_of("running", "", false, true, false), Stage::Planning); + for pass in ["implement", "implement_started", "test", "security"] { + assert_eq!( + stage_of("running", pass, false, true, false), + Stage::Building + ); + } + assert_eq!( + stage_of("running", "pr", true, true, false), + Stage::Reviewing + ); + // Read outside a step: the run handed off to a fresh one. + assert_eq!( + stage_of("running", "implement", false, false, false), + Stage::BetweenSteps + ); + assert_eq!( + stage_of("queued", "plan", false, false, false), + Stage::BetweenSteps + ); + let open = Stage::Finished { + pr_open: true, + waiting: false, + }; + assert_eq!(stage_of("awaiting_ci", "checks", true, false, false), open); + assert_eq!(stage_of("completed", "done", true, false, false), open); + let waiting = Stage::Finished { + pr_open: false, + waiting: true, + }; + assert_eq!( + stage_of("needs_input", "plan", false, false, false), + waiting + ); + assert_eq!( + stage_of("failed", "implement", false, false, false), + waiting + ); + // Left `running` long after its worker stopped. + assert_eq!( + stage_of("running", "implement", false, false, true), + waiting + ); + assert_eq!( + stage_of("merged", "done", false, false, false), + Stage::Finished { + pr_open: false, + waiting: false + } + ); + for status in ["cancelled", "closed"] { + assert_eq!( + stage_of(status, "implement", true, false, false), + Stage::Cancelled + ); + } + } + + #[test] + fn each_class_at_each_stage() { + use Action::*; + let pr_open = Stage::Finished { + pr_open: true, + waiting: false, + }; + let waiting = Stage::Finished { + pr_open: false, + waiting: true, + }; + let done = Stage::Finished { + pr_open: false, + waiting: false, + }; + for class in [Class::Answer, Class::Instruction] { + assert_eq!(decide(class, Stage::Planning, true, false), Fold); + assert_eq!(decide(class, Stage::Building, true, false), Defer); + assert_eq!(decide(class, Stage::Reviewing, true, false), Defer); + assert_eq!(decide(class, Stage::BetweenSteps, true, false), Wait); + assert_eq!(decide(class, pr_open, true, false), Round); + assert_eq!(decide(class, waiting, true, false), Restart); + assert_eq!(decide(class, done, true, false), Keep); + assert_eq!(decide(class, Stage::Cancelled, true, false), Keep); + // Kept for the pull request at an earlier boundary: it waits + // through the rest of the step, then becomes the round. + assert_eq!(decide(class, Stage::Building, true, true), Wait); + assert_eq!(decide(class, Stage::Reviewing, true, true), Wait); + assert_eq!(decide(class, Stage::BetweenSteps, true, true), Wait); + assert_eq!(decide(class, pr_open, true, true), Round); + assert_eq!(decide(class, waiting, true, true), Restart); + assert_eq!(decide(class, Stage::Cancelled, true, true), Keep); + } + // Not for CoderHelm: left alone at every stage. + for stage in WORKING + .into_iter() + .chain([pr_open, waiting, done, Stage::Cancelled]) + { + assert_eq!(decide(Class::NotForCoderhelm, stage, true, false), Leave); + } + } + + #[test] + fn a_stop_is_honoured_at_once_while_the_run_works() { + for stage in WORKING { + assert_eq!(decide(Class::Stop, stage, true, false), Action::Stop); + // Even one an earlier boundary had kept for the pull request. + assert_eq!(decide(Class::Stop, stage, true, true), Action::Stop); + } + // Written before the run started: context, never a stop. + assert_eq!( + decide(Class::Stop, Stage::Planning, false, false), + Action::Fold + ); + assert_eq!( + decide(Class::Stop, Stage::Building, false, false), + Action::Defer + ); + // On a finished run with its pull request open, the round reads it. + assert_eq!( + decide( + Class::Stop, + Stage::Finished { + pr_open: true, + waiting: false + }, + true, + false + ), + Action::Round + ); + // Nothing to stop, and never a restart. + assert_eq!( + decide( + Class::Stop, + Stage::Finished { + pr_open: false, + waiting: true + }, + true, + false + ), + Action::Keep + ); + assert_eq!( + decide(Class::Stop, Stage::Cancelled, true, false), + Action::Keep + ); + } + + #[test] + fn the_reply_is_read_per_comment_and_a_gap_is_never_a_stop() { + let questions = vec![ + "Which environments get the flag?".to_string(), + "Keep the old column?".to_string(), + ]; + let reply = json!({"comments": [ + {"n": 1, "class": "answer", "question": 2, "reason": ""}, + {"n": 2, "class": "stop", "question": 0, "reason": ""}, + {"n": 3, "class": "answer", "question": 0, "reason": ""}, + {"n": 4, "class": "not_for_coderhelm", "question": 1, "reason": ""}, + {"n": 9, "class": "stop", "question": 0, "reason": ""} + ]}); + let r = readings(&reply, &questions, 5); + assert_eq!(r[0].class, Class::Answer); + assert_eq!(r[0].question, "Keep the old column?"); + assert_eq!(r[1].class, Class::Stop); + // An answer that names no open question is an instruction. + assert_eq!(r[2].class, Class::Instruction); + assert_eq!(r[3].class, Class::NotForCoderhelm); + assert!(r[3].question.is_empty()); + // Left out by the model: read again downstream, never a stop. + assert_eq!(r[4], unread()); + assert_eq!(unread().class, Class::Instruction); + // No reply at all. + assert!(readings(&json!({}), &questions, 2) + .iter() + .all(|r| *r == unread())); + let p = prompt("Add the flag", &questions, &[comment("1", "Yes, keep it.")]); + assert!(p.contains("2. Keep the old column?")); + assert!(p.contains("Comment 1 (by Pat Doe)")); + } + + #[tokio::test] + async fn a_burst_is_read_together_and_each_comment_is_acted_on_once() { + let store = Memory::default(); + for (id, text) in [ + ("1", "Production only."), + ("2", "Also rename the flag."), + ("3", "Thanks all"), + ] { + store.record("TEAM#1", &comment(id, text)).await.unwrap(); + } + let mut open_now = open(store.all("TEAM#1", "ABC-1")); + assert_eq!(open_now.len(), 3); + let read = vec![ + Reading { + class: Class::Answer, + question: "Which environments?".into(), + }, + Reading { + class: Class::Instruction, + question: String::new(), + }, + Reading { + class: Class::NotForCoderhelm, + question: String::new(), + }, + ]; + keep_readings(&store, "TEAM#1", &mut open_now, &read).await; + // The readings are kept: a second reader doesn't ask the model again. + assert!(open(store.all("TEAM#1", "ABC-1")) + .iter() + .all(|c| c.class.is_some())); + + // Two readers at the same moment (the run's boundary and the read + // right after the comment): each comment is settled by one of them. + let a = settle_open(&store, "TEAM#1", "01RUN", &open_now, Stage::Building, None).await; + let b = settle_open(&store, "TEAM#1", "01RUN", &open_now, Stage::Building, None).await; + assert_eq!(a.done.len(), 3); + assert!(b.done.is_empty(), "the second reader acts on nothing"); + assert_eq!(a.with(Action::Defer).len(), 2); + assert_eq!(a.with(Action::Leave).len(), 1); + + // The step ends with the pull request open: the two kept for it + // become one round, and the one left alone is not read again. + let open_now = open(store.all("TEAM#1", "ABC-1")); + assert_eq!(open_now.len(), 2); + let end = settle_open( + &store, + "TEAM#1", + "01RUN", + &open_now, + Stage::Finished { + pr_open: true, + waiting: false, + }, + Some("acme/web#12"), + ) + .await; + let round = end.with(Action::Round); + assert_eq!(round.len(), 2); + let body = round_body(&round); + assert!(body.contains("Question: Which environments?")); + assert!(body.contains("Answer: Production only.")); + assert!(body.contains("change the code in the place the plan put that choice")); + assert!(body.contains("Also rename the flag.")); + assert!(open(store.all("TEAM#1", "ABC-1")).is_empty()); + // Nothing left to act on, whoever reads next. + let again = settle_open( + &store, + "TEAM#1", + "01RUN", + &open(store.all("TEAM#1", "ABC-1")), + Stage::Finished { + pr_open: true, + waiting: false, + }, + None, + ) + .await; + assert!(again.done.is_empty()); + } + + #[tokio::test] + async fn a_stop_settles_only_itself_and_the_rest_stay_for_the_next_run() { + let store = Memory::default(); + let mut stop = comment("1", "Stop, we are dropping this."); + stop.class = Some(Class::Stop); + let mut more = comment("2", "If we pick it up again, production only."); + more.class = Some(Class::Instruction); + store.record("TEAM#1", &stop).await.unwrap(); + store.record("TEAM#1", &more).await.unwrap(); + let open_now = open(store.all("TEAM#1", "ABC-1")); + let s = settle_open(&store, "TEAM#1", "01RUN", &open_now, Stage::Building, None).await; + assert!(s.stopped()); + assert_eq!(s.done.len(), 1); + let left = open(store.all("TEAM#1", "ABC-1")); + assert_eq!(left.len(), 1); + assert_eq!(left[0].comment_id, "2"); + assert_eq!(left[0].state, State::Pending); + let said = ticket_reply(&s.done, None).unwrap(); + assert!(said.contains("I stopped the run")); + } + + #[test] + fn what_is_said_on_the_ticket_and_the_run() { + let mut answer = comment("1", "Production only."); + answer.class = Some(Class::Answer); + answer.question = "Which environments get the flag?".into(); + let mut chat = comment("2", "Thanks"); + chat.class = Some(Class::NotForCoderhelm); + let pr = Some("https://example.test/pr/12"); + // The answer applied on the pull request is said on the ticket. + let said = ticket_reply(&[(Action::Round, answer.clone())], pr).unwrap(); + assert!(said.contains("Pat Doe's answer to \"Which environments get the flag?\"")); + assert!(said.contains("https://example.test/pr/12")); + // Left alone, folded or waiting: no reply. + assert_eq!(ticket_reply(&[(Action::Leave, chat.clone())], pr), None); + assert_eq!(ticket_reply(&[(Action::Fold, answer.clone())], pr), None); + assert_eq!(ticket_reply(&[(Action::Defer, answer.clone())], pr), None); + // The run page says what arrived and what was done with it. + assert!(received_note(&answer, Ack::Reply).contains( + "Pat Doe commented on the ticket: \"Production only.\". Acknowledged there with a reply." + )); + assert!(outcome(Action::Fold, &answer, None) + .starts_with("Read Pat Doe's comment as an answer to \"Which environments")); + assert!(outcome(Action::Leave, &chat, None).contains("not for CoderHelm: left as it is")); + // What the planner reads. + let a = as_answer(&answer); + assert_eq!(a.question, "Which environments get the flag?"); + assert_eq!(a.answer, "Production only."); + let mut instruction = comment("3", "Use the existing helper."); + instruction.class = Some(Class::Instruction); + assert_eq!(as_answer(&instruction).question, COMMENT_QUESTION); + assert_eq!( + direction(&[answer, instruction]), + "Pat Doe: Production only.\nPat Doe: Use the existing helper." + ); + } + + #[test] + fn open_comments_are_oldest_first_and_bounded() { + let mut all: Vec = (0..30).map(|i| comment(&format!("{i}"), "x")).collect(); + all[0].state = State::Handled; + all.reverse(); + let o = open(all); + assert_eq!(o.len(), MAX_BURST); + assert!(o.iter().all(Comment::is_open)); + assert!(o.windows(2).all(|w| w[0].at <= w[1].at)); + } +} diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index d67c7a846..fbdb368d3 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1349,6 +1349,13 @@ async fn handle_issue_comment( || lower.trim_start().starts_with("/coderhelm") || lower.contains("@coderhelm"); if !on_bot_pr && !addressed { + // A person writing on an issue a run is working on is talking to + // that run, mention or not (an answer to its questions). + if super::ticket_comments::on_github_issue_comment(state, payload, installation_id, team_id) + .await + { + return Ok(StatusCode::OK); + } // A person quoting CoderHelm's review in the PR conversation (GitHub's // "Quote reply") is answering it, mention or not. if action == "created" @@ -1641,7 +1648,16 @@ async fn handle_issue_comment( .await, super::trigger_gate::TicketGate::SkipInFlight ) { - info!(ticket_id = %ticket_id_str, "Skipping slash command — run already in flight"); + // No second run: the run in flight gets the comment (kept, + // acknowledged, read at its next step). + let kept = super::ticket_comments::on_github_issue_comment( + state, + payload, + installation_id, + team_id, + ) + .await; + info!(ticket_id = %ticket_id_str, kept, "Run already in flight — the comment goes to it, no second run"); return Ok(StatusCode::OK); } diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index 01e20a9bc..40130a007 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -715,6 +715,10 @@ async fn process_jira_payload( return Ok(StatusCode::OK); } + // What people already wrote on the ticket (the app sends its comments + // with the event) is kept, so the run reads it before it plans. + super::ticket_comments::keep_jira_existing(state, team_id, ticket_key, payload).await; + let message = WorkerMessage::Ticket(TicketMessage { team_id: team_id.to_string(), installation_id, @@ -941,11 +945,26 @@ async fn handle_jira_comment( .and_then(|v| v.as_str()) .unwrap_or(""); - // Ignore comments by the bot itself - if comment_author.to_ascii_lowercase().contains("coderhelm") { + // CoderHelm's own comments (its acknowledgement included) and other + // apps' are never read: one of them must never start anything. + let author_kind = payload + .pointer("/comment/author/accountType") + .and_then(|v| v.as_str()) + .unwrap_or(""); + if !common::ticket_comments::is_person( + common::ticket_comments::Source::Jira, + comment_author, + author_kind, + comment_body, + ) { info!(ticket_key, "Skipping own comment"); return Ok(StatusCode::OK); } + let comment_id = match payload.pointer("/comment/id") { + Some(Value::String(s)) => s.clone(), + Some(Value::Number(n)) => n.to_string(), + _ => String::new(), + }; info!(team_id, ticket_key, comment_author, "Jira comment received"); let requester = payload @@ -995,7 +1014,27 @@ async fn handle_jira_comment( } let Some(run_item) = run_item_found.as_ref() else { - info!(ticket_key, "No runs found for Jira comment — ignoring"); + // No run yet: the comment is kept, and the run that starts on the + // ticket reads it before it plans. + info!( + ticket_key, + "No runs found for Jira comment — kept for the run that starts on the ticket" + ); + super::ticket_comments::keep( + state, + &super::ticket_comments::Incoming { + team_id, + installation_id, + source: common::ticket_comments::Source::Jira, + ticket_id: ticket_key, + comment_id: &comment_id, + author: comment_author, + author_kind, + text: comment_body, + ..Default::default() + }, + ) + .await; return Ok(StatusCode::OK); }; @@ -1042,19 +1081,45 @@ async fn handle_jira_comment( .map(|s| s.as_str()) .unwrap_or(""); - // A run in flight owns the ticket; the comment waits for it. - if matches!(run_status, "running" | "queued" | "awaiting_ci") { + // A run is working on the ticket: the comment is kept for it, + // acknowledged on the ticket, and read at the run's next step (an + // answer to its questions, an instruction, or a request to stop). It + // used to be dropped here. + if common::ticket_comments::run_working(run_status) { + let received = super::ticket_comments::receive( + state, + &super::ticket_comments::Incoming { + team_id, + installation_id, + source: common::ticket_comments::Source::Jira, + ticket_id: ticket_key, + comment_id: &comment_id, + author: comment_author, + author_kind, + text: comment_body, + title, + run_id, + run_status, + pr_number, + repo_owner, + repo_name, + }, + ) + .await?; info!( ticket_key, - run_status, "Ignoring Jira comment — run already in progress" + run_status, run_id, "Jira comment kept for the run in progress" ); log_jira_event( state, team_id, - "comment_skipped", + "comment_kept", ticket_key, title, - "skipped", + match received { + super::ticket_comments::Received::Kept(..) => "queued", + _ => "duplicate", + }, None, ) .await; diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 55d5c61dd..10c0686a0 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -85,6 +85,7 @@ pub mod system_models; pub mod telemetry; pub mod tests; pub mod tests_setup; +pub mod ticket_comments; pub mod tools; pub mod trigger_gate; pub mod users; diff --git a/services/gateway/src/routes/ticket_comments.rs b/services/gateway/src/routes/ticket_comments.rs new file mode 100644 index 000000000..932726a67 --- /dev/null +++ b/services/gateway/src/routes/ticket_comments.rs @@ -0,0 +1,624 @@ +//! A person's comment on a ticket, taken in one way whatever the ticket's +//! source (see `common::ticket_comments`). +//! +//! The webhooks used to drop a comment that arrived while a run was +//! working ("Ignoring Jira comment — run already in progress", "Skipping +//! slash command — run already in flight", and a comment on a GitHub issue +//! that didn't mention CoderHelm). They now call [`receive`]: +//! +//! 1. the comment is kept, once per comment id (a webhook delivered twice +//! is one comment); +//! 2. the first time it is seen while a run works, it is acknowledged on +//! the ticket: a reaction on GitHub, one short reply in Jira. Never for +//! CoderHelm's own comments or another bot's; +//! 3. the run page gets a note with what the person wrote; +//! 4. the worker is told at once, so a comment that says to stop is read +//! now, not at the run's next step. +//! +//! A comment on a ticket no run is working on is kept too ([`keep`]), with +//! no acknowledgement: the run that starts on the ticket reads it first. + +use crate::models::{JiraCommentMessage, WorkerMessage}; +use crate::AppState; +use aws_sdk_dynamodb::types::AttributeValue; +use axum::http::StatusCode; +use common::ticket_comments::{self as tc, Ack, Comment, Source, Store}; +use serde_json::{json, Value}; +use tracing::{info, warn}; + +/// A comment as a webhook delivered it. +#[derive(Debug, Clone, Default)] +pub struct Incoming<'a> { + pub team_id: &'a str, + pub installation_id: u64, + pub source: Source, + pub ticket_id: &'a str, + /// The tracker's id for the comment. + pub comment_id: &'a str, + pub author: &'a str, + /// The tracker's account type for the author (`Bot`, `app`, ...). + pub author_kind: &'a str, + pub text: &'a str, + pub title: &'a str, + /// The ticket's latest run and its status; empty when it has none. + pub run_id: &'a str, + pub run_status: &'a str, + pub pr_number: u64, + pub repo_owner: &'a str, + pub repo_name: &'a str, +} + +/// What became of an incoming comment. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Received { + /// CoderHelm's own comment or another bot's: nothing is kept. + NotAPerson, + /// Already kept (the same delivery again): nothing more happens. + Duplicate, + /// Kept now, with how it is acknowledged. + Kept(Box, Ack), +} + +/// Keeps the comment and says how it is acknowledged. No side effect +/// beyond the store: [`receive`] does the acknowledgement. +pub async fn take(store: &dyn Store, inc: &Incoming<'_>) -> Result { + if !tc::is_person(inc.source, inc.author, inc.author_kind, inc.text) { + return Ok(Received::NotAPerson); + } + let working = tc::run_working(inc.run_status) && !inc.run_id.is_empty(); + let comment = Comment { + ticket_id: inc.ticket_id.to_string(), + source: inc.source, + comment_id: tc::comment_id(inc.comment_id, inc.author, inc.text), + author: inc.author.trim().to_string(), + text: common::truncate_str(inc.text.trim(), tc::MAX_TEXT_CHARS).to_string(), + at: chrono::Utc::now().to_rfc3339(), + run_id: if working { + inc.run_id.to_string() + } else { + String::new() + }, + ..Default::default() + }; + let new = store.record(inc.team_id, &comment).await?; + if !new { + return Ok(Received::Duplicate); + } + let ack = tc::ack_for(inc.source, true, new, working); + Ok(Received::Kept(Box::new(comment), ack)) +} + +fn store(state: &AppState) -> tc::Dynamo<'_> { + tc::Dynamo { + client: &state.dynamo, + table: &state.config.settings_table_name, + } +} + +/// A comment on a ticket a run is working on: kept, acknowledged, shown on +/// the run, and sent to the worker to read. Returns what became of it. +pub async fn receive(state: &AppState, inc: &Incoming<'_>) -> Result { + let received = take(&store(state), inc).await.map_err(|e| { + // The webhook is delivered again: the comment is never lost here. + warn!(ticket_id = inc.ticket_id, error = %e, "Could not keep the ticket comment"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let Received::Kept(comment, ack) = &received else { + info!( + ticket_id = inc.ticket_id, + outcome = ?received, + "Ticket comment not taken again" + ); + return Ok(received); + }; + info!( + team_id = inc.team_id, + ticket_id = inc.ticket_id, + run_id = inc.run_id, + run_status = inc.run_status, + ack = ?ack, + "Ticket comment kept for the run working on the ticket" + ); + match ack { + Ack::Reaction => react(state, inc).await, + Ack::Reply => reply(state, inc).await, + Ack::None => {} + } + if !comment.run_id.is_empty() { + note( + state, + inc.team_id, + &comment.run_id, + &tc::received_note(comment, *ack), + ) + .await; + // The worker reads it now: a comment that says to stop ends the run + // at once, and a run that just finished gets it as a round. + let message = WorkerMessage::JiraComment(JiraCommentMessage { + team_id: inc.team_id.to_string(), + installation_id: inc.installation_id, + ticket_id: inc.ticket_id.to_string(), + title: inc.title.to_string(), + run_id: inc.run_id.to_string(), + run_status: inc.run_status.to_string(), + pr_number: inc.pr_number, + repo_owner: inc.repo_owner.to_string(), + repo_name: inc.repo_name.to_string(), + author: comment.author.clone(), + comment: comment.text.clone(), + context_hash: String::new(), + action: None, + }); + match serde_json::to_string(&message) { + Ok(body) => { + if let Err(e) = state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + // Kept all the same: the run reads it at its next step. + warn!(ticket_id = inc.ticket_id, error = %e, "Could not send the ticket comment to the worker"); + } + } + Err(e) => warn!(error = %e, "Could not serialize the ticket comment"), + } + } + Ok(received) +} + +/// Keeps a comment written while no run works on the ticket, as context +/// for the run that starts on it. No acknowledgement and no note. +pub async fn keep(state: &AppState, inc: &Incoming<'_>) { + let quiet = Incoming { + run_id: "", + run_status: "", + ..inc.clone() + }; + match take(&store(state), &quiet).await { + Ok(Received::Kept(..)) => info!( + ticket_id = inc.ticket_id, + "Ticket comment kept for the run that starts on the ticket" + ), + Ok(_) => {} + Err(e) => { + warn!(ticket_id = inc.ticket_id, error = %e, "Could not keep the ticket comment") + } + } +} + +/// The comments a Jira event carries with the ticket (`comments`: id, +/// author, body), kept as context for the run the event starts. +pub async fn keep_jira_existing(state: &AppState, team_id: &str, ticket_id: &str, payload: &Value) { + for c in existing_jira_comments(payload) { + keep( + state, + &Incoming { + team_id, + source: Source::Jira, + ticket_id, + comment_id: &c.id, + author: &c.author, + author_kind: &c.kind, + text: &c.text, + ..Default::default() + }, + ) + .await; + } +} + +/// One comment a Jira event carries with its ticket. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Existing { + pub id: String, + pub author: String, + pub kind: String, + pub text: String, +} + +/// Most comments read from a ticket when a run starts on it (the newest). +pub const MAX_EXISTING: usize = 20; + +/// The ticket's comments in a Jira event, oldest first: the `comments` +/// list the app sends with the ticket, with a body and an id. +pub fn existing_jira_comments(payload: &Value) -> Vec { + let all: Vec = payload["comments"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| { + let id = match &c["id"] { + Value::String(s) => s.clone(), + Value::Number(n) => n.to_string(), + _ => return None, + }; + let text = common::jira_text::body_text(&c["body"]); + if text.trim().is_empty() { + return None; + } + Some(Existing { + id, + author: c["author"]["displayName"] + .as_str() + .unwrap_or("") + .to_string(), + kind: c["author"]["accountType"] + .as_str() + .unwrap_or("") + .to_string(), + text, + }) + }) + .collect(); + let skip = all.len().saturating_sub(MAX_EXISTING); + all.into_iter().skip(skip).collect() +} + +/// A comment on a GitHub issue (not a pull request) whose ticket has a run +/// working on it: taken for that run. `false` when no run is working on +/// the issue in this repository, or the commenter has no standing. +pub async fn on_github_issue_comment( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, +) -> bool { + if payload["action"].as_str() != Some("created") || payload["issue"]["pull_request"].is_object() + { + return false; + } + let number = payload["issue"]["number"].as_u64().unwrap_or(0); + if number == 0 { + return false; + } + let owner = payload["repository"]["owner"]["login"] + .as_str() + .unwrap_or(""); + let name = payload["repository"]["name"].as_str().unwrap_or(""); + let ticket_id = format!("GH-{number}"); + let Some(run) = working_run(state, team_id, &ticket_id).await else { + return false; + }; + if !run.repo.eq_ignore_ascii_case(&format!("{owner}/{name}")) { + return false; + } + let user = &payload["comment"]["user"]; + let author = user["login"].as_str().unwrap_or(""); + let kind = user["type"].as_str().unwrap_or(""); + let text = payload["comment"]["body"].as_str().unwrap_or(""); + if !tc::is_person(Source::Github, author, kind, text) { + return false; + } + // Only a person with standing in the repository or on the team may + // direct a run, as for any comment that starts work. + if !super::github_webhook::may_start_work( + state, + team_id, + installation_id, + payload, + &payload["comment"], + "comment", + ) + .await + { + return false; + } + let id = payload["comment"]["id"] + .as_u64() + .map(|i| i.to_string()) + .unwrap_or_default(); + receive( + state, + &Incoming { + team_id, + installation_id, + source: Source::Github, + ticket_id: &ticket_id, + comment_id: &id, + author, + author_kind: kind, + text, + title: payload["issue"]["title"].as_str().unwrap_or(""), + run_id: &run.run_id, + run_status: &run.status, + pr_number: run.pr_number, + repo_owner: owner, + repo_name: name, + }, + ) + .await + .is_ok() +} + +/// The ticket's run that is working now. +struct WorkingRun { + run_id: String, + status: String, + repo: String, + pr_number: u64, +} + +async fn working_run(state: &AppState, team_id: &str, ticket_id: &str) -> Option { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .map_err(|e| warn!(ticket_id, error = %e, "Could not look up the ticket's runs")) + .ok()?; + let text = |i: &std::collections::HashMap, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + out.items() + .iter() + .filter(|i| tc::run_working(&text(i, "status"))) + .max_by_key(|i| text(i, "run_id")) + .map(|i| WorkingRun { + run_id: text(i, "run_id"), + status: text(i, "status"), + repo: text(i, "repo"), + pr_number: i + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + }) +} + +/// The reaction on a GitHub comment: seen, and being read. +async fn react(state: &AppState, inc: &Incoming<'_>) { + if inc.comment_id.is_empty() || inc.repo_owner.is_empty() || inc.repo_name.is_empty() { + return; + } + let token = match crate::auth::github_app::get_installation_token(state, inc.installation_id) + .await + { + Ok(t) => t, + Err(e) => { + warn!(ticket_id = inc.ticket_id, error = %e, "No GitHub token to acknowledge the comment"); + return; + } + }; + let url = format!( + "https://api.github.com/repos/{}/{}/issues/comments/{}/reactions", + inc.repo_owner, inc.repo_name, inc.comment_id + ); + super::merge_control::gh_post(state, &token, &url, &json!({ "content": "eyes" })).await; +} + +/// The one short reply on a Jira ticket, through the team's Jira app. +async fn reply(state: &AppState, inc: &Incoming<'_>) { + let config = state + .dynamo + .get_item() + .table_name(&state.config.jira_config_table_name) + .key("pk", AttributeValue::S(inc.team_id.to_string())) + .key("sk", AttributeValue::S("JIRA#config".into())) + .send() + .await + .ok() + .and_then(|o| o.item); + let Some(url) = config + .as_ref() + .and_then(|c| c.get("add_comment_url")) + .and_then(|v| v.as_s().ok()) + .filter(|u| !u.is_empty()) + else { + warn!( + ticket_id = inc.ticket_id, + "No Jira comment address to acknowledge the comment" + ); + return; + }; + let payload = json!({ + "issueKey": inc.ticket_id, + "comment": tc::ack_reply(), + "commentType": "info", + "title": "Comment received", + }); + match state.http.post(url).json(&payload).send().await { + Ok(r) if r.status().is_success() => {} + Ok(r) => warn!( + ticket_id = inc.ticket_id, + status = r.status().as_u16(), + "Jira refused the acknowledgement" + ), + Err(e) => warn!(ticket_id = inc.ticket_id, error = %e, "Jira acknowledgement failed"), + } +} + +/// Most progress notes a run record holds (the worker moves older ones off +/// the record; see its `run_lists`). +const MAX_RUN_NOTES: usize = 250; + +/// Adds a note to the run page's activity. +async fn note(state: &AppState, team_id: &str, run_id: &str, message: &str) { + let now = chrono::Utc::now().to_rfc3339(); + let entry = AttributeValue::M(std::collections::HashMap::from([ + ( + "message".to_string(), + AttributeValue::S(common::truncate_str(message, 1000).to_string()), + ), + ("timestamp".to_string(), AttributeValue::S(now.clone())), + ])); + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression( + "SET progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", + ) + .condition_expression( + "attribute_exists(run_id) AND (attribute_not_exists(progress_notes) OR size(progress_notes) < :max)", + ) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values(":n", AttributeValue::L(vec![entry])) + .expression_attribute_values(":max", AttributeValue::N(MAX_RUN_NOTES.to_string())) + .send() + .await + { + warn!(run_id, error = %e, "Could not note the ticket comment on the run"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use common::ticket_comments::Memory; + + fn incoming<'a>(id: &'a str, author: &'a str, kind: &'a str, text: &'a str) -> Incoming<'a> { + Incoming { + team_id: "TEAM#1", + installation_id: 7, + source: Source::Jira, + ticket_id: "ABC-1", + comment_id: id, + author, + author_kind: kind, + text, + title: "Add the flag", + run_id: "01RUN", + run_status: "running", + ..Default::default() + } + } + + #[tokio::test] + async fn a_comment_during_a_run_is_kept_and_acknowledged_once() { + let store = Memory::default(); + let inc = incoming("10042", "Pat Doe", "atlassian", "Production only."); + let Received::Kept(c, ack) = take(&store, &inc).await.unwrap() else { + panic!("the comment was not kept") + }; + assert_eq!(ack, Ack::Reply, "Jira: one short reply"); + assert_eq!(c.run_id, "01RUN"); + assert_eq!(c.text, "Production only."); + // The webhook delivers it again (and again): one record, and no + // second acknowledgement, note or message. + for _ in 0..3 { + assert_eq!(take(&store, &inc).await.unwrap(), Received::Duplicate); + } + assert_eq!(store.all("TEAM#1", "ABC-1").len(), 1); + } + + #[tokio::test] + async fn github_gets_a_reaction_and_every_working_status_counts() { + let store = Memory::default(); + for (i, status) in ["running", "queued", "awaiting_ci"].into_iter().enumerate() { + let id = format!("{i}"); + let inc = Incoming { + source: Source::Github, + ticket_id: "GH-12", + run_status: status, + ..incoming(&id, "pat-doe", "User", "Production only.") + }; + let Received::Kept(_, ack) = take(&store, &inc).await.unwrap() else { + panic!("not kept at {status}") + }; + assert_eq!(ack, Ack::Reaction, "at {status}"); + } + } + + #[tokio::test] + async fn coderhelms_own_comments_and_bots_are_never_taken() { + let store = Memory::default(); + let own_reply = tc::ack_reply(); + for (author, kind, text) in [ + ("CoderHelm", "app", "Questions only a person can answer"), + ( + "Coderhelm", + "", + "I'm building the rest of the plan meanwhile", + ), + // The acknowledgement itself, whatever name the tracker shows. + ("Some App", "", own_reply.as_str()), + ("Automation for Jira", "app", "Moved to In Progress"), + ] { + let inc = incoming("1", author, kind, text); + assert_eq!(take(&store, &inc).await.unwrap(), Received::NotAPerson); + } + let gh = Incoming { + source: Source::Github, + ..incoming("2", "coderhelm[bot]", "Bot", "Working on it") + }; + assert_eq!(take(&store, &gh).await.unwrap(), Received::NotAPerson); + assert!( + store.all("TEAM#1", "ABC-1").is_empty(), + "nothing kept, so nothing can come back" + ); + } + + #[tokio::test] + async fn a_comment_with_no_run_working_is_kept_without_an_acknowledgement() { + let store = Memory::default(); + for status in [ + "", + "completed", + "failed", + "needs_input", + "cancelled", + "closed", + ] { + let id = format!("c-{status}"); + let inc = Incoming { + run_status: status, + ..incoming(&id, "Pat Doe", "", "Context for whoever picks this up.") + }; + let Received::Kept(c, ack) = take(&store, &inc).await.unwrap() else { + panic!("not kept at {status:?}") + }; + assert_eq!(ack, Ack::None, "at {status:?}"); + assert!(!c.during_run(), "context, never a stop: {status:?}"); + } + } + + #[test] + fn the_tickets_existing_comments_are_read_from_the_event() { + let payload = json!({"comments": [ + {"id": "1", "author": {"displayName": "Pat Doe", "accountType": "atlassian"}, + "body": "Production only."}, + {"id": 2, "author": {"displayName": "CoderHelm", "accountType": "app"}, + "body": "Questions only a person can answer"}, + {"id": "3", "author": {"displayName": "Sam Roe"}, "body": " "}, + {"author": {"displayName": "No Id"}, "body": "x"} + ]}); + let got = existing_jira_comments(&payload); + assert_eq!(got.len(), 2); + assert_eq!(got[0].id, "1"); + assert_eq!(got[0].text, "Production only."); + assert_eq!(got[1].kind, "app"); + // An event without the list (an older app) reads as none. + assert!(existing_jira_comments(&json!({"issue": {}})).is_empty()); + // Only the newest are read. + let many: Vec = (0..50) + .map(|i| json!({"id": i.to_string(), "author": {"displayName": "Pat"}, "body": "x"})) + .collect(); + let got = existing_jira_comments(&json!({ "comments": many })); + assert_eq!(got.len(), MAX_EXISTING); + assert_eq!(got.last().unwrap().id, "49"); + } + + #[test] + fn the_webhooks_no_longer_drop_a_comment_for_a_run_in_progress() { + let jira = include_str!("jira_webhook.rs"); + assert!(!jira.contains("Ignoring Jira comment")); + assert!(!jira.contains("\"comment_skipped\"")); + assert!(jira.contains("super::ticket_comments::receive(")); + assert!(jira.contains("super::ticket_comments::keep(")); + let github = include_str!("github_webhook.rs"); + assert!(github.contains("super::ticket_comments::on_github_issue_comment(")); + } +} diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 9abf9bacb..bd878c5d4 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -329,7 +329,11 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) let team_id = msg.team_id.clone(); let run_id = msg.run_id.clone(); let retry_msg = msg.clone(); - if let Err(e) = passes::feedback::run(&state, msg).await { + let round = passes::feedback::run(&state, msg).await; + // What people wrote on the ticket while the round worked is + // read now, never left for the next event. + passes::ticket_comments::after_round(&state, &team_id, &run_id).await; + if let Err(e) = round { // The run guard fired: it waits on a person, one way. if passes::run_guard::settle_open_pr(&state, &team_id, &run_id).await { return; @@ -491,7 +495,9 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) models::WorkerMessage::Resume(msg) => { info!(team_id = %msg.team_id, run_id = %msg.run_id, "Resuming run from webhook event"); let (team_id, run_id) = (msg.team_id.clone(), msg.run_id.clone()); - if let Err(e) = passes::resume::run(&state, msg).await { + let resumed = passes::resume::run(&state, msg).await; + passes::ticket_comments::after_round(&state, &team_id, &run_id).await; + if let Err(e) = resumed { error!("Resume failed: {e:?}"); // The run guard fired: it waits on a person, one way. if passes::run_guard::settle_open_pr(&state, &team_id, &run_id).await { diff --git a/services/worker/src/passes/incidents/aq_comment_during_run.rs b/services/worker/src/passes/incidents/aq_comment_during_run.rs new file mode 100644 index 000000000..fe8fa54bb --- /dev/null +++ b/services/worker/src/passes/incidents/aq_comment_during_run.rs @@ -0,0 +1,288 @@ +//! aq. A run started from a ticket asked three questions on it ("Questions +//! only a person can answer"), proposed its defaults and kept building. +//! Twenty minutes later a person answered on the ticket. The gateway logged +//! "Ignoring Jira comment — run already in progress" and dropped it: nothing +//! acknowledged the comment, the run never saw it, and its notes kept saying +//! "3 question(s) already asked on the ticket — not asked again; the run goes +//! on without the answers". Comments written on the ticket before any run +//! existed were dropped the same way ("No runs found for Jira comment — +//! ignoring"), and nothing read them when the run started. +//! +//! Guarantee: a person who writes on a ticket CoderHelm is working on gets +//! an acknowledgement, and what they wrote is acted on. The comment is kept +//! once per comment id and acknowledged once (a reaction on GitHub, one +//! short reply in Jira; never for CoderHelm's own comments). The run reads +//! its open comments at its next step boundary, together: an answer or an +//! instruction goes into the plan while it is being made; once the plan is +//! final it becomes one round on the pull request when the step ends, where +//! the code changes in the place the plan put that choice, and the ticket +//! is told; a comment that says to stop ends the run at once. A comment +//! nobody read yet stays open for whatever comes next, and comments written +//! before the run started are read at its first boundary. + +use super::fixture::*; +use crate::passes::ticket_comments::{self as worker_side, effects}; +use common::ticket_comments::{ + self as tc, Ack, Action, Class, Comment, Memory, Source, Stage, State, Store, +}; +use serde_json::json; + +/// What the gateway used to log, and what the run's notes used to say. +const OLD_DROP: &str = "run already in progress"; +const OLD_NOTE: &str = "goes on without the answers"; +const OLD_IGNORED: &str = "ignoring"; + +const TEAM: &str = "TEAM#1"; +const TICKET: &str = "ABC-1"; +const RUN: &str = "01RUN"; + +fn questions() -> Vec { + vec![ + "Which environments get the new flag: production only, or staging too?".to_string(), + "Keep the old column for one release, or drop it now?".to_string(), + "Who may see the export: admins only, or every member?".to_string(), + ] +} + +/// The comment as the tracker delivers it while the run is building. +fn answer_delivery() -> (String, String, String, String) { + ( + "10042".to_string(), + "Pat Doe".to_string(), + "atlassian".to_string(), + "Production only. Keep the old column for one release. Admins only.".to_string(), + ) +} + +/// The gateway's part, as `routes::ticket_comments::take` does it: a +/// person's comment is kept once, with the run that was working. +async fn deliver( + store: &Memory, + (id, author, kind, text): &(String, String, String, String), + run_status: &str, +) -> Option<(Comment, Ack)> { + if !tc::is_person(Source::Jira, author, kind, text) { + return None; + } + let working = tc::run_working(run_status); + let c = Comment { + ticket_id: TICKET.into(), + source: Source::Jira, + comment_id: tc::comment_id(id, author, text), + author: author.clone(), + text: text.clone(), + at: chrono::Utc::now().to_rfc3339(), + run_id: if working { RUN.into() } else { String::new() }, + ..Default::default() + }; + let new = store.record(TEAM, &c).await.unwrap(); + new.then(|| (c, tc::ack_for(Source::Jira, true, new, working))) +} + +/// One read of the ticket's open comments at `stage`, with the model's +/// reply for the unread ones. +async fn read_at( + store: &Memory, + stage: Stage, + model_reply: &serde_json::Value, + pr: Option<&str>, + end: &mut Ending, +) -> worker_side::Effects { + let mut open = tc::open(store.all(TEAM, TICKET)); + let unread = open.iter().filter(|c| c.class.is_none()).count(); + if unread > 0 { + let readings = tc::readings(model_reply, &questions(), unread); + tc::keep_readings(store, TEAM, &mut open, &readings).await; + } + let settled = tc::settle_open(store, TEAM, RUN, &open, stage, pr).await; + let fx = effects(&settled, pr); + for n in &fx.run_notes { + end.said(n.clone()); + } + if let Some(r) = &fx.reply { + end.said(r.clone()); + } + fx +} + +#[tokio::test] +async fn an_answer_written_while_the_run_builds_is_acknowledged_read_and_applied() { + let store = Memory::default(); + let mut end = Ending::default(); + + // Twenty minutes in, the run is building from its final plan. + let (c, ack) = deliver(&store, &answer_delivery(), "running") + .await + .expect("the comment is kept, never dropped"); + assert_eq!(ack, Ack::Reply, "one short reply on the ticket"); + end.said(tc::ack_reply()); + end.said(tc::received_note(&c, ack)); + assert!(end.says("Pat Doe commented on the ticket")); + + // The webhook is delivered again: no second record or acknowledgement. + assert!(deliver(&store, &answer_delivery(), "running") + .await + .is_none()); + // CoderHelm's own reply comes back as a comment event: never read. + let own = ( + "10043".to_string(), + "Coderhelm".to_string(), + "app".to_string(), + tc::ack_reply(), + ); + assert!(deliver(&store, &own, "running").await.is_none()); + assert_eq!(store.all(TEAM, TICKET).len(), 1); + + // Read as soon as it arrives (outside the run's step): it answers the + // run's questions and doesn't say to stop, so it waits for the run. + let model = json!({"comments": [ + {"n": 1, "class": "answer", "question": 1, "reason": "answers the three questions"} + ]}); + let fx = read_at(&store, Stage::BetweenSteps, &model, None, &mut end).await; + assert_eq!(fx, worker_side::Effects::default()); + assert_eq!( + tc::open(store.all(TEAM, TICKET))[0].class, + Some(Class::Answer) + ); + + // The run's next step boundary: the plan is final, so the answer is + // kept for the pull request, and the run page says so. + let fx = read_at(&store, Stage::Building, &json!({}), None, &mut end).await; + assert!( + fx.folded.is_empty() && fx.round.is_none(), + "nothing yet but the note" + ); + assert!(end.says("Read Pat Doe's comment as an answer to \"Which environments")); + assert!(end.says("applied as a round on the pull request when this step ends")); + assert_eq!(tc::open(store.all(TEAM, TICKET))[0].state, State::Deferred); + + // The step ends with the pull request open: one round on it, with the + // answer and where to apply it, and the ticket is told. + let pr = "https://example.test/acme/web/pull/12"; + let done = Stage::Finished { + pr_open: true, + waiting: false, + }; + let fx = read_at(&store, done, &json!({}), Some(pr), &mut end).await; + let round = fx.round.expect("a feedback round on the open pull request"); + assert!(round.contains("Answer: Production only. Keep the old column")); + assert!(round.contains( + "Where this answer differs from the default that was built, change the code in the place the plan put that choice" + )); + assert!(round.contains("Say in the pull request")); + assert!(end.says("I'm now changing the code where that choice lives to match the answer")); + assert!(end.says(pr)); + end.status = "completed".into(); + end.pr = Some(12); + + // Acted on once: nothing is left, whoever reads next. + assert!(tc::open(store.all(TEAM, TICKET)).is_empty()); + let fx = read_at(&store, done, &json!({}), Some(pr), &mut end).await; + assert_eq!(fx, worker_side::Effects::default()); + + end.never_says(OLD_DROP); + end.never_says(OLD_NOTE); + end.never_says(OLD_IGNORED); +} + +#[tokio::test] +async fn comments_written_before_the_run_are_read_when_it_starts() { + let store = Memory::default(); + let mut end = Ending::default(); + // No run yet: kept without an acknowledgement, as context. + let early = ( + "10001".to_string(), + "Sam Roe".to_string(), + "atlassian".to_string(), + "Use the existing export helper, don't add a new one.".to_string(), + ); + let (c, ack) = deliver(&store, &early, "").await.expect("kept"); + assert_eq!(ack, Ack::None); + assert!(!c.during_run()); + + // The run starts and reads the ticket at its first boundary, while it + // plans: the planner gets the comment word for word. + let model = json!({"comments": [ + {"n": 1, "class": "instruction", "question": 0, "reason": "says how to build it"} + ]}); + let fx = read_at(&store, Stage::Planning, &model, None, &mut end).await; + assert_eq!(fx.folded.len(), 1); + let note = common::run_questions::answers_note(&fx.folded); + assert!(note.contains("Answer from Sam Roe: Use the existing export helper")); + assert!(end.says("folded into the plan before any code was written")); + assert_eq!(fx.reply, None, "nothing more is posted on the ticket"); + // Even one that says to stop is context: it was written before the run. + assert_eq!( + tc::decide(Class::Stop, Stage::Planning, false, false), + Action::Fold + ); + end.never_says(OLD_IGNORED); +} + +#[tokio::test] +async fn whatever_state_the_run_is_in_the_comment_is_not_lost() { + let model = json!({"comments": [ + {"n": 1, "class": "answer", "question": 1, "reason": ""} + ]}); + let pr_open = Stage::Finished { + pr_open: true, + waiting: false, + }; + let waiting = Stage::Finished { + pr_open: false, + waiting: true, + }; + // (the stage when the comment is read, what becomes of it) + for (stage, expect) in [ + (Stage::Planning, Action::Fold), + (Stage::Building, Action::Defer), + (Stage::Reviewing, Action::Defer), + (pr_open, Action::Round), + (waiting, Action::Restart), + (Stage::Cancelled, Action::Keep), + ] { + let store = Memory::default(); + let mut end = Ending::default(); + deliver(&store, &answer_delivery(), "running") + .await + .unwrap(); + // Handed off between steps first: it waits, still open. + read_at(&store, Stage::BetweenSteps, &model, None, &mut end).await; + assert_eq!(tc::open(store.all(TEAM, TICKET)).len(), 1, "{stage:?}"); + let fx = read_at(&store, stage, &json!({}), Some("PR"), &mut end).await; + match expect { + Action::Fold => assert_eq!(fx.folded.len(), 1), + Action::Defer => { + assert_eq!(tc::open(store.all(TEAM, TICKET))[0].state, State::Deferred) + } + Action::Round => assert!(fx.round.is_some()), + Action::Restart => assert!(fx.restart.is_some()), + Action::Keep => assert_eq!(fx.ticket_notes.len(), 1), + other => panic!("unexpected {other:?}"), + } + assert!( + !end.words.is_empty(), + "the run page says what was done at {stage:?}" + ); + end.never_says(OLD_NOTE); + } +} + +#[test] +fn the_pipeline_and_the_webhooks_take_the_comment() { + // The run reads its ticket at its boundaries, and when a step ends. + let run = run_passes_src(); + assert!(run.contains("read_ticket_comments(state, msg, run_id, usage)")); + let src = include_str!("../mod.rs"); + assert!(src.contains("ticket_comments::after_step(state, &msg, &run_id)")); + // The note that said the run goes on without the answers is gone. + assert!(!src.contains("the run goes on without the answers")); + // The gateway keeps the comment where it used to drop it. + let jira = include_str!("../../../../gateway/src/routes/jira_webhook.rs"); + assert!(!jira.contains("Ignoring Jira comment")); + assert!(!jira.contains("No runs found for Jira comment — ignoring")); + assert!(jira.contains("super::ticket_comments::receive(")); + let github = include_str!("../../../../gateway/src/routes/github_webhook.rs"); + assert!(!github.contains("Skipping slash command — run already in flight")); + assert!(github.contains("super::ticket_comments::on_github_issue_comment(")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index ce9e89168..14742cbce 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -31,6 +31,7 @@ mod am_description_from_the_head; mod an_six_database_findings; mod ao_stopped_log_finding; mod ap_closed_pr_keeps_findings; +mod aq_comment_during_run; mod b_open_pr_retry; mod ba_verdict_on_old_commit; mod bb_flaky_not_broken; diff --git a/services/worker/src/passes/jira_comment.rs b/services/worker/src/passes/jira_comment.rs index 9c46fc167..cb58e6aec 100644 --- a/services/worker/src/passes/jira_comment.rs +++ b/services/worker/src/passes/jira_comment.rs @@ -197,13 +197,36 @@ async fn record( note: Note, done_reason: Option<&str>, ) { - let sk = ticket_state::sk(&msg.ticket_id); + record_notes( + state, + &msg.team_id, + &msg.ticket_id, + vec![note], + done_reason.map(|r| (r, msg.context_hash.as_str())), + ) + .await; +} + +/// Adds comments to the ticket's record, so the next plan on the ticket +/// reads them. `done`: also marks the ticket done, with the reason and the +/// ticket's content hash now. +pub(crate) async fn record_notes( + state: &WorkerState, + team_id: &str, + ticket_id: &str, + new: Vec, + done: Option<(&str, &str)>, +) { + if new.is_empty() && done.is_none() { + return; + } + let sk = ticket_state::sk(ticket_id); let table = &state.config.settings_table_name; let mut notes = state .dynamo .get_item() .table_name(table) - .key("pk", attr_s(&msg.team_id)) + .key("pk", attr_s(team_id)) .key("sk", attr_s(&sk)) .send() .await @@ -216,7 +239,7 @@ async fn record( }) .map(|j| ticket_state::parse_notes(&j)) .unwrap_or_default(); - notes.push(note); + notes.extend(new); if notes.len() > ticket_state::MAX_NOTES { let drop = notes.len() - ticket_state::MAX_NOTES; notes.drain(..drop); @@ -226,7 +249,7 @@ async fn record( .dynamo .update_item() .table_name(table) - .key("pk", attr_s(&msg.team_id)) + .key("pk", attr_s(team_id)) .key("sk", attr_s(&sk)) .expression_attribute_names("#n", ticket_state::FIELD_NOTES) .expression_attribute_values( @@ -234,19 +257,19 @@ async fn record( attr_s(&serde_json::to_string(¬es).unwrap_or_default()), ) .expression_attribute_values(":t", attr_s(&now)); - up = match done_reason { - Some(reason) => up + up = match done { + Some((reason, context_hash)) => up .update_expression("SET #n = :n, updated_at = :t, #s = :s, #r = :r, #h = :h") .expression_attribute_names("#s", ticket_state::FIELD_STATE) .expression_attribute_names("#r", ticket_state::FIELD_DONE_REASON) .expression_attribute_names("#h", ticket_state::FIELD_DONE_HASH) .expression_attribute_values(":s", attr_s(ticket_state::STATE_DONE)) .expression_attribute_values(":r", attr_s(reason)) - .expression_attribute_values(":h", attr_s(&msg.context_hash)), + .expression_attribute_values(":h", attr_s(context_hash)), None => up.update_expression("SET #n = :n, updated_at = :t"), }; if let Err(e) = up.send().await { - warn!(ticket_id = %msg.ticket_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not record the ticket comment"); + warn!(ticket_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not record the ticket comment"); } } @@ -308,6 +331,14 @@ pub async fn run( state: &WorkerState, msg: JiraCommentMessage, ) -> Result<(), Box> { + // Comments kept while a run worked on the ticket (see + // `ticket_comments`) are read first: a request to stop ends the run + // now, and what a run that has ended never read is acted on here. + super::ticket_comments::on_comment(state, &msg).await; + if msg.action.is_none() { + // The comment itself is one of those: nothing else to start. + return Ok(()); + } let provider = ModelProvider::load_for_team( &state.dynamo, &state.config.settings_table_name, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 5ce882505..7a5caa8cd 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1347,6 +1347,7 @@ mod test; pub mod test_bug; pub mod test_fix; pub mod ticket_base; +pub mod ticket_comments; pub mod ticket_history; pub mod tool_proposals; mod triage; @@ -1799,6 +1800,33 @@ pub async fn orchestrate_ticket( release_ticket_lock(state, &msg.team_id, &msg.ticket_id).await; } + // The step is over. What people wrote on the ticket meanwhile is never + // left behind: with the pull request open it becomes a round on it, a + // run that ended waiting or failed starts the ticket again with it, a + // run a person stopped keeps it for the next run, and a run that goes + // on in a fresh step reads it there. + ticket_comments::after_step(state, &msg, &run_id).await; + + Ok(()) +} + +/// A step boundary: the run reads what people wrote on its ticket (all of +/// it together) before it spends more work. Answers and instructions go +/// into the plan while it is being made; once the plan is final they are +/// kept for a round on the pull request; a person saying to stop ends the +/// run here, the way a cancel from the dashboard does. +async fn read_ticket_comments( + state: &WorkerState, + msg: &mut TicketMessage, + run_id: &str, + usage: &mut TokenUsage, +) -> Result<(), Box> { + let read = ticket_comments::at_boundary(state, msg, run_id, usage).await; + common::run_questions::merge(&mut msg.answers, &read.folded); + if read.stopped { + // The text `orchestrate_ticket` reads as a person's cancel. + return Err("Run cancelled by user".into()); + } Ok(()) } @@ -1983,6 +2011,11 @@ async fn run_passes( .map(common::ticket_state::decision_answer) .collect(); common::run_questions::merge(&mut msg.answers, &decided); + // 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. + ticket_comments::keep_existing_github(state, msg, &github).await; + read_ticket_comments(state, msg, run_id, usage).await?; // Every pull request for the ticket in the team's repositories (this // repo first; CoderHelm's or anyone's), read in full with how it ended: // an earlier attempt often holds the design, and its close event says @@ -2681,6 +2714,7 @@ async fn run_passes( // --- Pass 2: Plan --- check_cancelled(state, &msg.team_id, run_id).await?; + read_ticket_comments(state, msg, run_id, usage).await?; // How far planning got: saved from here on, so a step that runs out of // time while planning continues in a fresh step (see `steps::Gate::Plan`) // instead of failing with nothing committed. A continuation past @@ -3964,6 +3998,9 @@ async fn run_passes( } else { check_cancelled(state, &msg.team_id, run_id).await?; update_pass(state, &msg.team_id, run_id, "implement").await?; + // The plan is final from here: a comment read now is applied as a + // round on the pull request when this step ends. + read_ticket_comments(state, msg, run_id, usage).await?; // --- Re-run detection: check if branch already has an open PR --- // If an open PR exists, we always try to fix it rather than starting fresh. @@ -6049,6 +6086,7 @@ async fn run_passes( // --- Adversarial Test (multi-repo path) --- check_cancelled(state, &msg.team_id, run_id).await?; + read_ticket_comments(state, msg, run_id, usage).await?; let tested_at = github .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) .await @@ -6542,6 +6580,7 @@ async fn run_passes( } check_cancelled(state, &msg.team_id, run_id).await?; + read_ticket_comments(state, msg, run_id, usage).await?; if remaining_secs(start) < MIN_TIME_FOR_PR_SECS { close_memory(state, agent_memory.take()).await; return hand_off_at( @@ -9137,6 +9176,8 @@ async fn report_questions( github: &GitHubClient, decision: &fix_location::FixDecision, ) { + // Kept on the run, so a comment that answers one is read as its answer. + ticket_comments::keep_asked(state, &msg.team_id, run_id, &decision.questions).await; let rec = open_pr_choice::load_record(state, &msg.team_id, &msg.ticket_id).await; let fresh = new_questions(&decision.questions, &rec.notices); let earlier = decision @@ -9151,7 +9192,7 @@ async fn report_questions( &msg.team_id, run_id, &format!( - "{earlier} question(s) already asked on the ticket — not asked again; the run goes on without the answers" + "{earlier} question(s) already asked on the ticket — not asked again; the run builds its defaults and applies an answer when one is written on the ticket" ), ) .await; diff --git a/services/worker/src/passes/ticket_comments.rs b/services/worker/src/passes/ticket_comments.rs new file mode 100644 index 000000000..4b699c1c3 --- /dev/null +++ b/services/worker/src/passes/ticket_comments.rs @@ -0,0 +1,1056 @@ +//! The worker's side of ticket comments (see `common::ticket_comments`): +//! what people wrote on a ticket is read where the run can still use it, +//! and nothing a person wrote is lost when the run moves on. +//! +//! A run's open comments are read: +//! +//! - when the run starts and at each step boundary ([`at_boundary`]), +//! before it spends more work: answers and instructions go into the plan +//! while it is still being made, and are kept for a round on the pull +//! request once the code is being built from the final plan; +//! - when a step ends ([`after_step`]): with the pull request open, the +//! comments kept for it become one feedback round; a run that ended +//! waiting on a person or failed starts the ticket again with them; a +//! run a person stopped keeps them on the ticket for the next run; +//! - as soon as one arrives ([`on_comment`]), so a comment that says to +//! stop ends the run now and not at its next step, and a comment that +//! reached a run a moment after it ended is still acted on. +//! +//! Every read takes all open comments together (one model call for a +//! burst), and a comment is claimed in the store before anything is done +//! with it, so two readers never act on it twice. + +use crate::agent::provider::ModelProvider; +use crate::clients::github::GitHubClient; +use crate::models::{ + FeedbackMessage, JiraCommentMessage, TicketMessage, TicketSource, TokenUsage, WorkerMessage, +}; +use crate::passes::attr_s; +use crate::WorkerState; +use common::run_questions::Answer; +use common::ticket_comments::{self as tc, Action, Comment, Settled, Source, Stage, Store}; +use common::ticket_state::{Intent, Note}; +use tracing::{info, warn}; + +/// What a boundary read gives the run. +#[derive(Debug, Default)] +pub struct Read { + /// Answers and instructions for the plan being made: the planner reads + /// them word for word. + pub folded: Vec, + /// A person said to stop: the run ends now. + pub stopped: bool, +} + +/// The ticket a read is for, and how to reach it. +struct Ticket<'a> { + team_id: &'a str, + ticket_id: &'a str, + run_id: &'a str, + installation_id: u64, +} + +fn store(state: &WorkerState) -> tc::Dynamo<'_> { + tc::Dynamo { + client: &state.dynamo, + table: &state.config.settings_table_name, + } +} + +/// What the run's record says about where it is. +#[derive(Debug, Default, Clone)] +struct RunFacts { + status: String, + current_pass: String, + pr_number: u64, + pr_outcome: String, + repo: String, + title: String, + issue_number: u64, + updated_at: String, + /// The questions the run told the ticket about and kept building + /// without. + questions: Vec, +} + +impl RunFacts { + fn pr_open(&self) -> bool { + self.pr_number > 0 && !matches!(self.pr_outcome.as_str(), "closed" | "merged") + } + + fn pr_link(&self) -> Option { + (self.pr_number > 0 && !self.repo.is_empty()) + .then(|| format!("https://github.com/{}/pull/{}", self.repo, self.pr_number)) + } +} + +async fn run_facts(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + let item = 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)) + .consistent_read(true) + .send() + .await + .map_err(|e| warn!(run_id, error = %e, "Could not read the run for its ticket comments")) + .ok()? + .item?; + let text = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let number = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0) + }; + let mut questions: Vec = + serde_json::from_str(&text(tc::FIELD_ASKED)).unwrap_or_default(); + // A run that stopped to ask keeps its questions as asked (read only). + if let Ok(asked) = + serde_json::from_str::(&text(tc::FIELD_STOPPED_TO_ASK)) + { + for q in asked.questions { + if !questions.contains(&q.question) { + questions.push(q.question); + } + } + } + Some(RunFacts { + status: text("status"), + current_pass: text("current_pass"), + pr_number: number("pr_number"), + pr_outcome: text("pr_outcome"), + repo: text("repo"), + title: text("title"), + issue_number: number("issue_number"), + updated_at: text("updated_at"), + questions, + }) +} + +/// Whether a run still marked as working has gone quiet for longer than a +/// working run can (the bounds the trigger gate uses). +pub fn gone_quiet(status: &str, updated_at: &str, now: chrono::DateTime) -> bool { + let hours = chrono::DateTime::parse_from_rfc3339(updated_at) + .map(|t| now.signed_duration_since(t).num_hours()) + .unwrap_or(0); + match status { + "running" | "queued" => hours >= 2, + "awaiting_ci" => hours >= 26, + _ => false, + } +} + +/// Keeps the questions the run told its ticket about on the run record, so +/// a comment that answers one is read as that answer. +pub async fn keep_asked(state: &WorkerState, team_id: &str, run_id: &str, questions: &[String]) { + let asked: Vec<&str> = questions + .iter() + .map(|q| q.trim()) + .filter(|q| !q.is_empty()) + .collect(); + if asked.is_empty() { + 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 #q = :q") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#q", tc::FIELD_ASKED) + .expression_attribute_values( + ":q", + attr_s(&serde_json::to_string(&asked).unwrap_or_default()), + ) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the run's questions for its ticket comments"); + } +} + +/// The model's reading of the unread comments, in order; every one reads +/// as an instruction (never a stop) when the model can't be reached. +async fn classify( + state: &WorkerState, + team_id: &str, + title: &str, + questions: &[String], + unread: &[Comment], + usage: &mut TokenUsage, +) -> Vec { + let provider = match ModelProvider::load_for_team( + &state.dynamo, + &state.config.settings_table_name, + team_id, + ) + .await + { + Ok(p) => p, + Err(e) => { + warn!(team_id, error = %e, "No model to read the ticket comments; read as instructions"); + return Vec::new(); + } + }; + match crate::agent::anthropic::converse_json( + &provider.client(), + provider.judgment_model_id(), + tc::SYSTEM, + &tc::prompt(title, questions, unread), + &tc::schema(), + true, + common::stop_judge::JUDGMENT_EFFORT, + 4096, + usage, + ) + .await + { + Ok(reply) => tc::readings(&reply, questions, unread.len()), + Err(e) => { + warn!(team_id, error = %e, "Could not read the ticket comments; read as instructions"); + Vec::new() + } + } +} + +/// What a settled read asks of the worker, worked out before anything is +/// sent. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Effects { + /// For the plan being made. + pub folded: Vec, + /// The feedback round on the open pull request, when there is one. + pub round: Option, + /// The direction the ticket starts again with, when it does. + pub restart: Option<(String, Vec)>, + /// The person who said to stop, when one did. + pub stop_by: Option, + /// Kept on the ticket's record for later runs. + pub ticket_notes: Vec, + /// One line per comment for the run page. + pub run_notes: Vec, + /// The one comment CoderHelm posts on the ticket, when it has + /// something to say. + pub reply: Option, +} + +/// The work a settled read asks for. +pub fn effects(settled: &Settled, pr: Option<&str>) -> Effects { + let round = settled.with(Action::Round); + let restart = settled.with(Action::Restart); + let kept_for_later = |a: &Action| { + matches!( + a, + Action::Fold | Action::Round | Action::Restart | Action::Keep + ) + }; + Effects { + folded: settled + .with(Action::Fold) + .iter() + .map(tc::as_answer) + .collect(), + round: (!round.is_empty()).then(|| tc::round_body(&round)), + restart: (!restart.is_empty()).then(|| { + ( + tc::direction(&restart), + restart.iter().map(tc::as_answer).collect(), + ) + }), + stop_by: settled.with(Action::Stop).first().map(|c| c.author.clone()), + ticket_notes: settled + .done + .iter() + .filter(|(a, _)| kept_for_later(a)) + .map(|(_, c)| Note { + author: c.author.clone(), + text: common::truncate_str(c.text.trim(), 2000).to_string(), + intent: Intent::NewRequirement, + at: c.at.clone(), + }) + .collect(), + run_notes: settled + .done + .iter() + .map(|(_, c)| c.outcome.clone()) + .collect(), + reply: tc::ticket_reply(&settled.done, pr), + } +} + +/// Reads the ticket's open comments for the run and does what each asks. +/// `in_step`: read by the run's own step. `restart`: the ticket's message, +/// when this reader may start the ticket again. +async fn read( + state: &WorkerState, + t: &Ticket<'_>, + in_step: bool, + restart: Option<&TicketMessage>, + usage: &mut TokenUsage, +) -> Read { + let store = store(state); + let mut open = match store.of_ticket(t.team_id, t.ticket_id).await { + Ok(all) => tc::open(all), + Err(e) => { + warn!(ticket_id = t.ticket_id, error = %e, "Could not read the ticket's comments; they stay open"); + return Read::default(); + } + }; + if open.is_empty() { + return Read::default(); + } + let Some(facts) = run_facts(state, t.team_id, t.run_id).await else { + return Read::default(); + }; + let stale = gone_quiet(&facts.status, &facts.updated_at, chrono::Utc::now()); + let mut stage = tc::stage_of( + &facts.status, + &facts.current_pass, + facts.pr_open(), + in_step, + stale, + ); + // Only the run's own step may start the ticket again: any other reader + // keeps the comments on the ticket for the next run. + if let ( + Stage::Finished { + pr_open: false, + waiting: true, + }, + None, + ) = (stage, restart) + { + stage = Stage::Finished { + pr_open: false, + waiting: false, + }; + } + + let unread: Vec = open.iter().filter(|c| c.class.is_none()).cloned().collect(); + if !unread.is_empty() { + let readings = classify( + state, + t.team_id, + &facts.title, + &facts.questions, + &unread, + usage, + ) + .await; + tc::keep_readings(&store, t.team_id, &mut open, &readings).await; + } + + let pr = facts.pr_link(); + let mut settled = + tc::settle_open(&store, t.team_id, t.run_id, &open, stage, pr.as_deref()).await; + if settled.done.is_empty() { + return Read::default(); + } + info!( + run_id = t.run_id, + ticket_id = t.ticket_id, + stage = ?stage, + comments = settled.done.len(), + "Read the ticket's comments" + ); + // The work is sent first. What couldn't be sent is put back as open + // (whatever reads the ticket next takes it up) and nothing is said + // about it. + let planned = effects(&settled, pr.as_deref()); + if let Some(body) = &planned.round { + if !send_round(state, t, &facts, body).await { + reopen(&store, t.team_id, &settled.with(Action::Round)).await; + settled.done.retain(|(a, _)| *a != Action::Round); + } + } + if let Some((direction, answers)) = &planned.restart { + let started = match restart { + Some(msg) => start_again(state, msg, direction, answers).await, + None => false, + }; + if !started { + reopen(&store, t.team_id, &settled.with(Action::Restart)).await; + settled.done.retain(|(a, _)| *a != Action::Restart); + } + } + let fx = effects(&settled, pr.as_deref()); + if let Some(by) = &fx.stop_by { + stop_run(state, t, by).await; + } + for line in &fx.run_notes { + super::add_progress_note(state, t.team_id, t.run_id, line).await; + } + super::jira_comment::record_notes(state, t.team_id, t.ticket_id, fx.ticket_notes.clone(), None) + .await; + if let Some(reply) = &fx.reply { + say_on_ticket(state, t, &facts, &open, reply).await; + } + Read { + folded: fx.folded, + stopped: fx.stop_by.is_some(), + } +} + +/// Puts comments back as open when the work they asked for couldn't be +/// sent: whatever reads the ticket next takes them up. +async fn reopen(store: &dyn Store, team_id: &str, comments: &[Comment]) { + for c in comments { + let mut back = c.clone(); + back.state = tc::State::Pending; + back.outcome.clear(); + back.handled_by.clear(); + back.handled_at.clear(); + if let Err(e) = store.settle(team_id, &back, c.state).await { + warn!(ticket_id = %c.ticket_id, error = %e, "Could not reopen a ticket comment"); + } + } +} + +/// Ends the run because a person said to stop, the way a cancel from the +/// dashboard does: the run's next boundary sees it and stops. +async fn stop_run(state: &WorkerState, t: &Ticket<'_>, by: &str) { + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(t.team_id)) + .key("run_id", attr_s(t.run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, updated_at = :t, cancelled_by = :cb, cancel_reason = :cr", + ) + .condition_expression("#s IN (:running, :queued, :awaiting)") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(common::run_status::CANCELLED)) + .expression_attribute_values( + ":sri", + attr_s(&format!("{}#{}", common::run_status::CANCELLED, t.run_id)), + ) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":cb", attr_s(&format!("{by} (comment on the ticket)"))) + .expression_attribute_values(":cr", attr_s("cancelled_by_user")) + .expression_attribute_values(":running", attr_s("running")) + .expression_attribute_values(":queued", attr_s("queued")) + .expression_attribute_values(":awaiting", attr_s("awaiting_ci")) + .send() + .await; + match res { + Ok(_) => info!( + run_id = t.run_id, + "Run stopped: a person said to stop on the ticket" + ), + Err(e) => { + warn!(run_id = t.run_id, error = %e, "Could not stop the run for the ticket comment (it may have ended already)") + } + } +} + +/// Sends the feedback round for the comments onto the run's open pull +/// request. `false` when it couldn't be sent. +async fn send_round(state: &WorkerState, t: &Ticket<'_>, facts: &RunFacts, body: &str) -> bool { + let Some((owner, name)) = facts.repo.split_once('/') else { + warn!( + run_id = t.run_id, + "The run names no repository for the round" + ); + return false; + }; + let message = WorkerMessage::Feedback(FeedbackMessage { + team_id: t.team_id.to_string(), + installation_id: t.installation_id, + run_id: t.run_id.to_string(), + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number: facts.pr_number, + review_id: 0, + review_body: body.to_string(), + comments: vec![], + // Written on the ticket, not the pull request: nobody to address + // there. The round says what changed in the pull request itself. + trigger_author: String::new(), + ..Default::default() + }); + send(state, &state.config.feedback_queue_url, &message).await +} + +/// Starts the ticket again with the comments as a person's direction (a +/// run that ended waiting on a person, or failed). `false` when another +/// run is already starting on the ticket or it couldn't be sent. +async fn start_again( + state: &WorkerState, + msg: &TicketMessage, + direction: &str, + answers: &[Answer], +) -> bool { + if !super::acquire_ticket_lock(state, &msg.team_id, &msg.ticket_id).await { + info!(ticket_id = %msg.ticket_id, "Ticket lock held — the run starting on the ticket reads the comments"); + return false; + } + let message = WorkerMessage::Ticket(fresh_run(msg, direction, answers)); + send(state, &state.config.ticket_queue_url, &message).await +} + +/// The ticket's message for a new run that takes up the comments: the +/// same ticket, none of the ended run's own state. +pub fn fresh_run(msg: &TicketMessage, direction: &str, answers: &[Answer]) -> TicketMessage { + let mut all = msg.answers.clone(); + common::run_questions::merge(&mut all, answers); + TicketMessage { + team_id: msg.team_id.clone(), + installation_id: msg.installation_id, + source: msg.source.clone(), + ticket_id: msg.ticket_id.clone(), + title: msg.title.clone(), + body: msg.body.clone(), + repo_owner: msg.repo_owner.clone(), + repo_name: msg.repo_name.clone(), + issue_number: msg.issue_number, + sender: msg.sender.clone(), + requester: msg.requester.clone(), + base_branch: msg.base_branch.clone(), + image_attachments: msg.image_attachments.clone(), + ticket_type: msg.ticket_type.clone(), + person_direction: Some(direction.to_string()), + answers: all, + ..Default::default() + } +} + +async fn send(state: &WorkerState, queue: &str, message: &WorkerMessage) -> bool { + if queue.is_empty() { + warn!("No queue configured for the ticket comments' work"); + return false; + } + let body = match serde_json::to_string(message) { + Ok(b) => b, + Err(e) => { + warn!(error = %e, "Could not serialize the ticket comments' work"); + return false; + } + }; + match state + .sqs + .send_message() + .queue_url(queue) + .message_body(body) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(error = %aws_sdk_sqs::error::DisplayErrorContext(&e), "Could not send the ticket comments' work"); + false + } + } +} + +/// CoderHelm's one comment on the ticket about what it did with the +/// comments it read. Best effort. +async fn say_on_ticket( + state: &WorkerState, + t: &Ticket<'_>, + facts: &RunFacts, + open: &[Comment], + reply: &str, +) { + let source = open.first().map(|c| c.source).unwrap_or_default(); + match source { + Source::Jira => { + if let Err(e) = super::post_jira_comment( + state, + t.team_id, + t.ticket_id, + reply, + "info", + "Comments read", + ) + .await + { + warn!(ticket_id = t.ticket_id, error = %e, "Could not say on the ticket what was done with its comments"); + } + } + Source::Github => { + let Some((owner, name)) = facts.repo.split_once('/') else { + return; + }; + if facts.issue_number == 0 { + return; + } + let github = match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + t.installation_id, + &state.http, + ) { + Ok(g) => g, + Err(e) => { + warn!(ticket_id = t.ticket_id, error = %e, "No GitHub client to reply on the issue"); + return; + } + }; + if let Err(e) = github + .create_issue_comment(owner, name, facts.issue_number, reply) + .await + { + warn!(ticket_id = t.ticket_id, error = %e, "Could not say on the issue what was done with its comments"); + } + } + } +} + +/// The run's own step reads its ticket's open comments, before it spends +/// more work. +pub async fn at_boundary( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + usage: &mut TokenUsage, +) -> Read { + if !reads_comments(msg) { + return Read::default(); + } + read( + state, + &Ticket { + team_id: &msg.team_id, + ticket_id: &msg.ticket_id, + run_id, + installation_id: msg.installation_id, + }, + true, + None, + usage, + ) + .await +} + +/// A step ended: what the run kept for its pull request becomes a round +/// on it, and a run that ended some other way hands its open comments to +/// what comes next. +pub async fn after_step(state: &WorkerState, msg: &TicketMessage, run_id: &str) { + if !reads_comments(msg) { + return; + } + let mut usage = TokenUsage::default(); + read( + state, + &Ticket { + team_id: &msg.team_id, + ticket_id: &msg.ticket_id, + run_id, + installation_id: msg.installation_id, + }, + false, + Some(msg), + &mut usage, + ) + .await; +} + +/// A comment just arrived for the ticket's run (or for a run that has +/// ended): read the ticket's open comments now. +pub async fn on_comment(state: &WorkerState, msg: &JiraCommentMessage) { + if msg.run_id.is_empty() || msg.ticket_id.is_empty() { + return; + } + let mut usage = TokenUsage::default(); + read( + state, + &Ticket { + team_id: &msg.team_id, + ticket_id: &msg.ticket_id, + run_id: &msg.run_id, + installation_id: msg.installation_id, + }, + false, + None, + &mut usage, + ) + .await; +} + +/// A round on the run's pull request ended (feedback, a CI or review fix): +/// comments written on the ticket while it worked are read now. +pub async fn after_round(state: &WorkerState, team_id: &str, run_id: &str) { + let item = 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("ticket_id, installation_id") + .send() + .await + .ok() + .and_then(|o| o.item); + let Some(item) = item else { + return; + }; + let ticket_id = item + .get("ticket_id") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + if ticket_id.is_empty() { + return; + } + let installation_id = item + .get("installation_id") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + let mut usage = TokenUsage::default(); + read( + state, + &Ticket { + team_id, + ticket_id: &ticket_id, + run_id, + installation_id, + }, + false, + None, + &mut usage, + ) + .await; +} + +/// Tickets people comment on: a Jira ticket or a GitHub issue. An alert +/// has no thread. +fn reads_comments(msg: &TicketMessage) -> bool { + !msg.ticket_id.is_empty() && matches!(msg.source, TicketSource::Jira | TicketSource::Github) +} + +/// What people already wrote on a GitHub issue, kept when a run starts on +/// it so the run reads it before it plans (a Jira ticket's comments come +/// with its event). Comments already kept are left as they are. +pub async fn keep_existing_github(state: &WorkerState, msg: &TicketMessage, github: &GitHubClient) { + if !matches!(msg.source, TicketSource::Github) + || msg.issue_number == 0 + || msg.same_run() + || msg.repo_owner.is_empty() + { + return; + } + let comments = match github + .list_issue_comments(&msg.repo_owner, &msg.repo_name, msg.issue_number) + .await + { + Ok(c) => c, + Err(e) => { + warn!(ticket_id = %msg.ticket_id, error = %e, "Could not read the issue's comments"); + return; + } + }; + let store = store(state); + for c in existing_github(&msg.ticket_id, &comments) { + if let Err(e) = store.record(&msg.team_id, &c).await { + warn!(ticket_id = %msg.ticket_id, error = %e, "Could not keep an issue comment"); + } + } +} + +/// Most comments read from an issue when a run starts on it (the newest). +pub const MAX_EXISTING: usize = 20; + +/// The people's comments on an issue as kept for a run that starts on it: +/// context (no run was working when they were written), newest +/// [`MAX_EXISTING`], oldest first. +pub fn existing_github(ticket_id: &str, comments: &[serde_json::Value]) -> Vec { + let people: Vec = comments + .iter() + .filter_map(|c| { + let author = c["user"]["login"].as_str().unwrap_or(""); + let kind = c["user"]["type"].as_str().unwrap_or(""); + let text = c["body"].as_str().unwrap_or(""); + let id = c["id"].as_u64()?; + if text.trim().is_empty() || !tc::is_person(Source::Github, author, kind, text) { + return None; + } + Some(Comment { + ticket_id: ticket_id.to_string(), + source: Source::Github, + comment_id: id.to_string(), + author: author.to_string(), + text: common::truncate_str(text.trim(), tc::MAX_TEXT_CHARS).to_string(), + at: c["created_at"].as_str().unwrap_or("").to_string(), + ..Default::default() + }) + }) + .collect(); + let skip = people.len().saturating_sub(MAX_EXISTING); + people.into_iter().skip(skip).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use common::ticket_comments::{Class, Memory, State}; + use serde_json::json; + + fn comment(id: &str, text: &str, class: Class) -> Comment { + Comment { + ticket_id: "ABC-1".into(), + source: Source::Jira, + comment_id: id.into(), + author: "Pat Doe".into(), + text: text.into(), + at: format!("2026-01-01T00:00:0{id}Z"), + run_id: "01RUN".into(), + class: Some(class), + question: if class == Class::Answer { + "Which environments get the flag?".into() + } else { + String::new() + }, + ..Default::default() + } + } + + async fn settled_at(stage: Stage, comments: &[Comment]) -> (Memory, Settled) { + let store = Memory::default(); + for c in comments { + store.record("TEAM#1", c).await.unwrap(); + } + let open = tc::open(store.all("TEAM#1", "ABC-1")); + let s = tc::settle_open(&store, "TEAM#1", "01RUN", &open, stage, Some("PR")).await; + (store, s) + } + + fn burst() -> Vec { + vec![ + comment("1", "Production only.", Class::Answer), + comment("2", "Also rename the flag.", Class::Instruction), + comment("3", "Thanks all", Class::NotForCoderhelm), + ] + } + + #[tokio::test] + async fn while_planning_answers_and_instructions_go_into_the_plan() { + let (store, s) = settled_at(Stage::Planning, &burst()).await; + let fx = effects(&s, None); + assert_eq!(fx.folded.len(), 2); + assert_eq!(fx.folded[0].question, "Which environments get the flag?"); + assert_eq!(fx.folded[0].answer, "Production only."); + assert_eq!(fx.folded[1].question, tc::COMMENT_QUESTION); + // The planner reads them word for word, as settled. + let note = common::run_questions::answers_note(&fx.folded); + assert!(note.contains("Answer from Pat Doe: Production only.")); + assert!(note.contains("Also rename the flag.")); + // No round, no restart, no stop, nothing more said on the ticket. + assert_eq!(fx.round, None); + assert_eq!(fx.restart, None); + assert_eq!(fx.stop_by, None); + assert_eq!(fx.reply, None); + // Kept on the ticket for later runs; the chatter isn't. + assert_eq!(fx.ticket_notes.len(), 2); + // The run page says what was done with each of the three. + assert_eq!(fx.run_notes.len(), 3); + assert!(fx.run_notes[0].contains("folded into the plan")); + assert!(fx.run_notes[2].contains("not for CoderHelm: left as it is")); + assert!(tc::open(store.all("TEAM#1", "ABC-1")).is_empty()); + } + + #[tokio::test] + async fn while_building_or_reviewing_they_wait_for_the_pull_request() { + for stage in [Stage::Building, Stage::Reviewing] { + let (store, s) = settled_at(stage, &burst()).await; + let fx = effects(&s, None); + assert!(fx.folded.is_empty(), "the plan is final at {stage:?}"); + assert_eq!(fx.round, None, "no round before the step ends"); + assert_eq!(fx.reply, None); + assert!(fx.run_notes[0].contains("applied as a round on the pull request")); + let open = tc::open(store.all("TEAM#1", "ABC-1")); + assert_eq!(open.len(), 2); + assert!(open.iter().all(|c| c.state == State::Deferred)); + + // A later boundary of the same step leaves them be. + let again = tc::settle_open(&store, "TEAM#1", "01RUN", &open, stage, None).await; + assert!(again.done.is_empty()); + + // The step ends with the pull request open: one round for both, + // said once on the ticket. + let done = Stage::Finished { + pr_open: true, + waiting: false, + }; + let end = tc::settle_open(&store, "TEAM#1", "01RUN", &open, done, Some("PR#12")).await; + let fx = effects(&end, Some("PR#12")); + let round = fx.round.expect("a round on the open pull request"); + assert!(round.contains("Answer: Production only.")); + assert!(round.contains("Also rename the flag.")); + let reply = fx.reply.expect("said on the ticket"); + assert!(reply.contains("on PR#12")); + assert!(tc::open(store.all("TEAM#1", "ABC-1")).is_empty()); + } + } + + #[tokio::test] + async fn between_steps_they_stay_for_the_next_step() { + let (store, s) = settled_at(Stage::BetweenSteps, &burst()).await; + // Only the chatter is settled (left alone); the rest wait. + assert_eq!(s.done.len(), 1); + assert_eq!(s.done[0].0, Action::Leave); + let open = tc::open(store.all("TEAM#1", "ABC-1")); + assert_eq!(open.len(), 2); + assert!(open.iter().all(|c| c.state == State::Pending)); + // The fresh step reads them at its first boundary. + let next = tc::settle_open(&store, "TEAM#1", "01RUN", &open, Stage::Building, None).await; + assert_eq!(next.with(Action::Defer).len(), 2); + } + + #[tokio::test] + async fn a_finished_run_gets_a_round_and_a_waiting_one_starts_again() { + let done = Stage::Finished { + pr_open: true, + waiting: false, + }; + let (_, s) = settled_at(done, &burst()).await; + let fx = effects(&s, Some("PR#12")); + assert!(fx.round.is_some()); + assert_eq!(fx.restart, None); + + // The run ended waiting on a person (or failed) with no pull + // request: the ticket starts again with what was written. + let waiting = Stage::Finished { + pr_open: false, + waiting: true, + }; + let (_, s) = settled_at(waiting, &burst()).await; + let fx = effects(&s, None); + assert_eq!(fx.round, None); + let (direction, answers) = fx.restart.expect("the ticket starts again"); + assert!(direction.contains("Pat Doe: Production only.")); + assert_eq!(answers.len(), 2); + let msg = TicketMessage { + team_id: "TEAM#1".into(), + ticket_id: "ABC-1".into(), + title: "Add the flag".into(), + body: "b".into(), + source: TicketSource::Jira, + continuation: 4, + continuation_run_id: Some("01RUN".into()), + resume_from: Some("01OLD".into()), + ..Default::default() + }; + let fresh = fresh_run(&msg, &direction, &answers); + assert_eq!(fresh.ticket_id, "ABC-1"); + assert_eq!(fresh.continuation, 0, "a new run, not the ended one"); + assert_eq!(fresh.continuation_run_id, None); + assert_eq!(fresh.resume_from, None); + assert_eq!(fresh.person_direction.as_deref(), Some(direction.as_str())); + assert_eq!(fresh.answers.len(), 2); + } + + #[tokio::test] + async fn a_cancelled_run_keeps_them_on_the_ticket_for_the_next_run() { + let (store, s) = settled_at(Stage::Cancelled, &burst()).await; + let fx = effects(&s, None); + assert_eq!(fx.round, None); + assert_eq!(fx.restart, None, "a run a person stopped never restarts"); + assert_eq!(fx.reply, None); + assert_eq!(fx.ticket_notes.len(), 2); + assert!(fx.run_notes[0].contains("kept on the ticket's record")); + assert!(tc::open(store.all("TEAM#1", "ABC-1")).is_empty()); + } + + #[tokio::test] + async fn a_stop_ends_the_run_and_is_said_on_the_ticket() { + for stage in [ + Stage::Planning, + Stage::Building, + Stage::Reviewing, + Stage::BetweenSteps, + ] { + let mut all = burst(); + all.push(comment("4", "Stop, we are dropping this.", Class::Stop)); + let (store, s) = settled_at(stage, &all).await; + let fx = effects(&s, None); + assert_eq!(fx.stop_by.as_deref(), Some("Pat Doe"), "at {stage:?}"); + assert!(fx.folded.is_empty() && fx.round.is_none() && fx.restart.is_none()); + assert!(fx.reply.unwrap().contains("I stopped the run")); + // The other comments stay open for the next run on the ticket. + assert_eq!(tc::open(store.all("TEAM#1", "ABC-1")).len(), 3); + } + } + + #[test] + fn a_run_gone_quiet_is_not_working() { + let now = chrono::Utc::now(); + let ago = |h: i64| (now - chrono::Duration::hours(h)).to_rfc3339(); + assert!(!gone_quiet("running", &ago(0), now)); + assert!(gone_quiet("running", &ago(3), now)); + assert!(gone_quiet("queued", &ago(2), now)); + assert!(!gone_quiet("awaiting_ci", &ago(20), now)); + assert!(gone_quiet("awaiting_ci", &ago(27), now)); + assert!(!gone_quiet("completed", &ago(100), now)); + assert!(!gone_quiet("running", "", now)); + } + + #[test] + fn an_issues_existing_comments_are_context_for_the_run_that_starts() { + let comments = vec![ + json!({"id": 1, "user": {"login": "pat-doe", "type": "User"}, + "body": "Production only.", "created_at": "2026-01-01T00:00:00Z"}), + json!({"id": 2, "user": {"login": "coderhelm[bot]", "type": "Bot"}, + "body": "Questions only a person can answer"}), + json!({"id": 3, "user": {"login": "ci-reporter[bot]", "type": "Bot"}, "body": "Coverage 81%"}), + json!({"id": 4, "user": {"login": "sam-roe", "type": "User"}, "body": " "}), + json!({"id": 5, "user": {"login": "sam-roe", "type": "User"}, "body": "Stop for now."}), + ]; + let kept = existing_github("GH-12", &comments); + assert_eq!(kept.len(), 2); + assert_eq!(kept[0].comment_id, "1"); + assert_eq!(kept[0].source, Source::Github); + // Written before the run started: it can never stop the run. + assert!(kept.iter().all(|c| !c.during_run())); + assert_eq!( + tc::decide(Class::Stop, Stage::Planning, kept[1].during_run(), false), + Action::Fold + ); + let many: Vec = (0..60) + .map(|i| json!({"id": i, "user": {"login": "pat-doe", "type": "User"}, "body": "x"})) + .collect(); + let kept = existing_github("GH-12", &many); + assert_eq!(kept.len(), MAX_EXISTING); + assert_eq!(kept.last().unwrap().comment_id, "59"); + } + + #[test] + fn the_pipeline_reads_comments_at_its_boundaries_and_when_a_step_ends() { + let src = include_str!("mod.rs"); + let start = src.find("\nasync fn run_passes(").unwrap(); + let end = start + src[start..].find("\nasync fn hand_off_at(").unwrap(); + let run = &src[start..end]; + assert!( + run.matches("read_ticket_comments(state, msg, run_id, usage)") + .count() + >= 5, + "the run start and the plan, implement, test and pull request boundaries" + ); + assert!(run.contains("ticket_comments::keep_existing_github(")); + let orch = &src[src.find("\npub async fn orchestrate_ticket(").unwrap()..start]; + assert!(orch.contains("ticket_comments::after_step(")); + // The run's questions are kept for reading the answers. + let report = &src[src.find("\nasync fn report_questions(").unwrap()..]; + assert!(report.contains("ticket_comments::keep_asked(")); + // A round on the pull request reads them when it ends. + let main = include_str!("../main.rs"); + assert_eq!(main.matches("ticket_comments::after_round(").count(), 2); + // The comment reader is told at once, before anything else. + let jc = include_str!("jira_comment.rs"); + let run_fn = &jc[jc.find("\npub async fn run(").unwrap()..]; + assert!( + run_fn.find("ticket_comments::on_comment(").unwrap() + < run_fn.find("classify(state").unwrap() + ); + } +} From 5e83b7323d0a97e460aa183ad7f4e1c3038c2ac0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 18:54:11 -0500 Subject: [PATCH 2/3] Comments are stored only for tickets CoderHelm works, and for two weeks A comment written while no run works was stored for every ticket in a connected Jira project, for 30 days. It is now stored only when the ticket carries the team's trigger label or is assigned to CoderHelm when the comment is written (the rule that starts a run). Comments on every other ticket are never stored: when a run starts there, the event that starts it brings the ticket's comments, and a GitHub run reads the issue's. Records expire after 14 days for a comment written while a run worked and 7 days for one written before a run. Nothing reads a comment after it is acted on; the record only guards against a repeated delivery and keeps a comment nobody read for what comes next. A Jira app older than the version that sends comments with the ticket leaves CoderHelm no way to read them: the gateway notes on the ticket's record whether the event carried comments, and the run says on its page when comments written before it started were not read. The Jira app sends at most 200,000 characters of comment bodies with an event, leaving out the oldest whole. Its manifest is unchanged: no new scope or permission. --- coderhelm-jira/src/comments.js | 25 ++- coderhelm-jira/test/comments.test.js | 17 +- services/common/src/ticket_comments.rs | 75 +++++++- services/gateway/src/routes/jira_webhook.rs | 162 +++++++++++++----- .../gateway/src/routes/ticket_comments.rs | 153 +++++++++++++++-- services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/ticket_comments.rs | 33 ++++ 7 files changed, 399 insertions(+), 67 deletions(-) diff --git a/coderhelm-jira/src/comments.js b/coderhelm-jira/src/comments.js index b5b48ab7d..04d127389 100644 --- a/coderhelm-jira/src/comments.js +++ b/coderhelm-jira/src/comments.js @@ -11,6 +11,14 @@ /** The most comments sent with one ticket event: the newest ones. */ const MAX_COMMENTS = 20; +/** + * The most characters of comment bodies sent with one ticket event. The + * event also carries the ticket's images, and the whole request has to stay + * well inside what the gateway accepts. When the newest comments are longer + * than this in all, the oldest of them are left out. + */ +const MAX_TOTAL_CHARS = 200000; + /** * @param {object} fields The ticket's fields, as the issue REST API returns them. * @returns {{id: string, author: {displayName: string, accountType: string}, body: string}[]} @@ -18,10 +26,8 @@ const MAX_COMMENTS = 20; function existingComments(fields) { const all = (fields && fields.comment && fields.comment.comments) || []; if (!Array.isArray(all)) return []; - return all - .filter((c) => c && c.id && c.body) - .slice(-MAX_COMMENTS) - .map((c) => ({ + const newest = all.filter((c) => c && c.id && c.body).slice(-MAX_COMMENTS); + const sent = newest.map((c) => ({ id: String(c.id), author: { displayName: (c.author && c.author.displayName) || "", @@ -30,6 +36,15 @@ function existingComments(fields) { // A comment body is a document (JSON); the gateway reads its words. body: typeof c.body === "string" ? c.body : JSON.stringify(c.body), })); + // Keep the newest comments that fit; a body is never cut in the middle + // (it is a JSON document, and half of one cannot be read). + let total = 0; + let from = sent.length; + while (from > 0 && total + sent[from - 1].body.length <= MAX_TOTAL_CHARS) { + total += sent[from - 1].body.length; + from -= 1; + } + return sent.slice(from); } -module.exports = { existingComments, MAX_COMMENTS }; +module.exports = { existingComments, MAX_COMMENTS, MAX_TOTAL_CHARS }; diff --git a/coderhelm-jira/test/comments.test.js b/coderhelm-jira/test/comments.test.js index 8588c1324..d1bb76a9e 100644 --- a/coderhelm-jira/test/comments.test.js +++ b/coderhelm-jira/test/comments.test.js @@ -1,6 +1,6 @@ const { test } = require("node:test"); const assert = require("node:assert/strict"); -const { existingComments, MAX_COMMENTS } = require("../src/comments"); +const { existingComments, MAX_COMMENTS, MAX_TOTAL_CHARS } = require("../src/comments"); const doc = (text) => ({ type: "doc", version: 1, content: [{ type: "paragraph", content: [{ type: "text", text }] }] }); @@ -38,3 +38,18 @@ test("only the newest comments are sent", () => { assert.equal(got[got.length - 1].id, "49"); assert.deepEqual(got[0].author, { displayName: "", accountType: "" }); }); + +test("very long comments never make the event too large: the oldest are left out whole", () => { + const big = "x".repeat(MAX_TOTAL_CHARS / 2 + 10); + const comments = [ + { id: "1", author: {}, body: big }, + { id: "2", author: {}, body: big }, + { id: "3", author: {}, body: "short" }, + ]; + const got = existingComments({ comment: { comments } }); + assert.deepEqual(got.map((c) => c.id), ["2", "3"]); + assert.equal(got[0].body.length, big.length); + // One comment longer than the whole allowance is left out, not cut. + const huge = [{ id: "9", author: {}, body: "y".repeat(MAX_TOTAL_CHARS + 1) }]; + assert.deepEqual(existingComments({ comment: { comments: huge } }), []); +}); diff --git a/services/common/src/ticket_comments.rs b/services/common/src/ticket_comments.rs index 9dcce83a0..9613ba5fa 100644 --- a/services/common/src/ticket_comments.rs +++ b/services/common/src/ticket_comments.rs @@ -37,11 +37,19 @@ use std::collections::BTreeMap; /// The settings-table sort key prefix of a ticket's comments. pub const SK_PREFIX: &str = "TICKETCOMMENT#"; -/// Days a comment's record is kept. -pub const KEEP_DAYS: i64 = 90; -/// Days a comment written while no run worked on the ticket is kept: it is -/// only context for a run that starts soon after. -pub const KEEP_DAYS_NO_RUN: i64 = 30; +/// Days a comment written while a run worked is kept. Nothing reads a +/// comment after it is acted on; the record is kept only so that the same +/// comment delivered again is not taken twice, and so that one nobody read +/// (its worker stopped, or its round could not be sent) is still there for +/// what comes next. A run and its wait for CI end within 26 hours, and the +/// rounds on its open pull request follow within days: two weeks covers +/// them with room to spare. +pub const KEEP_DAYS: i64 = 14; +/// Days a comment written before a run is kept. It is stored only for a +/// ticket CoderHelm is already set to work (see the gateway), so the run +/// that reads it starts within minutes; a week covers a run held back by a +/// usage limit or a ticket lock. +pub const KEEP_DAYS_NO_RUN: i64 = 7; /// How long a comment's record is kept, in days. pub fn keep_days(c: &Comment) -> i64 { @@ -64,6 +72,35 @@ pub const FIELD_STOPPED_TO_ASK: &str = crate::run_questions::FIELD_QUESTIONS; /// The question an instruction (not an answer to a question) is kept under /// when it is folded into the plan. pub const COMMENT_QUESTION: &str = "A person's comment on the ticket"; +/// Ticket-record field (`ticket_state::sk`): whether the event that last +/// started a run on the ticket carried the ticket's existing comments +/// ([`EVENT_COMMENTS_SENT`] or [`EVENT_COMMENTS_NOT_SENT`]). A Jira app +/// older than the version that sends them leaves a run without what +/// people wrote before it started, and the run says so. +pub const FIELD_EVENT_COMMENTS: &str = "event_comments"; +pub const EVENT_COMMENTS_SENT: &str = "sent"; +pub const EVENT_COMMENTS_NOT_SENT: &str = "not_sent"; + +/// Whether a pre-run comment is stored at all. Only for a ticket +/// CoderHelm has something to do with: one it already ran on, or one +/// that carries the team's trigger label or is assigned to CoderHelm +/// when the comment is written. Comments on every other ticket are never +/// stored: when a run starts there, the event that starts it brings the +/// ticket's comments (Jira), or the run reads them from the issue +/// (GitHub). +pub fn stores_before_run(has_run: bool, has_trigger_label: bool, assigned: bool) -> bool { + has_run || has_trigger_label || assigned +} + +/// What a run on a Jira ticket says when the event that started it +/// carried no comments: it did not read what people wrote before it +/// started. `None` when the comments were sent, or nothing is known. +pub fn unread_earlier_note(marker: Option<&str>) -> Option<&'static str> { + (marker == Some(EVENT_COMMENTS_NOT_SENT)).then_some( + "Comments written on the ticket before this run started were not read: the event that started the run carried none (this site's Jira app is a version that does not send them), and CoderHelm has no other access to them. The run works from the ticket's title and description; comments written from now on are read. Updating the Jira app on the site sends earlier comments with the next ticket.", + ) +} + /// How CoderHelm's acknowledgement on a ticket starts. A comment that /// starts this way is its own, whoever the tracker says wrote it. pub const ACK_OPENING: &str = "Got it."; @@ -1389,6 +1426,34 @@ mod tests { ); } + #[test] + fn a_comment_on_a_ticket_coderhelm_has_nothing_to_do_with_is_never_stored() { + // No run on record, no trigger label, not assigned to CoderHelm. + assert!(!stores_before_run(false, false, false)); + assert!(stores_before_run(true, false, false)); + assert!(stores_before_run(false, true, false)); + assert!(stores_before_run(false, false, true)); + } + + #[test] + fn records_are_kept_two_weeks_and_a_week_before_a_run() { + let during = comment("1", "x"); + let mut before = comment("2", "x"); + before.run_id.clear(); + assert_eq!(keep_days(&during), 14); + assert_eq!(keep_days(&before), 7); + } + + #[test] + fn a_run_says_when_earlier_comments_were_not_read() { + let note = unread_earlier_note(Some(EVENT_COMMENTS_NOT_SENT)).unwrap(); + assert!(note.contains("before this run started were not read")); + assert_eq!(unread_earlier_note(Some(EVENT_COMMENTS_SENT)), None); + // Nothing known about the event (a retry from the dashboard on a + // ticket no event marked): nothing is claimed. + assert_eq!(unread_earlier_note(None), None); + } + #[test] fn open_comments_are_oldest_first_and_bounded() { let mut all: Vec = (0..30).map(|i| comment(&format!("{i}"), "x")).collect(); diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index 40130a007..eb7f72f2c 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -308,6 +308,75 @@ pub async fn process_relayed( process_jira_payload(state, team_id, installation_id, payload).await } +/// The labels on a Jira issue (plain strings, or objects with a `name`). +fn labels_of(issue: &Value) -> Vec { + issue + .get("fields") + .and_then(|f| f.get("labels")) + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|v| { + v.as_str().map(|s| s.to_string()).or_else(|| { + v.get("name") + .and_then(|n| n.as_str()) + .map(|s| s.to_string()) + }) + }) + .collect() + }) + .unwrap_or_default() +} + +/// Who a Jira issue is assigned to, as the site shows them. +fn assignee_of(issue: &Value) -> &str { + issue + .get("fields") + .and_then(|f| f.get("assignee")) + .and_then(|a| { + a.get("displayName") + .and_then(|v| v.as_str()) + .or_else(|| a.get("name").and_then(|v| v.as_str())) + }) + .unwrap_or("") +} + +/// Whether a Jira issue is CoderHelm's to work: (it carries the team's +/// trigger label, or one that starts with `