Skip to main content

agentmux_srv_core/migrations/
m0044_warden_split.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Warden was split: the Vault, History and Audit are panes of their own, Host is the Swarm, and
5//! Warden keeps only its Jobs section. Moves, once, for this channel:
6//! - blocks (`db_block`) saved as `view: "warden"` to the pane their `warden:section` lives in now;
7//! - the same for every block in the client's session-restore snapshot (`session:last_topology`);
8//! - settings.json: `warden` in `widget:pinned` is replaced, in place, by `vault`, `history` and
9//!   `audit` (those already pinned are not repeated).
10//!
11//! | saved Warden section         | becomes                                         |
12//! |------------------------------|-------------------------------------------------|
13//! | `vault`                      | `vault` (`vault:section`, `vault:request` kept) |
14//! | `history`                    | `history`                                       |
15//! | `audit`                      | `audit`                                         |
16//! | `host`                       | `swarm`                                         |
17//! | none, or unknown             | `audit` (read-only: a redirect nobody asked for never asks for the Vault key) |
18//! | `kanban`                     | `kanban`                                        |
19//! | `lan`, `internet`, `ambient` | `audit` (these sections have no pane)           |
20//! | `jobs`                       | unchanged                                       |
21//!
22//! `widgets.json` needs nothing: an entry that still names a moved section is resolved when the
23//! file is loaded (`WidgetConfigType::resolve_section`). Layout files live outside AgentMux and
24//! are translated on import (`layout_file.rs`).
25//!
26//! Idempotent: a second run finds no Warden pane on a moved section. The block and snapshot
27//! rewrite fails the migration (retried on the next boot) when the store cannot be read.
28
29use std::path::Path;
30use std::sync::Arc;
31
32use serde_json::{Map, Value};
33
34#[cfg(not(any(test, feature = "test-support")))]
35use crate::backend::config_watcher_fs::resolve_settings_dir;
36use crate::backend::storage::store::Store;
37use crate::backend::wconfig;
38
39use super::{Migration, MigrationContext, MigrationError, MigrationScope, VerifyOutcome};
40
41pub struct M0044WardenSplit;
42
43impl Migration for M0044WardenSplit {
44    fn id(&self) -> &'static str {
45        "0044_warden_split"
46    }
47    fn scope(&self) -> MigrationScope {
48        MigrationScope::Channel
49    }
50    fn description(&self) -> &'static str {
51        "Move saved Warden panes to the Vault, History, Audit and Swarm panes"
52    }
53
54    fn up(&self, ctx: &MigrationContext) -> Result<(), MigrationError> {
55        if ctx.channel_store_path.exists() {
56            let store = Arc::new(
57                Store::open(&ctx.channel_store_path)
58                    .map_err(|e| MigrationError(format!("warden_split: open store: {e}")))?,
59            );
60            let blocks = migrate_blocks(&store).map_err(MigrationError)?;
61            let snapshots = migrate_client_snapshots(&store).map_err(MigrationError)?;
62            if blocks + snapshots > 0 {
63                tracing::info!(
64                    blocks,
65                    snapshots,
66                    "warden_split: moved saved Warden panes to their own panes"
67                );
68            }
69        }
70        if let Some(settings_dir) = settings_dir() {
71            migrate_settings_file(&settings_dir.join(wconfig::SETTINGS_FILE));
72        }
73        Ok(())
74    }
75
76    fn verify(&self, ctx: &MigrationContext) -> VerifyOutcome {
77        if !ctx.channel_store_path.exists() {
78            return VerifyOutcome::Ok("no channel store".into());
79        }
80        let store = match Store::open(&ctx.channel_store_path) {
81            Ok(s) => s,
82            Err(e) => return VerifyOutcome::Error(format!("open store: {e}")),
83        };
84        match leftover_block_count(&store) {
85            Ok(0) => VerifyOutcome::Ok("no block saved as a Warden pane on a moved section".into()),
86            Ok(n) => VerifyOutcome::Mismatch(format!(
87                "{n} block(s) still saved as a Warden pane on a moved section"
88            )),
89            Err(e) => VerifyOutcome::Error(e),
90        }
91    }
92}
93
94/// Where settings.json lives. Not under test: the runner tests apply every migration, and the
95/// real resolver would point them at the developer's own settings.
96#[cfg(not(any(test, feature = "test-support")))]
97fn settings_dir() -> Option<std::path::PathBuf> {
98    Some(resolve_settings_dir())
99}
100#[cfg(any(test, feature = "test-support"))]
101fn settings_dir() -> Option<std::path::PathBuf> {
102    None
103}
104
105/// The pane a Warden pane saved on `section` opens now, or None when it stays Warden (Jobs).
106fn target_view(section: Option<&str>) -> Option<&'static str> {
107    match section.unwrap_or("") {
108        "jobs" => None,
109        "vault" => Some("vault"),
110        "history" => Some("history"),
111        "host" => Some("swarm"),
112        "kanban" => Some("kanban"),
113        _ => Some("audit"),
114    }
115}
116
117/// A pane meta saved as Warden on a section that moved, rewritten for its new pane. Returns whether
118/// it changed. Every other key (`vault:section`, `vault:request`, `term:zoom`, ...) is kept.
119fn migrate_meta(meta: &mut Map<String, Value>) -> bool {
120    if meta.get("view").and_then(Value::as_str) != Some("warden") {
121        return false;
122    }
123    let Some(view) = target_view(meta.get("warden:section").and_then(Value::as_str)) else {
124        return false;
125    };
126    meta.insert("view".into(), view.into());
127    meta.remove("warden:section");
128    true
129}
130
131/// Every object in `value` saved as a Warden pane on a moved section, rewritten. Returns how many changed.
132fn migrate_tree(value: &mut Value) -> usize {
133    match value {
134        Value::Object(map) => {
135            let mut n = usize::from(migrate_meta(map));
136            for child in map.values_mut() {
137                n += migrate_tree(child);
138            }
139            n
140        }
141        Value::Array(items) => items.iter_mut().map(migrate_tree).sum(),
142        _ => 0,
143    }
144}
145
146/// The panes that took over Warden's place in the widget bar.
147const PINNED_REPLACEMENT: [&str; 3] = ["vault", "history", "audit"];
148
149/// `widget:pinned` with `warden` replaced in place by the Vault, History and Audit (those already
150/// pinned are not repeated), or None when it does not pin Warden.
151fn migrate_pinned(value: &Value) -> Option<Value> {
152    let items = value.as_array()?;
153    if !items.iter().any(|v| v.as_str() == Some("warden")) {
154        return None;
155    }
156    let mut out: Vec<Value> = Vec::new();
157    for item in items {
158        if item.as_str() != Some("warden") {
159            out.push(item.clone());
160            continue;
161        }
162        for name in PINNED_REPLACEMENT {
163            let pinned = |v: &Value| v.as_str() == Some(name);
164            if !items.iter().any(pinned) && !out.iter().any(pinned) {
165                out.push(Value::String(name.into()));
166            }
167        }
168    }
169    Some(Value::Array(out))
170}
171
172fn migrate_settings_file(path: &Path) {
173    if !path.exists() {
174        return;
175    }
176    // A file with a mistake in it is left as it is; the migration finds it again once it parses.
177    let settings = match agentmux_common::settings_file::read(path) {
178        Ok(Some(loaded)) => loaded.values,
179        Ok(None) => return,
180        Err(e) => {
181            tracing::warn!(error = %e, "warden_split: settings.json can't be read; the Warden pin left");
182            return;
183        }
184    };
185    let Some(pinned) = settings.get("widget:pinned").and_then(migrate_pinned) else {
186        return;
187    };
188    match agentmux_common::settings_file::update(path, wconfig::SETTINGS_TEMPLATE, |settings| {
189        settings.insert("widget:pinned".into(), pinned.clone());
190    }) {
191        Ok(()) => tracing::info!(
192            "warden_split: settings.json pins moved from Warden to the Vault, History and Audit"
193        ),
194        Err(e) => {
195            tracing::warn!(error = %e, "warden_split: couldn't write settings.json; the Warden pin left")
196        }
197    }
198}
199
200fn read_rows(store: &Store, table: &str) -> Result<Vec<(String, Vec<u8>)>, String> {
201    let conn = store.conn().lock().unwrap();
202    let mut stmt = conn
203        .prepare(&format!("SELECT oid, data FROM {table}"))
204        .map_err(|e| format!("warden_split: read {table}: {e}"))?;
205    let rows = stmt
206        .query_map([], |row| {
207            Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))
208        })
209        .map_err(|e| format!("warden_split: read {table}: {e}"))?
210        .filter_map(Result::ok)
211        .collect();
212    Ok(rows)
213}
214
215fn migrate_blocks(store: &Store) -> Result<usize, String> {
216    let mut changed = 0;
217    for (oid, data) in read_rows(store, "db_block")? {
218        let Ok(mut block) = serde_json::from_slice::<Value>(&data) else {
219            continue;
220        };
221        let moved = match block.get_mut("meta") {
222            Some(Value::Object(meta)) => migrate_meta(meta),
223            _ => false,
224        };
225        if moved {
226            store
227                .update_raw("block", &oid, &block)
228                .map_err(|e| format!("warden_split: update block {oid}: {e}"))?;
229            changed += 1;
230        }
231    }
232    Ok(changed)
233}
234
235const SNAPSHOT_META_KEY: &str = "session:last_topology";
236
237fn migrate_client_snapshots(store: &Store) -> Result<usize, String> {
238    let mut changed = 0;
239    for (oid, data) in read_rows(store, "db_client")? {
240        let Ok(mut client) = serde_json::from_slice::<Value>(&data) else {
241            continue;
242        };
243        let moved = client
244            .get_mut("meta")
245            .and_then(|m| m.get_mut(SNAPSHOT_META_KEY))
246            .map(migrate_tree)
247            .unwrap_or(0);
248        if moved > 0 {
249            store
250                .update_raw("client", &oid, &client)
251                .map_err(|e| format!("warden_split: update client {oid}: {e}"))?;
252            changed += moved;
253        }
254    }
255    Ok(changed)
256}
257
258fn leftover_block_count(store: &Store) -> Result<usize, String> {
259    Ok(read_rows(store, "db_block")?
260        .into_iter()
261        .filter(|(_, data)| {
262            serde_json::from_slice::<Value>(data)
263                .ok()
264                .and_then(|b| b.get("meta")?.as_object().cloned())
265                .is_some_and(|mut meta| migrate_meta(&mut meta))
266        })
267        .count())
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use serde_json::json;
274
275    fn meta(v: Value) -> Map<String, Value> {
276        v.as_object().unwrap().clone()
277    }
278
279    fn moved(v: Value) -> Value {
280        let mut m = meta(v);
281        assert!(migrate_meta(&mut m));
282        Value::Object(m)
283    }
284
285    #[test]
286    fn a_vault_section_becomes_a_vault_pane_keeping_its_own_keys() {
287        let out = moved(json!({
288            "view": "warden", "warden:section": "vault", "vault:section": "cards", "vault:request": "r1", "term:zoom": 1.1
289        }));
290        assert_eq!(
291            out,
292            json!({ "view": "vault", "vault:section": "cards", "vault:request": "r1", "term:zoom": 1.1 })
293        );
294    }
295
296    #[test]
297    fn history_and_audit_become_panes_of_their_own() {
298        assert_eq!(
299            moved(json!({ "view": "warden", "warden:section": "history" })),
300            json!({ "view": "history" })
301        );
302        assert_eq!(
303            moved(json!({ "view": "warden", "warden:section": "audit" })),
304            json!({ "view": "audit" })
305        );
306    }
307
308    #[test]
309    fn host_becomes_the_swarm() {
310        assert_eq!(
311            moved(json!({ "view": "warden", "warden:section": "host" })),
312            json!({ "view": "swarm" })
313        );
314    }
315
316    #[test]
317    fn no_section_or_an_unknown_one_opens_the_audit() {
318        for meta in [
319            json!({ "view": "warden" }),
320            json!({ "view": "warden", "warden:section": "" }),
321            json!({ "view": "warden", "warden:section": "nope" }),
322        ] {
323            assert_eq!(moved(meta), json!({ "view": "audit" }));
324        }
325    }
326
327    #[test]
328    fn the_kanban_section_becomes_the_kanban_pane() {
329        assert_eq!(
330            moved(json!({ "view": "warden", "warden:section": "kanban" })),
331            json!({ "view": "kanban" })
332        );
333    }
334
335    #[test]
336    fn sections_with_no_pane_open_the_audit() {
337        for section in ["lan", "internet", "ambient"] {
338            assert_eq!(
339                moved(json!({ "view": "warden", "warden:section": section })),
340                json!({ "view": "audit" }),
341                "{section}"
342            );
343        }
344    }
345
346    #[test]
347    fn jobs_and_other_panes_are_left_alone_and_a_second_run_changes_nothing() {
348        assert!(!migrate_meta(&mut meta(
349            json!({ "view": "warden", "warden:section": "jobs" })
350        )));
351        assert!(!migrate_meta(&mut meta(
352            json!({ "view": "browser", "warden:section": "host" })
353        )));
354        assert!(!migrate_meta(&mut meta(
355            json!({ "view": "vault", "vault:section": "cards" })
356        )));
357        assert!(!migrate_meta(&mut meta(json!({ "view": "swarm" }))));
358        let mut m = meta(json!({ "view": "warden", "warden:section": "history" }));
359        assert!(migrate_meta(&mut m));
360        assert!(!migrate_meta(&mut m));
361    }
362
363    #[test]
364    fn the_session_snapshot_moves_too() {
365        let mut snapshot = json!({ "tabs": [{ "blocks": [
366            { "view": "warden", "warden:section": "audit" },
367            { "view": "warden", "warden:section": "jobs" },
368            { "view": "term" }
369        ] }] });
370        assert_eq!(migrate_tree(&mut snapshot), 1);
371        assert_eq!(snapshot["tabs"][0]["blocks"][0], json!({ "view": "audit" }));
372        assert_eq!(
373            snapshot["tabs"][0]["blocks"][1],
374            json!({ "view": "warden", "warden:section": "jobs" })
375        );
376        assert_eq!(migrate_tree(&mut snapshot), 0);
377    }
378
379    #[test]
380    fn a_warden_pin_is_replaced_in_place_by_the_three_panes() {
381        let pinned = json!(["agent", "warden", "term"]);
382        assert_eq!(
383            migrate_pinned(&pinned),
384            Some(json!(["agent", "vault", "history", "audit", "term"]))
385        );
386        // Already pinned panes are not repeated, wherever they sit.
387        assert_eq!(
388            migrate_pinned(&json!(["history", "warden"])),
389            Some(json!(["history", "vault", "audit"]))
390        );
391        assert_eq!(
392            migrate_pinned(&json!(["warden", "vault", "audit"])),
393            Some(json!(["history", "vault", "audit"]))
394        );
395        // Nothing to do without a Warden pin, and a second run changes nothing.
396        assert_eq!(migrate_pinned(&json!(["agent", "term"])), None);
397        assert_eq!(migrate_pinned(&json!([])), None);
398        assert_eq!(migrate_pinned(&json!("warden")), None);
399        assert_eq!(
400            migrate_pinned(&json!(["agent", "vault", "history", "audit", "term"])),
401            None
402        );
403    }
404
405    #[test]
406    fn settings_are_rewritten_only_when_warden_was_pinned() {
407        let dir = tempfile::tempdir().unwrap();
408        let settings = dir.path().join("settings.json");
409        std::fs::write(
410            &settings,
411            r#"{ "widget:pinned": ["agent", "warden"], "term:fontsize": 14 }"#,
412        )
413        .unwrap();
414        migrate_settings_file(&settings);
415        let after = wconfig::read_settings_raw_jsonc(&settings);
416        assert_eq!(
417            after["widget:pinned"],
418            json!(["agent", "vault", "history", "audit"])
419        );
420        assert_eq!(after["term:fontsize"], json!(14));
421
422        // No Warden pin: the file is byte for byte as it was.
423        let text = r#"{ "widget:pinned": ["agent"] }"#;
424        std::fs::write(&settings, text).unwrap();
425        migrate_settings_file(&settings);
426        assert_eq!(std::fs::read_to_string(&settings).unwrap(), text);
427
428        // Unparseable: left alone. Missing: no file is created.
429        std::fs::write(&settings, "{ not json").unwrap();
430        migrate_settings_file(&settings);
431        assert_eq!(std::fs::read_to_string(&settings).unwrap(), "{ not json");
432        let missing = dir.path().join("missing.json");
433        migrate_settings_file(&missing);
434        assert!(!missing.exists());
435    }
436}