Skip to main content

mur_common/agent/
reload.rs

1//! Which `profile.yaml` edits a running agent may pick up without a restart.
2//!
3//! One classifier for both sides: the runtime decides what to apply, the CLI
4//! decides whether to say "next turn" or "restart". Two hand-kept lists would
5//! drift, and the side that drifted would lie to the user.
6//!
7//! The comparison walks the serialized profile instead of naming fields, so a
8//! field added to [`AgentProfile`] later lands in `cold` by default. That is
9//! the safe direction: an unclassified field can only ever cost a restart, it
10//! can never be hot-applied by accident — which matters because the locked set
11//! includes entitlements and the sandbox.
12
13use super::AgentProfile;
14use super::reload_mcp::{MCP_SERVERS, diff_mcp_servers, overlay_hot_entries};
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::collections::BTreeMap;
18
19/// Dotted paths that take effect on the next turn.
20///
21/// `mcp_servers` is not listed: it is diffed per entry by name
22/// (`reload_mcp`), and a hot entry is reported as `mcp_servers.<name>`.
23///
24/// `addons` is here for the skill gate; its MCP half is not hot (MCP servers
25/// are spawned at boot), so a changed `addons` is reported in both lists.
26pub const HOT_PATHS: &[&str] = &[
27    "limits",
28    "disabled_skills",
29    "addons",
30    "hitl.autonomy",
31    "lifecycle.schedule",
32    "lifecycle.idle_triggers",
33];
34
35/// Top-level keys whose hot paths are nested, so the walk descends into them.
36const NESTED_PARENTS: &[&str] = &["hitl", "lifecycle"];
37
38/// Bookkeeping stamps that change on every CLI write and mean nothing at runtime.
39const IGNORED_PATHS: &[&str] = &["updated_at"];
40
41/// The result of comparing two profiles.
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
43pub struct ReloadDiff {
44    /// Changed paths a running agent applies on its next turn.
45    pub hot: Vec<String>,
46    /// Changed paths that need `mur agent restart`.
47    pub cold: Vec<String>,
48}
49
50impl ReloadDiff {
51    pub fn is_empty(&self) -> bool {
52        self.hot.is_empty() && self.cold.is_empty()
53    }
54
55    /// True when every change is hot — nothing waits for a restart.
56    pub fn hot_only(&self) -> bool {
57        self.cold.is_empty()
58    }
59}
60
61/// File in `agent_home` where a running agent records its reload state.
62/// Written by the runtime (agent_home stays writable), read by `doctor`.
63pub const RELOAD_STATE_FILE: &str = "reload_state.json";
64
65/// What a running agent last did with its `profile.yaml`.
66#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ReloadState {
68    /// Successful reloads since boot.
69    pub generation: u64,
70    /// Why the newest `profile.yaml` on disk is not the one being served.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub last_reload_error: Option<String>,
73    /// Same, for the global limits scope (`limits/global.yaml`, or the legacy
74    /// `config.yaml limits:` block before #1794). The field keeps its name so
75    /// doctor still reads state written by an agent started before the move.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub config_limits_error: Option<String>,
78    /// Changed paths that only take effect after `mur agent restart`.
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    pub pending_cold_restart: Vec<String>,
81    /// MCP server → why its edited entry is not the one running. Separate from
82    /// `pending_cold_restart` because that holds paths only, and a refusal
83    /// (a pin mismatch, a client that failed to start) needs its reason.
84    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
85    pub mcp_refusals: BTreeMap<String, String>,
86}
87
88impl ReloadState {
89    /// Atomic write: temp file + rename.
90    pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> {
91        let tmp = path.with_extension("json.tmp");
92        std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?;
93        std::fs::rename(&tmp, path)
94    }
95
96    /// `None` when absent or unreadable — an agent that never reloaded.
97    pub fn load(path: &std::path::Path) -> Option<Self> {
98        serde_json::from_slice(&std::fs::read(path).ok()?).ok()
99    }
100}
101
102impl AgentProfile {
103    /// Classify what changed between `old` and `new`.
104    pub fn reload_diff(old: &AgentProfile, new: &AgentProfile) -> ReloadDiff {
105        let (Ok(a), Ok(b)) = (serde_json::to_value(old), serde_json::to_value(new)) else {
106            // Unserializable is not a state the type can reach; if it ever
107            // does, refusing to hot-apply anything is the safe answer.
108            return ReloadDiff {
109                hot: vec![],
110                cold: vec!["<profile>".into()],
111            };
112        };
113        let mut diff = ReloadDiff::default();
114        walk(&a, &b, "", &mut diff);
115        diff_mcp_servers(old, new, &mut diff);
116        diff.hot.sort();
117        diff.cold.sort();
118        diff
119    }
120}
121
122impl AgentProfile {
123    /// `self` (the profile the process booted with) with only the [`HOT_PATHS`]
124    /// fields taken from `newer`.
125    ///
126    /// How the runtime applies a reload: it never swaps in `newer` wholesale,
127    /// so a changed locked field cannot reach a reader by any route — the
128    /// running process keeps the boot value until a restart.
129    pub fn with_hot_fields_from(&self, newer: &AgentProfile) -> AgentProfile {
130        self.with_hot_fields_over(&self.mcp_servers, newer)
131    }
132
133    /// [`Self::with_hot_fields_from`] for a process that has already reloaded:
134    /// `served` is the `mcp_servers` the last reload served. A cold MCP edit
135    /// keeps that entry instead of falling back to boot's, so it cannot undo
136    /// a hot edit (args, hosts) applied earlier.
137    pub fn with_hot_fields_over(
138        &self,
139        served: &[super::McpServerEntry],
140        newer: &AgentProfile,
141    ) -> AgentProfile {
142        let mut out = self.clone();
143        out.limits = newer.limits.clone();
144        out.disabled_skills = newer.disabled_skills.clone();
145        out.addons = newer.addons.clone();
146        out.hitl.autonomy = newer.hitl.autonomy;
147        out.lifecycle.schedule = newer.lifecycle.schedule.clone();
148        out.lifecycle.idle_triggers = newer.lifecycle.idle_triggers.clone();
149        out.mcp_servers = overlay_hot_entries(&self.mcp_servers, served, &newer.mcp_servers);
150        out
151    }
152}
153
154fn walk(a: &Value, b: &Value, prefix: &str, diff: &mut ReloadDiff) {
155    let null = Value::Null;
156    let (Some(ma), Some(mb)) = (a.as_object(), b.as_object()) else {
157        if a != b {
158            diff.cold.push(prefix.to_string());
159        }
160        return;
161    };
162    let mut keys: Vec<&String> = ma.keys().chain(mb.keys()).collect();
163    keys.sort();
164    keys.dedup();
165    for k in keys {
166        let path = if prefix.is_empty() {
167            k.clone()
168        } else {
169            format!("{prefix}.{k}")
170        };
171        let (va, vb) = (ma.get(k).unwrap_or(&null), mb.get(k).unwrap_or(&null));
172        if va == vb || IGNORED_PATHS.contains(&path.as_str()) || path == MCP_SERVERS {
173            continue;
174        }
175        if HOT_PATHS.contains(&path.as_str()) {
176            diff.hot.push(path.clone());
177            if path == "addons" {
178                diff.cold.push("addons (mcp servers)".into());
179            }
180        } else if prefix.is_empty() && NESTED_PARENTS.contains(&k.as_str()) {
181            walk(va, vb, &path, diff);
182        } else {
183            diff.cold.push(path);
184        }
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::agent::ScheduleEntry;
192
193    fn base() -> AgentProfile {
194        AgentProfile::default_for_tests()
195    }
196
197    #[test]
198    fn identical_profiles_have_no_diff() {
199        assert!(AgentProfile::reload_diff(&base(), &base()).is_empty());
200    }
201
202    #[test]
203    fn limits_and_autonomy_are_hot() {
204        let mut new = base();
205        new.limits = Some(crate::limits::Limits {
206            deadline: Some("5m".into()),
207            ..Default::default()
208        });
209        new.hitl.autonomy = Some(crate::hitl::Autonomy::Continue);
210        let d = AgentProfile::reload_diff(&base(), &new);
211        assert_eq!(d.hot, vec!["hitl.autonomy", "limits"]);
212        assert!(d.hot_only(), "{d:?}");
213    }
214
215    #[test]
216    fn schedule_is_hot_but_restart_policy_is_cold() {
217        let mut new = base();
218        new.lifecycle.schedule.push(ScheduleEntry {
219            cron: "0 9 * * *".into(),
220            message: "hi".into(),
221            sends_to: None,
222            not_after: None,
223        });
224        new.lifecycle.max_restarts += 1;
225        let d = AgentProfile::reload_diff(&base(), &new);
226        assert_eq!(d.hot, vec!["lifecycle.schedule"]);
227        assert_eq!(d.cold, vec!["lifecycle.max_restarts"]);
228    }
229
230    #[test]
231    fn locked_fields_are_cold() {
232        let mut new = base();
233        new.name = "other".into();
234        new.entitlements
235            .network
236            .outbound
237            .allow_hosts
238            .push("example.com".into());
239        new.disabled_mcp.push("x".into());
240        let d = AgentProfile::reload_diff(&base(), &new);
241        assert!(d.hot.is_empty(), "{d:?}");
242        assert!(d.cold.iter().any(|p| p == "name"), "{d:?}");
243        assert!(
244            d.cold.iter().any(|p| p.starts_with("entitlements")),
245            "{d:?}"
246        );
247        assert!(d.cold.iter().any(|p| p == "disabled_mcp"), "{d:?}");
248    }
249
250    #[test]
251    fn updated_at_alone_is_not_a_change() {
252        let mut new = base();
253        new.updated_at = "2099-01-01T00:00:00Z".into();
254        assert!(AgentProfile::reload_diff(&base(), &new).is_empty());
255    }
256
257    #[test]
258    fn overlay_applies_every_hot_path_and_nothing_else() {
259        let mut new = base();
260        new.limits = Some(crate::limits::Limits {
261            stuck: Some("off".into()),
262            ..Default::default()
263        });
264        new.disabled_skills.push("foo".into());
265        new.hitl.autonomy = Some(crate::hitl::Autonomy::Continue);
266        new.lifecycle.idle_triggers.push(crate::agent::IdleTrigger {
267            after_secs: 60,
268            message: "m".into(),
269            sends_to: None,
270            cooldown_secs: 600,
271            respect_quiet_hours: false,
272        });
273        new.name = "renamed".into();
274        let applied = base().with_hot_fields_from(&new);
275        let rest = AgentProfile::reload_diff(&applied, &new);
276        // Everything hot made it across; the locked rename did not.
277        assert!(rest.hot.is_empty(), "{rest:?}");
278        assert_eq!(rest.cold, vec!["name"]);
279    }
280
281    #[test]
282    fn disabled_skills_is_hot() {
283        let mut new = base();
284        new.disabled_skills.push("foo".into());
285        let d = AgentProfile::reload_diff(&base(), &new);
286        assert_eq!(d.hot, vec!["disabled_skills"]);
287        assert!(d.cold.is_empty());
288    }
289}