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                    match decision.status {
234                        DecisionStatus::AwaitingOwner => ev.owner.push(Item {
235                            reason: decision.reason.clone(),
236                            link,
237                        }),
238                        DecisionStatus::Queued => ev.waiting.push(item("decision queued")),
239                        DecisionStatus::InProgress => {
240                            ev.waiting.push(item("decision in progress"));
241                        }
242                        DecisionStatus::RetryNeeded => {
243                            ev.attention.push(item("decision needs reconciliation"));
244                        }
245                        DecisionStatus::Resolved => {}
246                    }
247                }
248            }
249            Err(error) => {
250                tracing::warn!("chat status: inquiries unreadable: {error:#}");
251                inv.unattributed_unreadable = true;
252            }
253        }
254
255        // Legacy approvals that are still operative and not mirrored natively.
256        for q in questions {
257            if q.status != QuestionStatus::Open
258                || q.node != crate::land::APPROVAL_NODE
259                || mirrored.contains(&q.id)
260            {
261                continue;
262            }
263            let Some(task) = tasks
264                .iter()
265                .find(|t| t.execution_runs().last() == Some(&q.run))
266            else {
267                continue;
268            };
269            if task.stale_question(q) {
270                continue;
271            }
272            let Some(chat) = chat_of(task) else {
273                continue;
274            };
275            match crate::run::RunState::load_under(&q.run, home) {
276                Ok(run)
277                    if task.assignment_accepts(&run)
278                        && run.status == crate::run::RunStatus::Landing
279                        && !run.released()
280                        && run.retired_to.is_none()
281                        && !run.merge_decision.as_ref().is_some_and(|d| d.closed)
282                        && run
283                            .land_approval
284                            .as_ref()
285                            .is_some_and(|a| a.question == q.id) => {}
286                Ok(_) => continue,
287                Err(_) => {
288                    inv.mark_unreadable();
289                    continue;
290                }
291            }
292            let task_id = task.id.clone();
293            inv.evidence(chat).owner.push(Item {
294                reason: "merge approval".into(),
295                link: Some(Link {
296                    kind: "task",
297                    id: task_id,
298                }),
299            });
300        }
301
302        for task in tasks {
303            let Some(chat) = chat_of(task) else { continue };
304            let link = Some(Link {
305                kind: "task",
306                id: task.id.clone(),
307            });
308            let reason = |what: &str| Item {
309                reason: format!("task {} {what}", short(&task.id)),
310                link: link.clone(),
311            };
312            let ev = inv.evidence(chat);
313            ev.tasks += 1;
314            match task.status {
315                TaskStatus::Done => ev.tasks_done += 1,
316                TaskStatus::Running => {
317                    use crate::run::{Liveness, RunState, RunStatus};
318                    match task
319                        .execution_runs()
320                        .last()
321                        .and_then(|id| RunState::load_under(id, home).ok())
322                    {
323                        Some(run) if task.assignment_accepts(&run) => match run
324                            .liveness_under(home, false)
325                        {
326                            Liveness::Live
327                                if run.resource_wait.is_some()
328                                    || (run.status == RunStatus::Landing
329                                        && run.active.is_empty()) =>
330                            {
331                                ev.waiting.push(reason("waiting"))
332                            }
333                            Liveness::Live => ev.working.push(reason("running")),
334                            Liveness::Dead => ev.attention.push(reason("execution stopped")),
335                            Liveness::Unknown => ev.attention.push(reason("execution unverified")),
336                        },
337                        _ => ev.attention.push(reason("execution evidence unavailable")),
338                    }
339                }
340                TaskStatus::Queued | TaskStatus::Parked => ev.waiting.push(reason("queued")),
341                TaskStatus::Blocked => ev.waiting.push(reason("blocked")),
342                TaskStatus::Failed => ev.attention.push(reason("failed")),
343                TaskStatus::Held if task.operator_held() => ev.owner.push(reason("on hold")),
344                TaskStatus::Held
345                    if task.has_disk_capacity_cause()
346                        || task
347                            .hold_reason
348                            .as_deref()
349                            .is_some_and(|r| r.starts_with(crate::cache::RESOURCE_HOLD)) =>
350                {
351                    ev.waiting.push(reason("waiting for resources"))
352                }
353                TaskStatus::Held => ev.attention.push(reason("held")),
354            }
355        }
356        inv
357    }
358
359    /// Mark incomplete source inventories without treating absence as idle.
360    pub fn mark_unreadable(&mut self) {
361        self.unattributed_unreadable = true;
362    }
363
364    /// A chat worker has reserved this conversation.
365    pub fn busy(&self, chat: &str) -> bool {
366        self.busy_chats.contains(chat)
367    }
368}
369
370fn pick(items: &[Item], label: &str) -> (String, Option<Link>) {
371    let first = items.first();
372    let reason = match items.len() {
373        0 => String::new(),
374        1 => first.map(|i| i.reason.clone()).unwrap_or_default(),
375        n => format!("{n} {label}"),
376    };
377    (reason, first.and_then(|i| i.link.clone()))
378}
379
380/// Pure status decision. Precedence: needs owner, attention / unknown,
381/// working, waiting, closed, completed, idle.
382pub fn derive(
383    open: bool,
384    ev: Option<&Evidence>,
385    goals: Goals,
386    thinking: bool,
387    unattributed_unreadable: bool,
388) -> ChatStatus {
389    let empty = Evidence::default();
390    let ev = ev.unwrap_or(&empty);
391    let status = |kind, reason: String, owner_count, link| ChatStatus {
392        kind,
393        reason,
394        owner_count,
395        link,
396    };
397
398    let owner = ev.owner.len() + goals.owner;
399    if owner > 0 {
400        let (reason, link) = if ev.owner.is_empty() {
401            ("goal needs your decision".to_owned(), None)
402        } else {
403            pick(&ev.owner, "decisions")
404        };
405        let reason = if owner > 1 && !ev.owner.is_empty() {
406            format!("{owner} decisions")
407        } else {
408            reason
409        };
410        return status(Kind::NeedsOwner, reason, owner, link);
411    }
412    if !ev.attention.is_empty() || goals.paused > 0 {
413        let (reason, link) = if ev.attention.is_empty() {
414            ("goal paused".to_owned(), None)
415        } else {
416            pick(&ev.attention, "need attention")
417        };
418        return status(Kind::NeedsAttention, reason, 0, link);
419    }
420    if unattributed_unreadable {
421        return status(
422            Kind::Unknown,
423            "some status records are unreadable".into(),
424            0,
425            None,
426        );
427    }
428    if thinking || !ev.working.is_empty() {
429        let (reason, link) = if ev.working.is_empty() {
430            ("replying".to_owned(), None)
431        } else {
432            pick(&ev.working, "running")
433        };
434        return status(Kind::Working, reason, 0, link);
435    }
436    if !ev.waiting.is_empty() || goals.runnable > 0 {
437        let (reason, link) = if ev.waiting.is_empty() {
438            ("goal turn queued".to_owned(), None)
439        } else {
440            pick(&ev.waiting, "waiting")
441        };
442        return status(Kind::Waiting, reason, 0, link);
443    }
444    if !open {
445        return status(Kind::Closed, String::new(), 0, None);
446    }
447    let done = (ev.tasks > 0 && ev.tasks_done == ev.tasks && goals.waiting == 0)
448        || (goals.completed > 0 && goals.waiting == 0 && ev.tasks_done == ev.tasks);
449    if done {
450        return status(Kind::Completed, String::new(), 0, None);
451    }
452    status(Kind::Idle, String::new(), 0, None)
453}
454
455impl ChatStatus {
456    /// Cached rows carry this until the per-request status is filled in.
457    pub fn placeholder() -> Self {
458        Self {
459            kind: Kind::Idle,
460            reason: String::new(),
461            owner_count: 0,
462            link: None,
463        }
464    }
465}
466
467impl Inventory {
468    /// Status of one conversation from the shared evidence.
469    pub fn status_of(&self, id: &str, open: bool, goals: Goals, thinking: bool) -> ChatStatus {
470        derive(
471            open,
472            self.chats.get(id),
473            goals,
474            thinking,
475            self.unattributed_unreadable,
476        )
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    fn item(reason: &str) -> Item {
485        Item {
486            reason: reason.into(),
487            link: None,
488        }
489    }
490
491    #[test]
492    fn owner_decision_outranks_work_and_closure() {
493        let ev = Evidence {
494            owner: vec![item("approve")],
495            working: vec![item("task running")],
496            ..Evidence::default()
497        };
498        let s = derive(false, Some(&ev), Goals::default(), true, false);
499        assert_eq!(s.kind, Kind::NeedsOwner);
500        assert_eq!(s.owner_count, 1);
501    }
502
503    #[test]
504    fn precedence_walks_down_the_ladder() {
505        let g = Goals::default();
506        let mut ev = Evidence {
507            attention: vec![item("failed")],
508            working: vec![item("run")],
509            waiting: vec![item("queued")],
510            ..Evidence::default()
511        };
512        assert_eq!(
513            derive(true, Some(&ev), g, false, false).kind,
514            Kind::NeedsAttention
515        );
516        ev.attention.clear();
517        assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Working);
518        ev.working.clear();
519        assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Waiting);
520        ev.waiting.clear();
521        assert_eq!(derive(true, Some(&ev), g, true, false).kind, Kind::Working);
522        assert_eq!(derive(true, Some(&ev), g, false, false).kind, Kind::Idle);
523        assert_eq!(derive(false, Some(&ev), g, false, false).kind, Kind::Closed);
524    }
525
526    #[test]
527    fn done_task_or_waiting_goal_alone_is_not_activity() {
528        let ev = Evidence {
529            tasks: 1,
530            tasks_done: 1,
531            ..Evidence::default()
532        };
533        assert_eq!(
534            derive(true, Some(&ev), Goals::default(), false, false).kind,
535            Kind::Completed
536        );
537        let waiting = Goals {
538            waiting: 1,
539            ..Goals::default()
540        };
541        assert_eq!(derive(true, None, waiting, false, false).kind, Kind::Idle);
542    }
543
544    #[test]
545    fn goal_owner_state_needs_owner_and_unreadable_evidence_is_unknown() {
546        let g = Goals {
547            owner: 1,
548            ..Goals::default()
549        };
550        assert_eq!(derive(false, None, g, false, false).kind, Kind::NeedsOwner);
551        assert_eq!(
552            derive(true, None, Goals::default(), false, true).kind,
553            Kind::Unknown
554        );
555        // Unreadable evidence never hides a proven owner decision.
556        let ev = Evidence {
557            owner: vec![item("a"), item("b")],
558            ..Evidence::default()
559        };
560        let s = derive(true, Some(&ev), Goals::default(), false, true);
561        assert_eq!((s.kind, s.owner_count), (Kind::NeedsOwner, 2));
562    }
563
564    fn task(chat: &str, repo: &str, status: TaskStatus) -> Task {
565        let mut t = Task::new(
566            format!("work {chat} {repo}"),
567            "text".into(),
568            repo.into(),
569            crate::queue::Source::Human,
570        );
571        t.chat = Some(chat.into());
572        t.status = status;
573        t
574    }
575
576    #[test]
577    fn collect_counts_distinct_live_decisions_and_skips_stale_or_resolved() {
578        let home = tempfile::TempDir::new().unwrap();
579        let outbox = Outbox::at(home.path());
580        let a = task("chat-a", "/repo", TaskStatus::Running);
581        let b = task("chat-a", "/repo", TaskStatus::Done);
582        let moved = task("chat-b", "/new", TaskStatus::Queued);
583        outbox.file(&a, None, "s".into(), "one", "d").unwrap();
584        outbox.file(&b, None, "s".into(), "two", "d").unwrap();
585        let resolved = outbox.file(&moved, None, "s".into(), "old", "d").unwrap();
586        outbox
587            .update_decision(&resolved.id, |d| d.settle("done by hand"))
588            .unwrap();
589        // Filed under an earlier assignment: the task has since moved repo.
590        let mut earlier = moved.clone();
591        earlier.repo = "/old".into();
592        outbox
593            .file(&earlier, None, "s".into(), "stale", "d")
594            .unwrap();
595
596        let inv = Inventory::collect(home.path(), &[a, b, moved], &[]);
597        let s = inv.status_of("chat-a", false, Goals::default(), false);
598        assert_eq!((s.kind, s.owner_count), (Kind::NeedsOwner, 2), "{s:?}");
599        assert_eq!(s.link.unwrap().kind, "decision");
600        assert!(inv.needs_owner().contains("chat-a"));
601        let other = inv.status_of("chat-b", true, Goals::default(), false);
602        assert_eq!(other.kind, Kind::Waiting, "{other:?}");
603    }
604
605    #[test]
606    fn machine_wait_and_unverified_running_are_distinct() {
607        let home = tempfile::TempDir::new().unwrap();
608        let mut held = task("held", "/repo", TaskStatus::Queued);
609        held.hold_machine(Some("[resource] cache busy".into()));
610        let running = task("running", "/repo", TaskStatus::Running);
611        let inv = Inventory::collect(home.path(), &[held, running], &[]);
612        assert_eq!(
613            inv.status_of("held", true, Goals::default(), false).kind,
614            Kind::Waiting
615        );
616        assert_eq!(
617            inv.status_of("running", true, Goals::default(), false).kind,
618            Kind::NeedsAttention
619        );
620    }
621
622    #[test]
623    fn failed_release_is_attention_not_automatic_wait() {
624        let home = tempfile::TempDir::new().unwrap();
625        let mut t = task("chat", "/repo", TaskStatus::Queued);
626        t.hold_machine(Some("[release] command failed".into()));
627        let inv = Inventory::collect(home.path(), &[t], &[]);
628        assert_eq!(
629            inv.status_of("chat", true, Goals::default(), false).kind,
630            Kind::NeedsAttention
631        );
632    }
633
634    #[test]
635    fn only_current_landing_approval_counts() {
636        let home = tempfile::TempDir::new().unwrap();
637        let mut t = task("chat", "/repo", TaskStatus::Parked);
638        let mut run = crate::run::RunState::new(
639            t.repo.clone(),
640            "main".into(),
641            "base".into(),
642            "task".into(),
643            crate::config::Config::default(),
644        );
645        run.status = crate::run::RunStatus::Landing;
646        t.runs.push(run.id.clone());
647        let question = |summary: &str| {
648            Question::new(
649                run.id.clone(),
650                crate::land::APPROVAL_NODE.into(),
651                "approval".into(),
652                summary.into(),
653                String::new(),
654                vec!["merge".into()],
655            )
656        };
657        let mut old = question("old");
658        old.id = "old".into();
659        let mut current = question("current");
660        current.id = "current".into();
661        run.land_approval = Some(crate::run::LandApproval {
662            question: current.id.clone(),
663            head: "head".into(),
664        });
665        run.save_under(home.path()).unwrap();
666        let inv = Inventory::collect(home.path(), &[t], &[old, current]);
667        let status = inv.status_of("chat", true, Goals::default(), false);
668        assert_eq!((status.kind, status.owner_count), (Kind::NeedsOwner, 1));
669    }
670
671    #[test]
672    fn returning_to_same_repo_does_not_revive_old_decision() {
673        let home = tempfile::TempDir::new().unwrap();
674        let mut t = task("chat", "/repo", TaskStatus::Queued);
675        let inquiry = Outbox::at(home.path())
676            .file(&t, None, "s".into(), "old", "d")
677            .unwrap();
678        t.reassignments.push(crate::queue::Reassignment {
679            from: "/other".into(),
680            to: t.repo.clone(),
681            actor: "operator".into(),
682            at: inquiry.created_at,
683            run_boundary: 0,
684        });
685        let inv = Inventory::collect(home.path(), &[t], &[]);
686        assert_eq!(
687            inv.status_of("chat", true, Goals::default(), false).kind,
688            Kind::Waiting
689        );
690    }
691
692    #[test]
693    fn unreadable_inquiry_is_explicit_unknown_not_idle() {
694        let home = tempfile::TempDir::new().unwrap();
695        let root = home.path().join("notifications/task-inquiries");
696        std::fs::create_dir_all(&root).unwrap();
697        std::fs::write(root.join("broken.json"), "{").unwrap();
698        let inv = Inventory::collect(home.path(), &[], &[]);
699        assert_eq!(
700            inv.status_of("any", true, Goals::default(), false).kind,
701            Kind::Unknown
702        );
703    }
704}