Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / triage.rs

triage.rs1108 lines · 45.2 KiBRaw
1//! Automatic GitHub issue triage (backend half).
2//!
3//! A background poller ([`poll_once`], driven by [`spawn_poller`]) lists new
4//! issues after a `triage_watermark` stored in the `kv` table (first start
5//! stores "now" and triages nothing: no backfill) and queues one
6//! `triage`-kind task per issue. [`drive_triage`] runs the
7//! agent with read-only tools and ends with `finish_triage`; agentd then
8//! applies the result via [`apply_triage`]: it fixes only the type label
9//! (`bug` / `enhancement`) and the app label, and posts the analysis as a
10//! marked comment ([`TRIAGE_MARKER`]).
11//!
12//! Without a GitHub token, [`apply_triage`] records nothing remotely
13//! (`skipped_writes`); the result still lands in the `triage` table for the
14//! UI.
15
16use serde_json::Value;
17
18use crate::github::{GitHub, ALL_APP_LABELS};
19
20/// Hidden marker identifying agentd triage comments (idempotency).
21pub const TRIAGE_MARKER: &str = "<!-- agentd-triage -->";
22/// `kv` key for the poll watermark (RFC3339 UTC).
23pub const WATERMARK_KEY: &str = "triage_watermark";
24/// Issues fetched per poll.
25pub const POLL_PAGE_SIZE: u32 = 50;
26/// Max bytes of `analysis_markdown` accepted from `finish_triage`.
27pub const ANALYSIS_CAP_BYTES: usize = 12 * 1024;
28
29/// Outcome kind of a triage.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum TriageKind {
32 Bug,
33 Feature,
34}
35
36/// Triage confidence.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum TriageConfidence {
39 High,
40 Medium,
41 Low,
42}
43
44/// Validated `finish_triage` arguments.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct TriageResult {
47 pub kind: TriageKind,
48 pub app: String,
49 pub confidence: TriageConfidence,
50 pub analysis_markdown: String,
51 pub duplicate_of: Option<u64>,
52}
53
54/// Validate `finish_triage{type, app, confidence, analysis_markdown,
55/// duplicate_of?}` args. Enums are exact lowercase; `app` must be non-empty;
56/// the analysis is capped at 12 KB.
57pub fn parse_finish_triage(args: &Value) -> Result<TriageResult, String> {
58 let get = |k: &str| {
59 args.get(k)
60 .and_then(|v| v.as_str())
61 .ok_or_else(|| format!("finish_triage: missing or non-string {k:?}"))
62 };
63 let kind = match get("type")? {
64 "bug" => TriageKind::Bug,
65 "feature" => TriageKind::Feature,
66 other => return Err(format!("finish_triage: bad type {other:?}: must be bug|feature")),
67 };
68 let app = get("app")?;
69 if app.trim().is_empty() {
70 return Err("finish_triage: app must be non-empty".to_string());
71 }
72 let confidence = match get("confidence")? {
73 "high" => TriageConfidence::High,
74 "medium" => TriageConfidence::Medium,
75 "low" => TriageConfidence::Low,
76 other => {
77 return Err(format!(
78 "finish_triage: bad confidence {other:?}: must be high|medium|low"
79 ));
80 }
81 };
82 let analysis = get("analysis_markdown")?;
83 if analysis.len() > ANALYSIS_CAP_BYTES {
84 return Err(format!(
85 "finish_triage: analysis_markdown is {} bytes (limit {ANALYSIS_CAP_BYTES})",
86 analysis.len()
87 ));
88 }
89 let duplicate_of = match args.get("duplicate_of") {
90 None | Some(Value::Null) => None,
91 Some(Value::Number(n)) => match n.as_u64() {
92 Some(v) if v > 0 => Some(v),
93 _ => {
94 return Err(
95 "finish_triage: duplicate_of must be a positive issue number".to_string(),
96 );
97 }
98 },
99 Some(other) => {
100 return Err(format!(
101 "finish_triage: duplicate_of must be an issue number, got {other}"
102 ));
103 }
104 };
105 Ok(TriageResult {
106 kind,
107 app: app.trim().to_string(),
108 confidence,
109 analysis_markdown: analysis.to_string(),
110 duplicate_of,
111 })
112}
113
114/// Plan label adds/removes for a triage result.
115///
116/// * Low confidence or an unknown `app` (not in `app_names`) → no changes.
117/// * Type label (`bug` / `enhancement`): exactly the matching one.
118/// * App label (any of `app_names`): exactly the result's app.
119/// * Everything else (version labels, `solved for next release`, ...) is
120/// never added or removed.
121///
122/// Matching is case-insensitive but emitted names are canonical: the `type`
123/// label in lowercase, the app label exactly as listed in `app_names`.
124pub fn plan_label_changes(
125 current: &[String],
126 result: &TriageResult,
127 app_names: &[&str],
128) -> (Vec<String>, Vec<String>) {
129 if result.confidence == TriageConfidence::Low {
130 return (Vec::new(), Vec::new());
131 }
132 let app_canonical = app_names
133 .iter()
134 .find(|a| a.eq_ignore_ascii_case(&result.app))
135 .copied();
136 let Some(app_canonical) = app_canonical else {
137 return (Vec::new(), Vec::new());
138 };
139 let want_type = match result.kind {
140 TriageKind::Bug => "bug",
141 TriageKind::Feature => "enhancement",
142 };
143
144 let has = |name: &str| current.iter().any(|l| l.eq_ignore_ascii_case(name));
145 let is_type = |l: &str| l.eq_ignore_ascii_case("bug") || l.eq_ignore_ascii_case("enhancement");
146 let is_app = |l: &str| app_names.iter().any(|a| a.eq_ignore_ascii_case(l));
147
148 let mut add = Vec::new();
149 let mut remove = Vec::new();
150 if !has(want_type) {
151 add.push(want_type.to_string());
152 }
153 for l in current {
154 if is_type(l) && !l.eq_ignore_ascii_case(want_type) {
155 remove.push(l.clone());
156 }
157 }
158 // Case-insensitive presence: GitHub labels are case-insensitive, so an
159 // existing `Weather` already satisfies `weather` (no churn).
160 if !has(app_canonical) {
161 add.push(app_canonical.to_string());
162 }
163 for l in current {
164 if is_app(l) && !l.eq_ignore_ascii_case(app_canonical) {
165 remove.push(l.clone());
166 }
167 }
168 (add, remove)
169}
170
171/// Render the triage comment: AI-generated header, type/app line, label
172/// summary, analysis section (root-cause for bugs, design suggestions for
173/// features), optional duplicate pointer, then [`TRIAGE_MARKER`].
174pub fn render_comment(result: &TriageResult, add: &[String], remove: &[String]) -> String {
175 let kind_s = match result.kind {
176 TriageKind::Bug => "bug",
177 TriageKind::Feature => "feature",
178 };
179 let conf_s = match result.confidence {
180 TriageConfidence::High => "high",
181 TriageConfidence::Medium => "medium",
182 TriageConfidence::Low => "low",
183 };
184 let mut s = "🤖 **Automated triage** (AI-generated; may be wrong)\n\n".to_string();
185 s.push_str(&format!(
186 "Type: {kind_s} · App: {} · Confidence: {conf_s}\n\n",
187 result.app
188 ));
189 if add.is_empty() && remove.is_empty() {
190 if result.confidence == TriageConfidence::Low {
191 s.push_str("Labels left unchanged (low confidence).\n\n");
192 } else {
193 s.push_str("Labels already correct.\n\n");
194 }
195 } else {
196 let mut parts: Vec<String> = add.iter().map(|l| format!("+{l}")).collect();
197 parts.extend(remove.iter().map(|l| format!("−{l}")));
198 s.push_str(&format!("Labels updated: {}\n\n", parts.join(" ")));
199 }
200 match result.kind {
201 TriageKind::Bug => s.push_str("### Root cause analysis\n\n"),
202 TriageKind::Feature => s.push_str("### Design suggestions\n\n"),
203 }
204 s.push_str(&result.analysis_markdown);
205 if !result.analysis_markdown.ends_with('\n') {
206 s.push('\n');
207 }
208 if let Some(n) = result.duplicate_of {
209 s.push_str(&format!("\nPossible duplicate of #{n}.\n"));
210 }
211 s.push_str(&format!("\n{TRIAGE_MARKER}\n"));
212 s
213}
214
215/// Outcome of [`apply_triage`].
216#[derive(Debug, Clone)]
217pub struct ApplyOutcome {
218 pub labels_added: Vec<String>,
219 pub labels_removed: Vec<String>,
220 pub comment_url: Option<String>,
221 pub skipped_writes: bool,
222 pub error: Option<String>,
223}
224
225/// Apply a triage result to an issue: re-fetch labels, plan changes, remove
226/// wrong labels one by one, add correct ones in one call, then post the
227/// marked comment. Without a token nothing is sent (`skipped_writes`).
228/// Failures are captured in `error`, never raised.
229pub async fn apply_triage(gh: &GitHub, issue: u64, result: &TriageResult) -> ApplyOutcome {
230 let mut out = ApplyOutcome {
231 labels_added: Vec::new(),
232 labels_removed: Vec::new(),
233 comment_url: None,
234 skipped_writes: false,
235 error: None,
236 };
237 if !gh.has_token() {
238 out.skipped_writes = true;
239 return out;
240 }
241 let current = match gh.read_issue(issue).await {
242 Ok(full) => full.labels,
243 Err(e) => {
244 out.error = Some(format!("triage: re-reading issue #{issue} failed: {e}"));
245 return out;
246 }
247 };
248 let (add, remove) = plan_label_changes(&current, result, ALL_APP_LABELS);
249 for name in &remove {
250 if let Err(e) = gh.remove_label(issue, name).await {
251 out.error = Some(format!("triage: removing label {name:?} on #{issue} failed: {e}"));
252 return out;
253 }
254 out.labels_removed.push(name.clone());
255 }
256 if !add.is_empty() {
257 if let Err(e) = gh.add_labels(issue, &add).await {
258 out.error = Some(format!("triage: adding labels on #{issue} failed: {e}"));
259 return out;
260 }
261 out.labels_added = add.clone();
262 }
263 let body = render_comment(result, &add, &remove);
264 match gh.post_comment(issue, &body).await {
265 Ok(url) => out.comment_url = Some(url),
266 Err(e) => out.error = Some(format!("triage: commenting on #{issue} failed: {e}")),
267 }
268 out
269}
270
271/// Current UTC time as RFC3339 `Z` (seconds precision).
272fn now_rfc3339_utc() -> String {
273 let secs = std::time::SystemTime::now()
274 .duration_since(std::time::UNIX_EPOCH)
275 .map(|d| d.as_secs())
276 .unwrap_or(0);
277 // Days → civil date (Howard Hinnant's algorithm), then HMS.
278 let days = (secs / 86_400) as i64;
279 let secs_of_day = (secs % 86_400) as i64;
280 let z = days + 719_468;
281 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
282 let doe = (z - era * 146_097) as u64;
283 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
284 let y = yoe as i64 + era * 400;
285 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
286 let mp = (5 * doy + 2) / 153;
287 let d = (doy - (153 * mp + 2) / 5 + 1) as i64;
288 let m = if mp < 10 { mp as i64 + 3 } else { mp as i64 - 9 };
289 let y = if m <= 2 { y + 1 } else { y };
290 format!(
291 "{y:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
292 m,
293 d,
294 secs_of_day / 3_600,
295 (secs_of_day % 3_600) / 60,
296 secs_of_day % 60
297 )
298}
299
300/// One poll: list issues newer than the watermark and queue a triage task per
301/// untriaged one. First start stores "now" and queues nothing (no backfill).
302/// Returns the number of tasks queued.
303pub async fn poll_once(ctx: &crate::agent::DriverCtx) -> Result<usize, String> {
304 let gh = crate::issues::github_client(&ctx.config).map_err(|e| e.to_string())?;
305 let watermark = ctx.store.kv_get(WATERMARK_KEY)?;
306 let Some(watermark) = watermark else {
307 ctx.store.kv_set(WATERMARK_KEY, &now_rfc3339_utc())?;
308 return Ok(0);
309 };
310 let issues = gh
311 .list_issues_since(&watermark, POLL_PAGE_SIZE)
312 .await
313 .map_err(|e| e.to_string())?;
314 let mut queued = 0;
315 let mut max_created = watermark.clone();
316 for summary in &issues {
317 if crate::github::normalize_rfc3339(&summary.created_at) > max_created {
318 max_created = summary.created_at.clone();
319 }
320 if ctx.store.triage_get(summary.number)?.is_some() {
321 continue;
322 }
323 if gh
324 .issue_has_marker(summary.number, TRIAGE_MARKER)
325 .await
326 .map_err(|e| e.to_string())?
327 {
328 continue;
329 }
330 // Prompt content is informational; [`drive_triage`]
331 // re-reads the issue and runs `finish_triage`. The issue number is
332 // stored on the row so the worker can find it.
333 let title = format!("#{} {}", summary.number, summary.title);
334 let title: String = if title.chars().count() > 80 {
335 title.chars().take(80).collect()
336 } else {
337 title
338 };
339 let module = crate::github::app_module_for_labels(&summary.labels).unwrap_or_default();
340 let prompt = format!(
341 "Triage GitHub issue #{}: {}\nLabels: {}\n\nRead the issue via github_read_issue, investigate the repo read-only, then end with finish_triage.",
342 summary.number,
343 summary.title,
344 if summary.labels.is_empty() {
345 "(none)".to_string()
346 } else {
347 summary.labels.join(", ")
348 },
349 );
350 let model = ctx.config.default_model.clone();
351 let task_id = ctx.store.create_triage_task(
352 summary.number,
353 &title,
354 &prompt,
355 &module,
356 &model,
357 )?;
358 if ctx.store.triage_insert(summary.number, task_id)? {
359 queued += 1;
360 }
361 }
362 if max_created > watermark {
363 ctx.store.kv_set(WATERMARK_KEY, &max_created)?;
364 }
365 Ok(queued)
366}
367
368/// Tools a triage task may call: read-only repo + history + issues, plus the
369/// terminal `finish_triage`. Everything else is refused.
370pub const TRIAGE_TOOLS: &[&str] = &[
371 "read_file",
372 "list_dir",
373 "search",
374 "find_files",
375 "git_log",
376 "git_show",
377 "git_blame",
378 "github_read_issue",
379 "github_search_issues",
380 "finish_triage",
381];
382
383fn finish_triage_def() -> crate::openrouter::ToolDef {
384 crate::openrouter::ToolDef {
385 kind: "function",
386 function: crate::openrouter::FunctionDef {
387 name: "finish_triage",
388 description: "Submit the triage result. Must be the ONLY tool call in its turn. agentd fixes the issue's type and app labels (unless confidence is low) and posts analysis_markdown as a comment.",
389 parameters: serde_json::json!({
390 "type": "object",
391 "properties": {
392 "type": {"type": "string", "enum": ["bug", "feature"]},
393 "app": {"type": "string", "description": "App label, e.g. weather, logicgate"},
394 "confidence": {"type": "string", "enum": ["high", "medium", "low"]},
395 "analysis_markdown": {"type": "string", "description": "Root cause analysis (bug) or design suggestions (feature), markdown, <= ~500 words"},
396 "duplicate_of": {"type": "integer", "description": "Issue number this duplicates (optional)"}
397 },
398 "required": ["type", "app", "confidence", "analysis_markdown"],
399 "additionalProperties": false,
400 }),
401 },
402 }
403}
404
405fn triage_tool_defs() -> Vec<crate::openrouter::ToolDef> {
406 let mut defs: Vec<_> = crate::openrouter::tool_defs()
407 .into_iter()
408 .filter(|d| TRIAGE_TOOLS.contains(&d.function.name))
409 .collect();
410 defs.push(finish_triage_def());
411 defs
412}
413
414fn triage_system_prompt(issue_text: &str, root_rules: Option<&str>, module_rules: Option<&str>) -> String {
415 format!(
416 r#"You triage GitHub issues for the Modern-Apps monorepo (Android apps in Kotlin plus Rust). You have READ-ONLY tools over a checkout of `main`: read_file, list_dir, search, find_files, git_log, git_show, git_blame, github_read_issue, github_search_issues. You cannot edit, build or run anything.
417
418Your job for the issue below:
4191. Decide the type: `bug` (something broken) or `feature` (a request for new or changed behaviour). The issue title usually starts with `[bug]:` or `[feat]:`, but judge from the body; reporters pick the wrong one sometimes.
4202. Decide the app. The issue form's `### App Name` section is a hint, not proof. Valid app labels: {apps}.
4213. Investigate the relevant code (start at the app's module dir; read its AGENTS.md if useful; keep it focused).
4224. Write a concise analysis in markdown (<= ~500 words):
423 - bug: a root cause analysis — the most likely cause with `path/File.kt:line` references, why it produces the reported behaviour, and how to verify and fix it.
424 - feature: design suggestions — affected modules/files, a concrete approach, UX and edge cases, risks.
425 Be honest: if you could not pin it down, say what you checked and what is uncertain, and use confidence `low`.
4265. Optionally use github_search_issues to spot an obvious duplicate.
4276. End by calling `finish_triage` ALONE in its turn.
428
429Repo rules (root AGENTS.md, for context):
430```
431{root}
432```
433
434App module rules:
435```
436{module}
437```
438
439The issue:
440{issue}
441"#,
442 apps = ALL_APP_LABELS.join(", "),
443 root = root_rules.unwrap_or("(unavailable)"),
444 module = module_rules.unwrap_or("(none)"),
445 issue = issue_text,
446 )
447}
448
449fn summarize(result: &TriageResult, out: &ApplyOutcome) -> String {
450 let kind = match result.kind {
451 TriageKind::Bug => "bug",
452 TriageKind::Feature => "feature",
453 };
454 let mut labels: Vec<String> = out.labels_added.iter().map(|l| format!("+{l}")).collect();
455 labels.extend(out.labels_removed.iter().map(|l| format!("−{l}")));
456 let labels = if labels.is_empty() { "labels unchanged".to_string() } else { format!("labels {}", labels.join(" ")) };
457 let comment = if out.comment_url.is_some() {
458 "commented"
459 } else if out.skipped_writes {
460 "no token: GitHub not updated"
461 } else {
462 "comment failed"
463 };
464 format!("{kind} · {} · {labels} · {comment}", result.app)
465}
466
467/// Drive one triage task: prepare a read-only checkout of `main`, run the
468/// model with [`TRIAGE_TOOLS`] until it calls `finish_triage`, then apply the
469/// result to GitHub. Unattended: text-only turns get one nudge, then fail;
470/// budget exhaustion fails. Never parks, never edits, never pushes.
471pub async fn drive_triage(
472 ctx: &crate::agent::DriverCtx,
473 task: &crate::models::Task,
474 slot: u32,
475 branch: &str,
476) -> crate::agent::TaskOutcome {
477 use crate::agent::{append_persisted, dispatch_tool, fail, trimmed_clone, ToolEffect};
478 use crate::models::{EVENT_ASSISTANT, EVENT_STATUS, EVENT_TOOL_RESULT, TaskStatus};
479 use crate::openrouter::Message;
480
481 let task_id = task.id;
482 let Some(issue_number) = task.issue_number else {
483 return fail(ctx, task_id, "triage task has no issue number").await;
484 };
485 let issue_number = issue_number as u64;
486 if let Err(e) = crate::git::fetch_main(&ctx.config.mirror_dir).await {
487 return fail(ctx, task_id, &format!("mirror fetch failed: {e}")).await;
488 }
489 if let Err(e) = ctx.runner.prepare(slot, branch).await {
490 return fail(ctx, task_id, &format!("runner prepare: {e}")).await;
491 }
492 let gh = match crate::issues::github_client(&ctx.config) {
493 Ok(g) => g,
494 Err(e) => return fail(ctx, task_id, &format!("github client: {e}")).await,
495 };
496 let issue_text = match gh.read_issue(issue_number).await {
497 Ok(issue) => crate::github::render_issue_for_model(&issue),
498 Err(e) => return fail(ctx, task_id, &format!("read issue #{issue_number}: {e}")).await,
499 };
500 let (root, module) =
501 crate::rules::load_session_rules(ctx, task_id, slot, &task.module_scope).await;
502 let system = triage_system_prompt(&issue_text, root.as_deref(), module.as_deref());
503 let mut messages = vec![Message::system(system)];
504 append_persisted(ctx, task_id, &mut messages, Message::user(format!("Triage issue #{issue_number}.")));
505 let tools = triage_tool_defs();
506 // Read tools see the whole repo: "" is the repo-wide scope.
507 let scope = "";
508 let mut nudged = false;
509
510 loop {
511 let cur = match ctx.store.get_task(task_id).ok().flatten() {
512 Some(t) => t,
513 None => return fail(ctx, task_id, "task row vanished").await,
514 };
515 if cur.stop_requested || cur.status == TaskStatus::Discarded {
516 return fail(ctx, task_id, "triage stopped by operator").await;
517 }
518 if cur.steps >= cur.budget_steps || cur.cost_usd >= cur.budget_usd {
519 let _ = ctx.store.triage_set_result(issue_number, "failed", None);
520 return fail(ctx, task_id, "triage budget exhausted").await;
521 }
522 let send = trimmed_clone(&messages, ctx.config.context_chars());
523 let turn = match ctx.openrouter.chat(&task.model, &send, &tools).await {
524 Ok(t) => t,
525 Err(e) => {
526 let _ = ctx.store.triage_set_result(issue_number, "failed", None);
527 return fail(ctx, task_id, &format!("OpenRouter: {e}")).await;
528 }
529 };
530 let _ = ctx.store.add_usage(task_id, 1, turn.usage.prompt_tokens, turn.usage.completion_tokens, turn.usage.cost_usd());
531 ctx.emit(task_id, EVENT_ASSISTANT, serde_json::json!({
532 "text": crate::agent::scrub_secrets(&turn.text),
533 "prompt_tokens": turn.usage.prompt_tokens,
534 "completion_tokens": turn.usage.completion_tokens,
535 "cost_usd": turn.usage.cost_usd(),
536 }));
537 append_persisted(ctx, task_id, &mut messages, Message::assistant_calls(
538 if turn.text.is_empty() { None } else { Some(turn.text.clone()) },
539 turn.tool_calls.clone(),
540 ));
541 if turn.tool_calls.is_empty() {
542 if nudged {
543 let _ = ctx.store.triage_set_result(issue_number, "failed", None);
544 return fail(ctx, task_id, "triage ended without finish_triage").await;
545 }
546 nudged = true;
547 append_persisted(ctx, task_id, &mut messages, Message::user(
548 "Keep going with the read-only tools, then call finish_triage alone.".to_string(),
549 ));
550 continue;
551 }
552 let sole = turn.tool_calls.len() == 1;
553 for call in &turn.tool_calls {
554 let name = call.function.name.as_str();
555 let result = if name == "finish_triage" {
556 if !sole {
557 "finish_triage must be the only call in its turn; re-issue it alone.".to_string()
558 } else {
559 let args: Value = serde_json::from_str(&call.function.arguments).unwrap_or(Value::Null);
560 match parse_finish_triage(&args) {
561 Err(e) => format!("finish_triage rejected: {e}"),
562 Ok(result) => {
563 let out = apply_triage(&gh, issue_number, &result).await;
564 let summary = summarize(&result, &out);
565 if let Some(err) = &out.error {
566 ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": format!("triage GitHub update error: {err}")}));
567 }
568 let record = serde_json::json!({
569 "type": match result.kind { TriageKind::Bug => "bug", TriageKind::Feature => "feature" },
570 "app": result.app,
571 "confidence": match result.confidence { TriageConfidence::High => "high", TriageConfidence::Medium => "medium", TriageConfidence::Low => "low" },
572 "labels_added": out.labels_added,
573 "labels_removed": out.labels_removed,
574 "comment_url": out.comment_url,
575 "skipped_writes": out.skipped_writes,
576 "error": out.error,
577 "duplicate_of": result.duplicate_of,
578 });
579 let status = if out.error.is_some() { "failed" } else { "done" };
580 let _ = ctx.store.triage_set_result(issue_number, status, Some(&record.to_string()));
581 append_persisted(ctx, task_id, &mut messages, Message::tool_result(call.id.clone(), "submitted".to_string()));
582 ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": format!("triage: {summary}")}));
583 let _ = ctx.store.update_status(task_id, TaskStatus::Succeeded, None, Some(&summary));
584 return crate::agent::TaskOutcome::Parked;
585 }
586 }
587 }
588 } else if TRIAGE_TOOLS.contains(&name) {
589 match dispatch_tool(ctx, task_id, slot, scope, call).await {
590 ToolEffect::Continue { result_for_model } => {
591 append_persisted(ctx, task_id, &mut messages, Message::tool_result(call.id.clone(), result_for_model));
592 continue;
593 }
594 ToolEffect::ReviewRequest { .. } => "not available during triage".to_string(),
595 }
596 } else {
597 format!("{name} is not available during triage (read-only tools and finish_triage only)")
598 };
599 ctx.emit(task_id, EVENT_TOOL_RESULT, serde_json::json!({"name": name, "truncated": false, "result": result}));
600 append_persisted(ctx, task_id, &mut messages, Message::tool_result(call.id.clone(), result));
601 }
602 }
603}
604
605/// Spawn the background triage poller. `AGENTD_TRIAGE=0` disables it;
606/// `AGENTD_TRIAGE_INTERVAL_SECS` sets the period (default 120s). Errors are
607/// logged and retried on the next tick.
608pub fn spawn_poller(ctx: crate::agent::DriverCtx) -> tokio::task::JoinHandle<()> {
609 tokio::spawn(async move {
610 if !ctx.config.triage_enabled {
611 tracing::info!("triage poller disabled (AGENTD_TRIAGE=0)");
612 return;
613 }
614 let interval = ctx.config.triage_interval_secs;
615 tracing::info!("triage poller starting (every {interval}s)");
616 loop {
617 match poll_once(&ctx).await {
618 Ok(0) => {}
619 Ok(n) => tracing::info!("triage poller queued {n} task(s)"),
620 Err(e) => tracing::warn!("triage poll: {e} (retrying next tick)"),
621 }
622 tokio::time::sleep(std::time::Duration::from_secs(interval)).await;
623 }
624 })
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630
631 fn bug_weather_high() -> TriageResult {
632 TriageResult {
633 kind: TriageKind::Bug,
634 app: "weather".to_string(),
635 confidence: TriageConfidence::High,
636 analysis_markdown: "The widget reads the wrong field.".to_string(),
637 duplicate_of: None,
638 }
639 }
640
641 fn result(kind: TriageKind, app: &str, conf: TriageConfidence) -> TriageResult {
642 TriageResult {
643 kind,
644 app: app.to_string(),
645 confidence: conf,
646 analysis_markdown: "analysis".to_string(),
647 duplicate_of: None,
648 }
649 }
650
651 fn apps() -> Vec<&'static str> {
652 vec!["weather", "notes", "chess"]
653 }
654
655 fn s(v: &[&str]) -> Vec<String> {
656 v.iter().map(|x| x.to_string()).collect()
657 }
658
659 // ---- parse_finish_triage ----
660
661 fn args(kind: &str, app: &str, conf: &str) -> Value {
662 serde_json::json!({
663 "type": kind, "app": app, "confidence": conf,
664 "analysis_markdown": "some analysis",
665 })
666 }
667
668 #[test]
669 fn parse_accepts_bug_and_feature() {
670 let r = parse_finish_triage(&args("bug", "weather", "high")).unwrap();
671 assert_eq!(r.kind, TriageKind::Bug);
672 assert_eq!(r.app, "weather");
673 assert_eq!(r.confidence, TriageConfidence::High);
674 assert_eq!(r.analysis_markdown, "some analysis");
675 assert_eq!(r.duplicate_of, None);
676
677 let mut a = args("feature", "notes", "medium");
678 a["duplicate_of"] = serde_json::json!(123);
679 let r = parse_finish_triage(&a).unwrap();
680 assert_eq!(r.kind, TriageKind::Feature);
681 assert_eq!(r.duplicate_of, Some(123));
682 // App is trimmed.
683 let r = parse_finish_triage(&args("bug", " chess ", "low")).unwrap();
684 assert_eq!(r.app, "chess");
685 }
686
687 #[test]
688 fn parse_rejects_bad_enums_and_shapes() {
689 assert!(parse_finish_triage(&args("BUG", "weather", "high")).is_err());
690 assert!(parse_finish_triage(&args("task", "weather", "high")).is_err());
691 assert!(parse_finish_triage(&args("bug", "weather", "HIGH")).is_err());
692 assert!(parse_finish_triage(&args("bug", "weather", "maybe")).is_err());
693 assert!(parse_finish_triage(&args("bug", "", "high")).is_err());
694 assert!(parse_finish_triage(&args("bug", " ", "high")).is_err());
695 // Missing keys.
696 assert!(parse_finish_triage(&serde_json::json!({"type": "bug"})).is_err());
697 // Non-string type.
698 assert!(parse_finish_triage(&serde_json::json!(
699 {"type": 1, "app": "w", "confidence": "high", "analysis_markdown": "a"}
700 ))
701 .is_err());
702 // Oversize analysis.
703 let mut a = args("bug", "weather", "high");
704 a["analysis_markdown"] = Value::String("x".repeat(ANALYSIS_CAP_BYTES + 1));
705 assert!(parse_finish_triage(&a).is_err());
706 let mut a = args("bug", "weather", "high");
707 a["analysis_markdown"] = Value::String("x".repeat(ANALYSIS_CAP_BYTES));
708 assert!(parse_finish_triage(&a).is_ok());
709 // Bad duplicate_of.
710 for dup in [
711 serde_json::json!(0),
712 serde_json::json!(-5),
713 serde_json::json!("12"),
714 serde_json::json!(1.5),
715 ] {
716 let mut a = args("bug", "weather", "high");
717 a["duplicate_of"] = dup;
718 assert!(parse_finish_triage(&a).is_err(), "dup={}", a["duplicate_of"]);
719 }
720 }
721
722 // ---- plan_label_changes ----
723
724 #[test]
725 fn plan_fixes_type_and_app_labels() {
726 let (add, remove) = plan_label_changes(&s(&["enhancement", "notes"]), &bug_weather_high(), &apps());
727 assert_eq!(add, s(&["bug", "weather"]));
728 assert_eq!(remove, s(&["enhancement", "notes"]));
729 }
730
731 #[test]
732 fn plan_already_correct_is_noop() {
733 let (add, remove) =
734 plan_label_changes(&s(&["bug", "weather"]), &bug_weather_high(), &apps());
735 assert!(add.is_empty() && remove.is_empty());
736 // Extra non-type/non-app labels don't trigger changes either.
737 let (add, remove) = plan_label_changes(
738 &s(&["bug", "weather", "2.6.12", "solved for next release"]),
739 &bug_weather_high(),
740 &apps(),
741 );
742 assert!(add.is_empty() && remove.is_empty());
743 }
744
745 #[test]
746 fn plan_never_touches_versions_or_solved() {
747 let (add, remove) = plan_label_changes(
748 &s(&["enhancement", "notes", "2.6.12", "solved for next release"]),
749 &bug_weather_high(),
750 &apps(),
751 );
752 assert_eq!(add, s(&["bug", "weather"]));
753 assert_eq!(remove, s(&["enhancement", "notes"]));
754 assert!(!add.iter().chain(remove.iter()).any(|l| l == "2.6.12" || l == "solved for next release"));
755 }
756
757 #[test]
758 fn plan_low_confidence_or_unknown_app_is_noop() {
759 let low = result(TriageKind::Bug, "weather", TriageConfidence::Low);
760 let (add, remove) = plan_label_changes(&s(&["enhancement", "notes"]), &low, &apps());
761 assert!(add.is_empty() && remove.is_empty());
762
763 let unknown = result(TriageKind::Bug, "notanapp", TriageConfidence::High);
764 let (add, remove) =
765 plan_label_changes(&s(&["enhancement", "notes"]), &unknown, &apps());
766 assert!(add.is_empty() && remove.is_empty());
767 }
768
769 #[test]
770 fn plan_case_handling() {
771 // Current labels in odd case still match; emitted names are canonical.
772 let (add, remove) =
773 plan_label_changes(&s(&["BUG", "Weather"]), &bug_weather_high(), &apps());
774 assert!(add.is_empty(), "add={add:?}");
775 assert!(remove.is_empty(), "remove={remove:?}");
776
777 let (add, remove) =
778 plan_label_changes(&s(&["ENHANCEMENT", "NoTeS"]), &bug_weather_high(), &apps());
779 assert_eq!(add, s(&["bug", "weather"]));
780 assert_eq!(remove, s(&["ENHANCEMENT", "NoTeS"]));
781
782 // Result app in odd case resolves to the canonical app_names entry.
783 let mixed = result(TriageKind::Feature, "WeAtHeR", TriageConfidence::High);
784 let (add, remove) = plan_label_changes(&s(&["bug", "notes"]), &mixed, &apps());
785 assert_eq!(add, s(&["enhancement", "weather"]));
786 assert_eq!(remove, s(&["bug", "notes"]));
787 }
788
789 #[test]
790 fn plan_feature_wants_enhancement() {
791 let feat = result(TriageKind::Feature, "notes", TriageConfidence::Medium);
792 let (add, remove) = plan_label_changes(&s(&["bug"]), &feat, &apps());
793 assert_eq!(add, s(&["enhancement", "notes"]));
794 assert_eq!(remove, s(&["bug"]));
795 }
796
797 #[test]
798 fn plan_missing_only_one_side() {
799 // Right type, wrong app: only the app changes.
800 let (add, remove) =
801 plan_label_changes(&s(&["bug", "notes"]), &bug_weather_high(), &apps());
802 assert_eq!(add, s(&["weather"]));
803 assert_eq!(remove, s(&["notes"]));
804 // Right app, wrong type: only the type changes.
805 let (add, remove) =
806 plan_label_changes(&s(&["enhancement", "weather"]), &bug_weather_high(), &apps());
807 assert_eq!(add, s(&["bug"]));
808 assert_eq!(remove, s(&["enhancement"]));
809 }
810
811 // ---- render_comment ----
812
813 #[test]
814 fn render_comment_shapes() {
815 let body = render_comment(
816 &bug_weather_high(),
817 &["bug".to_string(), "weather".to_string()],
818 &["enhancement".to_string(), "notes".to_string()],
819 );
820 assert!(body.contains("🤖 **Automated triage** (AI-generated; may be wrong)"), "{body}");
821 assert!(body.contains("Type: bug · App: weather"), "{body}");
822 assert!(body.contains("Labels updated: +bug +weather −enhancement −notes"), "{body}");
823 assert!(body.contains("### Root cause analysis"), "{body}");
824 assert!(body.contains("The widget reads the wrong field."), "{body}");
825 assert!(!body.contains("Possible duplicate"), "{body}");
826 assert!(body.contains(TRIAGE_MARKER), "{body}");
827 assert!(body.trim_end().ends_with(TRIAGE_MARKER), "{body}");
828 }
829
830 #[test]
831 fn render_comment_variants() {
832 // Feature → design suggestions + duplicate pointer.
833 let mut feat = result(TriageKind::Feature, "notes", TriageConfidence::Medium);
834 feat.analysis_markdown = "Consider a sidebar.".to_string();
835 feat.duplicate_of = Some(42);
836 let body = render_comment(&feat, &[], &[]);
837 assert!(body.contains("### Design suggestions"), "{body}");
838 assert!(body.contains("Possible duplicate of #42"), "{body}");
839 assert!(body.contains("Labels already correct."), "{body}");
840
841 // Low confidence → unchanged note.
842 let low = result(TriageKind::Bug, "weather", TriageConfidence::Low);
843 let body = render_comment(&low, &[], &[]);
844 assert!(body.contains("Labels left unchanged (low confidence)."), "{body}");
845 assert!(!body.contains("Labels already correct."), "{body}");
846 }
847
848 // ---- apply_triage + poll_once (mock GitHub) ----
849
850 #[derive(Debug, Clone)]
851 struct Recorded {
852 method: String,
853 path: String,
854 body: Vec<u8>,
855 }
856
857 #[derive(Clone, Default)]
858 struct Mock {
859 recorded: std::sync::Arc<std::sync::Mutex<Vec<Recorded>>>,
860 responses: std::sync::Arc<std::sync::Mutex<Responses>>,
861 }
862
863 /// Mock path → (status, body).
864 type Responses = std::collections::HashMap<String, (u16, Vec<u8>)>;
865
866 impl Mock {
867 fn respond(&self, path: &str, status: u16, body: impl Into<Vec<u8>>) {
868 self.responses
869 .lock()
870 .unwrap()
871 .insert(path.to_string(), (status, body.into()));
872 }
873
874 fn requests(&self) -> Vec<Recorded> {
875 self.recorded.lock().unwrap().clone()
876 }
877 }
878
879 async fn handler(
880 axum::extract::State(st): axum::extract::State<Mock>,
881 req: axum::http::Request<axum::body::Body>,
882 ) -> impl axum::response::IntoResponse {
883 use axum::http::StatusCode;
884 use axum::response::IntoResponse;
885 let (parts, body) = req.into_parts();
886 let body = axum::body::to_bytes(body, 4 * 1024 * 1024)
887 .await
888 .unwrap_or_default()
889 .to_vec();
890 let path = parts.uri.path().to_string();
891 st.recorded.lock().unwrap().push(Recorded {
892 method: parts.method.to_string(),
893 path: path.clone(),
894 body,
895 });
896 // POST to a `/comments` path is a comment write: return the posted
897 // shape even when the GET fixture for the same path is `[]`.
898 if parts.method == axum::http::Method::POST && path.ends_with("/comments") {
899 return (
900 StatusCode::CREATED,
901 [("content-type", "application/json")],
902 r#"{"html_url":"https://github.com/x/y/issues/1#issuecomment-9"}"#.as_bytes().to_vec(),
903 )
904 .into_response();
905 }
906 let found = st.responses.lock().unwrap().get(&path).cloned();
907 match found {
908 Some((status, body)) => (
909 StatusCode::from_u16(status).unwrap_or(StatusCode::OK),
910 [("content-type", "application/json")],
911 body,
912 )
913 .into_response(),
914 // DELETE of an unknown label path → 404 (already gone → Ok).
915 None if parts.method == axum::http::Method::DELETE => {
916 (StatusCode::NOT_FOUND, "no such label").into_response()
917 }
918 None => (StatusCode::NOT_FOUND, "no mock").into_response(),
919 }
920 }
921
922 async fn spawn_mock(mock: Mock) -> String {
923 let app = axum::Router::new().fallback(handler).with_state(mock);
924 let lis = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
925 let addr = lis.local_addr().unwrap();
926 tokio::spawn(async move { axum::serve(lis, app).await.unwrap() });
927 format!("http://{addr}")
928 }
929
930 const REPO: &str = "test-owner/test-repo";
931
932 fn issue_path(n: u64, suffix: &str) -> String {
933 format!("/repos/{REPO}/issues/{n}{suffix}")
934 }
935
936 fn issue_body(n: u64, labels: &[&str], created: &str) -> Vec<u8> {
937 serde_json::to_vec(&serde_json::json!({
938 "number": n, "title": format!("Issue {n}"), "state": "open",
939 "labels": labels.iter().map(|l| serde_json::json!({"name": l})).collect::<Vec<_>>(),
940 "user": {"login": "someone"}, "created_at": created, "body": "body",
941 }))
942 .unwrap()
943 }
944
945 fn gh(base: &str, token: Option<&str>) -> GitHub {
946 GitHub::with_base_url(base, REPO, token.map(str::to_string)).unwrap()
947 }
948
949 fn test_config(base: &str, token: Option<&str>) -> crate::config::Config {
950 crate::config::Config {
951 openrouter_api_key: "k".into(),
952 openrouter_base_url: "http://127.0.0.1:9".into(),
953 password_hash: "h".into(),
954 git_push_token: "g".into(),
955 repo_url: "r".into(),
956 public_origin: "o".into(),
957 default_model: "m".into(),
958 runner_url: "http://127.0.0.1:9".into(),
959 state_dir: std::path::PathBuf::from("/tmp"),
960 mirror_dir: std::path::PathBuf::from("/tmp"),
961 release_signal: std::path::PathBuf::from("/tmp/signal"),
962 listen: "127.0.0.1:0".into(),
963 slots: 1,
964 github_repo: REPO.into(),
965 github_api_base: base.to_string(),
966 github_token: token.map(str::to_string),
967 test: Default::default(),
968 test_skip_release_wait: false,
969 triage_enabled: true,
970 triage_interval_secs: 120,
971 }
972 }
973
974 fn test_ctx(config: crate::config::Config, dir: &tempfile::TempDir) -> crate::agent::DriverCtx {
975 use std::sync::Arc;
976 let store = crate::store::Store::open(dir.path()).unwrap();
977 let (events_tx, _) = tokio::sync::broadcast::channel(8);
978 crate::agent::DriverCtx {
979 config: Arc::new(config),
980 store,
981 runner: crate::runner::Runner::new("http://127.0.0.1:9".into()),
982 openrouter: crate::openrouter::OpenRouter::new(
983 "http://127.0.0.1:9".into(),
984 "k".into(),
985 ),
986 events_tx,
987 }
988 }
989
990 #[tokio::test]
991 async fn apply_triage_corrects_labels_and_comments() {
992 let mock = Mock::default();
993 mock.respond(
994 &issue_path(1, ""),
995 200,
996 issue_body(1, &["enhancement", "notes", "2.6.12", "solved for next release"], "2026-11-06T00:00:00Z"),
997 );
998 mock.respond(&issue_path(1, "/comments"), 200, b"[]".to_vec());
999 mock.respond(&issue_path(1, "/labels"), 200, b"[]".to_vec());
1000 let base = spawn_mock(mock.clone()).await;
1001 let gh = gh(&base, Some("tok"));
1002
1003 let out = apply_triage(&gh, 1, &bug_weather_high()).await;
1004 assert!(out.error.is_none(), "{out:?}");
1005 assert!(!out.skipped_writes);
1006 assert_eq!(out.labels_added, s(&["bug", "weather"]));
1007 assert_eq!(out.labels_removed, s(&["enhancement", "notes"]));
1008 assert!(out.comment_url.as_deref().is_some_and(|u| u.contains("issuecomment")));
1009
1010 let reqs = mock.requests();
1011 let deletes: Vec<&Recorded> = reqs.iter().filter(|r| r.method == "DELETE").collect();
1012 assert_eq!(deletes.len(), 2);
1013 assert!(deletes.iter().any(|r| r.path.ends_with("/labels/enhancement")));
1014 assert!(deletes.iter().any(|r| r.path.ends_with("/labels/notes")));
1015 assert!(reqs.iter().all(|r| !r.path.contains("2.6.12")), "versions untouched");
1016 assert!(reqs.iter().all(|r| !r.path.contains("solved%20for")), "solved untouched");
1017
1018 let add = reqs
1019 .iter()
1020 .find(|r| r.method == "POST" && r.path.ends_with("/issues/1/labels"))
1021 .expect("labels POST");
1022 let v: Value = serde_json::from_slice(&add.body).unwrap();
1023 assert_eq!(v, serde_json::json!({"labels": ["bug", "weather"]}));
1024
1025 let comment = reqs
1026 .iter()
1027 .find(|r| r.method == "POST" && r.path.ends_with("/issues/1/comments"))
1028 .expect("comment POST");
1029 let v: Value = serde_json::from_slice(&comment.body).unwrap();
1030 let text = v.get("body").and_then(|b| b.as_str()).unwrap_or("");
1031 assert!(text.contains(TRIAGE_MARKER), "{text}");
1032 assert!(text.contains("Labels updated:"), "{text}");
1033 // Re-fetch of the issue happened first (read-before-write).
1034 assert_eq!(reqs[0].method, "GET");
1035 }
1036
1037 #[tokio::test]
1038 async fn apply_triage_without_token_skips_writes() {
1039 let offline = GitHub::with_base_url("http://127.0.0.1:9", REPO, None).unwrap();
1040 let out = apply_triage(&offline, 1, &bug_weather_high()).await;
1041 assert!(out.skipped_writes);
1042 assert!(out.labels_added.is_empty() && out.labels_removed.is_empty());
1043 assert!(out.comment_url.is_none());
1044 assert!(out.error.is_none());
1045 }
1046
1047 fn list_body() -> Vec<u8> {
1048 serde_json::to_vec(&serde_json::json!([
1049 {"number": 800, "title": "Old", "state": "open", "labels": [],
1050 "comments": 0, "created_at": "2026-10-01T00:00:00Z",
1051 "updated_at": "2026-10-01T00:00:00Z"},
1052 {"number": 901, "title": "Fresh PR", "state": "open", "labels": [],
1053 "comments": 0, "created_at": "2026-11-06T00:00:00Z",
1054 "updated_at": "2026-11-06T00:00:00Z",
1055 "pull_request": {"url": "https://api.github.com/x"}},
1056 {"number": 902, "title": "Fresh issue", "state": "open",
1057 "labels": [{"name": "bug"}, {"name": "weather"}], "comments": 0,
1058 "created_at": "2026-11-06T01:00:00Z",
1059 "updated_at": "2026-11-06T01:00:00Z"},
1060 {"number": 903, "title": "Marked already", "state": "open",
1061 "labels": [], "comments": 1,
1062 "created_at": "2026-11-06T02:00:00Z",
1063 "updated_at": "2026-11-06T02:00:00Z"},
1064 ]))
1065 .unwrap()
1066 }
1067
1068 #[tokio::test]
1069 async fn poll_once_queues_and_advances_watermark() {
1070 let mock = Mock::default();
1071 mock.respond(&format!("/repos/{REPO}/issues"), 200, list_body());
1072 mock.respond(&issue_path(902, "/comments"), 200, b"[]".to_vec());
1073 mock.respond(
1074 &issue_path(903, "/comments"),
1075 200,
1076 format!(r#"[{{"id":1,"user":{{"login":"a"}},"created_at":"2026-11-06T02:00:00Z","body":"done {TRIAGE_MARKER}"}}]"#)
1077 .into_bytes(),
1078 );
1079 let base = spawn_mock(mock.clone()).await;
1080
1081 let dir = tempfile::tempdir().unwrap();
1082 let ctx = test_ctx(test_config(&base, None), &dir);
1083
1084 // First poll: no watermark → set to now, queue nothing (no backfill).
1085 assert_eq!(poll_once(&ctx).await.unwrap(), 0);
1086 let wm = ctx.store.kv_get(WATERMARK_KEY).unwrap().unwrap();
1087 assert!(wm.ends_with('Z'), "{wm}");
1088 // Override the fresh watermark with an old one to simulate new issues.
1089 ctx.store.kv_set(WATERMARK_KEY, "2026-11-05T00:00:00Z").unwrap();
1090
1091 // Second poll: #902 queued (PR filtered, #800 stale, #903 marked).
1092 assert_eq!(poll_once(&ctx).await.unwrap(), 1);
1093 let row = ctx.store.triage_get(902).unwrap().expect("triage row");
1094 let task = ctx.store.get_task(row.task_id).unwrap().unwrap();
1095 assert_eq!(task.kind, crate::models::TASK_KIND_TRIAGE);
1096 assert_eq!(task.issue_number, Some(902));
1097 assert_eq!(task.module_scope, "weather");
1098 assert!(ctx.store.triage_get(903).unwrap().is_none(), "marked issue skipped");
1099 // Watermark advanced past #903 (max created_at seen, even for skipped).
1100 assert_eq!(
1101 ctx.store.kv_get(WATERMARK_KEY).unwrap().unwrap(),
1102 "2026-11-06T02:00:00Z"
1103 );
1104
1105 // Third poll: row exists → nothing new.
1106 assert_eq!(poll_once(&ctx).await.unwrap(), 0);
1107 }
1108}