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