Skip to main content

agentmux_srv_core/backend/work_facts/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Work facts: per running agent, what srv can already see or cheaply derive
5//! about what it is working on, so agents can find out who else is working
6//! on the same file, branch or topic
7//! (docs/specs/SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md ยง3.1).
8//!
9//! | Fact | Source |
10//! |---|---|
11//! | goal | the line the agent set itself ([`live_phrase`]), else block meta `term:ambient_summary`, else `term:last_prompt` |
12//! | todos, current tool, recent files | the progress watcher (`reactive::progress_watcher`) |
13//! | working folder | bashwrap's cwd state file, else the start folder (`cmd:cwd`) |
14//! | repo, branch, uncommitted files | git in that folder, cached ([`git`]) |
15//!
16//! Files are compared across clones as (repository, repository-relative
17//! path), since every agent has its own clone. Nothing here blocks anyone:
18//! the facts only inform, through `WhoIsWorkingOn` ([`matching`]) and the
19//! overlap notes an agent gets when it edits a file another agent is also
20//! changing ([`overlap`], [`overlap_notes`]).
21//! What agents say they are working on (`ClaimWork`, [`claims`]) joins both.
22
23pub mod claims;
24pub mod coord;
25pub mod cross_channel;
26pub mod git;
27pub mod live_phrase;
28pub mod matching;
29pub mod overlap;
30pub mod overlap_notes;
31pub mod paths;
32
33use std::path::Path;
34
35use serde::{Deserialize, Serialize};
36
37use crate::backend::blockcontroller::{cmd_env_of, get_block_controller_status, META_KEY_CMD_CWD, STATUS_RUNNING};
38use crate::backend::obj::{self, Block, MetaMapType};
39use crate::backend::reactive::progress_watcher::{watched_work, TodoItem};
40use crate::backend::reactive::types::AgentRegistration;
41use crate::backend::storage::store::Store;
42
43/// The block meta key the agent pane writes the latest prompt to
44/// (`frontend/app/store/swarm-line.ts`, `META_LAST_PROMPT`).
45const META_LAST_PROMPT: &str = "term:last_prompt";
46
47/// One file an agent changed recently.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49pub struct FactFile {
50    /// Normalized absolute path, as the tool call named it.
51    pub path: String,
52    /// Relative to the agent's repository, when the file is inside it.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub rel: Option<String>,
55    pub tool: String,
56    pub ts_ms: u64,
57}
58
59/// Everything known about one agent's current work.
60#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
61pub struct WorkFacts {
62    pub agent: String,
63    pub block_id: String,
64    /// The AgentMux channel the agent runs in (`stable`, `dev`, ...).
65    pub channel: String,
66    /// `busy` (a turn is running), `idle`, or `stopped`.
67    pub status: String,
68    pub goal: Option<String>,
69    pub working_folder: Option<String>,
70    pub repo: Option<String>,
71    pub repo_root: Option<String>,
72    pub branch: Option<String>,
73    /// Repository-relative, at most a few hundred; `dirty_count` is the total.
74    pub dirty_files: Vec<String>,
75    pub dirty_count: usize,
76    /// Newest first.
77    pub recent_files: Vec<FactFile>,
78    pub todos: Vec<TodoItem>,
79    pub current_tool: Option<String>,
80    /// When git was last asked; `None` before the first probe or outside a
81    /// repository.
82    pub git_checked_ms: Option<u64>,
83    /// Set while this agent holds the host's build slot (`agentmux_common::build_slot`): other
84    /// agents' builds and tests wait behind it.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub build_slot: Option<BuildSlotHold>,
87    /// Where the agent runs: [`RUNS_ON_HOST`] or [`RUNS_IN_CONTAINER`]. `None` from an AgentMux that does
88    /// not say.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub runs_in: Option<String>,
91}
92
93/// [`WorkFacts::runs_in`] of an agent that runs as a process of this machine.
94pub const RUNS_ON_HOST: &str = "host";
95/// [`WorkFacts::runs_in`] of an agent that runs in a container.
96pub const RUNS_IN_CONTAINER: &str = "container";
97
98/// How long and why an agent has held the build slot.
99#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
100pub struct BuildSlotHold {
101    /// When it took the slot, epoch milliseconds.
102    pub since_ms: u64,
103    pub reason: String,
104    /// The command line, cut to 120 characters (see `SlotHolder::command`).
105    pub command: String,
106}
107
108impl WorkFacts {
109    /// The key two agents share when they work in the same repository: the
110    /// `owner/repo` of its origin, else (no remote) the clone's own folder.
111    pub fn repo_key(&self) -> Option<String> {
112        self.repo.clone().or_else(|| self.repo_root.as_ref().map(|r| format!("local:{r}")))
113    }
114
115    /// Whether the AgentMux of `channel` may run git in this agent's clone. It does for its own agents,
116    /// whose folders it knows (a container agent's is read inside its container), and for an agent of
117    /// another AgentMux only when that one says it runs on the host.
118    pub fn clone_is_read_by(&self, channel: &str) -> bool {
119        self.channel == channel || self.runs_in.as_deref() == Some(RUNS_ON_HOST)
120    }
121}
122
123/// The agent's goal: the line it set itself (or the title of the task it
124/// claimed), else its generated title, else its last prompt.
125pub fn goal_of(meta: &MetaMapType) -> Option<String> {
126    if let Some(declared) = live_phrase::declared_of(meta) {
127        return Some(declared.text);
128    }
129    let title = obj::meta_get_string(meta, crate::ambient::title::META_TITLE, "");
130    if crate::ambient::validate::is_usable_title(&title) {
131        return Some(title.trim().to_string());
132    }
133    let prompt = obj::meta_get_string(meta, META_LAST_PROMPT, "");
134    let prompt = prompt.trim();
135    (!prompt.is_empty()).then(|| prompt.to_string())
136}
137
138/// The agent's working folder (see [`paths::working_folder`]), from its
139/// block row. Reads the store: call off the async workers.
140pub fn folder_of(store: &Store, home: Option<&Path>, reg: &AgentRegistration) -> Option<String> {
141    let block = store.get::<Block>(&reg.block_id).ok()??;
142    folder_of_meta(&block.meta, home, &reg.agent_id)
143}
144
145fn folder_of_meta(meta: &MetaMapType, home: Option<&Path>, agent_id: &str) -> Option<String> {
146    let env = cmd_env_of(meta);
147    let start = obj::meta_get_string(meta, META_KEY_CMD_CWD, "");
148    paths::working_folder(home, &env, agent_id, &start)
149}
150
151fn status_of(block_id: &str) -> &'static str {
152    match get_block_controller_status(block_id) {
153        Some(s) if s.shellprocstatus == STATUS_RUNNING => {
154            if s.turn_active {
155                "busy"
156            } else {
157                "idle"
158            }
159        }
160        _ => "stopped",
161    }
162}
163
164/// The facts for every agent registered on this srv. Reads the store and
165/// the caches only, never git: call off the async workers.
166pub fn collect_local(store: &Store, regs: &[AgentRegistration], channel: &str) -> Vec<WorkFacts> {
167    let home = dirs::home_dir();
168    let slot = agentmux_common::build_slot::holder();
169    regs.iter()
170        .map(|reg| {
171            let meta = store.get::<Block>(&reg.block_id).ok().flatten().map(|b| b.meta).unwrap_or_default();
172            let folder = folder_of_meta(&meta, home.as_deref(), &reg.agent_id);
173            let git = folder.as_deref().and_then(|d| git::cached(&reg.block_id, d));
174            let watched = watched_work(&reg.block_id).unwrap_or_default();
175            let mut facts = build(reg, channel, status_of(&reg.block_id), goal_of(&meta), folder, git, watched);
176            facts.build_slot = build_slot_of(slot.as_ref(), &reg.agent_id, || {
177                crate::backend::spawn_env::identity::block_agent_slug(store, &reg.block_id)
178            });
179            let in_container = crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&meta).is_container();
180            facts.runs_in = Some(if in_container { RUNS_IN_CONTAINER } else { RUNS_ON_HOST }.to_string());
181            facts
182        })
183        .collect()
184}
185
186/// The build slot hold to show on the agent `agent_id`, when `holder` is that agent. The lock
187/// names its holder by `AGENTMUX_AGENT_ID`, the slug; the registry by name, so either may match.
188/// `slug` is only asked for while somebody holds the slot.
189pub fn build_slot_of(
190    holder: Option<&agentmux_common::build_slot::SlotHolder>,
191    agent_id: &str,
192    slug: impl FnOnce() -> Option<String>,
193) -> Option<BuildSlotHold> {
194    let h = holder?;
195    let is_it = h.agent.eq_ignore_ascii_case(agent_id) || slug().is_some_and(|s| h.agent.eq_ignore_ascii_case(&s));
196    is_it.then(|| BuildSlotHold { since_ms: h.since_ms, reason: h.reason.clone(), command: h.command.clone() })
197}
198
199/// Assemble one agent's facts from what each source said.
200pub fn build(
201    reg: &AgentRegistration,
202    channel: &str,
203    status: &str,
204    goal: Option<String>,
205    working_folder: Option<String>,
206    git: Option<git::GitFacts>,
207    watched: crate::backend::reactive::progress_watcher::WatchedWork,
208) -> WorkFacts {
209    let root = git.as_ref().map(|g| g.root.clone());
210    let recent_files = watched
211        .recent_files
212        .into_iter()
213        .map(|f| {
214            let path = paths::normalize_path(&f.path);
215            let rel = root.as_deref().and_then(|r| paths::relative_to(&path, r)).filter(|r| !r.is_empty());
216            FactFile { path, rel, tool: f.tool, ts_ms: f.ts_ms }
217        })
218        .collect();
219    let git = git.unwrap_or_default();
220    WorkFacts {
221        agent: reg.agent_id.clone(),
222        block_id: reg.block_id.clone(),
223        channel: channel.to_string(),
224        status: status.to_string(),
225        goal,
226        working_folder,
227        repo: git.repo,
228        repo_root: root,
229        branch: git.branch,
230        dirty_files: git.dirty_files,
231        dirty_count: git.dirty_count,
232        recent_files,
233        todos: watched.progress.todos,
234        current_tool: watched.progress.current_tool,
235        git_checked_ms: (git.checked_ms > 0).then_some(git.checked_ms),
236        build_slot: None,
237        runs_in: None,
238    }
239}
240
241/// How many uncommitted and recent files a `ListConversations` entry shows.
242const SUMMARY_DIRTY: usize = 10;
243const SUMMARY_RECENT: usize = 5;
244
245/// The facts as a `ListConversations` entry carries them (its `work` field):
246/// the first few files of each list and a checklist summary.
247pub fn conversation_summary(f: &WorkFacts) -> serde_json::Value {
248    let done = f.todos.iter().filter(|t| t.status == "completed").count();
249    let in_progress: Vec<&str> =
250        f.todos.iter().filter(|t| t.status == "in_progress").map(|t| t.text.as_str()).take(3).collect();
251    serde_json::json!({
252        "goal": f.goal,
253        "working_folder": f.working_folder,
254        "repo": f.repo,
255        "branch": f.branch,
256        "dirty_count": f.dirty_count,
257        "dirty_files": f.dirty_files.iter().take(SUMMARY_DIRTY).collect::<Vec<_>>(),
258        "recent_files": f.recent_files.iter().take(SUMMARY_RECENT).map(|r| serde_json::json!({
259            "path": r.rel.as_deref().unwrap_or(&r.path),
260            "tool": r.tool,
261            "ts_ms": r.ts_ms,
262        })).collect::<Vec<_>>(),
263        "todos": { "total": f.todos.len(), "completed": done, "in_progress": in_progress },
264        "current_tool": f.current_tool,
265        "git_checked_ms": f.git_checked_ms,
266    })
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use crate::backend::reactive::progress_watcher::{AgentProgress, RecentFile, WatchedWork};
273
274    fn reg(agent: &str, block: &str) -> AgentRegistration {
275        AgentRegistration {
276            agent_id: agent.to_string(),
277            block_id: block.to_string(),
278            tab_id: None,
279            uid: None,
280            registered_at: 0,
281            last_seen: 0,
282            registration_nonce: 0,
283        }
284    }
285
286    fn meta(pairs: &[(&str, &str)]) -> MetaMapType {
287        pairs.iter().map(|(k, v)| (k.to_string(), serde_json::Value::String(v.to_string()))).collect()
288    }
289
290    #[test]
291    fn the_goal_is_the_title_else_the_last_prompt() {
292        assert_eq!(
293            goal_of(&meta(&[("term:ambient_summary", "Fix the login race"), ("term:last_prompt", "hi")])).as_deref(),
294            Some("Fix the login race")
295        );
296        assert_eq!(
297            goal_of(&meta(&[("term:ambient_summary", ""), ("term:last_prompt", " add the allowlist ")])).as_deref(),
298            Some("add the allowlist")
299        );
300        assert_eq!(goal_of(&meta(&[])), None);
301    }
302
303    #[test]
304    fn the_line_the_agent_set_comes_before_the_title_and_the_last_prompt() {
305        let m = meta(&[
306            ("term:live_phrase", " Fixing the stale-site restore loop "),
307            ("term:ambient_summary", "Implement card tags and filter chips"),
308            ("term:last_prompt", "hi there"),
309        ]);
310        assert_eq!(goal_of(&m).as_deref(), Some("Fixing the stale-site restore loop"));
311        // Cleared, it falls back to what it did before.
312        let cleared = meta(&[("term:live_phrase", ""), ("term:ambient_summary", "Fix the login race")]);
313        assert_eq!(goal_of(&cleared).as_deref(), Some("Fix the login race"));
314    }
315
316    #[test]
317    fn git_is_run_in_another_agentmuxs_clone_only_for_an_agent_that_says_it_runs_on_the_host() {
318        let facts = |channel: &str, runs_in: Option<&str>| WorkFacts {
319            channel: channel.to_string(),
320            runs_in: runs_in.map(str::to_string),
321            ..Default::default()
322        };
323        assert!(facts("stable", Some(RUNS_IN_CONTAINER)).clone_is_read_by("stable"), "its own agent: read where its folder's git runs");
324        assert!(facts("stable", None).clone_is_read_by("stable"));
325        assert!(facts("dev", Some(RUNS_ON_HOST)).clone_is_read_by("stable"));
326        assert!(!facts("dev", Some(RUNS_IN_CONTAINER)).clone_is_read_by("stable"));
327        assert!(!facts("dev", None).clone_is_read_by("stable"), "an AgentMux that does not say is not read");
328    }
329
330    #[test]
331    fn build_maps_recent_files_into_the_repository_and_keeps_watcher_state() {
332        let git = git::GitFacts {
333            root: "C:/w/clone".into(),
334            repo: Some("o/r".into()),
335            branch: Some("feat".into()),
336            dirty_files: vec!["a.rs".into()],
337            dirty_count: 1,
338            error: None,
339            checked_ms: 7,
340        };
341        let watched = WatchedWork {
342            progress: AgentProgress {
343                todos: vec![TodoItem { text: "Ship".into(), status: "in_progress".into() }],
344                current_tool: Some("Edit".into()),
345                ..Default::default()
346            },
347            recent_files: vec![
348                RecentFile { path: r"C:\w\clone\src\b.rs".into(), tool: "Edit".into(), ts_ms: 5 },
349                RecentFile { path: "D:/elsewhere/c.rs".into(), tool: "Write".into(), ts_ms: 4 },
350            ],
351        };
352        let f = build(&reg("A", "b1"), "stable", "idle", None, Some("C:/w/clone".into()), Some(git), watched);
353        assert_eq!(f.repo.as_deref(), Some("o/r"));
354        assert_eq!(f.recent_files[0].rel.as_deref(), Some("src/b.rs"));
355        assert_eq!(f.recent_files[0].path, "C:/w/clone/src/b.rs");
356        assert_eq!(f.recent_files[1].rel, None, "outside the repository");
357        assert_eq!(f.current_tool.as_deref(), Some("Edit"));
358        assert_eq!(f.git_checked_ms, Some(7));
359        assert_eq!(f.repo_key().as_deref(), Some("o/r"));
360
361        let summary = conversation_summary(&f);
362        assert_eq!(summary["dirty_count"], 1);
363        assert_eq!(summary["recent_files"][0]["path"], "src/b.rs");
364        assert_eq!(summary["todos"]["in_progress"][0], "Ship");
365    }
366
367    #[test]
368    fn a_repository_without_a_remote_is_keyed_by_its_folder() {
369        let f = WorkFacts { repo_root: Some("C:/w/x".into()), ..Default::default() };
370        assert_eq!(f.repo_key().as_deref(), Some("local:C:/w/x"));
371        assert_eq!(WorkFacts::default().repo_key(), None);
372    }
373
374    #[test]
375    fn the_build_slot_is_shown_on_the_holder_by_slug_or_name_and_only_while_held() {
376        use agentmux_common::build_slot::SlotHolder;
377        let holder = SlotHolder { agent: "naki-naki-2".into(), since_ms: 5, reason: "cargo test".into(), command: "cargo test -p x".into(), ..Default::default() };
378        let hold = BuildSlotHold { since_ms: 5, reason: "cargo test".into(), command: "cargo test -p x".into() };
379        // By slug: the registry's name is the display name.
380        assert_eq!(build_slot_of(Some(&holder), "Naki-2", || Some("Naki-Naki-2".into())), Some(hold.clone()));
381        // By name, without asking for the slug.
382        let named = SlotHolder { agent: "lazo".into(), ..holder.clone() };
383        assert!(build_slot_of(Some(&named), "Lazo", || panic!("the name matched; no slug lookup")).is_some());
384        // Somebody else, or no slug, or nobody holding it.
385        assert_eq!(build_slot_of(Some(&holder), "Manoz", || Some("manoz".into())), None);
386        assert_eq!(build_slot_of(Some(&holder), "Naki-2", || None), None);
387        assert_eq!(build_slot_of(None, "Lazo", || panic!("nobody holds it; no slug lookup")), None);
388        // It is on the wire only while held.
389        let held = WorkFacts { agent: "A".into(), build_slot: Some(hold), ..Default::default() };
390        assert_eq!(serde_json::to_value(&held).unwrap()["build_slot"]["reason"], "cargo test");
391        assert!(serde_json::to_value(WorkFacts::default()).unwrap().get("build_slot").is_none());
392    }
393
394    #[test]
395    fn facts_round_trip_for_the_cross_channel_endpoint() {
396        let f = WorkFacts {
397            agent: "A".into(),
398            todos: vec![TodoItem { text: "t".into(), status: "pending".into() }],
399            recent_files: vec![FactFile { path: "/x".into(), rel: None, tool: "Edit".into(), ts_ms: 1 }],
400            ..Default::default()
401        };
402        let back: WorkFacts = serde_json::from_value(serde_json::to_value(&f).unwrap()).unwrap();
403        assert_eq!(back, f);
404    }
405}