Skip to main content

magi/
chat_status.rs

1//! List-level conversation status for the Chat list.
2//!
3//! Display and triage only: nothing here grants authority, resolves a decision,
4//! or controls a task. Evidence is gathered once per store revision into an
5//! [`Inventory`] keyed by conversation; [`derive`] is a pure function of that
6//! evidence plus the conversation's own cheap facts. Transcript prose, titles,
7//! notifications, a bare goal and a `Done` task are never evidence of approval
8//! or of active execution.
9use 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/// Coarse state shown on a Chat list row, most urgent first.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
23#[serde(rename_all = "snake_case")]
24pub enum Kind {
25    /// An unresolved owner decision or an explicit owner wait / manual hold.
26    NeedsOwner,
27    /// A failure or a decision effect that needs reconciliation.
28    NeedsAttention,
29    /// Evidence is unreadable or incomplete; nothing is assumed.
30    Unknown,
31    /// Verified current turn / task activity.
32    Working,
33    /// Queued, blocked or otherwise waiting without an owner.
34    Waiting,
35    /// Closed by hand with nothing outstanding.
36    Closed,
37    /// Recorded work finished and nothing is outstanding.
38    Completed,
39    /// Open and just discussing.
40    Idle,
41}
42
43/// Where a status can be examined further. Rendered as a hash route.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct Link {
46    /// `decision`, `task` or `run`.
47    pub kind: &'static str,
48    /// Full identity of the target.
49    pub id: String,
50}
51
52/// The wire projection of one row's status.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
54pub struct ChatStatus {
55    /// Coarse state.
56    pub kind: Kind,
57    /// Short phrase, empty when the label says it all.
58    /// Short phrase, empty when the label says it all.
59    pub reason: String,
60    /// Distinct unresolved owner decisions (`needs_owner` only).
61    /// Number of unresolved owner decisions.
62    pub owner_count: usize,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    /// Where to look further, when there is a single obvious place.
65    pub link: Option<Link>,
66}
67
68/// Per-conversation goal facts, counted from the saved goals.
69#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
70pub struct Goals {
71    /// Goals waiting for a fresh owner decision.
72    pub owner: usize,
73    /// Goals with a turn eligible to run.
74    pub runnable: usize,
75    /// Goals paused on interrupted or uncertain execution.
76    pub paused: usize,
77    /// Goals whose end condition was observed.
78    pub completed: usize,
79    /// Waiting goals: no activity is inferred from them.
80    pub waiting: usize,
81}
82
83impl Goals {
84    /// Count the saved goals by state.
85    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/// Everything durable that points at one conversation.
109#[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/// Evidence for every conversation, built once per store revision.
120#[derive(Debug, Default)]
121pub struct Inventory {
122    chats: HashMap<String, Evidence>,
123    busy_chats: HashSet<String>,
124    /// Records that exist but could not be read or attributed to a chat.
125    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    /// Chats with an unresolved owner decision, whatever their open state.
141    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    /// Read-only gather. A failure of one store degrades to explicit unknown
154    /// rather than to an empty (healthy-looking) answer.
155    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                        // A reservation protects admission but is not proof
164                        // of a running turn. The row's turn lease supplies that.
165                        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                    // A decision filed under an earlier repository assignment
198                    // belongs to history, not to the task's current work.
199                    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        // Legacy approvals that are still operative and not mirrored natively.
260        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 => ev.tasks_done += 1,
320                TaskStatus::Running => {
321                    use crate::run::{Liveness, RunState, RunStatus};
322                    match task
323                        .execution_runs()
324                        .last()
325                        .and_then(|id| RunState::load_under(id, home).ok())
326                    {
327                        Some(run) if task.assignment_accepts(&run) => match run
328                            .liveness_under(home, false)
329                        {
330                            Liveness::Live
331                                if run.resource_wait.is_some()
332                                    || (run.status == RunStatus::Landing
333                                        && run.active.is_empty()) =>
334                            {
335                                ev.waiting.push(reason("waiting"))
336                            }
337                            Liveness::Live => ev.working.push(reason("running")),
338                            Liveness::Dead => ev.attention.push(reason("execution stopped")),
339                            Liveness::Unknown => ev.attention.push(reason("execution unverified")),
340                        },
341                        _ => ev.attention.push(reason("execution evidence unavailable")),
342                    }
343                }
344                TaskStatus::Queued | TaskStatus::Parked => ev.waiting.push(reason("queued")),
345                TaskStatus::Blocked => ev.waiting.push(reason("blocked")),
346                TaskStatus::Failed => ev.attention.push(reason("failed")),
347                TaskStatus::Held if task.operator_held() => ev.owner.push(reason("on hold")),
348                TaskStatus::Held
349                    if task.has_disk_capacity_cause()
350                        || task
351                            .hold_reason
352                            .as_deref()
353                            .is_some_and(|r| r.starts_with(crate::cache::RESOURCE_HOLD)) =>
354                {
355                    ev.waiting.push(reason("waiting for resources"))
356                }
357                TaskStatus::Held => ev.attention.push(reason("held")),
358            }
359        }
360        inv
361    }
362
363    /// Mark incomplete source inventories without treating absence as idle.
364    pub fn mark_unreadable(&mut self) {
365        self.unattributed_unreadable = true;
366    }
367
368    /// A chat worker has reserved this conversation.
369    pub fn busy(&self, chat: &str) -> bool {
370        self.busy_chats.contains(chat)
371    }
372}
373
374fn pick(items: &[Item], label: &str) -> (String, Option<Link>) {
375    let first = items.first();
376    let reason = match items.len() {
377        0 => String::new(),
378        1 => first.map(|i| i.reason.clone()).unwrap_or_default(),
379        n => format!("{n} {label}"),
380    };
381    (reason, first.and_then(|i| i.link.clone()))
382}
383
384/// Pure status decision. Precedence: needs owner, attention / unknown,
385/// working, waiting, closed, completed, idle.
386pub fn derive(
387    open: bool,
388    ev: Option<&Evidence>,
389    goals: Goals,
390    thinking: bool,
391    unattributed_unreadable: bool,
392) -> ChatStatus {
393    let empty = Evidence::default();
394    let ev = ev.unwrap_or(&empty);
395    let status = |kind, reason: String, owner_count, link| ChatStatus {
396        kind,
397        reason,
398        owner_count,
399        link,
400    };
401
402    let owner = ev.owner.len() + goals.owner;
403    if owner > 0 {
404        let (reason, link) = if ev.owner.is_empty() {
405            ("goal needs your decision".to_owned(), None)
406        } else {
407            pick(&ev.owner, "decisions")
408        };
409        let reason = if owner > 1 && !ev.owner.is_empty() {
410            format!("{owner} decisions")
411        } else {
412            reason
413        };
414        return status(Kind::NeedsOwner, reason, owner, link);
415    }
416    if !ev.attention.is_empty() || goals.paused > 0 {
417        let (reason, link) = if ev.attention.is_empty() {
418            ("goal paused".to_owned(), None)
419        } else {
420            pick(&ev.attention, "need attention")
421        };
422        return status(Kind::NeedsAttention, reason, 0, link);
423    }
424    if unattributed_unreadable {
425        return status(
426            Kind::Unknown,
427            "some status records are unreadable".into(),
428            0,
429            None,
430        );
431    }
432    if thinking || !ev.working.is_empty() {
433        let (reason, link) = if ev.working.is_empty() {
434            ("replying".to_owned(), None)
435        } else {
436            pick(&ev.working, "running")
437        };
438        return status(Kind::Working, reason, 0, link);
439    }
440    if !ev.waiting.is_empty() || goals.runnable > 0 {
441        let (reason, link) = if ev.waiting.is_empty() {
442            ("goal turn queued".to_owned(), None)
443        } else {
444            pick(&ev.waiting, "waiting")
445        };
446        return status(Kind::Waiting, reason, 0, link);
447    }
448    if !open {
449        return status(Kind::Closed, String::new(), 0, None);
450    }
451    let done = (ev.tasks > 0 && ev.tasks_done == ev.tasks && goals.waiting == 0)
452        || (goals.completed > 0 && goals.waiting == 0 && ev.tasks_done == ev.tasks);
453    if done {
454        return status(Kind::Completed, String::new(), 0, None);
455    }
456    status(Kind::Idle, String::new(), 0, None)
457}
458
459impl ChatStatus {
460    /// Cached rows carry this until the per-request status is filled in.
461    pub fn placeholder() -> Self {
462        Self {
463            kind: Kind::Idle,
464            reason: String::new(),
465            owner_count: 0,
466            link: None,
467        }
468    }
469}
470
471impl Inventory {
472    /// Status of one conversation from the shared evidence.
473    pub fn status_of(&self, id: &str, open: bool, goals: Goals, thinking: bool) -> ChatStatus {
474        derive(
475            open,
476            self.chats.get(id),
477            goals,
478            thinking,
479            self.unattributed_unreadable,
480        )
481    }
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487
488    fn item(reason: &str) -> Item {
489        Item {
490            reason: reason.into(),
491            link: None,
492        }
493    }
494
495    #[test]
496    fn owner_decision_outranks_work_and_closure() {
497        let ev = Evidence {
498            owner: vec![item("approve")],
499            working: vec![item("task running")],
500            ..Evidence::default()
501        };
502        let s = derive(false, Some(&ev), Goals::default(), true, false);
503        assert_eq!(s.kind, Kind::NeedsOwner);
504        assert_eq!(s.owner_count, 1);
505    }
506
507    #[test]
508    fn precedence_walks_down_the_ladder() {
509        let g = Goals::default();
510        let mut ev = Evidence {
511            attention: vec![item("failed")],
512            working: vec![item("run")],
513            waiting: vec![item("queued")],
514            ..Evidence::default()
515        };
516        assert_eq!(
517            derive(true, Some(&ev), g, false, false).kind,
518            Kind::NeedsAttention
519        );
520        ev.attention.clear();
521        assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Working);
522        ev.working.clear();
523        assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Waiting);
524        ev.waiting.clear();
525        assert_eq!(derive(true, Some(&ev), g, true, false).kind, Kind::Working);
526        assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Idle);
527        assert_eq!(derive(false, Some(&ev), g, false, false).kind, Kind::Closed);
528    }
529
530    #[test]
531    fn done_task_or_waiting_goal_alone_is_not_activity() {
532        let ev = Evidence {
533            tasks: 1,
534            tasks_done: 1,
535            ..Evidence::default()
536        };
537        assert_eq!(
538            derive(true, Some(&ev), Goals::default(), false, false).kind,
539            Kind::Completed
540        );
541        let waiting = Goals {
542            waiting: 1,
543            ..Goals::default()
544        };
545        assert_eq!(derive(true, None, waiting, false, false).kind, Kind::Idle);
546    }
547
548    #[test]
549    fn goal_owner_state_needs_owner_and_unreadable_evidence_is_unknown() {
550        let g = Goals {
551            owner: 1,
552            ..Goals::default()
553        };
554        assert_eq!(derive(false, None, g, false, false).kind, Kind::NeedsOwner);
555        assert_eq!(
556            derive(true, None, Goals::default(), false, true).kind,
557            Kind::Unknown
558        );
559        // Unreadable evidence never hides a proven owner decision.
560        let ev = Evidence {
561            owner: vec![item("a"), item("b")],
562            ..Evidence::default()
563        };
564        let s = derive(true, Some(&ev), Goals::default(), false, true);
565        assert_eq!((s.kind, s.owner_count), (Kind::NeedsOwner, 2));
566    }
567
568    fn task(chat: &str, repo: &str, status: TaskStatus) -> Task {
569        let mut t = Task::new(
570            format!("work {chat} {repo}"),
571            "text".into(),
572            repo.into(),
573            crate::queue::Source::Human,
574        );
575        t.chat = Some(chat.into());
576        t.status = status;
577        t
578    }
579
580    #[test]
581    fn collect_counts_distinct_live_decisions_and_skips_stale_or_resolved() {
582        let home = tempfile::TempDir::new().unwrap();
583        let outbox = Outbox::at(home.path());
584        let a = task("chat-a", "/repo", TaskStatus::Running);
585        let b = task("chat-a", "/repo", TaskStatus::Done);
586        let moved = task("chat-b", "/new", TaskStatus::Queued);
587        outbox.file(&a, None, "s".into(), "one", "d").unwrap();
588        outbox.file(&b, None, "s".into(), "two", "d").unwrap();
589        let resolved = outbox.file(&moved, None, "s".into(), "old", "d").unwrap();
590        outbox
591            .update_decision(&resolved.id, |d| d.settle("done by hand"))
592            .unwrap();
593        // Filed under an earlier assignment: the task has since moved repo.
594        let mut earlier = moved.clone();
595        earlier.repo = "/old".into();
596        outbox
597            .file(&earlier, None, "s".into(), "stale", "d")
598            .unwrap();
599
600        let inv = Inventory::collect(home.path(), &[a, b, moved], &[]);
601        let s = inv.status_of("chat-a", false, Goals::default(), false);
602        assert_eq!((s.kind, s.owner_count), (Kind::NeedsOwner, 2), "{s:?}");
603        assert_eq!(s.link.unwrap().kind, "decision");
604        assert!(inv.needs_owner().contains("chat-a"));
605        let other = inv.status_of("chat-b", true, Goals::default(), false);
606        assert_eq!(other.kind, Kind::Waiting, "{other:?}");
607    }
608
609    #[test]
610    fn machine_wait_and_unverified_running_are_distinct() {
611        let home = tempfile::TempDir::new().unwrap();
612        let mut held = task("held", "/repo", TaskStatus::Queued);
613        held.hold_machine(Some("[resource] cache busy".into()));
614        let running = task("running", "/repo", TaskStatus::Running);
615        let inv = Inventory::collect(home.path(), &[held, running], &[]);
616        assert_eq!(
617            inv.status_of("held", true, Goals::default(), false).kind,
618            Kind::Waiting
619        );
620        assert_eq!(
621            inv.status_of("running", true, Goals::default(), false).kind,
622            Kind::NeedsAttention
623        );
624    }
625
626    #[test]
627    fn failed_release_is_attention_not_automatic_wait() {
628        let home = tempfile::TempDir::new().unwrap();
629        let mut t = task("chat", "/repo", TaskStatus::Queued);
630        t.hold_machine(Some("[release] command failed".into()));
631        let inv = Inventory::collect(home.path(), &[t], &[]);
632        assert_eq!(
633            inv.status_of("chat", true, Goals::default(), false).kind,
634            Kind::NeedsAttention
635        );
636    }
637
638    #[test]
639    fn only_current_landing_approval_counts() {
640        let home = tempfile::TempDir::new().unwrap();
641        let mut t = task("chat", "/repo", TaskStatus::Parked);
642        let mut run = crate::run::RunState::new(
643            t.repo.clone(),
644            "main".into(),
645            "base".into(),
646            "task".into(),
647            crate::config::Config::default(),
648        );
649        run.status = crate::run::RunStatus::Landing;
650        t.runs.push(run.id.clone());
651        let question = |summary: &str| {
652            Question::new(
653                run.id.clone(),
654                crate::land::APPROVAL_NODE.into(),
655                "approval".into(),
656                summary.into(),
657                String::new(),
658                vec!["merge".into()],
659            )
660        };
661        let mut old = question("old");
662        old.id = "old".into();
663        let mut current = question("current");
664        current.id = "current".into();
665        run.land_approval = Some(crate::run::LandApproval {
666            question: current.id.clone(),
667            head: "head".into(),
668        });
669        run.save_under(home.path()).unwrap();
670        let inv = Inventory::collect(home.path(), &[t], &[old, current]);
671        let status = inv.status_of("chat", true, Goals::default(), false);
672        assert_eq!((status.kind, status.owner_count), (Kind::NeedsOwner, 1));
673    }
674
675    #[test]
676    fn returning_to_same_repo_does_not_revive_old_decision() {
677        let home = tempfile::TempDir::new().unwrap();
678        let mut t = task("chat", "/repo", TaskStatus::Queued);
679        let inquiry = Outbox::at(home.path())
680            .file(&t, None, "s".into(), "old", "d")
681            .unwrap();
682        t.reassignments.push(crate::queue::Reassignment {
683            from: "/other".into(),
684            to: t.repo.clone(),
685            actor: "operator".into(),
686            at: inquiry.created_at,
687            run_boundary: 0,
688        });
689        let inv = Inventory::collect(home.path(), &[t], &[]);
690        assert_eq!(
691            inv.status_of("chat", true, Goals::default(), false).kind,
692            Kind::Waiting
693        );
694    }
695
696    #[test]
697    fn unreadable_inquiry_is_explicit_unknown_not_idle() {
698        let home = tempfile::TempDir::new().unwrap();
699        let root = home.path().join("notifications/task-inquiries");
700        std::fs::create_dir_all(&root).unwrap();
701        std::fs::write(root.join("broken.json"), "{").unwrap();
702        let inv = Inventory::collect(home.path(), &[], &[]);
703        assert_eq!(
704            inv.status_of("any", true, Goals::default(), false).kind,
705            Kind::Unknown
706        );
707    }
708}