From 696aa019a950564333b8030502460b2702c33473 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 16:38:16 +0800 Subject: [PATCH 01/12] fix(pc-mate): read a verdict the model printed with a stray quote --- pc-mate/src/intent.rs | 175 ++++++++++++++++++++++++++++++---- pc-mate/src/run_result.rs | 24 ++--- pc-mate/src/supervisor/mod.rs | 14 ++- 3 files changed, 184 insertions(+), 29 deletions(-) diff --git a/pc-mate/src/intent.rs b/pc-mate/src/intent.rs index 864a031156..07731bb7dc 100644 --- a/pc-mate/src/intent.rs +++ b/pc-mate/src/intent.rs @@ -124,6 +124,8 @@ pub fn compose_triage_prompt(context: TriageContext<'_>) -> String { String::new(), "Print exactly one JSON object and nothing else:".to_string(), String::new(), + "- Write the text of a value without double quotes inside it; a quote inside the text breaks the object.".to_string(), + String::new(), "```json".to_string(), "{".to_string(), " \"category\": \"bug_report\" | \"feature_request\" | \"question\" | \"other\",".to_string(), @@ -149,20 +151,131 @@ pub fn compose_triage_prompt(context: TriageContext<'_>) -> String { lines.join("\n") } -pub fn extract_json_object(text: &str) -> Result<&str> { - if let Some(start) = text.find("```") { - let after = &text[start + 3..]; - let after = after.strip_prefix("json").unwrap_or(after); - let after = after.strip_prefix('\n').unwrap_or(after); - if let Some(end) = after.find("```") { - if let Some(candidate) = balanced_object(after[..end].trim()) { - if serde_json::from_str::(candidate).is_ok() { - return Ok(candidate); +/// The JSON object a model printed. +/// +/// A verdict carries long free text, and a model that quotes a word inside that text leaves the +/// quote unescaped. The strict read then fails and the whole verdict is lost, so the reader also +/// repairs the common malformations before it gives up. +pub fn extract_json_value(text: &str) -> Result { + let mut strict_error = None; + for candidate in json_candidates(text) { + match serde_json::from_str::(candidate) { + Ok(value) => return Ok(value), + Err(error) => strict_error = Some(error), + } + } + if let Some(repaired) = repair_json_object(text) { + if let Ok(value) = serde_json::from_str::(&repaired) { + return Ok(value); + } + } + match strict_error { + // The output itself is not in the message: the reason is kept in the record, and the + // output belongs in the log. + Some(error) => Err(anyhow!("the model output is not a JSON object: {error}")), + None => Err(anyhow!("the model output did not contain a JSON object")), + } +} + +/// The JSON objects the text may hold, in the order they are worth reading. +fn json_candidates(text: &str) -> Vec<&str> { + let mut candidates = Vec::new(); + if let Some(block) = fenced_block(text) { + if let Some(candidate) = balanced_object(block) { + candidates.push(candidate); + } + } + if let Some(candidate) = balanced_object(text) { + candidates.push(candidate); + } + candidates +} + +/// The content of the first fenced block. +fn fenced_block(text: &str) -> Option<&str> { + let start = text.find("```")?; + let after = &text[start + 3..]; + let after = after.strip_prefix("json").unwrap_or(after); + let after = after.strip_prefix('\n').unwrap_or(after); + let end = after.find("```")?; + Some(after[..end].trim()) +} + +/// Rebuild the JSON object in the text, repairing what a model most often prints wrongly. +/// +/// A quote inside a value's text is escaped, a raw control character is written as its escape, +/// and a comma before a closing bracket is dropped. The object ends where its braces balance. +fn repair_json_object(text: &str) -> Option { + let region = fenced_block(text).unwrap_or(text); + let chars: Vec = region.chars().collect(); + let start = chars.iter().position(|ch| *ch == '{')?; + let mut out = String::new(); + let mut depth = 0i32; + let mut in_string = false; + let mut escaped = false; + let mut index = start; + while index < chars.len() { + let ch = chars[index]; + if in_string { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == '"' { + // A value ends where the JSON continues; a quote inside the text does not. + let mut next = index + 1; + while next < chars.len() && chars[next].is_whitespace() { + next += 1; + } + match chars.get(next) { + None | Some(',') | Some('}') | Some(']') | Some(':') => in_string = false, + Some(_) => { + out.push('\\'); + } + } + } else if (ch as u32) < 0x20 { + match ch { + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + _ => out.push_str(&format!("\\u{:04x}", ch as u32)), } + index += 1; + continue; } + out.push(ch); + index += 1; + continue; + } + match ch { + '"' => in_string = true, + '{' => depth += 1, + '}' => { + depth -= 1; + out.push(ch); + index += 1; + if depth == 0 { + return Some(out); + } + continue; + } + ',' => { + // A comma before a closing bracket is a leftover, not a separator. + let mut next = index + 1; + while next < chars.len() && chars[next].is_whitespace() { + next += 1; + } + if matches!(chars.get(next), Some('}') | Some(']')) { + index += 1; + continue; + } + } + _ => {} } + out.push(ch); + index += 1; } - balanced_object(text).ok_or_else(|| anyhow!("triage response did not contain a JSON object")) + None } fn balanced_object(text: &str) -> Option<&str> { @@ -199,8 +312,8 @@ fn balanced_object(text: &str) -> Option<&str> { } pub fn parse_triage_verdict(text: &str, max_reply_chars: usize) -> Result { - let json = extract_json_object(text)?; - let mut verdict: IntentVerdict = serde_json::from_str(json)?; + let value = extract_json_value(text)?; + let mut verdict: IntentVerdict = serde_json::from_value(value)?; verdict.confidence = verdict.confidence.clamp(0.0, 1.0); if matches!(verdict.category, IntentCategory::Other) { @@ -300,10 +413,40 @@ mod tests { #[test] fn extracts_fenced_json() { let text = "Here it is:\n```json\n{\"category\":\"other\",\"decision\":\"ignore\"}\n```\n"; - assert_eq!( - extract_json_object(text).unwrap(), - "{\"category\":\"other\",\"decision\":\"ignore\"}" - ); + let value = extract_json_value(text).unwrap(); + assert_eq!(value["category"], "other"); + assert_eq!(value["decision"], "ignore"); + } + + #[test] + fn a_quote_inside_a_value_is_read_rather_than_lost() { + // The model quoted a word inside the analysis and left the quote unescaped. + let text = r#"```json +{ + "category": "question", + "decision": "answer", + "analysis": "README.md names the release as "Fewer tokens" and gives the count.", + "reply": "It cuts token use." +} +```"#; + let parsed = parse_triage_verdict(text, 4000).unwrap(); + assert_eq!(parsed.category, IntentCategory::Question); + assert_eq!(parsed.decision, IntentDecision::Answer); + assert!(parsed.analysis.contains("Fewer tokens")); + } + + #[test] + fn a_leftover_comma_is_dropped() { + let text = r#"{"category":"question","decision":"answer","labels":["question",],}"#; + let parsed = parse_triage_verdict(text, 4000).unwrap(); + assert_eq!(parsed.decision, IntentDecision::Answer); + } + + #[test] + fn an_unreadable_output_is_reported_without_its_content() { + let error = extract_json_value("there is no object here").unwrap_err(); + assert!(error.to_string().contains("JSON object")); + assert!(!error.to_string().contains("there is no object here")); } #[test] diff --git a/pc-mate/src/run_result.rs b/pc-mate/src/run_result.rs index 705383a2ea..21c40de152 100644 --- a/pc-mate/src/run_result.rs +++ b/pc-mate/src/run_result.rs @@ -135,18 +135,10 @@ pub fn parse(text: &str) -> anyhow::Result { if trimmed.is_empty() { anyhow::bail!("the outcome file is empty"); } - let value: serde_json::Value = match serde_json::from_str(trimmed) { - Ok(value) => value, - // A run that answered inside a fenced block still wrote its outcome; the block is read - // the same way the triage reads a fenced verdict. - Err(first) => { - let block = crate::intent::extract_json_object(trimmed) - .map_err(|_| anyhow::anyhow!("the outcome file is not a JSON object: {first}"))?; - serde_json::from_str(block).map_err(|error| { - anyhow::anyhow!("the outcome file is not a JSON object: {error}") - })? - } - }; + // A run that answered inside a fenced block still wrote its outcome; the block is read the + // same way the triage reads a fenced verdict. + let value = crate::intent::extract_json_value(trimmed) + .map_err(|error| anyhow::anyhow!("the outcome file is not a JSON object: {error}"))?; let outcome: ReviewResult = serde_json::from_value(value) .map_err(|error| anyhow::anyhow!("the outcome file does not match the schema: {error}"))?; Ok(outcome) @@ -191,6 +183,14 @@ mod tests { assert_eq!(outcome.summary, "Done."); } + #[test] + fn an_outcome_that_quotes_a_word_inside_its_text_is_still_read() { + let outcome = + parse(r#"{"summary":"Fixed the "quoted" check.","state":"ready","changedFiles":[]}"#) + .unwrap(); + assert_eq!(outcome.summary, "Fixed the \"quoted\" check."); + } + #[test] fn a_file_that_is_not_an_outcome_is_refused() { assert!(parse("not json at all").is_err()); diff --git a/pc-mate/src/supervisor/mod.rs b/pc-mate/src/supervisor/mod.rs index 2f72e3aa1f..bdf6b1f7c0 100644 --- a/pc-mate/src/supervisor/mod.rs +++ b/pc-mate/src/supervisor/mod.rs @@ -401,7 +401,19 @@ impl Supervisor { .run(run, &self.settings.agent) .await .context("run the triage")?; - parse_triage_verdict(result.text(), self.settings.triage.max_reply_chars) + let text = result.text(); + match parse_triage_verdict(text, self.settings.triage.max_reply_chars) { + Ok(verdict) => Ok(verdict), + Err(error) => { + // The output is written to the log and kept out of the record: the record holds + // the reason, and the output is the model's own text. + let _ = self.state.append_main_log(&format!( + "the triage output could not be read: {error:#}; output: {}", + truncate_chars(text.trim(), 2000) + )); + Err(error) + } + } } /// The evidence the public Scope holds for this message. From 9370ce1aaeda2109b06faaebb53835d1bc891526 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 16:25:55 +0800 Subject: [PATCH 02/12] docs(pc-mate): explain who may start work and what an empty list means The allowed list is read in two places with different effects: a channel drops what comes from outside it, and the authority gate turns the people on it into explicit requests. An empty list therefore takes every message in and leaves the list of explicit requesters empty, so every request is inferred, and an inferred request is accepted in triage.mode auto alone. In response mode the message is read, assessed and dropped without an answer, which is why a reply mode that serves a group needs the people it serves on the list. The maintainers list answers a different question and is described next to it. --- pc-mate/README.md | 20 ++++++++++++++++++++ pc-mate/settings.example.yaml | 13 +++++++++++++ 2 files changed, 33 insertions(+) diff --git a/pc-mate/README.md b/pc-mate/README.md index 8d99641d79..9e27365a01 100644 --- a/pc-mate/README.md +++ b/pc-mate/README.md @@ -437,6 +437,10 @@ See `settings.example.yaml`. The important switches are: - `triage.autoLabel`: kept so an existing settings file still loads. The supervisor no longer queues a label, so this switch no longer has an effect. - `github.writeMode`: `off` for M1; `approved` for M2. +- `github.allowed`: the GitHub logins whose reports are taken in. An empty list takes every + issue in; a non-empty one drops everything that comes from outside it. +- `feishu.allowed`: the Feishu `open_id` values whose messages are taken in, and whose + request is an explicit one. - `github.maintainers`: GitHub logins allowed to resolve a case. - `feishu.maintainers`: Feishu `open_id` values allowed to resolve or approve. - `feishu.botName`: the bot display name, for example `ClawBot`. Some event @@ -473,6 +477,22 @@ See `settings.example.yaml`. The important switches are: `supervisor.batchWindowSeconds` (45 by default) is the quiet period before one thread's queued messages are assessed together. +### Who may start work + +`allowed` and `maintainers` answer different questions. `allowed` says whose +message may start work: a message from someone outside the list is dropped +before it is read, and a message from someone inside it carries an explicit +request. `maintainers` says who may resolve a case or approve a public write, +so a maintainer may approve a write they did not ask for. + +The list is empty by default, and an empty list is not the same as an open +door. An empty list takes every message in, but it also leaves the list of +people with an explicit request empty, so every request is only inferred. An +inferred request is accepted in `triage.mode: auto` alone: in `response` mode +it is read, assessed, and then dropped without an answer. A reply mode that +serves a group therefore needs the people it serves on `allowed`, or it answers +nobody. + `pc-mate worktree list` shows every case worktree, and `pc-mate worktree remove ` removes one after saving whatever only it holds. The local branch survives unless `--delete-branch` is given. diff --git a/pc-mate/settings.example.yaml b/pc-mate/settings.example.yaml index c70b928d24..e68d4a9b42 100644 --- a/pc-mate/settings.example.yaml +++ b/pc-mate/settings.example.yaml @@ -67,6 +67,10 @@ github: enabled: true repository: owner/name pollSeconds: 60 + # Whose reports are taken in. An empty list takes every issue in; a non-empty + # one drops everything that comes from outside it. Whoever is on the list + # also has an explicit request, and an explicit request is accepted in every + # triage mode. See the note under `feishu.allowed` for the whole rule. allowed: [] ignoreLabels: [wontfix, duplicate, invalid] baselineOnFirstRun: true @@ -92,7 +96,16 @@ feishu: appId: "" botName: "" # bot display name; used only when the event source drops `mentions`, # and only for an exact `@` mention + # Whose messages are taken in, and whose request is an explicit one. A + # message from someone outside this list is dropped before it is read. An + # empty list takes every message in, but then every request is only inferred, + # and an inferred request is accepted in `triage.mode: auto` alone: in + # `response` mode it is read and then dropped without an answer. A reply + # mode that serves a group therefore needs the people it serves listed here. allowed: [] + # Who may resolve a case or approve a public write. This is a different + # question from `allowed`: a maintainer may approve a write they did not ask + # for, while their own message stays inferred unless they are also allowed. maintainers: [] # Feishu open_id values allowed to resolve or approve # M2 uses this private chat for approval requests. It carries the exact write text and the # approval token, so it must not be a public community group. Commands in this chat are accepted From e7280defd4190d360818790e55c8acb777106b57 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 18:03:29 +0800 Subject: [PATCH 03/12] fix(pc-mate): name the response mode the way the configuration spells it --- pc-mate/src/domain.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/pc-mate/src/domain.rs b/pc-mate/src/domain.rs index 30d7ef0138..a8412d8dfb 100644 --- a/pc-mate/src/domain.rs +++ b/pc-mate/src/domain.rs @@ -451,10 +451,16 @@ pub enum IntentMode { } impl IntentMode { + /// The name the configuration reads and the records write. + /// + /// The name is the mode's own spelling in every place: the configuration reads + /// `response`, the triage record writes `response`, and the authority gate labels a policy + /// `response`. A second spelling here would drift from the configuration without anything + /// failing, so the test below holds the three together. pub fn as_str(self) -> &'static str { match self { Self::Observe => "observe", - Self::Response => "reply", + Self::Response => "response", Self::Auto => "auto", } } @@ -575,6 +581,19 @@ pub struct WorkItemSummary { mod tests { use super::*; + #[test] + fn the_mode_is_spelled_the_same_way_in_the_configuration_and_in_the_records() { + for mode in [IntentMode::Observe, IntentMode::Response, IntentMode::Auto] { + let spelled = mode.as_str(); + // The configuration reads the mode by this name. + let parsed: IntentMode = serde_yaml::from_str(spelled).expect("the mode is read back"); + assert_eq!(parsed, mode); + // The records write it by the same name. + let written = serde_json::to_string(&mode).expect("the mode is written"); + assert_eq!(written, format!("\"{spelled}\"")); + } + } + fn verdict(confidence: f64, evidence: Evidence) -> IntentVerdict { IntentVerdict { category: IntentCategory::BugReport, From 0dfd903c79e93a975385c87d7b50ecca4db25a36 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 18:03:29 +0800 Subject: [PATCH 04/12] fix(pc-mate): keep an identifier intact in a Feishu reply --- pc-mate/src/channels/feishu.rs | 155 ++++++++++++++++++++++++++++++++- pc-mate/src/intent.rs | 1 + 2 files changed, 155 insertions(+), 1 deletion(-) diff --git a/pc-mate/src/channels/feishu.rs b/pc-mate/src/channels/feishu.rs index 0a6775c1eb..fd5d3c1fcf 100644 --- a/pc-mate/src/channels/feishu.rs +++ b/pc-mate/src/channels/feishu.rs @@ -265,7 +265,7 @@ fn reply_args(direct: bool, _actor: &str, message_id: &str, _key: &str) -> Vec String { let content = serde_json::json!({ - "zh_cn": {"content": [[{"tag": "md", "text": text}]]} + "zh_cn": {"content": [[{"tag": "md", "text": protect_identifiers(text)}]]} }) .to_string(); let mut body = serde_json::json!({ @@ -281,6 +281,99 @@ fn reply_body(direct: bool, actor: &str, text: &str, key: &str) -> String { body.to_string() } +/// Write an identifier that contains an underscore as a code span. +/// +/// Feishu renders the markdown of a `post` message itself, and its renderer reads an underscore +/// inside a word as the start of an emphasis: `scope_id` arrives as "scope_" followed by "id", +/// with the underscore gone. A code span is the one form that renderer keeps literal, so the +/// identifier is written as one. +/// +/// Only an underscore between two word characters is treated as part of an identifier. An +/// underscore at the edge of a word is markdown emphasis, which the model may have meant, and +/// text that is already code, a fenced block, a link label or part of a URL is left as it is. +fn protect_identifiers(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut index = 0; + while index < chars.len() { + // Code is copied as it is: a fenced block and a code span both hold the text verbatim. + if chars[index] == '`' { + let fence = chars[index..].iter().take_while(|ch| **ch == '`').count(); + let mut scan = index + fence; + let mut end = chars.len(); + while scan < chars.len() { + if chars[scan] == '`' { + let run = chars[scan..].iter().take_while(|ch| **ch == '`').count(); + if run >= fence { + end = scan + fence; + break; + } + scan += run; + continue; + } + scan += 1; + } + out.extend(&chars[index..end]); + index = end; + continue; + } + if chars[index].is_alphanumeric() || chars[index] == '_' { + let start = index; + while index < chars.len() && is_identifier_char(chars[index]) { + index += 1; + } + // A trailing dot or dash belongs to the sentence, not to the identifier. + let mut core_end = index; + while core_end > start && (chars[core_end - 1] == '.' || chars[core_end - 1] == '-') { + core_end -= 1; + } + let core: String = chars[start..core_end].iter().collect(); + let suffix: String = chars[core_end..index].iter().collect(); + if has_intraword_underscore(&core) && !in_a_url(&out) && !is_link_label(&chars, index) { + out.push('`'); + out.push_str(&core); + out.push('`'); + } else { + out.push_str(&core); + } + out.push_str(&suffix); + continue; + } + out.push(chars[index]); + index += 1; + } + out +} + +/// Whether a character can be part of an identifier. +fn is_identifier_char(ch: char) -> bool { + ch.is_alphanumeric() || ch == '_' || ch == '.' || ch == '-' +} + +/// Whether the identifier carries an underscore between two word characters. +fn has_intraword_underscore(core: &str) -> bool { + let chars: Vec = core.chars().collect(); + chars.iter().enumerate().any(|(index, ch)| { + *ch == '_' + && index > 0 + && index + 1 < chars.len() + && chars[index - 1].is_alphanumeric() + && chars[index + 1].is_alphanumeric() + }) +} + +/// Whether the text written so far ends inside a URL. +fn in_a_url(out: &str) -> bool { + out.rsplit(|ch: char| ch.is_whitespace()) + .next() + .is_some_and(|token| token.contains("://")) +} + +/// Whether the identifier is the label of a link, which the markdown owns. +fn is_link_label(chars: &[char], index: usize) -> bool { + chars.get(index) == Some(&']') && chars.get(index + 1) == Some(&'(') +} + fn chat_args(_chat_id: &str) -> Vec { vec![ "api".into(), @@ -935,4 +1028,64 @@ mod tests { assert_eq!(parsed["msg_type"], "post"); assert!(parsed["reply_in_thread"].is_null()); } + + #[test] + fn an_identifier_with_an_underscore_is_written_as_code() { + assert_eq!( + protect_identifiers("every operation carries a scope_id"), + "every operation carries a `scope_id`" + ); + assert_eq!( + protect_identifiers("the reference is ARTIFACT_ID@REVISION"), + "the reference is `ARTIFACT_ID`@REVISION" + ); + assert_eq!( + protect_identifiers("see README_CN.md for the Chinese page."), + "see `README_CN.md` for the Chinese page." + ); + } + + #[test] + fn an_underscore_that_may_be_emphasis_is_left_alone() { + assert_eq!( + protect_identifiers("this is _emphasis_"), + "this is _emphasis_" + ); + assert_eq!( + protect_identifiers("this is __emphasis__"), + "this is __emphasis__" + ); + assert_eq!( + protect_identifiers("this is **strong**"), + "this is **strong**" + ); + } + + #[test] + fn code_a_link_and_a_url_are_left_alone() { + assert_eq!( + protect_identifiers("the field `scope_id` is already code"), + "the field `scope_id` is already code" + ); + assert_eq!( + protect_identifiers("```\nscope_id = 1\n```"), + "```\nscope_id = 1\n```" + ); + assert_eq!( + protect_identifiers("[scope_id](https://example.com)"), + "[scope_id](https://example.com)" + ); + assert_eq!( + protect_identifiers("https://example.com/a_b"), + "https://example.com/a_b" + ); + } + + #[test] + fn the_reply_carries_the_protected_identifier() { + let body = reply_body(false, "ou_alice", "use scope_id", "key"); + let parsed: serde_json::Value = serde_json::from_str(&body).unwrap(); + let content = parsed["content"].as_str().unwrap(); + assert!(content.contains("`scope_id`"), "content was {content}"); + } } diff --git a/pc-mate/src/intent.rs b/pc-mate/src/intent.rs index 07731bb7dc..26bad1b671 100644 --- a/pc-mate/src/intent.rs +++ b/pc-mate/src/intent.rs @@ -125,6 +125,7 @@ pub fn compose_triage_prompt(context: TriageContext<'_>) -> String { "Print exactly one JSON object and nothing else:".to_string(), String::new(), "- Write the text of a value without double quotes inside it; a quote inside the text breaks the object.".to_string(), + "- Write an identifier that contains an underscore inside backticks, so the chat shows it as written.".to_string(), String::new(), "```json".to_string(), "{".to_string(), From 2318caca7625b0b1b4497669c883b2d3c785cfe8 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 18:52:27 +0800 Subject: [PATCH 05/12] fix(pc-mate): answer the person with the whole read-stage text --- pc-mate/src/kernel/delegations.rs | 5 ++ pc-mate/src/kernel/tests.rs | 2 + pc-mate/src/supervisor/mod.rs | 104 +++++++++++++++++++++++++++++- 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/pc-mate/src/kernel/delegations.rs b/pc-mate/src/kernel/delegations.rs index d7e564023c..8a2d9cb7ad 100644 --- a/pc-mate/src/kernel/delegations.rs +++ b/pc-mate/src/kernel/delegations.rs @@ -34,6 +34,10 @@ const RECOVERY_NOTE: &str = "The host restarted during this work_item. Inspect t pub struct DelegationReport { pub state: RunState, pub summary: String, + /// The answer as the person receives it: the whole text, bounded. The summary is what the + /// record keeps, and a summary alone drops the evidence that follows the opening sentence. + /// `None` falls back to the summary. + pub reply_text: Option, /// An open question for a person. `None` keeps the current one, and an /// empty question clears it. pub question: Option, @@ -48,6 +52,7 @@ impl Default for DelegationReport { Self { state: RunState::Ready, summary: String::new(), + reply_text: None, question: None, asked_by: None, answers: None, diff --git a/pc-mate/src/kernel/tests.rs b/pc-mate/src/kernel/tests.rs index 97681f2d03..4f77a923bb 100644 --- a/pc-mate/src/kernel/tests.rs +++ b/pc-mate/src/kernel/tests.rs @@ -657,6 +657,7 @@ fn a_question_waits_for_a_person_and_their_answer_resumes_the_work_item() { &DelegationReport { state: RunState::Progress, summary: "I need to know which config file is used.".to_string(), + reply_text: None, question: Some("Which config file does the service read?".to_string()), asked_by: Some("feishu:om_1".to_string()), answers: None, @@ -700,6 +701,7 @@ fn a_question_waits_for_a_person_and_their_answer_resumes_the_work_item() { &DelegationReport { state: RunState::Ready, summary: "Fixed the config guard.".to_string(), + reply_text: None, question: None, asked_by: None, answers: Some("feishu:om_2".to_string()), diff --git a/pc-mate/src/supervisor/mod.rs b/pc-mate/src/supervisor/mod.rs index bdf6b1f7c0..0a857f3967 100644 --- a/pc-mate/src/supervisor/mod.rs +++ b/pc-mate/src/supervisor/mod.rs @@ -735,6 +735,15 @@ impl Supervisor { } else { "The analysis could not be completed.".to_string() }, + // The person gets the whole analysis: the evidence that follows the opening + // sentence is the answer, and the summary alone keeps only that sentence. + reply_text: if result.ok { + let answer = + truncate_chars(text.trim(), self.settings.triage.max_reply_chars); + (!answer.is_empty()).then_some(answer) + } else { + None + }, question: None, asked_by: None, // The answer to an open question is this stage's own answer. @@ -755,6 +764,7 @@ impl Supervisor { DelegationReport { state: RunState::Failed, summary: "The analysis could not be completed.".to_string(), + reply_text: None, question: None, asked_by: None, answers: None, @@ -786,6 +796,7 @@ impl Supervisor { DelegationReport { state: RunState::Failed, summary: "The implementation stage could not start.".to_string(), + reply_text: None, question: None, asked_by: None, answers: None, @@ -1037,6 +1048,7 @@ impl Supervisor { ) -> Result<()> { let question = report.question.clone(); let summary = report.summary.clone(); + let reply_text = report.reply_text.clone(); let state = report.state; let work_item_id = work_item.id.clone(); { @@ -1069,7 +1081,8 @@ impl Supervisor { work_item_id: Some(work_item_id), trigger_id: None, question: None, - text: summary, + // The whole answer reaches the person; the summary is what the record keeps. + text: reply_text.unwrap_or(summary), }; let mut pipeline = self.pipeline(); let _ = pipeline.reply(&request); @@ -1407,6 +1420,7 @@ fn report_of(outcome: &ReviewResult, answers: Option) -> DelegationRepor } else { outcome.summary.clone() }, + reply_text: None, question: outcome.question.clone(), asked_by: None, answers, @@ -1511,6 +1525,50 @@ mod tests { .unwrap_or(false) } + /// A runner whose read stage answers with an opening sentence and the evidence below it. + struct AnsweringRunner { + calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl AgentRunner for AnsweringRunner { + fn name(&self) -> &'static str { + "answering" + } + + async fn available(&self) -> bool { + true + } + + async fn run( + &self, + run: crate::agent_cli::AgentRun, + _agent: &crate::config::AgentConfig, + ) -> anyhow::Result { + match self.calls.fetch_add(1, Ordering::SeqCst) { + 0 => Ok(AgentResult { + ok: true, + exit_code: Some(0), + final_text: TRIAGE_VERDICT.to_string(), + ..AgentResult::default() + }), + _ if run.read_only => Ok(AgentResult { + ok: true, + exit_code: Some(0), + final_text: "最新已发布版本是 v1.6.1。\n\n- 发布于 2026-12-01\n- 来源:仓库自身的发布记录" + .to_string(), + ..AgentResult::default() + }), + _ => Ok(AgentResult { + ok: true, + exit_code: Some(0), + final_text: String::new(), + ..AgentResult::default() + }), + } + } + } + /// A runner that asks a question in the implementation stage and finishes once it is answered. struct QuestioningRunner { calls: AtomicUsize, @@ -1809,6 +1867,50 @@ mod tests { ); } + #[tokio::test] + async fn the_read_stage_answers_with_the_evidence_below_the_opening_sentence() { + if !git_available() { + return; + } + let (temp, repo, _remote) = seed_repository(); + let mut settings = settings_for(&repo, &temp.path().join("state")); + settings.operator.enabled = false; + let supervisor = supervisor_with_runner( + settings, + Arc::new(AnsweringRunner { + calls: AtomicUsize::new(0), + }), + ); + + supervisor + .receive(bug_trigger()) + .expect("the message is taken in"); + supervisor.tick().await.expect("the round runs"); + settle(&supervisor).await; + + let pending = supervisor.pending_replies(); + let answer = pending + .iter() + .find(|message| message.text.contains("最新已发布版本")) + .unwrap_or_else(|| panic!("the person is answered: {pending:?}")); + assert!( + answer.text.contains("来源:仓库自身的发布记录"), + "the evidence below the opening sentence reaches the person: {answer:?}" + ); + + // The record keeps the summary: the opening sentence alone. + let work_item_id = answer + .work_item_id + .clone() + .unwrap_or_else(|| panic!("the answer names its work_item: {answer:?}")); + let work_item = supervisor.work_item(&work_item_id).expect("the work_item"); + let summary = work_item + .latest_report() + .map(|report| report.summary.clone()) + .unwrap_or_default(); + assert_eq!(summary, "最新已发布版本是 v1.6.1。"); + } + #[tokio::test] async fn a_question_waits_for_the_answer_and_the_work_continues() { if !git_available() { From 289e8fee6ce301e3273acd71958fede41f79ad9e Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 20:27:51 +0800 Subject: [PATCH 06/12] fix(pc-mate): carry out explicit work and keep one group conversation per person - response mode: an explicit request (a listed person who named the agent) starts work, as the authority rule already promised; an inferred one still starts work only in auto mode. - Feishu: a group conversation is the person talking in the chat, so consecutive messages are one assessment and the answer to a question reaches the work that asked it. - the triage prompt is told what the installation does with its ruling, so a reply no longer promises work that will not happen. --- pc-mate/README.md | 36 +++--- pc-mate/settings.example.yaml | 9 +- pc-mate/src/case.rs | 34 ++++-- pc-mate/src/domain.rs | 16 +++ pc-mate/src/intent.rs | 54 ++++++++- pc-mate/src/kernel/entities.rs | 17 ++- pc-mate/src/kernel/tests.rs | 45 ++----- pc-mate/src/supervisor/mod.rs | 216 +++++++++++++++++++++++++++++++-- 8 files changed, 352 insertions(+), 75 deletions(-) diff --git a/pc-mate/README.md b/pc-mate/README.md index 9e27365a01..2c6c0103ef 100644 --- a/pc-mate/README.md +++ b/pc-mate/README.md @@ -2,9 +2,9 @@ An always-on maintainer agent for a GitHub repository and Feishu conversations. It runs a supervisor over an agent: the supervisor takes messages in, waits -for a thread to go quiet, assesses the burst, and hands accepted work to an -agent that works inside its own Git worktree. The agent's report comes back -as a reply in the conversation it came from. A GitHub issue or comment is +for a conversation to go quiet, assesses the burst, and hands accepted work to +an agent that works inside its own Git worktree. The agent's report comes +back as a reply in the conversation it came from. A GitHub issue or comment is still written only after a configured maintainer approves the exact text. This is an independent Rust sub-program at the repository root. It does not @@ -76,9 +76,12 @@ fresh installation responses to nothing and writes nothing. 2. Skip self/bot messages, disallowed chats, ignored labels, and seen events. 3. Take the message in. The supervisor stores it once and queues it for its thread. A message is never answered twice. -4. Wait for the thread to go quiet. Consecutive messages about one problem are - one problem, so they are assessed together after - `supervisor.batchWindowSeconds` of quiet (45 seconds by default). +4. Wait for the conversation to go quiet. Consecutive messages about one + problem are one problem, so they are assessed together after + `supervisor.batchWindowSeconds` of quiet (45 seconds by default). On GitHub + the conversation is the issue; on Feishu it is the person talking in the + chat, so their follow-up messages — and the answer to a question the bot + asked them — belong to the same one. 5. Assess the burst. The first step is still pc-mate's own four-way intent analysis — `bug_report`, `feature_request`, `question`, or `other` — run read-only in the checkout with `AGENTS.md`, repository docs, PowerContext @@ -114,8 +117,8 @@ fresh installation responses to nothing and writes nothing. that finds nothing new produces no second history and its next push is a fast-forward. 13. Advance the case the message belongs to (`open → investigating → - waiting_reporter → resolved`). A case is keyed by the thread, so a follow-up - continues it instead of opening a second one. + waiting_reporter → resolved`). A case is keyed by the conversation, so a + follow-up continues it instead of opening a second one. 14. On GitHub, a reply or filing becomes a pending action at the current case version. The maintainer chat receives the exact bounded text and a plain `确认写入 ` line. @@ -321,7 +324,7 @@ Three things are pc-mate's own and stay that way: local keynotes file is only the offline fallback. - **Sources and approvals** stay on pc-mate's contract: GitHub writes are pending actions confirmed in `feishu.approvalChat`, and every message is - keyed by its thread and case. + keyed by its conversation and case. The **agent runs in a Git worktree**, so the code it changes is never the shared checkout's. The worktree is the sandbox boundary. @@ -333,8 +336,10 @@ The authority decides what a work item may do: person, a report from anyone, a message from an unlisted person when `triage.allowCommunity` is on. -An explicit authority may write; an inferred one may only implement when -`triage.mode: auto` is on, and may only answer otherwise. +An explicit authority may write in every mode but `observe`: the reply mode +carries out the request of a listed person who named the agent. An inferred +one may only implement when `triage.mode: auto` is on, and may only answer +otherwise. ## State layout @@ -475,7 +480,7 @@ See `settings.example.yaml`. The important switches are: a fast-forward. - `supervisor.enabled`: when false nothing is assessed on its own. `supervisor.batchWindowSeconds` (45 by default) is the quiet period before - one thread's queued messages are assessed together. + one conversation's queued messages are assessed together. ### Who may start work @@ -489,9 +494,10 @@ The list is empty by default, and an empty list is not the same as an open door. An empty list takes every message in, but it also leaves the list of people with an explicit request empty, so every request is only inferred. An inferred request is accepted in `triage.mode: auto` alone: in `response` mode -it is read, assessed, and then dropped without an answer. A reply mode that -serves a group therefore needs the people it serves on `allowed`, or it answers -nobody. +it is read, assessed, answered in the conversation, and no branch is created +for it. A request that named the agent is carried out in every mode but +`observe`. A reply mode that serves a group therefore needs the people it +serves on `allowed`, or it answers nobody. `pc-mate worktree list` shows every case worktree, and `pc-mate worktree remove ` removes one after saving whatever only it diff --git a/pc-mate/settings.example.yaml b/pc-mate/settings.example.yaml index e68d4a9b42..e619cdfa9a 100644 --- a/pc-mate/settings.example.yaml +++ b/pc-mate/settings.example.yaml @@ -100,8 +100,10 @@ feishu: # message from someone outside this list is dropped before it is read. An # empty list takes every message in, but then every request is only inferred, # and an inferred request is accepted in `triage.mode: auto` alone: in - # `response` mode it is read and then dropped without an answer. A reply - # mode that serves a group therefore needs the people it serves listed here. + # `response` mode it is read, answered in the conversation, and no branch is + # created for it. A request that named the bot is carried out in every mode + # but `observe`. A reply mode that serves a group therefore needs the people + # it serves listed here. allowed: [] # Who may resolve a case or approve a public write. This is a different # question from `allowed`: a maintainer may approve a write they did not ask @@ -155,7 +157,8 @@ proposal: # The code-execution stage. An accepted bug/feature runs the agent with write access inside its own # Git worktree under `stateDir/work/`; the shared checkout stays read-only. The controller -# commits the result. Only `triage.mode: auto` reaches this stage. +# commits the result. This stage is reached by a request that named the agent, and by an inferred +# request in `triage.mode: auto`. operator: enabled: true branchPrefix: pc-mate/ diff --git a/pc-mate/src/case.rs b/pc-mate/src/case.rs index 96cd0ff50c..ff2eca237f 100644 --- a/pc-mate/src/case.rs +++ b/pc-mate/src/case.rs @@ -37,8 +37,9 @@ use crate::util::strip_leading_mention; /// The identity of the conversation a case follows. /// -/// Keyed by the thread, not by the message: consecutive messages about the same problem must land on -/// the same case, or a reporter's confirmation would open a second one instead of resolving the first. +/// Keyed by the conversation, not by the message: consecutive messages about the same problem must +/// land on the same case, or a reporter's confirmation would open a second one instead of +/// resolving the first. pub fn case_key(channel: &Channel) -> String { match channel.source { Source::Github => format!( @@ -46,10 +47,16 @@ pub fn case_key(channel: &Channel) -> String { channel.repository.as_deref().unwrap_or("unknown"), channel.number.unwrap_or_default() ), - // A group chat holds unrelated problems, so the thread root — not the chat — identifies the - // case. A direct message has no thread, and there the chat is the conversation. + // A group chat holds unrelated problems, so the person talking in it — not the chat — + // identifies the case. A direct message has no other party, and there the chat is the + // conversation. Source::Feishu => { let conversation = channel.chat_id.as_deref().unwrap_or("unknown"); + // The source says who the conversation is; a thread root only says where a reply was + // written. + if let Some(id) = channel.conversation_id.as_deref() { + return format!("feishu:{id}"); + } let thread = channel .thread_id .as_deref() @@ -666,17 +673,22 @@ mod tests { } #[test] - fn a_case_is_keyed_by_the_thread_nothing_else() { - // Two messages in one group thread must resolve to one case, or a reporter's confirmation - // would open a second case instead of resolving the first. - let group = Channel::feishu("oc_1", "om_7", false); - assert_eq!(case_key(&group), "feishu:oc_1#om_7"); - // A reply has its own message id, but the thread root still identifies the case. + fn a_case_is_keyed_by_the_conversation_nothing_else() { + // Two messages of one person must resolve to one case, or a reporter's confirmation would + // open a second case instead of resolving the first. + let group = Channel { + conversation_id: Some("oc_1#alice".to_string()), + ..Channel::feishu("oc_1", "om_7", false) + }; + assert_eq!(case_key(&group), "feishu:oc_1#alice"); + // A reply has its own message id, but the conversation of the person still identifies the + // case. let reply = Channel { + conversation_id: Some("oc_1#alice".to_string()), thread_id: Some("om_7".to_string()), ..Channel::feishu("oc_1", "om_9", false) }; - assert_eq!(case_key(&reply), "feishu:oc_1#om_7"); + assert_eq!(case_key(&reply), "feishu:oc_1#alice"); // A direct message has no thread, so the chat is the conversation. let direct = Channel::feishu("oc_2", "om_8", true); assert_eq!(case_key(&direct), "feishu:oc_2"); diff --git a/pc-mate/src/domain.rs b/pc-mate/src/domain.rs index a8412d8dfb..335db129a5 100644 --- a/pc-mate/src/domain.rs +++ b/pc-mate/src/domain.rs @@ -49,6 +49,14 @@ pub struct Channel { /// deduplication, while the case follows the root so a resolution finds the original report. #[serde(default, skip_serializing_if = "Option::is_none")] pub thread_id: Option, + /// The conversation a message belongs to when the source keys it by the person rather than by + /// a thread. + /// + /// A Feishu group has no thread of its own, so the conversation is the person talking in that + /// chat: the messages that continue a request and the answer to a question the bot asked + /// belong to the same one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, #[serde(default)] pub direct: bool, } @@ -62,6 +70,7 @@ impl Channel { chat_id: None, message_id: None, thread_id: None, + conversation_id: None, direct: false, } } @@ -74,6 +83,7 @@ impl Channel { chat_id: Some(chat_id.into()), message_id: Some(message_id.into()), thread_id: None, + conversation_id: None, direct, } } @@ -204,6 +214,12 @@ impl InboundEvent { ) -> Self { let mut channel = Channel::feishu(chat_id, message_id, direct); channel.thread_id = root_id.clone().filter(|root| !root.is_empty() && !direct); + // A group conversation is the person talking in it. Their follow-up messages, and the + // answer to a question the bot asked them, belong to the same conversation; a thread root + // only says where a reply was written. + if !direct { + channel.conversation_id = Some(format!("{chat_id}#{actor}")); + } Self { id: format!("feishu:{message_id}"), source: Source::Feishu, diff --git a/pc-mate/src/intent.rs b/pc-mate/src/intent.rs index 26bad1b671..85f169252a 100644 --- a/pc-mate/src/intent.rs +++ b/pc-mate/src/intent.rs @@ -15,7 +15,7 @@ use anyhow::{anyhow, Result}; use crate::config::Settings; -use crate::domain::{InboundEvent, IntentCategory, IntentDecision, IntentVerdict}; +use crate::domain::{InboundEvent, IntentCategory, IntentDecision, IntentMode, IntentVerdict}; use crate::util::{quote_untrusted, truncate_chars}; pub struct TriageContext<'a> { @@ -81,6 +81,26 @@ pub fn compose_triage_prompt(context: TriageContext<'_>) -> String { "- Response in the reporter's language. Be direct and factual; no generic filler.".to_string(), ]); + // The model is told what this installation does with the ruling, so its answer does not + // promise work that nobody asked for, or work that will not happen. + let mandate = match settings.triage.mode { + IntentMode::Observe => { + "This installation observes: it records what it would do and changes nothing. Never say that work is under way." + } + IntentMode::Response => { + "This installation answers. A request that names the agent explicitly is carried out; a request that does not name it is read and answered, and no branch is created for it. Say what the answer is; never promise work that was not asked for." + } + IntentMode::Auto => { + "This installation carries out a request it judges to be a bug report or a feature request, in a worktree of its own. A request that does not name the agent is carried out as well." + } + }; + lines.extend([ + String::new(), + "## What this installation does with your ruling".to_string(), + String::new(), + mandate.to_string(), + ]); + if !context.memory.is_empty() { lines.push(String::new()); lines.push("## Operational memory".to_string()); @@ -557,4 +577,36 @@ mod tests { assert!(prompt.contains("PowerContext returned no evidence")); assert!(prompt.contains("available context is insufficient")); } + + #[test] + fn the_prompt_says_what_the_installation_will_do_with_the_ruling() { + let trigger = trigger(); + let mut settings = Settings::default(); + settings.triage.mode = IntentMode::Response; + let prompt = compose_triage_prompt(TriageContext { + trigger: &trigger, + settings: &settings, + memory: &[], + site_context: None, + powercontext: None, + }); + assert!(prompt.contains("## What this installation does with your ruling")); + assert!( + prompt.contains("A request that names the agent explicitly is carried out"), + "the reply mode says what it carries out: {prompt}" + ); + + settings.triage.mode = IntentMode::Observe; + let prompt = compose_triage_prompt(TriageContext { + trigger: &trigger, + settings: &settings, + memory: &[], + site_context: None, + powercontext: None, + }); + assert!( + prompt.contains("it records what it would do and changes nothing"), + "the observe mode says that it changes nothing: {prompt}" + ); + } } diff --git a/pc-mate/src/kernel/entities.rs b/pc-mate/src/kernel/entities.rs index 5bfa4cfca4..d85ecd35c5 100644 --- a/pc-mate/src/kernel/entities.rs +++ b/pc-mate/src/kernel/entities.rs @@ -65,8 +65,8 @@ impl ConversationRef { /// The thread a channel belongs to. /// - /// A GitHub issue is its own thread; a Feishu group message belongs to the thread it responses - /// in, and a direct message to the chat itself. + /// A GitHub issue is its own thread; a Feishu group message belongs to the conversation of the + /// person who wrote it, and a direct message to the chat itself. pub fn for_channel(channel: &Channel) -> Self { match channel.source { Source::Github => Self { @@ -79,6 +79,14 @@ impl ConversationRef { }, Source::Feishu => { let chat = channel.chat_id.as_deref().unwrap_or("unknown"); + // The source says who the conversation is; a thread root only says where a reply + // was written. + if let Some(conversation) = channel.conversation_id.as_deref() { + return Self { + source: Source::Feishu.as_str().to_string(), + id: conversation.to_string(), + }; + } let thread = channel .thread_id .as_deref() @@ -1002,12 +1010,13 @@ mod tests { } #[test] - fn a_feishu_reply_belongs_to_the_thread_it_replies_in() { + fn a_feishu_message_belongs_to_the_conversation_of_its_author() { let channel = Channel { + conversation_id: Some("oc_1#alice".into()), thread_id: Some("om_7".into()), ..Channel::feishu("oc_1", "om_9", false) }; - assert_eq!(ConversationRef::for_channel(&channel).id, "oc_1#om_7"); + assert_eq!(ConversationRef::for_channel(&channel).id, "oc_1#alice"); // A direct message has no thread, so the chat is the conversation. let direct = Channel::feishu("oc_2", "om_8", true); assert_eq!(ConversationRef::for_channel(&direct).id, "oc_2"); diff --git a/pc-mate/src/kernel/tests.rs b/pc-mate/src/kernel/tests.rs index 4f77a923bb..bcc44f3f97 100644 --- a/pc-mate/src/kernel/tests.rs +++ b/pc-mate/src/kernel/tests.rs @@ -340,11 +340,10 @@ fn message(id: &str, text: &str, addressed: bool) -> InboundEvent { message_in(id, text, addressed, None) } -/// A Feishu message that belongs to a named thread. +/// A Feishu message that belongs to a named conversation. /// -/// A message that starts a conversation is its own thread; a reply in a chain -/// belongs to the chain. The tests that need several messages in one thread -/// name it, so the batching they check is the one the source would produce. +/// The source puts the messages of one person in one conversation; a test that needs a +/// conversation of its own names it. fn message_in(id: &str, text: &str, addressed: bool, thread: Option<&str>) -> InboundEvent { let mut trigger = InboundEvent::feishu( "oc_chat", @@ -413,15 +412,10 @@ fn consecutive_messages_on_one_thread_are_assessed_together_after_the_quiet_peri { let mut pipeline = harness.pipeline(); pipeline - .receive(message_in( - "om_1", - "the server crashes", - true, - Some("oc_chat#t1"), - )) + .receive(message_in("om_1", "the server crashes", true, None)) .unwrap(); pipeline - .receive(message_in("om_2", "on startup", true, Some("oc_chat#t1"))) + .receive(message_in("om_2", "on startup", true, None)) .unwrap(); // The window has not passed, so no judgement has started. pipeline.judge_due(ChronoDuration::seconds(45)).unwrap(); @@ -566,7 +560,7 @@ fn an_accepted_request_creates_a_work_item_that_owns_its_thread() { ); let thread = harness .repo - .thread_get("feishu:oc_chat#om_1") + .thread_get("feishu:oc_chat#yuyu") .unwrap() .expect("the thread exists"); assert_eq!(thread.subscriptions, vec![work_item_id]); @@ -600,12 +594,7 @@ fn a_follow_up_on_the_thread_reaches_the_work_item_instead_of_a_new_judgement() { let mut pipeline = harness.pipeline(); pipeline - .receive(message_in( - "om_2", - "also the logs are red", - true, - Some("oc_chat#om_1"), - )) + .receive(message_in("om_2", "also the logs are red", true, None)) .unwrap(); pipeline.judge_due(ChronoDuration::zero()).unwrap(); } @@ -676,12 +665,7 @@ fn a_question_waits_for_a_person_and_their_answer_resumes_the_work_item() { { let mut pipeline = harness.pipeline(); pipeline - .receive(message_in( - "om_2", - "it reads /etc/pc-mate.yaml", - true, - Some("oc_chat#om_1"), - )) + .receive(message_in("om_2", "it reads /etc/pc-mate.yaml", true, None)) .unwrap(); } let work_item = harness.repo.work_item_get(&work_item_id).unwrap().unwrap(); @@ -847,12 +831,7 @@ fn a_handback_returns_the_message_to_the_reviewer() { { let mut pipeline = harness.pipeline(); pipeline - .receive(message_in( - "om_2", - "also deploy it", - true, - Some("oc_chat#om_1"), - )) + .receive(message_in("om_2", "also deploy it", true, None)) .unwrap(); } let handed_back = { @@ -864,7 +843,7 @@ fn a_handback_returns_the_message_to_the_reviewer() { assert!(handed_back, "the message goes back to the reviewer"); let thread = harness .repo - .thread_get("feishu:oc_chat#om_1") + .thread_get("feishu:oc_chat#yuyu") .unwrap() .unwrap(); assert!( @@ -881,8 +860,8 @@ fn the_actor_and_the_thread_of_a_trigger_come_from_its_source() { assert_eq!(trigger.threads.len(), 1); assert_eq!( crate::kernel::entities::thread_key(&trigger.threads[0]), - "feishu:oc_chat#om_1", - "a message that starts a conversation is its own thread" + "feishu:oc_chat#yuyu", + "the conversation is the person who wrote the message" ); assert_eq!( trigger.addressed_kind(), diff --git a/pc-mate/src/supervisor/mod.rs b/pc-mate/src/supervisor/mod.rs index 0a857f3967..54418cb8d2 100644 --- a/pc-mate/src/supervisor/mod.rs +++ b/pc-mate/src/supervisor/mod.rs @@ -44,7 +44,9 @@ use crate::intent::{compose_triage_prompt, parse_triage_verdict, TriageContext}; use crate::kernel::contracts::{DeliveryMessage, ReviewOutcome}; use crate::kernel::contracts::{Operator as _, Storage as _}; use crate::kernel::delegations::DelegationReport; -use crate::kernel::entities::{Delegation, DelegationStage, InboundEvent, RunState, WorkItem}; +use crate::kernel::entities::{ + AuthorityLevel, Delegation, DelegationStage, InboundEvent, RunState, WorkItem, +}; use crate::kernel::ingress::ReceiveResult; use crate::kernel::judgements; use crate::kernel::pipeline::Pipeline; @@ -240,7 +242,7 @@ impl Supervisor { trigger.text = batch_text(&candidate.triggers); let (outcome, verdict) = match self.triage(&trigger).await { Ok(verdict) => { - let outcome = self.outcome_of(&verdict, &trigger); + let outcome = self.outcome_of(&verdict, &trigger, candidate.strength); (outcome, Some(verdict)) } Err(error) => { @@ -495,7 +497,12 @@ impl Supervisor { } /// What the four-way analysis means for the work. - fn outcome_of(&self, verdict: &IntentVerdict, trigger: &InboundEvent) -> ReviewOutcome { + fn outcome_of( + &self, + verdict: &IntentVerdict, + trigger: &InboundEvent, + strength: AuthorityLevel, + ) -> ReviewOutcome { let audit = Some(serde_json::json!({ "category": verdict.category.as_str(), "decision": verdict.decision.as_str(), @@ -535,9 +542,12 @@ impl Supervisor { }; } match verdict.decision { - // Only the auto mode turns a triage into work on the repository; the other modes - // answer and stop there. - IntentDecision::Implement if self.settings.triage.mode == IntentMode::Auto => { + // An explicit request may write; an inferred one may only implement when the auto + // mode is on. The reply mode answers and stops there for everything else. + IntentDecision::Implement + if self.settings.triage.mode == IntentMode::Auto + || strength == AuthorityLevel::Explicit => + { ReviewOutcome::Accept { title: verdict.title.clone(), scope: SCOPE_IMPLEMENT.to_string(), @@ -581,10 +591,10 @@ impl Supervisor { reason: format!("Triage needs more information: {}", reason), audit, }, - // The reply mode answers but never changes the repository. IntentDecision::Implement => ReviewOutcome::Ignore { reason: format!( - "Response mode: triage {} -> implement", + "Response mode: triage {} -> implement, and only an explicit request may start \ + work here", verdict.category.as_str() ), audit, @@ -1759,6 +1769,38 @@ mod tests { ) } + /// A Feishu message from a listed person, addressed to the bot or not. + fn feishu_trigger(actor: &str, addressed: bool) -> InboundEvent { + InboundEvent::feishu( + "oc_chat", + "om_1", + actor, + "fix the startup crash", + Utc::now(), + false, + addressed, + None, + None, + None, + ) + } + + /// A Feishu message with its own message id, so a follow-up is not the first message again. + fn feishu_message(message_id: &str, actor: &str, text: &str, addressed: bool) -> InboundEvent { + InboundEvent::feishu( + "oc_chat", + message_id, + actor, + text, + Utc::now(), + false, + addressed, + None, + None, + None, + ) + } + /// Wait until the background worker has reported. /// /// The acknowledgement the work_item carries when it opens is not the result; the result is the @@ -1867,6 +1909,62 @@ mod tests { ); } + #[tokio::test] + async fn an_explicit_request_starts_work_in_the_reply_mode() { + let temp = tempfile::tempdir().unwrap(); + let mut settings = settings_for(&temp.path().join("repo"), &temp.path().join("state")); + // The reply mode answers and stops there for an inferred request. + settings.triage.mode = IntentMode::Response; + settings.operator.enabled = false; + settings.feishu.enabled = true; + settings.feishu.allowed = vec!["alice".to_string()]; + let supervisor = supervisor_with(settings); + + supervisor + .receive(feishu_trigger("alice", true)) + .expect("the message is taken in"); + supervisor.tick().await.expect("the round runs"); + settle(&supervisor).await; + + let work_items = supervisor.repo.work_item_list().expect("work items"); + assert_eq!( + work_items.len(), + 1, + "an explicit request opens a work item in the reply mode too" + ); + let pending = supervisor.pending_replies(); + assert!( + pending + .iter() + .any(|message| message.text.contains("The flag is read before")), + "the request is answered by the worker that reads the repository: {pending:?}" + ); + } + + #[tokio::test] + async fn an_inferred_request_does_not_start_work_in_the_reply_mode() { + let temp = tempfile::tempdir().unwrap(); + let mut settings = settings_for(&temp.path().join("repo"), &temp.path().join("state")); + settings.triage.mode = IntentMode::Response; + settings.operator.enabled = false; + settings.feishu.enabled = true; + settings.feishu.allowed = vec!["alice".to_string()]; + let supervisor = supervisor_with(settings); + + // The same listed person, but the message did not address the bot. + supervisor + .receive(feishu_trigger("alice", false)) + .expect("the message is taken in"); + supervisor.tick().await.expect("the round runs"); + settle(&supervisor).await; + + let work_items = supervisor.repo.work_item_list().expect("work items"); + assert!( + work_items.is_empty(), + "an inferred request is answered, not worked on: {work_items:?}" + ); + } + #[tokio::test] async fn the_read_stage_answers_with_the_evidence_below_the_opening_sentence() { if !git_available() { @@ -2017,6 +2115,108 @@ mod tests { ); } + #[tokio::test] + async fn the_messages_of_one_person_in_a_group_are_one_assessment() { + let temp = tempfile::tempdir().unwrap(); + let mut settings = settings_for(&temp.path().join("repo"), &temp.path().join("state")); + settings.feishu.enabled = true; + settings.feishu.allowed = vec!["alice".to_string()]; + settings.github.enabled = false; + let supervisor = supervisor_with(settings); + + // The person writes the request in two messages, the way people write in a chat. + supervisor + .receive(feishu_message("om_1", "alice", "the service crashes", true)) + .expect("the first message is taken in"); + supervisor + .receive(feishu_message( + "om_2", + "alice", + "it happens right after it reads the config", + true, + )) + .expect("the second message is taken in"); + supervisor.tick().await.expect("the round runs"); + + let threads = supervisor.repo.thread_list().expect("threads"); + assert_eq!( + threads.len(), + 1, + "the two messages are one conversation: {threads:?}" + ); + let work_items = supervisor.repo.work_item_list().expect("work items"); + assert_eq!( + work_items.len(), + 1, + "the two messages are one assessment: {work_items:?}" + ); + let work_item = work_items.first().expect("the work item"); + assert_eq!( + work_item.origin.trigger_ids.len(), + 2, + "both messages are read by the same work: {work_item:?}" + ); + } + + #[tokio::test] + async fn an_answer_in_a_group_reaches_the_work_that_asked() { + if !git_available() { + return; + } + let (temp, repo, _remote) = seed_repository(); + let mut settings = settings_for(&repo, &temp.path().join("state")); + settings.feishu.enabled = true; + settings.feishu.allowed = vec!["alice".to_string()]; + settings.github.enabled = false; + let supervisor = supervisor_with_runner( + settings, + Arc::new(QuestioningRunner { + calls: AtomicUsize::new(0), + implementations: AtomicUsize::new(0), + }), + ); + + supervisor + .receive(feishu_message("om_1", "alice", "the service crashes", true)) + .expect("the request is taken in"); + supervisor.tick().await.expect("the round runs"); + + // The agent stops and asks. + assert!( + wait_for_text(&supervisor, "Which config file does the service read?").await, + "the question reaches the requester: {:?}", + supervisor.pending_replies() + ); + + // The requester answers in the chat, without naming the bot again. + supervisor + .receive(feishu_message( + "om_2", + "alice", + "it reads /etc/pc-mate.yaml", + false, + )) + .expect("the answer is taken in"); + supervisor.tick().await.expect("the round runs"); + + assert!( + wait_for_text(&supervisor, "Fixed the startup crash.").await, + "the work finishes after the answer: {:?}", + supervisor.pending_replies() + ); + let work_items = supervisor.repo.work_item_list().expect("work items"); + let work_item = work_items.first().expect("the work item"); + assert!( + work_item.pending_question.is_none(), + "the question is answered: {work_item:?}" + ); + assert!( + work_item.answers.iter().any(|id| id.contains("om_2")), + "the answer is recorded: {:?}", + work_item.answers + ); + } + #[tokio::test] async fn a_work_item_that_asks_to_look_again_is_checked_again() { let temp = tempfile::tempdir().unwrap(); From 9d2738ae333129fec43df38d401edc5cf02e1c0e Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 20:57:22 +0800 Subject: [PATCH 07/12] fix(pc-mate): stop re-sending every message on every round mark_sent wrote the sent marker but kept the queue entry, so pending() returned the message again on every round and the chat received every reply every 15 seconds. The pending entry is now removed after the marker is written, and pending() skips an entry whose marker already exists, so a crash between the two writes does not send it twice. --- pc-mate/src/supervisor/mailbox.rs | 64 ++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/pc-mate/src/supervisor/mailbox.rs b/pc-mate/src/supervisor/mailbox.rs index 001d1b33b9..0088391c85 100644 --- a/pc-mate/src/supervisor/mailbox.rs +++ b/pc-mate/src/supervisor/mailbox.rs @@ -64,6 +64,13 @@ impl FileMailbox { if path.extension().and_then(|value| value.to_str()) != Some("json") { continue; } + // A message that went out but was not removed before a crash must not go out again: + // the marker is written first, so it is the authority on whether the message was sent. + if let Some(stem) = path.file_stem().and_then(|value| value.to_str()) { + if self.sent_dir().join(format!("{stem}.json")).exists() { + continue; + } + } let Ok(text) = std::fs::read_to_string(&path) else { continue; }; @@ -81,7 +88,14 @@ impl FileMailbox { std::fs::create_dir_all(&dir) .map_err(|error| CoreError::new("mailbox_write").with("error", error.to_string()))?; crate::runtime_state::atomic_write(&self.file(dir, id), id.as_bytes()) - .map_err(|error| CoreError::new("mailbox_write").with("error", error.to_string())) + .map_err(|error| CoreError::new("mailbox_write").with("error", error.to_string()))?; + // The pending entry is what `pending()` lists; keeping it would send the message again on + // every round. + match std::fs::remove_file(self.file(self.pending_dir(), id)) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(CoreError::new("mailbox_write").with("error", error.to_string())), + } } } @@ -116,3 +130,51 @@ impl Mailbox for FileMailbox { let _ = std::fs::remove_file(path); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::Channel; + use crate::kernel::contracts::{DeliveryStatus, ResponseKind}; + + fn message(id: &str) -> DeliveryMessage { + DeliveryMessage { + id: id.to_string(), + channel: Channel::feishu("oc_chat", "om_1", false), + text: "the answer".to_string(), + kind: ResponseKind::Response, + work_item_id: None, + } + } + + #[test] + fn a_sent_message_is_not_queued_again() { + let temp = tempfile::tempdir().unwrap(); + let mailbox = FileMailbox::new(temp.path()); + mailbox.send(message("one")); + assert_eq!(mailbox.pending().unwrap().len(), 1); + + mailbox.mark_sent("one").expect("mark the message sent"); + + assert!( + mailbox.pending().unwrap().is_empty(), + "a message that went out is not queued again" + ); + assert_eq!(mailbox.status("one"), Some(DeliveryStatus::Sent)); + } + + #[test] + fn a_marker_left_by_a_crash_keeps_the_message_out_of_the_queue() { + let temp = tempfile::tempdir().unwrap(); + let mailbox = FileMailbox::new(temp.path()); + mailbox.send(message("one")); + // The process died after the marker was written and before the queue entry was removed. + std::fs::create_dir_all(mailbox.sent_dir()).unwrap(); + std::fs::write(mailbox.file(mailbox.sent_dir(), "one"), b"one").unwrap(); + + assert!( + mailbox.pending().unwrap().is_empty(), + "the marker says it went out, so it must not go out again" + ); + } +} From 1a1bd97d13b524af0953be31242512037f47bc10 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 21:21:23 +0800 Subject: [PATCH 08/12] test(pc-mate): parse the example settings in CI --- pc-mate/tests/settings_example.rs | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 pc-mate/tests/settings_example.rs diff --git a/pc-mate/tests/settings_example.rs b/pc-mate/tests/settings_example.rs new file mode 100644 index 0000000000..647774610b --- /dev/null +++ b/pc-mate/tests/settings_example.rs @@ -0,0 +1,36 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_mate::config::AgentKind; +use pc_mate::config::Settings; +use pc_mate::domain::IntentMode; + +/// The shipped example is the first configuration a new installation sees. Parse it with the real +/// type so a renamed field, an unknown key or a mode spelling that only exists in the docs fails +/// here instead of when a user copies the file. +/// +/// `Settings::load` is deliberately not used: it requires `checkout` to exist, and the example +/// carries a placeholder path. +#[test] +fn the_example_settings_match_the_settings_type() { + let settings: Settings = serde_yaml::from_str(include_str!("../settings.example.yaml")) + .expect("settings.example.yaml must parse as Settings"); + + // A fresh installation must not act on its own. + assert_eq!(settings.triage.mode, IntentMode::Observe); + assert_eq!(settings.triage.mode.as_str(), "observe"); + assert_eq!(settings.agent.kind, AgentKind::Codex); + assert!(settings.supervisor.enabled); + assert!(settings.operator.push); +} From 1530d3c319e4450b9df50cf16e79051990025132 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 21:21:31 +0800 Subject: [PATCH 09/12] docs(pc-mate): document the test playbook and add pc-mate to the project READMEs --- README.md | 12 ++ README_CN.md | 10 ++ README_JP.md | 11 ++ pc-mate/README.md | 286 +++++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 302 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index ea2d0438c2..4fa714aea4 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,18 @@ Codex is officially maintained; other Agent and Python framework integrations ar **Apps & teams** — [Python / HTTP / MCP](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Memory & Handoff](https://powercontext.oceanbase.io/en/docs/workflows/memory-and-handoff/) · [Deployment & access](https://powercontext.oceanbase.io/en/docs/workflows/scopes-and-access/) +## Maintainer agent + +`pc-mate` is an always-on maintainer agent for Feishu conversations and GitHub +issues. A supervisor receives and deduplicates messages, waits for a burst to +go quiet, runs the project's own four-way intent analysis (`question`, +`bug_report`, `feature_request`, `other`), and hands accepted work to an agent +that runs inside its own Git worktree. Evidence and lessons are read and +written through PowerContext, and every GitHub write still needs a +maintainer's approval. + +[pc-mate: architecture, settings and test playbook →](pc-mate/README.md) + ## News - **2026-12-01 · [v1.6.1](https://powercontext.oceanbase.io/en/changelog/v1.6.1/)** — Improve Atomic Memory processing, improve Gateway conversation and integration reliability, and make processing status clearer. diff --git a/README_CN.md b/README_CN.md index 324d5ae5a9..d5c8a2e614 100644 --- a/README_CN.md +++ b/README_CN.md @@ -222,6 +222,16 @@ Codex 为官方维护;其余 Agent 和 Python 框架集成为社区维护;Bu **应用与团队** — [Python / HTTP / MCP](https://powercontext.oceanbase.io/zh/docs/develop/interfaces/) · [记忆与任务交接](https://powercontext.oceanbase.io/zh/docs/workflows/memory-and-handoff/) · [部署与访问控制](https://powercontext.oceanbase.io/zh/docs/workflows/scopes-and-access/) +## 维护者 Agent + +`pc-mate` 是面向飞书会话和 GitHub Issue 的常驻维护者 Agent。supervisor +负责接收并去重消息、等待一轮对话安静下来、执行项目自己的四类意图判断 +(`question`、`bug_report`、`feature_request`、`other`),再把获准的工作交给 +运行在独立 Git worktree 里的 agent。证据与经验都通过 PowerContext 读写, +所有 GitHub 写入仍需维护者确认。 + +[pc-mate:架构、配置与测试手册 →](pc-mate/README.md) + ## 最新动态 - **2026-12-01 · [v1.6.1](https://powercontext.oceanbase.io/zh/changelog/v1.6.1/)** — 改进 Atomic Memory 处理,完善 Gateway 对话与集成可靠性,并提供更清晰的处理状态。 diff --git a/README_JP.md b/README_JP.md index c723dd18a9..ed4c9ad206 100644 --- a/README_JP.md +++ b/README_JP.md @@ -222,6 +222,17 @@ Codex 連携は公式メンテナンス、その他の Agent と Python フレ **アプリケーションとチーム** — [Python / HTTP / MCP](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Memory と Handoff](https://powercontext.oceanbase.io/en/docs/workflows/memory-and-handoff/) · [デプロイとアクセス制御](https://powercontext.oceanbase.io/en/docs/workflows/scopes-and-access/) +## メンテナー Agent + +`pc-mate` は Feishu の会話と GitHub Issue を扱う常駐メンテナー Agent です。 +supervisor がメッセージの受信と重複排除、会話が静まるまでの待機、プロジェクト +独自の四分類(`question`、`bug_report`、`feature_request`、`other`)の意図判定を +行い、承認された作業を独立した Git worktree 内で動く agent に渡します。根拠と +経験は PowerContext を通じて読み書きし、GitHub への書き込みはすべて +メンテナーの確認を必要とします。 + +[pc-mate:アーキテクチャ、設定、テスト手順 →](pc-mate/README.md) + ## 最新情報 - **2026-12-01 · [v1.6.1](https://powercontext.oceanbase.io/en/changelog/v1.6.1/)** — Atomic Memory の処理を改善し、Gateway と連携の信頼性、処理状況の可視化を改善。 diff --git a/pc-mate/README.md b/pc-mate/README.md index 2c6c0103ef..c5f51c616e 100644 --- a/pc-mate/README.md +++ b/pc-mate/README.md @@ -20,7 +20,7 @@ This is a proposal for community review. It accompanies [Discussion #2922](https://github.com/oceanbase/powercontext/discussions/2922) and RFC [#2919](https://github.com/oceanbase/powercontext/pull/2919), but it is not an approved product change. The default `triage.mode` is `observe`, so a -fresh installation responses to nothing and writes nothing. +fresh installation responds to nothing and writes nothing. ## Boundaries @@ -506,24 +506,276 @@ holds. The local branch survives unless `--delete-branch` is given. `doctor` checks the configured binaries, the GitHub App credentials when `writeMode: approved`, the Feishu CLI and writable state. -## Verification status +## Testing and troubleshooting -Local Linux, Rust `1.95.0`: 195 unit tests and 6 CLI tests pass. +### Automated gates + +Run these from `pc-mate/`. They are the same commands the hosted +`pc-mate-validation / check` job runs on Linux with Rust `1.95.0`: + +```bash +cargo fmt --all --check +cargo clippy --locked --all-targets -- -D warnings +cargo test --locked +cargo build --locked +``` + +The workflow is `.github/workflows/pc-mate.yml`. `cargo test --locked` builds +every target under `pc-mate/tests/`, so adding a test file needs no workflow +change. + +A green job means these held on that runner: + +- `tests/settings_example.rs` parses `settings.example.yaml` with the real + `Settings` type. An unknown key, a removed field or a mode spelling that + exists only in the docs fails before a user copies the example. +- `tests/command_smoke.rs` runs the built binary: `init` writes + `settings.yaml`, `state.db`, the readable mirrors and the schema, and + `status --json` reports empty collections instead of failing. +- Unit tests cover message parsing and dedupe, the four-way intent parse + (including a fenced verdict), authority and mode gating, single delivery + from the mailbox, the outcome-file parser, and worktree + create/commit/patch/push/remove against throwaway local repositories. + +They do not cover a real Feishu group, a real model, a real PowerContext +Server, a real GitHub App token or a push to a real remote. Those stay manual, +and the rest of this section is the playbook. + +On Windows one test is expected to fail in a restricted network: ```text -cargo test --locked --manifest-path pc-mate/Cargo.toml -cargo fmt --manifest-path pc-mate/Cargo.toml --all --check -cargo clippy --locked --manifest-path pc-mate/Cargo.toml --all-targets -- -D warnings +channels::github::tests::polling_a_changed_issue_keeps_unseen_human_comments_across_pages +``` + +It cannot open its loopback listener (`os error 10060`) because the local +firewall blocks the connection. The same test fails on the base commit. Run it +on Linux, allow loopback for the test process, or accept the single known +failure; do not weaken the test to make a Windows run green. + +With that exception, this Windows checkout reports 215 passed: 208 of 209 +library tests, all 6 CLI tests and the example-settings test. The Linux CI job +is the authoritative gate. + +### Manual end-to-end test + +Test against a disposable repository, never against the repository being +maintained. The sandbox has three parts: a normal checkout, a bare remote the +push can reach, and a state directory outside both. + +```bash +mkdir -p ~/pc-mate-sandbox && cd ~/pc-mate-sandbox +git init repo +git -C repo config user.email mate@example.com +git -C repo config user.name "pc-mate test" +printf '# sandbox\n' > repo/README.md +git -C repo add README.md +git -C repo commit -m "test: seed sandbox" +git init --bare remote.git +git -C repo remote add origin ../remote.git +git -C repo push -u origin HEAD ``` -On Windows, 191 tests pass and one fails: -`channels::github::tests::polling_a_changed_issue_keeps_unseen_human_comments_across_pages` -cannot open its loopback listener in this environment; the same test fails on -the PR's base commit, so it is not caused by this change. The hosted -`pc-mate-validation / check` job runs the Linux tests, formatting, clippy and -build. - -Not verified in this environment: a real GitHub App installation token, real -GitHub issue/comment/label writes, real Feishu delivery, real PowerContext -Scope/Principal enforcement, and real model runs. See -[`docs/rfc-conformance.md`](docs/rfc-conformance.md) for the remaining gaps. +Use a test-only settings file. The important parts are the absolute paths, the +reply mode, one listed tester, and a short quiet window: + +```yaml +stateDir: /home/you/pc-mate-sandbox/state +checkout: /home/you/pc-mate-sandbox/repo + +agent: + kind: codex + # Windows only: without this every exec_command is rejected. + extraArgs: ["-c", 'windows.sandbox="unelevated"'] + +triage: + mode: response + +feishu: + enabled: true + chats: + - chatId: oc_xxxxxxxxxxxxxxxx + name: sandbox + allowed: [ou_xxxxxxxxxxxxxxxx] # the tester; response mode serves only listed people + maintainers: [ou_xxxxxxxxxxxxxxxx] + botName: ClawBot + +powercontext: + enabled: true + baseUrl: http://127.0.0.1:8000 + scopeId: pc_xxxxxxxxxxxxxxxx + tokenEnv: POWERCONTEXT_TOKEN + +operator: + enabled: true + push: true + +supervisor: + enabled: true + batchWindowSeconds: 10 # test speed only; the default is 45 + +git: + remote: origin +``` + +Set `powercontext.enabled: false` to exercise the keynotes fallback without a +Server. Bind `lark-cli` to the app first and confirm the bot identity: + +```bash +lark-cli auth status # identities.bot.status must be "ready" +export LARK_APP_ID=... +export LARK_APP_SECRET=... +``` + +`pc-mate` starts `lark-cli event consume im.message.receive_v1 --as bot` and +sends replies as the bot. It passes only `LARK_*` and `FEISHU_*` from the +environment to the CLI, so the app credentials are the only Feishu secrets it +needs. Do not run `auth login` for the bot. + +Start one poller and watch it: + +```bash +./target/release/pc-mate doctor --settings ~/pc-mate-sandbox/settings.yaml +./target/release/pc-mate poll --settings ~/pc-mate-sandbox/settings.yaml +``` + +The binary holds `stateDir/poll.lock` for its whole lifetime, so exactly one +poller may run. Stop the previous one before starting a new build. + +Send the matrix below from the listed tester. In `response` mode a message +that names the bot is an explicit request and may reach the write stage; a +message that does not name it is inferred and is only answered. + +| Intent | Message | Expected result | +| --- | --- | --- | +| `question` | `@ClawBot how does the retry path work?` | A prose answer in the group. No worktree and no branch. | +| `bug_report` | `@ClawBot the parser rejects a fenced verdict` | A read-only answer, then a worktree write, one commit on the case branch, a saved patch, a push, and cleanup. | +| `feature_request` | `@ClawBot add a --dry-run flag to the poll command` | Same write path as a bug report. | +| `other` | `@ClawBot thanks, that helps` | A conversational answer; no work item. | +| burst | Two messages about one problem, less than `batchWindowSeconds` apart | One assessment and one reply. `supervisor/threads/` has one entry for the person in the chat. | +| follow-up | An outcome with `followupAfterSeconds: 60` | A new delegation about a minute later; the branch is based on the pushed head. | + +After each run, inspect the same evidence the controller used: + +```bash +./target/release/pc-mate status --json +./target/release/pc-mate logs +./target/release/pc-mate logs --tail 40 +./target/release/pc-mate worktree list + +git -C ~/pc-mate-sandbox/repo status --porcelain +git -C ~/pc-mate-sandbox/repo branch --list 'pc-mate/*' +git --git-dir ~/pc-mate-sandbox/remote.git log --oneline +ls ~/pc-mate-sandbox/state/cases//worktree.patch +``` + +The write path is complete when all of these are true: + +- `worktree list` is empty and the local `pc-mate/*` branch is gone. +- The checkout's `git status --porcelain` is empty; the agent never wrote + there. +- The bare remote has the case branch and its commits. +- `worktree.patch` exists under the case directory. +- `logs/main.log` and the work item log show one commit, one push and one + cleanup, in that order. + +The write stage reports with `.pc-mate/outcome.json` in its worktree. The +minimum object is: + +```json +{ + "summary": "Added the flag and a test.", + "state": "ready", + "changedFiles": ["src/main.rs"], + "verification": "cargo test --locked: 12 passed", + "followupAfterSeconds": 0 +} +``` + +A fenced JSON block is accepted. If the file is missing or malformed, the +controller falls back to the run's last prose paragraph, so the structured +fields — `changedFiles`, `question`, `lesson`, `followupAfterSeconds` — are +lost even though the commit may still happen. Check the work item log for +`implementation agent` lines before trusting a report. + +### Pitfalls and how to avoid them + +- **The agent says it can read the web but not the repository (Windows).** + The Codex CLI is running under the managed sandbox with approval `never`. + Add `-c 'windows.sandbox="unelevated"'` to `agent.extraArgs`. This applies to + both the read-only and the write stage. +- **`triage.mode: reply` does not parse.** The public values are `observe`, + `response` and `auto`. `reply` was an internal name in an older build; use + `response` and confirm with `pc-mate triage` or `status --json`. +- **A listed person gets an answer but no branch.** In `response` mode an + inferred request is only answered. To reach the write stage the tester must + address the bot (`@ClawBot ...`), `operator.enabled` must be true, and the + message must be a bug or feature request. +- **The bot ignores a group message.** Check four things in order: the chat is + in `feishu.chats`; the sender is in `feishu.allowed` (a non-empty list drops + everyone else); the event arrived (`state/supervisor/triggers/` and + `logs/main.log`); and the mention is recognizable — a structured bot mention, + or an exact `@` when the transport flattened `mentions`. + `@ClawBotHelper` is not a mention of `ClawBot`. +- **Every message in a group becomes its own conversation.** This was a defect + in an earlier build. On the current head the conversation is the person in + the chat, so a burst produces one thread and one assessment. Verify with + `state/supervisor/threads/` rather than the visible chat alone. +- **The same reply is sent again and again.** This was a mailbox defect in an + earlier build: every round re-sent the whole history. The current head marks + a response delivered once. If it recurs, keep `state/supervisor/mailbox/` and + the matching `logs/main.log` before restarting, because a restart can hide + the evidence. +- **Triage takes two to three minutes and later messages seem ignored.** The + round is serial: the model call for one burst delays intake for the next. + This is expected, not a hang. Use `batchWindowSeconds: 30`-`60`, watch for + the round to end in `logs/main.log`, and do not judge the bot from the first + minute. +- **`doctor` rejects the example file.** `checkout` is + `/absolute/path/to/powercontext` in the example and must exist. + `Settings::load` validates it, and the CI test therefore parses the example + directly instead of loading it. +- **"another poller is running" or events stop after a restart.** A previous + process still holds `stateDir/poll.lock`. Stop it first; the lock is held for + the process lifetime, not per round. +- **The push fails and the worktree remains.** That is the designed order: + patch, push, remove worktree, delete branch. Nothing is deleted after a + failed push. Fix the remote name or credentials in the daemon's environment, + then run `worktree remove ` or let the next round retry. A local bare + remote avoids credential setup entirely. +- **PowerContext memory writes fail with 503.** Check the Server's provider + quota: a chat call can return 402 and an embedding call 1008 when the + subscription is exhausted. The run can still finish, but the lesson is not + recorded. Top up and repeat the run if the memory write is part of the test. +- **The model returns prose where JSON was requested.** The controller keeps + the prose and loses the structured fields. Ask for the outcome file + explicitly in the task, keep the change small, and inspect the work item log + after the first run rather than assuming `changedFiles` or `followup` were + read. +- **A Feishu reply looks wrong although the raw text is right.** Feishu renders + Markdown, and `_` starts italics, so `bug_report` can lose its underscore on + screen. Read the raw response in `state/supervisor/mailbox/` or wrap + identifiers in backticks in the reply. + +### CI coverage and manual-only checks + +| Check | CI | Manual | +| --- | --- | --- | +| Format, clippy, build, unit and CLI tests | Yes | — | +| `settings.example.yaml` matches `Settings` | Yes | — | +| Worktree, patch and push against a local bare remote | Yes | — | +| Real Feishu event and reply | No | Yes | +| Real model run and PowerContext memory | No | Yes | +| Real GitHub App token, pending action and approval | No | Yes | +| Windows Codex sandbox and firewall behavior | No | Yes | + +### Known limitations + +- The readable work item starts and stays at `triaged` in this build, and the + delegation's `stage` field is not persisted. Follow a run through + `work_items//log.md`, `cases//worktree.json` and `logs/main.log` + instead of expecting the state file to advance. +- The pipeline performs one model round at a time. A long triage delays the + next message; the quiet window limits the number of rounds but does not make + them concurrent. +- The M2 GitHub write path and the approval chat are not exercised by CI. See + [`docs/rfc-conformance.md`](docs/rfc-conformance.md) for the remaining gaps. From 06875b5ea829ecd66c589d55d0a73b2bfd728a41 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 22:30:22 +0800 Subject: [PATCH 10/12] feat(pc-mate): configure the intents and open a pull request for the work The intent vocabulary moves into the configuration. `triage.intents` names the categories the classifier may answer with, each with the description the prompt shows the model, and an intent this build cannot act on yet is answered like `other`: the message is read, nothing else happens, and the record says which name the model used. The legacy `triage.categories` filter still loads and still narrows the set. A finished implementation can end at a pull request of its own. `github.pullRequest.enabled` with a named submitter opens it for the branch that was pushed and asks the reviewer to look at it. The reviewer has to be another account than the submitter, because GitHub refuses a review request from the author of a pull request. The reviews are read again, and a review that asks for changes runs the implementation once more with the findings in its prompt, on the same branch, until the review is satisfied or the round budget is spent. --- pc-mate/README.md | 90 ++- pc-mate/docs/rfc-conformance.md | 5 +- pc-mate/settings.example.yaml | 37 +- pc-mate/src/app.rs | 2 +- pc-mate/src/channels/github.rs | 273 ++++++++- pc-mate/src/config.rs | 361 +++++++++++- pc-mate/src/domain.rs | 26 +- pc-mate/src/intent.rs | 147 ++++- pc-mate/src/kernel/entities.rs | 25 + pc-mate/src/kernel/workitems.rs | 1 + pc-mate/src/supervisor/mod.rs | 749 ++++++++++++++++++++++++- pc-mate/src/supervisor/pull_request.rs | 87 +++ pc-mate/src/worktree.rs | 66 +++ 13 files changed, 1829 insertions(+), 40 deletions(-) create mode 100644 pc-mate/src/supervisor/pull_request.rs diff --git a/pc-mate/README.md b/pc-mate/README.md index c5f51c616e..703bd8eab6 100644 --- a/pc-mate/README.md +++ b/pc-mate/README.md @@ -49,7 +49,11 @@ fresh installation responds to nothing and writes nothing. stage implements it inside the case's own Git worktree. The agent never writes to the shared checkout. The controller commits the result and, when `operator.push` is on, pushes the branch to `git.remote` before the worktree - is removed. It never opens a pull request and never merges. + is removed. It never merges. +- A pull request is opened only when `github.pullRequest.enabled` is on and + the submitter account is named. The switch and the account are the + authorization; the pull request is not a pending action. pc-mate never merges + and never approves its own pull request. - The bot only pushes a branch that carries an accepted, implemented task. The push is the last step before the worktree goes away, so a push that fails leaves the work on disk. @@ -58,7 +62,9 @@ fresh installation responds to nothing and writes nothing. issue or a release is progress and resolves nothing. - M2 GitHub writes use a per-repository GitHub App installation token. The service validates one repository, `issues: write`, `metadata: read`, and a - token lifetime of at most one hour. + token lifetime of at most one hour. A pull request additionally needs + `pull_requests: write` on the installation, or a token of the submitter's + own. - Every GitHub issue, comment and label write is stored as a pending action whose approval binds the target, the exact text and the case version. The approval request is sent only to `feishu.approvalChat`. @@ -82,13 +88,16 @@ fresh installation responds to nothing and writes nothing. the conversation is the issue; on Feishu it is the person talking in the chat, so their follow-up messages — and the answer to a question the bot asked them — belong to the same one. -5. Assess the burst. The first step is still pc-mate's own four-way intent - analysis — `bug_report`, `feature_request`, `question`, or `other` — run +5. Assess the burst. The first step is still pc-mate's own intent analysis — + a bug report, a feature request, a question, or something else — run read-only in the checkout with `AGENTS.md`, repository docs, PowerContext memory, a prepared evidence extract, and a cached extract of - `https://powercontext.oceanbase.io/`. The assessment also decides the - *authority*: a listed person who addressed the agent makes an explicit - request, everything else worth assessing is inferred. + `https://powercontext.oceanbase.io/`. The vocabulary is configuration: + `triage.intents` names the categories the classifier may answer with, and + an intent this build cannot act on yet is answered like `other`. The + assessment also decides the *authority*: a listed person who addressed the + agent makes an explicit request, everything else worth assessing is + inferred. 6. Observe, answer in the conversation, or open a work item according to `triage.mode`. A decision that needs no work is answered where it was asked; a decision that needs work opens a work item and a case. @@ -132,6 +141,21 @@ fresh installation responds to nothing and writes nothing. sent — the latest GitHub comment, or the Feishu message with its mention stripped — not from the title-and-body context the model sees, and `triage.mode: observe` declines both commands instead of applying them. +17. When `github.pullRequest.enabled` is on and the submitter account is named, + the finished implementation opens a pull request of its own for the branch + it just pushed, and asks the reviewer account to look at it. The pull + request is not a pending action: the switch and the account are the + authorization, because a pull request that waits for a second person is not + the automation this is. +18. Every `github.pullRequest.reviewPollSeconds` the supervisor reads the + reviews of the pull requests that wait for one. A review that asks for + changes is a task: the implementation runs again with the findings, on the + same branch, so the push updates the pull request. The loop runs until the + review is satisfied or `github.pullRequest.maxReviewRounds` is spent, and + the requester is told what the review said. +19. The submitter and the reviewer are two accounts. GitHub refuses a review + request from the author of a pull request, so an installation that names + the same account twice is refused when the settings are loaded. ## Architecture @@ -171,11 +195,16 @@ flowchart TD WT["8. Write stage
stateDir/work/case"] IMPL["9. Implementation run
.pc-mate/outcome.json"] LIFE["11. commit → save patch → push branch
→ remove worktree → delete local branch"] + PR["17. pull request
branch → pull request"] + REV["18. review read
findings → another round"] WD -->|"7. no write"| RO WD -->|"8. write"| WT --> IMPL RO -->|"6, 10. answer"| OUT IMPL -->|"9-10. summary / question"| OUT IMPL -->|"11. commit"| LIFE + LIFE -->|"11. pushed branch"| PR + PR -->|"17. ask the reviewer"| REV + REV -->|"18. run again with the findings"| IMPL end GH -->|"1. poll"| IN @@ -255,6 +284,8 @@ flowchart LR PA["GitHub pending action"] AP["approval chat"] GW["post once"] + PR["9. pull request
github.pullRequest.enabled"] + RV["10. review findings
→ another round"] CMD["8. resolve / approval command
no model call"] end @@ -269,6 +300,9 @@ flowchart LR REP -->|"6. save patch"| PATCH BR -->|"6. push"| REM BR -->|"6. after push"| CLN + BR -->|"6. pushed branch"| PR + PR -->|"9. ask the reviewer"| RV + RV -->|"10. run again with the findings"| WT REP -->|"8. reply"| OB REP -->|"8. advance case"| CASE OB -->|"8. Feishu"| FE @@ -298,6 +332,8 @@ flowchart LR | 6 | 11 | Commit, save patch, push, remove worktree, delete local branch, lesson to PowerContext | | 7 | 12 | `followupAfterSeconds` schedules a new delegation | | 8 | 13-16 | Response, advance the case, GitHub pending action, approval chat, post once, resolve command | +| 9 | 17 | Pull request opened for the pushed branch, reviewer asked | +| 10 | 18-19 | Review read, another implementation round with the findings, the requester told | The domain lives under `pc-mate/src/kernel/` (`entities`, `pipeline`, `ingress`, `judgements`, `workitems`, `delegations`, `responses`, `rationale`, `contracts`). @@ -439,6 +475,12 @@ See `settings.example.yaml`. The important switches are: `run --write` command: the unattended paths either run read-only or run with write access in a worktree, and this runner cannot restrict its own tools. - `triage.mode`: `observe`, `response`, or `auto`. +- `triage.intents`: the categories the classifier may answer with, each with the + description the prompt shows the model. The vocabulary is configuration, so an + operator adds an intent here without a code change. An intent this build + cannot act on yet is answered like `other`: the message is read and nothing + else happens, and the record says which name the model used. `other` has to be + in the list, because it is the answer for noise. - `triage.autoLabel`: kept so an existing settings file still loads. The supervisor no longer queues a label, so this switch no longer has an effect. - `github.writeMode`: `off` for M1; `approved` for M2. @@ -447,6 +489,11 @@ See `settings.example.yaml`. The important switches are: - `feishu.allowed`: the Feishu `open_id` values whose messages are taken in, and whose request is an explicit one. - `github.maintainers`: GitHub logins allowed to resolve a case. +- `github.pullRequest.enabled`: when true a finished implementation opens a pull + request of its own. `github.pullRequest.submitter` names the account that + opens it, `github.pullRequest.reviewer` the account that is asked to review + it, and `github.pullRequest.maxReviewRounds` how many times the + implementation may run again for the findings of one review. - `feishu.maintainers`: Feishu `open_id` values allowed to resolve or approve. - `feishu.botName`: the bot display name, for example `ClawBot`. Some event transports flatten the callback and drop the structured `mentions` array. When @@ -506,6 +553,35 @@ holds. The local branch survives unless `--delete-branch` is given. `doctor` checks the configured binaries, the GitHub App credentials when `writeMode: approved`, the Feishu CLI and writable state. +### The pull request and the review loop + +A finished implementation ends at a pushed branch by default. With +`github.pullRequest.enabled` on and `github.pullRequest.submitter` named, it +ends at a pull request instead: + +- The branch was pushed before its worktree went away, so the pull request is + one API call. The head names the account the branch lives under when that is + another account than the repository's, so a branch pushed to a fork opens a + pull request from that fork. +- The pull request is written with the submitter's own token when + `github.pullRequest.submitterTokenEnv` names one, and with the GitHub App + installation token otherwise. Without a token of its own, the pull request is + the App bot's, so `submitter` has to be `github.botLogin`. +- `github.pullRequest.reviewer` is asked to review the pull request. It has to + be another account than the submitter: GitHub refuses a review request from + the author of a pull request, and a reviewer that is the author is no review + at all. An installation that names the same account twice is refused when the + settings are loaded. +- Every `github.pullRequest.reviewPollSeconds` the supervisor reads the reviews + of the pull requests that wait for one. A review that asks for changes is a + task: the implementation runs again with the findings in its prompt, on the + same branch, so the push updates the pull request. The loop ends when the + review is satisfied, when the round budget is spent, or when the requester + is told what is left to do. +- The pull request is not a pending action. The issue and comment writes wait + for a maintainer in `feishu.approvalChat`; the pull request does not, because + the switch and the account are the authorization. + ## Testing and troubleshooting ### Automated gates diff --git a/pc-mate/docs/rfc-conformance.md b/pc-mate/docs/rfc-conformance.md index 082735c31c..aee53920da 100644 --- a/pc-mate/docs/rfc-conformance.md +++ b/pc-mate/docs/rfc-conformance.md @@ -53,7 +53,10 @@ says so. Platform behavior that was not exercised is labeled unverified rather t | The outcome file is checked, not trusted | `run_result::read` refuses a file that is not a JSON object or does not match the schema; a run that wrote no file falls back to its own words | `an_outcome_names_what_was_done_and_how_it_was_checked`, `a_file_that_is_not_an_outcome_is_refused`, `a_run_that_wrote_nothing_falls_back_to_its_own_words` | | An accepted request is acknowledged where it was asked | `Supervisor::outcome_of` returns the acknowledgement with the acceptance, and the pipeline addresses it to the conversation the request came from | `the_acknowledgement_of_an_accepted_request_goes_to_the_conversation_it_came_from` | | An assessment that could not run answers nobody | a failed assessment becomes `Unavailable` and is logged; it is not turned into a reply | `a_failed_assessment_answers_nobody` | -| A category the installation does not act on has no side effect | the assessment stops at `Ignore` for a category outside `triage.categories`, and nothing is queued | `a_category_outside_the_configured_set_has_no_side_effects` | +| A category the installation does not act on has no side effect | the assessment stops at `Ignore` for a category outside `triage.intents` (or outside the legacy `triage.categories` filter), and nothing is queued | `a_category_outside_the_configured_set_has_no_side_effects` | +| The intent vocabulary is configuration | `triage.intents` names the categories the prompt offers, and a name this build cannot act on is answered like `other` | `an_intent_the_build_does_not_know_is_answered_like_other`, `a_configured_intent_the_build_does_not_handle_still_names_itself`, `the_prompt_offers_the_configured_intents` | +| A finished implementation opens a pull request and asks the reviewer | `github.pullRequest.enabled` with a named submitter opens the pull request for the branch that was pushed and asks the reviewer, who has to be another account than the submitter | `a_finished_implementation_opens_a_pull_request_and_asks_the_reviewer`, `the_pull_request_settings_have_to_name_accounts_that_can_act` | +| A review that asks for changes runs the implementation again | the findings of a `changes_requested` review go into the next implementation prompt, until the round budget is spent | `a_review_that_asks_for_changes_runs_the_implementation_again`, `the_prompt_carries_the_findings_of_the_review`, `an_approved_review_answers_the_requester` | | A flattened group event still requires an explicit address | `parse_event` accepts a group message only when a structured mention matches the bot id/app id, or when the transport sent no structured mention at all, `feishu.botName` is set, and the rendered text holds an exact `@` mention; a name that continues into another word (`@ClawBotHelper`) is not a mention, and a structured mention of another user wins over the display name, so RFC 2919 L92 full group ingestion stays excluded | `flattened_group_event_with_display_name_only_is_accepted`, `a_display_name_that_continues_into_another_word_is_not_a_mention`, `a_structured_mention_of_another_user_is_not_a_mention_of_the_bot`, `a_group_mention_without_a_bot_identity_is_ignored` | | A typed command is read from the message, not the assembled context | `InboundEvent::message` keeps the latest GitHub comment or the Feishu message; `InboundEvent::command_text` strips a leading bot mention; `App::handle_command` parses only that | `a_command_is_read_from_the_message_not_the_assembled_context`, `a_mention_is_stripped_before_a_strict_command_match` | | `observe` refuses commands as well as triage | `App::handle_command` logs and returns before `confirm`/`approve`, so a resolution or an approval changes nothing | `observe_mode_declines_a_typed_approval` | diff --git a/pc-mate/settings.example.yaml b/pc-mate/settings.example.yaml index e619cdfa9a..1062ff51fc 100644 --- a/pc-mate/settings.example.yaml +++ b/pc-mate/settings.example.yaml @@ -84,6 +84,25 @@ github: botLogin: "" writeMode: off # off | approved maintainers: [] # GitHub logins allowed to resolve a case + # The pull request a finished implementation opens, and the review loop around it. The + # switch and the submitter account are the authorization: the pull request is not a pending + # action that waits for a maintainer. + pullRequest: + enabled: false + # The account the pull request is opened as. It must differ from the reviewer: GitHub does + # not accept a review request from the author of a pull request. Without a token of its own + # the pull request is the App bot's, so the submitter then has to be `botLogin`. + submitter: "" + # The environment variable holding a token for the submitter account. Empty uses the GitHub + # App installation token, which needs `pull_requests: write` on the installation. + submitterTokenEnv: "" + # The account that is asked to review the pull request. Empty opens the pull request without + # asking anyone. + reviewer: "" + # How many times the implementation may run again for the findings of one review. + maxReviewRounds: 3 + # How long until the review of a pull request is looked at again, in seconds. + reviewPollSeconds: 300 feishu: enabled: false @@ -134,7 +153,23 @@ triage: # queued actions). Typed confirmations and approvals still work, because they are commands. enabled: true mode: observe # observe | response | auto - categories: [bug_report, feature_request, question] + # The intents the classifier may answer with. The vocabulary is configuration: an operator adds + # an intent here and the prompt offers it, without a code change. An intent this build cannot + # act on yet is answered like `other`, so a new entry is safe to add before the code that + # handles it exists. `other` is required: it is the answer for noise. + intents: + - name: bug_report + description: broken behavior, crash, regression, wrong output, error log, or an unexpected edge case in this project + - name: feature_request + description: a new capability, enhancement, configuration option, integration, or ergonomics improvement + - name: question + description: a general usage, setup, configuration, or documentation question that should be answered from the repository and official materials + - name: other + description: chatter, praise, off-topic remarks, spam, or noise + # Kept so an existing configuration file still loads. It used to name the intents this + # installation acted on; when it is set, it narrows the intents above to the kinds that are + # acted on. Leave it out to act on every intent above except `other`. + # categories: [bug_report, feature_request] # Kept so an existing configuration file still loads. The supervisor no longer queues a # label, so this switch has no effect. autoLabel: false diff --git a/pc-mate/src/app.rs b/pc-mate/src/app.rs index ac75793e83..30242b12d2 100644 --- a/pc-mate/src/app.rs +++ b/pc-mate/src/app.rs @@ -1464,7 +1464,7 @@ mod tests { settings.github.enabled = true; settings.github.allowed = vec!["bob".to_string()]; settings.triage.mode = IntentMode::Response; - settings.triage.categories = vec![crate::domain::IntentCategory::Question]; + settings.triage.categories = Some(vec![crate::domain::IntentCategory::Question]); // Approved writes make an unfiltered reply queue a real action, so this test fails if the // category policy is not applied before the reply path. settings.github.write_mode = crate::config::GithubWriteMode::Approved; diff --git a/pc-mate/src/channels/github.rs b/pc-mate/src/channels/github.rs index b323acd0e1..f469b40128 100644 --- a/pc-mate/src/channels/github.rs +++ b/pc-mate/src/channels/github.rs @@ -69,6 +69,50 @@ pub enum WriteOutcome { Unknown { error: String }, } +/// A pull request the installation opened. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OpenedPullRequest { + /// The number GitHub gave the pull request. + pub number: u64, + /// Where the pull request lives. + pub url: String, +} + +/// What the reviews of a pull request say. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ReviewFindings { + /// The state of the latest review: `approved`, `changes_requested`, `commented` and so on. + /// Empty when nobody has reviewed the pull request yet. + pub state: String, + /// What the reviewer asked for, one entry per finding. + pub findings: Vec, +} + +#[derive(Debug, Deserialize)] +struct PullRequestPayload { + number: u64, + #[serde(default)] + html_url: Option, +} + +#[derive(Debug, Deserialize)] +struct ReviewPayload { + #[serde(default)] + state: String, + #[serde(default)] + body: Option, +} + +#[derive(Debug, Deserialize)] +struct ReviewCommentPayload { + #[serde(default)] + body: Option, + #[serde(default)] + path: Option, + #[serde(default)] + line: Option, +} + #[derive(Debug, Deserialize)] struct Issue { number: u64, @@ -518,6 +562,132 @@ impl GithubSource { classify_write(response, "add labels").await } + /// Open a pull request for a branch that is already on the remote. + /// + /// The token is the submitter's own when the operator named one, and the installation + /// token otherwise; either way the pull request carries the identity of that token. + pub async fn create_pull_request( + &self, + head: &str, + base: &str, + title: &str, + body: &str, + ) -> Result { + let token = self.pull_request_token().await?; + let repository = self.config.repository.trim(); + let response = self + .client + .post(format!("{}/repos/{repository}/pulls", self.api_base)) + .bearer_auth(token) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .json(&serde_json::json!({ + "title": truncate_chars(title.trim(), 120), + "head": head, + "base": base, + "body": body, + })) + .send() + .await + .context("create pull request")?; + let status = response.status(); + let text = response.text().await.unwrap_or_default(); + if !status.is_success() { + bail!( + "creating the pull request returned {}: {}", + status.as_u16(), + text.chars().take(512).collect::() + ); + } + let payload: PullRequestPayload = + serde_json::from_str(&text).context("parse pull request response")?; + Ok(OpenedPullRequest { + number: payload.number, + url: payload.html_url.unwrap_or_default(), + }) + } + + /// Ask an account to review the pull request. + /// + /// GitHub does not accept a review request from the author of the pull request, so the + /// account asked here has to be another one. + pub async fn request_reviewers(&self, number: u64, reviewers: &[String]) -> Result<()> { + if reviewers.is_empty() { + return Ok(()); + } + let token = self.pull_request_token().await?; + let repository = self.config.repository.trim(); + let response = self + .client + .post(format!( + "{}/repos/{repository}/pulls/{number}/requested_reviewers", + self.api_base + )) + .bearer_auth(token) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .json(&serde_json::json!({ + "reviewers": reviewers, + "team_reviewers": [], + })) + .send() + .await + .context("request reviewers")?; + let status = response.status(); + let text = response.text().await.unwrap_or_default(); + if !status.is_success() { + bail!( + "requesting the review returned {}: {}", + status.as_u16(), + text.chars().take(512).collect::() + ); + } + Ok(()) + } + + /// What the reviews of a pull request say. + pub async fn pull_request_findings(&self, number: u64) -> Result { + let repository = self.config.repository.trim(); + let reviews: Vec = self + .get_json(&format!("/repos/{repository}/pulls/{number}/reviews")) + .await + .with_context(|| format!("read the reviews of pull request #{number}"))?; + let comments: Vec = self + .get_json(&format!("/repos/{repository}/pulls/{number}/comments")) + .await + .with_context(|| format!("read the review comments of pull request #{number}"))?; + Ok(findings_from_reviews(&reviews, &comments)) + } + + /// The branch a pull request is opened against. + pub async fn default_branch(&self) -> Result { + #[derive(Deserialize)] + struct RepositoryPayload { + default_branch: String, + } + let repository = self.config.repository.trim(); + let payload: RepositoryPayload = self + .get_json(&format!("/repos/{repository}")) + .await + .with_context(|| format!("read the default branch of {repository}"))?; + Ok(payload.default_branch) + } + + /// The token a pull request is written with. + /// + /// The submitter's own token when the operator named one, and the installation token + /// otherwise. The installation token speaks for the App bot, so the pull request is the + /// bot's; a token of its own lets the pull request be the submitter's. + async fn pull_request_token(&self) -> Result { + let variable = self.config.pull_request.submitter_token_env.trim(); + if !variable.is_empty() { + let token = std::env::var(variable).with_context(|| format!("read {variable}"))?; + anyhow::ensure!(!token.trim().is_empty(), "{variable} is empty"); + return Ok(token.trim().to_string()); + } + self.write_token().await + } + async fn get_json Deserialize<'de>>(&self, path: &str) -> Result { if let Some(until) = *self.read_after.lock().await { anyhow::ensure!(Utc::now() >= until, "GitHub read budget resets at {until}"); @@ -659,6 +829,19 @@ impl GithubSource { parsed.repositories = inventory.repositories; } validate_installation(&parsed, self.config.repository.trim(), Utc::now())?; + if self.config.pull_request.enabled + && self + .config + .pull_request + .submitter_token_env + .trim() + .is_empty() + { + anyhow::ensure!( + parsed.permissions.get("pull_requests").map(String::as_str) == Some("write"), + "the installation token must have pull_requests: write to open a pull request" + ); + } let expires_at = parsed.expires_at; let cached = CachedToken { value: parsed.token.clone(), @@ -683,7 +866,7 @@ fn validate_installation( bail!("installation token lifetime exceeds one hour"); } for permission in token.permissions.keys() { - if !matches!(permission.as_str(), "issues" | "metadata") { + if !matches!(permission.as_str(), "issues" | "metadata" | "pull_requests") { bail!("installation token has unexpected permission {permission:?}"); } } @@ -708,6 +891,53 @@ fn validate_installation( Ok(()) } +/// What the reviews of a pull request ask for. +/// +/// The state is the latest review's state, and the findings are the comments the reviewer +/// left on the code and the body of a review that asks for changes. A review that approves +/// says what it thinks in its own words, and those words are not a task. +fn findings_from_reviews( + reviews: &[ReviewPayload], + comments: &[ReviewCommentPayload], +) -> ReviewFindings { + let mut findings = Vec::new(); + for comment in comments { + let body = comment.body.as_deref().unwrap_or_default().trim(); + if body.is_empty() { + continue; + } + let finding = match (comment.path.as_deref(), comment.line) { + (Some(path), Some(line)) => format!("{path}:{line}: {body}"), + (Some(path), None) => format!("{path}: {body}"), + (None, _) => body.to_string(), + }; + findings.push(finding); + } + let state = reviews + .iter() + .rev() + .find_map(|review| { + let state = review.state.trim().to_ascii_lowercase(); + (!state.is_empty()).then_some(state) + }) + .unwrap_or_default(); + // A review that asks for changes says why in its body; that is a finding of its own. + for review in reviews.iter().rev() { + if !review + .state + .trim() + .eq_ignore_ascii_case("changes_requested") + { + continue; + } + let body = review.body.as_deref().unwrap_or_default().trim(); + if !body.is_empty() { + findings.insert(0, body.to_string()); + } + } + ReviewFindings { state, findings } +} + async fn classify_write( response: reqwest::Result, operation: &str, @@ -1021,4 +1251,45 @@ mod tests { "a bot comment must not become a maintainer-authored command" ); } + #[test] + fn the_findings_of_a_review_are_the_comments_and_the_changes_requested() { + let reviews = vec![ + ReviewPayload { + state: "COMMENTED".into(), + body: Some("looks fine so far".into()), + }, + ReviewPayload { + state: "CHANGES_REQUESTED".into(), + body: Some("the flag is read twice".into()), + }, + ]; + let comments = vec![ReviewCommentPayload { + body: Some("this line is dead".into()), + path: Some("src/lib.rs".into()), + line: Some(12), + }]; + let findings = findings_from_reviews(&reviews, &comments); + assert_eq!(findings.state, "changes_requested"); + assert_eq!( + findings.findings, + vec![ + "the flag is read twice".to_string(), + "src/lib.rs:12: this line is dead".to_string(), + ] + ); + } + + #[test] + fn an_approval_has_no_findings() { + let reviews = vec![ReviewPayload { + state: "APPROVED".into(), + body: Some("thank you".into()), + }]; + let findings = findings_from_reviews(&reviews, &[]); + assert_eq!(findings.state, "approved"); + assert!( + findings.findings.is_empty(), + "an approval is a verdict and not a task: {findings:?}" + ); + } } diff --git a/pc-mate/src/config.rs b/pc-mate/src/config.rs index d2e6324fa0..09659af93a 100644 --- a/pc-mate/src/config.rs +++ b/pc-mate/src/config.rs @@ -152,6 +152,8 @@ pub struct GithubConfig { pub write_mode: GithubWriteMode, /// Actors allowed to resolve a case or approve a public write. pub maintainers: Vec, + /// The pull request a finished implementation opens, and the review loop around it. + pub pull_request: PullRequestConfig, } impl Default for GithubConfig { @@ -172,6 +174,7 @@ impl Default for GithubConfig { bot_login: String::new(), write_mode: GithubWriteMode::Off, maintainers: Vec::new(), + pull_request: PullRequestConfig::default(), } } } @@ -185,6 +188,52 @@ pub enum GithubWriteMode { Approved, } +/// The pull request a finished implementation opens, and the review loop around it. +/// +/// The switch is the operator's: without it an implementation ends at a pushed branch, and +/// with it the implementation opens a pull request of its own and asks a reviewer to look at +/// it. The pull request is not an approved pending action like the issue and comment writes: +/// the switch and the submitter account are the authorization, because a pull request that +/// waits for a second person is not the automation this is. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default, deny_unknown_fields)] +pub struct PullRequestConfig { + /// When true a finished implementation opens a pull request. + pub enabled: bool, + /// The account the pull request is opened as. + /// + /// It must be an account that can open one, and it must not be the reviewer: GitHub does + /// not accept a review request from the author of the pull request. + pub submitter: String, + /// The environment variable holding a token for the submitter account. + /// + /// Empty uses the GitHub App installation token, which speaks for the App bot; then + /// `submitter` has to be `github.botLogin`. + pub submitter_token_env: String, + /// The account that is asked to review the pull request. + /// + /// Empty opens the pull request without asking anyone, and the review loop has nobody to + /// read. + pub reviewer: String, + /// How many times the implementation may run again for the findings of one review. + pub max_review_rounds: u32, + /// How long until the review is looked at again, in seconds. + pub review_poll_seconds: u64, +} + +impl Default for PullRequestConfig { + fn default() -> Self { + Self { + enabled: false, + submitter: String::new(), + submitter_token_env: String::new(), + reviewer: String::new(), + max_review_rounds: 3, + review_poll_seconds: 300, + } + } +} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default, deny_unknown_fields)] pub struct FeishuChat { @@ -271,7 +320,19 @@ pub struct TriageConfig { /// work because they are commands, not triage. pub enabled: bool, pub mode: IntentMode, - pub categories: Vec, + /// The intents the classifier may answer with. + /// + /// The vocabulary is configuration, not code: an operator adds an intent here and the + /// prompt offers it, without a line of Rust changing. An intent this build cannot act on + /// yet is treated like `other`, so a new entry is safe to add before the code that handles + /// it exists. + pub intents: Vec, + /// Kept so an existing configuration file still loads. + /// + /// It used to name the intents the installation acted on. The list of intents is + /// `intents` now, and this field only narrows it: when it is set, an intent that is not in + /// it is not acted on either. + pub categories: Option>, /// Kept for compatibility. The supervisor replaced the pipeline that queued the label, so /// this switch no longer has an effect. pub auto_label: bool, @@ -291,11 +352,8 @@ impl Default for TriageConfig { Self { enabled: true, mode: IntentMode::Observe, - categories: vec![ - IntentCategory::BugReport, - IntentCategory::FeatureRequest, - IntentCategory::Question, - ], + intents: IntentSpec::defaults(), + categories: None, auto_label: false, allow_community: true, max_reply_chars: 4000, @@ -308,6 +366,79 @@ impl Default for TriageConfig { } } +/// One intent the classifier may answer with. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct IntentSpec { + /// The name the model writes, for example `bug_report`. + pub name: String, + /// What the intent covers. The prompt shows this text to the model, so it is the whole + /// definition of the intent. + pub description: String, +} + +impl IntentSpec { + /// The intents every installation starts with. + pub fn defaults() -> Vec { + vec![ + IntentSpec { + name: "bug_report".into(), + description: "broken behavior, crash, regression, wrong output, error log, or an unexpected edge case in this project".into(), + }, + IntentSpec { + name: "feature_request".into(), + description: "a new capability, enhancement, configuration option, integration, or ergonomics improvement".into(), + }, + IntentSpec { + name: "question".into(), + description: "a general usage, setup, configuration, or documentation question that should be answered from the repository and official materials".into(), + }, + IntentSpec { + name: "other".into(), + description: "chatter, praise, off-topic remarks, spam, or noise".into(), + }, + ] + } +} + +impl TriageConfig { + /// The intent names the classifier may use, in the order the prompt lists them. + pub fn intent_names(&self) -> Vec<&str> { + self.intents + .iter() + .map(|intent| intent.name.trim()) + .filter(|name| !name.is_empty()) + .collect() + } + + /// Whether this installation acts on a kind of intent. + /// + /// A kind is acted on when the classifier may name it and the legacy `categories` filter + /// does not narrow it away. `other` is never acted on: it is the answer for noise. + pub fn handles(&self, category: IntentCategory) -> bool { + if matches!(category, IntentCategory::Other) { + return false; + } + if !self + .intents + .iter() + .any(|intent| intent.name.trim() == category.as_str()) + { + return false; + } + match &self.categories { + Some(categories) => categories.contains(&category), + None => true, + } + } + + /// Whether the configuration names an intent this build does not know. + pub fn knows_intent(&self, name: &str) -> bool { + let name = name.trim(); + !name.is_empty() && self.intent_names().contains(&name) + } +} + /// The switch that used to stop the pipeline before any code was touched. /// /// The supervisor replaced the proposal stage: the work_item's read-only stage answers in prose and @@ -566,6 +697,7 @@ impl Settings { if self.github.maintainers.is_empty() { bail!("github.maintainers must name who may resolve a case"); } + self.validate_pull_request()?; } if self.feishu.enabled && self.feishu.chats.is_empty() && !self.feishu.direct_messages { bail!("feishu is enabled but neither chats nor directMessages is configured"); @@ -582,6 +714,7 @@ impl Settings { if self.triage.max_reply_chars < 200 { bail!("triage.maxReplyChars must be at least 200"); } + self.validate_intents()?; // The prefix becomes a real branch name, so it has to satisfy the rules git applies to one. if self.operator.branch_prefix.trim().is_empty() { bail!("operator.branchPrefix must not be empty"); @@ -614,10 +747,87 @@ impl Settings { Ok(()) } + /// The intent vocabulary has to be usable by a model and by the records. + fn validate_intents(&self) -> Result<()> { + if self.triage.intents.is_empty() { + bail!("triage.intents must name at least one intent"); + } + let mut seen: Vec<&str> = Vec::new(); + for intent in &self.triage.intents { + let name = intent.name.trim(); + if name.is_empty() { + bail!("triage.intents: every intent needs a name"); + } + if !name + .chars() + .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_') + || name.starts_with(|ch: char| ch.is_ascii_digit()) + { + bail!( + "triage.intents: {name:?} is not a usable intent name; \ + use lower-case letters, digits and underscores" + ); + } + if seen.contains(&name) { + bail!("triage.intents: {name:?} is listed twice"); + } + seen.push(name); + if intent.description.trim().is_empty() { + bail!("triage.intents: {name:?} needs a description; it is the whole definition"); + } + } + // Without it the model has no way to say that a message is noise. + if !seen.contains(&"other") { + bail!("triage.intents must include `other`; it is the answer for noise"); + } + Ok(()) + } + pub fn state_path(&self) -> PathBuf { self.state_dir.clone() } + /// The pull request settings have to name accounts that can act. + fn validate_pull_request(&self) -> Result<()> { + let pull_request = &self.github.pull_request; + if !pull_request.enabled { + return Ok(()); + } + let submitter = pull_request.submitter.trim(); + if submitter.is_empty() { + bail!( + "github.pullRequest.submitter must name the account the pull request is opened as" + ); + } + let reviewer = pull_request.reviewer.trim(); + if !reviewer.is_empty() && reviewer.eq_ignore_ascii_case(submitter) { + // GitHub refuses a review request from the author of the pull request, and a + // reviewer that is the author is no review at all. + bail!("github.pullRequest.reviewer must be a different account than the submitter"); + } + let token_env = pull_request.submitter_token_env.trim(); + if token_env.is_empty() { + // Without a token of its own the installation token speaks for the App bot, so the + // pull request would be the App's and nobody else's. + let bot_login = self.github.bot_login.trim(); + if !submitter.eq_ignore_ascii_case(bot_login) { + bail!( + "github.pullRequest.submitter is {submitter:?}, but the pull request would be opened as the App bot {bot_login:?}; give the submitter its own token or name the bot" + ); + } + if !matches!(self.github.write_mode, GithubWriteMode::Approved) { + bail!("github.pullRequest needs github.writeMode: approved, or a token of its own"); + } + } + if pull_request.max_review_rounds == 0 { + bail!("github.pullRequest.maxReviewRounds must be at least 1"); + } + if pull_request.review_poll_seconds < 30 { + bail!("github.pullRequest.reviewPollSeconds must be at least 30"); + } + Ok(()) + } + pub fn work_dir(&self) -> PathBuf { self.state_dir.join("work") } @@ -731,6 +941,15 @@ github: botLogin: "" writeMode: off # off | approved maintainers: [] + # The pull request a finished implementation opens, and the review loop around it. The + # switch and the submitter account are the authorization. + pullRequest: + enabled: false + submitter: "" # the account the pull request is opened as + submitterTokenEnv: "" # a token for that account; empty uses the App installation token + reviewer: "" # the account asked to review the pull request + maxReviewRounds: 3 + reviewPollSeconds: 300 # M2 GitHub writes are requested here. This chat holds the exact text and the approval token, # so it must be a private maintainer channel, not a public community group. @@ -758,7 +977,17 @@ powercontext: triage: enabled: true mode: observe # observe | response | auto - categories: [bug_report, feature_request, question] + # The intents the classifier may answer with. An intent this build cannot act on yet is + # answered like `other`, so a new entry is safe to add before the code that handles it exists. + intents: + - name: bug_report + description: broken behavior, crash, regression, wrong output, error log, or an unexpected edge case in this project + - name: feature_request + description: a new capability, enhancement, configuration option, integration, or ergonomics improvement + - name: question + description: a general usage, setup, configuration, or documentation question that should be answered from the repository and official materials + - name: other + description: chatter, praise, off-topic remarks, spam, or noise autoLabel: false allowCommunity: true maxReplyChars: 4000 @@ -910,4 +1139,122 @@ mod tests { assert!(!agent.passes_allowlist("SOME_UNLISTED_TOKEN")); assert!(!agent.passes_allowlist("LD_PRELOAD")); } + #[test] + fn the_intent_vocabulary_has_to_be_usable() { + let dir = tempfile::tempdir().unwrap(); + let checkout = dir.path().join("checkout"); + std::fs::create_dir_all(&checkout).unwrap(); + let mut settings = Settings { + checkout, + state_dir: dir.path().join("state"), + ..Settings::default() + }; + + // An intent without a description is not a definition. + settings.triage.intents.push(crate::config::IntentSpec { + name: "performance_regression".into(), + description: " ".into(), + }); + let error = settings + .validate() + .expect_err("an intent without a description is unusable"); + assert!(format!("{error:#}").contains("description"), "{error:#}"); + + // The same name twice is a mistake the operator has to see. + settings.triage.intents.pop(); + settings.triage.intents.push(crate::config::IntentSpec { + name: "question".into(), + description: "a question".into(), + }); + let error = settings + .validate() + .expect_err("the same intent twice is a mistake"); + assert!(format!("{error:#}").contains("twice"), "{error:#}"); + + // A name the model cannot write is not a name. + settings.triage.intents.pop(); + settings.triage.intents.push(crate::config::IntentSpec { + name: "Performance Regression".into(), + description: "a regression".into(), + }); + let error = settings + .validate() + .expect_err("a name with spaces is not writable"); + assert!(format!("{error:#}").contains("intent name"), "{error:#}"); + + // Without `other` the model cannot say that a message is noise. + settings.triage.intents.pop(); + settings + .triage + .intents + .retain(|intent| intent.name != "other"); + let error = settings + .validate() + .expect_err("the vocabulary needs the noise answer"); + assert!(format!("{error:#}").contains("other"), "{error:#}"); + } + + #[test] + fn a_new_intent_is_offered_and_not_yet_handled() { + let mut settings = Settings::default(); + settings.triage.intents.push(crate::config::IntentSpec { + name: "performance_regression".into(), + description: "a change that made something slower".into(), + }); + assert!(settings.triage.knows_intent("performance_regression")); + // The kinds this build acts on did not change. + assert!(settings.triage.handles(IntentCategory::BugReport)); + assert!(settings.triage.handles(IntentCategory::FeatureRequest)); + assert!(settings.triage.handles(IntentCategory::Question)); + assert!(!settings.triage.handles(IntentCategory::Other)); + } + + #[test] + fn the_pull_request_settings_have_to_name_accounts_that_can_act() { + let dir = tempfile::tempdir().unwrap(); + let checkout = dir.path().join("checkout"); + std::fs::create_dir_all(&checkout).unwrap(); + let mut settings = Settings { + checkout, + state_dir: dir.path().join("state"), + ..Settings::default() + }; + settings.github.enabled = true; + settings.github.repository = "oceanbase/powercontext".into(); + settings.github.bot_login = "pc-mate[bot]".into(); + settings.github.maintainers = vec!["alice".into()]; + settings.github.pull_request.enabled = true; + + // The switch alone opens nothing. + let error = settings + .validate() + .expect_err("a pull request needs the account that opens it"); + assert!(format!("{error:#}").contains("submitter"), "{error:#}"); + + // The reviewer may not be the author: GitHub refuses such a review request. + settings.github.pull_request.submitter = "pc-mate[bot]".into(); + settings.github.pull_request.reviewer = "pc-mate[bot]".into(); + let error = settings + .validate() + .expect_err("the reviewer may not be the author"); + assert!( + format!("{error:#}").contains("different account"), + "{error:#}" + ); + + // Without a token of its own the pull request is the App bot's. + settings.github.pull_request.reviewer = "reviewer-bot".into(); + settings.github.pull_request.submitter = "someone-else".into(); + let error = settings + .validate() + .expect_err("the pull request would be the bot's, not the submitter's"); + assert!(format!("{error:#}").contains("App bot"), "{error:#}"); + + // The submitter's own token makes the pull request the submitter's. + settings.github.pull_request.submitter = "someone-else".into(); + settings.github.pull_request.submitter_token_env = "PC_MATE_GITHUB_TOKEN".into(); + settings + .validate() + .expect("the submitter's own token is enough"); + } } diff --git a/pc-mate/src/domain.rs b/pc-mate/src/domain.rs index 335db129a5..15ffba4fdb 100644 --- a/pc-mate/src/domain.rs +++ b/pc-mate/src/domain.rs @@ -272,7 +272,7 @@ pub fn is_human_login(login: &str) -> bool { !login.ends_with("[bot]") && !login.is_empty() } -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum IntentCategory { BugReport, @@ -291,6 +291,30 @@ impl IntentCategory { Self::Other => "other", } } + + /// The kind a name stands for. + /// + /// A name this build does not know is not an error. The vocabulary is configuration, so a + /// model may answer with an intent the configuration added and this build cannot act on + /// yet; such an intent is `other`, which is what an unknown name is worth here. + pub fn from_name(name: &str) -> Self { + match name.trim() { + "bug_report" => Self::BugReport, + "feature_request" => Self::FeatureRequest, + "question" => Self::Question, + _ => Self::Other, + } + } +} + +impl<'de> Deserialize<'de> for IntentCategory { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = String::deserialize(deserializer)?; + Ok(Self::from_name(&raw)) + } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/pc-mate/src/intent.rs b/pc-mate/src/intent.rs index 85f169252a..b615797849 100644 --- a/pc-mate/src/intent.rs +++ b/pc-mate/src/intent.rs @@ -14,7 +14,7 @@ use anyhow::{anyhow, Result}; -use crate::config::Settings; +use crate::config::{Settings, TriageConfig}; use crate::domain::{InboundEvent, IntentCategory, IntentDecision, IntentMode, IntentVerdict}; use crate::util::{quote_untrusted, truncate_chars}; @@ -55,10 +55,22 @@ pub fn compose_triage_prompt(context: TriageContext<'_>) -> String { String::new(), "## Classification".to_string(), String::new(), - "- `bug_report`: broken behavior, crash, regression, wrong output, error log, or an unexpected edge case in this project.".to_string(), - "- `feature_request`: a new capability, enhancement, configuration option, integration, or ergonomics improvement.".to_string(), - "- `question`: a general usage, setup, configuration, or documentation question that should be answered from the repository and official materials.".to_string(), - "- `other`: chatter, praise, off-topic remarks, spam, or noise.".to_string(), + ]); + // The vocabulary is the configuration's: an intent an operator added is offered here, and an + // intent this build cannot act on yet is answered like `other`. + for intent in &settings.triage.intents { + let name = intent.name.trim(); + if name.is_empty() { + continue; + } + lines.push(format!( + "- `{name}`: {}.", + intent.description.trim().trim_end_matches('.') + )); + } + lines.extend([ + String::new(), + "- Use only the categories listed above. A message that fits none of them is `other`.".to_string(), String::new(), "## Ruling".to_string(), String::new(), @@ -149,7 +161,16 @@ pub fn compose_triage_prompt(context: TriageContext<'_>) -> String { String::new(), "```json".to_string(), "{".to_string(), - " \"category\": \"bug_report\" | \"feature_request\" | \"question\" | \"other\",".to_string(), + format!( + " \"category\": {},", + settings + .triage + .intent_names() + .iter() + .map(|name| format!("\"{name}\"")) + .collect::>() + .join(" | ") + ), " \"decision\": \"implement\" | \"answer\" | \"decline\" | \"needs_info\" | \"duplicate\" | \"ignore\",".to_string(), " \"title\": \"\",".to_string(), " \"priority\": \"high\" | \"medium\" | \"low\",".to_string(), @@ -332,11 +353,32 @@ fn balanced_object(text: &str) -> Option<&str> { None } -pub fn parse_triage_verdict(text: &str, max_reply_chars: usize) -> Result { +pub fn parse_triage_verdict(text: &str, config: &TriageConfig) -> Result { let value = extract_json_value(text)?; + let raw_category = value + .get("category") + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .trim() + .to_string(); let mut verdict: IntentVerdict = serde_json::from_value(value)?; verdict.confidence = verdict.confidence.clamp(0.0, 1.0); + // An intent this build does not act on is answered like `other`. The reason keeps the name + // the model used, so a new intent and a name nobody configured stay apart in the record. + if !raw_category.is_empty() && raw_category != verdict.category.as_str() { + let note = if config.knows_intent(&raw_category) { + format!("the intent `{raw_category}` is not handled yet and was treated as `other`") + } else { + format!("`{raw_category}` is not a configured intent and was treated as `other`") + }; + verdict.reason = if verdict.reason.trim().is_empty() { + note + } else { + format!("{} ({note})", verdict.reason.trim()) + }; + } + if matches!(verdict.category, IntentCategory::Other) { verdict.decision = IntentDecision::Ignore; verdict.reply.clear(); @@ -379,7 +421,7 @@ pub fn parse_triage_verdict(text: &str, max_reply_chars: usize) -> Result String { mod tests { use super::*; + /// A triage configuration with the given reply limit. + fn config(max_reply_chars: usize) -> TriageConfig { + TriageConfig { + max_reply_chars, + ..TriageConfig::default() + } + } + #[test] fn extracts_fenced_json() { let text = "Here it is:\n```json\n{\"category\":\"other\",\"decision\":\"ignore\"}\n```\n"; @@ -450,7 +500,7 @@ mod tests { "reply": "It cuts token use." } ```"#; - let parsed = parse_triage_verdict(text, 4000).unwrap(); + let parsed = parse_triage_verdict(text, &TriageConfig::default()).unwrap(); assert_eq!(parsed.category, IntentCategory::Question); assert_eq!(parsed.decision, IntentDecision::Answer); assert!(parsed.analysis.contains("Fewer tokens")); @@ -459,7 +509,7 @@ mod tests { #[test] fn a_leftover_comma_is_dropped() { let text = r#"{"category":"question","decision":"answer","labels":["question",],}"#; - let parsed = parse_triage_verdict(text, 4000).unwrap(); + let parsed = parse_triage_verdict(text, &TriageConfig::default()).unwrap(); assert_eq!(parsed.decision, IntentDecision::Answer); } @@ -474,7 +524,7 @@ mod tests { fn other_is_always_ignored() { let parsed = parse_triage_verdict( r#"{"category":"other","decision":"implement","reply":"noise"}"#, - 4000, + &config(4000), ) .unwrap(); assert_eq!(parsed.decision, IntentDecision::Ignore); @@ -485,7 +535,7 @@ mod tests { fn question_cannot_implement() { let parsed = parse_triage_verdict( r#"{"category":"question","decision":"implement","reply":"answer"}"#, - 4000, + &config(4000), ) .unwrap(); assert_eq!(parsed.decision, IntentDecision::Answer); @@ -495,7 +545,7 @@ mod tests { fn implement_without_plan_becomes_needs_info() { let parsed = parse_triage_verdict( r#"{"category":"bug_report","decision":"implement","reply":"we will fix it"}"#, - 4000, + &config(4000), ) .unwrap(); assert_eq!(parsed.decision, IntentDecision::NeedsInfo); @@ -505,7 +555,7 @@ mod tests { fn empty_reply_gets_a_fallback() { let parsed = parse_triage_verdict( r#"{"category":"bug_report","decision":"decline","analysis":"not in scope"}"#, - 4000, + &config(4000), ) .unwrap(); assert_eq!(parsed.reply, "not in scope"); @@ -516,7 +566,7 @@ mod tests { fn reply_is_truncated_at_a_character_boundary() { let parsed = parse_triage_verdict( r#"{"category":"question","decision":"answer","reply":"一二三四五"}"#, - 4, + &config(4), ) .unwrap(); assert_eq!(parsed.reply, "一二三…"); @@ -526,13 +576,78 @@ mod tests { fn default_labels_are_derived() { let parsed = parse_triage_verdict( r#"{"category":"feature_request","decision":"duplicate","reply":"see #1"}"#, - 4000, + &config(4000), ) .unwrap(); assert!(parsed.labels.iter().any(|label| label == "enhancement")); assert!(parsed.labels.iter().any(|label| label == "duplicate")); } + #[test] + fn an_intent_the_build_does_not_know_is_answered_like_other() { + // The vocabulary is configuration, so a name this build cannot act on arrives here. + // It is `other`: the message is read and nothing else happens. + let parsed = parse_triage_verdict( + r#"{"category":"performance_regression","decision":"implement","reply":"we will speed it up"}"#, + &config(4000), + ) + .unwrap(); + assert_eq!(parsed.category, IntentCategory::Other); + assert_eq!(parsed.decision, IntentDecision::Ignore); + assert!(parsed.reply.is_empty()); + assert!( + parsed.reason.contains("performance_regression"), + "the record names the intent the model used: {}", + parsed.reason + ); + } + + #[test] + fn a_configured_intent_the_build_does_not_handle_still_names_itself() { + let mut config = config(4000); + config.intents.push(crate::config::IntentSpec { + name: "performance_regression".into(), + description: "a change that made something slower".into(), + }); + let parsed = parse_triage_verdict( + r#"{"category":"performance_regression","decision":"implement","reply":"we will speed it up"}"#, + &config, + ) + .unwrap(); + assert_eq!(parsed.category, IntentCategory::Other); + assert_eq!(parsed.decision, IntentDecision::Ignore); + assert!( + parsed.reason.contains("not handled yet"), + "a configured intent says it is not handled yet: {}", + parsed.reason + ); + } + + #[test] + fn the_prompt_offers_the_configured_intents() { + let trigger = trigger(); + let mut settings = Settings::default(); + settings.triage.intents.push(crate::config::IntentSpec { + name: "performance_regression".into(), + description: "a change that made something slower".into(), + }); + let prompt = compose_triage_prompt(TriageContext { + trigger: &trigger, + settings: &settings, + memory: &[], + site_context: None, + powercontext: None, + }); + assert!( + prompt.contains("- `performance_regression`: a change that made something slower."), + "the prompt offers the configured intent: {prompt}" + ); + assert!( + prompt.contains("\"category\": \"bug_report\" | \"feature_request\" | \"question\" | \"other\" | \"performance_regression\""), + "the output format names the configured intents: {prompt}" + ); + } + fn trigger() -> InboundEvent { InboundEvent::github( "oceanbase/powercontext", diff --git a/pc-mate/src/kernel/entities.rs b/pc-mate/src/kernel/entities.rs index d85ecd35c5..4d947838bc 100644 --- a/pc-mate/src/kernel/entities.rs +++ b/pc-mate/src/kernel/entities.rs @@ -743,6 +743,28 @@ pub struct SendFailure { pub at: DateTime, } +/// The pull request a work_item opened, and the review loop around it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PullRequestState { + /// The number GitHub gave the pull request. + pub number: u64, + /// Where the pull request lives. + pub url: String, + /// The branch the pull request carries. + pub branch: String, + /// How many implementation rounds the pull request has seen. + pub round: u32, + /// What the latest review asked for. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub findings: Vec, + /// The state of the latest review. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub review: Option, + /// When the review is looked at again. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_check_at: Option>, +} + /// The work_item aggregate: an authorized work item with its delegations, channels and inputs. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct WorkItem { @@ -799,6 +821,9 @@ pub struct WorkItem { /// When the work_item should look at itself again. #[serde(default, skip_serializing_if = "Option::is_none")] pub followup_at: Option>, + /// The pull request this work_item opened, when it opened one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pull_request: Option, } impl WorkItem { diff --git a/pc-mate/src/kernel/workitems.rs b/pc-mate/src/kernel/workitems.rs index d284bc2dda..eee7f51d7e 100644 --- a/pc-mate/src/kernel/workitems.rs +++ b/pc-mate/src/kernel/workitems.rs @@ -106,6 +106,7 @@ pub fn create( report: None, reply: None, followup_at: None, + pull_request: None, }; let delegation = new_delegation(&mut work_item); ctx.repo.work_item_save(&work_item)?; diff --git a/pc-mate/src/supervisor/mod.rs b/pc-mate/src/supervisor/mod.rs index 54418cb8d2..634f2a0f91 100644 --- a/pc-mate/src/supervisor/mod.rs +++ b/pc-mate/src/supervisor/mod.rs @@ -28,6 +28,7 @@ pub mod authority; pub mod evidence; pub mod mailbox; pub mod operator; +pub mod pull_request; pub mod reviewer; pub mod storage; @@ -45,7 +46,7 @@ use crate::kernel::contracts::{DeliveryMessage, ReviewOutcome}; use crate::kernel::contracts::{Operator as _, Storage as _}; use crate::kernel::delegations::DelegationReport; use crate::kernel::entities::{ - AuthorityLevel, Delegation, DelegationStage, InboundEvent, RunState, WorkItem, + AuthorityLevel, Delegation, DelegationStage, InboundEvent, PullRequestState, RunState, WorkItem, }; use crate::kernel::ingress::ReceiveResult; use crate::kernel::judgements; @@ -64,6 +65,7 @@ use authority::{AuthorityGate, SCOPE_ANSWER, SCOPE_IMPLEMENT, TRIAGE_RULE}; use evidence::PcMateEvidence; use mailbox::FileMailbox; use operator::{stage_of, WorktreeOperator}; +use pull_request::{GithubPullRequests, PullRequestChannel}; use reviewer::IntentReviewer; use storage::FileStorage; @@ -76,6 +78,8 @@ pub struct TickSummary { pub ran: usize, /// How many work_items were asked to look at themselves again. pub followed_up: usize, + /// How many pull requests were looked at for a review. + pub reviewed: usize, } /// What a dry run of the four-way analysis found. @@ -101,6 +105,7 @@ pub struct Supervisor { reviewer: IntentReviewer, operator: WorktreeOperator, mailbox: FileMailbox, + pull_requests: Arc, } impl Supervisor { @@ -119,6 +124,7 @@ impl Supervisor { reviewer: IntentReviewer::default(), operator: WorktreeOperator::default(), mailbox: FileMailbox::new(state.root()), + pull_requests: Arc::new(GithubPullRequests::new(settings.github.clone())), store, settings, state, @@ -127,6 +133,14 @@ impl Supervisor { } } + /// Use another pull request channel. + /// + /// The loop around a review is tested without a network, so the channel is a seam. + pub fn with_pull_request_channel(mut self, channel: Arc) -> Self { + self.pull_requests = channel; + self + } + /// The pipeline, with the contracts it drives. fn pipeline(&self) -> Pipeline<'_> { Pipeline { @@ -205,6 +219,7 @@ impl Supervisor { summary.assessed = self.assess().await?; summary.ran = self.run().await?; summary.followed_up = self.follow_up().await?; + summary.reviewed = self.check_reviews().await?; Ok(summary) } @@ -287,7 +302,7 @@ impl Supervisor { verdict: &IntentVerdict, ) -> Result<()> { if verdict.category == IntentCategory::Other - || !self.settings.triage.categories.contains(&verdict.category) + || !self.settings.triage.handles(verdict.category) || self.settings.triage.mode == IntentMode::Observe || matches!(verdict.decision, IntentDecision::Ignore) { @@ -404,7 +419,7 @@ impl Supervisor { .await .context("run the triage")?; let text = result.text(); - match parse_triage_verdict(text, self.settings.triage.max_reply_chars) { + match parse_triage_verdict(text, &self.settings.triage) { Ok(verdict) => Ok(verdict), Err(error) => { // The output is written to the log and kept out of the record: the record holds @@ -515,7 +530,7 @@ impl Supervisor { // A category this installation does not act on is not answered at all: the message was // read, and nothing else happened. if verdict.category == IntentCategory::Other - || !self.settings.triage.categories.contains(&verdict.category) + || !self.settings.triage.handles(verdict.category) { return ReviewOutcome::Ignore { reason: format!( @@ -693,6 +708,10 @@ impl Supervisor { &format!("the report could not be recorded: {error:#}"), ); } + // The kernel ends a work item as soon as a run reports that it is done. A pull + // request whose review is still to be read is after that point, so the work item + // stays open until the review is in. + this.keep_open_for_pending_work(&work_item_id); }); } @@ -964,7 +983,20 @@ impl Supervisor { (crate::run_result::CompletionState::Ready, None) => self.answer_of(work_item), _ => None, }; - (report_of(&outcome, answers), outcome) + let mut report = report_of(&outcome, answers); + // The branch is on the remote now, so the pull request of this work can be opened. + if outcome.state == crate::run_result::CompletionState::Ready { + if let Some(pull_request) = self + .publish_pull_request(work_item, &record.branch, &outcome) + .await + { + report.reply_text = Some(format!( + "{}\n\nThe pull request is open: {}", + report.summary, pull_request.url + )); + } + } + (report, outcome) } /// Keep what the run taught the installation. @@ -1177,6 +1209,328 @@ impl Supervisor { Ok(followed) } + /// Keep a work item open while something is still to come. + /// + /// The kernel ends a work item as soon as a run reports that the work is done. A pull + /// request whose review is still to be read, and a re-check the run asked for, are both + /// after that point, so the work item stays open until they are. A work item that a person + /// ended stays ended. + fn keep_open_for_pending_work(&self, work_item_id: &str) { + let Ok(Some(mut work_item)) = self.repo.work_item_get(work_item_id) else { + return; + }; + if work_item.ended.is_none() { + return; + } + if !matches!( + work_item.ended.as_ref().map(|ended| ended.by), + Some(crate::kernel::entities::WorkItemEndBy::Operator) + ) { + return; + } + let review_pending = work_item + .pull_request + .as_ref() + .map(|pull_request| pull_request.review.as_deref() != Some("approved")) + .unwrap_or(false); + if !review_pending && work_item.followup_at.is_none() { + return; + } + work_item.ended = None; + if let Err(error) = self.repo.work_item_save(&work_item) { + let _ = self.state.append_work_item_log( + work_item_id, + &format!("the work item could not be kept open: {error:#}"), + ); + } + } + + // ---- The pull request and the review around it + + /// Whether a finished implementation opens a pull request of its own. + fn pull_request_enabled(&self) -> bool { + self.settings.github.pull_request.enabled + } + + /// Open the pull request of a finished implementation, and ask the reviewer to look at it. + /// + /// The branch is already on the remote: the implementation pushed it before its worktree + /// went away, so the pull request is one API call and the review request another. A work + /// item that already has a pull request keeps it, because the new commit updated it. + async fn publish_pull_request( + &self, + work_item: &WorkItem, + branch: &str, + outcome: &ReviewResult, + ) -> Option { + let config = &self.settings.github.pull_request; + if !config.enabled { + return None; + } + if let Some(existing) = work_item.pull_request.clone() { + // Another round on the same pull request: the findings are worked on, and the + // review of the new commit is read again later. + let mut updated = existing; + updated.findings.clear(); + updated.next_check_at = Some(self.next_review_check()); + if let Err(error) = self.save_pull_request(&work_item.id, updated.clone()) { + let _ = self.state.append_work_item_log( + &work_item.id, + &format!("the pull request could not be recorded: {error:#}"), + ); + } + return Some(updated); + } + let head = self.pull_request_head(branch).await; + let base = match self.pull_request_base().await { + Ok(base) => base, + Err(error) => { + let _ = self.state.append_work_item_log( + &work_item.id, + &format!("the base of the pull request is unknown: {error:#}"), + ); + return None; + } + }; + let title = format!("pc-mate: {}", work_item.title.trim()); + let body = pull_request_body(outcome); + match self.pull_requests.open(&head, &base, &title, &body).await { + Ok(opened) => { + let reviewer = config.reviewer.trim(); + if !reviewer.is_empty() { + if let Err(error) = self + .pull_requests + .request_review(opened.number, &[reviewer.to_string()]) + .await + { + let _ = self.state.append_work_item_log( + &work_item.id, + &format!("the reviewer could not be asked: {error:#}"), + ); + } + } + let state = PullRequestState { + number: opened.number, + url: opened.url, + branch: branch.to_string(), + round: 1, + findings: Vec::new(), + review: None, + next_check_at: Some(self.next_review_check()), + }; + if let Err(error) = self.save_pull_request(&work_item.id, state.clone()) { + let _ = self.state.append_work_item_log( + &work_item.id, + &format!("the pull request could not be recorded: {error:#}"), + ); + } + Some(state) + } + Err(error) => { + let _ = self.state.append_work_item_log( + &work_item.id, + &format!("the pull request could not be opened: {error:#}"), + ); + None + } + } + } + + /// The head of the pull request: the branch, and the account it lives under when that is + /// another account than the repository's. + async fn pull_request_head(&self, branch: &str) -> String { + let owner = + crate::worktree::remote_owner(&self.settings.checkout, &self.settings.git.remote).await; + let repository_owner = self + .settings + .github + .repository + .trim() + .split('/') + .next() + .unwrap_or_default() + .to_string(); + match owner { + Some(owner) + if !owner.is_empty() && !owner.eq_ignore_ascii_case(repository_owner.trim()) => + { + format!("{owner}:{branch}") + } + _ => branch.to_string(), + } + } + + /// The branch the pull request is opened against. + async fn pull_request_base(&self) -> Result { + let configured = self + .settings + .git + .base_branch + .as_deref() + .unwrap_or_default() + .trim() + .to_string(); + if !configured.is_empty() { + return Ok(configured); + } + self.pull_requests.default_branch().await + } + + /// When the review of a pull request is looked at again. + fn next_review_check(&self) -> DateTime { + let seconds = self + .settings + .github + .pull_request + .review_poll_seconds + .max(30); + Utc::now() + ChronoDuration::seconds(seconds as i64) + } + + /// Record the pull request of a work item. + fn save_pull_request(&self, work_item_id: &str, state: PullRequestState) -> Result<()> { + let Some(mut work_item) = self.repo.work_item_get(work_item_id)? else { + return Ok(()); + }; + work_item.pull_request = Some(state); + self.repo.work_item_save(&work_item)?; + Ok(()) + } + + /// Read the reviews of the pull requests that wait for one. + async fn check_reviews(self: &Arc) -> Result { + if !self.pull_request_enabled() { + return Ok(0); + } + let now = Utc::now(); + let due: Vec = self + .repo + .work_item_list() + .unwrap_or_default() + .into_iter() + .filter(|work_item| work_item.is_live()) + .filter(|work_item| { + work_item + .pull_request + .as_ref() + .map(|pull_request| { + pull_request + .next_check_at + .map(|at| at <= now) + .unwrap_or(true) + }) + .unwrap_or(false) + }) + .collect(); + let mut checked = 0; + for work_item in due { + let Some(pull_request) = work_item.pull_request.clone() else { + continue; + }; + checked += 1; + match self.pull_requests.findings(pull_request.number).await { + Ok(findings) => self.handle_review(&work_item, pull_request, findings)?, + Err(error) => { + let _ = self.state.append_work_item_log( + &work_item.id, + &format!("the review could not be read: {error:#}"), + ); + let mut next = pull_request; + next.next_check_at = Some(self.next_review_check()); + let _ = self.save_pull_request(&work_item.id, next); + } + } + } + Ok(checked) + } + + /// What the supervisor does with a review. + /// + /// A review without findings is a verdict: the work is done and the requester is told. A + /// review with findings is a task: the implementation runs again with them, as long as the + /// round budget and the authority of the work item allow it. + fn handle_review( + &self, + work_item: &WorkItem, + mut pull_request: PullRequestState, + findings: crate::channels::github::ReviewFindings, + ) -> Result<()> { + let config = &self.settings.github.pull_request; + pull_request.review = Some(findings.state.clone()); + if findings.findings.is_empty() { + pull_request.findings.clear(); + let approved = findings.state.eq_ignore_ascii_case("approved"); + self.save_pull_request(&work_item.id, pull_request.clone())?; + if approved { + self.answer_requester( + work_item, + format!("The review of {} approved the change.", pull_request.url), + ); + } + return Ok(()); + } + if pull_request.round >= config.max_review_rounds { + // The budget is spent, so the findings are the requester's to act on. + let mut next = pull_request; + next.findings = findings.findings.clone(); + self.save_pull_request(&work_item.id, next.clone())?; + self.answer_requester( + work_item, + format!( + "The review of {} asked for changes, and the round budget is spent:\n\n{}", + next.url, + bullet_list(&next.findings) + ), + ); + return Ok(()); + } + if !matches!( + stage_of(work_item, self.settings.operator.enabled), + DelegationStage::Implement + ) { + // The work item may not write, so the findings are not this installation's to fix. + let mut next = pull_request; + next.findings = findings.findings.clone(); + self.save_pull_request(&work_item.id, next.clone())?; + self.answer_requester( + work_item, + format!( + "The review of {} asked for changes:\n\n{}", + next.url, + bullet_list(&next.findings) + ), + ); + return Ok(()); + } + // Another round: the implementation runs again with the findings. + let mut next = pull_request; + next.round += 1; + next.findings = findings.findings.clone(); + next.next_check_at = Some(self.next_review_check()); + self.save_pull_request(&work_item.id, next.clone())?; + let mut updated = self + .repo + .work_item_get(&work_item.id)? + .unwrap_or_else(|| work_item.clone()); + updated.pull_request = Some(next); + let delegation = crate::kernel::workitems::new_delegation(&mut updated); + self.repo.work_item_save(&updated)?; + self.operator.start(&updated, &delegation); + Ok(()) + } + + /// Answer the person who asked for the work. + fn answer_requester(&self, work_item: &WorkItem, text: String) { + let request = ResponseRequest { + purpose: ResponsePurpose::Result, + work_item_id: Some(work_item.id.clone()), + trigger_id: None, + question: None, + text, + }; + let mut pipeline = self.pipeline(); + let _ = pipeline.reply(&request); + } // ---- The prompts /// The messages that reached the work_item after the one it started from, oldest first. @@ -1340,6 +1694,7 @@ worktree; the shared checkout is not yours to write to. {analysis} {conversation} +{review} ## Operational memory {memory} @@ -1378,6 +1733,7 @@ The file is how your report reaches the requester, so it must be written before text = crate::util::quote_untrusted(&trigger.text, 12_000), analysis = work_item.verdict.analysis, conversation = self.conversation_of(work_item), + review = review_section(work_item), memory = memory_section(memory), powercontext = powercontext_section(prepared), outcome_file = crate::run_result::OUTCOME_FILE, @@ -1421,6 +1777,59 @@ fn powercontext_section(prepared: Option<&str>) -> String { } } +/// The findings of the review of the pull request, for the implementation prompt. +/// +/// An empty section means the run is not a reply to a review, and the prompt says nothing +/// about one. +fn review_section(work_item: &WorkItem) -> String { + let Some(pull_request) = work_item.pull_request.as_ref() else { + return String::new(); + }; + if pull_request.findings.is_empty() { + return String::new(); + } + format!( + "## What the review asked for\n\nThe review of {} asked for the following. Work on these\nfindings, keep the change scoped to them, and say in your report what you did about each\none.\n\n{}\n\n", + pull_request.url, + bullet_list(&pull_request.findings) + ) +} +/// The body of the pull request: what the run did, and how it checked itself. +fn pull_request_body(outcome: &ReviewResult) -> String { + let mut body = String::new(); + if !outcome.summary.trim().is_empty() { + body.push_str("## What the agent did\n\n"); + body.push_str(outcome.summary.trim()); + body.push_str("\n\n"); + } + if !outcome.details.trim().is_empty() { + body.push_str(outcome.details.trim()); + body.push_str("\n\n"); + } + if !outcome.verification.trim().is_empty() { + body.push_str("## Verification\n\n"); + body.push_str(outcome.verification.trim()); + body.push_str("\n\n"); + } + if !outcome.changed_files.is_empty() { + body.push_str("## Files changed\n\n"); + for file in &outcome.changed_files { + body.push_str(&format!("- {file}\n")); + } + body.push('\n'); + } + body.push_str("---\nOpened by pc-mate."); + body +} + +/// The findings of a review, one per line. +fn bullet_list(findings: &[String]) -> String { + findings + .iter() + .map(|finding| format!("- {finding}")) + .collect::>() + .join("\n") +} /// The report an outcome asks for. fn report_of(outcome: &ReviewResult, answers: Option) -> DelegationReport { DelegationReport { @@ -1456,6 +1865,7 @@ pub fn follow_up_at(now: DateTime, seconds: u64) -> DateTime { mod tests { use super::*; use crate::agent_cli::AgentResult; + use crate::channels::github::{OpenedPullRequest, ReviewFindings}; use crate::config::SupervisorConfig; use crate::kernel::entities::InboundEvent; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2263,6 +2673,7 @@ mod tests { report: None, reply: None, followup_at: None, + pull_request: None, }; supervisor .repo @@ -2289,4 +2700,332 @@ mod tests { "a re-check is a new delegation" ); } + /// A pull request channel that answers from a script instead of from GitHub. + struct ScriptedPullRequests { + opened: std::sync::Mutex>, + requested: std::sync::Mutex)>>, + findings: std::sync::Mutex>, + } + + impl ScriptedPullRequests { + fn new(findings: Vec) -> Self { + Self { + opened: std::sync::Mutex::new(Vec::new()), + requested: std::sync::Mutex::new(Vec::new()), + findings: std::sync::Mutex::new(findings), + } + } + } + + #[async_trait::async_trait] + impl PullRequestChannel for ScriptedPullRequests { + async fn open( + &self, + head: &str, + base: &str, + _title: &str, + _body: &str, + ) -> anyhow::Result { + self.opened + .lock() + .unwrap() + .push((head.to_string(), base.to_string())); + Ok(OpenedPullRequest { + number: 7, + url: "https://github.com/oceanbase/powercontext/pull/7".into(), + }) + } + + async fn request_review(&self, number: u64, reviewers: &[String]) -> anyhow::Result<()> { + self.requested + .lock() + .unwrap() + .push((number, reviewers.to_vec())); + Ok(()) + } + + async fn findings(&self, _number: u64) -> anyhow::Result { + let mut findings = self.findings.lock().unwrap(); + if findings.is_empty() { + return Ok(ReviewFindings::default()); + } + Ok(findings.remove(0)) + } + + async fn default_branch(&self) -> anyhow::Result { + Ok("main".into()) + } + } + + fn pull_request_settings(settings: &mut Settings) { + settings.github.pull_request = crate::config::PullRequestConfig { + enabled: true, + submitter: "pc-mate[bot]".into(), + reviewer: "reviewer-bot".into(), + max_review_rounds: 3, + review_poll_seconds: 60, + ..crate::config::PullRequestConfig::default() + }; + } + + fn supervisor_with_pull_requests( + settings: Settings, + channel: Arc, + ) -> Arc { + let settings = Arc::new(settings); + let state = + Arc::new(crate::runtime_state::StateStore::open(settings.state_path()).expect("state")); + let store = Arc::new( + crate::store::Store::open(&settings.state_path().join("state.db")).expect("store"), + ); + let keynotes = Arc::new(crate::keynotes::KeynotesManager::from_settings(&settings)); + Arc::new( + Supervisor::new( + settings, + state, + store, + keynotes, + Arc::new(ScriptedRunner { + calls: AtomicUsize::new(0), + }), + ) + .with_pull_request_channel(channel), + ) + } + + #[tokio::test] + async fn a_finished_implementation_opens_a_pull_request_and_asks_the_reviewer() { + if !git_available() { + return; + } + let (temp, repo, _remote) = seed_repository(); + let mut settings = settings_for(&repo, &temp.path().join("state")); + pull_request_settings(&mut settings); + let channel = Arc::new(ScriptedPullRequests::new(Vec::new())); + let supervisor = supervisor_with_pull_requests(settings, channel.clone()); + + supervisor + .receive(bug_trigger()) + .expect("the message is taken in"); + supervisor.tick().await.expect("the round runs"); + settle(&supervisor).await; + + // The pull request is opened for the branch the implementation pushed. + let opened = channel.opened.lock().unwrap().clone(); + assert_eq!(opened.len(), 1, "the implementation opened a pull request"); + assert!( + opened[0].0.starts_with("pc-mate/"), + "the pull request carries the pushed branch: {opened:?}" + ); + assert_eq!( + opened[0].1, "main", + "the pull request is opened against main" + ); + + // The reviewer is asked, by another account than the submitter. + let requested = channel.requested.lock().unwrap().clone(); + assert_eq!( + requested, + vec![(7, vec!["reviewer-bot".to_string()])], + "the reviewer is asked once" + ); + + // The requester hears about the pull request. + let pending = supervisor.pending_replies(); + assert!( + pending + .iter() + .any(|message| message.text.contains("pull request is open")), + "the person is told about the pull request: {pending:?}" + ); + + // The work item carries the pull request, so the review can be read later. + let work_item = supervisor + .repo + .work_item_list() + .expect("work items") + .pop() + .expect("a work item"); + let pull_request = work_item + .pull_request + .expect("the pull request is recorded"); + assert_eq!(pull_request.number, 7); + assert_eq!(pull_request.round, 1); + } + + #[tokio::test] + async fn a_review_that_asks_for_changes_runs_the_implementation_again() { + if !git_available() { + return; + } + let (temp, repo, _remote) = seed_repository(); + let mut settings = settings_for(&repo, &temp.path().join("state")); + pull_request_settings(&mut settings); + let channel = Arc::new(ScriptedPullRequests::new(vec![ReviewFindings { + state: "changes_requested".into(), + findings: vec!["src/lib.rs:12: the flag is read twice".into()], + }])); + let supervisor = supervisor_with_pull_requests(settings, channel.clone()); + + supervisor + .receive(bug_trigger()) + .expect("the message is taken in"); + supervisor.tick().await.expect("the round runs"); + settle(&supervisor).await; + + // Make the review due, and let the supervisor read it. + let mut work_item = supervisor + .repo + .work_item_list() + .expect("work items") + .pop() + .expect("a work item"); + if let Some(pull_request) = work_item.pull_request.as_mut() { + pull_request.next_check_at = Some(Utc::now() - ChronoDuration::seconds(1)); + } + supervisor + .repo + .work_item_save(&work_item) + .expect("the work item is stored"); + + let checked = supervisor + .check_reviews() + .await + .expect("the review is read"); + assert_eq!(checked, 1, "the review was read"); + + let work_item = supervisor + .repo + .work_item_list() + .expect("work items") + .pop() + .expect("a work item"); + let pull_request = work_item + .pull_request + .expect("the pull request is recorded"); + assert_eq!( + pull_request.round, 2, + "the implementation runs a second time" + ); + assert_eq!( + pull_request.findings, + vec!["src/lib.rs:12: the flag is read twice".to_string()], + "the findings wait for the next run" + ); + assert!( + work_item.delegations.len() >= 2, + "the findings start a new delegation: {:?}", + work_item.delegations.len() + ); + } + + #[tokio::test] + async fn an_approved_review_answers_the_requester() { + if !git_available() { + return; + } + let (temp, repo, _remote) = seed_repository(); + let mut settings = settings_for(&repo, &temp.path().join("state")); + pull_request_settings(&mut settings); + let channel = Arc::new(ScriptedPullRequests::new(vec![ReviewFindings { + state: "approved".into(), + findings: Vec::new(), + }])); + let supervisor = supervisor_with_pull_requests(settings, channel.clone()); + + supervisor + .receive(bug_trigger()) + .expect("the message is taken in"); + supervisor.tick().await.expect("the round runs"); + settle(&supervisor).await; + + let mut work_item = supervisor + .repo + .work_item_list() + .expect("work items") + .pop() + .expect("a work item"); + if let Some(pull_request) = work_item.pull_request.as_mut() { + pull_request.next_check_at = Some(Utc::now() - ChronoDuration::seconds(1)); + } + supervisor + .repo + .work_item_save(&work_item) + .expect("the work item is stored"); + + supervisor + .check_reviews() + .await + .expect("the review is read"); + + let pending = supervisor.pending_replies(); + assert!( + pending + .iter() + .any(|message| message.text.contains("approved the change")), + "the person hears that the review passed: {pending:?}" + ); + } + + #[test] + fn the_prompt_carries_the_findings_of_the_review() { + let work_item = crate::kernel::entities::WorkItem { + id: "work_item-1".to_string(), + title: "Fix startup".to_string(), + decision_id: "decision-1".to_string(), + authority: crate::kernel::entities::Authority { + strength: crate::kernel::entities::AuthorityLevel::Inferred, + policy_version: "test".to_string(), + basis: crate::kernel::entities::AuthorityBasis::Contact { + slot: crate::kernel::entities::ContactSlot::ListedQuiet, + addressed: None, + observation: None, + rules: vec![], + }, + actor: crate::kernel::entities::SenderRef::new("github", "alice"), + scope: SCOPE_ANSWER.to_string(), + }, + channels: Vec::new(), + ended: None, + pending_question: None, + delegations: Vec::new(), + inputs: Vec::new(), + undelivered: Vec::new(), + follows: Vec::new(), + answers: Vec::new(), + created_at: Utc::now(), + updated_at: Utc::now(), + origin: crate::kernel::entities::WorkItemOrigin { + trigger_id: "trigger-1".to_string(), + trigger_ids: vec!["trigger-1".to_string()], + }, + execution: None, + delivery: None, + case_id: "case-1".to_string(), + trigger: bug_trigger(), + verdict: crate::domain::IntentVerdict::default(), + state: crate::domain::WorkItemState::Triaged, + report: None, + reply: None, + followup_at: None, + pull_request: Some(crate::kernel::entities::PullRequestState { + number: 7, + url: "https://github.com/oceanbase/powercontext/pull/7".into(), + branch: "pc-mate/fix-startup".into(), + round: 1, + findings: vec!["src/lib.rs:12: the flag is read twice".into()], + review: Some("changes_requested".into()), + next_check_at: None, + }), + }; + let section = review_section(&work_item); + assert!( + section.contains("## What the review asked for"), + "{section}" + ); + assert!( + section.contains("src/lib.rs:12: the flag is read twice"), + "{section}" + ); + } } diff --git a/pc-mate/src/supervisor/pull_request.rs b/pc-mate/src/supervisor/pull_request.rs new file mode 100644 index 0000000000..22e91a5aaf --- /dev/null +++ b/pc-mate/src/supervisor/pull_request.rs @@ -0,0 +1,87 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The pull request a finished implementation opens, and the review loop around it. +//! +//! A work item that implemented something can end in a pull request of its own: the branch is +//! already on the remote, so the pull request is one API call and one review request. What +//! comes back from that review is read again, and the implementation runs once more with the +//! findings, until the review is satisfied or the round budget is spent. +//! +//! The channel is a trait so that the loop can be tested without a network. What is under +//! test is what pc-mate does with a review, not how GitHub answers one. + +use anyhow::Result; +use async_trait::async_trait; + +use crate::channels::github::{GithubSource, OpenedPullRequest, ReviewFindings}; + +/// What the supervisor needs from GitHub to open a pull request and read its review. +#[async_trait] +pub trait PullRequestChannel: Send + Sync { + /// Open a pull request for a branch that is already on the remote. + async fn open( + &self, + head: &str, + base: &str, + title: &str, + body: &str, + ) -> Result; + /// Ask an account to review the pull request. + async fn request_review(&self, number: u64, reviewers: &[String]) -> Result<()>; + /// What the reviews of the pull request say. + async fn findings(&self, number: u64) -> Result; + /// The branch a pull request is opened against. + async fn default_branch(&self) -> Result; +} + +/// The channel that talks to GitHub. +pub struct GithubPullRequests { + source: GithubSource, +} + +impl GithubPullRequests { + pub fn new(config: crate::config::GithubConfig) -> Self { + Self { + source: GithubSource::new(config), + } + } +} + +#[async_trait] +impl PullRequestChannel for GithubPullRequests { + async fn open( + &self, + head: &str, + base: &str, + title: &str, + body: &str, + ) -> Result { + self.source + .create_pull_request(head, base, title, body) + .await + } + + async fn request_review(&self, number: u64, reviewers: &[String]) -> Result<()> { + self.source.request_reviewers(number, reviewers).await + } + + async fn findings(&self, number: u64) -> Result { + self.source.pull_request_findings(number).await + } + + async fn default_branch(&self) -> Result { + self.source.default_branch().await + } +} diff --git a/pc-mate/src/worktree.rs b/pc-mate/src/worktree.rs index 51ac1f3128..a27ca6e120 100644 --- a/pc-mate/src/worktree.rs +++ b/pc-mate/src/worktree.rs @@ -506,6 +506,54 @@ async fn save_uncommitted(record: &WorktreeRecord, state_dir: &Path) -> Result Option { + let output = run_command( + "git", + &[ + "remote".to_string(), + "get-url".to_string(), + remote.to_string(), + ], + checkout, + None, + None, + GIT_TIMEOUT, + ) + .await + .ok()?; + if !output.success() { + return None; + } + owner_from_url(output.stdout.trim()) +} + +/// The account in a git remote URL. +/// +/// Both shapes are read: `https://github.com/owner/repo` and `git@github.com:owner/repo`. +pub fn owner_from_url(url: &str) -> Option { + let url = url.trim().trim_end_matches('/'); + let url = url.strip_suffix(".git").unwrap_or(url); + let path = if let Some((_, rest)) = url.split_once("://") { + // https://host/owner/repo or ssh://git@host/owner/repo + let rest = rest.split_once('@').map(|(_, rest)| rest).unwrap_or(rest); + rest.split_once('/').map(|(_, path)| path)? + } else if let Some((account, rest)) = url.split_once(':') { + // The ssh form carries the account before the colon: `git@host:owner/repo`. A local + // path has a colon and no account, and names no owner. + if !account.contains('@') { + return None; + } + rest + } else { + return None; + }; + let owner = path.split('/').next()?.trim(); + (!owner.is_empty()).then(|| owner.to_string()) +} async fn resolve_base(checkout: &Path, base_branch: Option<&str>) -> Result { let reference = match base_branch.map(str::trim).filter(|value| !value.is_empty()) { Some(branch) => format!("{branch}^{{commit}}"), @@ -1119,4 +1167,22 @@ mod tests { .unwrap(); String::from_utf8_lossy(&output.stdout).trim().to_string() } + #[test] + fn the_owner_of_a_remote_url_is_read_in_both_shapes() { + assert_eq!( + owner_from_url("https://github.com/oceanbase/powercontext.git"), + Some("oceanbase".to_string()) + ); + assert_eq!( + owner_from_url("git@github.com:oceanbase/powercontext.git"), + Some("oceanbase".to_string()) + ); + assert_eq!( + owner_from_url("ssh://git@github.com/oceanbase/powercontext"), + Some("oceanbase".to_string()) + ); + // A local path names no account. + assert_eq!(owner_from_url("/tmp/remote.git"), None); + assert_eq!(owner_from_url(r"C:\temp\remote.git"), None); + } } From 38264096936cb24834b581a69965cdff0a7c04c2 Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Fri, 4 Dec 2026 22:32:11 +0800 Subject: [PATCH 11/12] chore(pc-mate): log the pull request reviews a round read --- pc-mate/src/app.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pc-mate/src/app.rs b/pc-mate/src/app.rs index 30242b12d2..aada89469e 100644 --- a/pc-mate/src/app.rs +++ b/pc-mate/src/app.rs @@ -237,10 +237,14 @@ impl App { /// starts the re-checks that are due, and sends the responses that were queued. async fn supervisor_tick(&mut self) -> Result<()> { let summary = self.supervisor.tick().await?; - if summary.assessed > 0 || summary.ran > 0 || summary.followed_up > 0 { + if summary.assessed > 0 + || summary.ran > 0 + || summary.followed_up > 0 + || summary.reviewed > 0 + { self.state.append_main_log(&format!( - "supervisor: assessed={} ran={} followed_up={}", - summary.assessed, summary.ran, summary.followed_up + "supervisor: assessed={} ran={} followed_up={} reviewed={}", + summary.assessed, summary.ran, summary.followed_up, summary.reviewed ))?; } self.deliver_pending().await?; From 723c8a1dbff6c0f2c717562666b139191da9e6db Mon Sep 17 00:00:00 2001 From: "Xin.Zh" Date: Sat, 5 Dec 2026 00:19:07 +0800 Subject: [PATCH 12/12] refactor(pc-mate): use one intent vocabulary Remove the unreleased categories filter and use the configured intent vocabulary for routing. Document how GitHub API credentials determine the pull request author. Tested: cargo fmt --all --check, cargo clippy --locked --all-targets -- -D warnings, and 228 passing tests with the Windows loopback timeout test excluded. The full suite reproduces the existing loopback timeout. --- pc-mate/README.md | 14 ++++++++++---- pc-mate/docs/rfc-conformance.md | 2 +- pc-mate/settings.example.yaml | 13 ++++--------- pc-mate/src/app.rs | 7 +++++-- pc-mate/src/config.rs | 33 ++++++--------------------------- 5 files changed, 26 insertions(+), 43 deletions(-) diff --git a/pc-mate/README.md b/pc-mate/README.md index 703bd8eab6..a7e5b0ee7e 100644 --- a/pc-mate/README.md +++ b/pc-mate/README.md @@ -563,10 +563,16 @@ ends at a pull request instead: one API call. The head names the account the branch lives under when that is another account than the repository's, so a branch pushed to a fork opens a pull request from that fork. -- The pull request is written with the submitter's own token when - `github.pullRequest.submitterTokenEnv` names one, and with the GitHub App - installation token otherwise. Without a token of its own, the pull request is - the App bot's, so `submitter` has to be `github.botLogin`. +- GitHub sets the pull request author from the credential used for the API + call. To open the pull request as the GitHub App, set `submitter` to + `github.botLogin` and leave `submitterTokenEnv` empty. pc-mate obtains an + installation token from the configured App. Use `github.writeMode: approved` + and grant the installation `pull_requests: write`. +- To open the pull request as a GitHub user, set `submitter` to that login and + set `submitterTokenEnv` to the name of an environment variable containing a + token for that user with permission to create pull requests on the target + repository. pc-mate reads the token from its environment and also uses it to + request review. Authentication for the earlier Git push comes from Git. - `github.pullRequest.reviewer` is asked to review the pull request. It has to be another account than the submitter: GitHub refuses a review request from the author of a pull request, and a reviewer that is the author is no review diff --git a/pc-mate/docs/rfc-conformance.md b/pc-mate/docs/rfc-conformance.md index aee53920da..a13616ed6c 100644 --- a/pc-mate/docs/rfc-conformance.md +++ b/pc-mate/docs/rfc-conformance.md @@ -53,7 +53,7 @@ says so. Platform behavior that was not exercised is labeled unverified rather t | The outcome file is checked, not trusted | `run_result::read` refuses a file that is not a JSON object or does not match the schema; a run that wrote no file falls back to its own words | `an_outcome_names_what_was_done_and_how_it_was_checked`, `a_file_that_is_not_an_outcome_is_refused`, `a_run_that_wrote_nothing_falls_back_to_its_own_words` | | An accepted request is acknowledged where it was asked | `Supervisor::outcome_of` returns the acknowledgement with the acceptance, and the pipeline addresses it to the conversation the request came from | `the_acknowledgement_of_an_accepted_request_goes_to_the_conversation_it_came_from` | | An assessment that could not run answers nobody | a failed assessment becomes `Unavailable` and is logged; it is not turned into a reply | `a_failed_assessment_answers_nobody` | -| A category the installation does not act on has no side effect | the assessment stops at `Ignore` for a category outside `triage.intents` (or outside the legacy `triage.categories` filter), and nothing is queued | `a_category_outside_the_configured_set_has_no_side_effects` | +| A category the installation does not act on has no side effect | the assessment stops at `Ignore` for a category outside `triage.intents`, and nothing is queued | `a_category_outside_the_configured_set_has_no_side_effects` | | The intent vocabulary is configuration | `triage.intents` names the categories the prompt offers, and a name this build cannot act on is answered like `other` | `an_intent_the_build_does_not_know_is_answered_like_other`, `a_configured_intent_the_build_does_not_handle_still_names_itself`, `the_prompt_offers_the_configured_intents` | | A finished implementation opens a pull request and asks the reviewer | `github.pullRequest.enabled` with a named submitter opens the pull request for the branch that was pushed and asks the reviewer, who has to be another account than the submitter | `a_finished_implementation_opens_a_pull_request_and_asks_the_reviewer`, `the_pull_request_settings_have_to_name_accounts_that_can_act` | | A review that asks for changes runs the implementation again | the findings of a `changes_requested` review go into the next implementation prompt, until the round budget is spent | `a_review_that_asks_for_changes_runs_the_implementation_again`, `the_prompt_carries_the_findings_of_the_review`, `an_approved_review_answers_the_requester` | diff --git a/pc-mate/settings.example.yaml b/pc-mate/settings.example.yaml index 1062ff51fc..7de0c2ac43 100644 --- a/pc-mate/settings.example.yaml +++ b/pc-mate/settings.example.yaml @@ -89,12 +89,11 @@ github: # action that waits for a maintainer. pullRequest: enabled: false - # The account the pull request is opened as. It must differ from the reviewer: GitHub does - # not accept a review request from the author of a pull request. Without a token of its own - # the pull request is the App bot's, so the submitter then has to be `botLogin`. + # The GitHub login expected to open the pull request. It must differ from the reviewer. submitter: "" - # The environment variable holding a token for the submitter account. Empty uses the GitHub - # App installation token, which needs `pull_requests: write` on the installation. + # Optional name of an environment variable holding the submitter's GitHub API token. + # Leave empty to use the GitHub App installation token and set submitter to botLogin. + # The API credential needs pull_requests: write on the target repository. submitterTokenEnv: "" # The account that is asked to review the pull request. Empty opens the pull request without # asking anyone. @@ -166,10 +165,6 @@ triage: description: a general usage, setup, configuration, or documentation question that should be answered from the repository and official materials - name: other description: chatter, praise, off-topic remarks, spam, or noise - # Kept so an existing configuration file still loads. It used to name the intents this - # installation acted on; when it is set, it narrows the intents above to the kinds that are - # acted on. Leave it out to act on every intent above except `other`. - # categories: [bug_report, feature_request] # Kept so an existing configuration file still loads. The supervisor no longer queues a # label, so this switch has no effect. autoLabel: false diff --git a/pc-mate/src/app.rs b/pc-mate/src/app.rs index aada89469e..896eb9f479 100644 --- a/pc-mate/src/app.rs +++ b/pc-mate/src/app.rs @@ -1468,7 +1468,10 @@ mod tests { settings.github.enabled = true; settings.github.allowed = vec!["bob".to_string()]; settings.triage.mode = IntentMode::Response; - settings.triage.categories = Some(vec![crate::domain::IntentCategory::Question]); + settings + .triage + .intents + .retain(|intent| matches!(intent.name.as_str(), "question" | "other")); // Approved writes make an unfiltered reply queue a real action, so this test fails if the // category policy is not applied before the reply path. settings.github.write_mode = crate::config::GithubWriteMode::Approved; @@ -1500,7 +1503,7 @@ mod tests { assert!(processed, "the message is taken in"); app.supervisor_tick().await.unwrap(); - assert_eq!(calls.load(Ordering::SeqCst), 1, "the four-way analysis ran"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "the intent analysis ran"); assert!( app.supervisor.pending_replies().is_empty(), "a category this installation does not act on is not answered" diff --git a/pc-mate/src/config.rs b/pc-mate/src/config.rs index 09659af93a..6cec2a60fe 100644 --- a/pc-mate/src/config.rs +++ b/pc-mate/src/config.rs @@ -327,12 +327,6 @@ pub struct TriageConfig { /// yet is treated like `other`, so a new entry is safe to add before the code that handles /// it exists. pub intents: Vec, - /// Kept so an existing configuration file still loads. - /// - /// It used to name the intents the installation acted on. The list of intents is - /// `intents` now, and this field only narrows it: when it is set, an intent that is not in - /// it is not acted on either. - pub categories: Option>, /// Kept for compatibility. The supervisor replaced the pipeline that queued the label, so /// this switch no longer has an effect. pub auto_label: bool, @@ -353,7 +347,6 @@ impl Default for TriageConfig { enabled: true, mode: IntentMode::Observe, intents: IntentSpec::defaults(), - categories: None, auto_label: false, allow_community: true, max_reply_chars: 4000, @@ -413,29 +406,15 @@ impl TriageConfig { /// Whether this installation acts on a kind of intent. /// - /// A kind is acted on when the classifier may name it and the legacy `categories` filter - /// does not narrow it away. `other` is never acted on: it is the answer for noise. + /// `other` is never acted on: it is the answer for noise. pub fn handles(&self, category: IntentCategory) -> bool { - if matches!(category, IntentCategory::Other) { - return false; - } - if !self - .intents - .iter() - .any(|intent| intent.name.trim() == category.as_str()) - { - return false; - } - match &self.categories { - Some(categories) => categories.contains(&category), - None => true, - } + category != IntentCategory::Other && self.knows_intent(category.as_str()) } - /// Whether the configuration names an intent this build does not know. + /// Whether an intent name is in the configured vocabulary. pub fn knows_intent(&self, name: &str) -> bool { let name = name.trim(); - !name.is_empty() && self.intent_names().contains(&name) + !name.is_empty() && self.intents.iter().any(|intent| intent.name.trim() == name) } } @@ -945,8 +924,8 @@ github: # switch and the submitter account are the authorization. pullRequest: enabled: false - submitter: "" # the account the pull request is opened as - submitterTokenEnv: "" # a token for that account; empty uses the App installation token + submitter: "" # the GitHub login expected to open the pull request + submitterTokenEnv: "" # optional token variable for that login; empty uses the App token reviewer: "" # the account asked to review the pull request maxReviewRounds: 3 reviewPollSeconds: 300