Skip to main content

agentmux_srv_core/backend/
continuity_facts.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What AgentMux knows about an agent at the moment its session restarts, written
5//! without a model (SPEC_AGENT_PREP_BEFORE_SESSION_RESTART_2026_11_14.md §6, item 4).
6//!
7//! The running summary is up to ten minutes old and needs an account that can
8//! make it. These facts are read from the stores when the packet is built, so
9//! "In flight" no longer depends on the summarizer alone: the Kanban tasks the
10//! agent holds, the commands it left running, the status line it set and the
11//! state of its working clone.
12
13use crate::backend::obj::Block;
14use crate::backend::storage::background_tasks::BackgroundTaskStatus;
15use crate::backend::storage::store::Store;
16
17/// Most entries listed per kind; the rest is a count.
18const MAX_LISTED: usize = 5;
19/// Longest a title, label or status line is written.
20const MAX_TEXT_CHARS: usize = 120;
21
22pub(crate) struct HeldTask {
23    /// How the task is written (`#47659`, or `board#12`).
24    pub reference: String,
25    pub title: String,
26}
27
28pub(crate) struct Background {
29    pub label: String,
30    pub started_at_ms: i64,
31    /// Whether the process was found alive just now; `None` when it has no pid to ask about.
32    pub alive: Option<bool>,
33}
34
35pub(crate) struct StatusLine {
36    pub text: String,
37    pub state: Option<String>,
38    pub set_at_ms: u64,
39}
40
41pub(crate) struct WorkingClone {
42    pub branch: Option<String>,
43    pub dirty_files: usize,
44    pub checked_ms: Option<u64>,
45}
46
47#[derive(Default)]
48pub(crate) struct Facts {
49    pub tasks: Vec<HeldTask>,
50    pub background: Vec<Background>,
51    pub line: Option<StatusLine>,
52    pub repo: Option<WorkingClone>,
53}
54
55fn short(text: &str) -> String {
56    let one_line = text.split_whitespace().collect::<Vec<_>>().join(" ");
57    if one_line.chars().count() <= MAX_TEXT_CHARS {
58        return one_line;
59    }
60    let cut: String = one_line.chars().take(MAX_TEXT_CHARS - 1).collect();
61    format!("{cut}…")
62}
63
64fn age(ms: i64) -> String {
65    let s = (ms.max(0) / 1000) as u64;
66    match s {
67        0..=89 => format!("{s} s"),
68        90..=5_399 => format!("{} min", (s + 30) / 60),
69        _ => format!("{} h", (s + 1_800) / 3_600),
70    }
71}
72
73/// The facts as the lines of the packet's block; empty when there is nothing to say.
74pub(crate) fn render(facts: &Facts, now_ms: i64) -> String {
75    let mut lines: Vec<String> = Vec::new();
76    if !facts.tasks.is_empty() {
77        let mut parts: Vec<String> =
78            facts.tasks.iter().take(MAX_LISTED).map(|t| format!("{} {}", t.reference, short(&t.title))).collect();
79        if facts.tasks.len() > MAX_LISTED {
80            parts.push(format!("and {} more", facts.tasks.len() - MAX_LISTED));
81        }
82        lines.push(format!("- Kanban tasks you hold (claimed): {}. Re-read a task's brief with Tasks get (id), not from a summary.", parts.join("; ")));
83    }
84    if !facts.background.is_empty() {
85        let mut parts: Vec<String> = facts
86            .background
87            .iter()
88            .take(MAX_LISTED)
89            .map(|b| {
90                let state = match b.alive {
91                    Some(true) => "process alive",
92                    Some(false) => "process gone",
93                    None => "no pid",
94                };
95                format!("{} (running {}, {state})", short(&b.label), age(now_ms - b.started_at_ms))
96            })
97            .collect();
98        if facts.background.len() > MAX_LISTED {
99            parts.push(format!("and {} more", facts.background.len() - MAX_LISTED));
100        }
101        lines.push(format!("- Background commands the record shows running: {}", parts.join("; ")));
102    }
103    if let Some(l) = &facts.line {
104        let state = l.state.as_deref().map_or_else(String::new, |s| format!(" [{s}]"));
105        let set = if l.set_at_ms > 0 { format!(", set {} ago", age(now_ms - l.set_at_ms as i64)) } else { String::new() };
106        lines.push(format!("- Your status line{state}{set}: {}", short(&l.text)));
107    }
108    if let Some(c) = &facts.repo {
109        let branch = c.branch.as_deref().map_or_else(|| "no branch".to_string(), |b| format!("branch {b}"));
110        let checked = c.checked_ms.filter(|ms| *ms > 0).map_or_else(String::new, |ms| format!(" (checked {} ago)", age(now_ms - ms as i64)));
111        lines.push(format!("- Working clone: {branch}, {} files with uncommitted changes{checked}", c.dirty_files));
112    }
113    lines.join("\n")
114}
115
116/// What a restart of the session would cost, in the words the log and the audit row use, or `None`
117/// when nothing is lost: a Kanban task held, a command still running (one found dead is not), or
118/// files with uncommitted changes in the working clone (SPEC_AGENT_PREP_BEFORE_SESSION_RESTART_2026_11_14.md §3.2).
119pub(crate) fn something_lost(facts: &Facts) -> Option<&'static str> {
120    if !facts.tasks.is_empty() {
121        Some("holds a claimed task")
122    } else if facts.background.iter().any(|b| b.alive != Some(false)) {
123        Some("a background command is running")
124    } else if facts.repo.as_ref().is_some_and(|c| c.dirty_files > 0) {
125        Some("uncommitted changes in its working clone")
126    } else {
127        None
128    }
129}
130
131/// [`something_lost`] for the agent in `block_id`, read from the stores. Blocking reads.
132pub fn something_to_lose(mstore: &Store, identity: Option<&Store>, block_id: &str) -> Option<&'static str> {
133    something_lost(&collect(mstore, identity, block_id))
134}
135
136/// The Kanban tasks the agent holds (state `claimed`), each with how it is written (`#47659`, or
137/// `board#12`). `uid` may be empty. Blocking reads.
138pub(crate) fn held_tasks(identity: &Store, agent_id: &str, uid: &str) -> Vec<(String, crate::backend::storage::work_queue::WorkItem)> {
139    let mut out = Vec::new();
140    // The store's lookup matches the name or the UID; the holder rule narrows it to the UID when both sides have one.
141    let items = identity.work_queue_claimed_by(agent_id, uid).unwrap_or_default();
142    for item in crate::backend::work_claims::claims_held_by(&items, agent_id, Some(uid)).into_iter().cloned() {
143        let reference = match identity.work_task_board(&item.id) {
144            Ok(Some((board, num))) => board.task_ref(num),
145            _ => "task".to_string(),
146        };
147        out.push((reference, item));
148    }
149    out
150}
151
152/// The facts for the agent in `block_id`, from the stores. Blocking reads: call off the async workers.
153pub(crate) fn collect(mstore: &Store, identity: Option<&Store>, block_id: &str) -> Facts {
154    let mut facts = Facts::default();
155    let Some(agent_id) = crate::identity::resolver::block_agent_id(mstore, block_id) else { return facts };
156    // A spawn started by a jekt runs under the reactive handler's own lock, and building the packet is part of
157    // that spawn: the blocking `list_agents` would wait for a lock this very thread holds, for good (#48776).
158    // The bounded try-lock answers `None` then, and the facts that need the registration are left out.
159    let reg = crate::backend::reactive::get_global_handler().try_get_agent_by_block(block_id);
160    let reg = reg.as_ref();
161
162    if let Some(identity) = identity {
163        let uid = reg.and_then(|r| r.uid.clone()).unwrap_or_default();
164        for (reference, item) in held_tasks(identity, &agent_id, &uid) {
165            facts.tasks.push(HeldTask { reference, title: item.title });
166        }
167    }
168
169    for task in mstore.background_task_list_for_block(block_id).unwrap_or_default() {
170        if task.status != BackgroundTaskStatus::Running {
171            continue;
172        }
173        let alive = task.pid.and_then(|p| u32::try_from(p).ok()).map(crate::backend::reactive::registry::pid_alive);
174        facts.background.push(Background { label: task.label, started_at_ms: task.started_at_ms, alive });
175    }
176
177    let meta = mstore.get::<Block>(block_id).ok().flatten().map(|b| b.meta).unwrap_or_default();
178    if let Some(d) = crate::backend::work_facts::live_phrase::declared_of(&meta) {
179        facts.line = Some(StatusLine { text: d.text, state: d.state, set_at_ms: d.at_ms });
180    }
181    if let Some(reg) = reg {
182        let channel = crate::backend::work_facts::cross_channel::own_channel();
183        if let Some(w) = crate::backend::work_facts::collect_local(mstore, std::slice::from_ref(reg), &channel).pop() {
184            if w.working_folder.is_some() && (w.branch.is_some() || w.git_checked_ms.is_some()) {
185                facts.repo = Some(WorkingClone { branch: w.branch, dirty_files: w.dirty_count, checked_ms: w.git_checked_ms });
186            }
187        }
188    }
189    facts
190}
191
192#[cfg(test)]
193#[path = "continuity_facts_tests.rs"]
194mod tests;