Skip to main content

agentmux_srv_core/
persist.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.2 — bootstrap helper: load SQLite-persistent state into
5// the srv reducer at startup. The reducer's state is a SESSION-only
6// projection in E.2/E.2b — it's populated from SQLite at boot,
7// mutated by pipe-originated commands during the session, and
8// discarded on restart (the next bootstrap re-reads SQLite).
9//
10// HTTP/WS RPC continues to write to SQLite directly via wcore. So
11// SQLite stays authoritative for the duration of the session even
12// though the reducer's view diverges as soon as a pipe command
13// runs. That's intentional: pipe-originated commands have no
14// client populating them yet (saga coordinator is empty in E.1a;
15// E.5+ adds saga consumers). Once those exist, E.2c adds the
16// persist subscriber that mirrors pipe-event effects back to SQLite.
17//
18// This module DOES NOT define a persist subscriber. The HWM /
19// broadcast-lag concerns codex flagged are deferred to E.2c when
20// the subscriber actually exists.
21
22use std::sync::Arc;
23
24use tokio::sync::Mutex;
25
26use crate::backend::obj::{Block, Tab, Window, Workspace};
27use crate::backend::storage::store::Store;
28use crate::state::{BlockRecord, State, TabRecord, WindowRecord, WorkspaceRecord};
29
30mod pins;
31
32/// A block `Command::ParkBlock` left in no tab, which boot keeps (see `PARKED_META_KEY`).
33fn is_parked(block: &Block) -> bool {
34    crate::backend::obj::meta_get_bool(&block.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false)
35}
36
37/// Whether `block` is a child of a block that is in the store (`parentoref` is `block:<id>`).
38fn is_sub_block_of_a_stored_block(block: &Block, stored: &[Block]) -> bool {
39    block.parentoref.strip_prefix("block:").is_some_and(|parent| stored.iter().any(|b| b.oid == parent))
40}
41
42/// Reports a stored block that is in no tab and is not parked, which the bootstrap skips. A block's own
43/// child (an agent pane's shell) is in no tab by design and lives with its parent, which may be parked:
44/// it is no orphan, the reducer never tracked it, and nothing is reported for it.
45fn report_block_in_no_tab(block: &Block, stored: &[Block]) {
46    if is_sub_block_of_a_stored_block(block, stored) {
47        return;
48    }
49    tracing::warn!(
50        target: "srv-persist",
51        "[srv-persist] bootstrap: block {} has no parent tab in reducer state — skipping",
52        block.oid
53    );
54}
55
56/// A row written by an earlier build can hold a leaf for a block the tab no longer owns, or the
57/// pre-display-mode minimize fields; heal it before any window loads it, and store the healed row
58/// through the same write an intent's events take. Without the block list nothing is pruned (the
59/// tabs' block ids are incomplete), but the minimize fields are still converted: that needs no blocks.
60fn heal_loaded_layouts(state: &mut State, mstore: &Store, blocks_loaded: bool) {
61    if !blocks_loaded {
62        tracing::warn!(target: "srv-persist", "[srv-persist] bootstrap: blocks could not be read; healing the layouts without pruning");
63    }
64    let tab_ids: Vec<String> = state.tabs.keys().cloned().collect();
65    for tab_id in tab_ids {
66        for ev in crate::reducer::heal_loaded_layout(state, &tab_id, blocks_loaded) {
67            if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(&ev, mstore) {
68                tracing::warn!(target: "srv-persist", tab_id = %tab_id, "[srv-persist] bootstrap: storing the healed layout failed: {}", e);
69            }
70        }
71    }
72}
73
74/// Phase E.2 / E.2b — load workspaces and their tabs from SQLite
75/// into the reducer state. Called once at srv startup before the
76/// IPC server starts accepting commands. Async because we're inside
77/// the tokio runtime.
78///
79/// Errors are logged but non-fatal: if a SQLite read fails (fresh
80/// install, empty DB, transient I/O), the reducer starts with
81/// whatever loaded successfully. Workspace and tab loads are
82/// independent — a workspace-load failure does not prevent the tab
83/// load from being attempted (and vice versa), since pipe commands
84/// later in the session can populate either map.
85pub async fn bootstrap_state_from_mstore(state: &Arc<Mutex<State>>, mstore: &Store) {
86    let mut workspaces = mstore.get_all::<Workspace>().unwrap_or_else(|e| {
87        tracing::warn!(
88            target: "srv-persist",
89            "[srv-persist] bootstrap: failed to load workspaces from mstore: {} — workspaces start empty",
90            e
91        );
92        Vec::new()
93    });
94    let mut tabs = mstore.get_all::<Tab>().unwrap_or_else(|e| {
95        tracing::warn!(
96            target: "srv-persist",
97            "[srv-persist] bootstrap: failed to load tabs from mstore: {} — tabs start empty",
98            e
99        );
100        Vec::new()
101    });
102    // `get_all` fails as a whole when one row doesn't decode. Then every tab's
103    // block list below is empty, which is not the truth on disk: the layout
104    // heal must not run against it, or it would prune and store every tree
105    // empty.
106    let (blocks, blocks_loaded) = match mstore.get_all::<Block>() {
107        Ok(blocks) => (blocks, true),
108        Err(e) => {
109            tracing::warn!(
110                target: "srv-persist",
111                "[srv-persist] bootstrap: failed to load blocks from mstore: {} — blocks start empty",
112                e
113            );
114            (Vec::new(), false)
115        }
116    };
117    pins::adopt_stored_shelves(&mut workspaces, &mut tabs, mstore);
118    let mut state = state.lock().await;
119    for ws in &workspaces {
120        // The persistent `Workspace` carries two ordered lists:
121        // `tabids` (regular tabs) and `pinnedtabids` (sticky tabs).
122        // Both are equally "owned by this workspace" for reducer
123        // purposes — only their UX semantics differ. Concatenate
124        // pinned-then-regular (pinning convention puts pinned tabs
125        // first), then filter against the tabs we actually loaded
126        // to drop dangling references defensively. (codex P1 #612.)
127        let tab_ids: Vec<String> = ws
128            .pinnedtabids
129            .iter()
130            .chain(ws.tabids.iter())
131            .filter(|tid| tabs.iter().any(|t| &t.oid == *tid))
132            .cloned()
133            .collect();
134        let active_tab_id = if !ws.activetabid.is_empty()
135            && tab_ids.iter().any(|tid| tid == &ws.activetabid)
136        {
137            Some(ws.activetabid.clone())
138        } else {
139            None
140        };
141        state.workspaces.insert(
142            ws.oid.clone(),
143            WorkspaceRecord { tab_ids, active_tab_id, pins: ws.pins.clone(), ..WorkspaceRecord::new(ws.oid.clone(), ws.name.clone()) },
144        );
145    }
146    for tab in &tabs {
147        // Each tab needs to know its parent workspace_id, which the
148        // persistent `Tab` struct doesn't carry directly — we recover
149        // it from whichever workspace lists this tab id in EITHER
150        // `tabids` OR `pinnedtabids`. Tabs whose parent isn't loaded
151        // are skipped (orphans). (codex P1 #612.)
152        let Some(workspace_id) = workspaces
153            .iter()
154            .find(|ws| {
155                ws.tabids
156                    .iter()
157                    .chain(ws.pinnedtabids.iter())
158                    .any(|tid| tid == &tab.oid)
159            })
160            .map(|ws| ws.oid.clone())
161        else {
162            tracing::warn!(
163                target: "srv-persist",
164                "[srv-persist] bootstrap: tab {} has no parent workspace — skipping",
165                tab.oid
166            );
167            continue;
168        };
169        // Phase E.3 — filter dangling block ids on the same defensive
170        // basis we apply to tabs above.
171        let block_ids: Vec<String> = tab
172            .blockids
173            .iter()
174            .filter(|bid| blocks.iter().any(|b| &b.oid == *bid))
175            .cloned()
176            .collect();
177        // Phase E.4 (Option A) — bootstrap focused/magnified node from
178        // the tab's LayoutState row so the reducer's view matches what
179        // the user last saw on disk. Empty when the layout row isn't
180        // found or has no value (matches `LayoutState` defaults).
181        //
182        // Phase E.4.B — also bootstrap `rootnode` (the layout tree).
183        // Until the wcore-direct writers migrate to dispatch through
184        // the new layout reducer arms (Phase 7), the reducer's
185        // rootnode is a passive shadow — refreshed on startup, never
186        // diverging from disk because no reducer-arm writers exist
187        // yet at runtime.
188        let (focused_node_id, magnified_node_id, rootnode) = if tab.layoutstate.is_empty() {
189            (String::new(), String::new(), None)
190        } else {
191            match mstore.get::<crate::backend::obj::LayoutState>(&tab.layoutstate) {
192                Ok(Some(layout)) => (
193                    layout.focusednodeid,
194                    layout.magnifiednodeid,
195                    layout.rootnode,
196                ),
197                _ => (String::new(), String::new(), None),
198            }
199        };
200        state.tabs.insert(
201            tab.oid.clone(),
202            TabRecord {
203                tab_id: tab.oid.clone(),
204                workspace_id,
205                name: tab.name.clone(),
206                block_ids,
207                focused_node_id,
208                magnified_node_id,
209                rootnode,
210                recent_intent_ids: Vec::new(),
211            },
212        );
213    }
214    heal_loaded_layouts(&mut state, mstore, blocks_loaded);
215    for block in &blocks {
216        // Phase E.3 — recover each block's parent tab via reverse
217        // lookup against `state.tabs` (NOT raw `tabs` from SQLite):
218        // tabs orphaned in the prior loop (no parent workspace) are
219        // not in `state.tabs`, so blocks under them must also be
220        // dropped to keep reducer state consistent. (reagent P1 #613.)
221        let Some(tab_id) = state
222            .tabs
223            .values()
224            .find(|t| t.block_ids.iter().any(|bid| bid == &block.oid))
225            .map(|t| t.tab_id.clone())
226            .or_else(|| is_parked(block).then(String::new))
227        else {
228            report_block_in_no_tab(block, &blocks);
229            continue;
230        };
231        state.blocks.insert(
232            block.oid.clone(),
233            BlockRecord {
234                block_id: block.oid.clone(),
235                tab_id,
236            },
237        );
238    }
239    pins::reconcile(&mut state, mstore, blocks_loaded);
240    // Phase E.5 — load Window→Workspace mappings. Used by sagas
241    // (TearOff/Restore/CreateWindow/CloseWindow) that coordinate
242    // window+workspace lifecycle. Skip windows whose `workspaceid`
243    // refers to a workspace that didn't load — those are dangling
244    // refs, same defensive treatment as orphan tabs/blocks.
245    let windows = mstore.get_all::<Window>().unwrap_or_else(|e| {
246        tracing::warn!(
247            target: "srv-persist",
248            "[srv-persist] bootstrap: failed to load windows from mstore: {} — windows start empty",
249            e
250        );
251        Vec::new()
252    });
253    for window in &windows {
254        if window.workspaceid.is_empty() {
255            tracing::warn!(
256                target: "srv-persist",
257                "[srv-persist] bootstrap: window {} has empty workspaceid — skipping",
258                window.oid
259            );
260            continue;
261        }
262        if !state.workspaces.contains_key(&window.workspaceid) {
263            tracing::warn!(
264                target: "srv-persist",
265                "[srv-persist] bootstrap: window {} points at unknown workspace {} — skipping",
266                window.oid, window.workspaceid
267            );
268            continue;
269        }
270        state.windows.insert(
271            window.oid.clone(),
272            WindowRecord {
273                window_id: window.oid.clone(),
274                workspace_id: window.workspaceid.clone(),
275            },
276        );
277    }
278    tracing::info!(
279        target: "srv-persist",
280        "[srv-persist] bootstrap loaded {} workspace(s) + {} tab(s) + {} block(s) + {} window(s) from mstore",
281        state.workspaces.len(),
282        state.tabs.len(),
283        state.blocks.len(),
284        state.windows.len()
285    );
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    fn block(store: &Store, parent: &str, parked: bool) -> String {
293        let mut meta = crate::backend::obj::MetaMapType::new();
294        if parked {
295            meta.insert(crate::persist_subscriber::parked::PARKED_META_KEY.to_string(), serde_json::json!(true));
296        }
297        let mut b = Block { oid: uuid::Uuid::new_v4().to_string(), parentoref: parent.to_string(), meta, ..Default::default() };
298        store.insert(&mut b).unwrap();
299        b.oid
300    }
301
302    /// A parked block survives a restart in the reducer's state with no tab; a block that belongs to
303    /// no tab and is not marked is still dropped as the orphan it is.
304    #[tokio::test]
305    async fn boot_keeps_a_parked_block_and_still_drops_an_orphan() {
306        let store = Store::open_in_memory().unwrap();
307        let (shown, parked, orphan) = (block(&store, "tab:t1", false), block(&store, "", true), block(&store, "tab:gone", false));
308        let mut tab = Tab { oid: "t1".into(), name: "Tab".into(), blockids: vec![shown.clone()], ..Default::default() };
309        store.insert(&mut tab).unwrap();
310        let mut ws = Workspace { oid: "w1".into(), tabids: vec!["t1".into()], ..Default::default() };
311        store.insert(&mut ws).unwrap();
312
313        let state = Arc::new(Mutex::new(State::default()));
314        bootstrap_state_from_mstore(&state, &store).await;
315        let s = state.lock().await;
316        assert_eq!(s.blocks.get(&shown).map(|b| b.tab_id.as_str()), Some("t1"));
317        assert_eq!(s.blocks.get(&parked).map(|b| b.tab_id.as_str()), Some(""));
318        assert!(!s.blocks.contains_key(&orphan));
319        assert_eq!(s.tabs["t1"].block_ids, vec![shown]);
320    }
321
322    /// An agent pane's shell is a child of the agent's block, in no tab. With its parent in the store
323    /// (parked, here) it is not an orphan; with its parent gone it is.
324    #[test]
325    fn a_child_of_a_stored_block_is_not_an_orphan() {
326        let child = |parent: &str| Block { oid: "shell".into(), parentoref: parent.to_string(), ..Default::default() };
327        let stored = [Block { oid: "agent".into(), ..Default::default() }];
328        assert!(is_sub_block_of_a_stored_block(&child("block:agent"), &stored));
329        assert!(!is_sub_block_of_a_stored_block(&child("block:gone"), &stored));
330        assert!(!is_sub_block_of_a_stored_block(&child("tab:agent"), &stored));
331        assert!(!is_sub_block_of_a_stored_block(&child(""), &stored));
332    }
333}