diff --git a/coderhelm-jira/src/index.js b/coderhelm-jira/src/index.js index 29712750e..ccb59f6d0 100644 --- a/coderhelm-jira/src/index.js +++ b/coderhelm-jira/src/index.js @@ -93,7 +93,7 @@ exports.handler = async (event, context) => { let fields = {}; if (issue.id) { try { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment`); + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype`); if (res.ok) { const full = await res.json(); fields = full.fields || {}; @@ -128,6 +128,7 @@ exports.handler = async (event, context) => { reporter: fields.reporter, creator: fields.creator, project: fields.project, + issuetype: fields.issuetype ? { name: fields.issuetype.name } : undefined, }, }, comment: { @@ -158,7 +159,7 @@ exports.handler = async (event, context) => { let fields = {}; if (issue.id) { try { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment`); + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype`); if (res.ok) { const full = await res.json(); fields = full.fields || {}; @@ -201,6 +202,7 @@ exports.handler = async (event, context) => { reporter: fields.reporter, creator: fields.creator, project: fields.project, + issuetype: fields.issuetype ? { name: fields.issuetype.name } : undefined, }, }, image_attachments: imageAttachments, diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 87c40cf40..20e67a70c 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -938,6 +938,12 @@ pub struct TicketMessage { /// The run keeps its run_id across these, like a continuation. #[serde(default)] pub model_retries: u32, + /// What the tracker calls the ticket (a Jira issue type such as `Story` + /// or `Bug`, a GitHub issue type or its `bug`/`enhancement` label), when + /// it says. Triage weighs it with the ticket's text (see + /// [`ticket_type_of_jira`], [`ticket_type_of_github`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ticket_type: Option, /// Set in-process when the ticket changed under an open PR: the implement /// agent gets this note (old→new ticket diff + PR diff) and updates the /// existing PR instead of starting over. Never serialized. @@ -979,6 +985,56 @@ fn default_branch() -> String { "main".to_string() } +/// The issue type a Jira issue carries (`fields.issuetype.name`), when the +/// event has it. +pub fn ticket_type_of_jira(issue: &serde_json::Value) -> Option { + issue + .pointer("/fields/issuetype/name") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) +} + +/// Labels that say what kind of work a GitHub issue is. +const KIND_LABELS: &[&str] = &[ + "bug", + "defect", + "regression", + "enhancement", + "feature", + "feature request", + "new feature", + "improvement", + "chore", + "question", +]; + +/// What a GitHub issue says it is: its issue type (`type.name`), else the +/// first label that names a kind of work. +pub fn ticket_type_of_github(issue: &serde_json::Value) -> Option { + if let Some(t) = issue + .pointer("/type/name") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + return Some(t.to_string()); + } + issue["labels"] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l["name"].as_str().or_else(|| l.as_str())) + .map(str::trim) + .find(|l| { + let low = l.to_ascii_lowercase(); + let low = low.trim_start_matches("type:").trim_start_matches("kind/"); + KIND_LABELS.contains(&low.trim()) + }) + .map(str::to_string) +} + impl Default for TicketMessage { /// An empty ticket on `main`, as a message without `base_branch` reads. fn default() -> Self { @@ -1002,6 +1058,7 @@ impl Default for TicketMessage { resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, @@ -1216,3 +1273,43 @@ mod worker_contract_tests { assert!(e.contains("unknown variant `SkillSync`"), "{e}"); } } + +#[cfg(test)] +mod ticket_type_tests { + use super::{ticket_type_of_github, ticket_type_of_jira}; + use serde_json::json; + + #[test] + fn a_jira_issue_type_is_read() { + let issue = json!({"fields": {"issuetype": {"name": "Story"}, "summary": "s"}}); + assert_eq!(ticket_type_of_jira(&issue).as_deref(), Some("Story")); + assert_eq!(ticket_type_of_jira(&json!({"fields": {}})), None); + assert_eq!( + ticket_type_of_jira(&json!({"fields": {"issuetype": {"name": " "}}})), + None + ); + } + + #[test] + fn a_github_issue_type_or_kind_label_is_read() { + assert_eq!( + ticket_type_of_github(&json!({"type": {"name": "Feature"}, "labels": []})).as_deref(), + Some("Feature") + ); + assert_eq!( + ticket_type_of_github( + &json!({"labels": [{"name": "coderhelm"}, {"name": "enhancement"}]}) + ) + .as_deref(), + Some("enhancement") + ); + assert_eq!( + ticket_type_of_github(&json!({"labels": [{"name": "type: bug"}]})).as_deref(), + Some("type: bug") + ); + assert_eq!( + ticket_type_of_github(&json!({"labels": [{"name": "coderhelm"}]})), + None + ); + } +} diff --git a/services/common/src/run_questions.rs b/services/common/src/run_questions.rs index 5656d3ca2..4404fc80a 100644 --- a/services/common/src/run_questions.rs +++ b/services/common/src/run_questions.rs @@ -608,6 +608,80 @@ fn clip(s: &str, max_chars: usize) -> String { format!("{}…", kept.trim_end()) } +/// Openings of a question that hands a person the run's own search: where +/// the work goes, or what else it needs, with nothing to choose from. +const OPEN_FORMS: &[&str] = &[ + "where does the fix belong", + "where does this belong", + "where does it belong", + "where should the fix go", + "where should this go", + "where should the change go", + "which system or part", + "which system is", + "which part of the system", + "what else does this need", + "what else is needed", + "what should happen next", + "how should i proceed", + "how should this be fixed", + "what should i do", + "can you clarify", + "please clarify", + "please provide more", + "any other details", + "anything else i should know", +]; + +/// Why a question is too open to put to a person, or `None` when it is fit +/// to ask. A person is asked only what they can answer better than the +/// code: a specific question, with the options the run considered (at least +/// two) or its own recommendation in the question ("I plan to ...; anything +/// else?"). An open "where does it belong" with no options never is. +/// CoderHelm's own choice cards (`decision`) are always fit. +pub fn too_open(q: &Question) -> Option<&'static str> { + if !q.decision.is_empty() + || q.suggestions + .iter() + .filter(|s| !s.trim().is_empty()) + .count() + >= 2 + { + return None; + } + let text = q + .question + .split_whitespace() + .collect::>() + .join(" ") + .to_ascii_lowercase(); + if text.is_empty() { + return Some(WHY_EMPTY); + } + let recommends = [ + "i plan to", + "i will", + "i'll", + "i recommend", + "i propose", + "my plan is", + ] + .iter() + .any(|p| text.contains(p)); + if recommends { + return None; + } + if OPEN_FORMS.iter().any(|f| text.contains(f)) { + return Some(WHY_OPEN); + } + None +} + +/// [`too_open`]'s reason for an empty question. +pub const WHY_EMPTY: &str = "it is empty"; +/// [`too_open`]'s reason for an open question. +pub const WHY_OPEN: &str = "it hands a person the run's own search (where the work goes, what else it needs) with no options and no recommendation: name the options considered and the one recommended"; + #[cfg(test)] mod tests { use super::*; @@ -858,4 +932,51 @@ mod tests { assert!(digest(&[]).is_empty()); assert_ne!(digest(&[answer("A?", "1")]), digest(&[answer("A?", "2")])); } + + #[test] + fn an_open_question_with_no_options_is_not_asked() { + use super::{too_open, Question, WHY_OPEN}; + let open = Question { + question: "Where does the fix belong: which system or part of it?".into(), + why: "The plan didn't say.".into(), + ..Default::default() + }; + assert_eq!(too_open(&open), Some(WHY_OPEN)); + let open = Question { + question: "What else does this need before I build it?".into(), + ..Default::default() + }; + assert_eq!(too_open(&open), Some(WHY_OPEN)); + // The same doubt with the options considered is fit to ask. + let with_options = Question { + question: "Where does the fix belong?".into(), + suggestions: vec![ + "In the block schemas (code)".into(), + "In the CMS entries (content)".into(), + ], + ..Default::default() + }; + assert_eq!(too_open(&with_options), None); + // So is a plan with a recommendation. + let plan = Question { + question: "I plan to put the setting on these 3 block schemas and read it in these \ + components; anything else?" + .into(), + ..Default::default() + }; + assert_eq!(too_open(&plan), None); + // A specific yes/no question is fit too. + let specific = Question { + question: "Use the existing `title_size` field instead of creating a new one?".into(), + ..Default::default() + }; + assert_eq!(too_open(&specific), None); + // CoderHelm's own choice cards always are. + let card = Question { + question: "Where should this go?".into(), + decision: "open_pr:acme/web#1".into(), + ..Default::default() + }; + assert_eq!(too_open(&card), None); + } } diff --git a/services/common/src/stop_rules/screen.rs b/services/common/src/stop_rules/screen.rs index 6c7aa3e13..3af453098 100644 --- a/services/common/src/stop_rules/screen.rs +++ b/services/common/src/stop_rules/screen.rs @@ -372,6 +372,9 @@ pub fn asking_rule( if !q.decision.is_empty() { return None; } + if let Some(why) = crate::run_questions::too_open(q) { + return Some(why); + } if read.conflicting_findings { return Some(WHY_CONFLICT); } @@ -408,6 +411,8 @@ pub fn is_asking_rule(why: &str) -> bool { WHY_ANSWERABLE, WHY_FIELD_UNREAD, WHY_CONFLICT, + crate::run_questions::WHY_OPEN, + crate::run_questions::WHY_EMPTY, ] .contains(&why) } diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 49b15feee..b9de6490b 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -538,6 +538,7 @@ async fn handle_issue_event( payload["sender"]["login"].as_str().unwrap_or(""), ), image_attachments: vec![], + ticket_type: common::messages::ticket_type_of_github(issue), ..Default::default() }); @@ -1576,6 +1577,7 @@ async fn handle_issue_comment( payload["sender"]["login"].as_str().unwrap_or(""), ), image_attachments: vec![], + ticket_type: common::messages::ticket_type_of_github(issue), ..Default::default() }); diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index 803414e20..01e20a9bc 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -728,6 +728,7 @@ async fn process_jira_payload( sender, requester, image_attachments, + ticket_type: common::messages::ticket_type_of_jira(issue), ..Default::default() }); @@ -1133,6 +1134,7 @@ async fn handle_jira_comment( .and_then(|s| serde_json::from_str(s).ok()) .unwrap_or_default() }, + ticket_type: common::messages::ticket_type_of_jira(issue), ..Default::default() }) }; diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 42c811990..fa7cb82fe 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -849,6 +849,15 @@ pub async fn converse_tool_loop( .collect(); if tool_uses.is_empty() || response.stop_reason.as_deref() == Some("end_turn") { + // An answer cut at the output limit loses whatever it was to + // end with (a planner's decision block comes last): say so. + if response.stop_reason.as_deref() == Some("max_tokens") { + warn!( + max_tokens, + output_tokens = response.usage.output_tokens, + "Final answer stopped at the output limit; its end is missing" + ); + } // Log the final assistant response if let Some(ref mut log) = conversation_log { log.push(json!({ diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 8194b9474..1bf5e43db 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -314,6 +314,7 @@ mod tests { resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 8c1b16243..b6616c7d3 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -1631,6 +1631,7 @@ async fn start_fix_ticket( resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, @@ -1883,6 +1884,7 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, diff --git a/services/worker/src/passes/e2e_attribution.rs b/services/worker/src/passes/e2e_attribution.rs index da61ce86e..3fe463a17 100644 --- a/services/worker/src/passes/e2e_attribution.rs +++ b/services/worker/src/passes/e2e_attribution.rs @@ -462,6 +462,7 @@ async fn start_fix( resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 0168c83ec..b2b6d28b8 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -263,6 +263,7 @@ pub async fn run( resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, @@ -2908,6 +2909,7 @@ async fn handle_wrong_repo( resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index 2238f800d..7ed3bff87 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -371,6 +371,12 @@ pub struct FixDecision { /// can't take: that one action and what each outcome would mean. #[serde(default, skip_serializing_if = "Option::is_none")] pub next_step: Option, + /// Set when the planner's own answer carried no readable decision (a + /// format failure, never a question for a person): what was wrong with + /// it and how the run settled where the fix belongs instead (asked the + /// planner again for the block, or fell back from the plan itself). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub planner_failure: String, } /// One step of the whole job, and who does it. @@ -669,29 +675,266 @@ pub fn parse_for(response: &str, intent: TicketIntent) -> Option { /// The decision in the planner's reply, if it wrote one that reads. pub fn parse(response: &str) -> Option { + match parse_detailed(response) { + Ok(d) => Some(d), + Err(BlockProblem::Missing) => None, + Err(p) => { + tracing::warn!(problem = %p.describe(), "Planner's fix_location block didn't read"); + None + } + } +} + +/// Why a planner's reply has no decision that reads. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BlockProblem { + /// No ```fix_location.json fence at all. + Missing, + /// The fence opens but never closes: the answer was cut off (usually + /// at the output limit, since the block comes last). + Unterminated, + /// The fence closes but its JSON doesn't read. + Invalid(String), +} + +impl BlockProblem { + /// For the run's notes and record. + pub fn describe(&self) -> String { + match self { + BlockProblem::Missing => "the planner's answer had no fix_location block".to_string(), + BlockProblem::Unterminated => { + "the planner's fix_location block was cut off before it closed".to_string() + } + BlockProblem::Invalid(e) => format!( + "the planner's fix_location block didn't read as JSON ({})", + common::truncate_str(e, 160) + ), + } + } + + /// A short kind for analytics. + pub fn kind(&self) -> &'static str { + match self { + BlockProblem::Missing => "fix_location_missing", + BlockProblem::Unterminated => "fix_location_cut_off", + BlockProblem::Invalid(_) => "fix_location_malformed", + } + } +} + +/// The decision in the planner's reply, or what is wrong with it. +pub fn parse_detailed(response: &str) -> Result { let marker = format!("```{FENCE}"); - let start = response.find(&marker)?; - let body_start = start + response[start..].find('\n')? + 1; - let end = response[body_start..] - .find("```") - .map(|i| body_start + i) - .unwrap_or(response.len()); - let raw = response[body_start..end].trim(); + let start = response.find(&marker).ok_or(BlockProblem::Missing)?; + let Some(nl) = response[start..].find('\n') else { + return Err(BlockProblem::Unterminated); + }; + let body_start = start + nl + 1; + let closed = response[body_start..].find("```").map(|i| body_start + i); + let raw = response[body_start..closed.unwrap_or(response.len())].trim(); match serde_json::from_str::(raw) { Ok(mut d) => { // What the ticket asks for comes from triage, never the block. d.intent = TicketIntent::default(); // What is still open is the plan check's to say. d.open_gaps.clear(); - Some(d) - } - Err(e) => { - tracing::warn!(error = %e, "Planner's fix_location block didn't read"); - None + // How a missing block was settled is the run's to say. + d.planner_failure.clear(); + Ok(d) } + Err(_) if closed.is_none() => Err(BlockProblem::Unterminated), + Err(e) => Err(BlockProblem::Invalid(e.to_string())), } } +/// The one cheap call that asks the planner again for only its decision, +/// when its answer carried none that reads: the ticket, the plan it wrote +/// and the block's shape. No tools, no research: the plan is already made. +pub fn reask_prompt( + title: &str, + intent: TicketIntent, + problem: &BlockProblem, + proposal: &str, + design: &str, + tasks: &str, +) -> String { + format!( + "You planned this ticket, but {problem}. Write that block now, from the plan below, and \ + nothing else: no other text, no other files.\n\n\ + ## Ticket\nTitle: {title}\nTriage read it as: {intent}\n\n\ + ## Your plan\n### proposal.md\n{proposal}\n\n### design.md\n{design}\n\n### tasks.md\n{tasks}\n\n\ + ## The block\n\ + - `fix_location`: `code` when the tasks change files in the repository (new work always is, \ + unless a person or vendor does part of it: then `both`), `outside_code` only when the plan \ + itself says the fix is a change in another system, `unknown` only when tasks.md says \ + `NO_CODE_CHANGE:`.\n\ + - `cause`: one or two sentences, from the plan.\n\ + - `evidence.basis`: `feature` for new work, `code` or `data` for a bug.\n\ + - `questions`: only what the plan says a person must decide, each naming the options; [] \ + when none.\n\ + - `outside_change`: null unless `outside_code` or `both`, then `system` and `change`.\n\n\ + ```{FENCE}\n{{\"fix_location\": \"code\", \"cause\": \"...\", \"evidence\": {{\"basis\": \"feature\"}}, \"outside_change\": null, \"questions\": []}}\n```", + problem = problem.describe(), + intent = intent.as_str(), + proposal = common::truncate_str(proposal.trim(), 6000), + design = common::truncate_str(design.trim(), 6000), + tasks = common::truncate_str(tasks.trim(), 6000), + ) +} + +/// Where the fix belongs when the planner gave no decision that reads, +/// even after being asked once more: decided from the plan itself, never +/// by asking a person. New work or upkeep, and a plan whose tasks name +/// files in the repository, is `code`; a plan that says it changes no code +/// is `unknown` with its own line as the cause. `None` when the plan has +/// nothing to decide from (no tasks): that is a planner failure. +pub fn fallback(intent: TicketIntent, tasks: &str, failure: &str) -> Option { + let t = tasks.trim_start(); + if t.is_empty() || t.starts_with("NO_CHANGES_NEEDED:") || t.starts_with("CLARIFICATION_NEEDED:") + { + return None; + } + let mut d = FixDecision { + intent, + planner_failure: failure.to_string(), + ..Default::default() + }; + if let Some(line) = t.strip_prefix(NO_CODE_CHANGE) { + d.fix_location = FixLocation::Unknown; + d.cause = line.trim().to_string(); + return Some(d); + } + let files = super::feature::plan_files::planned_files(tasks); + let new_work = matches!(intent, TicketIntent::Feature | TicketIntent::Chore); + if !new_work && files.is_empty() { + return None; + } + d.fix_location = FixLocation::Code; + d.evidence.basis = if new_work { "feature" } else { "code" }.to_string(); + let names: Vec<&str> = files.iter().take(5).map(|f| f.path.as_str()).collect(); + d.cause = if names.is_empty() { + "The plan's tasks change this repository's code.".to_string() + } else { + format!( + "The plan's tasks change {} in this repository.", + names.join(", ") + ) + }; + Some(d) +} + +/// What a run asks a person when it stops without a fix: the plan's own +/// questions not answered already and fit to ask (see +/// `run_questions::too_open`), else one concrete question built from what +/// the run found, with the options it considered. Never an open "where +/// does the fix belong". Empty when there is nothing concrete to ask. +pub fn person_questions( + d: &FixDecision, + answers: &[common::run_questions::Answer], + tasks: &str, +) -> Vec { + use common::run_questions::{too_open, unanswered, Question}; + let renumber = |qs: Vec| -> Vec { + qs.into_iter() + .enumerate() + .map(|(i, q)| Question { + id: format!("q{}", i + 1), + ..q + }) + .collect() + }; + let own: Vec = unanswered(common::run_questions::from_lines(&d.questions), answers) + .into_iter() + .filter(|q| too_open(q).is_none()) + .collect(); + if !own.is_empty() { + return renumber(own); + } + let why = common::truncate_str(&one_line(&d.cause), 600).to_string(); + let q = |question: String, suggestions: Vec| Question { + id: "q1".to_string(), + question, + why: why.clone(), + suggestions, + ..Default::default() + }; + let built = if let Some(n) = d.next_step.as_ref().filter(|n| n.is_usable()) { + q( + format!( + "Can you {} and tell me what you see?", + one_line(&n.action).trim_end_matches('.') + ), + n.outcomes + .iter() + .filter(|o| !o.if_.trim().is_empty()) + .map(|o| one_line(&o.if_)) + .collect(), + ) + } else if let Some(c) = d + .outside_change + .as_ref() + .filter(|c| !c.change.trim().is_empty()) + { + let system = if c.system.trim().is_empty() { + "another system".to_string() + } else { + one_line(&c.system) + }; + q( + format!( + "I think the fix is this change in {system}: {}. Is that the fix, or should I change the code instead?", + one_line(&c.change).trim_end_matches('.') + ), + vec![ + format!("Yes: make that change in {system}"), + "No: change the code in this repository".to_string(), + ], + ) + } else { + let files: Vec = super::feature::plan_files::planned_files(tasks) + .into_iter() + .take(5) + .map(|f| f.path) + .collect(); + if !files.is_empty() { + q( + format!( + "I plan to change {}. Go ahead, or does it need anything else?", + files.join(", ") + ), + vec![ + "Go ahead with this plan".to_string(), + "It also needs: (say what)".to_string(), + ], + ) + } else if let Some(line) = tasks.trim_start().strip_prefix(NO_CODE_CHANGE) { + q( + format!( + "I found no code change to make: {}. Is that right?", + one_line(line).trim_end_matches('.') + ), + vec![ + "Yes: nothing to change in the code".to_string(), + "No: the code should change (say where)".to_string(), + ], + ) + } else if !why.is_empty() { + q( + "I stopped before changing code for the reason above. I recommend changing the \ + code in this repository; go ahead?" + .to_string(), + vec![ + "Go ahead and change the code".to_string(), + "No: the fix is somewhere else (say where)".to_string(), + ], + ) + } else { + return Vec::new(); + } + }; + unanswered(vec![built], answers) +} + /// The planner's instructions for the decision, appended to its prompt, by /// what the ticket asks for: a bug is traced to where its fault is; new /// work, upkeep and questions are not framed as a fault. Every plan gets the @@ -1114,17 +1357,6 @@ pub fn outside_report(d: &FixDecision, heading: bool) -> String { out } -/// The decision a run asks with when the plan carried none. -pub fn undecided() -> FixDecision { - FixDecision { - fix_location: FixLocation::Unknown, - cause: "The plan didn't say where the fix belongs (in this code or in data or settings \ - in another system), so I stopped before changing any code." - .to_string(), - ..Default::default() - } -} - /// The report when the run stops to ask: for a bug, where the fix belongs /// wasn't settled; for new work, what to build and what a person must /// decide first; for a question, what was found. @@ -1571,7 +1803,7 @@ mod tests { #[test] fn a_plan_without_a_decision_asks_and_never_codes() { assert_eq!(route(None), Route::Ask); - assert!(unknown_report(&undecided(), false).contains("stopped before changing any code")); + assert_eq!(parse("```tasks.md\n- [ ] a.rs: x\n```"), None); let d = FixDecision::default(); assert_eq!(route(Some(&d)), Route::Code); @@ -2198,3 +2430,189 @@ mod intent_tests { assert!(!ticket.contains("Not checked")); } } + +#[cfg(test)] +mod missing_block_tests { + use super::*; + + const FEATURE_TASKS: &str = + "- [ ] studio/schemas/blocks/hero.ts: [modify] Add a titleSize field (section | page)\n\ +- [ ] studio/schemas/blocks/cards.ts: [modify] Add a titleSize field\n\ +- [ ] web/components/blocks/Hero.tsx: [modify] Read titleSize for the heading level"; + + #[test] + fn a_missing_or_cut_off_or_malformed_block_says_which() { + assert_eq!( + parse_detailed("```tasks.md\n- [ ] a.rs: x\n```"), + Err(BlockProblem::Missing) + ); + // The answer hit the output limit inside the block. + assert_eq!( + parse_detailed("```fix_location.json\n{\"fix_location\": \"co"), + Err(BlockProblem::Unterminated) + ); + assert!(matches!( + parse_detailed("```fix_location.json\n{\"fix_location\": }\n```"), + Err(BlockProblem::Invalid(_)) + )); + let d = parse_detailed( + "```fix_location.json\n{\"fix_location\": \"code\", \"planner_failure\": \"x\"}\n```", + ) + .unwrap(); + assert_eq!(d.fix_location, FixLocation::Code); + assert!(d.planner_failure.is_empty(), "the block never sets it"); + } + + #[test] + fn a_feature_phrased_as_a_complaint_with_no_block_proceeds_to_code() { + // The live case: new work, the planner left the block out (twice). + let d = fallback( + TicketIntent::Feature, + FEATURE_TASKS, + "fix_location_missing; asked again: still none", + ) + .expect("a plan with tasks always decides"); + assert_eq!(route_for_plan(Some(&d), FEATURE_TASKS), Route::Code); + assert_eq!(d.evidence.basis, "feature"); + assert!( + d.cause.contains("studio/schemas/blocks/hero.ts"), + "{}", + d.cause + ); + assert!(!d.planner_failure.is_empty()); + // Even read as a bug, a plan whose tasks name this repo's files codes. + let d = fallback(TicketIntent::Bug, FEATURE_TASKS, "x").unwrap(); + assert_eq!(route_for_plan(Some(&d), FEATURE_TASKS), Route::Code); + // New work codes even when the tasks name no files the parser knows. + let d = fallback(TicketIntent::Chore, "- [ ] bump the SDK", "x").unwrap(); + assert_eq!(d.fix_location, FixLocation::Code); + } + + #[test] + fn a_plan_with_nothing_to_decide_from_is_a_planner_failure_not_a_question() { + assert_eq!(fallback(TicketIntent::Bug, " ", "x"), None); + assert_eq!(fallback(TicketIntent::Feature, "", "x"), None); + assert_eq!(fallback(TicketIntent::Bug, "- [ ] look into it", "x"), None); + // Directives are handled before any decision is needed. + assert_eq!( + fallback(TicketIntent::Bug, "NO_CHANGES_NEEDED: done", "x"), + None + ); + assert_eq!( + fallback( + TicketIntent::Bug, + "CLARIFICATION_NEEDED:\n- question: x", + "x" + ), + None + ); + // A plan that says it changes no code keeps its own line as the cause. + let d = fallback( + TicketIntent::Bug, + "NO_CODE_CHANGE: the venue's hours are unset in the CMS", + "x", + ) + .unwrap(); + assert_eq!(d.fix_location, FixLocation::Unknown); + assert_eq!(d.cause, "the venue's hours are unset in the CMS"); + // A decision settled for new work never reads as a fault question. + let d = fallback(TicketIntent::Feature, FEATURE_TASKS, "x").unwrap(); + assert_eq!(ask_title(&d), "Questions before I build this"); + } + + #[test] + fn the_reask_is_small_and_asks_only_for_the_block() { + let p = reask_prompt( + "Add a title size setting", + TicketIntent::Feature, + &BlockProblem::Unterminated, + "proposal", + "design", + FEATURE_TASKS, + ); + assert!(p.contains("cut off before it closed"), "{p}"); + assert!(p.contains("```fix_location.json"), "{p}"); + assert!(p.contains("nothing else"), "{p}"); + assert!(p.len() < 8000, "{}", p.len()); + // What the model then writes reads as a decision. + let reply = "```fix_location.json\n{\"fix_location\": \"code\", \"cause\": \"Adds the setting.\", \"evidence\": {\"basis\": \"feature\"}, \"outside_change\": null, \"questions\": []}\n```"; + let d = parse_for(reply, TicketIntent::Feature).unwrap(); + assert_eq!(route(Some(&d)), Route::Code); + } + + #[test] + fn a_question_to_a_person_is_never_an_open_where_does_it_belong() { + use common::run_questions::too_open; + // No decision questions, a plan with files: the question names them. + let d = FixDecision { + fix_location: FixLocation::Unknown, + intent: TicketIntent::Bug, + cause: "Not sure yet.".into(), + questions: vec!["Where does the fix belong: which system or part of it?".into()], + ..Default::default() + }; + let qs = person_questions(&d, &[], FEATURE_TASKS); + assert_eq!(qs.len(), 1); + assert!( + qs[0] + .question + .starts_with("I plan to change studio/schemas/blocks/hero.ts"), + "{}", + qs[0].question + ); + assert!(qs[0].suggestions.len() >= 2); + for q in &qs { + assert_eq!(too_open(q), None, "{}", q.question); + } + // Nothing concrete at all: nothing is asked. + assert!(person_questions(&FixDecision::default(), &[], "").is_empty()); + } + + #[test] + fn a_real_bug_outside_the_code_still_asks_with_a_concrete_next_step() { + let mut d = parse(fixture::PLANNER_REPLY).unwrap(); + d.intent = TicketIntent::Bug; + d.questions.clear(); + assert_eq!(route(Some(&d)), Route::OutsideOnly); + // Unsure, with the one step a person takes: the question is that step. + d.fix_location = FixLocation::Unknown; + d.next_step = Some(NextStep { + action: "run the full rebuild of the search index".into(), + why_person: "no access to the indexer".into(), + outcomes: vec![ + Outcome { + if_: "the item appears".into(), + means: "the incremental sync skipped it".into(), + }, + Outcome { + if_: "it still doesn't".into(), + means: "the inclusion rule drops it".into(), + }, + ], + }); + assert_eq!(route(Some(&d)), Route::Ask); + let qs = person_questions(&d, &[], "NO_CODE_CHANGE: unsure"); + assert_eq!( + qs[0].question, + "Can you run the full rebuild of the search index and tell me what you see?" + ); + assert_eq!( + qs[0].suggestions, + vec![ + "the item appears".to_string(), + "it still doesn't".to_string() + ] + ); + // Without a next step, the outside change it found is offered. + d.next_step = None; + let qs = person_questions(&d, &[], "NO_CODE_CHANGE: unsure"); + assert!( + qs[0] + .question + .starts_with("I think the fix is this change in the booking system"), + "{}", + qs[0].question + ); + assert_eq!(common::run_questions::too_open(&qs[0]), None); + } +} diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 527a11e62..32bf210d4 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -116,6 +116,7 @@ impl StartEnv for WorkerEnv<'_> { resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 09549a901..7b11caa37 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -890,6 +890,7 @@ pub(crate) mod run_lists; mod security; #[cfg(test)] mod selfhost_links; +mod series; pub mod skill_compat; pub mod skill_suggest; pub mod skills; @@ -2271,6 +2272,17 @@ async fn run_passes( ) .await; + // A plan with no decision (one saved before the planner settled every + // missing decision itself) decides from its own tasks; never by asking + // a person where the fix belongs. + if plan_result.fix.is_none() { + plan_result.fix = fix_location::fallback( + triage_result.intent, + &plan_result.tasks, + "the plan carried no fix_location decision; decided from its tasks", + ); + } + // --- Repo check, before anything is decided on this plan --- // A plan written against the wrong repo (its files live in another // one) is planned again in the right repo before its decision counts or @@ -2489,6 +2501,7 @@ async fn run_passes( &github, &decision, fix_location::Route::Ask, + &plan_result.tasks, usage, start, &used_mcp_ids, @@ -2536,12 +2549,15 @@ async fn run_passes( fix_route = route; } } + // A missing decision is not a directive: a plan with no decision and + // no tasks is a malformed plan (a planner failure), never a question. let plan_is_directive = plan_result.tasks.starts_with("NO_CHANGES_NEEDED:") || plan_result.tasks.starts_with("CLARIFICATION_NEEDED:") - || matches!( - fix_route, - fix_location::Route::OutsideOnly | fix_location::Route::Ask - ); + || (plan_result.fix.is_some() + && matches!( + fix_route, + fix_location::Route::OutsideOnly | fix_location::Route::Ask + )); if !plan_is_directive && (plan_result.tasks.trim().is_empty() || plan_result.design.trim().is_empty()) { @@ -2568,10 +2584,21 @@ async fn run_passes( fix_location::Route::OutsideOnly | fix_location::Route::Ask ) { - let mut decision = plan_result - .fix - .clone() - .unwrap_or_else(fix_location::undecided); + // A plan with no decision even after the planner was asked again + // and the plan's own tasks gave nothing to decide from is a planner + // failure: never a question to a person about where the fix goes. + let Some(mut decision) = plan_result.fix.clone() else { + warn!( + run_id, + "Plan has no decision and nothing to decide from — planner failure" + ); + close_memory(state, agent_memory.take()).await; + return Err( + "Planner failure: the plan carried no fix_location decision and its tasks name \ + no files to decide from. Nothing was asked of a person; retry the run." + .into(), + ); + }; if decision.cause.trim().is_empty() { // A plan that codes nothing but wrote no decision: its one line // is what it found. @@ -2590,6 +2617,7 @@ async fn run_passes( &github, &decision, fix_route, + &plan_result.tasks, usage, start, &used_mcp_ids, @@ -6922,6 +6950,7 @@ async fn finish_without_code( github: &GitHubClient, decision: &fix_location::FixDecision, route: fix_location::Route, + tasks: &str, usage: &TokenUsage, start: &std::time::Instant, mcp_ids: &[String], @@ -6980,7 +7009,7 @@ async fn finish_without_code( } 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); + let questions = unknown_fix_questions(decision, &msg.answers, tasks); ask_on_ticket( state, msg, @@ -8668,44 +8697,16 @@ fn empty_change_questions() -> Vec { ] } -/// 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. +/// What a run asks when it stops without a fix: the plan's own questions +/// not answered already and fit to ask, else one concrete question with the +/// options the run considered (see `fix_location::person_questions`). Never +/// an open "where does the fix belong". fn unknown_fix_questions( decision: &fix_location::FixDecision, answers: &[common::run_questions::Answer], + tasks: &str, ) -> 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(), - decision: String::new(), - evidence: Vec::new(), - ..Default::default() - }] + fix_location::person_questions(decision, answers, tasks) } /// Keeps what a run asked on its record (see `common::run_questions`). @@ -11715,17 +11716,22 @@ mod asking_tests { "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. + // No questions of its own: one concrete question with options and + // a recommendation, the cause as why; never an open "where does + // the fix belong". let bare = FixDecision { questions: vec![], ..d }; - let qs = unknown_fix_questions(&bare, &[]); + let qs = unknown_fix_questions(&bare, &[], ""); assert_eq!(qs.len(), 1); - assert!(qs[0].question.starts_with("Where does the fix belong")); + assert!(!qs[0].question.contains("Where does the fix belong")); + assert_eq!(common::run_questions::too_open(&qs[0]), None); + assert!(qs[0].suggestions.len() >= 2); assert_eq!(qs[0].why, "Two jobs write the same table."); } diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index cd02d095c..84b5fed04 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -13,7 +13,7 @@ use crate::WorkerState; /// any change to how plans are made or what a plan must carry, so a plan /// written by an older planner is never reused. pub const PLANNER_VERSION: &str = - "2026-11-04.intent-history-env-near-match-stop-rules-data-rules-cross-repo-asking-reproduce"; + "2026-11-06.intent-history-env-near-match-stop-rules-data-rules-cross-repo-asking-reproduce-decision-reask-series"; /// The openspec file holding the plan's end-to-end checklist, readable. pub const END_TO_END_FILE: &str = "end_to_end.md"; @@ -379,6 +379,26 @@ Then the ```fix_location.json block described above."#, "{prompt}{}", common::run_questions::answers_note(&msg.answers) ); + // One part of a numbered series: the other parts' pull requests, so + // the plan builds on them (see `series`). + let series_part = super::series::of_ticket(&msg.title, &msg.body); + let siblings = if series_part.is_some() { + super::series::find( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.ticket_id, + &msg.title, + &msg.body, + ) + .await + } else { + Vec::new() + }; + let prompt = format!( + "{prompt}{}", + super::series::planner_note(series_part, &default_repo, &siblings) + ); let mut tools = read_only_tools(); @@ -986,6 +1006,47 @@ Then the ```fix_location.json block described above."#, } } } + // A plan whose answer carried no decision that reads is a format + // failure, never a question for a person: the planner is asked once + // more for only the block (one small call, no tools), and when that + // still gives none, the plan itself decides (see `fix_location::fallback`). + let mut block_failure: Option = None; + if files.fix.is_none() && needs_decision(&files.tasks) { + let problem = match super::fix_location::parse_detailed(&response) { + Err(p) => p, + Ok(_) => super::fix_location::BlockProblem::Missing, + }; + let spent = usage.input_tokens + + usage.output_tokens + + usage.cache_read_tokens + + usage.cache_write_tokens; + warn!( + ticket_id = %msg.ticket_id, + problem = %problem.describe(), + tokens_so_far = spent, + "Planner gave no readable decision — asking again for the block only" + ); + let again = reask_decision(state, provider, usage, msg, intent, &problem, &files).await; + let outcome = if again.is_some() { + "asked the planner again for the block: got it" + } else { + "asked the planner again for the block: still none" + }; + let line = format!("{}; {outcome}", problem.describe()); + record_planner_failure(state, msg, run_id, problem.kind(), &line, spent).await; + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Plan check (format): {line}."), + ) + .await; + files.fix = again.map(|mut d| { + d.planner_failure = line.clone(); + d + }); + block_failure = Some(line); + } // The decision's own questions (where the fix belongs) are held to the // same rules: what may not stop the run is left out. if let Some(d) = files.fix.as_mut().filter(|d| !d.questions.is_empty()) { @@ -1033,6 +1094,38 @@ Then the ```fix_location.json block described above."#, } }); } + // Still no decision after asking again: the plan itself decides. A plan + // with nothing to decide from is a planner failure, reported as one. + if let Some(line) = block_failure.as_deref().filter(|_| files.fix.is_none()) { + match super::fix_location::fallback(intent, &files.tasks, line) { + Some(d) => { + info!( + ticket_id = %msg.ticket_id, + fix_location = d.fix_location.as_str(), + "Planner's decision settled from the plan itself" + ); + super::add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Plan check (format): decided from the plan itself: the fix is `{}` ({}).", + d.fix_location.as_str(), + d.cause + ), + ) + .await; + files.fix = Some(d); + } + None => { + return Err(format!( + "Planner failure: {line}, and the plan has no tasks to decide from. \ + Nothing was asked of a person; retry the run." + ) + .into()); + } + } + } // Every check sent its gaps back in the one send-back above; what each // still finds goes on the decision's open gaps (never another plan), and // planning moves on. Only the checks' own findings count as open gaps. @@ -1394,6 +1487,111 @@ Then the ```fix_location.json block described above."#, Ok(files) } +/// Whether a plan needs a decision on where the fix belongs: everything +/// but a plan that says the work is done or stops on a question. +fn needs_decision(tasks: &str) -> bool { + let t = tasks.trim_start(); + !t.starts_with("NO_CHANGES_NEEDED:") && !t.starts_with("CLARIFICATION_NEEDED:") +} + +/// Asks the planner once more for only its decision block: a fresh, small +/// call with the plan it wrote, no tools, low effort. `None` when the reply +/// still has no block that reads or the call fails. +async fn reask_decision( + state: &WorkerState, + provider: &ModelProvider, + usage: &mut TokenUsage, + msg: &TicketMessage, + intent: super::triage::TicketIntent, + problem: &super::fix_location::BlockProblem, + files: &PlanResult, +) -> Option { + let prompt = super::fix_location::reask_prompt( + &msg.title, + intent, + problem, + &files.proposal, + &files.design, + &files.tasks, + ); + let mut messages = vec![( + "user".to_string(), + vec![json!({"type": "text", "text": prompt})], + )]; + let reply = provider::converse( + state, + provider, + common::agent_policy::Agent::Planner, + provider.primary_model_id(), + "You write one JSON block for a plan that already exists. Return only the block.", + &mut messages, + &[], + &super::triage::NoOpExecutor, + usage, + llm::ConverseOptions { + max_turns: 1, + max_tokens: 4096, + deadline: None, + effort: Some("low"), + }, + None, + None, + ) + .await; + match reply { + Ok(text) => super::fix_location::parse_for(&text, intent), + Err(e) => { + warn!(ticket_id = %msg.ticket_id, error = %e, "Asking the planner again for its decision failed"); + None + } + } +} + +/// Records a planner format failure on the run and in the team's analytics +/// (`planner_format_failures`), so a model that spent its budget and then +/// left out its decision shows as a planner failure, not as a question. +async fn record_planner_failure( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + kind: &str, + line: &str, + tokens_before: u64, +) { + use aws_sdk_dynamodb::types::AttributeValue; + let s = |v: &str| AttributeValue::S(v.to_string()); + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", s(&msg.team_id)) + .key("run_id", s(run_id)) + .update_expression( + "SET planner_failure = :pf, planner_failure_kind = :k, planner_failure_tokens = :t", + ) + .expression_attribute_values(":pf", s(line)) + .expression_attribute_values(":k", s(kind)) + .expression_attribute_values(":t", AttributeValue::N(tokens_before.to_string())) + .send() + .await + { + warn!(run_id, error = %e, "Could not record the planner failure on the run"); + } + let month = chrono::Utc::now().format("%Y-%m").to_string(); + for period in [month.as_str(), "ALL_TIME"] { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.analytics_table_name) + .key("team_id", s(&msg.team_id)) + .key("period", s(period)) + .update_expression("ADD planner_format_failures :one") + .expression_attribute_values(":one", AttributeValue::N("1".to_string())) + .send() + .await; + } +} + /// The questions a plan stops on when its outside note (fix `both` or /// `outside_code`) still gives a person a step with no reason. `None` when /// every person step has its reason, or the plan already asks. diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index e1ca956a2..1e255656a 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2942,6 +2942,7 @@ async fn fix_context( resume_from: None, retry_of_run: false, model_retries: 0, + ticket_type: None, ticket_update_note: None, ticket_history_note: None, plan_cache_key: None, diff --git a/services/worker/src/passes/series.rs b/services/worker/src/passes/series.rs new file mode 100644 index 000000000..b52ffbb7f --- /dev/null +++ b/services/worker/src/passes/series.rs @@ -0,0 +1,309 @@ +//! A ticket that is one part of a numbered series ("part 4 of 4"): the +//! planner reads the earlier parts' pull requests before it plans, so it +//! builds on what they added instead of starting blind. +//! +//! The ticket's history already holds every pull request that names this +//! ticket, and the earlier-attempts search finds ones that name a ticket +//! this one names or read almost the same. A sibling part usually does +//! neither: its title shares the series' words but names another part, and +//! its key is another ticket. This finds those: pull requests in the run's +//! repository that name another part of the same series, or a nearby key of +//! the same project, and share the series' words. + +use std::collections::BTreeSet; + +use tracing::warn; + +use crate::clients::github::GitHubClient; +use crate::passes::feature::prior::{similarity, ticket_keys, words}; +use crate::passes::ticket_history::EarlierPr; + +/// Most sibling pull requests read for one ticket. +const MAX_SIBLINGS: usize = 6; +/// Word overlap with the series' title at or above which a pull request +/// that names another part counts. +const SERIES_WORDS: f64 = 0.2; + +/// Where a ticket sits in its series. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Part { + pub part: u32, + pub total: u32, +} + +/// The series marker a text carries: `part 2 of 4`, `part 2/4`, `(2/4)`, +/// `[2 of 4]`. `None` without one, or with a part outside its total. +pub fn marker(text: &str) -> Option { + let re = regex::Regex::new( + r"(?i)(?:\bpart\s*(\d{1,2})\s*(?:of|/)\s*(\d{1,2})\b|[\(\[]\s*(\d{1,2})\s*(?:of|/)\s*(\d{1,2})\s*[\)\]])", + ) + .ok()?; + let c = re.captures(text)?; + let n = |i: usize, j: usize| { + c.get(i) + .or_else(|| c.get(j)) + .and_then(|m| m.as_str().parse::().ok()) + }; + let part = n(1, 3)?; + let total = n(2, 4)?; + (total >= 2 && (1..=total).contains(&part)).then_some(Part { part, total }) +} + +/// The ticket's series marker, from its title first, then its body. +pub fn of_ticket(title: &str, body: &str) -> Option { + marker(title).or_else(|| marker(body)) +} + +/// The series' words: the title's significant words without the marker. +pub fn series_words(title: &str) -> BTreeSet { + let re = regex::Regex::new( + r"(?i)\bpart\s*\d{1,2}\s*(?:of|/)\s*\d{1,2}\b|[\(\[]\s*\d{1,2}\s*(?:of|/)\s*\d{1,2}\s*[\)\]]", + ); + let mut stripped = match re { + Ok(re) => re.replace_all(title, " ").to_string(), + Err(_) => title.to_string(), + }; + // A ticket key names the ticket, not the series. + for k in ticket_keys(&stripped.clone()) { + stripped = stripped.replace(&k, " "); + } + let mut w = words(&stripped); + w.remove("part"); + w +} + +/// A key's project and number (`ABC-12` is `("ABC", 12)`). +fn key_parts(key: &str) -> Option<(&str, u64)> { + let (p, n) = key.rsplit_once('-')?; + Some((p, n.parse().ok()?)) +} + +/// Whether a pull request (its title, branch and description) is another +/// part of this ticket's series: it names another part of a series of the +/// same length and shares the series' words, or it names a key of the same +/// project within the series' span and shares them. +pub fn is_sibling( + ticket_id: &str, + me: Part, + own_words: &BTreeSet, + pr_title: &str, + pr_branch: &str, + pr_body: &str, +) -> bool { + let head: String = pr_body.chars().take(1500).collect(); + let text = format!("{pr_title}\n{pr_branch}\n{head}"); + if !ticket_id.is_empty() && crate::passes::mentions_ticket(&text, ticket_id) { + // This ticket's own pull request: the ticket's history reads it. + return false; + } + let alike = similarity(own_words, &series_words(pr_title)) >= SERIES_WORDS; + if !alike { + return false; + } + if let Some(p) = marker(&text) { + return p.total == me.total && p.part != me.part; + } + let Some((project, n)) = key_parts(ticket_id) else { + return false; + }; + let span = u64::from(me.total) * 2; + ticket_keys(&text) + .iter() + .any(|k| key_parts(k).is_some_and(|(p, m)| p == project && m != n && m.abs_diff(n) <= span)) +} + +/// Finds the other parts' pull requests in the run's repository, oldest +/// part first. Best-effort and bounded: a list that can't be read adds +/// nothing. +pub async fn find( + github: &GitHubClient, + owner: &str, + name: &str, + ticket_id: &str, + title: &str, + body: &str, +) -> Vec { + let Some(me) = of_ticket(title, body) else { + return Vec::new(); + }; + let own = series_words(title); + let repo = format!("{owner}/{name}"); + let list = match github.list_pull_requests(owner, name, "all", 100).await { + Ok(v) => v, + Err(e) => { + warn!(repo, error = %e, "Could not list pull requests for the ticket's series"); + return Vec::new(); + } + }; + let mut out: Vec = Vec::new(); + for p in list.as_array().into_iter().flatten() { + let number = p["number"].as_u64().unwrap_or(0); + if number == 0 + || !is_sibling( + ticket_id, + me, + &own, + p["title"].as_str().unwrap_or(""), + p["head"]["ref"].as_str().unwrap_or(""), + p["body"].as_str().unwrap_or(""), + ) + { + continue; + } + if let Some(full) = crate::passes::ticket_history::read_pr(github, &repo, number).await { + out.push(full); + } + if out.len() >= MAX_SIBLINGS { + break; + } + } + out.sort_by_key(|p| { + marker(&format!("{}\n{}", p.title, p.body)) + .map(|m| m.part) + .unwrap_or(u32::MAX) + }); + out +} + +/// What the planner is told about the series. Empty when the ticket isn't +/// part of one. +pub fn planner_note(me: Option, repo: &str, siblings: &[EarlierPr]) -> String { + let Some(me) = me else { + return String::new(); + }; + let mut out = format!( + "\n\n## The other parts of this ticket's series\nThis ticket is part {} of {}. ", + me.part, me.total + ); + if siblings.is_empty() { + out.push_str(&format!( + "No pull request for the other parts was found among the last 100 in {repo}. Before \ + planning new code, search the code for what the earlier parts would have added (the \ + fields, components or settings this part builds on) and build on what is there.\n" + )); + return out; + } + out.push_str( + "Their pull requests are below. Build on what they added: read their changed files with \ + your tools before planning, reuse their fields, names and patterns, and don't redo or \ + undo their work. Say in design.md what this part adds on top of them.\n", + ); + for p in siblings { + let part = marker(&format!("{}\n{}", p.title, p.body)) + .map(|m| format!("part {} of {}, ", m.part, m.total)) + .unwrap_or_default(); + out.push_str(&format!( + "- #{} \"{}\" ({part}{}, branch `{}`): {}\n", + p.number, + p.title.trim(), + p.state, + p.branch, + common::truncate_str( + &p.body.split_whitespace().collect::>().join(" "), + 600 + ) + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_series_marker_is_read_in_its_usual_forms() { + let p = |part, total| Some(Part { part, total }); + assert_eq!(marker("Title size setting (Part 4 of 4)"), p(4, 4)); + assert_eq!(marker("part 2/3: the schema"), p(2, 3)); + assert_eq!(marker("Venue blocks [1/4]"), p(1, 4)); + assert_eq!(marker("Venue blocks (3 of 4)"), p(3, 4)); + assert_eq!(marker("No series here, 4 of 4 tests pass"), None); + assert_eq!(marker("part 5 of 4"), None); + assert_eq!(of_ticket("Add a setting", "This is part 4 of 4."), p(4, 4)); + } + + #[test] + fn the_other_parts_are_found_and_unrelated_prs_are_not() { + let title = "Venue page blocks: add a Title Size setting (Section / Page) (Part 4 of 4)"; + let me = of_ticket(title, "").unwrap(); + let own = series_words(title); + assert!(!own.contains("part")); + // Another part of the same series, by its marker. + assert!(is_sibling( + "WEB-104", + me, + &own, + "WEB-101: Venue page blocks: add the block schemas (Part 1 of 4)", + "coderhelm/web-101", + "", + )); + // By a nearby key of the same project, with no marker in the PR. + assert!(is_sibling( + "WEB-104", + me, + &own, + "WEB-103: Venue page blocks title setting", + "coderhelm/web-103", + "", + )); + // This ticket's own PR is the history's, not a sibling. + assert!(!is_sibling( + "WEB-104", + me, + &own, + "WEB-104: Venue page blocks title size (Part 4 of 4)", + "coderhelm/web-104", + "", + )); + // Another series, or unrelated work, is not. + assert!(!is_sibling( + "WEB-104", + me, + &own, + "WEB-90: Checkout redesign (Part 1 of 4)", + "x", + "", + )); + assert!(!is_sibling( + "WEB-104", + me, + &own, + "WEB-102: Venue page blocks (Part 1 of 3)", + "x", + "", + )); + assert!(!is_sibling( + "WEB-104", + me, + &own, + "WEB-180: Venue page blocks title setting", + "x", + "", + )); + } + + #[test] + fn the_planner_is_told_to_build_on_the_earlier_parts() { + assert_eq!(planner_note(None, "a/b", &[]), ""); + let me = Some(Part { part: 4, total: 4 }); + let none = planner_note(me, "a/b", &[]); + assert!(none.contains("part 4 of 4"), "{none}"); + assert!(none.contains("search the code"), "{none}"); + let pr = EarlierPr { + repo: "a/b".into(), + number: 12, + title: "WEB-101: Venue page blocks schemas (Part 1 of 4)".into(), + branch: "coderhelm/web-101".into(), + state: "merged".into(), + body: "Adds the block schemas.".into(), + ..Default::default() + }; + let note = planner_note(me, "a/b", &[pr]); + assert!(note.contains("Build on what they added"), "{note}"); + assert!( + note.contains("- #12 \"WEB-101: Venue page blocks schemas (Part 1 of 4)\" (part 1 of 4, merged, branch `coderhelm/web-101`): Adds the block schemas."), + "{note}" + ); + } +} diff --git a/services/worker/src/passes/triage.rs b/services/worker/src/passes/triage.rs index 9f1a6b1a2..132ddf92c 100644 --- a/services/worker/src/passes/triage.rs +++ b/services/worker/src/passes/triage.rs @@ -43,7 +43,9 @@ impl TicketIntent { /// unreadable answer keeps the root-cause flow. pub fn parse(s: &str) -> TicketIntent { match s.trim().to_ascii_lowercase().as_str() { - "feature" => TicketIntent::Feature, + "feature" | "new_feature" | "new feature" | "enhancement" | "improvement" | "story" => { + TicketIntent::Feature + } "chore" => TicketIntent::Chore, "question" => TicketIntent::Question, _ => TicketIntent::Bug, @@ -146,8 +148,8 @@ Return a JSON object with these fields: - "clarity": "clear" if you have enough info to implement, "needs_clarification" if not - "questions": list of specific questions if clarity is "needs_clarification" (empty list if clear) - "intent": what the ticket asks for, read from its meaning (not its wording or its labels): - - "bug": something that works, or should work, is wrong, missing or failing for its users - - "feature": something new to build, create or add (a new user, resource, endpoint, page, job, integration or setting), including setup work that never existed before + - "bug": something that already exists behaves wrongly or fails (an error, a crash, a wrong value, a regression, data that should show and doesn't) + - "feature": something new to build, create or add (a new user, resource, endpoint, page, field, option, setting, job, integration or capability), including setup work that never existed before. A ticket that asks to add a setting, option, field, page or capability is a feature even when it is phrased as a complaint ("editors can't choose X", "users have no way to Y") - "chore": upkeep with no new behaviour (a dependency bump, a config value, a cleanup, a rename) - "question": asks for information or an investigation, not a change @@ -228,10 +230,250 @@ Rules: common::truncate_str(raw, 200) ) })?; + let mut result = result; + let read = result.intent; + result.intent = settle_intent(read, &msg.title, &msg.body, msg.ticket_type.as_deref()); + if result.intent != read { + info!( + model = read.as_str(), + settled = result.intent.as_str(), + ticket_type = msg.ticket_type.as_deref().unwrap_or(""), + "Triage intent settled from the ticket's type and wording" + ); + } info!(complexity = %result.complexity, clarity = %result.clarity, intent = result.intent.as_str(), "Triage complete"); Ok(result) } +/// What the tracker's own type for a ticket says, when it says something. +fn intent_of_type(ticket_type: &str) -> Option { + let t = ticket_type.trim().to_ascii_lowercase(); + let t = t + .trim_start_matches("type:") + .trim_start_matches("kind/") + .trim(); + match t { + "story" | "user story" | "feature" | "new feature" | "feature request" | "enhancement" + | "improvement" | "epic" => Some(TicketIntent::Feature), + "bug" | "defect" | "regression" | "incident" | "problem" => Some(TicketIntent::Bug), + "chore" | "maintenance" | "tech debt" | "technical debt" => Some(TicketIntent::Chore), + "question" | "spike" | "research" => Some(TicketIntent::Question), + _ => None, + } +} + +/// Verbs that ask for something to be built. +const NEW_WORK_VERBS: &[&str] = &[ + "add", + "adds", + "adding", + "create", + "introduce", + "implement", + "build", + "support", + "enable", + "allow", + "let", + "expose", + "new", +]; + +/// Things a ticket asks to have built. +const NEW_WORK_NOUNS: &[&str] = &[ + "setting", + "settings", + "option", + "options", + "field", + "fields", + "page", + "pages", + "capability", + "ability", + "toggle", + "control", + "dropdown", + "selector", + "picker", + "filter", + "column", + "endpoint", + "button", + "tab", + "section", + "variant", + "mode", + "preference", + "config", + "configuration", + "integration", + "report", + "view", + "menu", + "screen", + "block", + "component", + "widget", + "flag", + "size", + "style", +]; + +/// Words that describe something broken rather than missing. +const DEFECT_WORDS: &[&str] = &[ + "crash", + "crashes", + "crashing", + "error", + "errors", + "broken", + "breaks", + "bug", + "regression", + "regressed", + "fails", + "failing", + "failed", + "failure", + "exception", + "incorrect", + "wrong", + "500", + "404", + "timeout", + "hangs", + "stopped", + "anymore", + "longer", + "duplicate", + "duplicated", +]; + +fn lower_words(text: &str) -> Vec { + text.to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_string) + .collect() +} + +/// Whether a line asks for something new: a new-work verb with a thing to +/// build after it, and nothing that says an existing thing is broken. +fn line_asks_for_new_work(line: &str) -> bool { + let words = lower_words(line); + if words.iter().any(|w| DEFECT_WORDS.contains(&w.as_str())) { + return false; + } + // "Allow admins to ...", "let editors ...", "enable users to ...": a + // request for a capability on its own. + if words + .first() + .is_some_and(|w| matches!(w.as_str(), "allow" | "let" | "enable")) + && words.len() >= 3 + { + return true; + } + words.iter().enumerate().any(|(i, w)| { + NEW_WORK_VERBS.contains(&w.as_str()) + && words + .iter() + .skip(i + 1) + .take(8) + .any(|n| NEW_WORK_NOUNS.contains(&n.as_str())) + }) +} + +/// The ticket's acceptance criteria lines, when it has a section for them. +fn acceptance_lines(body: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut inside = false; + for line in body.lines() { + let low = line.trim().to_ascii_lowercase(); + let heading = low.starts_with('#') || low.ends_with(':') || low.starts_with("**"); + if low.contains("acceptance criteria") || low.contains("definition of done") { + inside = true; + continue; + } + if inside && heading && !low.starts_with("- ") && !low.starts_with("* ") { + if low + .trim_matches(|c: char| !c.is_ascii_alphanumeric()) + .is_empty() + { + continue; + } + inside = false; + } + if inside && !low.is_empty() { + out.push(line.trim()); + } + } + out +} + +/// Whether the ticket's own words ask for new work: the title (the part a +/// person reads first, often ": ") or its acceptance +/// criteria ("editors can choose ...", "a new X setting"). +pub fn asks_for_new_work(title: &str, body: &str) -> bool { + let title_defect = lower_words(title) + .iter() + .any(|w| DEFECT_WORDS.contains(&w.as_str())); + // A title that says something is broken is a bug, whatever it asks + // to add to fix it. + if title_defect { + return false; + } + if title + .split([':', '-', '\u{2013}', '\u{2014}', '(', ')', ';']) + .any(line_asks_for_new_work) + { + return true; + } + let criteria = acceptance_lines(body); + let new_work = criteria + .iter() + .filter(|l| { + line_asks_for_new_work(l) || { + let w = lower_words(l); + let can = w.windows(2).any(|p| { + p[0] == "can" + && matches!( + p[1].as_str(), + "choose" | "select" | "set" | "pick" | "configure" | "toggle" + ) + }); + can && !w.iter().any(|x| DEFECT_WORDS.contains(&x.as_str())) + } + }) + .count(); + new_work > 0 && new_work * 2 >= criteria.len() +} + +/// The ticket's intent, from the model's read and the structured inputs the +/// ticket has: the tracker's own type, then the title's verbs and the +/// acceptance criteria. A ticket that asks to add a setting, option, field, +/// page or capability is new work even when it reads as a complaint; a +/// question or a chore the model named stays what it is. +pub fn settle_intent( + model: TicketIntent, + title: &str, + body: &str, + ticket_type: Option<&str>, +) -> TicketIntent { + let typed = ticket_type.and_then(intent_of_type); + match (model, typed) { + // The model read new work but the tracker says bug: the person + // filing it called it broken, and the text has to show otherwise. + (TicketIntent::Feature, Some(TicketIntent::Bug)) if !asks_for_new_work(title, body) => { + TicketIntent::Bug + } + (TicketIntent::Bug, Some(TicketIntent::Feature)) => TicketIntent::Feature, + (TicketIntent::Bug, Some(TicketIntent::Bug)) => TicketIntent::Bug, + (TicketIntent::Bug, _) if asks_for_new_work(title, body) => TicketIntent::Feature, + (m, _) => m, + } +} + /// No-op tool executor for passes that don't need tools. pub(crate) struct NoOpExecutor; @@ -801,7 +1043,98 @@ mod tests { #[cfg(test)] mod intent_tests { - use super::{TicketIntent, TriageResult}; + use super::{asks_for_new_work, settle_intent, TicketIntent, TriageResult}; + + #[test] + fn a_setting_asked_for_as_a_complaint_is_new_work() { + // The live case: a complaint, then what to add, with a Story type + // or with none at all. + let title = "Editors can't choose a block's title size: add a Title Size setting \ + (Section / Page) to the venue page blocks"; + let body = "Part 4 of 4.\n\nAcceptance criteria:\n- Editors can choose Section or Page \ + for each block's title\n- The site renders the chosen size"; + assert!(asks_for_new_work(title, body)); + for t in [None, Some("Story"), Some("Task")] { + assert_eq!( + settle_intent(TicketIntent::Bug, title, body, t), + TicketIntent::Feature, + "{t:?}" + ); + } + } + + #[test] + fn varied_new_work_phrasings_are_features() { + for (title, body) in [ + ("Allow admins to set a default timezone", ""), + ("Support a dark mode option in settings", ""), + ("Create a new page for venue events", ""), + ("Add an export button to the reports view", ""), + ("Users have no way to filter orders by date: add a date filter", ""), + ( + "Users can't export reports to CSV", + "## Acceptance criteria\n- Users can select CSV in the export menu\n- The file downloads", + ), + ] { + assert_eq!( + settle_intent(TicketIntent::Bug, title, body, None), + TicketIntent::Feature, + "{title}" + ); + } + } + + #[test] + fn real_bugs_stay_bugs() { + for (title, body, t) in [ + ("Add a null check so checkout stops crashing", "", None), + ("Login button doesn't work on Safari", "", None), + ("Price field shows the wrong currency", "", None), + ("Venue hours are missing on the venue page", "", None), + ( + "The new settings page throws an error on save", + "## Acceptance criteria\n- Saving works without an error", + None, + ), + ("Header overlaps the menu on mobile", "", Some("Bug")), + ("Search fails: add a missing index field", "", None), + ] { + assert_eq!( + settle_intent(TicketIntent::Bug, title, body, t), + TicketIntent::Bug, + "{title}" + ); + } + // A tracker that calls it a bug wins over a model that read new + // work, unless the text plainly asks for something new. + assert_eq!( + settle_intent( + TicketIntent::Feature, + "Totals are off by one", + "", + Some("Bug") + ), + TicketIntent::Bug + ); + assert_eq!( + settle_intent( + TicketIntent::Feature, + "Add a page size option to the table", + "", + Some("Bug") + ), + TicketIntent::Feature + ); + // Chores and questions stay what the model read. + assert_eq!( + settle_intent(TicketIntent::Chore, "Bump the SDK", "", Some("Story")), + TicketIntent::Chore + ); + assert_eq!( + settle_intent(TicketIntent::Bug, "Totals are off", "", Some("Story")), + TicketIntent::Feature + ); + } #[test] fn the_models_intent_is_read_and_anything_else_is_a_bug() { @@ -818,7 +1151,8 @@ mod intent_tests { assert_eq!(old.intent, TicketIntent::Bug); assert_eq!(TicketIntent::parse("chore"), TicketIntent::Chore); assert_eq!(TicketIntent::parse("question"), TicketIntent::Question); - assert_eq!(TicketIntent::parse("enhancement"), TicketIntent::Bug); + assert_eq!(TicketIntent::parse("enhancement"), TicketIntent::Feature); + assert_eq!(TicketIntent::parse("something else"), TicketIntent::Bug); assert!(!TicketIntent::Feature.is_bug()); let json = serde_json::to_string(&r).unwrap(); assert!(json.contains("\"intent\":\"feature\""), "{json}");