agentmux_srv_core/backend/
mcp_health_meta.rs1use std::sync::Arc;
12
13use serde_json::{json, Value};
14
15use crate::backend::eventbus::EventBus;
16use crate::backend::mcp_health::Notice;
17use crate::backend::storage::store::Store;
18
19pub const META_KEY: &str = "agent:mcp_health";
21
22pub fn meta_value(notice: &Notice, now_ms: u64) -> Value {
25 match notice.state {
26 "healing" | "restarting" | "gave_up" => json!({ "state": notice.state, "step": notice.step, "at": now_ms }),
27 _ => Value::Null,
28 }
29}
30
31pub fn clear(block_id: &str, store: &Arc<Store>, event_bus: &Option<Arc<EventBus>>) {
35 let ok = Notice { episode: String::new(), state: "ok", step: 0, error: None, safe_profile: false };
36 persist(block_id, &ok, store, event_bus);
37}
38
39pub fn persist(block_id: &str, notice: &Notice, store: &Arc<Store>, event_bus: &Option<Arc<EventBus>>) {
42 let current = store
43 .must_get::<crate::backend::obj::Block>(block_id)
44 .ok()
45 .and_then(|b| b.meta.get(META_KEY).cloned())
46 .filter(|v| !v.is_null());
47 let mut next = meta_value(notice, agentmux_common::time::now_ms_u64());
48 match (¤t, &next) {
49 (None, Value::Null) => return,
50 (Some(old), Value::Object(new)) if old.get("state") == new.get("state") && old.get("step") == new.get("step") => return,
52 (Some(old), Value::Object(new)) if old.get("state") == new.get("state") => {
53 if let (Some(at), Some(obj)) = (old.get("at"), next.as_object_mut()) {
54 obj.insert("at".to_string(), at.clone());
55 }
56 }
57 _ => {}
58 }
59 let mut update = crate::backend::obj::MetaMapType::new();
60 update.insert(META_KEY.to_string(), next);
61 let written = store.with_tx(|tx| {
64 let mut block = tx.must_get::<crate::backend::obj::Block>(block_id)?;
65 block.meta = crate::backend::obj::merge_meta(&block.meta, &update, true);
66 tx.update(&mut block)
67 });
68 match written {
69 Ok(_) => {
70 if let Some(bus) = event_bus {
71 crate::backend::blockcontroller::core::broadcast_block_update(store, bus, block_id);
72 }
73 }
74 Err(e) => tracing::warn!(block_id = %block_id, error = %e, "could not store agent:mcp_health"),
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 fn notice(state: &'static str, step: u8) -> Notice {
83 Notice { episode: "e".into(), state, step, error: Some("boom".into()), safe_profile: false }
84 }
85
86 #[test]
87 fn the_tools_being_down_is_stored_without_the_error_and_being_back_removes_it() {
88 assert_eq!(meta_value(¬ice("healing", 3), 7), json!({ "state": "healing", "step": 3, "at": 7 }));
89 assert_eq!(meta_value(¬ice("restarting", 0), 7)["state"], "restarting");
90 assert_eq!(meta_value(¬ice("gave_up", 0), 7)["state"], "gave_up");
91 assert_eq!(meta_value(¬ice("ok", 0), 7), Value::Null);
92 }
93
94 #[test]
95 fn a_state_is_stored_once_keeps_when_it_began_and_is_removed_when_the_tools_are_back() {
96 let store = Arc::new(Store::open_in_memory().unwrap());
97 let mut block = crate::backend::obj::Block {
98 oid: "77777777-7777-7777-7777-777777777777".into(),
99 parentoref: String::new(),
100 version: 1,
101 runtimeopts: None,
102 stickers: None,
103 meta: crate::backend::obj::MetaMapType::new(),
104 subblockids: None,
105 };
106 store.insert(&mut block).unwrap();
107 let read = || store.must_get::<crate::backend::obj::Block>("77777777-7777-7777-7777-777777777777").unwrap().meta.get(META_KEY).cloned();
108
109 persist("77777777-7777-7777-7777-777777777777", ¬ice("healing", 1), &store, &None);
110 let first = read().unwrap();
111 assert_eq!(first["state"], "healing");
112 persist("77777777-7777-7777-7777-777777777777", ¬ice("healing", 2), &store, &None);
113 let second = read().unwrap();
114 assert_eq!(second["step"], 2);
115 assert_eq!(second["at"], first["at"], "still the same episode state: it began when it first did");
116 persist("77777777-7777-7777-7777-777777777777", ¬ice("gave_up", 0), &store, &None);
117 assert_eq!(read().unwrap()["state"], "gave_up");
118
119 persist("77777777-7777-7777-7777-777777777777", ¬ice("ok", 0), &store, &None);
120 assert!(read().is_none_or(|v| v.is_null()), "the tools are back: nothing to show");
121 persist("77777777-7777-7777-7777-777777777777", ¬ice("ok", 0), &store, &None);
122
123 persist("77777777-7777-7777-7777-777777777777", ¬ice("gave_up", 0), &store, &None);
125 assert!(read().is_some());
126 clear("77777777-7777-7777-7777-777777777777", &store, &None);
127 assert!(read().is_none_or(|v| v.is_null()));
128 clear("77777777-7777-7777-7777-777777777777", &store, &None);
129 }
130}