diff --git a/coderhelm-jira/src/issues.js b/coderhelm-jira/src/issues.js index 86cf18cfe..47cda6d69 100644 --- a/coderhelm-jira/src/issues.js +++ b/coderhelm-jira/src/issues.js @@ -35,6 +35,43 @@ function jqlFor(query) { return `text ~ "${words}" ORDER BY updated DESC`; } +/** + * The account ids an Atlassian document mentions (`@Name` nodes), each once, + * in reading order. A mention is a node of type "mention" whose `attrs.id` + * is the person's account id. + */ +function adfMentions(node, out = []) { + if (!node || typeof node !== "object") return out; + if (node.type === "mention" && node.attrs && typeof node.attrs.id === "string" && node.attrs.id) { + if (!out.includes(node.attrs.id)) out.push(node.attrs.id); + } + for (const child of Array.isArray(node.content) ? node.content : []) adfMentions(child, out); + return out; +} + +/** + * The account id in a Jira user object, or "" when there is none. Jira user + * objects carry `accountId`; anything else (an old payload) has no id. + */ +function accountIdOf(user) { + return (user && typeof user.accountId === "string" && user.accountId) || ""; +} + +/** + * The JQL for "what is waiting on this person": the open issues assigned to + * them, most important and newest change first; and the open issues they + * watch or reported that changed lately (where they may be asked something). + * The account id is checked to be an account id, so it can't end the string. + */ +function mineJql(accountId) { + const id = String(accountId || ""); + if (!/^[A-Za-z0-9:-]{8,128}$/.test(id)) return null; + return { + assigned: `assignee = "${id}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`, + involved: `(watcher = "${id}" OR reporter = "${id}") AND statusCategory != Done AND updated >= -14d ORDER BY updated DESC`, + }; +} + /** One issue as CoderHelm reads it, from the issue REST API's shape. */ function issueOf(raw, links) { const f = (raw && raw.fields) || {}; @@ -42,6 +79,10 @@ function issueOf(raw, links) { .slice(-MAX_ISSUE_COMMENTS) .map((c) => ({ author: (c.author && c.author.displayName) || "", + // Who wrote it and who it mentions, as account ids, so CoderHelm can + // tell a question to a person they haven't answered yet. + author_id: accountIdOf(c.author), + mentions: adfMentions(c.body), created: c.created || "", text: adfText(c.body).trim().slice(0, MAX_COMMENT_CHARS), })); @@ -50,8 +91,13 @@ function issueOf(raw, links) { summary: f.summary || "", type: (f.issuetype && f.issuetype.name) || "", status: (f.status && f.status.name) || "", + // "new", "indeterminate" or "done": where the status sits in the workflow. + status_category: (f.status && f.status.statusCategory && f.status.statusCategory.key) || "", assignee: (f.assignee && f.assignee.displayName) || "", + assignee_id: accountIdOf(f.assignee), + reporter_id: accountIdOf(f.reporter), priority: (f.priority && f.priority.name) || "", + due: f.duedate || "", updated: f.updated || "", created: f.created || "", comments, @@ -63,4 +109,17 @@ function issueOf(raw, links) { }; } -module.exports = { adfText, jqlFor, issueOf, MAX_SEARCH, MAX_ISSUE_COMMENTS, MAX_COMMENT_CHARS }; +/** The most issues one "what is waiting on me" read returns, of each kind. */ +const MAX_MINE = 15; + +module.exports = { + adfText, + adfMentions, + jqlFor, + mineJql, + issueOf, + MAX_SEARCH, + MAX_MINE, + MAX_ISSUE_COMMENTS, + MAX_COMMENT_CHARS, +}; diff --git a/coderhelm-jira/src/release.js b/coderhelm-jira/src/release.js index ed610d9b6..50b10fb52 100644 --- a/coderhelm-jira/src/release.js +++ b/coderhelm-jira/src/release.js @@ -7,7 +7,7 @@ const api = require("@forge/api"); const { storage, route } = api; -const { jqlFor, issueOf, MAX_SEARCH } = require("./issues"); +const { jqlFor, mineJql, issueOf, MAX_SEARCH, MAX_MINE } = require("./issues"); const json = (statusCode, obj) => ({ statusCode, @@ -24,7 +24,9 @@ async function authorized(body) { /** One issue with its remote links; null when it can't be read. */ async function readIssue(key) { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${key}?fields=summary,issuetype,status,assignee,priority,updated,created,comment`); + const res = await api + .asApp() + .requestJira(route`/rest/api/3/issue/${key}?fields=summary,issuetype,status,assignee,reporter,priority,duedate,updated,created,comment`); if (!res.ok) return null; // unknown key / no access → dropped const raw = await res.json(); let links = []; @@ -37,17 +39,72 @@ async function readIssue(key) { return issueOf(raw, links); } +/** The issue keys a JQL search finds (up to `max`), or [] when it can't run. */ +async function keysFor(jql, max) { + const res = await api.asApp().requestJira(route`/rest/api/3/search/jql`, { + method: "POST", + headers: { Accept: "application/json", "Content-Type": "application/json" }, + body: JSON.stringify({ jql, maxResults: max, fields: ["summary"] }), + }); + if (!res.ok) return { keys: [], ok: false }; + const found = await res.json(); + return { keys: ((found && found.issues) || []).map((i) => i.key).filter(Boolean).slice(0, max), ok: true }; +} + +/** Reads issues by key, a few at a time, skipping any that can't be read. */ +async function readIssues(keys) { + const issues = []; + for (let i = 0; i < keys.length; i += 5) { + const batch = await Promise.all(keys.slice(i, i + 5).map((k) => readIssue(k).catch(() => null))); + issues.push(...batch.filter(Boolean)); + } + return issues; +} + +/** + * The "what is waiting on me" read: the open issues assigned to the person, + * and the open ones they watch or reported that changed in the last two + * weeks (CoderHelm reads those for questions to them they haven't answered). + */ +async function mineHandler(mine) { + // CoderHelm sends the person's account id (from the Jira events it has + // seen); the app reads no user directory, so it needs no user scope. + const accountId = String((mine && mine.account_id) || ""); + const jql = mineJql(accountId); + if (!jql) { + return json(200, { issues: [], mine: { found: false, why: "no Jira account id was sent" } }); + } + const assigned = await keysFor(jql.assigned, MAX_MINE); + // Watchers can be hidden from the app; then only assigned issues are read. + const involved = await keysFor(jql.involved, MAX_MINE).catch(() => ({ keys: [], ok: false })); + const keys = [...new Set([...assigned.keys, ...involved.keys])]; + return json(200, { + issues: await readIssues(keys), + mine: { + found: true, + account_id: accountId, + assigned: assigned.keys, + assigned_read: assigned.ok, + involved_read: involved.ok, + }, + }); +} + /** * POST { forge_secret, keys: ["ABC-1", ...] } or { forge_secret, query: "words" } + * or { forge_secret, mine: { account_id?, email? } } * → { issues: [{key, summary, type, status, assignee, priority, updated, created, comments, links}] } * * By keys: each issue the app can read (release notes, Chat). By query: the - * issues whose text matches, newest change first (Chat's ticket lookup). + * issues whose text matches, newest change first (Chat's ticket lookup). By + * mine: what is waiting on one person (Chat's "what needs me"), with a `mine` + * object that says whose it is; an older app version leaves `mine` out. */ exports.getIssuesHandler = async (request) => { try { const body = JSON.parse(request.body || "{}"); if (!(await authorized(body))) return json(403, { error: "forbidden" }); + if (body.mine && typeof body.mine === "object") return await mineHandler(body.mine); let keys = (Array.isArray(body.keys) ? body.keys : []) .filter((k) => /^[A-Z][A-Z0-9]+-\d+$/.test(k)) .slice(0, 50); diff --git a/coderhelm-jira/test/issues.test.js b/coderhelm-jira/test/issues.test.js index 7abf7fd85..81d6c607b 100644 --- a/coderhelm-jira/test/issues.test.js +++ b/coderhelm-jira/test/issues.test.js @@ -1,6 +1,6 @@ const { test } = require("node:test"); const assert = require("node:assert/strict"); -const { adfText, jqlFor, issueOf } = require("../src/issues"); +const { adfText, adfMentions, jqlFor, mineJql, issueOf } = require("../src/issues"); const doc = (text) => ({ type: "doc", version: 1, content: [{ type: "paragraph", content: [{ type: "text", text }] }] }); @@ -36,3 +36,37 @@ test("an issue carries its status, people, dates, newest comments and https link assert.deepEqual(i.links, [{ title: "PR #5", url: "https://github.com/acme/web/pull/5" }]); assert.equal(adfText(doc("hi")).trim(), "hi"); }); + +test("mentions and account ids come with each comment, for questions a person hasn't answered", () => { + const mention = (id, text) => ({ type: "mention", attrs: { id, text } }); + const body = { + type: "doc", + content: [{ type: "paragraph", content: [mention("acc-dana-0001", "@Dana"), { type: "text", text: " can you confirm?" }, mention("acc-dana-0001", "@Dana")] }], + }; + const i = issueOf({ + key: "ABC-8", + fields: { + summary: "Pick the retry limit", + status: { name: "To Do", statusCategory: { key: "new" } }, + assignee: { accountId: "acc-dana-0001", displayName: "Dana" }, + reporter: { accountId: "acc-sam-0002", displayName: "Sam" }, + duedate: "2026-11-20", + comment: { comments: [{ author: { accountId: "acc-sam-0002", displayName: "Sam" }, created: "c1", body }] }, + }, + }); + assert.equal(i.status_category, "new"); + assert.equal(i.assignee_id, "acc-dana-0001"); + assert.equal(i.reporter_id, "acc-sam-0002"); + assert.equal(i.due, "2026-11-20"); + assert.equal(i.comments[0].author_id, "acc-sam-0002"); + assert.deepEqual(i.comments[0].mentions, ["acc-dana-0001"]); + assert.deepEqual(adfMentions(null), []); +}); + +test("the waiting-on-me JQL takes only an account id, never more clauses", () => { + const q = mineJql("557058:0a1b2c3d-1111-2222-3333-444455556666"); + assert.match(q.assigned, /^assignee = "557058:0a1b2c3d-1111-2222-3333-444455556666" AND statusCategory != Done/); + assert.match(q.involved, /watcher = .* OR reporter = /); + assert.equal(mineJql('x" OR project = SECRET'), null); + assert.equal(mineJql(""), null); +}); diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index de8ea2bde..393857d7d 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -233,6 +233,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("work_runs", Risk::Read), ("work_findings", Risk::Read), ("work_records", Risk::Read), + ("work_needs_me", Risk::Read), // A chat asking the person to connect an account (shows a sign-in card). ("request_sign_in", Risk::Read), // Plugin runs: the plugin's own skills, and drafts kept in CoderHelm diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index 3c0684e45..738072917 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -752,6 +752,9 @@ pub struct Starter { /// How many starter questions the empty chat shows. pub const STARTERS: usize = 4; +/// The starter that asks what is waiting on the person. +pub const NEEDS_ME_STARTER: &str = "What needs my answer?"; + fn short_repo(repo: &str) -> &str { repo.rsplit('/').next().unwrap_or(repo) } @@ -819,29 +822,27 @@ pub fn starter_questions( .find(|r| repos.contains(r)) .or(repos.first()); - // Runs waiting on an answer lead: they are what someone has to act on. - let waiting: Vec<&RecentRun> = runs + // What waits on the person leads: it's what they have to act on. The + // answer reads every source for them (`chat_work_needs`), so it's + // offered whenever there's work to read, not only when a run waits. + let waiting = runs .iter() .filter(|r| r.status == common::run_status::NEEDS_INPUT && valid_run_id(&r.id)) - .take(MAX_RUN_CONTEXT) - .collect(); - if !waiting.is_empty() { + .count(); + if waiting > 0 || !repos.is_empty() { push( Starter { - question: "What needs my answer?".into(), - why: if waiting.len() == 1 { - "1 run is waiting on an answer".into() - } else { - format!("{} runs are waiting on an answer", waiting.len()) + question: NEEDS_ME_STARTER.into(), + why: match waiting { + 0 => "Runs, tickets and pull requests waiting on you".into(), + 1 => "1 run is waiting on an answer".into(), + n => format!("{n} runs are waiting on an answer"), + }, + sources: Picks { + work: true, + ..Default::default() }, - sources: Picks::default(), - mentions: waiting - .iter() - .map(|r| Mention { - kind: "run".into(), - id: r.id.clone(), - }) - .collect(), + mentions: Vec::new(), }, &mut out, ); @@ -1162,7 +1163,8 @@ How to work: - "What does file Y do?": read it (in ranges when it is long) and the files it leans on when that matters. - Never hand work back. Don't ask the person to open, read, paste or attach a file, to say which repository or who owns it, or to look something up: your tools do that. When a tool fails, try another way (another path, a search, the file listing). Say something isn't there only after you looked, and say where you looked. - Ask the person only for what no tool can reach, such as a decision or a preference. -- The team's own work lives in the work tools (work_tickets, work_pull_requests, work_runs, work_findings, work_records), not in the code or the docs. "What's the latest on X", "where are we on", "status of", a ticket key, a pull request number, a run, "what's running", a CVE id or a package, a quoted title: look it up there first (the ticket, then its pull requests and Coderhelm's runs on it), then read code or docs only for context. Give a dated status: say when each record last changed. Never say there's nothing on it before you searched the tickets, pull requests and runs. Once a record gives you a ticket key or a pull request number, look the rest up by that key or number, not by the title again. +- The team's own work lives in the work tools (work_needs_me, work_tickets, work_pull_requests, work_runs, work_findings, work_records), not in the code or the docs. "What's the latest on X", "where are we on", "status of", a ticket key, a pull request number, a run, "what's running", a CVE id or a package, a quoted title: look it up there first (the ticket, then its pull requests and Coderhelm's runs on it), then read code or docs only for context. Give a dated status: say when each record last changed. Never say there's nothing on it before you searched the tickets, pull requests and runs. Once a record gives you a ticket key or a pull request number, look the rest up by that key or number, not by the title again. +- What is waiting on the person asking ("what needs my answer", "what needs me", "what's on my plate", "what should I work on", their reviews, their tickets, "am I blocking anyone"): call work_needs_me first, once. It finds who they are and reads Coderhelm's runs, approvals, Jira and GitHub for them. Answer in the shape its result gives: the count line, then the groups most urgent first, one line per item with its link and exactly what to do, a run's questions with their options, then a plain sentence for each source it couldn't read. - When a lookup the answer needed couldn't be read and no other way found it, say so in one short sentence in the answer (which records, such as "Coderhelm's runs couldn't be read just now"), then answer from what you did read. Don't mention a failed lookup that another one made up for. - Don't guess a field, column, type or property name. Before you query a data source, a CMS or a database, read its schema (its describe, schema or mapping tool) and query with the names it lists. @@ -1473,10 +1475,39 @@ fn tool_label(name: &str, input: &Value) -> String { let (server, tool) = n.split_once("__").unwrap_or((n, "")); format!("{server}: {}", tool.replace('_', " ")) } - n => n.replace('_', " "), + n => data_source_label(n, input).unwrap_or_else(|| n.replace('_', " ")), } } +/// What the dashboard shows for a data source's lookup (the worker's +/// `api_get`, `db_query`, ...), in words: "Read /v1/orders from Orders API". +/// `None` for a tool that isn't one. +pub fn data_source_label(name: &str, input: &Value) -> Option { + let source = input["source"] + .as_str() + .or_else(|| input["api"].as_str()) + .map(|s| common::truncate_str(s.trim(), 40).to_string()) + .filter(|s| !s.is_empty()); + let from = |default: &str| source.clone().unwrap_or_else(|| default.to_string()); + Some(match name { + "api_get" => { + let path = common::truncate_str(input["path"].as_str().unwrap_or("").trim(), 60); + if path.is_empty() { + format!("Read from {}", from("the team's API")) + } else { + format!("Read {path} from {}", from("the team's API")) + } + } + "live_lookup" => format!("Looked up {}", from("a live source")), + "live_describe" => format!("Read the shape of {}", from("a live source")), + "db_query" => format!("Queried {}", from("the database")), + "logs_search" => format!("Searched the logs in {}", from("the team's logs")), + "search_read" | "opensearch_search" => format!("Searched {}", from("the search index")), + "opensearch_mapping" => format!("Read the fields of {}", from("the search index")), + _ => return None, + }) +} + /// The plugins store (settings table), for the plugins source. fn plugin_kv(state: &AppState) -> common::plugins::kv::Dynamo { common::plugins::kv::Dynamo { @@ -2615,14 +2646,7 @@ async fn answer( notes.push_str(&super::chat_work::hint_note(&hints, &offered)); // A status question's answer is in the tickets, pull requests and runs: // an answer that found nothing without looking there goes back once. - let must_look = hints.about_work().then(|| chat_agent::MustLook { - tools: super::chat_work::STATUS_TOOLS - .iter() - .filter(|t| offered.contains(t)) - .map(|t| t.to_string()) - .collect(), - what: "the team's tickets, pull requests and Coderhelm's runs".into(), - }); + let must_look = super::chat_work::must_look(&hints, &offered); notes.push_str(&run.run_note); if !problems.is_empty() { notes.push_str(&format!( @@ -2811,24 +2835,47 @@ mod tests { } #[test] - fn waiting_runs_lead_the_starters_and_carry_their_ids() { + fn a_data_source_lookup_says_what_it_read() { + assert_eq!( + tool_label( + "api_get", + &json!({"source": "Orders API", "path": "/v1/orders/42"}) + ), + "Read /v1/orders/42 from Orders API" + ); + assert_eq!( + tool_label("api_get", &json!({"path": "/v1/orders"})), + "Read /v1/orders from the team's API" + ); + assert_eq!( + tool_label("db_query", &json!({"source": "billing"})), + "Queried billing" + ); + // Nothing reads "api get" any more; an unknown tool keeps its name. + assert!(!tool_label("api_get", &json!({})).contains("api get")); + assert_eq!(tool_label("some_tool", &json!({})), "some tool"); + } + + #[test] + fn what_needs_me_leads_the_starters_and_reads_everything() { let mut waiting = run("Add a Heading component", "acme/web"); waiting.id = "01RUNWAITING".into(); waiting.status = "needs_input".into(); let repos = vec!["acme/web".to_string()]; let s = starter_questions(&[], &repos, &[waiting, run("Fix login", "acme/web")]); - assert_eq!(s[0].question, "What needs my answer?"); + assert_eq!(s[0].question, NEEDS_ME_STARTER); assert_eq!(s[0].why, "1 run is waiting on an answer"); - assert_eq!( - s[0].mentions, - vec![Mention { - kind: "run".into(), - id: "01RUNWAITING".into() - }] - ); - // Without waiting runs there is no such starter. + // It reads everything waiting on the person, not only the runs: no + // run mentions, the team's work on. + assert!(s[0].mentions.is_empty()); + assert!(s[0].sources.work); + assert!(crate::routes::chat_hints::read(NEEDS_ME_STARTER).needs_me); + // Without waiting runs it still leads, for tickets and reviews. let s = starter_questions(&[], &repos, &[run("Fix login", "acme/web")]); - assert!(s.iter().all(|x| x.question != "What needs my answer?")); + assert_eq!(s[0].question, NEEDS_ME_STARTER); + assert_eq!(s[0].why, "Runs, tickets and pull requests waiting on you"); + // With nothing connected there is nothing to read. + assert!(starter_questions(&[], &[], &[]).is_empty()); } #[test] @@ -2890,19 +2937,20 @@ mod tests { ]; let s = starter_questions(&bases, &repos, &runs); assert_eq!(s.len(), STARTERS); - assert_eq!(s[0].question, "What should I know from HR handbook?"); - assert_eq!(s[0].sources.knowledge, vec!["kb1".to_string()]); - assert!(!s[0].sources.code); + // What waits on the person leads. + assert_eq!(s[0].question, NEEDS_ME_STARTER); + assert_eq!(s[1].question, "What should I know from HR handbook?"); + assert_eq!(s[1].sources.knowledge, vec!["kb1".to_string()]); + assert!(!s[1].sources.code); assert_eq!( - s[1].question, + s[2].question, "What's the latest on “Add rate limiting to login”?" ); - assert_eq!(s[1].why, "From recent work in web"); - assert!(s[1].sources.code); - assert_eq!(s[1].sources.repo.as_deref(), Some("acme/web")); + assert_eq!(s[2].why, "From recent work in web"); + assert!(s[2].sources.code); + assert_eq!(s[2].sources.repo.as_deref(), Some("acme/web")); // The repository with the latest run leads, not the first by name. - assert_eq!(s[2].question, "How is web put together?"); - assert!(s[3].sources.memories && !s[3].sources.code); + assert_eq!(s[3].question, "How is web put together?"); // A run in a repository that is no longer connected is never offered. assert!(s.iter().all(|q| !q.question.contains("Old work"))); // Every starter turns on at least one source. @@ -2922,8 +2970,8 @@ mod tests { assert!(s.iter().all(|q| q.sources.knowledge.len() == 1)); let long = "word ".repeat(40); let s = starter_questions(&[], &["a/b".into()], &[run(&long, "a/b")]); - assert!(s[0].question.contains('…')); - assert!(s[0].question.chars().count() < 110); + assert!(s[1].question.contains('…')); + assert!(s[1].question.chars().count() < 110); } #[test] diff --git a/services/gateway/src/routes/chat_agent.rs b/services/gateway/src/routes/chat_agent.rs index a492647df..bd1a16a35 100644 --- a/services/gateway/src/routes/chat_agent.rs +++ b/services/gateway/src/routes/chat_agent.rs @@ -108,12 +108,15 @@ pub struct Ask<'a> { /// The tools a question's answer lives in (a status question: the tickets, /// pull requests and runs). An answer that says it found nothing without -/// calling any of them is sent back once. +/// calling any of them is sent back once; with `always`, any answer that +/// didn't call one is ("what needs me" is only ever answered from its tool). #[derive(Debug, Clone, Default, PartialEq)] pub struct MustLook { pub tools: Vec, /// Where to look, in a few words ("the ticket, its pull requests and runs"). pub what: String, + /// Send back any answer that didn't look there, found or not. + pub always: bool, } /// The note sent back when an answer found nothing without looking where @@ -127,6 +130,16 @@ pub fn look_there(what: &str, tools: &[String]) -> String { ) } +/// The note sent back when an answer didn't read the one place its answer +/// comes from. +pub fn answer_from(what: &str, tools: &[String]) -> String { + format!( + "This question is answered from {what}, and you didn't look there. Call {} now, \ + then answer in the shape its result gives, with citations.", + tools.join(", ") + ) +} + /// The note sent back when an answer guessed a field or type name. pub const READ_THE_SCHEMA: &str = "Your answer says it guessed a field, column or type \ name. Don't guess: read the source's schema first (its describe, schema or mapping tool), then \ @@ -148,6 +161,9 @@ pub fn checked_in_code( .cloned() .collect(); let looked = calls.iter().any(|c| m.tools.contains(c)); + if !offered.is_empty() && !looked && m.always { + return Some(answer_from(&m.what, &offered)); + } if !offered.is_empty() && !looked && says_nothing_found(answer) { return Some(look_there(&m.what, &offered)); } diff --git a/services/gateway/src/routes/chat_eval.rs b/services/gateway/src/routes/chat_eval.rs index d2b4399fa..267645f04 100644 --- a/services/gateway/src/routes/chat_eval.rs +++ b/services/gateway/src/routes/chat_eval.rs @@ -30,6 +30,11 @@ //! holds two teams, and pass only when the answer looked where the answer //! lives, cites those records, states their facts and dates, and says //! nothing of the other team. `live_work_eval` runs them against the model. +//! +//! "What needs me", in other words than the starter's, is a work case too: +//! it passes only when the answer came from `work_needs_me` (the real +//! gathering over `chat_work_needs`' two-team fixture), leads with the count, +//! keeps a run's options, and cites a run, a ticket and a pull request. use super::brain::system_prompt; use super::chat_agent::testing::{CodeBox, Recorder}; @@ -591,6 +596,41 @@ impl<'a> WorkBox<'a> { } } +impl WorkBox<'_> { + /// "What needs me" over `chat_work_needs`' fixture (runs, approvals, + /// Jira and GitHub for two teams), as this box's team. + async fn needs_me(&self, reg: &mut Registry) -> Called { + use super::chat_work_needs::{self as needs, tests as fx}; + let store = fx::store(); + let http = fx::http(); + let app = fx::app(); + let repos = vec!["acme/web".to_string(), "acme/api".to_string()]; + let src = needs::Sources { + team: if self.team == TEAM { + fx::TEAM + } else { + fx::OTHER + }, + store: &store, + http: &http, + jira: Some(&app), + github: Some(fx::gh()), + repos: &repos, + readable: &self.readable, + budget: needs::SOURCE_BUDGET, + }; + let report = needs::gather(&src, fx::me(), fx::now()).await; + let (text, summary) = needs::render(&report, reg, "2026-11-16 12:00 UTC"); + Called::Done { + text, + label: work::label(work::NEEDS_ME, &json!({})), + summary, + is_error: false, + kind: "work".into(), + } + } +} + #[async_trait::async_trait] impl Toolbox for WorkBox<'_> { fn defs(&self) -> &[Value] { @@ -603,6 +643,9 @@ impl Toolbox for WorkBox<'_> { name: &str, input: &Value, ) -> Called { + if name == work::NEEDS_ME { + return self.needs_me(reg).await; + } let (text, summary, is_error) = match self.find(name, input) { Ok((found, noun)) => work::register(reg, found, noun, ""), Err(e) => (e, "Not allowed".into(), true), @@ -679,6 +722,19 @@ pub const WORK_CASES: &[WorkCase] = &[ facts: &[&["TLS 1.0"], &["snapshot"]], never: &["Old container image", "Secret bucket"], }, + WorkCase { + name: "what needs me, in other words", + question: "Anything waiting on me today?", + uses_all: &[work::NEEDS_ME], + cites: &["run", "ticket", "pull_request"], + facts: &[ + &["things need you"], + &["3 tries"], + &["ABC-10"], + &["acme/web#41", "#41"], + ], + never: &["OTH-9", "drop_table", "other/secret"], + }, WorkCase { name: "a ticket the asker can't see", question: "What's the latest on OTH-9?", @@ -743,14 +799,7 @@ pub async fn ask_work( work::put_first(&mut tb.defs, &hints); let offered: Vec<&str> = tb.defs.iter().filter_map(|t| t["name"].as_str()).collect(); let notes = work::hint_note(&hints, &offered); - let must_look = hints.about_work().then(|| chat_agent::MustLook { - tools: work::STATUS_TOOLS - .iter() - .filter(|t| offered.contains(t)) - .map(|t| t.to_string()) - .collect(), - what: "the team's tickets, pull requests and Coderhelm's runs".into(), - }); + let must_look = work::must_look(&hints, &offered); let sink = Recorder::default(); let mut reg = Registry::default(); let (_, repos) = fixture(); @@ -999,6 +1048,7 @@ mod tests { )) }), ], + "what needs me, in other words" => needs_script(), _ => vec![ Box::new(|_| calls("a", work::TICKETS, json!({"key": "OTH-9"}))), Box::new(|_| calls("b", work::RUNS, json!({"ticket": "OTH-9"}))), @@ -1009,6 +1059,65 @@ mod tests { } } + /// A good "what needs me" answer: one call, then the shape it gives. + fn needs_script() -> Vec { + vec![ + Box::new(|_| calls("n", work::NEEDS_ME, json!({}))), + Box::new(|b| { + let r = last_result(b); + let count = r + .lines() + .find_map(|l| l.strip_prefix("Count line: ")) + .unwrap_or("") + .to_string(); + let (run, ticket, pr) = ( + ids_of(b, "run")[0].clone(), + ids_of(b, "ticket")[0].clone(), + ids_of(b, "pull_request")[0].clone(), + ); + say(&format!( + "{count}\n\n**Needs you now**\n- [ABC-1 Retry the export job](/runs/detail?id=01A): answer the run's question, since Nov 14 [{run}]\n - Which retry limit should the job use? Possible answers: 3 tries; 5 tries\n - [ABC-10 Payments fail on retry](https://team.atlassian.net/browse/ABC-10): move it forward, Highest priority [{ticket}]\n - [acme/web#41 Add slips](https://github.com/acme/web/pull/41): review it, your review was asked for [{pr}]" + )) + }), + ] + } + + /// "What needs me" is never answered from the runs alone: an answer + /// that didn't gather everything is sent back once, whatever it says. + #[tokio::test] + async fn offline_what_needs_me_is_never_answered_from_the_runs_alone() { + let store = work_store(); + let case = WORK_CASES + .iter() + .find(|c| c.name == "what needs me, in other words") + .unwrap(); + let mut steps: Vec = vec![ + Box::new(|_| calls("r", work::RUNS, json!({"status": "waiting"}))), + Box::new(|_| say("One run is waiting on your answer.")), + ]; + steps.extend(needs_script()); + let model = Scripted::new(steps, vec![r#"{"hands_back": false}"#]); + let (out, _) = ask_work(&model, &store, all_kinds(), case).await; + assert!(out.rechecked); + assert!( + grade_work(case, &out).is_empty(), + "{:?}\n{}", + grade_work(case, &out), + out.fin.text + ); + let bodies = model.bodies.lock().unwrap(); + // The first turn offered the tool first and said to call it. + assert_eq!(bodies[0]["tools"][0]["name"], work::NEEDS_ME); + assert!(bodies[0]["messages"] + .to_string() + .contains("Call work_needs_me first")); + let nudged = bodies[2]["messages"].to_string(); + assert!( + nudged.contains("you didn't look there") && nudged.contains(work::NEEDS_ME), + "{nudged}" + ); + } + #[tokio::test] async fn offline_every_work_case_passes_with_a_good_trajectory() { let store = work_store(); diff --git a/services/gateway/src/routes/chat_hints.rs b/services/gateway/src/routes/chat_hints.rs index 70853f680..1ab759029 100644 --- a/services/gateway/src/routes/chat_hints.rs +++ b/services/gateway/src/routes/chat_hints.rs @@ -1,7 +1,8 @@ //! What a Chat question names, read without a model: a ticket key, a pull //! request number, a CVE or advisory id, a quoted title, a status question //! ("what's the latest", "where are we") or "what's running". The hints put -//! the tool that holds the answer first and tell the model where to look; +//! the tool that holds the answer first and tell the model where to look +//! ("what needs me", in any words, goes to the tool that gathers it); //! they never route on their own (the model still picks its tools). //! //! The same reading tells the answer check (`chat_agent`) when an answer @@ -87,6 +88,40 @@ const FINDING_WORDS: &[&str] = &[ "security issue", ]; +/// Words that ask what is waiting on the asker ("what needs my answer"). +const NEEDS_ME_WORDS: &[&str] = &[ + "needs my", + "need my", + "needs me", + "need me", + "waiting on me", + "waiting for me", + "waiting on my", + "blocked on me", + "blocking anyone", + "am i blocking", + "on my plate", + "should i work on", + "should i look at", + "for me to do", + "anything for me", + "my todo", + "my to-do", + "my to do", + "my queue", + "my inbox", + "my action items", + "my reviews", + "review requests", + "reviews pending", + "pending reviews", + "my tickets", + "my prs", + "my pull requests", + "assigned to me", + "mentioned me", +]; + /// Prefixes of ids that look like ticket keys but are not. const NOT_TICKETS: &[&str] = &[ "CVE", "GHSA", "UTF", "SHA", "ISO", "RFC", "HTTP", "TLS", "SSL", "AES", "MD", "ES", "IPV", @@ -107,6 +142,8 @@ pub struct Hints { pub running: bool, /// It asks about security or infrastructure findings. pub findings: bool, + /// It asks what is waiting on the asker. + pub needs_me: bool, } /// The most of each kind a question carries into the note. @@ -158,6 +195,8 @@ pub fn read(question: &str) -> Hints { h.running = RUNNING_WORDS.iter().any(|w| lower.contains(w)); h.findings = !h.advisories.is_empty() || FINDING_WORDS.iter().any(|w| lower.contains(w)); h.status = h.running || STATUS_WORDS.iter().any(|w| has_word(&lower, w)); + let plain = lower.replace('\u{2019}', "'"); + h.needs_me = NEEDS_ME_WORDS.iter().any(|w| has_word(&plain, w)); h } @@ -175,6 +214,7 @@ impl Hints { /// a run, a finding, a quoted title, or where something stands. pub fn about_work(&self) -> bool { self.status + || self.needs_me || self.running || self.findings || !self.tickets.is_empty() @@ -266,6 +306,31 @@ mod tests { assert!(h.running && h.status && h.about_work()); } + #[test] + fn what_is_waiting_on_me_is_its_own_question() { + for q in [ + "What needs my answer?", + "what needs me?", + "Is anything waiting on me?", + "What\u{2019}s on my plate today?", + "what should I work on next", + "show my pull requests", + "Am I blocking anyone?", + ] { + let h = read(q); + assert!(h.needs_me && h.about_work(), "{q}: {h:?}"); + } + for q in [ + "What does the runner need?", + "Where are refunds handled?", + "Does the tool need memory?", + "What should I do to fix the login redirect?", + "Do I need to restart the worker after a config change?", + ] { + assert!(!read(q).needs_me, "{q}"); + } + } + #[test] fn a_code_question_is_not_about_work() { for q in [ diff --git a/services/gateway/src/routes/chat_work.rs b/services/gateway/src/routes/chat_work.rs index ac5f6d8dd..5fda5405b 100644 --- a/services/gateway/src/routes/chat_work.rs +++ b/services/gateway/src/routes/chat_work.rs @@ -12,6 +12,8 @@ //! infrastructure findings and quarantined tests. //! - [`RECORDS`]: reviews and their verdicts, alerts, log findings, plans //! and the team's AWS resources (`chat_work_records`). +//! - [`NEEDS_ME`]: everything waiting on the asker, from the runs, Jira and +//! GitHub in one call, grouped by urgency (`chat_work_needs`). //! //! Each tool is offered only when the asker could see what it reads in the //! dashboard: the route that shows it is named ([`Kind::handler`]) and @@ -34,9 +36,10 @@ pub const PULL_REQUESTS: &str = "work_pull_requests"; pub const RUNS: &str = "work_runs"; pub const FINDINGS: &str = "work_findings"; pub const RECORDS: &str = "work_records"; +pub const NEEDS_ME: &str = "work_needs_me"; /// Every tool of this source, in the order they are offered. -pub const TOOLS: [&str; 5] = [TICKETS, PULL_REQUESTS, RUNS, FINDINGS, RECORDS]; +pub const TOOLS: [&str; 6] = [NEEDS_ME, TICKETS, PULL_REQUESTS, RUNS, FINDINGS, RECORDS]; /// The tools a status question's answer lives in. pub const STATUS_TOOLS: [&str; 3] = [TICKETS, PULL_REQUESTS, RUNS]; @@ -213,6 +216,16 @@ pub fn defs(readable: &[&str], repos: &[String], can_github: bool) -> Vec repos.iter().take(40).cloned().collect::>().join(", ")) }); let mut out = Vec::new(); + if ["runs", "tickets", "pull_requests"] + .iter() + .any(|k| may(readable, k)) + { + out.push(json!({ + "name": NEEDS_ME, + "description": "Everything waiting on the person asking, in one call: questions Coderhelm's runs stopped on (with their options), runs waiting on an outside change, tool calls held for their approval, Jira tickets assigned to them or where someone asked them something they haven't answered, pull requests asking for their review, their own pull requests with changes asked for, failing checks or ready to merge, and comments mentioning them. It finds who they are itself (email, GitHub login, Jira account), reads only their team, and returns the items grouped by urgency with links, plus every source it couldn't read. Call it first, once, for any question about what is waiting on them, in any words: \"what needs my answer\", \"what needs me\", \"what's on my plate\", \"what should I work on\", \"anything waiting on me\", \"my reviews\", \"my tickets\", \"am I blocking anyone\". No input.", + "input_schema": {"type": "object", "properties": {}} + })); + } if may(readable, "tickets") { out.push(json!({ "name": TICKETS, @@ -301,6 +314,7 @@ pub fn label(name: &str, input: &Value) -> String { None => format!("Looked up {noun}"), }; match name { + NEEDS_ME => "Checked what's waiting on you".into(), TICKETS => about("tickets"), PULL_REQUESTS => about("pull requests"), RUNS if input["status"] == "active" && what.is_none() => { @@ -322,6 +336,11 @@ pub fn label(name: &str, input: &Value) -> String { /// names (`chat_hints`). Empty when it names nothing of the team's work. pub fn hint_note(h: &super::chat_hints::Hints, offered: &[&str]) -> String { let has = |t: &str| offered.contains(&t); + if h.needs_me && has(NEEDS_ME) { + return format!( + "\nThis question asks what is waiting on the person asking. Call {NEEDS_ME} first, once: it reads Coderhelm's runs, the held approvals, Jira and GitHub for them and says which of those it couldn't read. Answer in the shape its result gives. Look further only to explain one of its items.\n" + ); + } let mut steps: Vec = Vec::new(); if h.running && has(RUNS) { steps.push(format!("{RUNS} with status \"active\"")); @@ -386,6 +405,7 @@ pub fn put_first(tools: &mut [Value], h: &super::chat_hints::Hints) { } let rank = |t: &Value| -> usize { match t["name"].as_str().unwrap_or("") { + NEEDS_ME if h.needs_me => 0, FINDINGS if h.findings => 0, RUNS if h.running => 0, TICKETS => 1, @@ -393,12 +413,40 @@ pub fn put_first(tools: &mut [Value], h: &super::chat_hints::Hints) { RUNS => 3, FINDINGS => 4, RECORDS => 5, + NEEDS_ME => 6, _ => 9, } }; tools.sort_by_key(rank); } +/// Where a question's answer must be looked for before the answer may say +/// nothing was found: "what needs me" must call [`NEEDS_ME`] whatever it +/// says; a status question must look in the tickets, pull requests or runs +/// before it says there's nothing. +pub fn must_look( + h: &super::chat_hints::Hints, + offered: &[&str], +) -> Option { + if h.needs_me && offered.contains(&NEEDS_ME) { + return Some(super::chat_agent::MustLook { + tools: vec![NEEDS_ME.to_string()], + what: "everything waiting on the person: Coderhelm's runs, approvals, Jira and GitHub" + .into(), + always: true, + }); + } + h.about_work().then(|| super::chat_agent::MustLook { + tools: STATUS_TOOLS + .iter() + .filter(|t| offered.contains(t)) + .map(|t| t.to_string()) + .collect(), + what: "the team's tickets, pull requests and Coderhelm's runs".into(), + always: false, + }) +} + // ── Running a call ────────────────────────────────────────────────────────── /// What one question's work tools read with: the asker, what they may read, @@ -507,6 +555,7 @@ pub async fn call( }; let team = ctx.claims.team_id.as_str(); match name { + NEEDS_ME => Box::pin(needs_me(ctx, reg)).await, RUNS => { if !may(&ctx.readable, "runs") { return refused(); @@ -629,6 +678,59 @@ pub async fn call( } } +/// Everything waiting on the asker (`chat_work_needs`), from their team only. +async fn needs_me( + ctx: &Ctx, + reg: &mut common::knowledge::answer::Registry, +) -> (String, String, bool) { + use super::chat_work_needs as needs; + let now = chrono::Utc::now(); + let held = match ctx.installation_id { + Some(id) => crate::lookups::github_hold( + ctx.caller, + limited_until(&ctx.state, id).await, + now.timestamp().max(0) as u64, + ), + None => None, + }; + let http = common::mcp_remote::http::GuardedHttps; + let store = needs::Dynamo { state: &ctx.state }; + let src = needs::Sources { + team: &ctx.claims.team_id, + store: &store, + http: &http, + jira: ctx.jira.as_ref(), + github: ctx.github_token.as_ref().map(|t| needs::GitHub { + auth: format!("Bearer {t}"), + base: "https://api.github.com".into(), + held, + }), + repos: &ctx.repos, + readable: &ctx.readable, + budget: needs::SOURCE_BUDGET, + }; + let me = needs::Me { + email: ctx.claims.email.trim().to_string(), + github: ctx + .claims + .github_login + .as_deref() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(str::to_string), + jira_id: None, + is_admin: matches!(ctx.claims.role.as_str(), "admin" | "owner"), + }; + let report = Box::pin(needs::gather(&src, me, now)).await; + for s in &report.sources { + if let needs::Read::Failed(e) = &s.read { + tracing::warn!(tool = NEEDS_ME, source = s.name, error = %e, "Chat: a source of what needs the asker couldn't be read"); + } + } + let (text, summary) = needs::render(&report, reg, &live_stamp()); + (text, summary, false) +} + /// Tickets: from Jira by key or text, and from the runs that worked on them. async fn tickets( ctx: &Ctx, @@ -753,6 +855,18 @@ mod tests { } } + /// The permission gate asks every call; a tool it doesn't know is denied. + #[test] + fn every_work_tool_is_known_to_the_permission_gate() { + for t in TOOLS { + assert_eq!( + common::agent_policy::registry::builtin(t), + Some(common::agent_policy::Risk::Read), + "{t}" + ); + } + } + #[test] fn a_viewer_reads_only_what_the_dashboard_shows_a_viewer() { let viewer = readable(&Holder::builtin("viewer")); @@ -786,7 +900,11 @@ mod tests { .iter() .filter_map(|t| t["name"].as_str()) .collect(); - assert_eq!(names, [RUNS]); + assert_eq!(names, [NEEDS_ME, RUNS]); + // A role that reads none of runs, tickets or pull requests isn't + // offered what needs them. + let only_infra = defs(&["infra"], &repos, true); + assert!(!only_infra.iter().any(|t| t["name"] == NEEDS_ME)); let every = defs(&all(), &repos, true); assert_eq!(every.len(), TOOLS.len()); // No GitHub token: no pull request tool. @@ -829,6 +947,40 @@ mod tests { assert!(hint_note(&h, &TOOLS).contains("status \"active\"")); let h = super::super::chat_hints::read("How is harbor-api put together?"); assert!(hint_note(&h, &TOOLS).is_empty()); + assert!(must_look(&h, &TOOLS).is_none()); + } + + #[test] + fn what_needs_me_goes_to_its_tool_first_in_any_words() { + for q in [ + "What needs my answer?", + "what needs me today", + "Anything waiting on me?", + "what's on my plate", + "What should I work on next?", + "Do I have any reviews pending?", + "am I blocking anyone?", + "show me my tickets", + ] { + let h = super::super::chat_hints::read(q); + assert!(h.needs_me, "{q}"); + let mut tools = vec![ + json!({"name": RUNS}), + json!({"name": TICKETS}), + json!({"name": NEEDS_ME}), + ]; + put_first(&mut tools, &h); + assert_eq!(tools[0]["name"], NEEDS_ME, "{q}"); + assert!( + hint_note(&h, &TOOLS).contains("Call work_needs_me first"), + "{q}" + ); + let m = must_look(&h, &TOOLS).unwrap(); + assert!(m.always && m.tools == [NEEDS_ME], "{q}"); + } + // Without the tool on offer, the status rule stands. + let h = super::super::chat_hints::read("What needs my answer?"); + assert!(!hint_note(&h, &[RUNS]).contains(NEEDS_ME)); } #[test] @@ -845,6 +997,7 @@ mod tests { label(FINDINGS, &json!({"kind": "infra"})), "Looked up infrastructure findings" ); + assert_eq!(label(NEEDS_ME, &json!({})), "Checked what's waiting on you"); assert_eq!( words_of("Embed the Portal, on sign-up pages!"), ["embed", "portal", "sign-up", "pages"] diff --git a/services/gateway/src/routes/chat_work_needs.rs b/services/gateway/src/routes/chat_work_needs.rs new file mode 100644 index 000000000..5f2389697 --- /dev/null +++ b/services/gateway/src/routes/chat_work_needs.rs @@ -0,0 +1,1996 @@ +//! Chat's "what needs me": everything waiting on the person asking, from +//! every place Coderhelm reads, in one call ([`super::chat_work::NEEDS_ME`]). +//! +//! - Coderhelm's runs: questions a run stopped on (with the options it +//! found), runs waiting on a change outside their repository, and +//! Coderhelm's open pull requests on the person's tickets or runs. +//! - Approvals: tool calls held for an admin's yes (admins only, as the +//! page that decides them). +//! - Jira, through the team's Jira app: open tickets assigned to them, and +//! tickets where someone mentioned them after their last comment. +//! - GitHub, through the installation, in the team's repositories only: +//! pull requests asking for their review, their own pull requests with +//! changes asked for, failing checks or ready to merge, and comments that +//! mention them they haven't answered. +//! +//! The person is who signed in: their email, their GitHub login, and the +//! Jira account Coderhelm has seen with their email. Every read is of the +//! asker's team only. The sources are read side by side, each within +//! [`SOURCE_BUDGET`]; one that fails, times out or isn't connected is named +//! in the result, never skipped quietly. Items are grouped by urgency and +//! ranked by priority and age; stale tickets are left out and counted. + +use std::time::Duration; + +use common::mcp_remote::http::{Http, HttpRequest, Limit}; +use serde_json::{json, Value}; + +use super::chat_work::clip; +use super::chat_work_prs::{scoped_queries, Client}; +use super::chat_work_runs::Item; +use super::chat_work_tickets::JiraApp; + +/// How long one source may take before it's reported as not answering. +pub const SOURCE_BUDGET: Duration = Duration::from_secs(12); +/// Most items one answer lists. +pub const MAX_ITEMS: usize = 25; +/// An assigned ticket nobody touched for this long is noise, unless it's +/// urgent or someone asked the person something on it. +pub const STALE_DAYS: i64 = 60; +/// A run waiting this long is left out as noise (it's counted). +pub const OLD_RUN_DAYS: i64 = 30; +/// Own pull requests read in full (reviews, checks). +const MAX_OWN_PRS: usize = 4; +/// Pull requests whose comments are read for unanswered mentions. +const MAX_MENTION_PRS: usize = 3; + +/// How soon something needs the person. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Urgency { + /// Something is stopped on them. + Now, + Today, + Later, +} + +impl Urgency { + pub fn heading(self) -> &'static str { + match self { + Urgency::Now => "Needs you now", + Urgency::Today => "Today", + Urgency::Later => "When you can", + } + } + + fn word(self) -> &'static str { + match self { + Urgency::Now => "now", + Urgency::Today => "today", + Urgency::Later => "when you can", + } + } +} + +/// One thing waiting on the person. +#[derive(Debug, Clone, PartialEq)] +pub struct Need { + pub urgency: Urgency, + /// Higher first within its group (priority, then how long it waited). + pub rank: i64, + /// `run`, `ticket`, `pull_request` or `record` (an approval). + pub kind: &'static str, + /// What it is: "ABC-12 Fix the login redirect", "acme/web#41 Add slips". + pub what: String, + /// Exactly what the person does. + pub action: String, + /// Where they do it: the page outside Coderhelm, or the dashboard page. + pub link: String, + /// Since when it waits. + pub since: String, + /// More for the answer: a run's questions with their options. + pub detail: String, + /// The repository or place, for the citation. + pub loc: String, +} + +/// How a source was read. +#[derive(Debug, Clone, PartialEq)] +pub enum Read { + /// Read; this many items came from it. + Ok(usize), + /// Tried and failed, or didn't answer in time: why. + Failed(String), + /// Not read: not connected, not linked or not allowed. Why, plainly. + Off(String), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct SourceNote { + pub name: &'static str, + pub read: Read, +} + +/// Who is asking. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Me { + pub email: String, + pub github: Option, + /// Their Jira account, once known ([`Store::jira_accounts`]). + pub jira_id: Option, + /// An admin or owner: decides held tool calls. + pub is_admin: bool, +} + +/// What Coderhelm keeps itself, read for one team only. +#[async_trait::async_trait] +pub trait Store: Send + Sync { + /// The team's latest runs (newest first, bounded). + async fn runs(&self, team: &str) -> Result, String>; + /// The team's tool calls held for a person's yes, pending only. + async fn approvals(&self, team: &str) -> Result, String>; + /// The Jira account ids Coderhelm has seen with this email. + async fn jira_accounts(&self, team: &str, email: &str) -> Vec; +} + +/// GitHub through the team's installation. +#[derive(Debug, Clone)] +pub struct GitHub { + pub auth: String, + pub base: String, + /// GitHub said the hour's limit is spent: why. + pub held: Option, +} + +/// Where one "what needs me" reads, all of it the asker's team's. +pub struct Sources<'a> { + pub team: &'a str, + pub store: &'a dyn Store, + pub http: &'a dyn Http, + pub jira: Option<&'a JiraApp>, + pub github: Option, + /// The team's repositories the person may read. + pub repos: &'a [String], + /// The record kinds the person may read (`chat_work::readable`). + pub readable: &'a [&'static str], + /// How long each source may take ([`SOURCE_BUDGET`]). + pub budget: Duration, +} + +/// Everything found, grouped and ranked. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Report { + pub needs: Vec, + pub sources: Vec, + /// What was left out as noise, in words ("3 tickets untouched for 60+ days"). + pub skipped: Vec, + /// Who the items are for, in words. + pub who: String, +} + +// ── Time ──────────────────────────────────────────────────────────────────── + +type Time = chrono::DateTime; + +/// RFC 3339, or Jira's `2026-11-12T10:00:00.000+0000`, or a bare date. +pub fn parse_time(s: &str) -> Option