diff --git a/docs/incidents/cu_chat_answers_the_question.md b/docs/incidents/cu_chat_answers_the_question.md new file mode 100644 index 000000000..0ff342f4d --- /dev/null +++ b/docs/incidents/cu_chat_answers_the_question.md @@ -0,0 +1,7 @@ +# cu. `cu_chat_answers_the_question` + +**What happened:** A team's CTO opened chat for the first time and asked what could be useful to someone in his role. Chat answered a different question. It led with "what's waiting on you" (24 items, one ticket's details first), because the prompt sent any "what should I work on" style question to that list and the list's lookup told the model to write every answer in its fixed shape. It also said Jira wasn't connected, a claim no check in that answer supported. His next message had to correct it, and chat walked the claim back only in part. Earlier, a question that linked a pull request comment got the canned "found nothing" line, because any answer that cited nothing was replaced by it, whatever the question. + +**The guarantee:** Chat reads a question before it answers: what the person wants (an orientation, what Chat can do, what needs me, a status, a how-to, a lookup, a judgement, a correction of Chat itself, or small talk), the role they say they hold, and, for a correction, the sentences of the last answer they question. It answers that question first and sizes the answer to it. The "what needs me" list keeps its fixed shape only for that question; for any other, the lookup says to use only what answers it. An orientation looks the team's setup up (`coderhelm_setup`: each connection checked with the integrations page's own test, the runs and records counted) before it may answer. A correction must check the disputed point again in that answer, and a check that failed is named as that check, never as "not connected". An uncited reply is kept only for small talk; any other answer that cites nothing looks once with its tools before the plain no-source line replaces it. + +**Where it's enforced:** `common::chat_intent::{read, Intent::fixed_shape, Intent::uncited_ok, Reading::note}`, `common::knowledge::answer::finalize_reply`; in the gateway, `chat_understand::{read, Understood::must_look, Understood::order}`, `chat_setup::{render, github_check, jira_check}`, `chat_work_needs::{render_for, NOT_THE_LIST}`, `chat_agent::cite_something`, `chat_hints` (pull request links), and the "Understand the question first" and "Check before you claim" parts of `brain::CHAT_SYSTEM`. The replay evals are `chat_eval_replay`. diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 556b74294..d8dbccd29 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -248,6 +248,8 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("work_findings", Risk::Read), ("work_records", Risk::Read), ("work_needs_me", Risk::Read), + // What Coderhelm is set up to do for the team, checked now (chat_setup.rs). + ("coderhelm_setup", 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/common/src/chat_intent.rs b/services/common/src/chat_intent.rs new file mode 100644 index 000000000..af90e808f --- /dev/null +++ b/services/common/src/chat_intent.rs @@ -0,0 +1,718 @@ +//! What a Chat question asks for, read before the model answers: an +//! orientation ("I'm new, what can you do for me"), whether Chat can do +//! something, what is waiting on the person, where something stands, how to +//! do something, a lookup, a judgement call, small talk, or a correction of +//! something Chat said. Also the role the person says they hold. +//! +//! The reading decides only what code would otherwise force on every +//! answer: a fixed answer shape is used only for the question it was made +//! for ([`Intent::fixed_shape`]), an uncited reply is kept only for small +//! talk ([`Intent::uncited_ok`]), and a correction or an orientation must +//! look something up this turn before it answers. The model is told the +//! reading as a note it checks against the question itself +//! ([`Reading::note`]): when the question asks something else, it answers +//! what the question asks. + +use std::sync::LazyLock; + +use regex::Regex; + +/// What the person wants from the answer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Intent { + /// New to Coderhelm, or asking what it can do for them. + Orientation, + /// Whether Chat or Coderhelm can do something. + Capability, + /// What is waiting on the person asking. + NeedsMe, + /// Where a piece of work stands. + Status, + /// How to do something. + HowTo, + /// A fact: what, where, why, who. + Lookup, + /// A verdict: is it right, should we, is it safe. + Judgement, + /// The person says something Chat said was wrong, or asks what it meant. + Correction, + /// A greeting, thanks or acknowledgement. + SmallTalk, +} + +impl Intent { + /// In a few words, for the note and the logs. + pub fn words(self) -> &'static str { + match self { + Intent::Orientation => "an orientation: what Coderhelm already does for their team and what it can do for them", + Intent::Capability => "whether Chat or Coderhelm can do something", + Intent::NeedsMe => "what is waiting on them", + Intent::Status => "where a piece of work stands", + Intent::HowTo => "how to do something", + Intent::Lookup => "a specific fact", + Intent::Judgement => "your judgement on something", + Intent::Correction => "a correction: they question something you said", + Intent::SmallTalk => "small talk", + } + } + + /// A short key, for logs and evals. + pub fn key(self) -> &'static str { + match self { + Intent::Orientation => "orientation", + Intent::Capability => "capability", + Intent::NeedsMe => "needs_me", + Intent::Status => "status", + Intent::HowTo => "how_to", + Intent::Lookup => "lookup", + Intent::Judgement => "judgement", + Intent::Correction => "correction", + Intent::SmallTalk => "small_talk", + } + } + + /// A fixed answer shape (the "what's waiting on you" list) fits only + /// the question it was made for. + pub fn fixed_shape(self) -> bool { + self == Intent::NeedsMe + } + + /// An answer with no citation is kept as written only for small talk; + /// every other answer rests on something read this turn. + pub fn uncited_ok(self) -> bool { + self == Intent::SmallTalk + } + + /// How the answer is sized and laid out. + pub fn shape(self) -> &'static str { + match self { + Intent::Orientation => "Call coderhelm_setup first. Open with one or two sentences on what Coderhelm already does for this team, from what it found (cited). Then three to five things Coderhelm can do for someone in their role, each in a line with one example question they could ask. Don't list their to-do items or one ticket's details unless they asked; if things are waiting on them, say so in one line and that \"What needs my answer?\" lists them. Keep it under about 250 words.", + Intent::Capability => "Say yes or no first: whether Chat or Coderhelm can do it, from coderhelm_setup or the tools you have this turn, cited. Then, in a few lines, what you can do instead or how to get it done. If it's something you can do right now with your tools, do it.", + Intent::NeedsMe => "Answer in the shape work_needs_me's result gives.", + Intent::Status => "Lead with where it stands and when that last changed, then only the detail that explains it.", + Intent::HowTo => "Give the shortest way to do it first, as numbered steps, from the team's own docs or code (cited), then any exceptions.", + Intent::Lookup => "Lead with the answer in a sentence or two, then only the detail that supports it.", + Intent::Judgement => "Give your verdict first (yes, no, or what it depends on), then the evidence you checked this turn, then what would settle what you couldn't check.", + Intent::Correction => "Check the disputed point again now with a tool, never from the earlier answer's words. Say in the first sentence whether you were wrong and what is right, plainly, then answer what they asked. Don't guess at causes you can't see.", + Intent::SmallTalk => "Reply in a sentence or two, with no lookups. If it fits, offer one thing you can do.", + } + } +} + +/// What the question names, from the gateway's reading of it +/// (`chat_hints`): it asks what is waiting on the person, where something +/// stands, or names a piece of work (a ticket, a pull request, a title). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Signals { + pub needs_me: bool, + pub status: bool, + pub names_work: bool, +} + +/// How a question was read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reading { + pub intent: Intent, + /// The role the person says they hold ("cto", "product manager"). + pub role: Option, + /// They say they are new to Coderhelm. + pub newcomer: bool, + /// The sentences of Chat's last answer the person questions. + pub disputed: Vec, +} + +fn has(text: &str, words: &[&str]) -> bool { + words.iter().any(|w| has_phrase(text, w)) +} + +/// `w` in `text` at word boundaries. +fn has_phrase(text: &str, w: &str) -> bool { + text.match_indices(w).any(|(i, _)| { + let before = text[..i].chars().next_back(); + let after = text[i + w.len()..].chars().next(); + !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric) + }) +} + +/// Lower case, curly quotes made straight. +fn plain(text: &str) -> String { + text.trim() + .to_lowercase() + .replace(['\u{2019}', '\u{2018}'], "'") + .replace(['\u{201c}', '\u{201d}'], "\"") +} + +const NEWCOMER: &[&str] = &[ + "first time", + "i'm new", + "im new", + "i am new", + "new here", + "new to coderhelm", + "new to this", + "just joined", + "just started using", + "getting started", + "get started", + "where do i start", + "where should i start", + "onboard me", + "show me around", +]; + +/// Asks what Coderhelm or Chat offers them, in general. +const OFFER: &[&str] = &[ + "what can you do", + "what can coderhelm do", + "what does coderhelm do", + "what do you do", + "how can you help", + "how could you help", + "how can coderhelm help", + "how does coderhelm help", + "what can you help", + "what can i use you for", + "what can i use coderhelm for", + "what should i use you for", + "what should i use coderhelm for", + "how should i use you", + "how should i use coderhelm", + "how do i use coderhelm", + "useful to me", + "useful for me", + "could be useful", + "would be useful", + "be helpful to me", + "what is coderhelm", + "what's coderhelm", + "who are you", + "what are you", + "what should i know", + "what are you good at", + "what can you tell me", +]; + +const CAPABILITY: &[&str] = &[ + "are you able", + "is coderhelm able", + "are you allowed", + "is it possible for you", + "can you run", + "can you see", + "can you read", + "can you access", + "can you open", + "can you connect", + "can you use", + "can you change", + "can you edit", + "can you write", + "can you deploy", + "can you merge", + "can coderhelm", + "could coderhelm", + "does coderhelm", + "do you support", + "does it support", + "do you have access", + "have access to", + "do you know about", +]; + +const JUDGEMENT: &[&str] = &[ + "accurate", + "is this right", + "is that right", + "is it right", + "is this correct", + "is that correct", + "is it correct", + "is this true", + "is that true", + "should we", + "should i", + "do you think", + "would you", + "is it safe", + "is this safe", + "safe to", + "worth", + "is it ok", + "is it okay", + "recommend", + "better to", + "which is better", + "pros and cons", + "tradeoff", + "trade-off", + "risky", + "make sense", + "makes sense", + "good idea", + "bad idea", +]; + +const HOW_TO: &[&str] = &[ + "how do i", + "how can i", + "how do we", + "how can we", + "how would i", + "how should i", + "how should we", + "how to", + "steps to", + "what's the process", + "what is the process", + "walk me through", + "how does one", + "how can a", + "how can an", + "how can someone", + "how can they", + "how can people", + "how do they", + "how do people", + "how does someone", +]; + +/// The person says Chat got something wrong, or asks what it meant. +const CORRECTION: &[&str] = &[ + "what do you mean", + "what did you mean", + "what does that mean", + "that's wrong", + "thats wrong", + "that is wrong", + "you're wrong", + "you are wrong", + "that's not right", + "that is not right", + "that isn't right", + "that's not true", + "that isn't true", + "not true", + "that's incorrect", + "incorrect", + "that's false", + "you said", + "you told me", + "i see", + "i can see", + "but it is", + "but it's", + "it is connected", + "it's connected", + "is connected", + "are you sure", + "not what i asked", + "i didn't ask", + "i did not ask", + "i asked", + "that's not what", + "is wrong", + "was wrong", + "got it wrong", + "got that wrong", + "why did you say", + "why do you say", +]; + +/// Words of a greeting, a thanks or an acknowledgement. +const SMALL: &[&str] = &[ + "hi", + "hello", + "hey", + "there", + "yo", + "thanks", + "thank", + "you", + "so", + "much", + "thx", + "ty", + "ok", + "okay", + "k", + "cool", + "great", + "got", + "it", + "nice", + "perfect", + "good", + "morning", + "afternoon", + "evening", + "bye", + "awesome", + "sounds", + "appreciate", + "appreciated", + "cheers", + "how", + "are", + "doing", + "chat", + "coderhelm", + "lol", + "sure", + "yes", + "no", + "yep", + "nope", + "that", + "helps", + "helped", + "makes", + "sense", + "understood", + "love", + "this", + "a", + "lot", + "all", + "again", + "will", + "do", +]; + +static ROLE: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?:^|[\s,.;(])(?:i'?m|i am|as)\s+(?:the|a|an|our)\s+([a-z][a-z/&-]*(?:\s+[a-z][a-z/&-]*){0,3}?)(?:\s+(?:of|at|for|on|in|here|and|who|that)\b|\s*[,.!?;:)]|\s*$)", + ) + .unwrap() +}); + +/// Words that never name a role ("I'm the one who", "as a result"). +const NOT_ROLES: &[&str] = &[ + "one", "result", "reminder", "test", "matter", "way", "first", "only", "same", "person", + "user", "new", "little", "bit", +]; + +/// The role the person says they hold, as they wrote it. +pub fn role_of(question: &str) -> Option { + let q = plain(question); + for c in ROLE.captures_iter(&q) { + let r = c[1].trim().to_string(); + let head = r.split_whitespace().next().unwrap_or(""); + if r.is_empty() || NOT_ROLES.contains(&head) || r.split_whitespace().count() > 4 { + continue; + } + return Some(r); + } + None +} + +/// A greeting, a thanks or an acknowledgement, and nothing else. +pub fn is_small_talk(question: &str) -> bool { + let q = plain(question); + let words: Vec<&str> = q + .split(|c: char| !c.is_alphanumeric() && c != '\'') + .map(|w| w.trim_matches('\'')) + .filter(|w| !w.is_empty()) + .collect(); + if words.is_empty() { + // Only emoji or punctuation ("πŸ‘", "?"). + return !q.contains('?') || q.chars().count() <= 3; + } + words.len() <= 8 + && words + .iter() + .all(|w| SMALL.contains(w) || SMALL.contains(&w.trim_end_matches("'s"))) +} + +/// Content words of a sentence: lower case, four letters or more. +fn content_words(text: &str) -> Vec { + const COMMON: &[&str] = &[ + "that", "this", "what", "your", "with", "from", "have", "there", "their", "about", "would", + "could", "should", "which", "when", "where", "into", "they", "them", "were", "been", + "does", "mean", "said", "isn't", "aren't", "don't", "just", "like", "some", + ]; + plain(text) + .split(|c: char| !c.is_alphanumeric() && c != '\'') + .filter(|w| w.chars().count() >= 4 && !COMMON.contains(w)) + .map(str::to_string) + .collect() +} + +/// The sentences of `answer` that `question` questions: those sharing the +/// most content words with it (two at least), at most three. +pub fn disputed(question: &str, answer: &str) -> Vec { + let q = content_words(question); + if q.is_empty() { + return Vec::new(); + } + let mut scored: Vec<(usize, usize, String)> = answer + .split(['.', '\n', '!', '?']) + .map(str::trim) + .filter(|s| s.chars().count() >= 12) + .enumerate() + .filter_map(|(i, s)| { + let words = content_words(s); + let shared = q.iter().filter(|w| words.contains(w)).count(); + (shared >= 2).then(|| { + ( + shared, + i, + s.trim_start_matches(['-', '*', '#', ' ']).to_string(), + ) + }) + }) + .collect(); + scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + scored.truncate(3); + scored.sort_by_key(|s| s.1); + scored.into_iter().map(|(_, _, s)| s).collect() +} + +/// Reads a question. `last_answer` is Chat's previous answer in the thread. +pub fn read(question: &str, last_answer: Option<&str>, s: Signals) -> Reading { + let q = plain(question); + let role = role_of(question); + let newcomer = has(&q, NEWCOMER); + let last = last_answer.map(str::trim).filter(|a| !a.is_empty()); + let mut disputes: Vec = Vec::new(); + let corrects = match last { + Some(a) if has(&q, CORRECTION) || q.starts_with("no,") || q.starts_with("actually") => { + disputes = disputed(question, a); + // "What do you mean" and plain contradictions question the last + // answer even when no sentence of it is named again. + !disputes.is_empty() + || has( + &q, + &[ + "what do you mean", + "what did you mean", + "you said", + "that's wrong", + "you're wrong", + "that's not right", + "that isn't right", + "not true", + "incorrect", + "not what i asked", + "i didn't ask", + "are you sure", + ], + ) + } + _ => false, + }; + let intent = if corrects { + Intent::Correction + } else if s.needs_me { + Intent::NeedsMe + } else if (newcomer || has(&q, OFFER)) && !s.names_work { + Intent::Orientation + } else if is_small_talk(question) { + Intent::SmallTalk + } else if has(&q, CAPABILITY) { + Intent::Capability + } else if has(&q, JUDGEMENT) { + Intent::Judgement + } else if s.status { + Intent::Status + } else if has(&q, HOW_TO) { + Intent::HowTo + } else { + Intent::Lookup + }; + Reading { + intent, + role, + newcomer, + disputed: if intent == Intent::Correction { + disputes + } else { + Vec::new() + }, + } +} + +impl Reading { + /// The note the model reads before the question. + pub fn note(&self) -> String { + let mut out = format!( + "\nHow this question reads (check it against the question itself; if it asks something else, answer what it actually asks):\n- They want {}.\n", + self.intent.words() + ); + if let Some(r) = &self.role { + out.push_str(&format!( + "- They say they are the {r}: answer for what someone in that role needs.\n" + )); + } + if self.newcomer { + out.push_str("- They are new to Coderhelm.\n"); + } + if !self.disputed.is_empty() { + out.push_str("- What they question in your last answer:\n"); + for d in &self.disputed { + out.push_str(&format!( + " \u{201c}{}\u{201d}\n", + crate::truncate_str(d, 300) + )); + } + } + out.push_str(&format!("- How to answer: {}\n", self.intent.shape())); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn r(q: &str) -> Intent { + read(q, None, Signals::default()).intent + } + + #[test] + fn a_newcomer_asking_what_helps_them_wants_an_orientation() { + let q = "this is my first time using coderhelm. i'm the cto of the company. are are a few things that you think could be useful to me"; + let reading = read(q, None, Signals::default()); + assert_eq!(reading.intent, Intent::Orientation); + assert_eq!(reading.role.as_deref(), Some("cto")); + assert!(reading.newcomer); + for q in [ + "What can you do?", + "how can coderhelm help me as an engineering manager?", + "I'm new here, where do I start?", + "what is coderhelm", + "What should I use you for?", + ] { + assert_eq!(r(q), Intent::Orientation, "{q}"); + } + } + + #[test] + fn a_question_naming_work_or_asking_what_waits_is_not_an_orientation() { + let s = Signals { + needs_me: true, + ..Default::default() + }; + assert_eq!( + read("I'm new, what needs my answer?", None, s).intent, + Intent::NeedsMe + ); + let s = Signals { + names_work: true, + status: true, + ..Default::default() + }; + assert_eq!( + read("what can you tell me about ABC-12?", None, s).intent, + Intent::Status + ); + } + + #[test] + fn every_intent_reads_from_its_own_words() { + assert_eq!( + r("are you able to run skills in the web repo"), + Intent::Capability + ); + assert_eq!(r("Can you see our production logs?"), Intent::Capability); + assert_eq!(r("How can I cancel a reservation?"), Intent::HowTo); + assert_eq!(r("how do I add a knowledge base"), Intent::HowTo); + assert_eq!( + r("is this comment accurate https://github.com/acme/web/pull/14#issuecomment-1"), + Intent::Judgement + ); + assert_eq!(r("should we roll back the last deploy?"), Intent::Judgement); + assert_eq!(r("what caused the enospc error?"), Intent::Lookup); + assert_eq!( + r("what does B7 mean in reference to crawlers"), + Intent::Lookup + ); + let st = Signals { + status: true, + ..Default::default() + }; + assert_eq!( + read("where are we on the portal?", None, st).intent, + Intent::Status + ); + for q in [ + "thanks!", + "hi", + "ok cool", + "thank you so much", + "πŸ‘", + "Good morning", + ] { + assert_eq!(r(q), Intent::SmallTalk, "{q}"); + } + assert_ne!(r("hi, why is the build red?"), Intent::SmallTalk); + } + + #[test] + fn a_correction_names_what_it_questions_in_the_last_answer() { + let last = "Welcome. Three runs are waiting on you. Jira isn't connected to Coderhelm, so your Jira tickets aren't in this list. Ask me for a DORA report."; + let q = "what do you mean that jira isn't connected? i see atlassian in the integrations"; + let reading = read(q, Some(last), Signals::default()); + assert_eq!(reading.intent, Intent::Correction); + assert_eq!( + reading.disputed, + ["Jira isn't connected to Coderhelm, so your Jira tickets aren't in this list"] + ); + let note = reading.note(); + assert!(note.contains("Jira isn't connected to Coderhelm"), "{note}"); + assert!( + note.contains("Check the disputed point again now"), + "{note}" + ); + // The same words with no earlier answer are not a correction. + assert_ne!(r(q), Intent::Correction); + // A plain contradiction with no shared words still is. + assert_eq!( + read("that's wrong", Some(last), Signals::default()).intent, + Intent::Correction + ); + // A follow-up that questions nothing is read as itself. + assert_eq!( + read("and who owns the web repo?", Some(last), Signals::default()).intent, + Intent::Lookup + ); + } + + #[test] + fn only_the_list_question_gets_the_fixed_shape_and_only_small_talk_goes_uncited() { + for i in [ + Intent::Orientation, + Intent::Capability, + Intent::Status, + Intent::HowTo, + Intent::Lookup, + Intent::Judgement, + Intent::Correction, + Intent::SmallTalk, + ] { + assert!(!i.fixed_shape(), "{i:?}"); + assert!(!i.shape().is_empty()); + } + assert!(Intent::NeedsMe.fixed_shape()); + assert!(Intent::SmallTalk.uncited_ok()); + assert!(!Intent::Orientation.uncited_ok() && !Intent::Correction.uncited_ok()); + } + + #[test] + fn roles_are_read_as_written_and_non_roles_are_not() { + assert_eq!( + role_of("As a product manager, what can you do?").as_deref(), + Some("product manager") + ); + assert_eq!( + role_of("I am the head of platform here").as_deref(), + Some("head") + ); + assert_eq!( + role_of("I'm a backend engineer.").as_deref(), + Some("backend engineer") + ); + assert_eq!(role_of("I'm the one who merged it"), None); + assert_eq!(role_of("as a result the build broke"), None); + assert_eq!(role_of("what is the cto dashboard"), None); + } +} diff --git a/services/common/src/knowledge/answer.rs b/services/common/src/knowledge/answer.rs index 759d63e20..e952b5ed6 100644 --- a/services/common/src/knowledge/answer.rs +++ b/services/common/src/knowledge/answer.rs @@ -207,6 +207,12 @@ fn bracket_ids(inner: &str) -> Option> { /// The answer as shown: brackets naming no registered source removed, the /// sources it cites listed, and the no-source answer when it cites nothing. pub fn finalize(text: &str, reg: &Registry) -> Final { + finalize_reply(text, reg, false) +} + +/// [`finalize`], keeping an uncited reply as written when `uncited_ok` (a +/// greeting or a thanks, which rests on no source). +pub fn finalize_reply(text: &str, reg: &Registry, uncited_ok: bool) -> Final { let mut out = String::with_capacity(text.len()); let mut cited: Vec = Vec::new(); let mut rest = text; @@ -239,6 +245,13 @@ pub fn finalize(text: &str, reg: &Registry) -> Final { } } out.push_str(rest); + if cited.is_empty() && uncited_ok && !out.trim().is_empty() { + return Final { + text: out.replace(" .", ".").replace(" ,", ",").trim().to_string(), + citations: Vec::new(), + grounded: true, + }; + } if cited.is_empty() { return Final { text: NO_SOURCE_ANSWER.to_string(), @@ -335,6 +348,19 @@ mod tests { assert_eq!(f.text, NO_SOURCE_ANSWER); } + #[test] + fn only_a_reply_that_may_go_uncited_is_kept_uncited() { + let f = finalize_reply("You're welcome!", &Registry::default(), true); + assert!(f.grounded && f.citations.is_empty()); + assert_eq!(f.text, "You're welcome!"); + assert_eq!( + finalize_reply("You're welcome!", &Registry::default(), false).text, + NO_SOURCE_ANSWER + ); + // An empty reply is never kept. + assert!(!finalize_reply(" ", &Registry::default(), true).grounded); + } + #[test] fn hits_become_knowledge_sources() { let mut r = Registry::default(); diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 46be5e245..43b83aabe 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -9,6 +9,9 @@ pub mod agent_log; /// The app map: CoderHelm's adapter around the vendored Floorplan map /// (`vendor/floorplan`): storage, CoderHelm's overlays and lookups. pub mod app_map; +/// What a Chat question asks for (an orientation, a status, a how-to, a +/// correction of Chat itself, ...), read before the model answers. +pub mod chat_intent; /// A repository's code map: sections stamped with the commit they describe, /// rebuilt only where a change touched them, given to the planner and coder. pub mod code_map; diff --git a/services/gateway/src/mcp_lookups.rs b/services/gateway/src/mcp_lookups.rs index c2369c46f..fce5d7665 100644 --- a/services/gateway/src/mcp_lookups.rs +++ b/services/gateway/src/mcp_lookups.rs @@ -996,6 +996,7 @@ async fn connect( installation_id, jira, caller: common::github_budget::caller::MCP, + needs_shape: true, }, repos, repos_withheld, diff --git a/services/gateway/src/routes/app_map.rs b/services/gateway/src/routes/app_map.rs index b03535067..098a94f1f 100644 --- a/services/gateway/src/routes/app_map.rs +++ b/services/gateway/src/routes/app_map.rs @@ -713,6 +713,8 @@ pub async fn ask( retries: 0, }, must_look: None, + // A map answer always cites the map; it is never small talk. + uncited_ok: false, }; let out = chat_agent::run(&model, &mut tools, &Quiet, &mut reg, ask) .await diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index 11421ce07..39b2f7189 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -258,6 +258,7 @@ pub fn kind_of_tool(name: &str) -> &'static str { "read_skill" | "read_skill_file" | "ask_team_agent" => "skills", common::plugins::brain::ASK_TOOL => common::plugins::brain::SOURCE_KEY, n if super::chat_work::is_work_tool(n) => super::chat_work::SOURCE_KEY, + super::chat_setup::SETUP => super::chat_work::SOURCE_KEY, n if n.starts_with("github__") || n.starts_with("graph_") => "code", n if n.contains("__") => "connections", _ => "data_sources", @@ -1314,18 +1315,30 @@ fn user_folder(user_id: &str) -> String { // ── Asking ────────────────────────────────────────────────────────────────── -const CHAT_SYSTEM: &str = r#"You are Chat, the assistant for a software team that uses Coderhelm. You answer questions about the team's work from the team's own sources: their code (which you read with your tools), passages from their knowledge bases, files attached to the question, and the results of tools for connected apps, past work, data sources and team skills. +const CHAT_SYSTEM: &str = r#"You are Chat, the assistant for a software team that uses Coderhelm. You answer questions about the team's work from the team's own sources: their code (which you read with your tools), passages from their knowledge bases, files attached to the question, Coderhelm's own records of the team, and the results of tools for connected apps, past work, data sources and team skills. + +Understand the question first: +- Before any lookup, work out what the person is asking for: an orientation (they are new, or ask what Coderhelm can do for them), whether you or Coderhelm can do something, what is waiting on them, where some work stands, how to do something, a specific fact, your judgement on something, small talk, or a correction of something you said. Work out who is asking (the role they say they hold, or that the question implies) and what they need from the answer. A note before the question says how it reads; check it against the question, and when the question asks something else, answer what it asks. +- Answer the question that was asked, first, and size the answer to it: a yes-or-no question gets yes or no in the first sentence, a greeting gets a sentence, a fact gets the fact and then the detail that supports it. Related things come after, briefly, and only when they help. Never lead with something they didn't ask for. +- A fixed answer shape (such as the "what's waiting on you" list) is only for the question it was made for. When a lookup returns more than the question needs, use only what answers it. +- An orientation is a real answer about them: call coderhelm_setup, say what Coderhelm already does for their team from what it found, then a few things it can do for someone in their role, each with a question they could ask. Not their to-do list, and not one ticket's details, unless they asked. + +Check before you claim: +- Every claim about what is connected, set up or allowed, about counts, or about where something stands rests on a lookup made in this answer, cited. Don't repeat such a claim from an earlier answer in the thread without checking it again now. +- When a check fails, say exactly which check failed and what it said ("the ticket lookup returned an error"), never a broader claim it doesn't support ("Jira isn't connected"). A check that couldn't run says nothing about whether the thing is set up. +- When the person says something you said is wrong, or asks what you meant, check that point again now with the tool that can, say plainly in your first sentence whether you were wrong and what is right, and then answer what they asked. Don't defend the earlier answer, and don't guess at causes you can't see. How to work: -- Research before you answer. You can take many steps: look a repository over, list folders, read files, search the code, follow imports, read more. Keep going until you can answer from what you read. Most code questions need several reads. +- Research before you answer a question about the team's code, docs or work. You can take many steps: look a repository over, list folders, read files, search the code, follow imports, read more. Keep going until you can answer from what you read. Most code questions need several reads. Small talk needs no lookups. - The team's repositories are listed below. When the question names one, by its full or short name however it is written, it means that repository. Open it with github__repo_overview; don't search the code or the code graph for the repository's own name. - "How is X put together?" (built, structured, organized): look it over, then read the entry points and the files that tie it together (app or server setup, routing, main modules, configuration). Explain the main parts, what each does, and how a request or a job moves through them. - "Where is X handled?": search the code for the words and the likely names, read the matching files to confirm, and name the file and the function. - "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_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. +- 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 or link, 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. +- Only when the question asks 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, and 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. +- What Coderhelm is set up to do for the team (connections, repositories, knowledge bases, how much it did lately, what you can read and what you can't do) is in coderhelm_setup. - 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. @@ -1337,7 +1350,7 @@ Citations: How to write: - Lead with the answer in a sentence or two, then the details. Use a short list or a few short sections when it helps; no headings for a short answer. - Name real files and functions in backticks, like `src/app/page.tsx`. Quote code only when it helps: a short fenced block with its language and the file's path as its title, like ```ts title="src/app/page.tsx" -- Write for the whole team, in plain words; explain a technical term in a few words the first time."#; +- Write for the person asking, in plain words; explain a technical term in a few words the first time."#; /// The system prompt: how to work, and the repositories this question may /// read (with what each is for). @@ -1451,6 +1464,13 @@ struct Run { /// The team's work (tickets, pull requests, runs, findings) as this /// asker may read it; `None` when the question doesn't read it. work: Option, + /// What the question asks for, read with the thread before it. + understood: super::chat_understand::Understood, + /// The asker's Coderhelm role, and whether a GitHub account is linked. + role: String, + github_linked: bool, + /// The knowledge bases the asker may read, by name. + kb_names: Vec, } impl Run { @@ -1603,6 +1623,8 @@ fn tool_defs(run: &Run) -> Vec { w.github_token.is_some(), )); } + // What Coderhelm is set up to do for the team: every question may ask. + tools.push(super::chat_setup::def()); tools.extend( run.worker .tools @@ -1631,6 +1653,7 @@ fn tool_label(name: &str, input: &Value) -> String { MEMORY_TOOL => format!("Searched past work in {}", short_repo(&s("repo"))), common::plugins::brain::ASK_TOOL => format!("Asked the {} plugin", s("plugin")), n if super::chat_work::is_work_tool(n) => super::chat_work::label(n, input), + super::chat_setup::SETUP => "Checked Coderhelm's setup for the team".into(), n if n.starts_with("graph_") => chat_code::graph_label(n, input), n if n.contains("__") => { let (server, tool) = n.split_once("__").unwrap_or((n, "")); @@ -1780,6 +1803,9 @@ async fn run_tool( input: &Value, ) -> (String, String, bool) { let kind = kind_of_tool(name); + if name == super::chat_setup::SETUP { + return setup(run, reg).await; + } if !run.picks.allows(kind) { return ( "That source isn't part of this question.".into(), @@ -1982,6 +2008,94 @@ async fn run_tool( } } +/// The team's setup, checked now (`chat_setup`): each connection with the +/// test the integrations page uses, the runs counted, the records counted +/// as the asker may see them. +async fn setup(run: &Run, reg: &mut Registry) -> (String, String, bool) { + use super::chat_setup as cs; + let state = &run.state; + let (installation, token, jira) = match &run.work { + Some(w) => (w.installation_id, w.github_token.is_some(), w.jira.clone()), + None => { + let (id, jira) = tokio::join!( + super::graph::installation_id(state, &run.team_id), + super::chat_work_tickets::load(state, &run.team_id), + ); + let token = match id { + Some(_) => github_token(state, &run.team_id).await.is_some(), + None => false, + }; + (id, token, jira) + } + }; + let (runs, records) = match &run.work { + Some(w) => { + let runs = async { + if super::chat_work::may(&w.readable, "runs") { + Some( + Box::pin(super::chat_work_runs::tally( + state, + &run.team_id, + cs::RUN_DAYS, + )) + .await, + ) + } else { + None + } + }; + tokio::join!(runs, cs::count_records(w)) + } + None => (None, Vec::new()), + }; + let mut servers: Vec = run + .mcp_tools + .iter() + .filter_map(|t| { + t["name"] + .as_str()? + .split_once("__") + .map(|(s, _)| s.to_string()) + }) + .filter(|s| s != "github") + .collect(); + servers.sort(); + servers.dedup(); + let mut connections = vec![ + cs::Connection { + name: "GitHub".into(), + check: cs::github_check(installation, token, run.repos.len()), + }, + cs::Connection { + name: "Jira".into(), + check: cs::jira_check(&jira), + }, + ]; + connections.extend(cs::app_checks(&servers, &run.missing)); + let mut repos: Vec = run.repos.keys().cloned().collect(); + repos.sort(); + let reads: Vec = SOURCE_KINDS + .iter() + .filter(|k| run.picks.allows(k.key)) + .filter(|k| k.key != "code" || run.github_token.is_some()) + .map(|k| k.label.to_string()) + .collect(); + let found = cs::Setup { + checked_at: live_stamp(), + role: run.role.clone(), + can_change_integrations: run.is_admin, + github_linked: run.github_linked, + connections, + repos, + knowledge: run.kb_names.clone(), + runs, + records, + reads, + }; + let (text, summary) = cs::render(&found, reg); + (text, summary, false) +} + /// Chat's tools behind the agent permission gate: every call is asked of /// the gate first, a connection the asker can't use yet is offered as a /// sign-in card, and the code tools read through one [`CodeReader`]. @@ -2373,18 +2487,19 @@ pub async fn brain_stream( crate::bases::decide_all(&who, &auds, None) }; let base_open = |k: &str| open.get(k).is_some_and(crate::bases::Decision::is_open); - let readable: Vec = if base_open(crate::lookups::TEAM) { + let readable_bases = if base_open(crate::lookups::TEAM) { super::knowledge::chat_readable( st.bases(&claims.team_id).await.unwrap_or_default(), &holder, &me, ) - .into_iter() - .map(|b| b.id) - .collect() } else { Vec::new() }; + let readable: Vec = readable_bases.iter().map(|b| b.id.clone()).collect(); + // What the question asks for, with the thread before it: it decides + // the answer's shape, where it must look, and the notes. + let understood = super::chat_understand::read(&question, &history); let all_repos = load_repos(&state, &claims.team_id).await; let repo_names: Vec = all_repos.iter().map(|r| r.name.clone()).collect(); let picks = resolve_picks( @@ -2495,12 +2610,14 @@ pub async fn brain_stream( installation_id, jira, caller: common::github_budget::caller::CHAT, + needs_shape: understood.needs_shape(), }) } else { None }; // Code reads only when the question reads code. let github = github.filter(|_| picks.code && !code_repos.is_empty()); + let picks_kbs = picks.knowledge.clone(); let run = Run { state: state.clone(), team_id: claims.team_id.clone(), @@ -2523,6 +2640,17 @@ pub async fn brain_stream( run_note: run_note(&state, &claims.team_id, &mentioned_runs(&body.mentions)).await, found: std::sync::Mutex::new(Vec::new()), work, + kb_names: readable_bases + .iter() + .filter(|b| picks_kbs.contains(&b.id)) + .map(|b| b.name.clone()) + .collect(), + understood, + role: claims.role.clone(), + github_linked: claims + .github_login + .as_deref() + .is_some_and(|l| !l.trim().is_empty()), }; let (tx, rx) = tokio::sync::mpsc::channel::>(256); @@ -2790,9 +2918,10 @@ async fn answer( .await; let mut tools = tool_defs(run); - // What the question names puts the tool that holds the answer first. - let hints = super::chat_hints::read(question); - super::chat_work::put_first(&mut tools, &hints); + // What the question names and asks for puts the tool that holds the + // answer first. + let understood = &run.understood; + understood.order(&mut tools, question); // Agent permissions: a connection the asker can't use yet is offered as // a sign-in card, and every call is asked of the gate first. if let Some(t) = super::chat_policy::sign_in_tool(&run.missing) { @@ -2817,10 +2946,11 @@ async fn answer( let mut notes = mention_note(&run.code_repos, question); let offered: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect(); - 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 = super::chat_work::must_look(&hints, &offered); + notes.push_str(&understood.notes(&offered)); + // A status question's answer is in the tickets, pull requests and runs, + // an orientation's in the team's setup, a correction's in a check made + // now: an answer that didn't look there goes back once. + let must_look = understood.must_look(&offered, question); notes.push_str(&run.run_note); if !problems.is_empty() { notes.push_str(&format!( @@ -2864,7 +2994,9 @@ async fn answer( question, limits: chat_agent::LIMITS, must_look, + uncited_ok: understood.uncited_ok(), }; + info!(team_id = %run.team_id, intent = understood.intent().key(), "Chat: the question reads"); let out = chat_agent::run(&model, &mut toolbox, sink, &mut reg, ask) .await .ok()?; diff --git a/services/gateway/src/routes/chat_agent.rs b/services/gateway/src/routes/chat_agent.rs index bd1a16a35..5f0908fef 100644 --- a/services/gateway/src/routes/chat_agent.rs +++ b/services/gateway/src/routes/chat_agent.rs @@ -14,7 +14,7 @@ //! calls in `model_call`), the [`Toolbox`] (Chat's tools behind the agent //! permission gate) and the [`Sink`] (the answer stream). -use common::knowledge::answer::{finalize, Final, Registry}; +use common::knowledge::answer::{finalize, finalize_reply, Final, Registry}; use common::model_stream::SseParser; use common::usage::UsageMeter; use futures::StreamExt; @@ -104,6 +104,8 @@ pub struct Ask<'a> { pub limits: Limits, /// Where this question's answer would be, when the question says so. pub must_look: Option, + /// A reply that cites nothing is kept as written (small talk only). + pub uncited_ok: bool, } /// The tools a question's answer lives in (a status question: the tickets, @@ -135,11 +137,26 @@ pub fn look_there(what: &str, tools: &[String]) -> String { 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.", + then answer the question that was asked, with citations.", tools.join(", ") ) } +/// The note sent back when an answer cites nothing it read this turn. +pub fn cite_something(defs: &[Value]) -> String { + let setup = if defs.iter().any(|d| d["name"] == super::chat_setup::SETUP) { + " If the question is about Coderhelm itself (what it does, what is connected, what you can do), call coderhelm_setup and cite it." + } else { + "" + }; + format!( + "Your answer cites nothing read in this answer, so it can't be shown as written. \ + Look up what the answer rests on with your tools and cite it.{setup} Then answer the \ + question that was asked, first, sized to it. If nothing your tools reach holds the \ + answer, say exactly where you looked." + ) +} + /// 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 \ @@ -264,6 +281,7 @@ pub async fn run( question, limits, must_look, + uncited_ok, } = ask; let mut used: Vec = Vec::new(); let mut calls: Vec = Vec::new(); @@ -315,14 +333,18 @@ pub async fn run( if t.stop != "tool_use" || tool_uses.is_empty() || must_answer { // An answer. Check it doesn't hand back work the tools can do. if has_tools && retries < limits.retries && !must_answer && !text.trim().is_empty() { - // In code first; the model's check only when that passes. + // In code first; the model's check only when that passes; + // then an answer that cites nothing (it would be replaced by + // the plain no-source line) looks once with its tools. + let cited = uncited_ok || finalize(&text, reg).grounded; let note = match checked_in_code(&text, must_look.as_ref(), &calls, tools.defs()) { Some(note) => Some(note), None => model .ask(check_body(model.check_id(), question, &text, tools.defs())) .await .and_then(|r| read_check(&r)) - .map(|what| nudge(&what)), + .map(|what| nudge(&what)) + .or_else(|| (!cited).then(|| cite_something(tools.defs()))), }; if let Some(note) = note { retries += 1; @@ -368,7 +390,7 @@ pub async fn run( Called::Stop(note) => { sink.send("text_delta", json!({ "text": note })).await; return Ok(Answered { - fin: finalize(¬e, reg), + fin: finalize_reply(¬e, reg, true), used, rechecked: retries > 0, calls, @@ -411,7 +433,7 @@ pub async fn run( sink.send("text_reset", json!({})).await; } Ok(Answered { - fin: finalize(&last_text, reg), + fin: finalize_reply(&last_text, reg, uncited_ok), used, rechecked: retries > 0, calls, @@ -709,6 +731,7 @@ mod tests { question: q, limits: LIMITS, must_look: None, + uncited_ok: false, } } diff --git a/services/gateway/src/routes/chat_eval.rs b/services/gateway/src/routes/chat_eval.rs index 3fc55cdaf..92ad8a8ce 100644 --- a/services/gateway/src/routes/chat_eval.rs +++ b/services/gateway/src/routes/chat_eval.rs @@ -363,6 +363,7 @@ pub async fn ask( question: case.question, limits: LIMITS, must_look: None, + uncited_ok: false, }, ) .await @@ -473,6 +474,9 @@ pub struct WorkBox<'a> { pub team: String, pub readable: Vec<&'static str>, pub defs: Vec, + /// "What needs me" comes back in its list's shape (the question is + /// that one), as `chat_work::Ctx::needs_shape`. + pub needs_shape: bool, } impl<'a> WorkBox<'a> { @@ -483,6 +487,7 @@ impl<'a> WorkBox<'a> { team: team.into(), readable, defs, + needs_shape: true, } } @@ -621,7 +626,8 @@ impl WorkBox<'_> { 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"); + let (text, summary) = + needs::render_for(&report, reg, "2026-11-16 12:00 UTC", self.needs_shape); Called::Done { text, label: work::label(work::NEEDS_ME, &json!({})), @@ -796,11 +802,13 @@ pub async fn ask_work( case: &WorkCase, ) -> (Answered, Recorder) { let mut tb = WorkBox::new(store, TEAM, readable); - let hints = super::chat_hints::read(case.question); - work::put_first(&mut tb.defs, &hints); + // Read as production reads it (`brain::answer`). + let understood = super::chat_understand::read(case.question, &[]); + tb.needs_shape = understood.needs_shape(); + understood.order(&mut tb.defs, case.question); 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 = work::must_look(&hints, &offered); + let notes = understood.notes(&offered); + let must_look = understood.must_look(&offered, case.question); let sink = Recorder::default(); let mut reg = Registry::default(); let (_, repos) = fixture(); @@ -816,6 +824,7 @@ pub async fn ask_work( question: case.question, limits: LIMITS, must_look, + uncited_ok: understood.uncited_ok(), }, ) .await @@ -1166,6 +1175,7 @@ mod tests { question: case.question, limits: LIMITS, must_look: None, + uncited_ok: false, }, ) .await @@ -1175,7 +1185,10 @@ mod tests { why.iter().any(|w| w.contains("didn't call work_tickets")), "{why:?}" ); - assert!(!before.rechecked); + // Even with no must-look check, an answer that cites nothing now + // looks once (`chat_agent::cite_something`); this script has no + // second answer, so the reported one still fails its case. + assert!(before.rechecked); // After: the same first answer is sent back in code (the model's // check isn't even asked), and the answer looks where it lives. let mut steps: Vec = vec![Box::new(move |_| say(reported))]; diff --git a/services/gateway/src/routes/chat_eval_cases.json b/services/gateway/src/routes/chat_eval_cases.json new file mode 100644 index 000000000..0899317e2 --- /dev/null +++ b/services/gateway/src/routes/chat_eval_cases.json @@ -0,0 +1,381 @@ +[ + { + "name": "real: what caused a disk-full error", + "origin": "real", + "intent": "lookup", + "question": "what caused the ENOSPC error?", + "wants": "The cause of the 'no space left on device' errors the web app logs, from the logs and code, and whether it is still happening." + }, + { + "name": "real: can you run skills in a repository", + "origin": "real", + "intent": "capability", + "question": "are you able to run skills in the harbor-web repo", + "wants": "A yes or no on whether Chat can run the team's skills in that repository, and what it can do instead." + }, + { + "name": "real: is a linked pull request comment accurate", + "origin": "real", + "intent": "judgement", + "question": "is this comment accurate https://github.com/northwind/harbor-web/pull/88#issuecomment-5550001", + "wants": "A verdict on whether Coderhelm's comment on pull request 88 is accurate, from what can be checked about that pull request (its checks and runs), saying plainly that the comment's own text couldn't be read if so." + }, + { + "name": "real: the same comment, pasted after a non-answer", + "origin": "real", + "intent": "judgement", + "history": [ + ["user", "is this comment accurate https://github.com/northwind/harbor-web/pull/88#issuecomment-5550001"], + ["assistant", "I looked through your team's code and knowledge and found nothing that answers this, so I won't guess. If it lives in a document Coderhelm can't see yet, add it to Knowledge or attach it to your question."] + ], + "question": "on pr https://github.com/northwind/harbor-web/pull/88 coderhelm left this comment: Post-merge health check FAILED, the merge introduced NEW check failure(s): e2e. A human should decide on a rollback. Is it accurate?", + "wants": "A verdict on whether the e2e failure after merging pull request 88 is new and real, from the pull request's checks and runs, and what to look at before deciding on a rollback." + }, + { + "name": "real: how to cancel a booking (from a knowledge page)", + "origin": "real", + "intent": "how_to", + "question": "How can I cancel a booking?", + "wants": "The steps and rules for cancelling a slip booking, from the team's own policy documents." + }, + { + "name": "real: a new leader asks what could be useful to them", + "origin": "real", + "intent": "orientation", + "question": "this is my first time using coderhelm. i'm the cto of the company. are are a few things that you think could be useful to me", + "wants": "An orientation for a CTO new to Coderhelm: what Coderhelm already does for their team (from real data) and a few things it can do for someone in their role. Not a to-do list." + }, + { + "name": "real: the leader questions a claim that Jira isn't connected", + "origin": "real", + "intent": "correction", + "history": [ + ["user", "this is my first time using coderhelm. i'm the cto of the company. are are a few things that you think could be useful to me"], + ["assistant", "Welcome. Here are the things I think will matter most to you, starting with something already waiting on you.\n\n## 1. Questions only you can answer\nI checked what's waiting on you: **4 items: 2 need you now, 1 today, 1 when you can.** The first is [ABC-1 Retry the export job](/runs/detail?id=01A), which stopped on a question about its retry limit. Jira isn't connected to Coderhelm, so your Jira tickets aren't in this list.\n\n## 2. Status of any piece of work\nAsk things like \"where are we on HAR-27?\".\n\n## 3. Getting work done by Coderhelm\nAdd the coderhelm label to a Jira ticket."] + ], + "question": "what do you mean that jira isn't connected? i see atlassian in the integrations", + "wants": "A re-check of the Jira connection made now, a plain admission that the earlier claim was wrong (Jira is connected), and the right answer about what that means for their list." + }, + { + "name": "real: what a crawler's name means", + "origin": "real", + "intent": "lookup", + "question": "what does B7 mean in reference to crawlers", + "wants": "What 'B7' names in the team's firewall setup, from the code that defines it." + }, + { + "name": "orientation: what can you do", + "origin": "variant", + "intent": "orientation", + "question": "What can you do?", + "wants": "A short overview of what Chat and Coderhelm can do for this team, grounded in what is set up, with example questions." + }, + { + "name": "orientation: a product manager asks how Coderhelm helps", + "origin": "variant", + "intent": "orientation", + "question": "I'm a product manager on the bookings team. How can coderhelm help me?", + "wants": "What Coderhelm does that matters to a product manager (where work stands, tickets to pull requests, answers from docs), grounded in this team's setup, with example questions." + }, + { + "name": "orientation: first day, where to start", + "origin": "variant", + "intent": "orientation", + "question": "first day here, where do I start?", + "wants": "A brief welcome and a few first things to try in Coderhelm, based on what is set up for the team." + }, + { + "name": "orientation: what is Coderhelm", + "origin": "variant", + "intent": "orientation", + "question": "what is coderhelm exactly?", + "wants": "A plain explanation of what Coderhelm is and what it does for this team, briefly." + }, + { + "name": "orientation: an engineering leader asks what to use it for", + "origin": "variant", + "intent": "orientation", + "question": "As the VP of engineering, what should I use you for?", + "wants": "The few things that matter to a VP of engineering (where work stands, review and security posture, what Coderhelm ships), grounded in this team's data, with example questions." + }, + { + "name": "capability: production logs", + "origin": "variant", + "intent": "capability", + "question": "Can you see our production logs?", + "wants": "A yes or no on whether Chat can read the team's logs, from what is connected, and what it can look at." + }, + { + "name": "capability: merge pull requests", + "origin": "variant", + "intent": "capability", + "question": "can you merge PRs for me?", + "wants": "A clear no for Chat (it only reads), and how Coderhelm merges (auto merge after approval) or what to do instead." + }, + { + "name": "capability: access to the wiki", + "origin": "variant", + "intent": "capability", + "question": "Do you have access to our Confluence?", + "wants": "Whether Confluence or the team's docs are readable, from what is connected and the knowledge bases, without guessing." + }, + { + "name": "capability: run the tests", + "origin": "variant", + "intent": "capability", + "question": "can you run the harbor-api test suite?", + "wants": "A clear no (Chat can't run commands or tests) and what it can do instead (read the tests, or have a run do it)." + }, + { + "name": "capability: review pull requests", + "origin": "variant", + "intent": "capability", + "question": "is coderhelm able to review our pull requests?", + "wants": "Yes, with how (the review label) and what this team's reviews look like if any are recorded." + }, + { + "name": "needs me: what needs my answer", + "origin": "variant", + "intent": "needs_me", + "question": "What needs my answer?", + "wants": "The list of what is waiting on them, most urgent first, with links and what to do." + }, + { + "name": "needs me: anything waiting on me", + "origin": "variant", + "intent": "needs_me", + "question": "anything waiting on me today?", + "wants": "The list of what is waiting on them, most urgent first." + }, + { + "name": "needs me: am I blocking anyone", + "origin": "variant", + "intent": "needs_me", + "question": "am I blocking anyone?", + "wants": "Whether anything is waiting on them, especially reviews and questions others wait on." + }, + { + "name": "needs me: my reviews", + "origin": "variant", + "intent": "needs_me", + "question": "do I have reviews pending?", + "wants": "The pull requests waiting on their review, and nothing unrelated in front of that." + }, + { + "name": "status: the latest on a ticket by title", + "origin": "variant", + "intent": "status", + "question": "What's the latest on \"Embed the booking portal on the signup pages\"?", + "wants": "Where that ticket stands, its pull request and checks, with dates." + }, + { + "name": "status: what is running", + "origin": "variant", + "intent": "status", + "question": "What's running now?", + "wants": "The runs working right now." + }, + { + "name": "status: is a ticket merged", + "origin": "variant", + "intent": "status", + "question": "is HAR-27 merged yet?", + "wants": "Yes or no on whether HAR-27's pull request is merged, with where it stands and when it last changed." + }, + { + "name": "status: why a run stopped", + "origin": "variant", + "intent": "status", + "question": "Why did the run for HAR-12 stop?", + "wants": "Why the HAR-12 run stopped, from the run's record." + }, + { + "name": "status: is a CVE fixed", + "origin": "variant", + "intent": "status", + "question": "Is CVE-2026-1234 fixed in harbor-web?", + "wants": "Yes or no on whether that advisory is fixed in harbor-web, with the fix." + }, + { + "name": "how-to: get Coderhelm to work on a ticket", + "origin": "variant", + "intent": "how_to", + "question": "how do I get coderhelm to work on a ticket?", + "wants": "The steps to hand a ticket to Coderhelm (the label or the comment), briefly." + }, + { + "name": "how-to: run the API locally", + "origin": "variant", + "intent": "how_to", + "question": "How do I run harbor-api locally?", + "wants": "The steps to run harbor-api on a laptop, from its README." + }, + { + "name": "how-to: get a full refund", + "origin": "variant", + "intent": "how_to", + "question": "how can a boater get a full refund?", + "wants": "The rule for a full refund (cancel at least 48 hours before arrival), from the code or policy." + }, + { + "name": "how-to: transfer a booking", + "origin": "variant", + "intent": "how_to", + "question": "What's the process to move a booking to another date?", + "wants": "The rescheduling rules from the team's policy documents." + }, + { + "name": "lookup: how a repository is put together", + "origin": "variant", + "intent": "lookup", + "question": "How is harbor-api put together?", + "wants": "The main parts of harbor-api and how a request moves through them, from the code." + }, + { + "name": "lookup: where refunds are handled", + "origin": "variant", + "intent": "lookup", + "question": "Where are refunds handled?", + "wants": "The file and function that handle refunds." + }, + { + "name": "lookup: what a file does", + "origin": "variant", + "intent": "lookup", + "question": "What does src/jobs/expireHolds.ts do?", + "wants": "What that job does and when it runs." + }, + { + "name": "lookup: who owns a ticket", + "origin": "variant", + "intent": "lookup", + "question": "who is assigned to HAR-27?", + "wants": "The assignee of HAR-27, from the ticket." + }, + { + "name": "lookup: open infrastructure findings", + "origin": "variant", + "intent": "lookup", + "question": "Which infra findings are open?", + "wants": "The open infrastructure findings." + }, + { + "name": "judgement: roll back a pull request", + "origin": "variant", + "intent": "judgement", + "question": "should we roll back PR 88?", + "wants": "A verdict on rolling back pull request 88 (it isn't merged, so there's nothing to roll back), from its state and checks." + }, + { + "name": "judgement: is an upgrade safe", + "origin": "variant", + "intent": "judgement", + "question": "is it safe to bump express in harbor-api to fix CVE-2026-5678?", + "wants": "A verdict with the evidence: the open finding, where express is used, and what would need checking." + }, + { + "name": "judgement: is the refund rule right", + "origin": "variant", + "intent": "judgement", + "question": "do you think the half refund after 48 hours makes sense the way the code does it?", + "wants": "A view on the refund rule as coded (48 hours full, otherwise half, floor), with the code cited and any edge case." + }, + { + "name": "judgement: retry a failed run", + "origin": "variant", + "intent": "judgement", + "question": "is the HAR-12 run worth retrying as is?", + "wants": "A verdict: the run failed because the change used 24 hours where the tests expect 48, so retrying unchanged would likely fail again." + }, + { + "name": "correction: a wrong fact about the code", + "origin": "variant", + "intent": "correction", + "history": [ + ["user", "how long before arrival does a boater have to cancel for a full refund?"], + ["assistant", "A boater gets a full refund when they cancel at least 24 hours before arrival."] + ], + "question": "that's wrong, I'm pretty sure it's 48 hours", + "wants": "A re-check of the code now, a plain admission that 24 hours was wrong, and the right rule (48 hours, half after that)." + }, + { + "name": "correction: a wrong claim that nothing is running", + "origin": "variant", + "intent": "correction", + "history": [ + ["user", "anything running?"], + ["assistant", "Nothing is running right now."] + ], + "question": "are you sure? I can see a run working on the waitlist", + "wants": "A re-check of the running runs now, an admission that a run is working (HAR-31, the waitlist), and its state." + }, + { + "name": "correction: the answer missed the question", + "origin": "variant", + "intent": "correction", + "history": [ + ["user", "who wrote the refund logic?"], + ["assistant", "Refunds are handled in `src/services/refundService.ts`, which gives a full refund 48 hours out and half after that."] + ], + "question": "that's not what I asked. I asked who wrote it", + "wants": "An acknowledgement that the answer missed the question, then an honest answer about who wrote it from what can be checked (or exactly what couldn't be checked)." + }, + { + "name": "correction: a claim that GitHub isn't connected", + "origin": "variant", + "intent": "correction", + "history": [ + ["user", "can you read our code?"], + ["assistant", "GitHub isn't connected to Coderhelm, so I can't read your code."] + ], + "question": "what do you mean github isn't connected? we installed the app last week", + "wants": "A re-check of GitHub made now, a plain admission that the claim was wrong (the app is installed and code is readable), and the right answer." + }, + { + "name": "correction: a claim that was right", + "origin": "variant", + "intent": "correction", + "history": [ + ["user", "Is CVE-2026-5678 fixed in harbor-api?"], + ["assistant", "No, CVE-2026-5678 (open redirect in express 4.19.2) is still open in harbor-api."] + ], + "question": "are you sure? I thought we fixed that one", + "wants": "A re-check of the finding now that confirms it is still open, said plainly, with the evidence." + }, + { + "name": "small talk: thanks", + "origin": "variant", + "intent": "small_talk", + "history": [ + ["user", "What's running now?"], + ["assistant", "One run is working now: HAR-31, adding a waitlist to full slips."] + ], + "question": "thanks!", + "wants": "A short, warm acknowledgement. No lookups, no unrequested dump." + }, + { + "name": "small talk: hi", + "origin": "variant", + "intent": "small_talk", + "question": "hi", + "wants": "A short greeting and an offer of help, not a canned 'found nothing' line." + }, + { + "name": "small talk: ok cool", + "origin": "variant", + "intent": "small_talk", + "history": [ + ["user", "Is CVE-2026-1234 fixed in harbor-web?"], + ["assistant", "Yes. It was fixed by upgrading next to 15.0.4 in pull request 80."] + ], + "question": "ok cool", + "wants": "A one-line acknowledgement." + }, + { + "name": "small talk: good morning", + "origin": "variant", + "intent": "small_talk", + "question": "good morning!", + "wants": "A short greeting, optionally one offer of help." + } +] diff --git a/services/gateway/src/routes/chat_eval_replay.rs b/services/gateway/src/routes/chat_eval_replay.rs new file mode 100644 index 000000000..30dcb4696 --- /dev/null +++ b/services/gateway/src/routes/chat_eval_replay.rs @@ -0,0 +1,901 @@ +//! Chat's replay evals: does Chat understand what a person asks, and answer +//! that? The cases (`chat_eval_cases.json`) are real conversations, made +//! anonymous and moved onto the made-up marina team of `chat_eval`, and +//! variants that cover every kind of question: an orientation, what Chat can +//! do, what needs me, a status, a how-to, a lookup, a judgement, a +//! correction of Chat itself, and small talk. Some carry the thread before +//! the question (a correction needs the answer it corrects). +//! +//! Each case runs through the real answer loop, prepared exactly as +//! production prepares a question ([`prepare`], `brain::answer`), over the +//! team's code, work, knowledge, logs and skills, and over the team's +//! setup ([`team_setup`]). A model judge grades the answer once against a +//! rubric ([`JUDGE_SYSTEM`]): it understood the question, answered that +//! first, checked every claim in this answer, fits the question's size, and +//! has the right tone. +//! +//! `offline_*` tests run on every build with a scripted model. The live run +//! asks the real model and writes one JSON line per case: +//! +//! ```text +//! CHAT_EVAL_API_KEY=... (or CHAT_EVAL_BEDROCK=1) CHAT_EVAL_OUT=/path/replay.jsonl \ +//! cargo test -p gateway live_replay_eval -- --ignored --nocapture +//! ``` + +use common::knowledge::answer::{Registry, SourceRef}; +use common::repo_read::{MemHost, RepoInfo}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use super::brain::{mention_note, system_prompt, Message}; +use super::chat_agent::testing::{CodeBox, Recorder}; +use super::chat_agent::{self, Answered, Ask, Called, MustLook, Sink, Toolbox, LIMITS}; +use super::chat_eval::{fixture, work_store, WorkBox, WorkStore, TEAM}; +use super::chat_work as work; + +/// One question to replay. +#[derive(Debug, Clone, Deserialize)] +pub struct ReplayCase { + pub name: String, + /// `real` (from a real conversation, anonymous) or `variant`. + pub origin: String, + /// The kind of question it is (`common::chat_intent::Intent::key`). + pub intent: String, + /// The thread before the question, as `(role, text)`. + #[serde(default)] + pub history: Vec<(String, String)>, + pub question: String, + /// What the person wanted from the answer, for the judge. + pub wants: String, +} + +pub fn cases() -> Vec { + serde_json::from_str(include_str!("chat_eval_cases.json")).expect("chat_eval_cases.json") +} + +pub fn history_of(c: &ReplayCase) -> Vec { + c.history + .iter() + .enumerate() + .map(|(i, (role, content))| Message { + seq: i as u32, + role: role.clone(), + content: content.clone(), + ..Default::default() + }) + .collect() +} + +// ── The team ──────────────────────────────────────────────────────────────── + +/// The team's infrastructure repository. +pub const INFRA: &str = "northwind/harbor-infra"; + +const INFRA_FILES: &[(&str, &str)] = &[ + ( + "README.md", + "# Harbor infra\n\nTerraform for the Harbor apps: `envs/prod` and `envs/staging`, \ + modules in `modules/`.\n", + ), + ( + "envs/prod/waf.tf", + "# Crawler B7: the team's name for one bot that crawls the slip listing pages. It looks\n\ + # like ordinary Chrome on Windows, sends no cookie, comes through residential proxies and\n\ + # changes its Chrome version often, so fingerprint rules miss it. It is matched by the\n\ + # shape of its requests: a listing page filtered for 4 or more marinas, with no cookie\n\ + # and no Referer. Counted only for now; switch to block once the counts agree.\n\ + module \"waf\" {\n source = \"../../modules/waf\"\n signature_b7 = {\n \ + action = \"count\"\n paths = [\"/slips\", \"/moorings\"]\n min_marinas = 4\n }\n}\n", + ), + ( + "envs/prod/alarms.tf", + "# harbor-web tasks ran out of local disk once: the Next.js fetch cache under\n\ + # .next/cache/fetch-cache grows with every fetch and nothing clears it, so a task that\n\ + # stays up long enough fills its disk and every write fails with ENOSPC. The disk size\n\ + # was left at Fargate's default on purpose. This alarm is the safety net.\n\ + resource \"aws_cloudwatch_metric_alarm\" \"web_enospc\" {\n alarm_name = \ + \"prod-harbor-web-enospc\"\n threshold = 1\n period = 300\n}\n", + ), +]; + +/// The team's repositories, with the infrastructure one. +pub fn replay_fixture() -> (MemHost, Vec) { + let (host, mut repos) = fixture(); + let host = host.with_repo(INFRA, "5d0c11aa90", INFRA_FILES); + repos.push(RepoInfo { + role: Some("infra".into()), + ..RepoInfo::new(INFRA, "main") + }); + (host, repos) +} + +/// The team's knowledge passages: `(file, page, text)`. +pub const KNOWLEDGE: &[(&str, &str, &str)] = &[ + ( + "Booking policy.pdf", + "Page 2", + "Cancelling a slip booking: cancel from My bookings in the Harbor app, or ask the harbor \ + office to cancel it for you. Cancel at least 48 hours before arrival to get the full \ + amount back; a later cancellation gets half back. A no-show gets nothing back.", + ), + ( + "Booking policy.pdf", + "Page 3", + "Moving a booking to another date: one free change with at least 24 hours' notice, to a \ + date within one year of the original. A later change counts as a cancellation and a new \ + booking.", + ), + ( + "Event bookings.pdf", + "Page 1", + "Party and event bookings: cancel more than 5 days before the event and only the deposit \ + is kept; 5 days or less before, the deposit and the full balance are kept.", + ), +]; + +const KB_NAME: &str = "Member handbook"; +pub const KNOWLEDGE_TOOL: &str = "search_knowledge"; +pub const LOGS_TOOL: &str = "logs_search"; +pub const SKILL_TOOL: &str = "read_skill"; + +fn words(text: &str) -> Vec { + work::words_of(text) + .into_iter() + .filter(|w| w.chars().count() >= 4) + .collect() +} + +/// The passages sharing at least two words with `query` (a booking and a +/// bookings are one word). +pub fn search_knowledge(query: &str) -> Vec<(&'static str, &'static str, &'static str)> { + let q = words(query); + let stem = |w: &str| w.trim_end_matches('s').to_string(); + KNOWLEDGE + .iter() + .filter(|(_, _, text)| { + let t: Vec = words(text).iter().map(|w| stem(w)).collect(); + q.iter().filter(|w| t.contains(&stem(w))).count() >= 2 + }) + .copied() + .collect() +} + +fn add_passages(reg: &mut Registry, found: &[(&str, &str, &str)]) -> Vec { + found + .iter() + .map(|(title, loc, text)| { + reg.add(SourceRef { + kind: "knowledge".into(), + title: title.to_string(), + loc: loc.to_string(), + as_of: "2026-09-01".into(), + passage: text.to_string(), + base: KB_NAME.into(), + href: Some("/knowledge/base/?id=kb1".into()), + ..Default::default() + }) + }) + .collect() +} + +const LOG_LINES: &str = "Searched harbor-web's log group over the last 14 days.\n\ +26,599 matching lines, all from task 7f3a91c0 (started 2026-11-15 17:54 UTC), the first at 2026-11-18 04:44 UTC and the latest a minute ago.\n\ +2026-11-18T04:44:10Z [7f3a91c0] Failed to update prerender cache: ENOSPC: no space left on device, open '/app/.next/cache/fetch-cache/3f9a...'\n\ +2026-11-18T09:12:51Z [7f3a91c0] ENOSPC: no space left on device, write\n\ +Other tasks in the window ran a few hours to a day before they were replaced; none logged ENOSPC."; + +const SKILLS: &str = "The team's skills: skill:harbor-frontend (how the web app is laid out and its conventions), \ +skill:code-standards (review rules), skill:e2e-test (runs the Playwright end-to-end suite from a terminal: \ +`npx playwright test`), skill:sanity-deploy (deploys the CMS from a terminal)."; + +/// The team's setup, as `coderhelm_setup` would find it: GitHub and Jira +/// connected, the runs of the work store counted. +pub fn team_setup(store: &WorkStore) -> super::chat_setup::Setup { + use super::chat_setup::{github_check, jira_check, Check, Connection, Counted, Setup}; + let items: Vec = store + .runs + .iter() + .filter(|(t, _)| t == TEAM) + .map(|(_, i)| i.clone()) + .collect(); + let runs = super::chat_work_runs::tally_of(&items, "2026-10-20T00:00:00Z", 30, false); + Setup { + checked_at: "2026-11-19 14:00 UTC".into(), + role: "admin".into(), + can_change_integrations: true, + github_linked: true, + connections: vec![ + Connection { + name: "GitHub".into(), + check: github_check(Some(42), true, 3), + }, + Connection { + name: "Jira".into(), + check: jira_check(&super::chat_work_tickets::Jira { + app: Some(super::chat_work_tickets::JiraApp { + issues_url: "https://example.invalid/issues".into(), + secret: "x".into(), + site: "https://northwind.atlassian.net".into(), + }), + off: String::new(), + }), + }, + Connection { + name: "AWS account 111122223333".into(), + check: Check::Ok( + "CloudWatch logs and metrics read through a read-only role".into(), + ), + }, + ], + repos: vec![ + super::chat_eval::API.into(), + super::chat_eval::WEB.into(), + INFRA.into(), + ], + knowledge: vec![KB_NAME.into()], + runs: Some(Ok(runs)), + records: vec![ + Counted { + what: "pull request reviews", + n: Ok(12), + at_least: false, + }, + Counted { + what: "open security findings", + n: Ok(1), + at_least: false, + }, + Counted { + what: "open infrastructure findings", + n: Ok(2), + at_least: false, + }, + ], + reads: vec![ + "Files and pages".into(), + "Code".into(), + "Logs and data".into(), + "Team know-how".into(), + "Tickets, pull requests and runs".into(), + ], + } +} + +/// Every tool the team's Chat has: code, work, knowledge, logs, skills, +/// and the side's own tools ([`side_tools`]). +pub struct ReplayBox<'a> { + pub code: CodeBox<'a>, + pub work: WorkBox<'a>, + pub defs: Vec, + pub store: &'a WorkStore, +} + +impl<'a> ReplayBox<'a> { + pub fn new(host: &'a MemHost, repos: &[RepoInfo], store: &'a WorkStore) -> Self { + let code = CodeBox::new(host, repos.to_vec()); + let all: Vec<&'static str> = work::KINDS.iter().map(|k| k.key).collect(); + let work = WorkBox::new(store, TEAM, all); + let mut defs = code.defs.clone(); + defs.push(json!({ + "name": KNOWLEDGE_TOOL, + "description": "Search the team's knowledge bases again with different words. Returns passages as blocks you can cite.", + "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]} + })); + defs.push(json!({ + "name": LOGS_TOOL, + "description": "Search the team's CloudWatch logs (read only) for words or an error, over the last days.", + "input_schema": {"type": "object", "properties": { + "query": {"type": "string"}, "source": {"type": "string"}, "hours": {"type": "integer"} + }, "required": ["query"]} + })); + defs.push(json!({ + "name": SKILL_TOOL, + "description": "Read the team's skills (written guidance and helpers) by name, or list them with no name.", + "input_schema": {"type": "object", "properties": {"name": {"type": "string"}}} + })); + defs.extend(work.defs.iter().cloned()); + defs.extend(side_tools()); + ReplayBox { + code, + work, + defs, + store, + } + } +} + +fn one(reg: &mut Registry, kind: &str, title: &str, passage: &str) -> String { + let id = reg.add(SourceRef { + kind: kind.into(), + title: title.into(), + as_of: "2026-11-19 14:00 UTC".into(), + passage: passage.into(), + ..Default::default() + }); + reg.render(&[id]) +} + +#[async_trait::async_trait] +impl Toolbox for ReplayBox<'_> { + fn defs(&self) -> &[Value] { + &self.defs + } + async fn call( + &mut self, + reg: &mut Registry, + sink: &dyn Sink, + name: &str, + input: &Value, + ) -> Called { + let done = |text: String, label: &str, summary: &str, kind: &str| Called::Done { + text, + label: label.into(), + summary: summary.into(), + is_error: false, + kind: kind.into(), + }; + match name { + n if super::chat_code::is_code_tool(n) => self.code.call(reg, sink, name, input).await, + n if work::is_work_tool(n) => self.work.call(reg, sink, name, input).await, + KNOWLEDGE_TOOL => { + let found = search_knowledge(input["query"].as_str().unwrap_or("")); + if found.is_empty() { + return done( + "No passages matched.".into(), + "Searched knowledge", + "No passages matched", + "knowledge", + ); + } + let ids = add_passages(reg, &found); + done( + reg.render(&ids), + "Searched knowledge", + "passages", + "knowledge", + ) + } + LOGS_TOOL => { + let q = input["query"].as_str().unwrap_or("").to_lowercase(); + if ["enospc", "space", "disk", "cache"] + .iter() + .any(|w| q.contains(w)) + { + let text = one( + reg, + "data_source", + "Searched the logs in harbor-web", + LOG_LINES, + ); + done(text, "Searched the logs", "26,599 lines", "data_sources") + } else { + done( + "No results found.".into(), + "Searched the logs", + "No results", + "data_sources", + ) + } + } + SKILL_TOOL => { + let text = one(reg, "skill", "The team's skills", SKILLS); + done(text, "Read the team's skills", "Read", "skills") + } + super::chat_setup::SETUP => { + let (text, summary) = super::chat_setup::render(&team_setup(self.store), reg); + done( + text, + "Checked Coderhelm's setup for the team", + &summary, + "work", + ) + } + _ => done(format!("Unknown tool: {name}"), name, "Unknown", ""), + } + } +} + +// ── Preparing a question, as production does ──────────────────────────────── + +/// The tools this side of the comparison has beyond the team's sources. +pub fn side_tools() -> Vec { + vec![super::chat_setup::def()] +} + +/// What `brain::answer` does before the loop: read the question with the +/// thread, order the tools, write the notes, decide where it must look and +/// whether an uncited reply stands. Returns `(notes, must_look, uncited_ok)`. +pub fn prepare( + question: &str, + history: &[Message], + tb: &mut ReplayBox<'_>, + repos: &[RepoInfo], +) -> (String, Option, bool) { + let understood = super::chat_understand::read(question, history); + tb.work.needs_shape = understood.needs_shape(); + understood.order(&mut tb.defs, question); + let offered: Vec<&str> = tb.defs.iter().filter_map(|t| t["name"].as_str()).collect(); + let mut notes = mention_note(repos, question); + notes.push_str(&understood.notes(&offered)); + notes.push_str(&format!( + "\nThe team's own tools for this question:\n{SKILLS}\n" + )); + ( + notes, + understood.must_look(&offered, question), + understood.uncited_ok(), + ) +} + +/// The model's input, as `brain::build_messages` writes it: the thread, +/// then the sources found first, the notes and the question. +pub fn messages(history: &[Message], sources: &str, notes: &str, question: &str) -> Vec { + let mut out: Vec = Vec::new(); + for m in history { + let role = if m.role == "assistant" { + "assistant" + } else { + "user" + }; + if out.last().is_some_and(|l| l["role"] == role) { + continue; + } + out.push(json!({ "role": role, "content": [{"type": "text", "text": m.content}] })); + } + if out.last().is_some_and(|l| l["role"] == "user") { + out.pop(); + } + if out.first().is_some_and(|f| f["role"] == "assistant") { + out.remove(0); + } + let block = if sources.trim().is_empty() { + "(no knowledge passages matched this question)".to_string() + } else { + sources.to_string() + }; + out.push(json!({ "role": "user", "content": [{"type": "text", "text": + format!("\n{block}\n{notes}\nQuestion: {question}") + }]})); + out +} + +/// One case through the real loop. Returns the answer and every source read. +pub async fn replay( + model: &dyn chat_agent::Model, + host: &MemHost, + repos: &[RepoInfo], + store: &WorkStore, + case: &ReplayCase, +) -> (Answered, Registry) { + let history = history_of(case); + let mut tb = ReplayBox::new(host, repos, store); + let mut reg = Registry::default(); + // Knowledge first, in code, as production retrieves it. + let first = add_passages( + &mut reg, + &search_knowledge(&super::brain::retrieval_query(&case.question, &history)), + ); + let (notes, must_look, uncited_ok) = prepare(&case.question, &history, &mut tb, repos); + let sink = Recorder::default(); + let msgs = messages(&history, ®.render(&first), ¬es, &case.question); + let out = chat_agent::run( + model, + &mut tb, + &sink, + &mut reg, + Ask { + system: system_prompt(repos, true), + messages: msgs, + question: &case.question, + limits: LIMITS, + must_look, + uncited_ok, + }, + ) + .await + .unwrap_or_else(|_| panic!("{}: the model couldn't be reached", case.name)); + (out, reg) +} + +// ── The judge ─────────────────────────────────────────────────────────────── + +pub const JUDGE_SYSTEM: &str = "You grade one answer written by a software team's Chat assistant (Coderhelm's Chat). You see the thread before the question, the question, what the person actually wanted (written by the eval's author), everything Chat read while answering (its sources this turn), and the answer the person saw. Grade five things, each true or false:\n\ +1. understood: the answer shows Chat understood what the person actually wanted, not a different or template question.\n\ +2. answered_first: the first sentence or two answer that question directly; anything else comes after.\n\ +3. claims_checked: every claim about connections, setup, counts, state, people or facts in the answer is supported by what Chat read this turn (its sources); nothing is asserted that the sources don't support or that contradicts them; a failed check is described as that check, never as a broader claim like \"X isn't connected\". An answer that says plainly what it couldn't check is fine. A greeting with no claims is true.\n\ +4. length_right: the length and structure fit the question: a greeting or a yes-or-no gets a short answer, an orientation is brief and scannable, a diagnosis may be longer; no padding, no unrequested lists or dumps.\n\ +5. tone_right: plain, direct and respectful; a mistake is admitted plainly when the person corrects it; no defensiveness, no salesmanship, and no handing work back that the assistant's tools could do. A canned line that doesn't engage with the question is false.\n\ +Reply with JSON only: {\"understood\": bool, \"answered_first\": bool, \"claims_checked\": bool, \"length_right\": bool, \"tone_right\": bool, \"why\": \"one or two sentences on any false\"}."; + +/// The criteria, in the order they are reported. +pub const CRITERIA: [&str; 5] = [ + "understood", + "answered_first", + "claims_checked", + "length_right", + "tone_right", +]; + +pub fn judge_body(model_id: &str, case: &ReplayCase, answer: &str, reg: &Registry) -> Value { + let thread: String = case + .history + .iter() + .map(|(r, t)| format!("{r}: {}\n", common::truncate_str(t, 1500))) + .collect(); + let read: String = (1..=reg.len()) + .filter_map(|n| reg.get(&format!("S{n}"))) + .map(|s| { + format!( + "[{}] {} ({}): {}\n", + s.id, + s.title, + s.kind, + common::truncate_str(&s.passage, 6000) + ) + }) + .collect(); + json!({ + "model": model_id, + "max_tokens": 2000, + "system": JUDGE_SYSTEM, + "messages": [{"role": "user", "content": [{"type": "text", "text": format!( + "Thread before the question:\n{}\nQuestion:\n{}\n\nWhat the person wanted:\n{}\n\nWhat Chat read this turn:\n{}\nThe answer the person saw:\n{}", + if thread.is_empty() { "(none)\n".to_string() } else { thread }, + case.question, + case.wants, + if read.is_empty() { "(nothing)\n".to_string() } else { read }, + answer + )}]}], + }) +} + +/// The judge's grades, by [`CRITERIA`], and why. +pub fn read_verdict(reply: &str) -> Option<([bool; 5], String)> { + let start = reply.find('{')?; + let end = reply.rfind('}')?; + let v: Value = serde_json::from_str(reply.get(start..=end)?).ok()?; + let mut out = [false; 5]; + for (i, k) in CRITERIA.iter().enumerate() { + out[i] = v[*k].as_bool()?; + } + Some((out, v["why"].as_str().unwrap_or("").to_string())) +} + +#[cfg(test)] +/// How the live eval reaches Claude: `CHAT_EVAL_API_KEY` for the Anthropic +/// API, or `CHAT_EVAL_BEDROCK=1` for Bedrock with the shell's AWS +/// credentials (the way a hosted install calls it). The key returned is +/// empty on Bedrock. +async fn eval_model_access() -> String { + if std::env::var("CHAT_EVAL_BEDROCK").is_ok_and(|v| v == "1") { + let aws = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; + common::model_provider::set_bedrock_client(aws_sdk_bedrockruntime::Client::new(&aws)); + common::model_provider::set_current( + common::model_provider::Settings { + provider: common::model_provider::Provider::Bedrock, + ..Default::default() + }, + common::model_provider::Source::Deploy, + ); + return String::new(); + } + std::env::var("CHAT_EVAL_API_KEY").expect("set CHAT_EVAL_API_KEY or CHAT_EVAL_BEDROCK=1") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::routes::chat_agent::testing::{calls, say, Scripted, Step}; + use crate::routes::chat_setup::SETUP; + use crate::routes::chat_work_needs::{ANSWER_SHAPE, NOT_THE_LIST}; + + #[test] + fn every_case_reads_as_the_kind_of_question_it_is() { + let all = cases(); + assert!(all.len() >= 40, "{}", all.len()); + assert!(all.iter().filter(|c| c.origin == "real").count() >= 8); + let mut wrong = Vec::new(); + for c in &all { + let read = super::super::chat_understand::read(&c.question, &history_of(c)); + if read.intent().key() != c.intent { + wrong.push(format!( + "{}: read as {}, is {}", + c.name, + read.intent().key(), + c.intent + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + // Every kind of question has cases. + for k in [ + "orientation", + "capability", + "needs_me", + "status", + "how_to", + "lookup", + "judgement", + "correction", + "small_talk", + ] { + assert!(all.iter().filter(|c| c.intent == k).count() >= 4, "{k}"); + } + } + + /// The real conversations were made anonymous: every link and + /// repository in a case is the made-up team's, and no case names a + /// person by address. + #[test] + fn every_case_is_about_the_made_up_team_only() { + let text = include_str!("chat_eval_cases.json"); + assert!(!text.contains('@'), "an address in a case"); + for (i, _) in text.match_indices("github.com/") { + assert!( + text[i..].starts_with("github.com/northwind/"), + "{}", + &text[i..i + 40] + ); + } + for (i, _) in text.match_indices(".atlassian.net") { + assert!( + text[..i].ends_with("northwind"), + "{}", + &text[i.saturating_sub(30)..i] + ); + } + let repos = [ + super::super::chat_eval::API, + super::super::chat_eval::WEB, + INFRA, + ]; + for c in cases() { + for h in super::super::chat_hints::read(&c.question).repos { + assert!(repos.contains(&h.as_str()), "{}: {h}", c.name); + } + } + } + + fn case(name: &str) -> ReplayCase { + cases().into_iter().find(|c| c.name == name).unwrap() + } + + /// The incident, replayed: the newcomer's question reached for the + /// to-do list and wrote it in its fixed shape. Now the list comes back + /// without its shape, the answer must look the setup up, and it does. + #[tokio::test] + async fn offline_the_newcomer_gets_an_orientation_not_the_to_do_list() { + let c = case("real: a new leader asks what could be useful to them"); + let (host, repos) = replay_fixture(); + let store = work_store(); + let steps: Vec = vec![ + // As in the incident: the list first, and an answer from it. + Box::new(|_| calls("n", work::NEEDS_ME, json!({}))), + Box::new(|b| { + let r = super::super::chat_agent::testing::last_result(b); + assert!(r.contains(NOT_THE_LIST) && !r.contains(ANSWER_SHAPE), "{r}"); + say("Welcome. 4 things need you now: ABC-1 is waiting on your answer [S1].") + }), + // Sent back: it didn't look at the setup. + Box::new(|b| { + let sent = b["messages"].to_string(); + assert!( + sent.contains("you didn't look there") && sent.contains(SETUP), + "{sent}" + ); + calls("s", SETUP, json!({})) + }), + Box::new(|b| { + let r = super::super::chat_agent::testing::last_result(b); + let team = super::super::chat_agent::testing::id_for(&r, "Coderhelm for this team") + .unwrap(); + let what = + super::super::chat_agent::testing::id_for(&r, "What Coderhelm does").unwrap(); + say(&format!("Coderhelm already works for your team: 3 runs in the last 30 days across harbor-web and harbor-api [{team}]. For a CTO: ask β€œWhere are we on the checkout redesign?” for status, β€œWhich critical findings are open?” for risk [{what}].")) + }), + ]; + let model = Scripted::new(steps, vec![r#"{"hands_back": false}"#]); + let (out, _) = replay(&model, &host, &repos, &store, &c).await; + assert!(out.rechecked); + assert_eq!(out.calls, [work::NEEDS_ME, SETUP]); + assert!( + out.fin + .text + .starts_with("Coderhelm already works for your team"), + "{}", + out.fin.text + ); + assert!(out + .fin + .citations + .iter() + .any(|s| s.title == "Coderhelm for this team")); + let bodies = model.bodies.lock().unwrap(); + // The first turn offered the setup first and said how the question reads. + assert_eq!(bodies[0]["tools"][0]["name"], SETUP); + let first = bodies[0]["messages"].to_string(); + assert!( + first.contains("an orientation") && first.contains("the cto"), + "{first}" + ); + assert!(!first.contains("Call work_needs_me first"), "{first}"); + } + + /// The follow-up, replayed: a correction is never answered from the + /// earlier answer's words. + #[tokio::test] + async fn offline_a_correction_checks_again_before_it_answers() { + let c = case("real: the leader questions a claim that Jira isn't connected"); + let (host, repos) = replay_fixture(); + let store = work_store(); + let steps: Vec = vec![ + Box::new(|_| say("Jira isn't connected to Coderhelm, as I said.")), + Box::new(|_| calls("s", SETUP, json!({}))), + Box::new(|_| { + say("You're right, and I was wrong: Jira is connected through the Jira app, and Chat can look your tickets up [S1].") + }), + ]; + let model = Scripted::new(steps, vec![]); + let (out, _) = replay(&model, &host, &repos, &store, &c).await; + assert!(out.rechecked); + assert_eq!(out.calls, [SETUP]); + assert!(out.fin.text.starts_with("You're right, and I was wrong")); + let bodies = model.bodies.lock().unwrap(); + let first = bodies[0]["messages"].to_string(); + assert!( + first.contains("What they question in your last answer"), + "{first}" + ); + assert!( + first.contains("Jira isn't connected to Coderhelm, so your Jira tickets"), + "{first}" + ); + } + + /// Small talk is answered as written; anything else uncited looks once + /// with its tools before the plain no-source line replaces it. + #[tokio::test] + async fn offline_small_talk_stands_and_an_uncited_answer_looks_once() { + let (host, repos) = replay_fixture(); + let store = work_store(); + let hi = case("small talk: hi"); + let model = Scripted::new( + vec![Box::new(|_| say("Hi! What can I help you with?"))], + vec![], + ); + let (out, _) = replay(&model, &host, &repos, &store, &hi).await; + assert_eq!(out.fin.text, "Hi! What can I help you with?"); + assert!(!out.rechecked && out.calls.is_empty()); + let logs = case("capability: production logs"); + let model = Scripted::new( + vec![ + Box::new(|_| say("Yes, I can read your logs.")), + Box::new(|b| { + let sent = b["messages"].to_string(); + assert!(sent.contains("cites nothing read in this answer"), "{sent}"); + calls("s", SETUP, json!({})) + }), + Box::new(|_| { + say("Yes: an AWS account is connected, and Chat reads its CloudWatch logs [S1].") + }), + ], + vec![r#"{"hands_back": false}"#], + ); + let (out, _) = replay(&model, &host, &repos, &store, &logs).await; + assert!(out.rechecked && out.fin.grounded); + assert!(out.fin.text.starts_with("Yes: an AWS account is connected")); + } + + #[test] + fn the_judge_reads_five_grades_and_sees_what_chat_read() { + let v = read_verdict("ok {\"understood\": true, \"answered_first\": false, \"claims_checked\": true, \"length_right\": true, \"tone_right\": true, \"why\": \"led with a list\"}").unwrap(); + assert_eq!(v.0, [true, false, true, true, true]); + assert_eq!(v.1, "led with a list"); + assert!(read_verdict("{\"understood\": true}").is_none()); + let mut reg = Registry::default(); + add_passages(&mut reg, &search_knowledge("How can I cancel a booking?")); + let b = judge_body( + "m", + &case("real: how to cancel a booking (from a knowledge page)"), + "a", + ®, + ); + let text = b["messages"][0]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("[S1] Booking policy.pdf"), "{text}"); + assert!(text.contains("What the person wanted")); + } +} + +/// The replay set against the real model, judged once per case. Ignored +/// unless asked for. +#[tokio::test] +#[ignore = "calls the real model: set CHAT_EVAL_API_KEY or CHAT_EVAL_BEDROCK=1 and run with --ignored"] +async fn live_replay_eval() { + use futures::StreamExt; + let key = eval_model_access().await; + let model_id = std::env::var("CHAT_EVAL_MODEL").unwrap_or_else(|_| "claude-sonnet-5-5".into()); + let judge_id = std::env::var("CHAT_EVAL_JUDGE_MODEL").unwrap_or_else(|_| model_id.clone()); + let out_path = std::env::var("CHAT_EVAL_OUT").ok(); + let (meter, _) = common::usage::UsageMeter::memory("TEAM#eval"); + let model = chat_agent::ApiModel { + http: reqwest::Client::new(), + api_key: key.clone(), + meter: meter.clone(), + model_id: model_id.clone(), + check_model_id: model_id.clone(), + kind_of: crate::routes::brain::kind_of_tool, + }; + let judge = chat_agent::ApiModel { + http: reqwest::Client::new(), + api_key: key, + meter, + model_id: judge_id.clone(), + check_model_id: judge_id.clone(), + kind_of: crate::routes::brain::kind_of_tool, + }; + let (host, repos) = replay_fixture(); + let store = work_store(); + let all = cases(); + let rows: Vec = futures::stream::iter(all.iter()) + .map(|c| { + let (model, judge, host, repos, store) = (&model, &judge, &host, &repos, &store); + let judge_id = judge_id.clone(); + async move { + let (out, reg) = replay(model, host, repos, store, c).await; + // A judge that didn't answer, or answered off the form, is + // asked again; it never grades the answer as failed. + let mut verdict = None; + let mut last = String::from("no reply"); + for attempt in 0..4u64 { + if attempt > 0 { + tokio::time::sleep(std::time::Duration::from_secs(2 * attempt)).await; + } + match chat_agent::Model::ask(judge, judge_body(&judge_id, c, &out.fin.text, ®)).await { + Some(r) => match read_verdict(&r) { + Some(v) => { + verdict = Some(v); + break; + } + None => last = format!("off the form: {}", common::truncate_str(&r, 400)), + }, + None => last = String::from("no reply"), + } + } + let judged = verdict.is_some(); + let (grades, why) = verdict.unwrap_or(([false; 5], format!("not judged ({last})"))); + println!("\n=== {} ===\nQ: {}\ncalls: {:?}\nA: {}\ngrades: {grades:?} {why}", c.name, c.question, out.calls, out.fin.text); + json!({ + "name": c.name, "origin": c.origin, "intent": c.intent, + "calls": out.calls, "rechecked": out.rechecked, "answer": out.fin.text, + "grades": CRITERIA.iter().zip(grades).map(|(k, g)| (k.to_string(), json!(g))).collect::>(), + "all": grades.iter().all(|g| *g), "why": why, "judged": judged, + }) + } + }) + .buffer_unordered(6) + .collect() + .await; + if let Some(p) = out_path { + let lines: String = rows.iter().map(|r| format!("{r}\n")).collect(); + std::fs::write(&p, lines).expect("write CHAT_EVAL_OUT"); + } + let n = rows.len() as f64; + println!("\ncases: {}", rows.len()); + for k in CRITERIA.iter().copied().chain(["all"]) { + let pass = rows + .iter() + .filter(|r| { + if k == "all" { + r["all"] == true + } else { + r["grades"][k] == true + } + }) + .count(); + println!( + "{k}: {pass}/{} ({:.0}%)", + rows.len(), + 100.0 * pass as f64 / n + ); + } +} diff --git a/services/gateway/src/routes/chat_hints.rs b/services/gateway/src/routes/chat_hints.rs index 1ab759029..e20c2a013 100644 --- a/services/gateway/src/routes/chat_hints.rs +++ b/services/gateway/src/routes/chat_hints.rs @@ -21,6 +21,10 @@ static GHSA: LazyLock = static PR_NUMBER: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)(?:\bpull request|\bPR|\bpull|\bmerge request|\bMR)\s*(?:number\s*)?#?\s*([0-9]{1,7})\b|(?:^|[\s(])#([0-9]{1,7})\b").unwrap() }); +/// A link to a pull request on GitHub, and to a comment on it. +static PR_LINK: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)https?://github\.com/([a-z0-9_.-]+)/([a-z0-9_.-]+)/pull/([0-9]{1,7})(?:/[a-z]+)?(#(?:issuecomment|discussion_r|pullrequestreview)-?[0-9]+)?").unwrap() +}); static QUOTED: LazyLock = LazyLock::new(|| { Regex::new("\"([^\"]{4,200})\"|\u{201c}([^\u{201d}]{4,200})\u{201d}|\u{2018}([^\u{2019}]{4,200})\u{2019}|`([^`]{4,200})`") .unwrap() @@ -136,6 +140,10 @@ pub struct Hints { /// CVE and GHSA ids, upper case. pub advisories: Vec, pub quoted: Vec, + /// Repositories a linked pull request is in (`owner/name`). + pub repos: Vec, + /// It links to a comment or review on a pull request. + pub comment_link: bool, /// It asks where something stands. pub status: bool, /// It asks what is running now. @@ -174,6 +182,13 @@ pub fn read(question: &str) -> Hints { } push_unique(&mut h.tickets, key); } + for c in PR_LINK.captures_iter(q) { + if let Ok(n) = c[3].parse::() { + push_unique(&mut h.prs, n); + } + push_unique(&mut h.repos, format!("{}/{}", &c[1], &c[2])); + h.comment_link |= c.get(4).is_some(); + } for c in PR_NUMBER.captures_iter(q) { if let Some(n) = c .get(1) @@ -300,6 +315,17 @@ mod tests { .is_empty()); } + #[test] + fn a_pull_request_link_names_its_number_repository_and_comment() { + let h = read("is this comment accurate https://github.com/acme/web/pull/1450#issuecomment-6450165666"); + assert_eq!(h.prs, [1450]); + assert_eq!(h.repos, ["acme/web"]); + assert!(h.comment_link && h.about_work()); + let h = read("look at https://github.com/acme/web/pull/7/files please"); + assert_eq!(h.prs, [7]); + assert!(!h.comment_link); + } + #[test] fn what_is_running_is_its_own_question() { let h = read("What's running now?"); diff --git a/services/gateway/src/routes/chat_setup.rs b/services/gateway/src/routes/chat_setup.rs new file mode 100644 index 000000000..4575d9459 --- /dev/null +++ b/services/gateway/src/routes/chat_setup.rs @@ -0,0 +1,542 @@ +//! Chat's `coderhelm_setup` lookup: what Coderhelm is set up to do for the +//! asker's team, checked when it is called. Each connection is checked +//! with the same test the integrations page uses (GitHub's installation and +//! token, `common::jira_connection` for Jira), Coderhelm's runs over the +//! last 30 days are counted from the runs themselves, and the records the +//! asker may read (reviews, findings, alerts, quarantined tests) are counted +//! from the pages that show them. With it comes what Coderhelm does, in +//! plain words, each with a question to ask. +//! +//! It is what an orientation ("I'm new, what can you do for me?"), a +//! question about what Chat can do, and a correction about a connection are +//! answered from: a claim about connections, counts or state rests on a +//! check made in this answer, and a check that failed is named as that +//! check, never widened to "X isn't connected". + +use common::knowledge::answer::{Registry, SourceRef}; +use serde_json::{json, Value}; + +use super::chat_work_runs::Tally; + +pub const SETUP: &str = "coderhelm_setup"; + +/// The days of runs counted. +pub const RUN_DAYS: u32 = 30; + +pub fn def() -> Value { + json!({ + "name": SETUP, + "description": "What Coderhelm is set up to do for this team, checked now: each connection (GitHub, Jira, connected apps) with exactly what works and what doesn't, the repositories and knowledge bases, how many runs Coderhelm made in the last 30 days and how they ended, how many reviews, findings, alerts and quarantined tests it keeps, the asker's Coderhelm role, what Chat can read for this answer and what it can't do. Also what Coderhelm does, each with an example question. Call it for an orientation (\"I'm new\", \"what can you do for me\"), for whether Chat or Coderhelm can do something, before any claim about what is connected or how much Coderhelm does, and again whenever the person questions such a claim. No input.", + "input_schema": {"type": "object", "properties": {}} + }) +} + +/// One check's outcome, in words for the answer. +#[derive(Debug, Clone, PartialEq)] +pub enum Check { + /// Works (with what it does). + Ok(String), + /// Set up in part: what works and what doesn't, as the check said it. + Partly(String), + /// Not set up (the check's own words). + Off(String), + /// The check itself failed: what failed, never "not connected". + Failed(String), +} + +impl Check { + fn words(&self) -> String { + match self { + Check::Ok(w) => format!("works: {w}"), + Check::Partly(w) => format!("set up in part: {w}"), + Check::Off(w) => format!("not set up: {w}"), + Check::Failed(w) => format!( + "couldn't be checked just now ({w}); this says nothing about whether it is set up" + ), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Connection { + pub name: String, + pub check: Check, +} + +/// A count of records the asker may read. +#[derive(Debug, Clone, PartialEq)] +pub struct Counted { + pub what: &'static str, + pub n: Result, + /// The read stopped at a limit: at least this many. + pub at_least: bool, +} + +/// Everything the lookup found. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Setup { + pub checked_at: String, + /// The asker's Coderhelm role, and whether it may change integrations. + pub role: String, + pub can_change_integrations: bool, + pub github_linked: bool, + pub connections: Vec, + pub repos: Vec, + pub knowledge: Vec, + pub runs: Option>, + pub records: Vec, + /// What Chat can read for this answer, by source. + pub reads: Vec, +} + +/// One thing Coderhelm does. +pub struct Feature { + pub name: &'static str, + pub does: &'static str, + /// Who leans on it most. + pub helps: &'static str, + /// A question to ask Chat about it. + pub ask: &'static str, +} + +pub const FEATURES: &[Feature] = &[ + Feature { + name: "Tickets to pull requests", + does: "A Jira ticket or GitHub issue with the coderhelm label (or a /coderhelm comment) becomes a run: Coderhelm plans the change, writes it on a coderhelm/ branch, runs the build and tests, reviews its own work and opens the pull request. It then fixes failing CI, answers review comments and resolves conflicts.", + helps: "engineers, engineering managers", + ask: "What's Coderhelm running right now?", + }, + Feature { + name: "Pull request reviews", + does: "Reviews pull requests with the review label: line comments, a risk level, and a verdict that asks for changes only for a named, evidenced problem.", + helps: "engineers, tech leads, engineering leaders", + ask: "What did Coderhelm's reviews flag this week?", + }, + Feature { + name: "Where work stands", + does: "Chat answers from the team's tickets, pull requests and Coderhelm's runs, with the date each last changed.", + helps: "engineering leaders, product managers, engineering managers", + ask: "Where are we on the checkout redesign?", + }, + Feature { + name: "What's waiting on you", + does: "One list of the questions runs stopped on, approvals held for you, reviews asked of you and tickets assigned to you, most urgent first.", + helps: "everyone", + ask: "What needs my answer?", + }, + Feature { + name: "Security and infrastructure", + does: "Dependency advisories checked for whether your code reaches them, with fix pull requests; infrastructure findings; the team's AWS resources and where each is defined.", + helps: "engineering leaders, security, platform and DevOps", + ask: "Which critical findings are open, and who is fixing them?", + }, + Feature { + name: "Alerts, logs and flaky tests", + does: "CloudWatch alarms become fix pull requests, chosen log groups are read for problems, and flaky tests are found and quarantined.", + helps: "platform and DevOps, engineers on call", + ask: "What alerts came in this week and what was done about them?", + }, + Feature { + name: "Answers from the code and docs", + does: "Chat reads the team's code (citing files and lines), its knowledge bases (Notion, Confluence, Google Drive, websites, files) and, when connected, logs, databases and other apps, only reading.", + helps: "everyone, especially people new to the code", + ask: "How is our booking flow put together?", + }, + Feature { + name: "Team controls", + does: "Agent permissions (allow, ask or deny each action), custom roles, monthly token limits, usage and audit records, and an API and MCP server for the team's own AI tools.", + helps: "engineering leaders, admins", + ask: "What can Coderhelm's agents do without asking us?", + }, +]; + +/// What Chat itself can't do, whatever is connected. +pub const CHAT_CANNOT: &str = "Chat only reads: it can't change code, settings or records, and it can't run commands, scripts, tests or deploys. To have Coderhelm change code, label a ticket or issue for a run."; + +fn count_words(c: &Counted) -> String { + match &c.n { + Ok(n) if c.at_least => format!("{}: at least {n}", c.what), + Ok(n) => format!("{}: {n}", c.what), + Err(e) => format!("{}: couldn't be counted just now ({e})", c.what), + } +} + +fn runs_words(t: &Tally) -> String { + if t.started == 0 { + return format!( + "Coderhelm's runs in the last {} days: none started.", + t.days + ); + } + let mut parts = vec![format!("{} finished", t.done)]; + for (n, w) in [ + (t.running, "working now"), + (t.waiting, "waiting on the team"), + (t.failed, "stopped with an error"), + (t.stopped, "cancelled or closed"), + ] { + if n > 0 { + parts.push(format!("{n} {w}")); + } + } + let repos: Vec = t.repos.iter().map(|(r, n)| format!("{r} ({n})")).collect(); + format!( + "Coderhelm's runs in the last {} days: {}{} started ({}); {} opened a pull request; by repository: {}; the newest started {}.", + t.days, + if t.capped { "at least " } else { "" }, + t.started, + parts.join(", "), + t.with_pr, + if repos.is_empty() { "none named".to_string() } else { repos.join(", ") }, + t.latest + ) +} + +/// The team's setup as a source the answer cites, and what Coderhelm does +/// as another. Returns the text the model reads and the step's summary. +pub fn render(s: &Setup, reg: &mut Registry) -> (String, String) { + let mut lines = vec![format!( + "Checked just now ({}). Each line is that check's own result.", + s.checked_at + )]; + lines.push("Connections:".into()); + for c in &s.connections { + lines.push(format!("- {}: {}", c.name, c.check.words())); + } + lines.push(format!( + "Repositories Coderhelm works in: {}{}", + s.repos.len(), + if s.repos.is_empty() { + String::new() + } else { + format!( + " ({}{})", + s.repos + .iter() + .take(12) + .cloned() + .collect::>() + .join(", "), + if s.repos.len() > 12 { ", ..." } else { "" } + ) + } + )); + lines.push(format!( + "Knowledge bases this person can read: {}{}", + s.knowledge.len(), + if s.knowledge.is_empty() { + String::new() + } else { + format!( + " ({})", + s.knowledge + .iter() + .take(10) + .cloned() + .collect::>() + .join(", ") + ) + } + )); + match &s.runs { + Some(Ok(t)) => lines.push(runs_words(t)), + Some(Err(e)) => lines.push(format!( + "Coderhelm's runs couldn't be counted just now ({e})." + )), + None => lines.push("Coderhelm's runs: this person's role can't see runs.".into()), + } + if !s.records.is_empty() { + lines.push(format!( + "Records Coderhelm keeps that this person can see: {}.", + s.records + .iter() + .map(count_words) + .collect::>() + .join("; ") + )); + } + lines.push(format!( + "The person asking: Coderhelm role {}{}; GitHub account {}.", + if s.role.is_empty() { + "unknown" + } else { + &s.role + }, + if s.can_change_integrations { + " (can change integrations)" + } else { + " (can't change integrations; an admin can)" + }, + if s.github_linked { + "linked" + } else { + "not linked" + } + )); + if !s.reads.is_empty() { + lines.push(format!( + "What Chat can read for this answer: {}.", + s.reads.join(", ") + )); + } + lines.push(CHAT_CANNOT.into()); + let team = reg.add(SourceRef { + kind: "coderhelm".into(), + title: "Coderhelm for this team".into(), + loc: "Settings and runs".into(), + as_of: s.checked_at.clone(), + passage: lines.join("\n"), + href: Some("/settings/integrations".into()), + ..Default::default() + }); + let features: Vec = FEATURES + .iter() + .map(|f| { + format!( + "- {}: {} Helps most: {}. Ask: \u{201c}{}\u{201d}", + f.name, f.does, f.helps, f.ask + ) + }) + .collect(); + let what = reg.add(SourceRef { + kind: "coderhelm".into(), + title: "What Coderhelm does".into(), + loc: "Coderhelm".into(), + passage: features.join("\n"), + url: Some("https://docs.coderhelm.com".into()), + ..Default::default() + }); + // The source's own text is read whole (the citation keeps an excerpt). + let text = format!( + "{}{}A line that couldn't be checked says only that the check failed: say which check and what it said, never that the thing isn't set up.", + reg.render_with(&team, &lines.join("\n")), + reg.render_with(&what, &features.join("\n")), + ); + let gaps = s + .connections + .iter() + .filter(|c| matches!(c.check, Check::Failed(_))) + .count(); + let summary = if gaps == 0 { + "Checked the setup".to_string() + } else { + format!("Checked the setup, {gaps} check failed") + }; + (text, summary) +} + +// ── Gathering ─────────────────────────────────────────────────────────────── + +/// GitHub, from what the question already loaded: an installation and +/// whether its token came. +pub fn github_check(installation: Option, token: bool, repos: usize) -> Check { + match (installation, token) { + (Some(_), true) => Check::Ok(format!( + "Coderhelm's GitHub app is installed and its token works; {repos} repositories enabled" + )), + (Some(_), false) => { + Check::Failed("the GitHub app is installed, but its token couldn't be fetched".into()) + } + (None, _) => Check::Off("Coderhelm's GitHub app isn't installed for this team".into()), + } +} + +/// Jira, from the one test of "connected" every reader uses. +pub fn jira_check(j: &super::chat_work_tickets::Jira) -> Check { + if j.app.is_some() { + return Check::Ok( + "Jira is connected through the Jira app; Chat can look tickets up, and runs start from labeled tickets".into(), + ); + } + let words = j.off_words(); + if words == common::jira_connection::NOT_CONNECTED { + Check::Off(words.to_string()) + } else { + // "Jira is connected, but the app hasn't registered ...". + Check::Partly(words.to_string()) + } +} + +/// The connected apps Chat can use, and those that need a sign-in. +pub fn app_checks(servers: &[String], missing: &[super::chat_policy::Missing]) -> Vec { + let mut out = Vec::new(); + if !servers.is_empty() { + out.push(Connection { + name: "Connected apps".into(), + check: Check::Ok(format!("Chat can use {}", servers.join(", "))), + }); + } + if !missing.is_empty() { + out.push(Connection { + name: "Apps waiting on a sign-in".into(), + check: Check::Partly(format!( + "{} {} set up for the team, but this person can't use {} until they sign in or an admin reconnects", + missing.iter().map(|m| m.name.clone()).collect::>().join(", "), + if missing.len() == 1 { "is" } else { "are" }, + if missing.len() == 1 { "it" } else { "them" }, + )), + }); + } + out +} + +/// The records the asker may read, counted from the pages that show them. +pub async fn count_records(ctx: &super::chat_work::Ctx) -> Vec { + use super::chat_work_records as rec; + let kinds: [(&str, &'static str, &str); 5] = [ + ("reviews", "pull request reviews", "any"), + ("security", "open security findings", "open"), + ("infra", "open infrastructure findings", "open"), + ("alerts", "alerts", "any"), + ("tests", "quarantined tests", "open"), + ]; + let reads = kinds + .iter() + .filter(|(k, _, _)| super::chat_work::may(&ctx.readable, k)) + .map(|(k, what, state)| async move { + let ask = rec::RecordAsk { + kind: k.to_string(), + state: state.to_string(), + ..Default::default() + }; + let n = Box::pin(rec::fetch(&ctx.state, &ctx.claims, &ctx.holder, &ask)) + .await + .map(|rows| rows.iter().filter(|r| rec::in_state(r, state)).count()); + Counted { + what, + at_least: *k == "reviews" && n.as_ref().is_ok_and(|n| *n >= 100), + n, + } + }); + futures::future::join_all(reads).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::routes::chat_work_tickets::{Jira, JiraApp}; + + fn setup() -> Setup { + Setup { + checked_at: "2026-11-19 14:00 UTC".into(), + role: "admin".into(), + can_change_integrations: true, + github_linked: true, + connections: vec![ + Connection { + name: "GitHub".into(), + check: github_check(Some(7), true, 3), + }, + Connection { + name: "Jira".into(), + check: jira_check(&Jira { + app: Some(JiraApp { + issues_url: "https://x".into(), + secret: "s".into(), + site: "https://acme.atlassian.net".into(), + }), + off: String::new(), + }), + }, + ], + repos: vec!["acme/web".into(), "acme/api".into(), "acme/infra".into()], + knowledge: vec!["Engineering handbook".into()], + runs: Some(Ok(Tally { + days: 30, + started: 42, + done: 30, + waiting: 5, + failed: 2, + with_pr: 31, + repos: vec![("acme/web".into(), 30), ("acme/api".into(), 12)], + latest: "2026-11-18T22:00:00Z".into(), + ..Default::default() + })), + records: vec![ + Counted { + what: "pull request reviews", + n: Ok(100), + at_least: true, + }, + Counted { + what: "open security findings", + n: Err("Coderhelm couldn't read the security findings just now.".into()), + at_least: false, + }, + ], + reads: vec!["Code".into(), "Tickets, pull requests and runs".into()], + } + } + + #[test] + fn the_setup_is_two_citable_sources_with_every_check_in_its_own_words() { + let mut reg = Registry::default(); + let (text, summary) = render(&setup(), &mut reg); + assert_eq!(reg.len(), 2); + assert!(text.contains("id=\"S1\"") && text.contains("id=\"S2\"")); + assert!( + text.contains("GitHub: works: Coderhelm's GitHub app is installed"), + "{text}" + ); + assert!(text.contains("Jira: works: Jira is connected"), "{text}"); + assert!( + text.contains( + "42 started (30 finished, 5 waiting on the team, 2 stopped with an error)" + ), + "{text}" + ); + assert!(text.contains("31 opened a pull request")); + assert!(text.contains("pull request reviews: at least 100")); + assert!(text.contains("open security findings: couldn't be counted just now")); + assert!(text.contains("Coderhelm role admin (can change integrations)")); + assert!(text.contains(CHAT_CANNOT)); + for f in FEATURES { + assert!(text.contains(f.name) && text.contains(f.ask), "{}", f.name); + } + assert_eq!(summary, "Checked the setup"); + assert!(!text.contains("isn't connected"), "{text}"); + } + + #[test] + fn a_failed_check_is_named_as_that_check_and_never_as_not_connected() { + let mut s = setup(); + s.connections[0].check = github_check(Some(7), false, 3); + s.connections[1].check = jira_check(&Jira { + app: None, + off: common::jira_connection::Gap::LookupNotRegistered + .words() + .into(), + }); + let mut reg = Registry::default(); + let (text, summary) = render(&s, &mut reg); + assert!(text.contains("GitHub: couldn't be checked just now (the GitHub app is installed, but its token couldn't be fetched)"), "{text}"); + assert!( + text.contains("Jira: set up in part: Jira is connected, but"), + "{text}" + ); + assert!(!text.contains("isn't connected"), "{text}"); + assert_eq!(summary, "Checked the setup, 1 check failed"); + // Only a team with no Jira at all hears "not connected", as Jira's own words. + let off = jira_check(&Jira::default()); + assert_eq!( + off, + Check::Off(common::jira_connection::NOT_CONNECTED.into()) + ); + assert_eq!( + github_check(None, false, 0), + Check::Off("Coderhelm's GitHub app isn't installed for this team".into()) + ); + } + + #[test] + fn the_lookup_is_read_only_and_known_to_the_permission_gate() { + assert_eq!( + common::agent_policy::registry::builtin(SETUP), + Some(common::agent_policy::Risk::Read) + ); + assert!(def()["description"] + .as_str() + .unwrap() + .contains("orientation")); + } +} diff --git a/services/gateway/src/routes/chat_understand.rs b/services/gateway/src/routes/chat_understand.rs new file mode 100644 index 000000000..479f30102 --- /dev/null +++ b/services/gateway/src/routes/chat_understand.rs @@ -0,0 +1,251 @@ +//! Chat understands a question before it answers: what it names +//! (`chat_hints`: a ticket, a pull request, "what needs me") and what the +//! person wants (`common::chat_intent`: an orientation, a status, a how-to, +//! a judgement, a correction of Chat itself, small talk, ...), with the +//! earlier answer in the thread. From that reading, and only from it: +//! +//! - the tools are ordered (the one that holds the answer first); +//! - the model is told how the question reads and how to size the answer; +//! - "what needs me" comes back in its list's shape only when that is the +//! question (`chat_work::Ctx::needs_shape`); +//! - an orientation looks the team's setup up, and a correction checks the +//! disputed point again, before either may answer ([`Understood::must_look`]); +//! - an uncited reply is kept only for small talk. +//! +//! The same reading runs in production (`brain::answer`) and in the evals +//! (`chat_eval`), so what is measured is what ships. + +use common::chat_intent::{self, Intent, Reading, Signals}; +use serde_json::Value; + +use super::brain::Message; +use super::chat_agent::MustLook; +use super::chat_hints::{self, Hints}; +use super::chat_setup::SETUP; + +/// A question as read. +#[derive(Debug, Clone, PartialEq)] +pub struct Understood { + pub hints: Hints, + pub reading: Reading, +} + +/// Words that put a disputed point on Coderhelm's own setup. +const SETUP_WORDS: &[&str] = &[ + "connect", + "integration", + "installed", + "set up", + "setup", + "access", + "jira", + "github", + "atlassian", + "confluence", + "slack", + "linked", + "sign in", + "signed in", + "permission", +]; + +/// Reads a question with the thread before it. +pub fn read(question: &str, history: &[Message]) -> Understood { + let hints = chat_hints::read(question); + let last = history + .iter() + .rev() + .find(|m| m.role == "assistant") + .map(|m| m.content.as_str()); + read_with(question, last, hints) +} + +/// [`read`] from the last answer's text. +pub fn read_with(question: &str, last_answer: Option<&str>, hints: Hints) -> Understood { + let signals = Signals { + needs_me: hints.needs_me, + status: hints.status, + names_work: !hints.tickets.is_empty() + || !hints.prs.is_empty() + || !hints.quoted.is_empty() + || !hints.advisories.is_empty(), + }; + Understood { + reading: chat_intent::read(question, last_answer, signals), + hints, + } +} + +impl Understood { + pub fn intent(&self) -> Intent { + self.reading.intent + } + + /// "What needs me" is written in its list's shape. + pub fn needs_shape(&self) -> bool { + self.intent().fixed_shape() + } + + pub fn uncited_ok(&self) -> bool { + self.intent().uncited_ok() + } + + /// The disputed point is about Coderhelm's own setup (a connection, + /// an integration, access). + fn disputes_setup(&self, question: &str) -> bool { + let text = format!("{question} {}", self.reading.disputed.join(" ")).to_lowercase(); + SETUP_WORDS.iter().any(|w| text.contains(w)) + } + + /// Puts the tool that holds the answer first. + pub fn order(&self, tools: &mut [Value], question: &str) { + super::chat_work::put_first(tools, &self.hints); + let setup_first = match self.intent() { + Intent::Orientation | Intent::Capability => true, + Intent::Correction => self.disputes_setup(question), + _ => false, + }; + if setup_first { + tools.sort_by_key(|t| usize::from(t["name"] != SETUP)); + } + } + + /// The notes before the question: where the work lives (when it names + /// work), then how the question reads and how to answer it. + pub fn notes(&self, offered: &[&str]) -> String { + let mut out = super::chat_work::hint_note(&self.hints, offered); + out.push_str(&self.reading.note()); + out + } + + /// Where the answer must look before it may be given. + pub fn must_look(&self, offered: &[&str], question: &str) -> Option { + let has = |t: &str| offered.contains(&t); + match self.intent() { + Intent::Orientation if has(SETUP) => Some(MustLook { + tools: vec![SETUP.to_string()], + what: "what Coderhelm is set up to do for this team, checked now".into(), + always: true, + }), + Intent::Correction => { + let tools: Vec = if has(SETUP) && self.disputes_setup(question) { + vec![SETUP.to_string()] + } else { + offered + .iter() + .filter(|t| **t != super::chat_policy::SIGN_IN_TOOL) + .map(|t| t.to_string()) + .collect() + }; + (!tools.is_empty()).then(|| MustLook { + tools, + what: "the point they question, checked again in this answer (never from the earlier answer's words)".into(), + always: true, + }) + } + _ => super::chat_work::must_look(&self.hints, offered), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::routes::chat_work::{self as work, NEEDS_ME, RUNS, TICKETS}; + use serde_json::json; + + fn msg(role: &str, content: &str) -> Message { + Message { + role: role.into(), + content: content.into(), + ..Default::default() + } + } + + const OFFERED: &[&str] = &[SETUP, NEEDS_ME, TICKETS, work::PULL_REQUESTS, RUNS]; + + /// The first question of the report: an orientation, never the list. + #[test] + fn a_newcomer_gets_an_orientation_from_the_setup_not_the_to_do_list() { + let q = "this is my first time using coderhelm. i'm the cto of the company. are are a few things that you think could be useful to me"; + let u = read(q, &[]); + assert_eq!(u.intent(), Intent::Orientation); + assert!(!u.needs_shape()); + let m = u.must_look(OFFERED, q).unwrap(); + assert!(m.always && m.tools == [SETUP], "{m:?}"); + let notes = u.notes(OFFERED); + assert!(notes.contains("an orientation"), "{notes}"); + assert!(notes.contains("the cto"), "{notes}"); + assert!(!notes.contains("Call work_needs_me first"), "{notes}"); + let mut tools = vec![ + json!({"name": NEEDS_ME}), + json!({"name": RUNS}), + json!({"name": SETUP}), + ]; + u.order(&mut tools, q); + assert_eq!(tools[0]["name"], SETUP); + } + + /// The second: a correction about a connection checks the setup again. + #[test] + fn a_correction_about_a_connection_must_check_the_setup_again() { + let history = vec![ + msg("user", "first time here, what can you do for me?"), + msg("assistant", "Welcome. 24 items need you. Jira isn't connected to Coderhelm, so your Jira tickets aren't in this list."), + ]; + let q = "what do you mean that jira isn't connected? i see atlassian in the integrations"; + let u = read(q, &history); + assert_eq!(u.intent(), Intent::Correction); + let m = u.must_look(OFFERED, q).unwrap(); + assert!(m.always && m.tools == [SETUP], "{m:?}"); + let mut tools = vec![json!({"name": TICKETS}), json!({"name": SETUP})]; + u.order(&mut tools, q); + assert_eq!(tools[0]["name"], SETUP); + // A correction about anything else must look somewhere, anywhere. + let history = vec![msg("assistant", "The refund window is 24 hours [S1].")]; + let q = "that's wrong, the refund window is 48 hours"; + let u = read(q, &history); + assert_eq!(u.intent(), Intent::Correction); + let m = u.must_look(&[TICKETS, "github__search_code"], q).unwrap(); + assert!(m.always && m.tools.len() == 2, "{m:?}"); + } + + #[test] + fn what_needs_me_keeps_its_list_and_its_tool() { + let u = read("What needs my answer?", &[]); + assert_eq!(u.intent(), Intent::NeedsMe); + assert!(u.needs_shape()); + let m = u.must_look(OFFERED, "What needs my answer?").unwrap(); + assert!(m.always && m.tools == [NEEDS_ME]); + assert!(u.notes(OFFERED).contains("Call work_needs_me first")); + } + + #[test] + fn small_talk_may_go_uncited_and_nothing_else_may() { + assert!(read("thanks!", &[]).uncited_ok()); + for q in [ + "what can you do?", + "How can I cancel a reservation?", + "is this comment accurate https://github.com/acme/web/pull/3#issuecomment-9", + "what caused the disk full error?", + ] { + assert!(!read(q, &[]).uncited_ok(), "{q}"); + } + } + + #[test] + fn a_linked_pull_request_comment_is_looked_up_by_number_and_repository() { + let q = "is this comment accurate https://github.com/acme/web/pull/1450#issuecomment-6450165666"; + let u = read(q, &[]); + assert_eq!(u.intent(), Intent::Judgement); + let notes = u.notes(OFFERED); + assert!( + notes.contains("work_pull_requests with number 1450 and repo \"acme/web\""), + "{notes}" + ); + assert!(notes.contains("not its comments"), "{notes}"); + assert!(notes.contains("verdict first"), "{notes}"); + let m = u.must_look(OFFERED, q).unwrap(); + assert!(!m.always && m.tools.contains(&work::PULL_REQUESTS.to_string())); + } +} diff --git a/services/gateway/src/routes/chat_work.rs b/services/gateway/src/routes/chat_work.rs index 8716ef1ba..405b2603f 100644 --- a/services/gateway/src/routes/chat_work.rs +++ b/services/gateway/src/routes/chat_work.rs @@ -366,7 +366,10 @@ pub fn hint_note(h: &super::chat_hints::Hints, offered: &[&str]) -> String { } for n in &h.prs { if has(PULL_REQUESTS) { - steps.push(format!("{PULL_REQUESTS} with number {n}")); + match h.repos.first() { + Some(r) => steps.push(format!("{PULL_REQUESTS} with number {n} and repo \"{r}\"")), + None => steps.push(format!("{PULL_REQUESTS} with number {n}")), + } } if has(RUNS) { steps.push(format!("{RUNS} with pr {n}")); @@ -391,9 +394,14 @@ pub fn hint_note(h: &super::chat_hints::Hints, offered: &[&str]) -> String { return String::new(); } steps.truncate(8); + let comment = if h.comment_link { + " The link points at a comment on that pull request: your lookups read a pull request's state, checks, reviews and the runs on it, not its comments, so judge what the comment claims from those records, and say plainly that you couldn't read the comment itself if its exact words matter." + } else { + "" + }; format!( "\nThis question is about the team's own work. Look it up where it lives first: {}. \ - Then read code or docs only for context. Give a dated status (when each record last changed).\n", + Then read code or docs only for context. Give a dated status (when each record last changed).{comment}\n", steps.join("; ") ) } @@ -468,6 +476,10 @@ pub struct Ctx { /// Who its GitHub reads are counted under (`github_budget::caller`): /// Chat, or an AI tool on `/mcp`. pub caller: &'static str, + /// The question is what's waiting on the person: "what needs me" comes + /// back in its list's shape. Any other question uses only what answers + /// it (`chat_work_needs::NOT_THE_LIST`). + pub needs_shape: bool, } /// The installation's spent-limit time, from the worker's record of it. @@ -729,7 +741,7 @@ async fn needs_me( 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()); + let (text, summary) = needs::render_for(&report, reg, &live_stamp(), ctx.needs_shape); (text, summary, false) } diff --git a/services/gateway/src/routes/chat_work_needs.rs b/services/gateway/src/routes/chat_work_needs.rs index b05781eae..cc35b06de 100644 --- a/services/gateway/src/routes/chat_work_needs.rs +++ b/services/gateway/src/routes/chat_work_needs.rs @@ -1173,12 +1173,28 @@ fn read_words(r: &Read) -> String { /// How the answer is written. pub const ANSWER_SHAPE: &str = "Write the answer in exactly this shape. First the count line. Then each group in the order given (skip an empty one), with its heading, and one line per item, most urgent first: a markdown link to the item named by what it is, then exactly what they need to do, then since when, and its citation. Under a run's line, keep its questions with their possible answers as a short nested list. Then, for every source that couldn't be read or wasn't checked, one plain sentence that says so (for example \"GitHub couldn't be read, so your pull requests aren't listed\"), in that source's own words: never say a system isn't connected unless its line says exactly that. Don't add items that aren't listed here."; +/// How the list is used when the question is something else (an +/// orientation, a status, a judgement): only what answers it. +pub const NOT_THE_LIST: &str = "The question isn't what's waiting on them, so don't write this list. Use only the items that answer the question asked, in a line each. If it helps, say in one line how many things wait on them and that \"What needs my answer?\" lists them. For a source that couldn't be read or wasn't checked, say so only when it matters to the answer, in that source's own words: never say a system isn't connected unless its line says exactly that."; + /// Registers each item as a citable source and writes what the model reads. /// Returns the text and the step's summary. +#[cfg(test)] pub fn render( report: &Report, reg: &mut common::knowledge::answer::Registry, stamp: &str, +) -> (String, String) { + render_for(report, reg, stamp, true) +} + +/// [`render`], with the list's fixed shape only when the question is what's +/// waiting on them (`shaped`); otherwise [`NOT_THE_LIST`]. +pub fn render_for( + report: &Report, + reg: &mut common::knowledge::answer::Registry, + stamp: &str, + shaped: bool, ) -> (String, String) { use common::knowledge::answer::SourceRef; let mut text = format!( @@ -1249,7 +1265,10 @@ pub fn render( report.skipped.join("; ") )); } - text.push_str(&format!("\n{ANSWER_SHAPE}\n\n")); + text.push_str(&format!( + "\n{}\n\n", + if shaped { ANSWER_SHAPE } else { NOT_THE_LIST } + )); text.push_str(®.render(&ids)); let gaps = report .sources diff --git a/services/gateway/src/routes/chat_work_records.rs b/services/gateway/src/routes/chat_work_records.rs index 6bd9845b0..364cd8c61 100644 --- a/services/gateway/src/routes/chat_work_records.rs +++ b/services/gateway/src/routes/chat_work_records.rs @@ -214,7 +214,7 @@ const FIXED: &[&str] = &[ ]; const DISMISSED: &[&str] = &["dismissed", "withdrawn", "ignored", "aws_managed"]; -fn in_state(v: &Value, want: &str) -> bool { +pub fn in_state(v: &Value, want: &str) -> bool { let st = status_of(v); match want { "open" => !FIXED.contains(&st.as_str()) && !DISMISSED.contains(&st.as_str()), diff --git a/services/gateway/src/routes/chat_work_runs.rs b/services/gateway/src/routes/chat_work_runs.rs index c0add1cf1..c2199b612 100644 --- a/services/gateway/src/routes/chat_work_runs.rs +++ b/services/gateway/src/routes/chat_work_runs.rs @@ -488,6 +488,108 @@ pub async fn find(state: &AppState, team_id: &str, ask: &RunAsk) -> Result, + /// When the newest run started. + pub latest: String, + /// More runs may lie past what was read. + pub capped: bool, +} + +/// [`Tally`] from listed runs (newest first), counting those started on or +/// after `since` (RFC 3339). +pub fn tally_of(items: &[Item], since: &str, days: u32, capped: bool) -> Tally { + let mut t = Tally { + days, + capped, + ..Default::default() + }; + let mut repos: HashMap = HashMap::new(); + for i in items { + let status = st(i, "status"); + let created = st(i, "created_at"); + if status == common::run_status::ARCHIVED || created < since { + continue; + } + t.started += 1; + if t.latest.as_str() < created { + t.latest = created.to_string(); + } + if Group::Done.holds(status) { + t.done += 1; + } else if Group::Running.holds(status) { + t.running += 1; + } else if Group::Waiting.holds(status) { + t.waiting += 1; + } else if Group::Failed.holds(status) { + t.failed += 1; + } else if Group::Stopped.holds(status) { + t.stopped += 1; + } + if !pr_numbers(i).is_empty() || !st(i, "pr_url").is_empty() { + t.with_pr += 1; + } + let repo = st(i, "repo"); + if !repo.is_empty() { + *repos.entry(repo.to_string()).or_default() += 1; + } + } + let mut repos: Vec<(String, usize)> = repos.into_iter().collect(); + repos.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + repos.truncate(8); + t.repos = repos; + t +} + +/// The team's runs over the last `days`, counted. Only `team_id`'s +/// partition is read, newest first, at most [`SCAN`] runs. +pub async fn tally(state: &AppState, team_id: &str, days: u32) -> Result { + let since = (chrono::Utc::now() - chrono::Duration::days(days as i64)).to_rfc3339(); + let (projection, names) = projection(); + let mut items: Vec = Vec::new(); + let mut start: Option = None; + let mut capped = false; + loop { + let r = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .key_condition_expression("team_id = :tid") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .projection_expression(&projection) + .set_expression_attribute_names(Some(names.clone())) + .scan_index_forward(false) + .limit((SCAN - items.len()).min(200) as i32) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| why("list the runs", e))?; + items.extend(r.items().iter().cloned()); + match r.last_evaluated_key() { + Some(k) if !k.is_empty() && items.len() < SCAN => start = Some(k.clone()), + Some(k) if !k.is_empty() => { + capped = true; + break; + } + _ => break, + } + } + Ok(tally_of(&items, &since, days, capped)) +} + /// The pull requests the matching runs opened, as `(owner/name, number)`, /// best match first: a title search finds its pull request through the run /// that opened it, whatever GitHub's search makes of the title. @@ -545,6 +647,40 @@ pub(crate) mod tests { RunAsk::from_input(&v, chrono::Utc::now()) } + #[test] + fn the_tally_counts_the_window_by_where_each_run_stands() { + let mut with_pr = run("01AAAAAAAAAAAAAAAAAAAA", "merged", "A-1", "x", "acme/web"); + with_pr.insert( + "pr_url".into(), + AttributeValue::S("https://github.com/acme/web/pull/3".into()), + ); + let items = vec![ + with_pr, + run("01AAAAAAAAAAAAAAAAAAAB", "running", "A-2", "y", "acme/web"), + run( + "01AAAAAAAAAAAAAAAAAAAC", + "needs_input", + "A-3", + "z", + "acme/api", + ), + run("01AAAAAAAAAAAAAAAAAAAD", "failed", "A-4", "w", "acme/api"), + run("01AAAAAAAAAAAAAAAAAAAE", "archived", "A-5", "v", "acme/api"), + // Started before the window. + run("01A", "merged", "A-6", "u", "acme/old"), + ]; + let t = tally_of(&items, "2026-11-10T00:00:00Z", 30, false); + assert_eq!( + (t.started, t.done, t.running, t.waiting, t.failed, t.with_pr), + (4, 1, 1, 1, 1, 1) + ); + assert_eq!( + t.repos, + [("acme/api".to_string(), 2), ("acme/web".to_string(), 2)] + ); + assert!(!t.latest.is_empty() && !t.capped); + } + #[test] fn a_title_finds_its_run_even_when_the_words_differ_a_little() { let items = vec![ diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index acc44bd13..f7e7fdd41 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -13,8 +13,12 @@ pub mod chat_agent; pub mod chat_code; #[cfg(test)] pub mod chat_eval; +#[cfg(test)] +pub mod chat_eval_replay; pub mod chat_hints; pub mod chat_policy; +pub mod chat_setup; +pub mod chat_understand; pub mod chat_work; pub mod chat_work_needs; pub mod chat_work_prs; diff --git a/services/worker/src/passes/host_steps_readers.rs b/services/worker/src/passes/host_steps_readers.rs index 980410687..4207ff7b7 100644 --- a/services/worker/src/passes/host_steps_readers.rs +++ b/services/worker/src/passes/host_steps_readers.rs @@ -88,6 +88,7 @@ mod tests { ("gateway/src/routes/brain.rs", "chat answers questions; it offers read_skill as a source and carries out no steps"), ("gateway/src/routes/chat_code.rs", "chat's code reads"), ("gateway/src/routes/chat_eval.rs", "chat evaluations"), + ("gateway/src/routes/chat_eval_replay.rs", "chat's replay evaluations; a fake read_skill for the fixture team"), ("gateway/src/routes/learning.rs", "shows where lessons were written"), ("gateway/src/routes/memory.rs", "describes what reviews read"), ("gateway/src/routes/plan_chat_tools.rs", "forwards the plan chat's tools to the worker's plan_chat (routed)"), diff --git a/services/worker/src/passes/incidents/cu_chat_answers_the_question.rs b/services/worker/src/passes/incidents/cu_chat_answers_the_question.rs new file mode 100644 index 000000000..d18c49a86 --- /dev/null +++ b/services/worker/src/passes/incidents/cu_chat_answers_the_question.rs @@ -0,0 +1,98 @@ +//! cu. A team's CTO opened chat for the first time and asked what could be +//! useful to someone in his role. Chat answered a different question: it +//! led with "what's waiting on you" (24 items, one ticket's details first), +//! in the fixed shape that list's lookup imposes on every answer, and said +//! Jira wasn't connected, a claim it hadn't checked. His next message had to +//! correct it ("what do you mean that jira isn't connected?"). Earlier, a +//! question that linked a pull request comment got the canned "found +//! nothing" line, because any answer that cited nothing was replaced by it. +//! +//! Guarantee: a question is read before it is answered +//! (`common::chat_intent::read`): an orientation, what Chat can do, what +//! needs me, a status, a how-to, a lookup, a judgement, a correction of +//! Chat itself, or small talk, and the role the person says they hold. The +//! list's fixed shape belongs only to "what needs me" +//! (`Intent::fixed_shape`); a correction names what it questions in the +//! last answer and must check it again (`Reading::disputed`); and an uncited +//! reply is kept as written only for small talk +//! (`common::knowledge::answer::finalize_reply`). + +use common::chat_intent::{read, Intent, Signals}; +use common::knowledge::answer::{finalize_reply, Registry, NO_SOURCE_ANSWER}; + +const FIRST: &str = "this is my first time using coderhelm. i'm the cto of the company. are are a few things that you think could be useful to me"; + +/// The answer as it was given (shortened): the list first, then a claim +/// no check made in that answer supported. +const GIVEN: &str = "Welcome. Here are the things I think will matter most to you, starting with something already waiting on you.\n## 1. Questions only you can answer\nI checked what's waiting on your GitHub account: 24 items: 14 need you now, 8 today, 2 when you can. Jira isn't connected to Coderhelm, so your Jira tickets aren't in this list."; + +const NEXT: &str = + "what do you mean that jira isn't connected? i see atlassian in the integrations"; + +#[test] +fn the_first_question_is_an_orientation_for_a_cto_and_never_the_list() { + let r = read(FIRST, None, Signals::default()); + assert_eq!(r.intent, Intent::Orientation); + assert_eq!(r.role.as_deref(), Some("cto")); + assert!(r.newcomer); + // The list's fixed shape is not this question's. + assert!(!r.intent.fixed_shape()); + let note = r.note(); + assert!(note.contains("coderhelm_setup"), "{note}"); + assert!(note.contains("Don't list their to-do items"), "{note}"); + // Only the list's own question gets the list's shape. + let list = read( + "What needs my answer?", + None, + Signals { + needs_me: true, + ..Default::default() + }, + ); + assert!(list.intent.fixed_shape()); +} + +#[test] +fn the_follow_up_is_a_correction_that_names_the_unchecked_claim() { + let r = read(NEXT, Some(GIVEN), Signals::default()); + assert_eq!(r.intent, Intent::Correction); + assert_eq!( + r.disputed, + ["Jira isn't connected to Coderhelm, so your Jira tickets aren't in this list"] + ); + let note = r.note(); + assert!( + note.contains("Check the disputed point again now"), + "{note}" + ); + assert!(note.contains("whether you were wrong"), "{note}"); +} + +#[test] +fn only_small_talk_goes_uncited_and_every_other_answer_rests_on_a_source() { + let thanks = read("thanks!", Some(GIVEN), Signals::default()); + assert_eq!(thanks.intent, Intent::SmallTalk); + let kept = finalize_reply( + "Glad to help.", + &Registry::default(), + thanks.intent.uncited_ok(), + ); + assert_eq!(kept.text, "Glad to help."); + // A judgement on a linked comment is not small talk: uncited, it is + // never shown as if it were checked. + let judged = read( + "is this comment accurate https://github.com/acme/web/pull/3#issuecomment-1", + None, + Signals { + names_work: true, + ..Default::default() + }, + ); + assert_eq!(judged.intent, Intent::Judgement); + let f = finalize_reply( + "Yes, it's accurate.", + &Registry::default(), + judged.intent.uncited_ok(), + ); + assert_eq!(f.text, NO_SOURCE_ANSWER); +}