1use std::collections::{HashMap, HashSet};
10use std::path::Path;
11
12use serde::Serialize;
13
14use crate::{
15 ask::{Question, QuestionStatus},
16 queue::{Task, TaskStatus},
17 task_decision::Status as DecisionStatus,
18 task_inquiry::Outbox,
19};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
23#[serde(rename_all = "snake_case")]
24pub enum Kind {
25 NeedsOwner,
27 NeedsAttention,
29 Unknown,
31 Working,
33 Waiting,
35 Closed,
37 Completed,
39 Idle,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct Link {
46 pub kind: &'static str,
48 pub id: String,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
54pub struct ChatStatus {
55 pub kind: Kind,
57 pub reason: String,
60 pub owner_count: usize,
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub link: Option<Link>,
66}
67
68#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
70pub struct Goals {
71 pub owner: usize,
73 pub runnable: usize,
75 pub paused: usize,
77 pub completed: usize,
79 pub waiting: usize,
81}
82
83impl Goals {
84 pub fn of(goals: &[crate::chat_goal::Goal]) -> Self {
86 use crate::chat_goal::State;
87 let mut out = Self::default();
88 for goal in goals {
89 match goal.state {
90 State::Owner => out.owner += 1,
91 State::Runnable => out.runnable += 1,
92 State::Paused => out.paused += 1,
93 State::Completed => out.completed += 1,
94 State::Waiting => out.waiting += 1,
95 State::Stopped => {}
96 }
97 }
98 out
99 }
100}
101
102#[derive(Debug, Clone, Default)]
103struct Item {
104 reason: String,
105 link: Option<Link>,
106}
107
108#[derive(Debug, Clone, Default)]
110pub struct Evidence {
111 owner: Vec<Item>,
112 attention: Vec<Item>,
113 working: Vec<Item>,
114 waiting: Vec<Item>,
115 tasks: usize,
116 tasks_done: usize,
117}
118
119#[derive(Debug, Default)]
121pub struct Inventory {
122 chats: HashMap<String, Evidence>,
123 busy_chats: HashSet<String>,
124 unattributed_unreadable: bool,
126}
127
128fn chat_of(task: &Task) -> Option<&str> {
129 task.chat
130 .as_deref()
131 .or_else(|| task.filed_by_chat())
132 .or(task.origin_chat.as_deref())
133}
134
135fn short(id: &str) -> &str {
136 id.get(..8).unwrap_or(id)
137}
138
139impl Inventory {
140 pub fn needs_owner(&self) -> HashSet<&str> {
142 self.chats
143 .iter()
144 .filter(|(_, e)| !e.owner.is_empty())
145 .map(|(id, _)| id.as_str())
146 .collect()
147 }
148
149 fn evidence(&mut self, chat: &str) -> &mut Evidence {
150 self.chats.entry(chat.to_owned()).or_default()
151 }
152
153 pub fn collect(home: &Path, tasks: &[Task], questions: &[Question]) -> Self {
156 let mut inv = Self::default();
157 match crate::worker::observe_active(home) {
158 Ok(jobs) => {
159 for job in jobs.iter().filter(|job| job.kind == "chat") {
160 if let Some(chat) = job.payload.get("talk").and_then(serde_json::Value::as_str)
161 {
162 inv.busy_chats.insert(chat.to_owned());
163 inv.evidence(chat).waiting.push(Item {
166 reason: "reply queued".into(),
167 link: None,
168 });
169 } else {
170 inv.mark_unreadable();
171 }
172 }
173 }
174 Err(_) => inv.mark_unreadable(),
175 }
176 let by_id: HashMap<&str, &Task> = tasks.iter().map(|t| (t.id.as_str(), t)).collect();
177 let by_question: HashMap<&str, &Question> =
178 questions.iter().map(|q| (q.id.as_str(), q)).collect();
179 let mut mirrored: HashSet<String> = HashSet::new();
180
181 match Outbox::at(home).list_readable() {
182 Ok((items, unreadable)) => {
183 if unreadable > 0 {
184 inv.unattributed_unreadable = true;
185 }
186 for inquiry in items {
187 if let Some(id) = inquiry.key.strip_prefix("question:") {
188 mirrored.insert(id.to_owned());
189 }
190 let Some(decision) = inquiry.decision.as_ref() else {
191 continue;
192 };
193 if inquiry.archived || decision.status == DecisionStatus::Resolved {
194 continue;
195 }
196 let task = by_id.get(inquiry.task.as_str()).copied();
197 if task.is_some_and(|t| {
200 t.repo != inquiry.repo
201 || inquiry
202 .key
203 .strip_prefix("question:")
204 .and_then(|id| by_question.get(id))
205 .is_some_and(|q| t.stale_question(q))
206 || t.reassignments
207 .last()
208 .is_some_and(|r| inquiry.created_at <= r.at)
209 || inquiry
210 .run
211 .as_ref()
212 .is_some_and(|run| !t.execution_run(run))
213 }) {
214 continue;
215 }
216 let Some(chat) = inquiry
217 .delivered_to
218 .as_deref()
219 .or_else(|| task.and_then(chat_of))
220 else {
221 inv.unattributed_unreadable = true;
222 continue;
223 };
224 let link = Some(Link {
225 kind: "decision",
226 id: inquiry.id.clone(),
227 });
228 let item = |reason: &str| Item {
229 reason: reason.to_owned(),
230 link: link.clone(),
231 };
232 let ev = inv.evidence(chat);
233 use crate::task_decision::Attention;
234 match inquiry.attention().expect("decision exists") {
235 Attention::OwnerChoice => ev.owner.push(Item {
236 reason: decision.reason.clone(),
237 link,
238 }),
239 Attention::InFlight => ev.waiting.push(item("decision effect in flight")),
240 Attention::ReleaseFollowup => {
241 ev.waiting.push(item("release follow-up remains"))
242 }
243 Attention::ReceiptCheck => ev
244 .attention
245 .push(item("decision needs receipt verification")),
246 Attention::StaleTarget => {
247 ev.attention.push(item("decision target changed or closed"))
248 }
249 Attention::Resolved => {}
250 }
251 }
252 }
253 Err(error) => {
254 tracing::warn!("chat status: inquiries unreadable: {error:#}");
255 inv.unattributed_unreadable = true;
256 }
257 }
258
259 for q in questions {
261 if q.status != QuestionStatus::Open
262 || q.node != crate::land::APPROVAL_NODE
263 || mirrored.contains(&q.id)
264 {
265 continue;
266 }
267 let Some(task) = tasks
268 .iter()
269 .find(|t| t.execution_runs().last() == Some(&q.run))
270 else {
271 continue;
272 };
273 if task.stale_question(q) {
274 continue;
275 }
276 let Some(chat) = chat_of(task) else {
277 continue;
278 };
279 match crate::run::RunState::load_under(&q.run, home) {
280 Ok(run)
281 if task.assignment_accepts(&run)
282 && run.status == crate::run::RunStatus::Landing
283 && !run.released()
284 && run.retired_to.is_none()
285 && !run.merge_decision.as_ref().is_some_and(|d| d.closed)
286 && run
287 .land_approval
288 .as_ref()
289 .is_some_and(|a| a.question == q.id) => {}
290 Ok(_) => continue,
291 Err(_) => {
292 inv.mark_unreadable();
293 continue;
294 }
295 }
296 let task_id = task.id.clone();
297 inv.evidence(chat).owner.push(Item {
298 reason: "merge approval".into(),
299 link: Some(Link {
300 kind: "task",
301 id: task_id,
302 }),
303 });
304 }
305
306 for task in tasks {
307 let Some(chat) = chat_of(task) else { continue };
308 let link = Some(Link {
309 kind: "task",
310 id: task.id.clone(),
311 });
312 let reason = |what: &str| Item {
313 reason: format!("task {} {what}", short(&task.id)),
314 link: link.clone(),
315 };
316 let ev = inv.evidence(chat);
317 ev.tasks += 1;
318 match task.status {
319 TaskStatus::Done => {
320 ev.tasks_done += 1;
321 if let Some(detail) = task.stale_pr_attention(home) {
322 ev.attention.push(reason(&detail));
323 }
324 }
325 TaskStatus::Running => {
326 use crate::run::{Liveness, RunState, RunStatus};
327 match task
328 .execution_runs()
329 .last()
330 .and_then(|id| RunState::load_under(id, home).ok())
331 {
332 Some(run) if task.assignment_accepts(&run) => match run
333 .liveness_under(home, false)
334 {
335 Liveness::Live
336 if run.resource_wait.is_some()
337 || (run.status == RunStatus::Landing
338 && run.active.is_empty()) =>
339 {
340 ev.waiting.push(reason("waiting"))
341 }
342 Liveness::Live => ev.working.push(reason("running")),
343 Liveness::Dead => ev.attention.push(reason("execution stopped")),
344 Liveness::Unknown => ev.attention.push(reason("execution unverified")),
345 },
346 _ => ev.attention.push(reason("execution evidence unavailable")),
347 }
348 }
349 TaskStatus::Queued | TaskStatus::Parked => ev.waiting.push(reason("queued")),
350 TaskStatus::Blocked => ev.waiting.push(reason("blocked")),
351 TaskStatus::Failed => ev.attention.push(reason("failed")),
352 TaskStatus::Held if task.operator_held() => ev.owner.push(reason("on hold")),
353 TaskStatus::Held
354 if task.has_disk_capacity_cause()
355 || task
356 .hold_reason
357 .as_deref()
358 .is_some_and(|r| r.starts_with(crate::cache::RESOURCE_HOLD)) =>
359 {
360 ev.waiting.push(reason("waiting for resources"))
361 }
362 TaskStatus::Held => ev.attention.push(reason("held")),
363 }
364 }
365 inv
366 }
367
368 pub fn mark_unreadable(&mut self) {
370 self.unattributed_unreadable = true;
371 }
372
373 pub fn busy(&self, chat: &str) -> bool {
375 self.busy_chats.contains(chat)
376 }
377}
378
379fn pick(items: &[Item], label: &str) -> (String, Option<Link>) {
380 let first = items.first();
381 let reason = match items.len() {
382 0 => String::new(),
383 1 => first.map(|i| i.reason.clone()).unwrap_or_default(),
384 n => format!("{n} {label}"),
385 };
386 (reason, first.and_then(|i| i.link.clone()))
387}
388
389pub fn derive(
392 open: bool,
393 ev: Option<&Evidence>,
394 goals: Goals,
395 thinking: bool,
396 unattributed_unreadable: bool,
397) -> ChatStatus {
398 let empty = Evidence::default();
399 let ev = ev.unwrap_or(&empty);
400 let status = |kind, reason: String, owner_count, link| ChatStatus {
401 kind,
402 reason,
403 owner_count,
404 link,
405 };
406
407 let owner = ev.owner.len() + goals.owner;
408 if owner > 0 {
409 let (reason, link) = if ev.owner.is_empty() {
410 ("goal needs your decision".to_owned(), None)
411 } else {
412 pick(&ev.owner, "decisions")
413 };
414 let reason = if owner > 1 && !ev.owner.is_empty() {
415 format!("{owner} decisions")
416 } else {
417 reason
418 };
419 return status(Kind::NeedsOwner, reason, owner, link);
420 }
421 if !ev.attention.is_empty() || goals.paused > 0 {
422 let (reason, link) = if ev.attention.is_empty() {
423 ("goal paused".to_owned(), None)
424 } else {
425 pick(&ev.attention, "need attention")
426 };
427 return status(Kind::NeedsAttention, reason, 0, link);
428 }
429 if unattributed_unreadable {
430 return status(
431 Kind::Unknown,
432 "some status records are unreadable".into(),
433 0,
434 None,
435 );
436 }
437 if thinking || !ev.working.is_empty() {
438 let (reason, link) = if ev.working.is_empty() {
439 ("replying".to_owned(), None)
440 } else {
441 pick(&ev.working, "running")
442 };
443 return status(Kind::Working, reason, 0, link);
444 }
445 if !ev.waiting.is_empty() || goals.runnable > 0 {
446 let (reason, link) = if ev.waiting.is_empty() {
447 ("goal turn queued".to_owned(), None)
448 } else {
449 pick(&ev.waiting, "waiting")
450 };
451 return status(Kind::Waiting, reason, 0, link);
452 }
453 if !open {
454 return status(Kind::Closed, String::new(), 0, None);
455 }
456 let done = (ev.tasks > 0 && ev.tasks_done == ev.tasks && goals.waiting == 0)
457 || (goals.completed > 0 && goals.waiting == 0 && ev.tasks_done == ev.tasks);
458 if done {
459 return status(Kind::Completed, String::new(), 0, None);
460 }
461 status(Kind::Idle, String::new(), 0, None)
462}
463
464impl ChatStatus {
465 pub fn placeholder() -> Self {
467 Self {
468 kind: Kind::Idle,
469 reason: String::new(),
470 owner_count: 0,
471 link: None,
472 }
473 }
474}
475
476impl Inventory {
477 pub fn status_of(&self, id: &str, open: bool, goals: Goals, thinking: bool) -> ChatStatus {
479 derive(
480 open,
481 self.chats.get(id),
482 goals,
483 thinking,
484 self.unattributed_unreadable,
485 )
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 fn item(reason: &str) -> Item {
494 Item {
495 reason: reason.into(),
496 link: None,
497 }
498 }
499
500 #[test]
501 fn owner_decision_outranks_work_and_closure() {
502 let ev = Evidence {
503 owner: vec![item("approve")],
504 working: vec![item("task running")],
505 ..Evidence::default()
506 };
507 let s = derive(false, Some(&ev), Goals::default(), true, false);
508 assert_eq!(s.kind, Kind::NeedsOwner);
509 assert_eq!(s.owner_count, 1);
510 }
511
512 #[test]
513 fn precedence_walks_down_the_ladder() {
514 let g = Goals::default();
515 let mut ev = Evidence {
516 attention: vec![item("failed")],
517 working: vec![item("run")],
518 waiting: vec![item("queued")],
519 ..Evidence::default()
520 };
521 assert_eq!(
522 derive(true, Some(&ev), g, false, false).kind,
523 Kind::NeedsAttention
524 );
525 ev.attention.clear();
526 assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Working);
527 ev.working.clear();
528 assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Waiting);
529 ev.waiting.clear();
530 assert_eq!(derive(true, Some(&ev), g, true, false).kind, Kind::Working);
531 assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Idle);
532 assert_eq!(derive(false, Some(&ev), g, false, false).kind, Kind::Closed);
533 }
534
535 #[test]
536 fn done_task_or_waiting_goal_alone_is_not_activity() {
537 let ev = Evidence {
538 tasks: 1,
539 tasks_done: 1,
540 ..Evidence::default()
541 };
542 assert_eq!(
543 derive(true, Some(&ev), Goals::default(), false, false).kind,
544 Kind::Completed
545 );
546 let waiting = Goals {
547 waiting: 1,
548 ..Goals::default()
549 };
550 assert_eq!(derive(true, None, waiting, false, false).kind, Kind::Idle);
551 }
552
553 #[test]
554 fn goal_owner_state_needs_owner_and_unreadable_evidence_is_unknown() {
555 let g = Goals {
556 owner: 1,
557 ..Goals::default()
558 };
559 assert_eq!(derive(false, None, g, false, false).kind, Kind::NeedsOwner);
560 assert_eq!(
561 derive(true, None, Goals::default(), false, true).kind,
562 Kind::Unknown
563 );
564 let ev = Evidence {
566 owner: vec![item("a"), item("b")],
567 ..Evidence::default()
568 };
569 let s = derive(true, Some(&ev), Goals::default(), false, true);
570 assert_eq!((s.kind, s.owner_count), (Kind::NeedsOwner, 2));
571 }
572
573 fn task(chat: &str, repo: &str, status: TaskStatus) -> Task {
574 let mut t = Task::new(
575 format!("work {chat} {repo}"),
576 "text".into(),
577 repo.into(),
578 crate::queue::Source::Human,
579 );
580 t.chat = Some(chat.into());
581 t.status = status;
582 t
583 }
584
585 #[test]
586 fn collect_counts_distinct_live_decisions_and_skips_stale_or_resolved() {
587 let home = tempfile::TempDir::new().unwrap();
588 let outbox = Outbox::at(home.path());
589 let a = task("chat-a", "/repo", TaskStatus::Running);
590 let b = task("chat-a", "/repo", TaskStatus::Done);
591 let moved = task("chat-b", "/new", TaskStatus::Queued);
592 outbox.file(&a, None, "s".into(), "one", "d").unwrap();
593 outbox.file(&b, None, "s".into(), "two", "d").unwrap();
594 let resolved = outbox.file(&moved, None, "s".into(), "old", "d").unwrap();
595 outbox
596 .update_decision(&resolved.id, |d| d.settle("done by hand"))
597 .unwrap();
598 let mut earlier = moved.clone();
600 earlier.repo = "/old".into();
601 outbox
602 .file(&earlier, None, "s".into(), "stale", "d")
603 .unwrap();
604
605 let inv = Inventory::collect(home.path(), &[a, b, moved], &[]);
606 let s = inv.status_of("chat-a", false, Goals::default(), false);
607 assert_eq!((s.kind, s.owner_count), (Kind::NeedsOwner, 2), "{s:?}");
608 assert_eq!(s.link.unwrap().kind, "decision");
609 assert!(inv.needs_owner().contains("chat-a"));
610 let other = inv.status_of("chat-b", true, Goals::default(), false);
611 assert_eq!(other.kind, Kind::Waiting, "{other:?}");
612 }
613
614 #[test]
615 fn machine_wait_and_unverified_running_are_distinct() {
616 let home = tempfile::TempDir::new().unwrap();
617 let mut held = task("held", "/repo", TaskStatus::Queued);
618 held.hold_machine(Some("[resource] cache busy".into()));
619 let running = task("running", "/repo", TaskStatus::Running);
620 let inv = Inventory::collect(home.path(), &[held, running], &[]);
621 assert_eq!(
622 inv.status_of("held", true, Goals::default(), false).kind,
623 Kind::Waiting
624 );
625 assert_eq!(
626 inv.status_of("running", true, Goals::default(), false).kind,
627 Kind::NeedsAttention
628 );
629 }
630
631 #[test]
632 fn failed_release_is_attention_not_automatic_wait() {
633 let home = tempfile::TempDir::new().unwrap();
634 let mut t = task("chat", "/repo", TaskStatus::Queued);
635 t.hold_machine(Some("[release] command failed".into()));
636 let inv = Inventory::collect(home.path(), &[t], &[]);
637 assert_eq!(
638 inv.status_of("chat", true, Goals::default(), false).kind,
639 Kind::NeedsAttention
640 );
641 }
642
643 #[test]
644 fn only_current_landing_approval_counts() {
645 let home = tempfile::TempDir::new().unwrap();
646 let mut t = task("chat", "/repo", TaskStatus::Parked);
647 let mut run = crate::run::RunState::new(
648 t.repo.clone(),
649 "main".into(),
650 "base".into(),
651 "task".into(),
652 crate::config::Config::default(),
653 );
654 run.status = crate::run::RunStatus::Landing;
655 t.runs.push(run.id.clone());
656 let question = |summary: &str| {
657 Question::new(
658 run.id.clone(),
659 crate::land::APPROVAL_NODE.into(),
660 "approval".into(),
661 summary.into(),
662 String::new(),
663 vec!["merge".into()],
664 )
665 };
666 let mut old = question("old");
667 old.id = "old".into();
668 let mut current = question("current");
669 current.id = "current".into();
670 run.land_approval = Some(crate::run::LandApproval {
671 question: current.id.clone(),
672 head: "head".into(),
673 });
674 run.save_under(home.path()).unwrap();
675 let inv = Inventory::collect(home.path(), &[t], &[old, current]);
676 let status = inv.status_of("chat", true, Goals::default(), false);
677 assert_eq!((status.kind, status.owner_count), (Kind::NeedsOwner, 1));
678 }
679
680 #[test]
681 fn returning_to_same_repo_does_not_revive_old_decision() {
682 let home = tempfile::TempDir::new().unwrap();
683 let mut t = task("chat", "/repo", TaskStatus::Queued);
684 let inquiry = Outbox::at(home.path())
685 .file(&t, None, "s".into(), "old", "d")
686 .unwrap();
687 t.reassignments.push(crate::queue::Reassignment {
688 from: "/other".into(),
689 to: t.repo.clone(),
690 actor: "operator".into(),
691 at: inquiry.created_at,
692 run_boundary: 0,
693 });
694 let inv = Inventory::collect(home.path(), &[t], &[]);
695 assert_eq!(
696 inv.status_of("chat", true, Goals::default(), false).kind,
697 Kind::Waiting
698 );
699 }
700
701 #[test]
702 fn unreadable_inquiry_is_explicit_unknown_not_idle() {
703 let home = tempfile::TempDir::new().unwrap();
704 let root = home.path().join("notifications/task-inquiries");
705 std::fs::create_dir_all(&root).unwrap();
706 std::fs::write(root.join("broken.json"), "{").unwrap();
707 let inv = Inventory::collect(home.path(), &[], &[]);
708 assert_eq!(
709 inv.status_of("any", true, Goals::default(), false).kind,
710 Kind::Unknown
711 );
712 }
713}