From 53d63a9394ee57e9b26f082ef556198a77617b8d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 10:34:16 -0400 Subject: [PATCH 1/2] Runs that stop to ask keep their questions; answer them from CoderHelm A run that stops as needs_input now stores what it asked on its record: each question in plain words, why it blocks the change, and candidate answers when the planner found any, plus a link to the comment it posted on the ticket or issue. The planner is asked for that shape. POST /api/runs/{run_id}/answer takes answers for those questions (members and up), claims the run in one conditional write, starts the ticket again with the answers on the message, and posts them on the ticket as ' answered in CoderHelm:'. Triage and the planner read the answers word for word; a plan that asks an answered question again is sent back once, and answered questions are never stored or posted again. The run API returns questions, questions_url, answers, answers_url and continued_run_id; docs/api/openapi.json is regenerated. --- docs/api/openapi.json | 393 +++++++- services/common/src/lib.rs | 3 + services/common/src/messages.rs | 12 + services/common/src/run_questions.rs | 711 +++++++++++++++ services/gateway/src/main.rs | 1 + services/gateway/src/openapi.rs | 2 + services/gateway/src/permissions.rs | 1 + services/gateway/src/routes/api.rs | 256 +++++- services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/run_answer.rs | 905 +++++++++++++++++++ services/gateway/src/routes/run_close.rs | 2 +- services/worker/src/models.rs | 2 + services/worker/src/passes/e2e.rs | 4 + services/worker/src/passes/feedback.rs | 4 + services/worker/src/passes/log_autofix.rs | 2 + services/worker/src/passes/mod.rs | 507 +++++++++-- services/worker/src/passes/plan.rs | 59 +- services/worker/src/passes/resume.rs | 2 + services/worker/src/passes/ticket_history.rs | 24 + services/worker/src/passes/triage.rs | 9 +- 20 files changed, 2769 insertions(+), 131 deletions(-) create mode 100644 services/common/src/run_questions.rs create mode 100644 services/gateway/src/routes/run_answer.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 11c587bf1..eaefaa47e 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -1,6 +1,64 @@ { "components": { "schemas": { + "AnswerRun": { + "description": "Answers to a run's questions.", + "properties": { + "answers": { + "description": "One entry per question answered. Questions left out (or blank) stay\nopen; at least one needs an answer.", + "items": { + "$ref": "#/components/schemas/GivenAnswer" + }, + "type": "array" + } + }, + "required": [ + "answers" + ], + "type": "object" + }, + "AnswerRunResult": { + "description": "What answering did.", + "properties": { + "comment_url": { + "description": "The reply on the ticket or issue, when its address is known.", + "examples": [ + "https://github.com/acme/web/issues/42#issuecomment-2211" + ], + "type": [ + "string", + "null" + ] + }, + "posted": { + "description": "Whether the answers were posted on the ticket or issue.", + "examples": [ + true + ], + "type": "boolean" + }, + "run_id": { + "description": "The id of the run that continues the work. It shows in\n`GET /api/runs/{run_id}` once it starts, within seconds.", + "examples": [ + "01JB8Z3N5Q7S9V1X3Z5B7D9F1H" + ], + "type": "string" + }, + "status": { + "description": "`continuing`: the ticket is queued again with the answers.", + "examples": [ + "continuing" + ], + "type": "string" + } + }, + "required": [ + "status", + "run_id", + "posted" + ], + "type": "object" + }, "Backfill": { "description": "Whether the records from before rollups existed are all counted yet.", "properties": { @@ -777,6 +835,30 @@ ], "type": "object" }, + "GivenAnswer": { + "description": "The answer to one question.", + "properties": { + "answer": { + "description": "The answer, in plain words. At most 4000 characters.", + "examples": [ + "Production only. Staging keeps the old limit." + ], + "type": "string" + }, + "question_id": { + "description": "The question's `id` from the run's `questions`.", + "examples": [ + "q1" + ], + "type": "string" + } + }, + "required": [ + "question_id", + "answer" + ], + "type": "object" + }, "JiraComment": { "description": "The comment in a Jira comment event.", "properties": { @@ -2578,6 +2660,23 @@ "Run": { "description": "One run, in full.", "properties": { + "answers": { + "description": "Answers people gave to its questions in CoderHelm.", + "items": { + "$ref": "#/components/schemas/RunAnswer" + }, + "type": "array" + }, + "answers_url": { + "description": "The reply with those answers on the ticket or issue, when known.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, "applied_standards": { "description": "The team standards the run was given in full (\"always apply\").", "examples": [ @@ -2673,6 +2772,16 @@ "null" ] }, + "continued_run_id": { + "description": "The run that picked the answers up and continued the work.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, "cost_usd": { "description": "What the run cost in model usage, in US dollars, as recorded.", "examples": [ @@ -2900,6 +3009,23 @@ "null" ] }, + "questions": { + "description": "What the run asked when it stopped as `needs_input`, one question\neach. Answer them with `POST /api/runs/{run_id}/answer`. Empty when\nit asked nothing it can take answers for here.", + "items": { + "$ref": "#/components/schemas/RunQuestion" + }, + "type": "array" + }, + "questions_url": { + "description": "The comment with the questions on the ticket or issue, when known.", + "examples": [ + "https://github.com/acme/web/issues/42#issuecomment-2210" + ], + "type": [ + "string", + "null" + ] + }, "repo": { "description": "The repository, `owner/name`.", "examples": [ @@ -3004,7 +3130,9 @@ "cache_write_tokens", "cost_usd", "applied_standards", - "sign_in_prompts" + "sign_in_prompts", + "questions", + "answers" ], "type": "object" }, @@ -3024,6 +3152,54 @@ ], "type": "object" }, + "RunAnswer": { + "description": "An answer given in CoderHelm to a run's question.", + "properties": { + "answer": { + "description": "The answer, as written.", + "examples": [ + "Production only." + ], + "type": "string" + }, + "answered_at": { + "description": "When (RFC 3339).", + "examples": [ + "2026-10-22T14:20:00Z" + ], + "type": "string" + }, + "author": { + "description": "Who answered, as the ticket shows them.", + "examples": [ + "Pat Doe" + ], + "type": "string" + }, + "question": { + "description": "That question, as asked.", + "examples": [ + "Which environments get the new rate limit?" + ], + "type": "string" + }, + "question_id": { + "description": "The question it answers.", + "examples": [ + "q1" + ], + "type": "string" + } + }, + "required": [ + "question_id", + "question", + "answer", + "author", + "answered_at" + ], + "type": "object" + }, "RunNote": { "description": "A note the run wrote while it worked.", "properties": { @@ -3076,6 +3252,54 @@ }, "type": "object" }, + "RunQuestion": { + "description": "A question a run asked a person.", + "properties": { + "id": { + "description": "The question's id within the run (`q1`, `q2`, ...).", + "examples": [ + "q1" + ], + "type": "string" + }, + "question": { + "description": "The question, in plain words.", + "examples": [ + "Which environments get the new rate limit?" + ], + "type": "string" + }, + "suggestions": { + "description": "Candidate answers the run found in the code or the data.", + "examples": [ + [ + "Production only", + "Every environment" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "why": { + "description": "Why it matters: what it blocks.", + "examples": [ + "config/limits.yml holds one value per environment." + ], + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "question", + "suggestions" + ], + "type": "object" + }, "RunSummary": { "description": "One run in a list.", "properties": { @@ -5804,6 +6028,173 @@ ] } }, + "/api/runs/{run_id}/answer": { + "post": { + "description": "Answers the questions a `needs_input` run asked (its `questions`) and continues the work: the answers are posted on the ticket or issue as a reply from you, kept on the run, and the ticket starts again as a new run whose plan reads them word for word. The old run becomes `retried` with `continued_run_id` set. A run that isn't `needs_input` any more (answered, retried or closed meanwhile) is refused with `409`.", + "operationId": "answerRun", + "parameters": [ + { + "description": "The run's id.", + "example": "01JB8X6F4M2C9QZ3T7V5W1K0HA", + "in": "path", + "name": "run_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AnswerRun" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AnswerRunResult" + } + } + }, + "description": "The work continues with the answers.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No answer written, an answer too long, or a question the run didn't ask." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No run with this id in the team." + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The run isn't waiting for an answer, or asked nothing to answer here." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "runs" + ] + } + ], + "summary": "Answer a run's questions", + "tags": [ + "Runs" + ] + } + }, "/api/runs/{run_id}/cancel": { "post": { "description": "Stops a run that is `running`. The run becomes `cancelled`, and the work it has not done yet is dropped; a pull request it already opened stays open. A run in any other state answers `400`, so cancelling twice is harmless.", diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 975066090..6478cf18b 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -101,6 +101,9 @@ pub mod review_stats; pub mod rewards; /// The one way a run is marked failed: always with a reason and a pass. pub mod run_fail; +/// The questions a run asks when it needs a person's answer, and the +/// answers people give in CoderHelm. +pub mod run_questions; /// Run statuses; which ones a person set; closing and reopening a run. pub mod run_status; #[cfg(test)] diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 5b44076c7..68178b1ef 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -738,6 +738,16 @@ pub struct TicketMessage { /// "author: words". The planner's trace checks then inform, not block. #[serde(default, skip_serializing_if = "Option::is_none")] pub person_direction: Option, + /// Answers people gave in CoderHelm to an earlier run's questions on + /// this ticket. Triage and the planner read them word for word, and the + /// planner doesn't ask them again (see `run_questions`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub answers: Vec, + /// The id the new run takes, when whoever sent the ticket named it + /// first (answering on the dashboard links the asking run to the run + /// that picks the answers up). A continuation keeps its own id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub new_run_id: Option, } fn default_branch() -> String { @@ -770,6 +780,8 @@ impl Default for TicketMessage { plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, } } } diff --git a/services/common/src/run_questions.rs b/services/common/src/run_questions.rs new file mode 100644 index 000000000..fab42d8c9 --- /dev/null +++ b/services/common/src/run_questions.rs @@ -0,0 +1,711 @@ +//! The questions a run asks when it stops as `needs_input`, and the answers +//! people give to them in CoderHelm. +//! +//! The worker stores what it asked on the run (`questions`, see [`Asked`]) +//! next to the comment it posted on the ticket. The gateway takes answers +//! for those questions, posts them as a reply on the ticket, keeps them on +//! the run (`answers`) and starts the ticket again with them on the message +//! ([`crate::messages::TicketMessage::answers`]). The next run's triage and +//! planner read them word for word ([`answers_note`]), and a plan that asks +//! an answered question again is sent back ([`repeated`]). + +use serde::{Deserialize, Serialize}; + +/// Run attribute holding the [`Asked`] JSON. +pub const FIELD_QUESTIONS: &str = "questions"; +/// Run attribute holding the JSON list of [`Answer`]s given on it. +pub const FIELD_ANSWERS: &str = "answers"; + +/// The most questions kept for one stop. +pub const MAX_QUESTIONS: usize = 8; +/// The longest answer taken, in characters. +pub const MAX_ANSWER_CHARS: usize = 4_000; + +const MAX_QUESTION_CHARS: usize = 600; +const MAX_WHY_CHARS: usize = 600; +const MAX_SUGGESTIONS: usize = 4; +const MAX_SUGGESTION_CHARS: usize = 200; + +/// One thing a run needs a person to tell it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Question { + /// Stable within the run: `q1`, `q2`, ... + pub id: String, + /// The question, in plain words. + pub question: String, + /// Why it matters: what it blocks. Empty when the run didn't say. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub why: String, + /// Candidate answers the run found in the code or the data. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub suggestions: Vec, +} + +/// What a run asked when it stopped, and where it asked it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Asked { + pub questions: Vec, + /// When it asked (RFC 3339). + #[serde(default)] + pub asked_at: String, + /// The comment with the questions on the ticket or issue, when posting + /// it worked and its address is known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub comment_url: Option, +} + +/// An answer a person gave in CoderHelm. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Answer { + pub question_id: String, + /// The question as it was asked, kept with the answer so the next run + /// reads both even when the asking run is gone. + pub question: String, + pub answer: String, + /// Who answered, as the ticket shows them (their name or `@login`). + pub author: String, + /// When (RFC 3339). + #[serde(default)] + pub answered_at: String, +} + +/// Why answers were refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AnswerError { + /// Every answer was blank. + Empty, + /// An answer names a question this run didn't ask. + UnknownQuestion(String), + /// An answer is longer than [`MAX_ANSWER_CHARS`]. + TooLong(String), + /// The same question was answered twice in one request. + Duplicate(String), +} + +impl AnswerError { + /// For a person to read. + pub fn message(&self) -> String { + match self { + AnswerError::Empty => "Write an answer to at least one question.".to_string(), + AnswerError::UnknownQuestion(id) => { + format!("This run didn't ask a question with id \"{id}\".") + } + AnswerError::TooLong(id) => format!( + "The answer to \"{id}\" is longer than {MAX_ANSWER_CHARS} characters. Shorten it or \ + add the detail to the ticket." + ), + AnswerError::Duplicate(id) => format!("\"{id}\" is answered twice."), + } + } +} + +/// The answers to keep, in the order the questions were asked: blank ones +/// dropped, each trimmed. At least one must be left. +pub fn validate( + questions: &[Question], + given: &[(String, String)], + author: &str, + now: &str, +) -> Result, AnswerError> { + let mut seen: Vec<&str> = Vec::new(); + for (id, text) in given { + if !questions.iter().any(|q| q.id == *id) { + return Err(AnswerError::UnknownQuestion(id.clone())); + } + if seen.contains(&id.as_str()) { + return Err(AnswerError::Duplicate(id.clone())); + } + seen.push(id); + if text.trim().chars().count() > MAX_ANSWER_CHARS { + return Err(AnswerError::TooLong(id.clone())); + } + } + let out: Vec = questions + .iter() + .filter_map(|q| { + let text = given.iter().find(|(id, _)| *id == q.id)?.1.trim(); + (!text.is_empty()).then(|| Answer { + question_id: q.id.clone(), + question: q.question.clone(), + answer: text.to_string(), + author: author.to_string(), + answered_at: now.to_string(), + }) + }) + .collect(); + if out.is_empty() { + return Err(AnswerError::Empty); + } + Ok(out) +} + +/// The questions in a planner's `CLARIFICATION_NEEDED:` text. +/// +/// The planner is asked for one block per question: +/// +/// ```text +/// - question: Which environments get the new limit? +/// why: Each environment has its own value in config/limits.yml. +/// options: Production only | Every environment +/// ``` +/// +/// Older or looser answers still read: bullet or numbered lines become one +/// question each, and prose becomes a single question. +pub fn parse(detail: &str) -> Vec { + let detail = detail.trim(); + if detail.is_empty() { + return Vec::new(); + } + let mut out: Vec = Vec::new(); + let mut structured = false; + for raw in detail.lines() { + let line = raw.trim(); + let item = strip_bullet(line); + if let Some(q) = field(item, "question") { + structured = true; + out.push(Question { + question: q.to_string(), + ..Default::default() + }); + } else if let (Some(why), Some(last)) = (field(item, "why"), out.last_mut()) { + last.why = why.to_string(); + } else if let (Some(opts), Some(last)) = ( + field(item, "options").or_else(|| field(item, "suggestions")), + out.last_mut(), + ) { + last.suggestions = opts + .split('|') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + } + } + if !structured { + let bullets: Vec<&str> = detail + .lines() + .map(str::trim) + .filter(|l| strip_bullet(l).len() < l.len()) + .map(strip_bullet) + .filter(|l| !l.is_empty()) + .collect(); + out = if bullets.len() >= 2 { + bullets + .into_iter() + .map(|q| Question { + question: q.to_string(), + ..Default::default() + }) + .collect() + } else { + vec![Question { + question: detail.to_string(), + ..Default::default() + }] + }; + } + tidy(out) +} + +/// Questions from a list of plain lines (a plan decision's `questions`). +pub fn from_lines>(lines: &[S]) -> Vec { + tidy( + lines + .iter() + .map(|l| strip_bullet(l.as_ref().trim()).to_string()) + .filter(|l| !l.is_empty()) + .map(|question| Question { + question, + ..Default::default() + }) + .collect(), + ) +} + +/// Numbered ids, clipped text, at most [`MAX_QUESTIONS`]. +fn tidy(questions: Vec) -> Vec { + questions + .into_iter() + .filter(|q| !q.question.trim().is_empty()) + .take(MAX_QUESTIONS) + .enumerate() + .map(|(i, q)| Question { + id: format!("q{}", i + 1), + question: clip(q.question.trim(), MAX_QUESTION_CHARS), + why: clip(q.why.trim(), MAX_WHY_CHARS), + suggestions: q + .suggestions + .iter() + .map(|s| clip(s.trim(), MAX_SUGGESTION_CHARS)) + .filter(|s| !s.is_empty()) + .take(MAX_SUGGESTIONS) + .collect(), + }) + .collect() +} + +/// The questions as the ticket comment lists them (Markdown). +pub fn markdown(questions: &[Question]) -> String { + let mut out = String::new(); + for (i, q) in questions.iter().enumerate() { + out.push_str(&format!("{}. {}\n", i + 1, q.question)); + if !q.why.is_empty() { + out.push_str(&format!(" _Why: {}_\n", q.why)); + } + if !q.suggestions.is_empty() { + out.push_str(&format!( + " Possible answers: {}\n", + q.suggestions + .iter() + .map(|s| format!("`{s}`")) + .collect::>() + .join(", ") + )); + } + } + out.trim_end().to_string() +} + +/// The questions as plain text (a Jira comment, where Markdown shows as is). +pub fn plain(questions: &[Question]) -> String { + questions + .iter() + .enumerate() + .map(|(i, q)| { + let mut s = format!("{}. {}", i + 1, q.question); + if !q.why.is_empty() { + s.push_str(&format!(" (Why: {})", q.why)); + } + if !q.suggestions.is_empty() { + s.push_str(&format!(" Possible answers: {}.", q.suggestions.join("; "))); + } + s + }) + .collect::>() + .join("\n\n") +} + +/// The reply posted on the ticket for answers given in CoderHelm. `markdown` +/// for GitHub; plain paragraphs for Jira. `asked_at` links to the comment +/// with the questions, when known. +pub fn reply(author: &str, answers: &[Answer], asked_at: Option<&str>, markdown: bool) -> String { + let who = if author.trim().is_empty() { + "Someone on the team" + } else { + author.trim() + }; + let mut out = if markdown { + format!("**{who} answered in CoderHelm:**\n\n") + } else { + format!("{who} answered in CoderHelm:\n\n") + }; + for a in answers { + if markdown { + let quoted = a + .question + .lines() + .map(|l| format!("> {l}")) + .collect::>() + .join("\n"); + out.push_str(&format!("{quoted}\n\n{}\n\n", a.answer)); + } else { + out.push_str(&format!( + "Q: {}\n\nA: {}\n\n", + one_line(&a.question), + a.answer + )); + } + } + if let Some(url) = asked_at.filter(|u| !u.is_empty()) { + if markdown { + out.push_str(&format!( + "_In reply to [CoderHelm's questions]({url})._\n\n" + )); + } else { + out.push_str(&format!("In reply to CoderHelm's questions: {url}\n\n")); + } + } + out.push_str("CoderHelm is continuing the work with these answers."); + out +} + +/// The section the triage and planner prompts get: every answer word for +/// word, and that these questions are settled. Empty with no answers. +pub fn answers_note(answers: &[Answer]) -> String { + if answers.is_empty() { + return String::new(); + } + let mut out = String::from( + "\n\n## Answers to CoderHelm's earlier questions (given in CoderHelm, word for word)\n\ + An earlier run stopped to ask about this ticket, and people answered. Treat each answer \ + as part of the ticket. These questions are settled: plan with the answers and never ask \ + them again. Ask only about something the answers leave open, and say what is still \ + missing.\n", + ); + for a in answers { + out.push_str(&format!( + "- Question: {}\n Answer from {}: {}\n", + one_line(&a.question), + if a.author.is_empty() { + "a teammate" + } else { + &a.author + }, + a.answer.replace('\n', "\n ") + )); + } + out +} + +/// Adds `more` to `into`, skipping any already there (same question and +/// answer), in order. +pub fn merge(into: &mut Vec, more: &[Answer]) { + for a in more { + let same = |b: &Answer| { + b.question.trim() == a.question.trim() && b.answer.trim() == a.answer.trim() + }; + if !into.iter().any(same) { + into.push(a.clone()); + } + } +} + +/// A stable digest of the answers (part of the plan cache key). +pub fn digest(answers: &[Answer]) -> String { + if answers.is_empty() { + return String::new(); + } + let parts: Vec = answers + .iter() + .map(|a| format!("{}|{}", a.question, a.answer)) + .collect(); + let refs: Vec<&str> = parts.iter().map(String::as_str).collect(); + crate::sha256_hex(&refs) +} + +/// Whether `question` asks again what one of `answers` already answered. +pub fn already_answered(question: &str, answers: &[Answer]) -> bool { + let asked = words(question); + if asked.is_empty() { + return false; + } + answers.iter().any(|a| { + let before = words(&a.question); + if before.is_empty() { + return false; + } + let common = asked.iter().filter(|w| before.contains(w)).count(); + let smaller = asked.len().min(before.len()); + let union = asked.len() + before.len() - common; + // Same question reworded: most of the shorter one's words, or a + // large overlap overall. + common * 10 >= smaller * 8 || common * 10 >= union * 6 + }) +} + +/// The questions in a plan's `CLARIFICATION_NEEDED:` text that were +/// answered already. Empty when the plan isn't asking or nothing repeats. +pub fn repeated(tasks: &str, answers: &[Answer]) -> Vec { + let Some(detail) = tasks.trim_start().strip_prefix("CLARIFICATION_NEEDED:") else { + return Vec::new(); + }; + if answers.is_empty() { + return Vec::new(); + } + parse(detail) + .into_iter() + .filter(|q| already_answered(&q.question, answers)) + .collect() +} + +/// Of `questions`, the ones not answered already (ids kept). +pub fn unanswered(questions: Vec, answers: &[Answer]) -> Vec { + questions + .into_iter() + .filter(|q| !already_answered(&q.question, answers)) + .collect() +} + +/// What the planner is told when its plan asks an answered question again. +pub fn send_back(repeats: &[Question], answers: &[Answer]) -> String { + let mut out = String::from( + "Your plan asks again what people already answered in CoderHelm. Those questions are \ + settled:\n", + ); + for q in repeats { + out.push_str(&format!("- You asked: {}\n", one_line(&q.question))); + if let Some(a) = answers + .iter() + .find(|a| already_answered(&q.question, std::slice::from_ref(a))) + { + out.push_str(&format!(" They answered: {}\n", one_line(&a.answer))); + } + } + out.push_str( + "Plan with those answers now. Use CLARIFICATION_NEEDED only for something the answers \ + leave open, asking about that alone. Output the COMPLETE plan again in exactly the same \ + format as before (every file block, the fix decision included).", + ); + out +} + +/// The words that carry a question's meaning: lowercase, three letters or +/// more, common filler dropped. +fn words(s: &str) -> Vec { + const FILLER: &[&str] = &[ + "the", "and", "for", "should", "which", "what", "when", "where", "this", "that", "with", + "you", "your", "are", "does", "use", "from", "into", "will", "would", "can", "there", + "they", "them", "its", "how", "who", "any", "all", "need", "needs", "please", + ]; + let mut out: Vec = s + .split(|c: char| !c.is_alphanumeric()) + .map(str::to_lowercase) + .filter(|w| w.chars().count() >= 3 && !FILLER.contains(&w.as_str())) + .collect(); + out.sort(); + out.dedup(); + out +} + +fn strip_bullet(line: &str) -> &str { + let l = line.trim_start(); + for b in ["- ", "* ", "• "] { + if let Some(rest) = l.strip_prefix(b) { + return rest.trim(); + } + } + let digits = l.chars().take_while(|c| c.is_ascii_digit()).count(); + if digits > 0 { + let rest = &l[digits..]; + if let Some(r) = rest.strip_prefix(". ").or_else(|| rest.strip_prefix(") ")) { + return r.trim(); + } + } + l +} + +/// `key: value` (any case), the value trimmed. +fn field<'a>(line: &'a str, key: &str) -> Option<&'a str> { + let (k, v) = line.split_once(':')?; + k.trim() + .eq_ignore_ascii_case(key) + .then(|| v.trim()) + .filter(|v| !v.is_empty()) +} + +fn one_line(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +fn clip(s: &str, max_chars: usize) -> String { + if s.chars().count() <= max_chars { + return s.to_string(); + } + let kept: String = s.chars().take(max_chars).collect(); + format!("{}…", kept.trim_end()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn answer(q: &str, a: &str) -> Answer { + Answer { + question_id: "q1".into(), + question: q.into(), + answer: a.into(), + author: "Pat Doe".into(), + answered_at: "2026-10-27T10:00:00Z".into(), + } + } + + #[test] + fn reads_the_structured_blocks() { + let qs = parse( + "\n- question: Which environments get the new limit?\n why: Each environment has its \ + own value.\n options: Production only | Every environment\n- question: What is the \ + new limit?\n", + ); + assert_eq!(qs.len(), 2); + assert_eq!(qs[0].id, "q1"); + assert_eq!(qs[0].question, "Which environments get the new limit?"); + assert_eq!(qs[0].why, "Each environment has its own value."); + assert_eq!( + qs[0].suggestions, + vec!["Production only", "Every environment"] + ); + assert_eq!(qs[1].id, "q2"); + assert!(qs[1].why.is_empty() && qs[1].suggestions.is_empty()); + } + + #[test] + fn reads_bullets_and_prose() { + let qs = parse("- Which file holds the copy?\n- What should it say?"); + assert_eq!( + qs.iter().map(|q| q.question.as_str()).collect::>(), + vec!["Which file holds the copy?", "What should it say?"] + ); + let qs = parse("The new timeout value is not in the ticket."); + assert_eq!(qs.len(), 1); + assert_eq!( + qs[0].question, + "The new timeout value is not in the ticket." + ); + assert!(parse(" ").is_empty()); + } + + #[test] + fn keeps_at_most_eight_and_clips() { + let many: String = (0..12).map(|i| format!("- question: Q{i}?\n")).collect(); + assert_eq!(parse(&many).len(), MAX_QUESTIONS); + let long = "x".repeat(2_000); + assert!(parse(&long)[0].question.chars().count() <= MAX_QUESTION_CHARS + 1); + } + + #[test] + fn validate_keeps_the_written_answers_in_order() { + let qs = parse("- question: First?\n- question: Second?"); + let got = validate( + &qs, + &[("q2".into(), " two ".into()), ("q1".into(), "".into())], + "Pat Doe", + "now", + ) + .unwrap(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].question_id, "q2"); + assert_eq!(got[0].question, "Second?"); + assert_eq!(got[0].answer, "two"); + assert_eq!(got[0].author, "Pat Doe"); + } + + #[test] + fn validate_refuses_blank_unknown_long_and_twice() { + let qs = parse("- question: First?"); + assert_eq!( + validate(&qs, &[("q1".into(), " ".into())], "a", "n"), + Err(AnswerError::Empty) + ); + assert_eq!(validate(&qs, &[], "a", "n"), Err(AnswerError::Empty)); + assert_eq!( + validate(&qs, &[("q9".into(), "x".into())], "a", "n"), + Err(AnswerError::UnknownQuestion("q9".into())) + ); + assert_eq!( + validate( + &qs, + &[("q1".into(), "x".repeat(MAX_ANSWER_CHARS + 1))], + "a", + "n" + ), + Err(AnswerError::TooLong("q1".into())) + ); + assert_eq!( + validate( + &qs, + &[("q1".into(), "a".into()), ("q1".into(), "b".into())], + "a", + "n" + ), + Err(AnswerError::Duplicate("q1".into())) + ); + } + + #[test] + fn the_planner_reads_answers_word_for_word() { + let note = answers_note(&[answer( + "Which environments get the new limit?", + "Production only.\nStaging keeps 100.", + )]); + assert!(note.contains("Which environments get the new limit?")); + assert!(note.contains("Answer from Pat Doe: Production only.\n Staging keeps 100.")); + assert!(note.contains("never ask them again")); + assert!(answers_note(&[]).is_empty()); + } + + #[test] + fn an_answered_question_is_recognized_when_reworded() { + let answers = [answer( + "Which environments get the new rate limit?", + "Production", + )]; + assert!(already_answered( + "Which environments should get the new rate limit?", + &answers + )); + assert!(already_answered( + "Which environments get the new rate limit?", + &answers + )); + assert!(!already_answered( + "What should the error message say?", + &answers + )); + assert!(!already_answered("", &answers)); + } + + #[test] + fn repeated_finds_only_answered_questions_in_a_clarification() { + let answers = [answer( + "Which environments get the new rate limit?", + "Production", + )]; + let tasks = + "CLARIFICATION_NEEDED:\n- question: Which environments should get the new rate \ + limit?\n- question: What should the error message say?"; + let r = repeated(tasks, &answers); + assert_eq!(r.len(), 1); + assert!(r[0].question.contains("environments")); + assert!(repeated("- [ ] src/a.rs: do it", &answers).is_empty()); + assert!(repeated(tasks, &[]).is_empty()); + let left = unanswered( + parse(tasks.strip_prefix("CLARIFICATION_NEEDED:").unwrap()), + &answers, + ); + assert_eq!(left.len(), 1); + assert_eq!(left[0].question, "What should the error message say?"); + let back = send_back(&r, &answers); + assert!(back.contains("They answered: Production")); + } + + #[test] + fn the_reply_names_who_answered() { + let a = [answer("Which page?", "The pricing page.")]; + let md = reply("Pat Doe", &a, Some("https://example.com/c/1"), true); + assert!(md.starts_with("**Pat Doe answered in CoderHelm:**")); + assert!(md.contains("> Which page?\n\nThe pricing page.")); + assert!(md.contains("(https://example.com/c/1)")); + let plain = reply("", &a, None, false); + assert!(plain.starts_with("Someone on the team answered in CoderHelm:")); + assert!(plain.contains("Q: Which page?\n\nA: The pricing page.")); + assert!(!plain.contains("**")); + } + + #[test] + fn comment_renderings_list_why_and_options() { + let qs = + parse("- question: Which page?\n why: Two pages share it.\n options: Home | Pricing"); + let md = markdown(&qs); + assert!(md.contains("1. Which page?")); + assert!(md.contains("_Why: Two pages share it._")); + assert!(md.contains("`Home`, `Pricing`")); + let p = plain(&qs); + assert!(p.contains( + "1. Which page? (Why: Two pages share it.) Possible answers: Home; Pricing." + )); + } + + #[test] + fn merging_skips_answers_already_there() { + let mut have = vec![answer("A?", "1")]; + merge(&mut have, &[answer("A?", "1"), answer("B?", "2")]); + assert_eq!(have.len(), 2); + assert_eq!(have[1].question, "B?"); + } + + #[test] + fn the_digest_changes_with_the_answers() { + assert!(digest(&[]).is_empty()); + assert_ne!(digest(&[answer("A?", "1")]), digest(&[answer("A?", "2")])); + } +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index b39c71825..bc6e3888e 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -360,6 +360,7 @@ async fn main() -> Result<(), Error> { .route("/runs/:run_id/agent-log", get(routes::api::get_agent_log)) .route("/runs/:run_id/openspec", get(routes::api::get_run_openspec)) .route("/runs/:run_id/retry", post(routes::api::retry_run)) + .route("/runs/:run_id/answer", post(routes::run_answer::answer_run)) .route("/runs/:run_id/reset", post(routes::api::reset_and_rerun)) .route("/runs/:run_id/re-review", post(routes::api::re_review_run)) .route("/runs/:run_id/cancel", post(routes::api::cancel_run)) diff --git a/services/gateway/src/openapi.rs b/services/gateway/src/openapi.rs index 250265bc7..8f48903d2 100644 --- a/services/gateway/src/openapi.rs +++ b/services/gateway/src/openapi.rs @@ -80,6 +80,7 @@ pub const PUBLIC_ROUTES: &[PublicRoute] = &[ key("GET", "/api/runs", "api::list_runs"), key("GET", "/api/runs/:run_id", "api::get_run"), key("POST", "/api/runs/:run_id/retry", "api::retry_run"), + key("POST", "/api/runs/:run_id/answer", "run_answer::answer_run"), key("POST", "/api/runs/:run_id/cancel", "api::cancel_run"), key("GET", "/api/plans", "plans::list_plans"), key("POST", "/api/plans", "plans::create_plan"), @@ -277,6 +278,7 @@ are verified by their signatures."; crate::routes::api::list_runs, crate::routes::api::get_run, crate::routes::api::retry_run, + crate::routes::run_answer::answer_run, crate::routes::api::cancel_run, crate::routes::plans::list_plans, crate::routes::plans::create_plan, diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 90fa90ea4..fe8604d28 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -223,6 +223,7 @@ pub const CAPABILITIES: &[Capability] = &[ min_role: "member", handlers: &[ "api::retry_run", + "run_answer::answer_run", "api::reset_and_rerun", "api::re_review_run", "api::cancel_run", diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 4a64d915b..50e974637 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1015,6 +1015,58 @@ pub struct Run { /// Notes it wrote while working, in order. #[schema(example = json!([{"message": "Tests pass; opening the pull request.", "timestamp": "2026-10-22T14:15:02Z"}]))] pub progress_notes: Option>, + /// What the run asked when it stopped as `needs_input`, one question + /// each. Answer them with `POST /api/runs/{run_id}/answer`. Empty when + /// it asked nothing it can take answers for here. + pub questions: Vec, + /// The comment with the questions on the ticket or issue, when known. + #[schema(example = "https://github.com/acme/web/issues/42#issuecomment-2210")] + pub questions_url: Option, + /// Answers people gave to its questions in CoderHelm. + pub answers: Vec, + /// The reply with those answers on the ticket or issue, when known. + #[schema(example = json!(null))] + pub answers_url: Option, + /// The run that picked the answers up and continued the work. + #[schema(example = json!(null))] + pub continued_run_id: Option, +} + +/// A question a run asked a person. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunQuestion { + /// The question's id within the run (`q1`, `q2`, ...). + #[schema(example = "q1")] + pub id: String, + /// The question, in plain words. + #[schema(example = "Which environments get the new rate limit?")] + pub question: String, + /// Why it matters: what it blocks. + #[schema(example = "config/limits.yml holds one value per environment.")] + pub why: Option, + /// Candidate answers the run found in the code or the data. + #[schema(example = json!(["Production only", "Every environment"]))] + pub suggestions: Vec, +} + +/// An answer given in CoderHelm to a run's question. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunAnswer { + /// The question it answers. + #[schema(example = "q1")] + pub question_id: String, + /// That question, as asked. + #[schema(example = "Which environments get the new rate limit?")] + pub question: String, + /// The answer, as written. + #[schema(example = "Production only.")] + pub answer: String, + /// Who answered, as the ticket shows them. + #[schema(example = "Pat Doe")] + pub author: String, + /// When (RFC 3339). + #[schema(example = "2026-10-22T14:20:00Z")] + pub answered_at: String, } /// GET /api/runs/:run_id — get single run detail (from runs table). @@ -1198,6 +1250,7 @@ fn run_of(item: &run_search::Item, run_id: &str, usage: RunUsage) -> Run { .collect::>() }) }; + let asked = run_asked(item); Run { run_id: run_id.to_string(), status: st("status"), @@ -1274,9 +1327,51 @@ fn run_of(item: &run_search::Item, run_id: &str, usage: RunUsage) -> Run { .map(|(_, _, message, timestamp)| RunNote { message, timestamp }) .collect() }), + questions: asked + .as_ref() + .map(|a| { + a.questions + .iter() + .map(|q| RunQuestion { + id: q.id.clone(), + question: q.question.clone(), + why: (!q.why.is_empty()).then(|| q.why.clone()), + suggestions: q.suggestions.clone(), + }) + .collect() + }) + .unwrap_or_default(), + questions_url: asked.and_then(|a| a.comment_url), + answers: run_answers(item) + .into_iter() + .map(|a| RunAnswer { + question_id: a.question_id, + question: a.question, + answer: a.answer, + author: a.author, + answered_at: a.answered_at, + }) + .collect(), + answers_url: st("answers_url"), + continued_run_id: st("continued_run_id"), } } +/// What a run asked when it stopped (see `common::run_questions`). +pub(crate) fn run_asked(item: &run_search::Item) -> Option { + item.get(common::run_questions::FIELD_QUESTIONS) + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok()) +} + +/// The answers given on a run in CoderHelm. +pub(crate) fn run_answers(item: &run_search::Item) -> Vec { + item.get(common::run_questions::FIELD_ANSWERS) + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_default() +} + /// What a pass kept about what it did (e.g. which team agents reviewed a /// plan): its JSON, or the text as kept when it isn't JSON, or null. fn trace_detail(raw: Option<&String>) -> Value { @@ -1585,6 +1680,60 @@ pub async fn retry_run( return Err(StatusCode::BAD_REQUEST); } + let ticket = retry_message(&state, &claims, item).await?; + // Dashboard retry: force-delete existing lock so re-enqueue always succeeds + delete_ticket_lock(&state, &claims.team_id, &ticket.ticket_id).await; + let message = WorkerMessage::Ticket(ticket); + + let body = serde_json::to_string(&message).map_err(|e| { + error!("Failed to serialize retry message: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(&body) + .send() + .await + .map_err(|e| { + error!("Failed to enqueue retry: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + // Mark the old run as retried so it can't be retried again + let now = chrono::Utc::now().to_rfc3339(); + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&claims.team_id)) + .key("run_id", attr_s(&run_id)) + .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") + .expression_attribute_names("#status", "status") + .expression_attribute_values(":s", attr_s("retried")) + .expression_attribute_values(":sri", attr_s(&format!("retried#{run_id}"))) + .expression_attribute_values(":t", attr_s(&now)) + .send() + .await; + + info!(run_id, "Run retried — dispatched to SQS"); + + Ok(Json(RunActionResult { + status: "retrying".into(), + })) +} + +/// The message that starts a run's ticket again, from the run's record: +/// the ticket, its repository (cleared for Jira, so the worker picks it +/// fresh), its body for Jira and alerts (GitHub re-reads the issue) and the +/// person asking. +pub(crate) async fn retry_message( + state: &AppState, + claims: &Claims, + item: &std::collections::HashMap, +) -> Result { let repo = item .get("repo") .and_then(|v| v.as_s().ok()) @@ -1602,7 +1751,7 @@ pub async fn retry_run( .and_then(|n| n.parse::().ok()) .unwrap_or(0); if installation_id == 0 { - installation_id = get_team_installation_id(&state, &claims.team_id).await?; + installation_id = get_team_installation_id(state, &claims.team_id).await?; } let issue_number = item .get("issue_number") @@ -1627,9 +1776,6 @@ pub async fn retry_run( .map(|s| s.as_str()) .unwrap_or(""); - // Dashboard retry: force-delete existing lock so re-enqueue always succeeds - delete_ticket_lock(&state, &claims.team_id, ticket_id).await; - // For Jira tickets, clear repo_owner/repo_name so the worker's // select_repo LLM can pick the correct repo fresh (the old run // may have been routed to the wrong repo). @@ -1649,7 +1795,7 @@ pub async fn retry_run( String::new() }; - let message = WorkerMessage::Ticket(TicketMessage { + Ok(TicketMessage { team_id: claims.team_id.clone(), installation_id, source, @@ -1678,46 +1824,7 @@ pub async fn retry_run( .and_then(|s| serde_json::from_str(s).ok()) .unwrap_or_default(), ..Default::default() - }); - - let body = serde_json::to_string(&message).map_err(|e| { - error!("Failed to serialize retry message: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - - state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(&body) - .send() - .await - .map_err(|e| { - error!("Failed to enqueue retry: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - - // Mark the old run as retried so it can't be retried again - let now = chrono::Utc::now().to_rfc3339(); - let _ = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(&claims.team_id)) - .key("run_id", attr_s(&run_id)) - .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") - .expression_attribute_names("#status", "status") - .expression_attribute_values(":s", attr_s("retried")) - .expression_attribute_values(":sri", attr_s(&format!("retried#{run_id}"))) - .expression_attribute_values(":t", attr_s(&now)) - .send() - .await; - - info!(run_id, "Run retried — dispatched to SQS"); - - Ok(Json(RunActionResult { - status: "retrying".into(), - })) + }) } /// Close a PR and delete a branch via the GitHub App token. Best-effort. @@ -5409,6 +5516,65 @@ mod tests { std::collections::HashMap::from([("status".to_string(), A::S("running".into()))]); let run = serde_json::to_value(run_of(&bare, "01JB8Y", usage())).unwrap(); assert_eq!(run["run_id"], "01JB8Y"); + assert_eq!(run["questions"], json!([])); + assert_eq!(run["answers"], json!([])); + } + + /// What a run stored when it stopped to ask comes back on `get_run`: + /// each question with its reason and candidate answers, the comment's + /// address, the answers given and the run that continued. + #[test] + fn get_run_returns_the_questions_the_run_stored() { + use aws_sdk_dynamodb::types::AttributeValue as A; + let asked = json!({ + "questions": [ + {"id": "q1", "question": "Which environments get the new limit?", + "why": "Each environment has its own value.", + "suggestions": ["Production only", "Every environment"]}, + {"id": "q2", "question": "What is the new limit?"} + ], + "asked_at": "2026-10-27T10:00:00Z", + "comment_url": "https://example.atlassian.net/browse/ABC-1?focusedCommentId=10001" + }); + let answers = json!([{ + "question_id": "q1", "question": "Which environments get the new limit?", + "answer": "Production only", "author": "Pat Doe", + "answered_at": "2026-10-27T10:05:00Z" + }]); + let item = std::collections::HashMap::from([ + ("status".to_string(), A::S("retried".into())), + ("questions".to_string(), A::S(asked.to_string())), + ("answers".to_string(), A::S(answers.to_string())), + ("continued_run_id".to_string(), A::S("01JB8Z".into())), + ]); + let run = serde_json::to_value(run_of( + &item, + "01JB8Y", + RunUsage { + tokens_in: 0, + tokens_out: 0, + cache_read: 0, + cache_write: 0, + cost_usd: 0.0, + }, + )) + .unwrap(); + assert_eq!( + run["questions"], + json!([ + {"id": "q1", "question": "Which environments get the new limit?", + "why": "Each environment has its own value.", + "suggestions": ["Production only", "Every environment"]}, + {"id": "q2", "question": "What is the new limit?", "why": null, "suggestions": []} + ]) + ); + assert_eq!( + run["questions_url"], + "https://example.atlassian.net/browse/ABC-1?focusedCommentId=10001" + ); + assert_eq!(run["answers"][0]["answer"], "Production only"); + assert_eq!(run["answers"][0]["author"], "Pat Doe"); + assert_eq!(run["continued_run_id"], "01JB8Z"); } #[test] diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 32580fe78..7d92928c8 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -48,6 +48,7 @@ pub mod plugins; pub mod review_lessons; pub mod reviewer; pub mod roles; +pub mod run_answer; pub mod run_close; pub mod run_search; pub mod search; diff --git a/services/gateway/src/routes/run_answer.rs b/services/gateway/src/routes/run_answer.rs new file mode 100644 index 000000000..e52bf23fd --- /dev/null +++ b/services/gateway/src/routes/run_answer.rs @@ -0,0 +1,905 @@ +//! Answering a run's questions from the dashboard (or the API). +//! +//! A run that stops as `needs_input` keeps the questions it asked on its +//! record (`common::run_questions`). Answering them here: +//! +//! 1. checks the person may start runs, the run is still waiting, and the +//! answers are for its questions (at least one written); +//! 2. claims the run in one conditional write: `needs_input` becomes +//! `retried`, with the answers and the id of the run that continues, so a +//! second answer or a Retry racing this one is refused, never doubled; +//! 3. starts the ticket again with the answers on the message: the new +//! run's triage and planner read them word for word; +//! 4. posts the answers on the ticket or issue, under CoderHelm's question, +//! as " answered in CoderHelm:". +//! +//! Retry stays for a ticket edited directly. + +use std::collections::HashMap; +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{extract::State, http::StatusCode, Extension, Json}; +use common::run_questions::{self, Answer}; +use serde_json::{json, Value}; +use tracing::{error, info, warn}; + +use crate::models::{Claims, TicketSource, WorkerMessage}; +use crate::AppState; + +type Item = HashMap; +type Refusal = (StatusCode, Json); + +/// Answers to a run's questions. +#[derive(Debug, serde::Deserialize, utoipa::ToSchema)] +pub struct AnswerRun { + /// One entry per question answered. Questions left out (or blank) stay + /// open; at least one needs an answer. + pub answers: Vec, +} + +/// The answer to one question. +#[derive(Debug, serde::Deserialize, utoipa::ToSchema)] +pub struct GivenAnswer { + /// The question's `id` from the run's `questions`. + #[schema(example = "q1")] + pub question_id: String, + /// The answer, in plain words. At most 4000 characters. + #[schema(example = "Production only. Staging keeps the old limit.")] + pub answer: String, +} + +/// What answering did. +#[derive(Debug, serde::Serialize, utoipa::ToSchema)] +pub struct AnswerRunResult { + /// `continuing`: the ticket is queued again with the answers. + #[schema(example = "continuing")] + pub status: String, + /// The id of the run that continues the work. It shows in + /// `GET /api/runs/{run_id}` once it starts, within seconds. + #[schema(example = "01JB8Z3N5Q7S9V1X3Z5B7D9F1H")] + pub run_id: String, + /// Whether the answers were posted on the ticket or issue. + #[schema(example = true)] + pub posted: bool, + /// The reply on the ticket or issue, when its address is known. + #[schema(example = "https://github.com/acme/web/issues/42#issuecomment-2211")] + pub comment_url: Option, +} + +fn refuse(status: StatusCode, message: &str) -> Refusal { + ( + status, + Json(json!({ "error": message, "code": crate::openapi::default_code(status) })), + ) +} + +fn s(item: &Item, key: &str) -> String { + item.get(key) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +/// Why a run can't take answers now, in words for a person; `None` when it +/// can. Pure, so the rules are tested on their own. +pub fn not_answerable(status: &str, has_questions: bool) -> Option { + if status != common::run_status::NEEDS_INPUT { + return Some(match status { + "retried" => { + "These questions were answered already, or the run was retried. Refresh to see \ + the run that continued." + .to_string() + } + "" => "This run isn't waiting for an answer.".to_string(), + other => format!( + "This run isn't waiting for an answer any more (it is {}). Refresh to see where \ + it is.", + other.replace('_', " ") + ), + }); + } + if !has_questions { + return Some( + "This run didn't leave questions to answer here. Add the detail to the ticket, then \ + retry." + .to_string(), + ); + } + None +} + +/// POST /api/runs/:run_id/answer — answer a run's questions and continue. +#[utoipa::path( + post, + path = "/api/runs/{run_id}/answer", + tag = "Runs", + operation_id = "answerRun", + summary = "Answer a run's questions", + description = "Answers the questions a `needs_input` run asked (its `questions`) and continues \ + the work: the answers are posted on the ticket or issue as a reply from you, kept on the \ + run, and the ticket starts again as a new run whose plan reads them word for word. The \ + old run becomes `retried` with `continued_run_id` set. A run that isn't `needs_input` \ + any more (answered, retried or closed meanwhile) is refused with `409`.", + params(("run_id" = String, Path, description = "The run's id.", example = "01JB8X6F4M2C9QZ3T7V5W1K0HA")), + request_body = AnswerRun, + responses( + (status = 200, description = "The work continues with the answers.", body = AnswerRunResult), + (status = 400, description = "No answer written, an answer too long, or a question the run didn't ask.", body = crate::openapi::ErrorBody), + (status = 404, description = "No run with this id in the team.", body = crate::openapi::ErrorBody), + (status = 409, description = "The run isn't waiting for an answer, or asked nothing to answer here.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["runs"])), +)] +pub async fn answer_run( + State(state): State>, + Extension(claims): Extension, + axum::extract::Path(run_id): axum::extract::Path, + Json(body): Json, +) -> Result, Refusal> { + // Members and up, as Retry (checked again in `answer`). + claims.require_role(1).map_err(members_only)?; + answer(&state, &claims, &run_id, body).await.map(Json) +} + +fn members_only(code: StatusCode) -> Refusal { + refuse( + code, + "Only members can answer a run's questions. Ask an admin for member access.", + ) +} + +/// The handler's work, callable from tests. +pub async fn answer( + state: &AppState, + claims: &Claims, + run_id: &str, + body: AnswerRun, +) -> Result { + claims.require_role(1).map_err(members_only)?; + if super::github_webhook::check_run_budget(state, &claims.team_id) + .await + .is_some() + { + return Err(refuse( + StatusCode::TOO_MANY_REQUESTS, + "The monthly token limit is reached, so no new work can start.", + )); + } + + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(claims.team_id.clone())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .consistent_read(true) + .send() + .await + .map_err(|e| { + error!(run_id, error = %e, "answer: could not read the run"); + refuse( + StatusCode::INTERNAL_SERVER_ERROR, + "The run couldn't be read. Try again.", + ) + })? + .item + .ok_or_else(|| refuse(StatusCode::NOT_FOUND, "No run with this id in the team."))?; + + let asked = super::api::run_asked(&item); + let questions = asked + .as_ref() + .map(|a| a.questions.clone()) + .unwrap_or_default(); + if let Some(why) = not_answerable(&s(&item, "status"), !questions.is_empty()) { + return Err(refuse(StatusCode::CONFLICT, &why)); + } + + let profile = super::run_close::profile_name(state, claims).await; + let person = super::run_close::closer(claims, profile.as_deref()); + let now = chrono::Utc::now().to_rfc3339(); + let given: Vec<(String, String)> = body + .answers + .into_iter() + .map(|a| (a.question_id, a.answer)) + .collect(); + let answers = run_questions::validate(&questions, &given, &person.public, &now) + .map_err(|e| refuse(StatusCode::BAD_REQUEST, &e.message()))?; + + let mut ticket = super::api::retry_message(state, claims, &item) + .await + .map_err(|code| refuse(code, "The run's ticket couldn't be read. Try again."))?; + let new_run_id = ulid::Ulid::new().to_string(); + // Answers from earlier stops of the ticket reach the run through its + // history (the worker merges them in). + ticket.answers = answers.clone(); + ticket.new_run_id = Some(new_run_id.clone()); + + claim( + state, + &claims.team_id, + run_id, + &answers, + &new_run_id, + &person.email, + &now, + ) + .await?; + + let queued = match serde_json::to_string(&WorkerMessage::Ticket(ticket.clone())) { + Ok(msg) => { + super::api::delete_ticket_lock(state, &claims.team_id, &ticket.ticket_id).await; + state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(msg) + .send() + .await + .map_err(|e| e.to_string()) + } + Err(e) => Err(e.to_string()), + }; + if let Err(e) = queued { + error!(run_id, error = %e, "answer: could not queue the ticket again"); + release(state, &claims.team_id, run_id).await; + return Err(refuse( + StatusCode::INTERNAL_SERVER_ERROR, + "Your answers couldn't be sent on. Nothing was posted; try again.", + )); + } + + let asked_at = asked.and_then(|a| a.comment_url); + let comment_url = post_reply(state, &item, &person.public, &answers, asked_at.as_deref()).await; + let posted = comment_url.is_some(); + if let Some(Some(url)) = &comment_url { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(claims.team_id.clone())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression("SET answers_url = :u") + .expression_attribute_values(":u", AttributeValue::S(url.clone())) + .send() + .await; + } + info!( + run_id, + new_run_id, + answered = answers.len(), + posted, + "Run's questions answered — continuing" + ); + Ok(AnswerRunResult { + status: "continuing".to_string(), + run_id: new_run_id, + posted, + comment_url: comment_url.flatten(), + }) +} + +/// Marks the run answered, only while it still waits: two answers or an +/// answer and a Retry at once leave exactly one run going. +async fn claim( + state: &AppState, + team_id: &str, + run_id: &str, + answers: &[Answer], + new_run_id: &str, + by: &str, + now: &str, +) -> Result<(), Refusal> { + let json = serde_json::to_string(answers).unwrap_or_else(|_| "[]".to_string()); + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t, #a = :a, \ + continued_run_id = :nr, answered_by = :by", + ) + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .expression_attribute_names("#a", run_questions::FIELD_ANSWERS) + .expression_attribute_values(":s", AttributeValue::S("retried".into())) + .expression_attribute_values(":sri", AttributeValue::S(format!("retried#{run_id}"))) + .expression_attribute_values(":t", AttributeValue::S(now.to_string())) + .expression_attribute_values(":a", AttributeValue::S(json)) + .expression_attribute_values(":nr", AttributeValue::S(new_run_id.to_string())) + .expression_attribute_values(":by", AttributeValue::S(by.to_string())) + .expression_attribute_values( + ":waiting", + AttributeValue::S(common::run_status::NEEDS_INPUT.into()), + ) + .send() + .await; + match res { + Ok(_) => Ok(()), + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => + { + Err(refuse( + StatusCode::CONFLICT, + "This run moved on while you were writing (answered, retried or closed). \ + Refresh to see where it is.", + )) + } + Err(e) => { + error!(run_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "answer: could not mark the run answered"); + Err(refuse( + StatusCode::INTERNAL_SERVER_ERROR, + "Your answers couldn't be saved. Try again.", + )) + } + } +} + +/// Puts the run back to waiting when the ticket couldn't be queued. +async fn release(state: &AppState, team_id: &str, run_id: &str) { + 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 #status = :w, status_run_id = :sri REMOVE #a, continued_run_id, answered_by", + ) + .condition_expression("#status = :retried") + .expression_attribute_names("#status", "status") + .expression_attribute_names("#a", run_questions::FIELD_ANSWERS) + .expression_attribute_values( + ":w", + AttributeValue::S(common::run_status::NEEDS_INPUT.into()), + ) + .expression_attribute_values(":sri", AttributeValue::S(format!("needs_input#{run_id}"))) + .expression_attribute_values(":retried", AttributeValue::S("retried".into())) + .send() + .await + { + warn!(run_id, error = %e, "answer: could not put the run back to waiting"); + } +} + +/// Posts the answers on the run's ticket or issue. `None` when nothing was +/// posted; `Some(None)` when posted but its address isn't known. +async fn post_reply( + state: &AppState, + item: &Item, + author: &str, + answers: &[Answer], + asked_at: Option<&str>, +) -> Option> { + let run_id = s(item, "run_id"); + let source = match s(item, "ticket_source").as_str() { + "jira" => TicketSource::Jira, + "alert" => TicketSource::Alert, + _ => TicketSource::Github, + }; + match source { + TicketSource::Jira => { + let ticket = s(item, "ticket_id"); + let config = state + .dynamo + .get_item() + .table_name(&state.config.jira_config_table_name) + .key("pk", AttributeValue::S(s(item, "team_id"))) + .key("sk", AttributeValue::S("JIRA#config".into())) + .send() + .await + .ok() + .and_then(|o| o.item)?; + let url = Some(s(&config, "add_comment_url")).filter(|u| !u.is_empty())?; + let site = s(&config, "site_url"); + let payload = json!({ + "issueKey": ticket, + "comment": run_questions::reply(author, answers, asked_at, false), + "commentType": "answer", + "title": "Answered in CoderHelm", + }); + match state.http.post(&url).json(&payload).send().await { + Ok(r) if r.status().is_success() => { + let id = r.json::().await.ok().and_then(|v| match &v["id"] { + Value::String(s) => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + }); + Some(jira_link(&site, &ticket, id.as_deref())) + } + Ok(r) => { + warn!( + run_id, + status = r.status().as_u16(), + "answer: Jira refused the reply" + ); + None + } + Err(e) => { + warn!(run_id, error = %e, "answer: Jira reply failed"); + None + } + } + } + TicketSource::Github => { + let issue = item + .get("issue_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + let repo = s(item, "repo"); + let (owner, name) = repo.split_once('/')?; + if issue == 0 { + return None; + } + let installation = item + .get("installation_id") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + let token = crate::auth::github_app::get_installation_token(state, installation) + .await + .map_err(|e| warn!(run_id, error = %e, "answer: no GitHub token for the reply")) + .ok()?; + let res = state + .http + .post(format!( + "https://api.github.com/repos/{owner}/{name}/issues/{issue}/comments" + )) + .header("Authorization", format!("Bearer {token}")) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "Coderhelm-bot") + .json(&json!({ "body": run_questions::reply(author, answers, asked_at, true) })) + .send() + .await; + match res { + Ok(r) if r.status().is_success() => Some( + r.json::() + .await + .ok() + .and_then(|v| v["html_url"].as_str().map(str::to_string)), + ), + Ok(r) => { + warn!( + run_id, + status = r.status().as_u16(), + "answer: GitHub refused the reply" + ); + None + } + Err(e) => { + warn!(run_id, error = %e, "answer: GitHub reply failed"); + None + } + } + } + // An alert has no thread to reply in. + TicketSource::Alert => None, + } +} + +/// The address of a Jira comment, or of the ticket when the id is unknown. +fn jira_link(site: &str, ticket: &str, id: Option<&str>) -> Option { + let site = site.trim().trim_end_matches('/'); + if site.is_empty() || ticket.is_empty() { + return None; + } + Some(match id.filter(|i| !i.is_empty()) { + Some(id) => format!("{site}/browse/{ticket}?focusedCommentId={id}"), + None => format!("{site}/browse/{ticket}"), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_waiting_run_with_questions_takes_answers() { + assert_eq!(not_answerable("needs_input", true), None); + assert!(not_answerable("needs_input", false) + .unwrap() + .contains("Add the detail to the ticket")); + assert!(not_answerable("retried", true) + .unwrap() + .contains("answered already")); + assert!(not_answerable("running", true) + .unwrap() + .contains("(it is running)")); + assert!(not_answerable("needs_outside_change", true) + .unwrap() + .contains("needs outside change")); + } + + #[test] + fn jira_links_point_at_the_comment() { + assert_eq!( + jira_link("https://example.atlassian.net/", "ABC-1", Some("10001")).as_deref(), + Some("https://example.atlassian.net/browse/ABC-1?focusedCommentId=10001") + ); + assert_eq!( + jira_link("https://example.atlassian.net", "ABC-1", None).as_deref(), + Some("https://example.atlassian.net/browse/ABC-1") + ); + assert_eq!(jira_link("", "ABC-1", Some("1")), None); + } + + // ── The handler against a stand-in for DynamoDB, SQS and the Jira app ── + + use axum::body::Bytes; + use axum::http::HeaderMap; + use std::sync::Mutex; + + /// What the stand-in holds and what it was asked. + #[derive(Default)] + struct Fake { + /// One item per table, in DynamoDB's JSON. + items: HashMap, + /// Conditional updates fail (the run moved on meanwhile). + conditions_fail: bool, + /// (operation, request body), in order. + calls: Vec<(String, Value)>, + } + + impl Fake { + fn ops(&self, op: &str) -> Vec { + self.calls + .iter() + .filter(|(o, _)| o == op) + .map(|(_, b)| b.clone()) + .collect() + } + } + + async fn serve(fake: Arc>) -> String { + async fn handle( + axum::extract::State(fake): axum::extract::State>>, + uri: axum::http::Uri, + headers: HeaderMap, + body: Bytes, + ) -> axum::response::Response { + use axum::response::IntoResponse; + let body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null); + let op = headers + .get("x-amz-target") + .and_then(|v| v.to_str().ok()) + .map(|t| t.rsplit('.').next().unwrap_or("").to_string()) + .unwrap_or_else(|| uri.path().to_string()); + let mut f = fake.lock().unwrap(); + f.calls.push((op.clone(), body.clone())); + let amz = |status: u16, v: Value| { + ( + StatusCode::from_u16(status).unwrap(), + [("content-type", "application/x-amz-json-1.0")], + v.to_string(), + ) + .into_response() + }; + match op.as_str() { + "GetItem" => { + let table = body["TableName"].as_str().unwrap_or(""); + match f.items.get(table) { + Some(item) => amz(200, json!({ "Item": item })), + None => amz(200, json!({})), + } + } + "UpdateItem" if f.conditions_fail && body.get("ConditionExpression").is_some() => { + amz( + 400, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException", + "message": "The conditional request failed" + }), + ) + } + "UpdateItem" | "DeleteItem" | "PutItem" => amz(200, json!({})), + "Query" => amz(200, json!({ "Items": [], "Count": 0, "ScannedCount": 0 })), + "SendMessage" => amz(200, json!({ "MessageId": "m-1" })), + "/jira-comment" => ( + StatusCode::CREATED, + [("content-type", "application/json")], + json!({ "id": "10042" }).to_string(), + ) + .into_response(), + _ => amz(400, json!({ "__type": "UnknownOperation" })), + } + } + let app = axum::Router::new().fallback(handle).with_state(fake); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + url + } + + fn state_for(url: &str) -> AppState { + let creds = aws_sdk_dynamodb::config::SharedCredentialsProvider::new( + aws_sdk_dynamodb::config::Credentials::new("test", "test", None, None, "test"), + ); + let aws = aws_config::SdkConfig::builder() + .behavior_version(aws_config::BehaviorVersion::latest()) + .region(aws_config::Region::new("us-east-1")) + .endpoint_url(url) + .credentials_provider(creds) + .build(); + let secrets: crate::models::Secrets = + serde_json::from_value(json!({ "jwt_secret": "test" })).unwrap(); + AppState { + dynamo: aws_sdk_dynamodb::Client::new(&aws), + sqs: aws_sdk_sqs::Client::new(&aws), + ses: aws_sdk_sesv2::Client::new(&aws), + s3: aws_sdk_s3::Client::new(&aws), + cognito: aws_sdk_cognitoidentityprovider::Client::new(&aws), + lambda: aws_sdk_lambda::Client::new(&aws), + kms: aws_sdk_kms::Client::new(&aws), + sts: aws_sdk_sts::Client::new(&aws), + bedrock: aws_sdk_bedrockruntime::Client::new(&aws), + scheduler: common::plugins::schedule::aws_sdk_scheduler::Client::new(&aws), + http: reqwest::Client::new(), + secrets, + config: crate::models::Config { + runs_table_name: "runs".into(), + jira_config_table_name: "jira".into(), + users_table_name: "users".into(), + teams_table_name: "teams".into(), + settings_table_name: "settings".into(), + analytics_table_name: "analytics".into(), + ticket_queue_url: format!("{url}/queue/tickets"), + ..Default::default() + }, + cognito_client_secret: String::new(), + } + } + + fn claims(role: &str) -> Claims { + serde_json::from_value(json!({ + "sub": "USER#u1", + "team_id": "TEAM#t1", + "email": "pat@example.com", + "role": role, + "exp": 4_000_000_000u64, + "iat": 1u64, + })) + .unwrap() + } + + /// A Jira run stopped on two questions, the team's Jira app, and the + /// member's profile. + async fn fixture(status: &str) -> (Arc>, AppState) { + let fake = Arc::new(Mutex::new(Fake::default())); + let url = serve(fake.clone()).await; + let asked = json!({ + "questions": [ + {"id": "q1", "question": "Which environments get the new limit?", + "why": "Each environment has its own value.", + "suggestions": ["Production only", "Every environment"]}, + {"id": "q2", "question": "What is the new limit?"} + ], + "asked_at": "2026-10-27T10:00:00Z", + "comment_url": "https://example.atlassian.net/browse/ABC-7?focusedCommentId=10001" + }); + { + let mut f = fake.lock().unwrap(); + f.items.insert( + "runs".into(), + json!({ + "team_id": {"S": "TEAM#t1"}, + "run_id": {"S": "01JB8X6F4M2C9QZ3T7V5W1K0HA"}, + "status": {"S": status}, + "ticket_source": {"S": "jira"}, + "ticket_id": {"S": "ABC-7"}, + "title": {"S": "Raise the sign-up rate limit"}, + "repo": {"S": "acme/web"}, + "installation_id": {"N": "7"}, + "ticket_body": {"S": "Raise the limit."}, + "questions": {"S": asked.to_string()} + }), + ); + f.items.insert( + "jira".into(), + json!({ + "add_comment_url": {"S": format!("{url}/jira-comment")}, + "site_url": {"S": "https://example.atlassian.net"} + }), + ); + f.items + .insert("users".into(), json!({ "name": {"S": "Pat Doe"} })); + } + (fake, state_for(&url)) + } + + fn body(answers: &[(&str, &str)]) -> AnswerRun { + AnswerRun { + answers: answers + .iter() + .map(|(q, a)| GivenAnswer { + question_id: q.to_string(), + answer: a.to_string(), + }) + .collect(), + } + } + + const RUN: &str = "01JB8X6F4M2C9QZ3T7V5W1K0HA"; + + #[tokio::test] + async fn an_answer_is_kept_posted_on_the_ticket_and_continues_the_run() { + let (fake, state) = fixture("needs_input").await; + let out = answer( + &state, + &claims("member"), + RUN, + body(&[ + ("q1", " Production only.\nStaging keeps 100. "), + ("q2", ""), + ]), + ) + .await + .unwrap(); + assert_eq!(out.status, "continuing"); + assert!(ulid::Ulid::from_string(&out.run_id).is_ok()); + assert!(out.posted); + assert_eq!( + out.comment_url.as_deref(), + Some("https://example.atlassian.net/browse/ABC-7?focusedCommentId=10042") + ); + + let f = fake.lock().unwrap(); + // The run is claimed only while it still waits, with the answer. + let updates = f.ops("UpdateItem"); + let claim = &updates[0]; + assert_eq!(claim["ConditionExpression"], "#status = :waiting"); + assert_eq!( + claim["ExpressionAttributeValues"][":waiting"]["S"], + "needs_input" + ); + assert_eq!(claim["ExpressionAttributeValues"][":s"]["S"], "retried"); + assert_eq!(claim["ExpressionAttributeValues"][":nr"]["S"], out.run_id); + let kept: Vec = serde_json::from_str( + claim["ExpressionAttributeValues"][":a"]["S"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(kept.len(), 1, "a blank answer leaves its question open"); + assert_eq!(kept[0].question, "Which environments get the new limit?"); + assert_eq!(kept[0].answer, "Production only.\nStaging keeps 100."); + assert_eq!(kept[0].author, "Pat Doe"); + + // The ticket goes back on the queue as a new run with the answer. + let sent = f.ops("SendMessage"); + assert_eq!(sent.len(), 1); + let msg: Value = serde_json::from_str(sent[0]["MessageBody"].as_str().unwrap()).unwrap(); + assert_eq!(msg["type"], "ticket"); + assert_eq!(msg["ticket_id"], "ABC-7"); + assert_eq!(msg["body"], "Raise the limit."); + assert_eq!(msg["new_run_id"], out.run_id); + assert_eq!( + msg["answers"][0]["answer"], + "Production only.\nStaging keeps 100." + ); + + // The reply is on the ticket, from the person, under the question. + let posted = f.ops("/jira-comment"); + assert_eq!(posted.len(), 1); + assert_eq!(posted[0]["issueKey"], "ABC-7"); + let text = posted[0]["comment"].as_str().unwrap(); + assert!(text.starts_with("Pat Doe answered in CoderHelm:"), "{text}"); + assert!(text.contains("Q: Which environments get the new limit?")); + assert!(text.contains("A: Production only.\nStaging keeps 100.")); + assert!(text.contains("focusedCommentId=10001")); + assert!(!text.contains("What is the new limit?")); + // And its address is kept on the run. + assert_eq!( + updates.last().unwrap()["ExpressionAttributeValues"][":u"]["S"], + "https://example.atlassian.net/browse/ABC-7?focusedCommentId=10042" + ); + } + + #[tokio::test] + async fn a_viewer_cannot_answer() { + let (fake, state) = fixture("needs_input").await; + let err = answer( + &state, + &claims("viewer"), + RUN, + body(&[("q1", "Production")]), + ) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::FORBIDDEN); + assert!( + fake.lock().unwrap().calls.is_empty(), + "nothing read or written" + ); + } + + #[tokio::test] + async fn blank_or_unknown_answers_are_refused_before_anything_changes() { + let (fake, state) = fixture("needs_input").await; + let err = answer(&state, &claims("member"), RUN, body(&[("q1", " ")])) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::BAD_REQUEST); + assert!(err.1["error"].as_str().unwrap().contains("at least one")); + let err = answer(&state, &claims("member"), RUN, body(&[("q9", "yes")])) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::BAD_REQUEST); + let f = fake.lock().unwrap(); + assert!(f.ops("UpdateItem").is_empty()); + assert!(f.ops("SendMessage").is_empty()); + assert!(f.ops("/jira-comment").is_empty()); + } + + #[tokio::test] + async fn a_run_that_moved_on_is_refused() { + // Already answered (or retried) when the page was opened. + let (fake, state) = fixture("retried").await; + let err = answer( + &state, + &claims("member"), + RUN, + body(&[("q1", "Production")]), + ) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::CONFLICT); + assert!(fake.lock().unwrap().ops("SendMessage").is_empty()); + + // Moved on between the read and the write: the claim fails. + let (fake, state) = fixture("needs_input").await; + fake.lock().unwrap().conditions_fail = true; + let err = answer( + &state, + &claims("member"), + RUN, + body(&[("q1", "Production")]), + ) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::CONFLICT); + assert!(err.1["error"].as_str().unwrap().contains("moved on")); + let f = fake.lock().unwrap(); + assert!(f.ops("SendMessage").is_empty(), "no second run"); + assert!(f.ops("/jira-comment").is_empty(), "nothing posted"); + } + + #[tokio::test] + async fn a_run_without_questions_takes_no_answers() { + let (fake, state) = fixture("needs_input").await; + if let Some(run) = fake.lock().unwrap().items.get_mut("runs") { + run.as_object_mut().unwrap().remove("questions"); + } + let err = answer( + &state, + &claims("member"), + RUN, + body(&[("q1", "Production")]), + ) + .await + .unwrap_err(); + assert_eq!(err.0, StatusCode::CONFLICT); + } + + #[test] + fn answering_is_a_runs_action_for_members() { + use crate::permissions::{resolve_access, Access, Holder}; + assert!(matches!( + resolve_access(&Holder::builtin("member"), Some("run_answer::answer_run")), + Access::Allow { .. } + )); + match resolve_access(&Holder::builtin("viewer"), Some("run_answer::answer_run")) { + Access::Deny { capability } => assert_eq!(capability.key, "runs"), + other => panic!("{other:?}"), + } + assert_eq!( + crate::permissions::routed_handler("POST", "/api/runs/:run_id/answer"), + Some("run_answer::answer_run") + ); + } +} diff --git a/services/gateway/src/routes/run_close.rs b/services/gateway/src/routes/run_close.rs index 126e9a26f..b72d828e9 100644 --- a/services/gateway/src/routes/run_close.rs +++ b/services/gateway/src/routes/run_close.rs @@ -406,7 +406,7 @@ async fn load_run(state: &AppState, team_id: &str, run_id: &str) -> Result Option { +pub(crate) async fn profile_name(state: &AppState, claims: &Claims) -> Option { let id = claims.sub.strip_prefix("USER#").unwrap_or(&claims.sub); state .dynamo diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 004b67604..2e30c8c14 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -267,6 +267,8 @@ mod tests { plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, }); let json = serde_json::to_string(&msg).unwrap(); let parsed: WorkerMessage = serde_json::from_str(&json).unwrap(); diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index f08961903..13cd493ba 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1603,6 +1603,8 @@ async fn start_fix_ticket( plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, }; match enqueue(state, crate::models::WorkerMessage::Ticket(ticket)).await { Ok(()) => { @@ -1851,6 +1853,8 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, }; enqueue(state, crate::models::WorkerMessage::Ticket(ticket)).await?; rec.status = "generating".into(); diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 36ed8d026..89fcd340b 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -231,6 +231,8 @@ pub async fn run( plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, }; match super::pr::resolve_conflicts( state, @@ -2250,6 +2252,8 @@ async fn handle_wrong_repo( plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, }); if state.config.ticket_queue_url.is_empty() { diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 81d82fa3b..3cbd15300 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -119,6 +119,8 @@ impl StartEnv for WorkerEnv<'_> { plan_cache_key: None, team_instructions: String::new(), person_direction: None, + answers: Vec::new(), + new_run_id: None, }); let body = serde_json::to_string(&msg).map_err(|e| e.to_string())?; self.state diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 8e1bc7b8c..ad5753c58 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -791,10 +791,17 @@ pub async fn orchestrate_ticket( .as_deref() .map(|s| !s.is_empty()) .unwrap_or(false); + // A fresh run takes the id its sender named, when it is a ULID (an + // answer on the dashboard links the asking run to this one). let run_id = msg .continuation_run_id .clone() .filter(|s| !s.is_empty()) + .or_else(|| { + msg.new_run_id + .clone() + .filter(|s| ulid::Ulid::from_string(s).is_ok()) + }) .unwrap_or_else(|| ulid::Ulid::new().to_string()); let mut usage = TokenUsage::default(); let start = std::time::Instant::now(); @@ -1173,6 +1180,12 @@ async fn run_passes( // the planner is shown it and held to it below. let mut history = ticket_history::load(state, &msg.team_id, &msg.ticket_id, run_id).await; ticket_history::add_pr_comments(&mut history, &github).await; + // Answers people gave in CoderHelm on any earlier stop of this ticket + // count for this run too: triage and the planner read them, and they + // are not asked again. + for r in &history.runs { + common::run_questions::merge(&mut msg.answers, &r.answers); + } // 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 @@ -1645,7 +1658,11 @@ async fn run_passes( let plan_key = plan::plan_cache_key( &context_hash, &memory_context, - &history.digest(), + &format!( + "{}{}", + history.digest(), + common::run_questions::digest(&msg.answers) + ), &msg.team_instructions, &review_key, ); @@ -1803,7 +1820,11 @@ async fn run_passes( msg.plan_cache_key = Some(plan::plan_cache_key( &context_hash, &format!("{memory_context}{ctx}"), - &history.digest(), + &format!( + "{}{}", + history.digest(), + common::run_questions::digest(&msg.answers) + ), &msg.team_instructions, &review_key, )); @@ -2199,37 +2220,34 @@ async fn run_passes( detail, "Plan needs clarification from the ticket author" ); + // The questions, one by one: on the ticket, and kept on the run so + // its page lists them and takes answers. Questions people answered + // already in CoderHelm are not asked again. + let questions = clarification_questions(detail, &msg.answers); + let list_md = common::run_questions::markdown(&questions); + let list_plain = common::run_questions::plain(&questions); let raw_github = format!( - "❓ **Clarification needed**\n\n{detail}\n\nPlease update the issue with the missing details and re-trigger the run." + "❓ **Clarification needed**\n\n{list_md}\n\nReply here, or answer on the run page in \ + CoderHelm, and I'll continue." ); let github_comment = formatter::format_with_voice(state, &voice, &raw_github, &provider, usage).await; let raw_jira = format!( - "{detail}\n\nPlease update the issue with the missing details and comment to re-trigger." + "{list_plain}\n\nReply here, or answer on the run page in CoderHelm, and I'll continue." ); let jira_comment = formatter::format_with_voice(state, &voice, &raw_jira, &provider, usage).await; - - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - let _ = github - .create_issue_comment( - &msg.repo_owner, - &msg.repo_name, - msg.issue_number, - &github_comment, - ) - .await; - } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { - let _ = post_jira_comment( - state, - &msg.team_id, - &msg.ticket_id, - &jira_comment, - "clarification", - "Clarification needed", - ) - .await; - } + ask_on_ticket( + state, + msg, + run_id, + &github, + &questions, + &github_comment, + &jira_comment, + "Clarification needed", + ) + .await; // Mark the run as needs_input so a comment can re-trigger it mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids).await; @@ -3555,32 +3573,24 @@ async fn run_passes( let clarification = formatter::format_with_voice(state, &voice, raw_clarification, &provider, usage) .await; - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - if let Err(e) = github - .create_issue_comment( - &msg.repo_owner, - &msg.repo_name, - msg.issue_number, - &clarification, - ) - .await - { - warn!(run_id, error = %e, "Failed to comment on issue about empty implementation"); - } - } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { - if let Err(e) = post_jira_comment( - state, - &msg.team_id, - &msg.ticket_id, - &clarification, - "clarification", - "More detail needed", - ) - .await - { - warn!(run_id, error = %e, "Failed to comment on Jira ticket about empty implementation"); - } - } + // With no other repo to point at, the two things a person can + // add are asked one by one, so the run page takes the answers. + let questions = if elsewhere_note.is_some() { + Vec::new() + } else { + empty_change_questions() + }; + ask_on_ticket( + state, + msg, + run_id, + &github, + &questions, + &clarification, + &clarification, + "More detail needed", + ) + .await; let duration = start.elapsed().as_secs(); let cost = usage.estimated_cost(); @@ -4827,31 +4837,50 @@ async fn finish_without_code( ); add_progress_note(state, &msg.team_id, run_id, jira_title).await; - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - if let Err(e) = github - .create_issue_comment( - &msg.repo_owner, - &msg.repo_name, - msg.issue_number, - &format!("{heading}{report}"), + let github_body = format!("{heading}{report}"); + let jira_body = fix_location::jira_text(&report); + if outside { + if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { + if let Err(e) = github + .create_issue_comment( + &msg.repo_owner, + &msg.repo_name, + msg.issue_number, + &github_body, + ) + .await + { + warn!(run_id, error = %e, "Could not post the outside-the-code report on the issue"); + } + } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { + if let Err(e) = post_jira_comment( + state, + &msg.team_id, + &msg.ticket_id, + &jira_body, + jira_type, + jira_title, ) .await - { - warn!(run_id, error = %e, "Could not post the outside-the-code report on the issue"); + { + warn!(run_id, error = %e, "Could not post the outside-the-code report on the ticket"); + } } - } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { - if let Err(e) = post_jira_comment( + } else { + // Not knowing where the fix belongs is a question for a person: the + // run page lists the decision's questions and takes the answers. + let questions = unknown_fix_questions(decision, &msg.answers); + ask_on_ticket( state, - &msg.team_id, - &msg.ticket_id, - &fix_location::jira_text(&report), - jira_type, + msg, + run_id, + github, + &questions, + &github_body, + &jira_body, jira_title, ) - .await - { - warn!(run_id, error = %e, "Could not post the outside-the-code report on the ticket"); - } + .await; } if !outside { @@ -5827,7 +5856,22 @@ async fn post_jira_comment( comment_type: &str, title: &str, ) -> Result<(), Box> { - let url = state + post_jira_comment_link(state, team_id, issue_key, comment, comment_type, title) + .await + .map(|_| ()) +} + +/// Posts a comment on a Jira ticket through the team's Jira app and returns +/// the comment's address, when the app said its id and the site is known. +async fn post_jira_comment_link( + state: &WorkerState, + team_id: &str, + issue_key: &str, + comment: &str, + comment_type: &str, + title: &str, +) -> Result, Box> { + let config = state .dynamo .get_item() .table_name(&state.config.jira_config_table_name) @@ -5841,14 +5885,17 @@ async fn post_jira_comment( ) .send() .await? - .item - .and_then(|item| { - item.get("add_comment_url") - .and_then(|v| v.as_s().ok()) - .filter(|s| !s.is_empty()) - .cloned() - }) - .ok_or("No Jira add_comment_url configured")?; + .item; + let field = |k: &str| { + config + .as_ref() + .and_then(|item| item.get(k)) + .and_then(|v| v.as_s().ok()) + .filter(|s| !s.is_empty()) + .cloned() + }; + let url = field("add_comment_url").ok_or("No Jira add_comment_url configured")?; + let site = field("site_url"); let payload = serde_json::json!({ "issueKey": issue_key, @@ -5870,8 +5917,202 @@ async fn post_jira_comment( let body = resp.text().await.unwrap_or_default(); return Err(format!("Jira comment failed ({status}): {body}").into()); } + let id = resp + .json::() + .await + .ok() + .and_then(|v| match &v["id"] { + serde_json::Value::String(s) => Some(s.clone()), + serde_json::Value::Number(n) => Some(n.to_string()), + _ => None, + }); + Ok(jira_comment_link(site.as_deref(), issue_key, id.as_deref())) +} - Ok(()) +/// The address of a comment on a Jira ticket. +fn jira_comment_link(site: Option<&str>, issue_key: &str, id: Option<&str>) -> Option { + let site = site?.trim().trim_end_matches('/'); + if site.is_empty() || issue_key.is_empty() { + return None; + } + Some(match id.filter(|i| !i.is_empty()) { + Some(id) => format!("{site}/browse/{issue_key}?focusedCommentId={id}"), + None => format!("{site}/browse/{issue_key}"), + }) +} + +/// Posts a run's questions on the ticket it came from (`github_body` on a +/// GitHub issue, `jira_body` under `jira_title` on a Jira ticket) and keeps +/// them on the run with the comment's address, so the run page lists them +/// and takes answers. Best effort: a comment that fails is logged, and the +/// questions are kept anyway. +#[allow(clippy::too_many_arguments)] +async fn ask_on_ticket( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + questions: &[common::run_questions::Question], + github_body: &str, + jira_body: &str, + jira_title: &str, +) { + let mut comment_url = None; + if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { + match github + .create_issue_comment( + &msg.repo_owner, + &msg.repo_name, + msg.issue_number, + github_body, + ) + .await + { + Ok(c) => { + comment_url = c["html_url"] + .as_str() + .filter(|u| !u.is_empty()) + .map(str::to_string) + } + Err(e) => warn!(run_id, error = %e, "Could not post the run's questions on the issue"), + } + } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { + match post_jira_comment_link( + state, + &msg.team_id, + &msg.ticket_id, + jira_body, + "clarification", + jira_title, + ) + .await + { + Ok(link) => comment_url = link, + Err(e) => warn!(run_id, error = %e, "Could not post the run's questions on the ticket"), + } + } + record_questions(state, &msg.team_id, run_id, questions, comment_url).await; +} + +/// What a run asks when it wrote no change and the ticket names no other +/// repository: the files, and the behaviour or values. +fn empty_change_questions() -> Vec { + let why = "I ran but made no file changes. If the ticket already says this, Retry: it is \ + usually a one-off miss."; + vec![ + common::run_questions::Question { + id: "q1".to_string(), + question: "Which files or components should change?".to_string(), + why: why.to_string(), + suggestions: Vec::new(), + }, + common::run_questions::Question { + id: "q2".to_string(), + question: "What should happen instead: the expected behaviour, or the exact values or \ + text to use?" + .to_string(), + why: "Without it I can't tell what the finished change looks like.".to_string(), + suggestions: Vec::new(), + }, + ] +} + +/// What a run asks when it doesn't know where the fix belongs: the plan's +/// own questions not answered already, else one question by the kind of +/// ticket, with the cause as its reason. +fn unknown_fix_questions( + decision: &fix_location::FixDecision, + answers: &[common::run_questions::Answer], +) -> Vec { + let own = common::run_questions::unanswered( + common::run_questions::from_lines(&decision.questions), + answers, + ); + if !own.is_empty() { + return own; + } + let question = match decision.intent { + fix_location::TicketIntent::Bug => "Where does the fix belong: which system or part of it?", + fix_location::TicketIntent::Feature | fix_location::TicketIntent::Chore => { + "What else does this need before I build it?" + } + fix_location::TicketIntent::Question => "Does this answer it, or what should happen next?", + }; + vec![common::run_questions::Question { + id: "q1".to_string(), + question: question.to_string(), + why: common::truncate_str( + &decision + .cause + .split_whitespace() + .collect::>() + .join(" "), + 600, + ) + .to_string(), + suggestions: Vec::new(), + }] +} + +/// Keeps what a run asked on its record (see `common::run_questions`). +async fn record_questions( + state: &WorkerState, + team_id: &str, + run_id: &str, + questions: &[common::run_questions::Question], + comment_url: Option, +) { + if questions.is_empty() { + return; + } + let asked = common::run_questions::Asked { + questions: questions.to_vec(), + asked_at: chrono::Utc::now().to_rfc3339(), + comment_url, + }; + let Ok(json) = serde_json::to_string(&asked) else { + return; + }; + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #q = :q") + .expression_attribute_names("#q", common::run_questions::FIELD_QUESTIONS) + .expression_attribute_values(":q", attr_s(&json)) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the run's questions on its record"); + } +} + +/// The questions a plan's `CLARIFICATION_NEEDED:` text asks, less those +/// people answered already. When it asks only answered ones, one question +/// says the answers didn't settle it. +fn clarification_questions( + detail: &str, + answers: &[common::run_questions::Answer], +) -> Vec { + let asked = common::run_questions::parse(detail); + let left = common::run_questions::unanswered(asked.clone(), answers); + if !left.is_empty() || asked.is_empty() { + return left; + } + vec![common::run_questions::Question { + id: "q1".to_string(), + question: + "The answers so far didn't settle it. What else should I know to make this change?" + .to_string(), + why: common::truncate_str( + &detail.split_whitespace().collect::>().join(" "), + 600, + ) + .to_string(), + suggestions: Vec::new(), + }] } /// Check if there is already an active run for this ticket. "Active" means @@ -8634,3 +8875,109 @@ mod open_pr_tests { assert!(!mentions_ticket("anything", "")); } } + +#[cfg(test)] +mod asking_tests { + use super::{clarification_questions, jira_comment_link, unknown_fix_questions}; + use crate::passes::fix_location::{FixDecision, FixLocation, TicketIntent}; + use common::run_questions::Answer; + + fn answered(q: &str, a: &str) -> Answer { + Answer { + question_id: "q1".into(), + question: q.into(), + answer: a.into(), + author: "Pat Doe".into(), + answered_at: "2026-10-27T10:00:00Z".into(), + } + } + + /// The plan's questions are kept one by one, with why and options. + #[test] + fn a_clarification_becomes_questions() { + let qs = clarification_questions( + "- question: Which environments get the new limit?\n why: One value per \ + environment.\n options: Production only | Every environment\n- question: What is \ + the new limit?", + &[], + ); + assert_eq!(qs.len(), 2); + assert_eq!(qs[0].why, "One value per environment."); + assert_eq!(qs[0].suggestions.len(), 2); + } + + /// A question people answered in CoderHelm is not asked again; one + /// still open is. + #[test] + fn an_answered_question_is_not_asked_again() { + let answers = [answered( + "Which environments get the new rate limit?", + "Production only", + )]; + let qs = clarification_questions( + "- question: Which environments should get the new rate limit?\n- question: What \ + should the error message say?", + &answers, + ); + assert_eq!(qs.len(), 1); + assert_eq!(qs[0].question, "What should the error message say?"); + + // Asking only answered questions again: one question says the + // answers didn't settle it, never the same question. + let qs = clarification_questions( + "- question: Which environments should get the new rate limit?", + &answers, + ); + assert_eq!(qs.len(), 1); + assert!(qs[0] + .question + .starts_with("The answers so far didn't settle it")); + assert!(!qs[0].question.contains("environments")); + } + + #[test] + fn not_knowing_where_the_fix_goes_asks_the_plans_questions() { + let d = FixDecision { + fix_location: FixLocation::Unknown, + cause: "Two jobs write the same table.".into(), + intent: TicketIntent::Bug, + questions: vec![ + "Which job should own the table?".into(), + "Is the nightly job still needed?".into(), + ], + ..Default::default() + }; + let qs = unknown_fix_questions( + &d, + &[answered( + "Which job should own the table?", + "The hourly one", + )], + ); + assert_eq!(qs.len(), 1); + assert_eq!(qs[0].question, "Is the nightly job still needed?"); + // No questions of its own: one by the kind of ticket, the cause as why. + let bare = FixDecision { + questions: vec![], + ..d + }; + let qs = unknown_fix_questions(&bare, &[]); + assert_eq!(qs.len(), 1); + assert!(qs[0].question.starts_with("Where does the fix belong")); + assert_eq!(qs[0].why, "Two jobs write the same table."); + } + + #[test] + fn a_jira_comment_link_needs_the_site() { + assert_eq!( + jira_comment_link( + Some("https://example.atlassian.net/"), + "ABC-7", + Some("10001") + ) + .as_deref(), + Some("https://example.atlassian.net/browse/ABC-7?focusedCommentId=10001") + ); + assert_eq!(jira_comment_link(None, "ABC-7", Some("1")), None); + } +} diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index e248de186..3586374e2 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -278,7 +278,17 @@ set tasks.md to EXACTLY `NO_CHANGES_NEEDED: `. **Ambiguous values:** If the issue asks to change a value but does NOT include the new value: 1. Check if the issue body contains URLs. If so, call the appropriate MCP tool to fetch them. 2. Do NOT proactively search external tools unless a URL is present. -3. If you cannot determine the value, set tasks.md to `CLARIFICATION_NEEDED: `. +3. If you cannot determine the value, set tasks.md to `CLARIFICATION_NEEDED:` followed by one + block per question a person must answer (a short plain question; why it blocks the change; + candidate answers you found in the code or the data, separated by `|`, when you have any): + ``` + CLARIFICATION_NEEDED: + - question: Which environments get the new limit? + why: config/limits.yml holds one value per environment. + options: production only | every environment + ``` + Ask only what blocks the change, at most a few questions, and never a question the ticket or + the answers below already settle. Otherwise, generate four openspec files: @@ -329,11 +339,16 @@ Then the ```fix_location.json block described above."#, body = msg.body, complexity_guidance = complexity_guidance, ); - // The ticket's history comes right after the issue's own text. + // The ticket's history comes right after the issue's own text, then + // the answers people gave to an earlier run's questions, word for word. let prompt = match msg.ticket_history_note.as_deref() { Some(h) if !h.trim().is_empty() => format!("{prompt}{h}"), _ => prompt, }; + let prompt = format!( + "{prompt}{}", + common::run_questions::answers_note(&msg.answers) + ); let mut tools = read_only_tools(); @@ -670,7 +685,11 @@ Then the ```fix_location.json block described above."#, let judge_prompt = |files: &PlanResult| { super::plan_judge::prompt( &msg.title, - &msg.body, + &format!( + "{}{}", + msg.body, + common::run_questions::answers_note(&msg.answers) + ), history_note, &live.as_ref().map(|l| l.connected()).unwrap_or_default(), &live @@ -730,6 +749,40 @@ Then the ```fix_location.json block described above."#, } let mut files = parse_openspec_files(&response, intent); + // A plan that asks again what people answered in CoderHelm goes back + // once with the answers; what it still asks after that is filtered when + // the run stops (see `clarification_questions`). + let repeats = common::run_questions::repeated(&files.tasks, &msg.answers); + if !repeats.is_empty() { + info!( + ticket_id = %msg.ticket_id, + repeated = repeats.len(), + "Plan asks an answered question again — sending it back" + ); + messages.push(( + "user".to_string(), + vec![serde_json::json!({ + "type": "text", + "text": common::run_questions::send_back(&repeats, &msg.answers), + })], + )); + response = provider::converse( + state, + provider, + common::agent_policy::Agent::Planner, + model_id, + &full_system, + &mut messages, + &tools, + &executor, + usage, + plan_opts, + None, + None, + ) + .await?; + files = parse_openspec_files(&response, intent); + } let gaps = super::fix_location::gaps(files.fix.as_ref(), can_look_up, lookups(), &read()); if !gaps.is_empty() && msg.person_direction.is_some() { // A person told CoderHelm where the fix is and to go ahead: their diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 62157a6d5..ea903b7a2 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -1566,6 +1566,8 @@ pub async fn run( ) .await, person_direction: None, + answers: Vec::new(), + new_run_id: None, }; let provider = ModelProvider::load_for_team( diff --git a/services/worker/src/passes/ticket_history.rs b/services/worker/src/passes/ticket_history.rs index e6e822a2b..c5df46fad 100644 --- a/services/worker/src/passes/ticket_history.rs +++ b/services/worker/src/passes/ticket_history.rs @@ -37,6 +37,8 @@ pub struct PriorRun { pub context_hash: String, /// What people wrote on its PR, as (author, text), newest last. pub pr_comments: Vec<(String, String)>, + /// Answers people gave in CoderHelm to the questions it stopped to ask. + pub answers: Vec, } impl PriorRun { @@ -556,6 +558,8 @@ fn prior_run(item: &Item) -> PriorRun { fix_decision: serde_json::from_str(&s(item, "fix_decision")).ok(), context_hash: s(item, "context_hash"), pr_comments: Vec::new(), + answers: serde_json::from_str(&s(item, common::run_questions::FIELD_ANSWERS)) + .unwrap_or_default(), } } @@ -1295,4 +1299,24 @@ mod earlier_pr_tests { .plan_gaps("#7 kept; #41 closed by a-maintainer on 2026-01-11, asking why.") .is_empty()); } + + /// Answers given in CoderHelm on an earlier run are read with it (the + /// run merges them into its own, see `passes::run_passes`). + #[test] + fn an_earlier_runs_answers_are_read() { + let mut item = Item::new(); + item.insert("run_id".into(), attr_s("01Q")); + item.insert("status".into(), attr_s("retried")); + item.insert( + "answers".into(), + attr_s( + r#"[{"question_id":"q1","question":"Which environments get the new limit?","answer":"Production only","author":"Pat Doe","answered_at":"2026-10-27T10:00:00Z"}]"#, + ), + ); + let r = prior_run(&item); + assert_eq!(r.answers.len(), 1); + assert_eq!(r.answers[0].answer, "Production only"); + item.remove("answers"); + assert!(prior_run(&item).answers.is_empty()); + } } diff --git a/services/worker/src/passes/triage.rs b/services/worker/src/passes/triage.rs index 10eebd981..9f1a6b1a2 100644 --- a/services/worker/src/passes/triage.rs +++ b/services/worker/src/passes/triage.rs @@ -120,6 +120,13 @@ pub async fn run( "" }; + // Answers people gave to an earlier run's questions are part of the + // ticket. + let body = format!( + "{}{}", + msg.body, + common::run_questions::answers_note(&msg.answers) + ); let prompt = format!( r#"Analyze this GitHub issue and return a JSON classification. @@ -152,7 +159,7 @@ Rules: repo = msg.repo_name, number = msg.issue_number, title = msg.title, - body = msg.body, + body = body, image_hint = image_hint, tree_hint = tree_hint, ); From a28e8731edfe06d68e05d8c0f842139ccd241096 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 11:12:38 -0400 Subject: [PATCH 2/2] Honor replies to the open pull request notice; never ask what is settled The guard that stops when someone else's pull request for the ticket is open now reads the answers to its notice (replies on the Jira ticket or GitHub issue, newest first, and answers on the run page), has the model classify each as own / existing / unclear, and records the first clear one on the ticket's record. Every later run honours it: own opens CoderHelm's own pull request and leaves the other open; existing works on the other pull request's branch. Recorded decisions and earlier answers reach triage and the planner as resolved decisions. Before a plan's questions reach a person, the model judges each against them (covered, or CoderHelm's own call such as closing someone else's pull request); those are sent back once and then dropped. A notice already posted with the same text, or about the same pull request and not answered, is linked instead of posted again. The open pull request notice is a run-page question with its two choices; choosing one records the decision on the ticket. --- docs/api/openapi.json | 12 +- services/common/src/run_questions.rs | 25 +- services/common/src/ticket_state.rs | 202 ++++++++ services/gateway/src/routes/api.rs | 14 +- services/gateway/src/routes/run_answer.rs | 168 ++++++ services/worker/src/passes/mod.rs | 258 ++++++++-- services/worker/src/passes/open_pr_choice.rs | 507 +++++++++++++++++++ services/worker/src/passes/plan.rs | 58 ++- services/worker/src/passes/resolved.rs | 340 +++++++++++++ services/worker/src/passes/review_eval.rs | 1 + services/worker/src/passes/ticket_history.rs | 8 + 11 files changed, 1521 insertions(+), 72 deletions(-) create mode 100644 services/worker/src/passes/open_pr_choice.rs create mode 100644 services/worker/src/passes/resolved.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index eaefaa47e..44f947611 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3255,6 +3255,16 @@ "RunQuestion": { "description": "A question a run asked a person.", "properties": { + "decision": { + "description": "Set when the question is a choice CoderHelm records on the ticket and\nhonours on every later run, such as what to do about a pull request\nsomeone else opened (`open_pr:owner/name#number`).", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, "id": { "description": "The question's id within the run (`q1`, `q2`, ...).", "examples": [ @@ -3270,7 +3280,7 @@ "type": "string" }, "suggestions": { - "description": "Candidate answers the run found in the code or the data.", + "description": "Candidate answers the run found in the code or the data. When\n`decision` is set, these are the choices.", "examples": [ [ "Production only", diff --git a/services/common/src/run_questions.rs b/services/common/src/run_questions.rs index fab42d8c9..3c2989d75 100644 --- a/services/common/src/run_questions.rs +++ b/services/common/src/run_questions.rs @@ -39,6 +39,11 @@ pub struct Question { /// Candidate answers the run found in the code or the data. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub suggestions: Vec, + /// Set when the question is a choice CoderHelm records on the ticket + /// (see `ticket_state::Decision`), e.g. `open_pr:acme/web#12`; its + /// `suggestions` are then the choices. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub decision: String, } /// What a run asked when it stopped, and where it asked it. @@ -67,6 +72,9 @@ pub struct Answer { /// When (RFC 3339). #[serde(default)] pub answered_at: String, + /// The question's `decision` key, when it was a recorded choice. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub decision: String, } /// Why answers were refused. @@ -130,6 +138,7 @@ pub fn validate( answer: text.to_string(), author: author.to_string(), answered_at: now.to_string(), + decision: q.decision.clone(), }) }) .collect(); @@ -240,6 +249,7 @@ fn tidy(questions: Vec) -> Vec { .filter(|s| !s.is_empty()) .take(MAX_SUGGESTIONS) .collect(), + decision: q.decision, }) .collect() } @@ -336,11 +346,14 @@ pub fn answers_note(answers: &[Answer]) -> String { return String::new(); } let mut out = String::from( - "\n\n## Answers to CoderHelm's earlier questions (given in CoderHelm, word for word)\n\ - An earlier run stopped to ask about this ticket, and people answered. Treat each answer \ - as part of the ticket. These questions are settled: plan with the answers and never ask \ - them again. Ask only about something the answers leave open, and say what is still \ - missing.\n", + "\n\n## Resolved decisions (people's answers to CoderHelm's earlier questions and \ + notices, word for word)\n\ + An earlier run stopped to ask about this ticket, or posted a notice on it, and people \ + answered. Treat each answer as part of the ticket. These are settled: plan with them and \ + never ask them again, in any wording. Ask only about something they leave open, and say \ + what is still missing. Never ask a person to settle what CoderHelm decides itself: \ + closing or replacing a pull request someone else opened is never CoderHelm's call; once \ + told to open its own, it leaves the other one open and opens its own.\n", ); for a in answers { out.push_str(&format!( @@ -516,6 +529,7 @@ mod tests { answer: a.into(), author: "Pat Doe".into(), answered_at: "2026-10-27T10:00:00Z".into(), + decision: String::new(), } } @@ -620,6 +634,7 @@ mod tests { assert!(note.contains("Which environments get the new limit?")); assert!(note.contains("Answer from Pat Doe: Production only.\n Staging keeps 100.")); assert!(note.contains("never ask them again")); + assert!(note.contains("Resolved decisions")); assert!(answers_note(&[]).is_empty()); } diff --git a/services/common/src/ticket_state.rs b/services/common/src/ticket_state.rs index aff71b804..7a8775ded 100644 --- a/services/common/src/ticket_state.rs +++ b/services/common/src/ticket_state.rs @@ -85,6 +85,158 @@ pub fn parse_notes(json: &str) -> Vec { serde_json::from_str(json).unwrap_or_default() } +/// Field: decisions people made on CoderHelm's notices and questions, JSON +/// (`Vec`), newest last. Every later run honours them. +pub const FIELD_DECISIONS: &str = "decisions"; +/// Field: the notices CoderHelm posted on the ticket, JSON (`Vec`), +/// newest last, so the same one isn't posted twice. +pub const FIELD_NOTICES: &str = "notices"; +/// Most notices kept on the record. +pub const MAX_NOTICES: usize = 30; + +/// Decision kind: what to do about an open pull request someone else +/// opened for the ticket. `subject` is `owner/name#number`. +pub const KIND_OPEN_PR: &str = "open_pr"; +/// Open CoderHelm's own pull request, leaving the other one as it is. +pub const CHOICE_OWN: &str = "own"; +/// Work on the other pull request instead. +pub const CHOICE_EXISTING: &str = "existing"; + +/// A choice a person made on one of CoderHelm's notices. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Decision { + /// What it decides, e.g. [`KIND_OPEN_PR`]. + pub kind: String, + /// What it is about, e.g. `acme/web#12`. + pub subject: String, + /// The choice, e.g. [`CHOICE_OWN`]. + pub choice: String, + /// What the person wrote, word for word (trimmed). + #[serde(default)] + pub said: String, + /// Who said it, as the ticket shows them. + #[serde(default)] + pub by: String, + /// When it was recorded (RFC 3339). + #[serde(default)] + pub at: String, +} + +impl Decision { + /// The key a question carries for this decision (`kind:subject`). + pub fn key(&self) -> String { + decision_key(&self.kind, &self.subject) + } +} + +/// `kind:subject`, as a question's `decision` field holds it. +pub fn decision_key(kind: &str, subject: &str) -> String { + format!("{kind}:{subject}") +} + +/// A notice CoderHelm posted on the ticket. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Notice { + /// What it is about: a decision key, or `questions` for a list of + /// questions. + pub key: String, + /// A hash of its text: the same text is never posted twice. + pub text_hash: String, + /// The comment's address, when known. + #[serde(default)] + pub url: String, + /// When it was posted (RFC 3339). + #[serde(default)] + pub at: String, +} + +/// The decisions on a record, oldest first; empty when unreadable. +pub fn parse_decisions(json: &str) -> Vec { + serde_json::from_str(json).unwrap_or_default() +} + +/// The notices on a record, oldest first; empty when unreadable. +pub fn parse_notices(json: &str) -> Vec { + serde_json::from_str(json).unwrap_or_default() +} + +/// The newest decision on `key` (`kind:subject`). +pub fn decision_on<'a>(decisions: &'a [Decision], key: &str) -> Option<&'a Decision> { + decisions.iter().rev().find(|d| d.key() == key) +} + +/// `decisions` with `new` in place of any earlier one on the same key. +pub fn with_decision(mut decisions: Vec, new: Decision) -> Vec { + decisions.retain(|d| d.key() != new.key()); + decisions.push(new); + decisions +} + +/// The notice already posted with this exact text, or for this key and not +/// decided since: posting it again only repeats it. +pub fn posted_before<'a>( + notices: &'a [Notice], + key: &str, + text_hash: &str, + decided: bool, +) -> Option<&'a Notice> { + notices + .iter() + .rev() + .find(|n| n.text_hash == text_hash || (!decided && n.key == key && !key.is_empty())) +} + +/// `notices` with `new` added, the oldest dropped past [`MAX_NOTICES`]. +pub fn with_notice(mut notices: Vec, new: Notice) -> Vec { + notices.push(new); + if notices.len() > MAX_NOTICES { + let drop = notices.len() - MAX_NOTICES; + notices.drain(..drop); + } + notices +} + +/// A decision as a settled question and answer, for the run's prompts +/// (see `run_questions::answers_note`). +pub fn decision_answer(d: &Decision) -> crate::run_questions::Answer { + let (question, answer) = match (d.kind.as_str(), d.choice.as_str()) { + (KIND_OPEN_PR, CHOICE_OWN) => ( + format!( + "Pull request {} is already open for this ticket: should CoderHelm work on it, \ + open its own, or close or replace it?", + d.subject + ), + format!( + "Open CoderHelm's own pull request and leave {} open as it is. (They wrote: \"{}\")", + d.subject, d.said + ), + ), + (KIND_OPEN_PR, CHOICE_EXISTING) => ( + format!( + "Pull request {} is already open for this ticket: should CoderHelm work on it, \ + or open its own?", + d.subject + ), + format!( + "Work on {} instead of opening another pull request. (They wrote: \"{}\")", + d.subject, d.said + ), + ), + _ => ( + format!("{} ({})", d.kind, d.subject), + format!("{} (They wrote: \"{}\")", d.choice, d.said), + ), + }; + crate::run_questions::Answer { + question_id: d.key(), + question, + answer, + author: d.by.clone(), + answered_at: d.at.clone(), + decision: d.key(), + } +} + /// Whether a ticket event may start a new run, given the ticket's record: /// a done ticket stays done until its text changes. pub fn done_blocks_run( @@ -114,6 +266,56 @@ mod tests { assert!(!done_blocks_run(None, None, Some("h2"))); } + #[test] + fn a_later_decision_replaces_an_earlier_one_on_the_same_pr() { + let d = |choice: &str| Decision { + kind: KIND_OPEN_PR.into(), + subject: "acme/web#12".into(), + choice: choice.into(), + said: "go ahead".into(), + ..Default::default() + }; + let all = with_decision(vec![d(CHOICE_EXISTING)], d(CHOICE_OWN)); + assert_eq!(all.len(), 1); + assert_eq!( + decision_on(&all, "open_pr:acme/web#12").unwrap().choice, + CHOICE_OWN + ); + assert!(decision_on(&all, "open_pr:acme/web#13").is_none()); + let a = decision_answer(&all[0]); + assert!(a.answer.contains("leave acme/web#12 open")); + assert!(a.answer.contains("\"go ahead\"")); + assert_eq!(a.decision, "open_pr:acme/web#12"); + } + + #[test] + fn a_notice_is_posted_once() { + let n = Notice { + key: "open_pr:acme/web#12".into(), + text_hash: "h1".into(), + url: "https://example.com/c/1".into(), + at: "2026-10-27T10:00:00Z".into(), + }; + let all = with_notice(Vec::new(), n); + // Same text: never again. + assert!(posted_before(&all, "other", "h1", true).is_some()); + // Same subject, not decided yet: link to the earlier one. + assert!(posted_before(&all, "open_pr:acme/web#12", "h2", false).is_some()); + // Decided since, new text: a new notice may go out. + assert!(posted_before(&all, "open_pr:acme/web#12", "h2", true).is_none()); + let many = (0..40).fold(Vec::new(), |acc, i| { + with_notice( + acc, + Notice { + key: format!("k{i}"), + ..Default::default() + }, + ) + }); + assert_eq!(many.len(), MAX_NOTICES); + assert_eq!(many[0].key, "k10"); + } + #[test] fn intents_read_loosely() { assert_eq!( diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 50e974637..ab5dfd4c4 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1044,9 +1044,15 @@ pub struct RunQuestion { /// Why it matters: what it blocks. #[schema(example = "config/limits.yml holds one value per environment.")] pub why: Option, - /// Candidate answers the run found in the code or the data. + /// Candidate answers the run found in the code or the data. When + /// `decision` is set, these are the choices. #[schema(example = json!(["Production only", "Every environment"]))] pub suggestions: Vec, + /// Set when the question is a choice CoderHelm records on the ticket and + /// honours on every later run, such as what to do about a pull request + /// someone else opened (`open_pr:owner/name#number`). + #[schema(example = json!(null))] + pub decision: Option, } /// An answer given in CoderHelm to a run's question. @@ -1337,6 +1343,7 @@ fn run_of(item: &run_search::Item, run_id: &str, usage: RunUsage) -> Run { question: q.question.clone(), why: (!q.why.is_empty()).then(|| q.why.clone()), suggestions: q.suggestions.clone(), + decision: (!q.decision.is_empty()).then(|| q.decision.clone()), }) .collect() }) @@ -5564,8 +5571,9 @@ mod tests { json!([ {"id": "q1", "question": "Which environments get the new limit?", "why": "Each environment has its own value.", - "suggestions": ["Production only", "Every environment"]}, - {"id": "q2", "question": "What is the new limit?", "why": null, "suggestions": []} + "suggestions": ["Production only", "Every environment"], "decision": null}, + {"id": "q2", "question": "What is the new limit?", "why": null, "suggestions": [], + "decision": null} ]) ); assert_eq!( diff --git a/services/gateway/src/routes/run_answer.rs b/services/gateway/src/routes/run_answer.rs index e52bf23fd..61f9d3451 100644 --- a/services/gateway/src/routes/run_answer.rs +++ b/services/gateway/src/routes/run_answer.rs @@ -225,6 +225,15 @@ pub async fn answer( &now, ) .await?; + // A choice made with its button is recorded on the ticket now; words + // typed instead are read by the next run (see the worker's + // `open_pr_choice`), the way a reply on the ticket is. + for (a, d) in answers + .iter() + .filter_map(|a| chosen(&questions, a).map(|d| (a, d))) + { + record_decision(state, &claims.team_id, &s(&item, "ticket_id"), a, d).await; + } let queued = match serde_json::to_string(&WorkerMessage::Ticket(ticket.clone())) { Ok(msg) => { @@ -279,6 +288,84 @@ pub async fn answer( }) } +/// The decision an answer makes when it is one of its question's offered +/// choices, word for word: for an open pull request, "Work on #N" works on +/// it and "Open my own" opens CoderHelm's own. `(kind, subject, choice)`. +pub fn chosen( + questions: &[run_questions::Question], + answer: &Answer, +) -> Option<(String, String, &'static str)> { + let q = questions.iter().find(|q| q.id == answer.question_id)?; + let (kind, subject) = q.decision.split_once(':')?; + if kind != common::ticket_state::KIND_OPEN_PR + || !q.suggestions.iter().any(|s| s == &answer.answer) + { + return None; + } + let number = subject.rsplit_once('#')?.1; + let choice = if answer.answer == format!("Work on #{number}") { + common::ticket_state::CHOICE_EXISTING + } else if answer.answer == "Open my own" { + common::ticket_state::CHOICE_OWN + } else { + return None; + }; + Some((kind.to_string(), subject.to_string(), choice)) +} + +/// Records a choice on the ticket's record, in place of an earlier one. +async fn record_decision( + state: &AppState, + team_id: &str, + ticket_id: &str, + answer: &Answer, + (kind, subject, choice): (String, String, &'static str), +) { + use common::ticket_state as ts; + let earlier = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(ts::sk(ticket_id))) + .consistent_read(true) + .send() + .await + .ok() + .and_then(|o| o.item) + .map(|i| ts::parse_decisions(&s(&i, ts::FIELD_DECISIONS))) + .unwrap_or_default(); + let all = ts::with_decision( + earlier, + ts::Decision { + kind, + subject, + choice: choice.to_string(), + said: answer.answer.clone(), + by: answer.author.clone(), + at: answer.answered_at.clone(), + }, + ); + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(ts::sk(ticket_id))) + .update_expression("SET #d = :d, updated_at = :t") + .expression_attribute_names("#d", ts::FIELD_DECISIONS) + .expression_attribute_values( + ":d", + AttributeValue::S(serde_json::to_string(&all).unwrap_or_default()), + ) + .expression_attribute_values(":t", AttributeValue::S(answer.answered_at.clone())) + .send() + .await + { + warn!(ticket_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "answer: could not record the choice on the ticket"); + } +} + /// Marks the run answered, only while it still waits: two answers or an /// answer and a Retry at once leave exactly one run going. async fn claim( @@ -514,6 +601,42 @@ mod tests { .contains("needs outside change")); } + #[test] + fn a_choice_button_records_the_decision_typed_words_do_not() { + let q = run_questions::Question { + id: "q1".into(), + question: "A pull request is already open: work on #12, or open my own?".into(), + suggestions: vec!["Work on #12".into(), "Open my own".into()], + decision: "open_pr:acme/web#12".into(), + ..Default::default() + }; + let a = |text: &str| Answer { + question_id: "q1".into(), + answer: text.into(), + ..Default::default() + }; + assert_eq!( + chosen(std::slice::from_ref(&q), &a("Open my own")), + Some(("open_pr".into(), "acme/web#12".into(), "own")) + ); + assert_eq!( + chosen(std::slice::from_ref(&q), &a("Work on #12")) + .unwrap() + .2, + "existing" + ); + // Typed words are read by the next run's model, not matched here. + assert_eq!( + chosen(std::slice::from_ref(&q), &a("go ahead with yours")), + None + ); + let plain = run_questions::Question { + decision: String::new(), + ..q + }; + assert_eq!(chosen(&[plain], &a("Open my own")), None); + } + #[test] fn jira_links_point_at_the_comment() { assert_eq!( @@ -800,6 +923,51 @@ mod tests { ); } + /// The open pull request notice, answered with its "Open my own" button: + /// the choice is on the ticket's record before the next run starts. + #[tokio::test] + async fn choosing_open_my_own_records_the_decision_on_the_ticket() { + let (fake, state) = fixture("needs_input").await; + let asked = json!({ + "questions": [{ + "id": "q1", + "question": "A pull request is already open: work on #12, or open my own?", + "suggestions": ["Work on #12", "Open my own"], + "decision": "open_pr:acme/web#12" + }] + }); + fake.lock().unwrap().items.get_mut("runs").unwrap()["questions"] = + json!({"S": asked.to_string()}); + answer( + &state, + &claims("member"), + RUN, + body(&[("q1", "Open my own")]), + ) + .await + .unwrap(); + let f = fake.lock().unwrap(); + let recorded = f + .ops("UpdateItem") + .into_iter() + .find(|u| u["TableName"] == "settings") + .expect("the decision is written to the ticket's record"); + assert_eq!(recorded["Key"]["sk"]["S"], "TICKETSTATE#ABC-7"); + let decisions: Vec = serde_json::from_str( + recorded["ExpressionAttributeValues"][":d"]["S"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(decisions.len(), 1); + assert_eq!(decisions[0].subject, "acme/web#12"); + assert_eq!(decisions[0].choice, "own"); + // And the run that continues carries the answer with its key. + let sent = f.ops("SendMessage"); + let msg: Value = serde_json::from_str(sent[0]["MessageBody"].as_str().unwrap()).unwrap(); + assert_eq!(msg["answers"][0]["decision"], "open_pr:acme/web#12"); + } + #[tokio::test] async fn a_viewer_cannot_answer() { let (fake, state) = fixture("needs_input").await; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index ad5753c58..41dfdab83 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -718,6 +718,7 @@ mod log_fix_checks; mod log_fix_eval; pub mod model_check; pub mod onboard; +pub mod open_pr_choice; pub mod ops_tools; mod plan; pub mod plan_chat; @@ -735,6 +736,7 @@ pub mod release_notes; pub mod remote_mcp; pub(crate) mod repo_pick; mod resolve; +mod resolved; pub mod resume; mod review; pub mod review_actions; @@ -1186,6 +1188,14 @@ async fn run_passes( for r in &history.runs { common::run_questions::merge(&mut msg.answers, &r.answers); } + // So do the choices people made on CoderHelm's notices (an open pull + // request: work on it, or open CoderHelm's own), as settled questions. + let decided: Vec = history + .decisions + .iter() + .map(common::ticket_state::decision_answer) + .collect(); + common::run_questions::merge(&mut msg.answers, &decided); // 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 @@ -2260,10 +2270,18 @@ async fn run_passes( // The team's branch/commit/PR title templates, read once for the run. let conventions = load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; let tokens = ticket_tokens(msg); + // A pull request someone else opened for this ticket: what a person + // decided about it (their replies to CoderHelm's notice, read newest + // first and recorded on the ticket, so every later run honours them). + // `own`: open CoderHelm's own and leave the other one as it is. + // `existing`: work on the other one's branch. Undecided: the guard below + // stops and asks, once. + let mut open_pr_settled = msg.person_direction.is_some(); + let mut other_open_pr: Option = None; let branch_name = if can_skip_implement { checkpoint.as_ref().unwrap().1.clone() } else { - resolve_run_branch( + let own_branch = resolve_run_branch( &github, &msg.repo_owner, &msg.repo_name, @@ -2272,7 +2290,51 @@ async fn run_passes( &tokens, "", ) + .await; + match open_pr_for_ticket( + &github, + &msg.repo_owner, + &msg.repo_name, + &msg.ticket_id, + &own_branch, + ) .await + { + Some(other) if !open_pr_settled => { + match open_pr_choice::decide(state, &provider, msg, &github, &other, usage).await { + open_pr_choice::Choice::Own => { + open_pr_settled = true; + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Opening my own pull request, as a person said; #{} stays open as it is.", + other.number + ), + ) + .await; + own_branch + } + open_pr_choice::Choice::Existing if other.same_repo => { + open_pr_settled = true; + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Working on #{}, as a person said.", other.number), + ) + .await; + other.head.clone() + } + _ => { + other_open_pr = Some(other); + own_branch + } + } + } + _ => own_branch, + } }; let impl_result = if can_skip_implement { @@ -2349,20 +2411,11 @@ async fn run_passes( } }; // Someone else's open pull request for this ticket (a person's, or an - // earlier run's on another branch): don't open a second one unless a - // person said to go ahead. - if existing_pr.is_none() && msg.person_direction.is_none() { - if let Some(other) = open_pr_for_ticket( - &github, - &msg.repo_owner, - &msg.repo_name, - &msg.ticket_id, - &branch_name, - ) - .await - { - let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); - stop_for_open_pr(state, msg, &github, run_id, usage, start, &repo, &other).await; + // earlier run's on another branch), and nobody has said what to do + // about it: don't open a second one; ask (once). + if existing_pr.is_none() && !open_pr_settled { + if let Some(other) = other_open_pr.as_ref() { + stop_for_open_pr(state, msg, &github, run_id, usage, start, other).await; close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -3149,7 +3202,8 @@ async fn run_passes( } // A pull request for this ticket already open in any of the repos - // (a person's, or an earlier run's): none is opened twice. + // (a person's, or an earlier run's): none is opened twice, unless + // a person said to open CoderHelm's own. if msg.person_direction.is_none() { for (repo_task, own) in plan_result.repo_tasks.iter().zip(&repo_branches) { if let Some(other) = open_pr_for_ticket( @@ -3161,9 +3215,13 @@ async fn run_passes( ) .await { - let repo = format!("{}/{}", repo_task.owner, repo_task.name); - stop_for_open_pr(state, msg, &github, run_id, usage, start, &repo, &other) - .await; + let choice = + open_pr_choice::decide(state, &provider, msg, &github, &other, usage) + .await; + if choice == open_pr_choice::Choice::Own { + continue; + } + stop_for_open_pr(state, msg, &github, run_id, usage, start, &other).await; close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -5742,16 +5800,17 @@ pub fn is_own_login(login: &str) -> bool { } /// An open pull request in `owner/name` that already names the ticket (in -/// its title, branch or description), other than the one on `own_branch`: -/// `(number, title, author)`. A failed lookup finds none. +/// its title, branch or description), other than the one on `own_branch`. +/// A failed lookup finds none. async fn open_pr_for_ticket( github: &GitHubClient, owner: &str, name: &str, ticket: &str, own_branch: &str, -) -> Option<(u64, String, String)> { +) -> Option { let prs = github.list_open_pulls(owner, name).await.ok()?; + let repo = format!("{owner}/{name}"); prs.as_array()?.iter().find_map(|p| { let head = p["head"]["ref"].as_str().unwrap_or(""); let title = p["title"].as_str().unwrap_or(""); @@ -5760,12 +5819,15 @@ async fn open_pr_for_ticket( && (mentions_ticket(title, ticket) || mentions_ticket(head, ticket) || mentions_ticket(body, ticket))) - .then(|| { - ( - p["number"].as_u64().unwrap_or(0), - title.to_string(), - p["user"]["login"].as_str().unwrap_or("").to_string(), - ) + .then(|| open_pr_choice::OtherPr { + repo: repo.clone(), + number: p["number"].as_u64().unwrap_or(0), + title: title.to_string(), + author: p["user"]["login"].as_str().unwrap_or("").to_string(), + head: head.to_string(), + same_repo: p["head"]["repo"]["full_name"] + .as_str() + .is_some_and(|f| f.eq_ignore_ascii_case(&repo)), }) }) } @@ -5793,8 +5855,8 @@ async fn repo_of_ticket_pr( let Some((owner, name)) = r.split_once('/') else { continue; }; - if let Some((number, _, _)) = open_pr_for_ticket(github, owner, name, ticket_id, "").await { - found.push((r.clone(), number)); + if let Some(pr) = open_pr_for_ticket(github, owner, name, ticket_id, "").await { + found.push((r.clone(), pr.number)); } } match found.as_slice() { @@ -5806,8 +5868,10 @@ async fn repo_of_ticket_pr( } } -/// Stops a run because a pull request for its ticket is already open: says -/// so on the ticket and the run, and waits for a person to say what to do. +/// Stops a run because a pull request for its ticket is already open and +/// nobody has said what to do about it: posts the notice on the ticket +/// (once: a notice already posted and not answered is linked, never +/// repeated) and leaves the choice on the run page as a question. #[allow(clippy::too_many_arguments)] async fn stop_for_open_pr( state: &WorkerState, @@ -5816,35 +5880,29 @@ async fn stop_for_open_pr( run_id: &str, usage: &TokenUsage, start: &std::time::Instant, - repo: &str, - pr: &(u64, String, String), + pr: &open_pr_choice::OtherPr, ) { - let note = format!( - "An open pull request for {} already exists in {repo}: #{} \"{}\" by {}. I didn't open another. Reply here to have me work on that pull request, or to go ahead with my own.", - msg.ticket_id, pr.0, pr.1, pr.2 - ); + let note = open_pr_choice::notice_text(&msg.ticket_id, pr); info!( run_id, - repo, - pr = pr.0, + repo = %pr.repo, + pr = pr.number, "Open pull request for the ticket exists — not opening another" ); add_progress_note(state, &msg.team_id, run_id, ¬e).await; - if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { - let _ = github - .create_issue_comment(&msg.repo_owner, &msg.repo_name, msg.issue_number, ¬e) - .await; - } else if matches!(msg.source, TicketSource::Jira) && !msg.ticket_id.is_empty() { - let _ = post_jira_comment( - state, - &msg.team_id, - &msg.ticket_id, - ¬e, - "clarification", - "A pull request is already open", - ) - .await; - } + let question = open_pr_choice::notice_question(pr); + ask_on_ticket_keyed( + state, + msg, + run_id, + github, + std::slice::from_ref(&question), + ¬e, + ¬e, + "A pull request is already open", + &pr.key(), + ) + .await; mark_run_needs_input(state, msg, run_id, usage, start, &[]).await; } @@ -5957,7 +6015,72 @@ async fn ask_on_ticket( jira_body: &str, jira_title: &str, ) { + ask_on_ticket_keyed( + state, + msg, + run_id, + github, + questions, + github_body, + jira_body, + jira_title, + "", + ) + .await +} + +/// [`ask_on_ticket`], for a notice about `key` (a decision key, or empty): +/// one already posted with the same text, or about the same key and not +/// decided since, is linked instead of posted again. +#[allow(clippy::too_many_arguments)] +async fn ask_on_ticket_keyed( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + questions: &[common::run_questions::Question], + github_body: &str, + jira_body: &str, + jira_title: &str, + key: &str, +) { + let text_hash = common::sha256_hex(&[ + &questions + .iter() + .map(|q| q.question.as_str()) + .collect::>() + .join("\n"), + key, + ]); + let rec = open_pr_choice::load_record(state, &msg.team_id, &msg.ticket_id).await; + let decided = common::ticket_state::decision_on(&rec.decisions, key).is_some(); + if let Some(earlier) = + common::ticket_state::posted_before(&rec.notices, key, &text_hash, decided) + { + info!( + run_id, + key, "Same notice posted before — linking it instead of posting again" + ); + add_progress_note( + state, + &msg.team_id, + run_id, + &if earlier.url.is_empty() { + "Still waiting on the answer to my earlier comment on the ticket.".to_string() + } else { + format!( + "Still waiting on the answer to my earlier comment: {}", + earlier.url + ) + }, + ) + .await; + let url = (!earlier.url.is_empty()).then(|| earlier.url.clone()); + record_questions(state, &msg.team_id, run_id, questions, url).await; + return; + } let mut comment_url = None; + let mut posted = false; if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { match github .create_issue_comment( @@ -5969,6 +6092,7 @@ async fn ask_on_ticket( .await { Ok(c) => { + posted = true; comment_url = c["html_url"] .as_str() .filter(|u| !u.is_empty()) @@ -5987,10 +6111,27 @@ async fn ask_on_ticket( ) .await { - Ok(link) => comment_url = link, + Ok(link) => { + posted = true; + comment_url = link + } Err(e) => warn!(run_id, error = %e, "Could not post the run's questions on the ticket"), } } + if posted && !questions.is_empty() { + open_pr_choice::record_notice( + state, + &msg.team_id, + &msg.ticket_id, + common::ticket_state::Notice { + key: key.to_string(), + text_hash, + url: comment_url.clone().unwrap_or_default(), + at: chrono::Utc::now().to_rfc3339(), + }, + ) + .await; + } record_questions(state, &msg.team_id, run_id, questions, comment_url).await; } @@ -6005,6 +6146,7 @@ fn empty_change_questions() -> Vec { question: "Which files or components should change?".to_string(), why: why.to_string(), suggestions: Vec::new(), + decision: String::new(), }, common::run_questions::Question { id: "q2".to_string(), @@ -6013,6 +6155,7 @@ fn empty_change_questions() -> Vec { .to_string(), why: "Without it I can't tell what the finished change looks like.".to_string(), suggestions: Vec::new(), + decision: String::new(), }, ] } @@ -6051,6 +6194,7 @@ fn unknown_fix_questions( ) .to_string(), suggestions: Vec::new(), + decision: String::new(), }] } @@ -6112,6 +6256,7 @@ fn clarification_questions( ) .to_string(), suggestions: Vec::new(), + decision: String::new(), }] } @@ -8889,6 +9034,7 @@ mod asking_tests { answer: a.into(), author: "Pat Doe".into(), answered_at: "2026-10-27T10:00:00Z".into(), + decision: String::new(), } } diff --git a/services/worker/src/passes/open_pr_choice.rs b/services/worker/src/passes/open_pr_choice.rs new file mode 100644 index 000000000..c2f4e41db --- /dev/null +++ b/services/worker/src/passes/open_pr_choice.rs @@ -0,0 +1,507 @@ +//! What to do about a pull request someone else already opened for the +//! ticket: work on it, or open CoderHelm's own. +//! +//! CoderHelm never opens a second pull request for a ticket on its own. It +//! posts a notice and waits. The person's answer can come as a reply on the +//! ticket (Jira) or the issue (GitHub), or as an answer on the run page. Every +//! run reads those answers here, newest first, has the model say which choice +//! each one makes (structured output: `own`, `existing` or `unclear`), and +//! records the first clear one on the ticket's record +//! (`ticket_state::Decision`), so every later run honours it without asking +//! again. Closing the other pull request is never CoderHelm's call: `own` +//! leaves it open. + +use crate::agent::provider::ModelProvider; +use crate::models::{TicketMessage, TicketSource, TokenUsage}; +use crate::passes::attr_s; +use crate::WorkerState; +use common::run_questions::{Answer, Question}; +use common::ticket_state::{self, Decision, Note, Notice, CHOICE_EXISTING, CHOICE_OWN}; +use serde_json::{json, Value}; +use tracing::{info, warn}; + +/// Most replies read for one decision. +const MAX_REPLIES: usize = 6; + +/// A pull request for the ticket that isn't CoderHelm's own for this run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OtherPr { + /// `owner/name`. + pub repo: String, + pub number: u64, + pub title: String, + pub author: String, + /// Its branch. + pub head: String, + /// Its branch is in `repo` itself (not a fork): CoderHelm can push to it. + pub same_repo: bool, +} + +impl OtherPr { + /// `owner/name#number`. + pub fn subject(&self) -> String { + format!("{}#{}", self.repo, self.number) + } + + /// The decision key questions and notices carry. + pub fn key(&self) -> String { + ticket_state::decision_key(ticket_state::KIND_OPEN_PR, &self.subject()) + } +} + +/// What a person chose. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Choice { + Own, + Existing, + Unclear, +} + +impl Choice { + pub fn parse(s: &str) -> Choice { + match s.trim().to_ascii_lowercase().as_str() { + "own" => Choice::Own, + "existing" => Choice::Existing, + _ => Choice::Unclear, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Choice::Own => CHOICE_OWN, + Choice::Existing => CHOICE_EXISTING, + Choice::Unclear => "unclear", + } + } +} + +/// The notice CoderHelm posts, word for word. +pub fn notice_text(ticket_id: &str, pr: &OtherPr) -> String { + format!( + "An open pull request for {ticket_id} already exists in {}: #{} \"{}\"{}. I didn't open \ + another. Reply here to have me work on that pull request, or to go ahead with my own.", + pr.repo, + pr.number, + pr.title, + if pr.author.is_empty() { + String::new() + } else { + format!(" by {}", pr.author) + } + ) +} + +/// The notice as a question on the run page: two choices as buttons. +pub fn notice_question(pr: &OtherPr) -> Question { + Question { + id: "q1".to_string(), + question: format!( + "A pull request is already open: work on #{}, or open my own?", + pr.number + ), + why: format!( + "#{} \"{}\" in {} already names this ticket, so I didn't open another. Opening my \ + own leaves #{} open as it is.", + pr.number, pr.title, pr.repo, pr.number + ), + suggestions: vec![ + choice_label(Choice::Existing, pr), + choice_label(Choice::Own, pr), + ], + decision: pr.key(), + } +} + +/// The words of a choice's button. +pub fn choice_label(choice: Choice, pr: &OtherPr) -> String { + match choice { + Choice::Existing => format!("Work on #{}", pr.number), + _ => "Open my own".to_string(), + } +} + +/// One answer to the notice, from wherever it was given. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reply { + pub author: String, + pub text: String, + /// RFC 3339. + pub at: String, +} + +/// The answers to the notice about `pr`, newest first: answers on the run +/// page to the notice's question, and replies people wrote on the ticket +/// (Jira `notes`) or the issue (GitHub `comments`) after the notice was +/// posted (`since`; every reply when unknown, as for a notice posted before +/// notices were recorded). +pub fn replies( + key: &str, + answers: &[Answer], + notes: &[Note], + comments: &[Value], + since: Option<&str>, +) -> Vec { + let after = |at: &str| since.is_none_or(|s| at > s); + let mut out: Vec = Vec::new(); + for a in answers.iter().filter(|a| a.decision == key) { + out.push(Reply { + author: a.author.clone(), + text: a.answer.clone(), + at: a.answered_at.clone(), + }); + } + for n in notes.iter().filter(|n| after(&n.at)) { + out.push(Reply { + author: n.author.clone(), + text: n.text.clone(), + at: n.at.clone(), + }); + } + for c in comments { + let login = c["user"]["login"].as_str().unwrap_or(""); + let bot = c["user"]["type"].as_str() == Some("Bot") || super::is_own_login(login); + let at = c["created_at"].as_str().unwrap_or(""); + let text = c["body"].as_str().unwrap_or("").trim(); + if !bot && !text.is_empty() && after(at) { + out.push(Reply { + author: login.to_string(), + text: text.to_string(), + at: at.to_string(), + }); + } + } + out.sort_by(|a, b| b.at.cmp(&a.at)); + out.truncate(MAX_REPLIES); + out +} + +pub const SYSTEM: &str = "CoderHelm, an automated coding agent, found a pull request someone \ + else already opened for a ticket, so it did not open its own and posted a notice asking \ + what to do. You read one reply a person wrote after that notice and say which choice it \ + makes. own: CoderHelm should go ahead and open its own pull request (\"go ahead\", \"open \ + your own\", \"ignore that one\", \"that PR is stale, start fresh\"). existing: CoderHelm \ + should work on, update or take over the existing pull request. unclear: the reply doesn't \ + choose (it is about something else, asks a question, or is ambiguous). Judge the reply's \ + meaning, not its words. Closing the other pull request is not part of either choice."; + +pub fn schema() -> Value { + json!({ + "type": "object", + "properties": { + "choice": {"type": "string", "enum": ["own", "existing", "unclear"]}, + "reason": {"type": "string"} + }, + "required": ["choice", "reason"], + "additionalProperties": false + }) +} + +pub fn prompt(notice: &str, reply: &Reply) -> String { + format!( + "## CoderHelm's notice\n{notice}\n\n## The reply (by {})\n{}\n", + if reply.author.trim().is_empty() { + "a person" + } else { + reply.author.trim() + }, + common::truncate_str(reply.text.trim(), 4000) + ) +} + +/// The model's reading of one reply; `Unclear` when it couldn't be read. +async fn classify( + state: &WorkerState, + provider: &ModelProvider, + notice: &str, + reply: &Reply, + usage: &mut TokenUsage, +) -> Choice { + match crate::agent::anthropic::converse_json( + &provider.client(), + &state.config.light_model_id, + SYSTEM, + &prompt(notice, reply), + &schema(), + true, + "low", + 512, + usage, + ) + .await + { + Ok(v) => { + let c = Choice::parse(v["choice"].as_str().unwrap_or("")); + info!( + choice = c.as_str(), + reason = v["reason"].as_str().unwrap_or(""), + "Read a reply to the open pull request notice" + ); + c + } + Err(e) => { + warn!(error = %e, "Could not read a reply to the open pull request notice"); + Choice::Unclear + } + } +} + +/// The ticket's record: decisions and notices CoderHelm keeps on it. +#[derive(Debug, Clone, Default)] +pub struct Record { + pub decisions: Vec, + pub notices: Vec, + pub notes: Vec, +} + +pub async fn load_record(state: &WorkerState, team_id: &str, ticket_id: &str) -> Record { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&ticket_state::sk(ticket_id))) + .consistent_read(true) + .send() + .await + .ok() + .and_then(|o| o.item); + let field = |k: &str| { + item.as_ref() + .and_then(|i| i.get(k)) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + Record { + decisions: ticket_state::parse_decisions(&field(ticket_state::FIELD_DECISIONS)), + notices: ticket_state::parse_notices(&field(ticket_state::FIELD_NOTICES)), + notes: ticket_state::parse_notes(&field(ticket_state::FIELD_NOTES)), + } +} + +async fn save_field( + state: &WorkerState, + team_id: &str, + ticket_id: &str, + field: &str, + json: String, +) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&ticket_state::sk(ticket_id))) + .update_expression("SET #f = :v, updated_at = :t") + .expression_attribute_names("#f", field) + .expression_attribute_values(":v", attr_s(&json)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + { + warn!(ticket_id, field, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not update the ticket's record"); + } +} + +/// Records a decision on the ticket, in place of an earlier one on the +/// same subject. +pub async fn record_decision(state: &WorkerState, team_id: &str, ticket_id: &str, d: Decision) { + let rec = load_record(state, team_id, ticket_id).await; + let all = ticket_state::with_decision(rec.decisions, d); + save_field( + state, + team_id, + ticket_id, + ticket_state::FIELD_DECISIONS, + serde_json::to_string(&all).unwrap_or_default(), + ) + .await; +} + +/// Records a notice posted on the ticket. +pub async fn record_notice(state: &WorkerState, team_id: &str, ticket_id: &str, n: Notice) { + let rec = load_record(state, team_id, ticket_id).await; + let all = ticket_state::with_notice(rec.notices, n); + save_field( + state, + team_id, + ticket_id, + ticket_state::FIELD_NOTICES, + serde_json::to_string(&all).unwrap_or_default(), + ) + .await; +} + +/// What a person decided about `pr`: the recorded decision, else the first +/// clear answer among the replies to the notice (newest first), which is +/// then recorded. `Unclear` when nobody has chosen. +pub async fn decide( + state: &WorkerState, + provider: &ModelProvider, + msg: &TicketMessage, + github: &crate::clients::github::GitHubClient, + pr: &OtherPr, + usage: &mut TokenUsage, +) -> Choice { + let key = pr.key(); + let rec = load_record(state, &msg.team_id, &msg.ticket_id).await; + if let Some(d) = ticket_state::decision_on(&rec.decisions, &key) { + return Choice::parse(&d.choice); + } + let since = rec + .notices + .iter() + .find(|n| n.key == key) + .map(|n| n.at.clone()); + let comments = if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { + github + .list_issue_comments(&msg.repo_owner, &msg.repo_name, msg.issue_number) + .await + .unwrap_or_default() + } else { + Vec::new() + }; + let notes = if matches!(msg.source, TicketSource::Jira) { + rec.notes + } else { + Vec::new() + }; + let notice = notice_text(&msg.ticket_id, pr); + for reply in replies(&key, &msg.answers, ¬es, &comments, since.as_deref()) { + let choice = classify(state, provider, ¬ice, &reply, usage).await; + if choice == Choice::Unclear { + continue; + } + record_decision( + state, + &msg.team_id, + &msg.ticket_id, + Decision { + kind: ticket_state::KIND_OPEN_PR.to_string(), + subject: pr.subject(), + choice: choice.as_str().to_string(), + said: common::truncate_str(reply.text.trim(), 600).to_string(), + by: reply.author, + at: chrono::Utc::now().to_rfc3339(), + }, + ) + .await; + return choice; + } + Choice::Unclear +} + +#[cfg(test)] +mod tests { + use super::*; + use common::ticket_state::Intent; + + fn pr() -> OtherPr { + OtherPr { + repo: "acme/web".into(), + number: 12, + title: "Fix the sign-up form".into(), + author: "a-maintainer".into(), + head: "fix/sign-up".into(), + same_repo: true, + } + } + + fn note(text: &str, at: &str) -> Note { + Note { + author: "A Teammate".into(), + text: text.into(), + intent: Intent::Other, + at: at.into(), + } + } + + #[test] + fn the_notice_becomes_a_choice_on_the_run_page() { + let q = notice_question(&pr()); + assert_eq!( + q.question, + "A pull request is already open: work on #12, or open my own?" + ); + assert_eq!(q.suggestions, vec!["Work on #12", "Open my own"]); + assert_eq!(q.decision, "open_pr:acme/web#12"); + assert!(q.why.contains("leaves #12 open")); + assert!( + notice_text("ABC-7", &pr()).contains("#12 \"Fix the sign-up form\" by a-maintainer") + ); + } + + #[test] + fn replies_are_read_newest_first_and_only_after_the_notice() { + let answers = vec![ + Answer { + question_id: "q1".into(), + question: "A pull request is already open: work on #12, or open my own?".into(), + answer: "Open my own".into(), + author: "A Teammate".into(), + answered_at: "2026-10-27T12:00:00Z".into(), + decision: "open_pr:acme/web#12".into(), + }, + // An answer to another question is not a reply to this notice. + Answer { + question_id: "q1".into(), + question: "Which page?".into(), + answer: "Pricing".into(), + answered_at: "2026-10-27T13:00:00Z".into(), + ..Default::default() + }, + ]; + let notes = vec![ + note("Before the notice", "2026-10-27T08:00:00Z"), + note( + "@coderhelm Go ahead and open your own", + "2026-10-27T11:00:00Z", + ), + ]; + let comments = vec![ + json!({"user": {"login": "coderhelm[bot]", "type": "Bot"}, "body": "notice", "created_at": "2026-10-27T10:00:00Z"}), + json!({"user": {"login": "someone", "type": "User"}, "body": "work on that one", "created_at": "2026-10-27T10:30:00Z"}), + ]; + let r = replies( + "open_pr:acme/web#12", + &answers, + ¬es, + &comments, + Some("2026-10-27T09:00:00Z"), + ); + let texts: Vec<&str> = r.iter().map(|r| r.text.as_str()).collect(); + assert_eq!( + texts, + vec![ + "Open my own", + "@coderhelm Go ahead and open your own", + "work on that one" + ] + ); + // No notice on record (posted before notices were kept): every reply. + assert_eq!( + replies("open_pr:acme/web#12", &[], ¬es, &[], None).len(), + 2 + ); + } + + #[test] + fn the_classifier_is_asked_for_one_of_three_choices() { + assert_eq!( + schema()["properties"]["choice"]["enum"], + json!(["own", "existing", "unclear"]) + ); + let p = prompt( + ¬ice_text("ABC-7", &pr()), + &Reply { + author: "".into(), + text: "Go ahead and open your own".into(), + at: String::new(), + }, + ); + assert!(p.contains("## The reply (by a person)\nGo ahead and open your own")); + assert_eq!(Choice::parse("Own"), Choice::Own); + assert_eq!(Choice::parse("existing"), Choice::Existing); + assert_eq!(Choice::parse("maybe"), Choice::Unclear); + } +} diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 3586374e2..755287cd9 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -288,7 +288,9 @@ set tasks.md to EXACTLY `NO_CHANGES_NEEDED: `. options: production only | every environment ``` Ask only what blocks the change, at most a few questions, and never a question the ticket or - the answers below already settle. + the resolved decisions below already settle. Never ask a person to decide what is CoderHelm's + own call: closing or replacing a pull request someone else opened is never asked; when told to + open its own, it leaves the other one open. Otherwise, generate four openspec files: @@ -749,21 +751,30 @@ Then the ```fix_location.json block described above."#, } let mut files = parse_openspec_files(&response, intent); - // A plan that asks again what people answered in CoderHelm goes back - // once with the answers; what it still asks after that is filtered when - // the run stops (see `clarification_questions`). - let repeats = common::run_questions::repeated(&files.tasks, &msg.answers); + // A plan that asks what is settled on the ticket (answers given in + // CoderHelm, choices people made on its notices), or what CoderHelm + // decides itself, goes back once with the answers (the model judges + // each question against them, see `resolved`). What it still asks + // after that is filtered below. + let asked = clarification_of(&files.tasks); + let verdicts = super::resolved::judge(state, provider, &asked, &msg.answers, usage).await; + let repeats: Vec<(common::run_questions::Question, super::resolved::Verdict)> = asked + .iter() + .cloned() + .zip(verdicts) + .filter(|(_, v)| !v.may_ask()) + .collect(); if !repeats.is_empty() { info!( ticket_id = %msg.ticket_id, repeated = repeats.len(), - "Plan asks an answered question again — sending it back" + "Plan asks a settled question again — sending it back" ); messages.push(( "user".to_string(), vec![serde_json::json!({ "type": "text", - "text": common::run_questions::send_back(&repeats, &msg.answers), + "text": super::resolved::send_back(&repeats, &msg.answers), })], )); response = provider::converse( @@ -929,6 +940,30 @@ Then the ```fix_location.json block described above."#, } } + // Never ask a person what is settled, or what CoderHelm decides itself: + // the decision's questions and a clarification are checked once more. + if !msg.answers.is_empty() { + let asked = clarification_of(&files.tasks); + if !asked.is_empty() { + let v = super::resolved::judge(state, provider, &asked, &msg.answers, usage).await; + if v.iter().any(|v| !v.may_ask()) { + files.tasks = super::resolved::keep_open(&asked, &v); + } + } + if let Some(d) = files.fix.as_mut() { + let qs = common::run_questions::from_lines(&d.questions); + let v = super::resolved::judge(state, provider, &qs, &msg.answers, usage).await; + if v.iter().any(|v| !v.may_ask()) { + d.questions = qs + .into_iter() + .zip(v) + .filter(|(_, v)| v.may_ask()) + .map(|(q, _)| q.question) + .collect(); + } + } + } + // The questions only a person can answer are part of the plan people read. if let Some(d) = files.fix.as_ref() { files.proposal = with_questions(&files.proposal, d); @@ -1059,6 +1094,15 @@ Then the ```fix_location.json block described above."#, Ok(files) } +/// The questions in a `CLARIFICATION_NEEDED:` tasks file; none otherwise. +fn clarification_of(tasks: &str) -> Vec { + tasks + .trim_start() + .strip_prefix("CLARIFICATION_NEEDED:") + .map(common::run_questions::parse) + .unwrap_or_default() +} + /// The proposal with the decision's questions for a person after it, once. fn with_questions(proposal: &str, d: &super::fix_location::FixDecision) -> String { let qs = super::fix_location::questions_markdown(d); diff --git a/services/worker/src/passes/resolved.rs b/services/worker/src/passes/resolved.rs new file mode 100644 index 000000000..9e96b152b --- /dev/null +++ b/services/worker/src/passes/resolved.rs @@ -0,0 +1,340 @@ +//! Questions a plan may not ask: ones a person already settled, and ones +//! CoderHelm decides itself. +//! +//! The run carries every settled question on the ticket (answers given in +//! CoderHelm, and choices people made on its notices, see +//! `ticket_state::decision_answer`). Before a plan's questions reach a person, +//! the model reads each against them (structured output) and says whether a +//! settled answer covers it, in any wording, or whether it is something the +//! system decides (closing or replacing a pull request someone else opened is +//! never CoderHelm's call: once told to open its own, it leaves the other one +//! open). Those are dropped, or the plan is sent back once with the answers. +//! A model failure falls back to comparing the words. + +use crate::agent::provider::ModelProvider; +use crate::models::TokenUsage; +use crate::WorkerState; +use common::run_questions::{self, Answer, Question}; +use serde_json::{json, Value}; +use tracing::{info, warn}; + +/// What may happen to one question. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + /// Nobody has settled it: it may be asked. + Open, + /// A settled answer covers it (its index, when the model named one). + Settled(Option), + /// CoderHelm decides it itself; a person is never asked. + SystemDecides, +} + +impl Verdict { + pub fn may_ask(self) -> bool { + self == Verdict::Open + } +} + +pub const SYSTEM: &str = "An automated coding agent (CoderHelm) wants to ask a person some \ + questions about a ticket. Some questions on the ticket are already settled: people \ + answered them, or chose on CoderHelm's notices. For each new question, say whether a \ + settled answer already covers it, even in other words or from another angle (covered, \ + with the settled answer's number), or whether it is something CoderHelm must decide \ + itself and never ask a person (system_decides): whether to close, replace or take over a \ + pull request someone else opened when a person already said to open CoderHelm's own, or \ + anything the settled answers plus ordinary engineering judgement decide. Otherwise it is \ + open. Judge meaning, not wording."; + +pub fn schema() -> Value { + json!({ + "type": "object", + "properties": { + "verdicts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "question": {"type": "integer"}, + "verdict": {"type": "string", "enum": ["open", "covered", "system_decides"]}, + "settled_by": {"type": "integer"}, + "reason": {"type": "string"} + }, + "required": ["question", "verdict", "settled_by", "reason"], + "additionalProperties": false + } + } + }, + "required": ["verdicts"], + "additionalProperties": false + }) +} + +pub fn prompt(questions: &[Question], settled: &[Answer]) -> String { + let mut out = String::from("## Settled on this ticket\n"); + for (i, a) in settled.iter().enumerate() { + out.push_str(&format!( + "{}. Question: {}\n Answer: {}\n", + i + 1, + one_line(&a.question), + one_line(&a.answer) + )); + } + out.push_str("\n## Questions CoderHelm wants to ask now\n"); + for (i, q) in questions.iter().enumerate() { + out.push_str(&format!("{}. {}\n", i + 1, one_line(&q.question))); + } + out.push_str( + "\nGive one verdict per question (numbered as above); settled_by is the settled \ + answer's number, or 0 when none.", + ); + out +} + +/// The model's verdicts, one per question (1-based numbers in the reply); +/// a question it left out stays open. +pub fn apply(reply: &Value, questions: usize, settled: usize) -> Vec { + let mut out = vec![Verdict::Open; questions]; + for v in reply["verdicts"].as_array().into_iter().flatten() { + let Some(i) = v["question"] + .as_u64() + .and_then(|n| (n as usize).checked_sub(1)) + .filter(|i| *i < questions) + else { + continue; + }; + let by = v["settled_by"] + .as_u64() + .and_then(|n| (n as usize).checked_sub(1)) + .filter(|n| *n < settled); + out[i] = match v["verdict"].as_str().unwrap_or("") { + "covered" => Verdict::Settled(by), + "system_decides" => Verdict::SystemDecides, + _ => Verdict::Open, + }; + } + out +} + +/// The words-only reading, when the model can't be asked. +pub fn by_words(questions: &[Question], settled: &[Answer]) -> Vec { + questions + .iter() + .map(|q| { + match settled + .iter() + .position(|a| run_questions::already_answered(&q.question, std::slice::from_ref(a))) + { + Some(i) => Verdict::Settled(Some(i)), + None => Verdict::Open, + } + }) + .collect() +} + +/// One verdict per question. Nothing settled: every question is open. +pub async fn judge( + state: &WorkerState, + provider: &ModelProvider, + questions: &[Question], + settled: &[Answer], + usage: &mut TokenUsage, +) -> Vec { + if questions.is_empty() || settled.is_empty() { + return vec![Verdict::Open; questions.len()]; + } + match crate::agent::anthropic::converse_json( + &provider.client(), + &state.config.light_model_id, + SYSTEM, + &prompt(questions, settled), + &schema(), + true, + "low", + 2048, + usage, + ) + .await + { + Ok(v) => { + let out = apply(&v, questions.len(), settled.len()); + info!( + asked = questions.len(), + dropped = out.iter().filter(|v| !v.may_ask()).count(), + "Checked the plan's questions against what is settled" + ); + // The words still catch a plain repeat the model let through. + out.into_iter() + .zip(by_words(questions, settled)) + .map(|(m, w)| if m.may_ask() { w } else { m }) + .collect() + } + Err(e) => { + warn!(error = %e, "Could not check the plan's questions; comparing words"); + by_words(questions, settled) + } + } +} + +/// What the planner is told when its plan asks settled questions again. +pub fn send_back(asked: &[(Question, Verdict)], settled: &[Answer]) -> String { + let mut out = String::from( + "Your plan asks what is already settled on this ticket, or what CoderHelm decides \ + itself. Don't ask these:\n", + ); + for (q, v) in asked { + out.push_str(&format!("- You asked: {}\n", one_line(&q.question))); + match v { + Verdict::Settled(Some(i)) => { + out.push_str(&format!(" Settled: {}\n", one_line(&settled[*i].answer))) + } + Verdict::Settled(None) => out.push_str(" Settled by the answers above.\n"), + Verdict::SystemDecides => out.push_str( + " This is CoderHelm's own call: decide it (never close or replace a pull \ + request someone else opened; leave it open).\n", + ), + Verdict::Open => {} + } + } + out.push_str( + "Plan with what is settled now. Use CLARIFICATION_NEEDED only for something still \ + open, asking about that alone. Output the COMPLETE plan again in exactly the same \ + format as before (every file block, the fix decision included).", + ); + out +} + +/// A plan's `CLARIFICATION_NEEDED:` text with only the questions that may +/// be asked; when none may, one question says what is settled didn't +/// settle the plan. +pub fn keep_open(questions: &[Question], verdicts: &[Verdict]) -> String { + let open: Vec<&Question> = questions + .iter() + .zip(verdicts) + .filter(|(_, v)| v.may_ask()) + .map(|(q, _)| q) + .collect(); + let mut out = String::from("CLARIFICATION_NEEDED:\n"); + if open.is_empty() { + out.push_str( + "- question: The answers so far didn't settle it. What else should I know to make \ + this change?\n", + ); + return out; + } + for q in open { + out.push_str(&format!("- question: {}\n", one_line(&q.question))); + if !q.why.is_empty() { + out.push_str(&format!(" why: {}\n", one_line(&q.why))); + } + if !q.suggestions.is_empty() { + out.push_str(&format!(" options: {}\n", q.suggestions.join(" | "))); + } + } + out +} + +fn one_line(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + use common::ticket_state::{decision_answer, Decision, CHOICE_OWN, KIND_OPEN_PR}; + + fn q(text: &str) -> Question { + Question { + question: text.into(), + ..Default::default() + } + } + + fn own() -> Answer { + decision_answer(&Decision { + kind: KIND_OPEN_PR.into(), + subject: "acme/web#12".into(), + choice: CHOICE_OWN.into(), + said: "Go ahead and open your own".into(), + ..Default::default() + }) + } + + #[test] + fn the_settled_decisions_and_the_new_questions_go_to_the_model() { + let p = prompt( + &[q( + "Should the work continue on #12, or should #12 be closed and replaced?", + )], + &[own()], + ); + assert!(p.contains("1. Question: Pull request acme/web#12 is already open")); + assert!(p.contains("Answer: Open CoderHelm's own pull request and leave acme/web#12 open")); + assert!(p.contains("## Questions CoderHelm wants to ask now\n1. Should the work continue")); + assert_eq!( + schema()["properties"]["verdicts"]["items"]["properties"]["verdict"]["enum"], + json!(["open", "covered", "system_decides"]) + ); + } + + /// The question from the field: the reply already said to open its own, + /// and closing the other PR is not CoderHelm's call. Both readings drop + /// it; an unrelated question stays. + #[test] + fn a_question_a_recorded_decision_covers_is_dropped() { + let asked = [ + q( + "The ticket comment says to open your own while #12 is still open. Should the \ + work continue as new commits on #12, or should #12 be closed and replaced by a \ + new PR?", + ), + q("Which error message should the form show?"), + ]; + let reply = json!({"verdicts": [ + {"question": 1, "verdict": "covered", "settled_by": 1, "reason": "said open own"}, + {"question": 2, "verdict": "open", "settled_by": 0, "reason": "new"} + ]}); + let v = apply(&reply, asked.len(), 1); + assert_eq!(v, vec![Verdict::Settled(Some(0)), Verdict::Open]); + let tasks = keep_open(&asked, &v); + assert!(!tasks.contains("#12")); + assert!(tasks.contains("- question: Which error message should the form show?")); + + let reply = json!({"verdicts": [ + {"question": 1, "verdict": "system_decides", "settled_by": 0, "reason": "not ours"} + ]}); + assert_eq!(apply(&reply, 1, 1), vec![Verdict::SystemDecides]); + let back = send_back(&[(asked[0].clone(), Verdict::Settled(Some(0)))], &[own()]); + assert!(back.contains("Settled: Open CoderHelm's own pull request")); + } + + #[test] + fn a_bad_or_partial_reply_leaves_questions_open() { + assert_eq!(apply(&json!({}), 2, 1), vec![Verdict::Open, Verdict::Open]); + let reply = json!({"verdicts": [{"question": 9, "verdict": "covered", "settled_by": 7}]}); + assert_eq!(apply(&reply, 1, 1), vec![Verdict::Open]); + assert_eq!( + keep_open(&[q("A?")], &[Verdict::SystemDecides]), + "CLARIFICATION_NEEDED:\n- question: The answers so far didn't settle it. What else \ + should I know to make this change?\n" + ); + } + + #[test] + fn the_word_reading_catches_a_plain_repeat() { + let settled = [Answer { + question: "Which environments get the new rate limit?".into(), + answer: "Production".into(), + ..Default::default() + }]; + assert_eq!( + by_words( + &[ + q("Which environments should get the new rate limit?"), + q("What color?") + ], + &settled + ), + vec![Verdict::Settled(Some(0)), Verdict::Open] + ); + } +} diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index ac70ae9c2..722936197 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -1460,6 +1460,7 @@ fn review_eval_replays_every_run_case() { notes: h.notes, done_hash: String::new(), prs: vec![], + decisions: vec![], }; // What the run does: the planner's route, then the history. let route = match history.guard(case.plan.as_ref(), &case.current_hash) { diff --git a/services/worker/src/passes/ticket_history.rs b/services/worker/src/passes/ticket_history.rs index c5df46fad..ab2901f9b 100644 --- a/services/worker/src/passes/ticket_history.rs +++ b/services/worker/src/passes/ticket_history.rs @@ -71,6 +71,9 @@ pub struct TicketHistory { /// Every pull request for this ticket in the team's repositories /// (CoderHelm's or anyone's), as GitHub shows it now, oldest first. pub prs: Vec, + /// Choices people made on CoderHelm's notices (see + /// `ticket_state::Decision`), oldest first. + pub decisions: Vec, } /// An earlier pull request for the ticket, read from GitHub: what it said, @@ -892,6 +895,8 @@ pub async fn load( { if let Some(item) = out.item() { history.notes = ticket_state::parse_notes(&s(item, ticket_state::FIELD_NOTES)); + history.decisions = + ticket_state::parse_decisions(&s(item, ticket_state::FIELD_DECISIONS)); if s(item, ticket_state::FIELD_STATE) == ticket_state::STATE_DONE { history.done_hash = s(item, ticket_state::FIELD_DONE_HASH); } @@ -944,6 +949,7 @@ mod tests { notes: vec![], done_hash: String::new(), prs: vec![], + decisions: vec![], } } @@ -1021,6 +1027,7 @@ mod tests { }], done_hash: "h1".into(), prs: vec![], + decisions: vec![], }; match h.guard(Some(&override_plan("")), "h1") { Guard::Stop { @@ -1130,6 +1137,7 @@ mod traced_guard_tests { notes: vec![], done_hash: String::new(), prs: vec![], + decisions: vec![], } }