1use 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
19pub const HOT_PATHS: &[&str] = &[
27 "limits",
28 "disabled_skills",
29 "addons",
30 "hitl.autonomy",
31 "lifecycle.schedule",
32 "lifecycle.idle_triggers",
33];
34
35const NESTED_PARENTS: &[&str] = &["hitl", "lifecycle"];
37
38const IGNORED_PATHS: &[&str] = &["updated_at"];
40
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
43pub struct ReloadDiff {
44 pub hot: Vec<String>,
46 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 pub fn hot_only(&self) -> bool {
57 self.cold.is_empty()
58 }
59}
60
61pub const RELOAD_STATE_FILE: &str = "reload_state.json";
64
65#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ReloadState {
68 pub generation: u64,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub last_reload_error: Option<String>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub config_limits_error: Option<String>,
78 #[serde(default, skip_serializing_if = "Vec::is_empty")]
80 pub pending_cold_restart: Vec<String>,
81 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
85 pub mcp_refusals: BTreeMap<String, String>,
86}
87
88impl ReloadState {
89 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 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 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 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 pub fn with_hot_fields_from(&self, newer: &AgentProfile) -> AgentProfile {
130 self.with_hot_fields_over(&self.mcp_servers, newer)
131 }
132
133 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 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}