Skip to main content

agentmux_srv/server/
startup_refresh.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Keeps a running Claude agent's AgentMux-owned startup file current
5//! (`docs/specs/SPEC_MEMORY_DELIVERY_INDEX_NOT_FULL_TEXT_2026_11_17.md` section 3.1). The file is written when the
6//! agent is launched, and the CLI reads it again after a compaction or `/clear`; without a refresh it holds the
7//! Global Memory of the day of the launch, and the delivery that follows has to send every changed entry again.
8//!
9//! Global Memory has no single place where a change commits (the RPC handlers, the `Memory` tool, a revert, the fleet
10//! sync and the Operator Config seed all write it), so this does not hook the writers: every [`CHECK_EVERY`] it
11//! compares a fingerprint of the Global sections and, when it moved, re-renders the startup file of each running
12//! Claude pane. The refresh is not tied to a compaction or to the hook: one made after the CLI has reloaded the old
13//! file would hide the changed sections from the delivery's per-section check and leave the agent with the old copy.
14
15use std::hash::{DefaultHasher, Hash, Hasher};
16use std::path::Path;
17use std::time::Duration;
18
19use crate::backend::agent_config::{AGENTMUX_MEMORY_FILENAME, CLAUDE_MD_MANAGED_MARKER};
20use crate::backend::obj::{self, Block};
21use crate::backend::storage::store::Store;
22use crate::server::AppState;
23
24const CHECK_EVERY: Duration = Duration::from_secs(20);
25
26/// How a pane's startup file fared.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(crate) enum Refresh {
29    Written,
30    /// Not a Claude agent: the other providers' files are never overwritten once they exist.
31    NotClaude,
32    /// No folder on the pane, or no startup file of AgentMux's in it: a user's own project is left as it is.
33    NotOurs,
34    /// The pane or its agent's definition is gone, so nothing is known about the pane's folder.
35    Unknown,
36    Failed,
37}
38
39impl Refresh {
40    /// Whether the pane was a Claude agent whose folder was looked at, so another pane in the same folder would meet
41    /// the same file and is not visited again. A pane that was not (another provider, a pane or definition that is
42    /// gone) leaves the folder to the next pane.
43    fn handled_the_folder(self) -> bool {
44        !matches!(self, Refresh::NotClaude | Refresh::Unknown)
45    }
46}
47
48/// Starts the watcher.
49pub(crate) fn start(state: AppState) {
50    tokio::spawn(async move {
51        let mut tick = tokio::time::interval(CHECK_EVERY);
52        let mut watch = Watch::default();
53        loop {
54            tick.tick().await;
55            let state = state.clone();
56            let moved = tokio::task::spawn_blocking(move || {
57                let moved = watch.changed(fingerprint(&state.id_store));
58                if moved {
59                    refresh_running(&state);
60                }
61                watch
62            })
63            .await;
64            match moved {
65                Ok(next) => watch = next,
66                Err(e) => tracing::warn!(error = %e, "startup refresh: the check did not finish"),
67            }
68        }
69    });
70}
71
72/// What the last check saw. The first check records a baseline: a file older than this srv is covered by the
73/// delivery's per-section check, and refreshing every agent at boot would only add a write burst to it.
74#[derive(Debug, Clone, Copy, Default)]
75struct Watch {
76    seen: Option<u64>,
77}
78
79impl Watch {
80    /// Whether Global Memory moved since the last check. A check that could not read it changes nothing.
81    fn changed(&mut self, now: Option<u64>) -> bool {
82        let Some(now) = now else { return false };
83        let moved = self.seen.is_some_and(|seen| seen != now);
84        self.seen = Some(now);
85        moved
86    }
87}
88
89/// A fingerprint of every Global section (a section's id and text). Operator Config entries that target another kind
90/// of agent are in it too: a change to one refreshes agents that do not carry it, which rewrites their file with the
91/// same text.
92fn fingerprint(id_store: &Store) -> Option<u64> {
93    let bundles = id_store.bundle_list_global().ok()?;
94    let mut hasher = DefaultHasher::new();
95    for section in crate::backend::storage::global_bundle_sections(&bundles) {
96        section.id.hash(&mut hasher);
97        section.text.hash(&mut hasher);
98    }
99    Some(hasher.finish())
100}
101
102/// Refreshes the startup file of every running agent pane, once per folder.
103fn refresh_running(state: &AppState) {
104    let Ok(defs) = state.mstore.agent_def_list() else { return };
105    let panes: Vec<String> = defs.iter().flat_map(|def| crate::backend::worker_notes::live_panes_of(&state.mstore, &def.id)).collect();
106    let written = refresh_panes(state, &panes);
107    if written > 0 {
108        tracing::info!(files = written, "startup refresh: Global Memory changed, startup files rewritten");
109    }
110}
111
112/// Refreshes the startup file of each pane in turn, once per folder, and returns how many it wrote. A folder counts
113/// as done only after a Claude pane has been looked at in it: a pane of another provider that comes first must not
114/// use it up and leave a Claude pane in the same folder with a stale file.
115fn refresh_panes(state: &AppState, panes: &[String]) -> usize {
116    let (mut written, mut seen_dirs) = (0usize, std::collections::HashSet::new());
117    for block_id in panes {
118        let Some(cwd) = startup_file_key(&state.mstore, block_id) else { continue };
119        if seen_dirs.contains(&cwd) {
120            continue;
121        }
122        let outcome = refresh_pane(state, block_id);
123        if outcome.handled_the_folder() {
124            seen_dirs.insert(cwd);
125        }
126        if outcome == Refresh::Written {
127            written += 1;
128        }
129    }
130    written
131}
132
133/// The pane's folder as a path that exists on this machine. `agent.open` stores a default folder as
134/// `~/.agentmux/agents/<slug>`, unexpanded, and the launch expands it when it writes the file.
135fn pane_cwd(mstore: &Store, block_id: &str) -> Option<String> {
136    let block = mstore.get::<Block>(block_id).ok().flatten()?;
137    let raw = obj::meta_get_string(&block.meta, "cmd:cwd", "");
138    let raw = raw.trim();
139    (!raw.is_empty()).then(|| crate::backend::base::expand_home_dir_safe(raw).to_string_lossy().into_owned())
140}
141
142/// What names the startup file a pane's agent reads: its folder, and whether the file is kept outside it (a host
143/// agent in a folder a container agent can write, `host_agent_files`). A container agent's pane on the same
144/// folder reads the folder's own file, which is another one.
145fn startup_file_key(mstore: &Store, block_id: &str) -> Option<String> {
146    let cwd = pane_cwd(mstore, block_id)?;
147    let block = mstore.get::<Block>(block_id).ok().flatten()?;
148    let outside = crate::backend::mcp_folder_rule::folder_of(&block.meta).is_some();
149    Some(if outside { format!("{cwd} (outside)") } else { cwd })
150}
151
152/// Re-renders the pane's startup file from the agent's definition, the way its launch did, through the writer that
153/// never touches a file AgentMux does not own.
154pub(crate) fn refresh_pane(state: &AppState, block_id: &str) -> Refresh {
155    let Some(block) = state.mstore.get::<Block>(block_id).ok().flatten() else { return Refresh::Unknown };
156    let agent_id = obj::meta_get_string(&block.meta, "agentId", "");
157    let Some(dir) = pane_cwd(&state.mstore, block_id) else { return Refresh::NotOurs };
158    let Ok(Some(def)) = state.mstore.agent_def_get(&agent_id) else { return Refresh::Unknown };
159    let provider = state.id_store.resolve_effective_provider_id(&def);
160    if crate::backend::providers::resolve_provider_alias(&provider) != "claude" {
161        return Refresh::NotClaude;
162    }
163    let dir = Path::new(&dir);
164    // A host agent in a folder a container agent can write reads its startup file from outside the folder.
165    let outside = crate::backend::mcp_folder_rule::folder_of(&block.meta).is_some();
166    if !outside && !has_an_agentmux_startup_file(dir) {
167        return Refresh::NotOurs;
168    }
169    // The name the pane was launched under fills `{{AGENT}}` and `{{AGENT_DISPLAY}}`, as it did when the file was
170    // first written; the whole file is replaced here, so the definition's own name would overwrite it.
171    let launched_name = obj::meta_get_string(&block.meta, "agentName", "");
172    let instance_name = Some(launched_name.as_str()).filter(|n| !n.trim().is_empty());
173    let files = match crate::server::picker_config::launch_files(&state.mstore, &state.id_store, &state.identity_store, &agent_id, instance_name, &dir.to_string_lossy()) {
174        Ok(files) => files,
175        Err(e) => {
176            tracing::warn!(agent_id = %agent_id, error = %e, "startup refresh: could not render the startup file");
177            return Refresh::Failed;
178        }
179    };
180    let Some(claude_md) = files.into_iter().find(|f| f.path == "CLAUDE.md") else { return Refresh::NotOurs };
181    if outside {
182        return match crate::backend::host_agent_files::refresh_instructions(&dir.to_string_lossy(), &claude_md.content) {
183            Ok(true) => Refresh::Written,
184            Ok(false) => Refresh::NotOurs,
185            Err(e) => {
186                tracing::warn!(agent_id = %agent_id, error = %e, "startup refresh: could not write the startup file kept outside the folder");
187                Refresh::Failed
188            }
189        };
190    }
191    match crate::backend::agent_config::write_claude_md_respecting_ownership(dir, &claude_md.content) {
192        Ok(()) => Refresh::Written,
193        Err(e) => {
194            tracing::warn!(agent_id = %agent_id, dir = %dir.display(), error = %e, "startup refresh: could not write the startup file");
195            Refresh::Failed
196        }
197    }
198}
199
200/// Whether `dir` holds a startup file AgentMux wrote: a `CLAUDE.md` with its marker, or the memory file a user's own
201/// `CLAUDE.md` imports. A folder with neither is not given one by a refresh.
202fn has_an_agentmux_startup_file(dir: &Path) -> bool {
203    let claude_md = std::fs::read_to_string(dir.join("CLAUDE.md")).unwrap_or_default();
204    claude_md.starts_with(CLAUDE_MD_MANAGED_MARKER) || dir.join(AGENTMUX_MEMORY_FILENAME).is_file()
205}
206
207#[cfg(test)]
208mod tests;