Skip to main content

agentmux_srv_core/
persist_subscriber.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Persist subscriber: a tokio task that consumes the srv reducer's event
5// bus and writes each domain event (workspaces, tabs, blocks, windows,
6// meta, the layout tree and its focus/magnify, the backend-action queue)
7// to SQLite through `apply_event_to_mstore`. The reducer owns that state;
8// SQLite is its projection, loaded back at startup by
9// `persist::bootstrap_state_from_mstore`.
10//
11// RPC handlers and saga steps also call `apply_event_to_mstore` right after
12// dispatching, so a follow-up read sees the write; every arm is idempotent,
13// so this task's second apply of the same event is a no-op. Events from the
14// srv IPC pipe (`srv_ipc/server.rs`) get no such synchronous apply and reach
15// SQLite only through this task.
16//
17// Bus lag: on `RecvError::Lagged` the dropped events are lost, so
18// `resync::resync_from_reducer` rewrites the workspace, tab, block, window
19// and layout rows from the reducer's snapshot (what it can't rebuild is in
20// that module's header).
21
22use std::sync::Arc;
23
24use agentmux_common::ipc::Event;
25use tokio::sync::{broadcast, Mutex};
26
27use crate::backend::obj::{
28    Block, Client, LayoutActionData, LayoutState as PersistedLayoutState, Tab, Window, Workspace,
29};
30use crate::backend::storage::store::Store;
31use crate::backend::wcore;
32use crate::state::State;
33
34pub mod layout_queue;
35pub mod parked;
36mod pins;
37mod tab_order;
38pub mod resync;
39
40use layout_queue::apply_layout_backend_actions_queued;
41
42/// Spawn the persist subscriber task. Runs until the broadcast
43/// channel closes (i.e., the reducer's bus is dropped at process
44/// shutdown). The `state` handle is read for the full resync after a
45/// `RecvError::Lagged`.
46pub fn spawn_persist_subscriber(
47    events_rx: broadcast::Receiver<Event>,
48    mstore: Arc<Store>,
49    state: Arc<Mutex<State>>,
50) -> tokio::task::JoinHandle<()> {
51    tokio::spawn(run_persist_subscriber(events_rx, mstore, state))
52}
53
54async fn run_persist_subscriber(
55    mut events_rx: broadcast::Receiver<Event>,
56    mstore: Arc<Store>,
57    state: Arc<Mutex<State>>,
58) {
59    tracing::info!(target: "srv-persist-subscriber", "[srv-persist-subscriber] started");
60    loop {
61        match events_rx.recv().await {
62            Ok(event) => {
63                if let Err(e) = apply_event_to_mstore(&event, &mstore) {
64                    tracing::warn!(
65                        target: "srv-persist-subscriber",
66                        "[srv-persist-subscriber] apply failed for event {:?}: {}",
67                        event_kind(&event),
68                        e
69                    );
70                }
71            }
72            Err(broadcast::error::RecvError::Lagged(n)) => {
73                // Dropped `n` events; rather than guess which were
74                // lost, rewrite SQLite's reducer-owned rows from the reducer.
75                tracing::warn!(
76                    target: "srv-persist-subscriber",
77                    "[srv-persist-subscriber] dropped {} event(s) — resyncing from the reducer",
78                    n
79                );
80                if let Err(e) = resync::resync_from_reducer(&state, &mstore).await {
81                    tracing::error!(
82                        target: "srv-persist-subscriber",
83                        "[srv-persist-subscriber] resync failed: {} — SQLite may diverge from reducer until next event",
84                        e
85                    );
86                }
87            }
88            Err(broadcast::error::RecvError::Closed) => {
89                tracing::info!(target: "srv-persist-subscriber", "[srv-persist-subscriber] bus closed — exiting");
90                return;
91            }
92        }
93    }
94}
95
96/// Apply one reducer event to the on-disk store. Idempotent: each
97/// arm checks for the entity's current SQLite state before writing
98/// so duplicate events (from at-least-once delivery semantics) don't
99/// produce duplicate rows or wcore errors.
100///
101/// Phase E.2c.2 — exposed at crate visibility so RPC handlers in
102/// `service.rs` can apply events synchronously after dispatching
103/// through the reducer. This closes the race where the async
104/// subscriber hadn't yet written SQLite by the time a follow-up
105/// RPC (e.g., `CreateTab` against a just-created workspace) tried
106/// to read it. Calling this from the RPC handler followed by the
107/// subscriber receiving the broadcast event is safe because the
108/// arms are idempotent — the subscriber's later apply is a no-op.
109pub fn apply_event_to_mstore(
110    event: &Event,
111    mstore: &Store,
112) -> Result<(), Box<dyn std::error::Error>> {
113    match event {
114        Event::WorkspaceCreated {
115            workspace_id, name, ..
116        } => apply_workspace_created(mstore, workspace_id, name),
117        Event::WorkspaceDeleted { workspace_id, .. } => {
118            apply_workspace_deleted(mstore, workspace_id)
119        }
120        Event::TabCreated {
121            workspace_id,
122            tab_id,
123            name,
124            ..
125        } => apply_tab_created(mstore, workspace_id, tab_id, name),
126        Event::TabDeleted {
127            workspace_id,
128            tab_id,
129            ..
130        } => apply_tab_deleted(mstore, workspace_id, tab_id),
131        Event::ActiveTabChanged {
132            workspace_id,
133            tab_id,
134            ..
135        } => apply_active_tab_changed(mstore, workspace_id, tab_id.as_deref()),
136        Event::TabReordered {
137            workspace_id,
138            tab_id,
139            new_index,
140            ..
141        } => tab_order::apply_tab_reordered(mstore, workspace_id, tab_id, *new_index),
142        Event::BlockCreated {
143            tab_id,
144            block_id,
145            meta,
146            ..
147        } => apply_block_created(mstore, tab_id, block_id, meta),
148        Event::BlockDeleted {
149            tab_id, block_id, ..
150        } => parked::apply_block_deleted(mstore, tab_id, block_id),
151        Event::PinsChanged { .. } => pins::apply(mstore, event),
152        Event::BlockParked { tab_id, block_id, .. } => parked::apply_block_parked(mstore, tab_id, block_id),
153        Event::BlockAttached { block_id, dst_tab_id, dst_index, .. } => parked::apply_block_attached(mstore, block_id, dst_tab_id, *dst_index),
154        Event::SrvWindowOpened {
155            window_id,
156            workspace_id,
157            ..
158        } => apply_srv_window_opened(mstore, window_id, workspace_id),
159        Event::SrvWindowClosed { window_id, .. } => apply_srv_window_closed(mstore, window_id),
160        Event::SrvWindowWorkspaceChanged {
161            window_id,
162            workspace_id,
163            ..
164        } => apply_srv_window_workspace_changed(mstore, window_id, workspace_id),
165        Event::TabsReorderedBulk {
166            workspace_id,
167            tab_ids,
168            ..
169        } => apply_tabs_reordered_bulk(mstore, workspace_id, tab_ids),
170        Event::WorkspaceRenamed {
171            workspace_id, name, ..
172        } => apply_workspace_renamed(mstore, workspace_id, name),
173        Event::TabRenamed { tab_id, name, .. } => apply_tab_renamed(mstore, tab_id, name),
174        Event::WorkspaceMetaUpdated {
175            workspace_id,
176            meta_patch,
177            ..
178        } => apply_workspace_meta_updated(mstore, workspace_id, meta_patch),
179        Event::WindowMetaUpdated {
180            window_id,
181            meta_patch,
182            ..
183        } => apply_window_meta_updated(mstore, window_id, meta_patch),
184        Event::TabMetaUpdated {
185            tab_id,
186            meta_patch,
187            ..
188        } => apply_tab_meta_updated(mstore, tab_id, meta_patch),
189        Event::BlockMetaUpdated {
190            block_id,
191            meta_patch,
192            ..
193        } => apply_block_meta_updated(mstore, block_id, meta_patch),
194        Event::TabMoved {
195            tab_id,
196            src_workspace_id,
197            dst_workspace_id,
198            dst_index,
199            new_src_active_tab_id,
200            new_dst_active_tab_id,
201            ..
202        } => apply_tab_moved(
203            mstore,
204            tab_id,
205            src_workspace_id,
206            dst_workspace_id,
207            *dst_index,
208            new_src_active_tab_id.as_deref(),
209            new_dst_active_tab_id.as_deref(),
210        ),
211        Event::BlockMoved {
212            block_id,
213            src_tab_id,
214            dst_tab_id,
215            dst_index,
216            ..
217        } => apply_block_moved(mstore, block_id, src_tab_id, dst_tab_id, *dst_index),
218        Event::FocusedNodeChanged { tab_id, node_id, .. } => {
219            apply_focused_node_changed(mstore, tab_id, node_id)
220        }
221        Event::MagnifiedNodeChanged { tab_id, node_id, .. } => {
222            apply_magnified_node_changed(mstore, tab_id, node_id)
223        }
224        // Layout-tree persistence. Every tree-changing event the reducer emits
225        // carries its resulting tree, so the subscriber writes it rather
226        // than re-running the tree algebra (a second divergence surface).
227        Event::LayoutTreeReplaced {
228            tab_id,
229            new_tree,
230            slices,
231            ..
232        } => apply_layout_tree_replaced(mstore, tab_id, new_tree, slices.as_ref(), NO_FOCUS_CLEAR),
233        // A delete is the one structural op that can legitimately EMPTY the
234        // tree (root-orphan case), so `tree_cleared` tells a real clear from
235        // a version-skewed sender's absent `new_tree`, which is ignored
236        // rather than applied as an erase. `was_focused`/`was_magnified`
237        // mean the reducer cleared that id; the row must match.
238        Event::LayoutNodeDeleted {
239            tab_id,
240            new_tree,
241            tree_cleared,
242            was_focused,
243            was_magnified,
244            ..
245        } => match (new_tree.is_some(), tree_cleared) {
246            (true, _) => apply_layout_tree_replaced(
247                mstore,
248                tab_id,
249                new_tree,
250                None,
251                FocusClear { focused: *was_focused, magnified: *was_magnified },
252            ),
253            (false, true) => apply_layout_tree_replaced(mstore, tab_id, &None, None, NO_FOCUS_CLEAR),
254            (false, false) => Ok(()),
255        },
256        // SPEC_864 Phase 4 — APPEND to the pending queue (unlike the
257        // slices path above, which REPLACEs it). Idempotent under the
258        // double-apply contract (sync from the dispatch helper, again
259        // from broadcast) by deduping on `actionid` — every writer
260        // stamps a fresh UUID per action.
261        Event::LayoutBackendActionsQueued { tab_id, actions, .. } => {
262            apply_layout_backend_actions_queued(mstore, tab_id, actions)
263        }
264        // All other event variants are not domain-state mutations
265        // (lifecycle, errors, snapshots). The subscriber ignores them.
266        _ => Ok(()),
267    }
268}
269
270fn apply_workspace_created(
271    mstore: &Store,
272    workspace_id: &str,
273    name: &str,
274) -> Result<(), Box<dyn std::error::Error>> {
275    if mstore.get::<Workspace>(workspace_id)?.is_some() {
276        return Ok(()); // already present
277    }
278    let mut ws = Workspace {
279        oid: workspace_id.to_string(),
280        name: name.to_string(),
281        ..Default::default()
282    };
283    mstore.insert(&mut ws)?;
284    Ok(())
285}
286
287fn apply_workspace_deleted(
288    mstore: &Store,
289    workspace_id: &str,
290) -> Result<(), Box<dyn std::error::Error>> {
291    if mstore.get::<Workspace>(workspace_id)?.is_none() {
292        return Ok(()); // already gone
293    }
294    wcore::delete_workspace(mstore, workspace_id)?;
295    Ok(())
296}
297
298fn apply_tab_created(
299    mstore: &Store,
300    workspace_id: &str,
301    tab_id: &str,
302    name: &str,
303) -> Result<(), Box<dyn std::error::Error>> {
304    // F1.A — wrap the insert-layout + insert-tab + update-workspace
305    // sequence in a single SQLite transaction so a partial failure
306    // can't leave a tab without a layout or a workspace whose
307    // tab_ids points at a tab that doesn't exist on disk.
308    mstore.with_tx(|tx| {
309        if tx.get::<Tab>(tab_id)?.is_none() {
310            // Phase E.2c.2 — create a LayoutState row alongside the
311            // Tab so reducer-originated tabs have a `Tab.layoutstate`
312            // to seed (e.g. `setup_torn_off_block_layout`'s
313            // `seed_layout_via_reducer` call) just like wcore-created
314            // tabs. Mirrors the wcore::create_tab pattern. (codex P2 #614.)
315            let mut layout = PersistedLayoutState {
316                oid: uuid::Uuid::new_v4().to_string(),
317                rootnode: None,
318                magnifiednodeid: String::new(),
319                focusednodeid: String::new(),
320                pendingbackendactions: None,
321                meta: None,
322                ..Default::default()
323            };
324            tx.insert(&mut layout)?;
325            let mut tab = Tab {
326                oid: tab_id.to_string(),
327                name: name.to_string(),
328                layoutstate: layout.oid.clone(),
329                ..Default::default()
330            };
331            tx.insert(&mut tab)?;
332        }
333        // Idempotently link tab into the workspace's tabids.
334        if let Some(mut ws) = tx.get::<Workspace>(workspace_id)? {
335            let already_present = ws.tabids.iter().any(|t| t == tab_id)
336                || ws.pinnedtabids.iter().any(|t| t == tab_id);
337            if !already_present {
338                ws.tabids.push(tab_id.to_string());
339                tx.update(&mut ws)?;
340            }
341        }
342        Ok(())
343    })?;
344    Ok(())
345}
346
347fn apply_tab_deleted(
348    mstore: &Store,
349    workspace_id: &str,
350    tab_id: &str,
351) -> Result<(), Box<dyn std::error::Error>> {
352    if mstore.get::<Tab>(tab_id)?.is_none() {
353        return Ok(()); // already gone (or never existed)
354    }
355    // wcore::delete_tab handles unlinking from the workspace's
356    // tabids, deleting the tab's blocks + layout, and the tab row
357    // itself. Returns NotFound errors if any of those don't exist —
358    // we surface those as the operation having already happened.
359    match wcore::delete_tab(mstore, workspace_id, tab_id) {
360        Ok(()) => Ok(()),
361        Err(crate::backend::storage::StoreError::NotFound) => Ok(()),
362        Err(e) => Err(Box::new(e)),
363    }
364}
365
366fn apply_active_tab_changed(
367    mstore: &Store,
368    workspace_id: &str,
369    tab_id: Option<&str>,
370) -> Result<(), Box<dyn std::error::Error>> {
371    let Some(mut ws) = mstore.get::<Workspace>(workspace_id)? else {
372        return Ok(()); // workspace already gone — nothing to update
373    };
374    let new = tab_id.unwrap_or("").to_string();
375    if ws.activetabid == new {
376        return Ok(());
377    }
378    ws.activetabid = new;
379    mstore.update(&mut ws)?;
380    Ok(())
381}
382
383fn apply_block_created(
384    mstore: &Store,
385    tab_id: &str,
386    block_id: &str,
387    meta: &serde_json::Value,
388) -> Result<(), Box<dyn std::error::Error>> {
389    // F1.A — block insert + tab.blockids update wrapped in one tx.
390    let meta_map: crate::backend::obj::MetaMapType = match meta {
391        serde_json::Value::Object(_) => {
392            serde_json::from_value(meta.clone()).unwrap_or_default()
393        }
394        _ => Default::default(),
395    };
396    mstore.with_tx(|tx| {
397        if tx.get::<Block>(block_id)?.is_none() {
398            // Phase E.2c.4 — write the meta map carried in the event
399            // (`view`, layout hints, etc.) so reducer-routed
400            // CreateBlock RPC produces blocks with valid view/meta in
401            // SQLite. Without this, the frontend sees a block with
402            // empty meta and renders a blank pane.
403            let mut block = Block {
404                oid: block_id.to_string(),
405                parentoref: format!("tab:{}", tab_id),
406                meta: meta_map,
407                ..Default::default()
408            };
409            tx.insert(&mut block)?;
410        }
411        if let Some(mut tab) = tx.get::<Tab>(tab_id)? {
412            if !tab.blockids.iter().any(|b| b == block_id) {
413                tab.blockids.push(block_id.to_string());
414                tx.update(&mut tab)?;
415            }
416        }
417        Ok(())
418    })?;
419    Ok(())
420}
421
422/// Phase E.5 — record/update a window's workspace pointer on the
423/// persisted Window row. Idempotent: inserts if missing, updates
424/// if `workspaceid` differs, no-ops if identical.
425///
426/// Also keeps `Client.windowids` in sync — appends the new window_id
427/// when the Window row is freshly created. The legacy
428/// `wcore::create_window_full` path does this too; without it, the
429/// Window row exists but `GetClientData` / focus-order logic can't
430/// see it. (codex P1 #619.)
431fn apply_srv_window_opened(
432    mstore: &Store,
433    window_id: &str,
434    workspace_id: &str,
435) -> Result<(), Box<dyn std::error::Error>> {
436    // F1.A — Window upsert + Client.windowids update wrapped in one
437    // tx so a partial failure can't leave a Window row that
438    // `GetClientData` doesn't see (or a `windowids` entry pointing
439    // at a Window row that wasn't written).
440    mstore.with_tx(|tx| {
441        let was_new = match tx.get::<Window>(window_id)? {
442            Some(existing) if existing.workspaceid == workspace_id => false,
443            Some(mut existing) => {
444                existing.workspaceid = workspace_id.to_string();
445                tx.update(&mut existing)?;
446                false
447            }
448            None => {
449                let mut window = Window {
450                    oid: window_id.to_string(),
451                    workspaceid: workspace_id.to_string(),
452                    ..Default::default()
453                };
454                tx.insert(&mut window)?;
455                true
456            }
457        };
458        if was_new {
459            // Inline `wcore::get_client` against the tx-handle to keep
460            // the Client.windowids update in the same transaction.
461            let clients = tx.get_all::<Client>()?;
462            if let Some(mut client) = clients.into_iter().next() {
463                if !client.windowids.iter().any(|id| id == window_id) {
464                    client.windowids.push(window_id.to_string());
465                    tx.update(&mut client)?;
466                }
467            }
468        }
469        Ok(())
470    })?;
471    Ok(())
472}
473
474/// Phase E.5 — remove the id from `Client.windowids`, then delete the
475/// persisted Window row, in one transaction. Pruning FIRST means any
476/// read between the two ops doesn't see a dangling id.
477/// (codex P1 #619.)
478///
479/// `pub(crate)`: besides the `SrvWindowClosed` subscriber arm, the
480/// `CloseWindow` handler calls this directly on its divergence path —
481/// when the reducer never knew the window (silent no-op, no event) but
482/// the store still holds it (#2051). Deliberately defensive/idempotent:
483/// both callers rely on the already-gone cases being safe.
484pub fn apply_srv_window_closed(
485    mstore: &Store,
486    window_id: &str,
487) -> Result<(), Box<dyn std::error::Error>> {
488    // F1.A — Client.windowids prune + Window-row delete in one tx.
489    // Order matters: prune the client list FIRST so any read between
490    // the two ops doesn't see a dangling id pointing at a Window row
491    // that's already been removed.
492    mstore.with_tx(|tx| {
493        let window_exists = tx.get::<Window>(window_id)?.is_some();
494        // Always defensively prune the client list — handles the
495        // already-gone case where divergence left a stale entry.
496        let clients = tx.get_all::<Client>()?;
497        if let Some(mut client) = clients.into_iter().next() {
498            if client.windowids.iter().any(|id| id == window_id) {
499                client.windowids.retain(|id| id != window_id);
500                tx.update(&mut client)?;
501            }
502        }
503        if window_exists {
504            tx.delete::<Window>(window_id)?;
505        }
506        Ok(())
507    })?;
508    Ok(())
509}
510
511/// Phase E.5 — same shape as `apply_srv_window_opened` for the
512/// upsert behavior; separate function for log-clarity since the
513/// emitted event is distinct.
514fn apply_srv_window_workspace_changed(
515    mstore: &Store,
516    window_id: &str,
517    workspace_id: &str,
518) -> Result<(), Box<dyn std::error::Error>> {
519    apply_srv_window_opened(mstore, window_id, workspace_id)
520}
521
522/// Phase E.5.3 — replace the workspace's `tabids` with the new
523/// list and drain any legacy `pinnedtabids` rows. Pinning was a
524/// Waveterm feature removed from AgentMux; bootstrap merges legacy
525/// pinned tabs into the reducer's `tab_ids`, so the next reorder
526/// is the canonical full ordering. Leaving stale `pinnedtabids`
527/// in SQLite would cause UI double-insertion (`workspace.tsx`
528/// builds the displayed tab list as `[...pinnedtabids, ...tabids]`).
529fn apply_tabs_reordered_bulk(
530    mstore: &Store,
531    workspace_id: &str,
532    tab_ids: &[String],
533) -> Result<(), Box<dyn std::error::Error>> {
534    let Some(mut ws) = mstore.get::<Workspace>(workspace_id)? else {
535        return Ok(());
536    };
537    let tabids_match = ws.tabids == tab_ids;
538    let pinned_clear = ws.pinnedtabids.is_empty();
539    if tabids_match && pinned_clear {
540        return Ok(());
541    }
542    ws.tabids = tab_ids.to_vec();
543    ws.pinnedtabids.clear();
544    mstore.update(&mut ws)?;
545    Ok(())
546}
547
548/// Phase E.5.3 — rename a persisted workspace.
549fn apply_workspace_renamed(
550    mstore: &Store,
551    workspace_id: &str,
552    name: &str,
553) -> Result<(), Box<dyn std::error::Error>> {
554    let Some(mut ws) = mstore.get::<Workspace>(workspace_id)? else {
555        return Ok(());
556    };
557    if ws.name == name {
558        return Ok(());
559    }
560    ws.name = name.to_string();
561    mstore.update(&mut ws)?;
562    Ok(())
563}
564
565/// Phase E.5.3 — rename a persisted tab.
566fn apply_tab_renamed(
567    mstore: &Store,
568    tab_id: &str,
569    name: &str,
570) -> Result<(), Box<dyn std::error::Error>> {
571    let Some(mut tab) = mstore.get::<Tab>(tab_id)? else {
572        return Ok(());
573    };
574    if tab.name == name {
575        return Ok(());
576    }
577    tab.name = name.to_string();
578    mstore.update(&mut tab)?;
579    Ok(())
580}
581
582/// Phase E.4 (Option A) — write the reducer-emitted focused node id
583/// onto the tab's `LayoutState.focusednodeid` column. Tab→layout is
584/// a join through `Tab.layoutstate`. Idempotent: silent no-op when the
585/// tab is unknown (deleted concurrently), the layout row is missing
586/// (legacy tab without one), or the value already matches. Other
587/// `LayoutState` fields stay on their existing wcore-direct path until
588/// Option B lands.
589fn apply_focused_node_changed(
590    mstore: &Store,
591    tab_id: &str,
592    node_id: &str,
593) -> Result<(), Box<dyn std::error::Error>> {
594    let Some(tab) = mstore.get::<Tab>(tab_id)? else {
595        return Ok(());
596    };
597    if tab.layoutstate.is_empty() {
598        return Ok(());
599    }
600    let Some(mut layout) = mstore.get::<PersistedLayoutState>(&tab.layoutstate)? else {
601        return Ok(());
602    };
603    if layout.focusednodeid == node_id {
604        return Ok(());
605    }
606    layout.focusednodeid = node_id.to_string();
607    mstore.update(&mut layout)?;
608    Ok(())
609}
610
611/// Phase E.4 (Option A) — write the reducer-emitted magnified node id
612/// onto the tab's `LayoutState.magnifiednodeid` column. Same shape as
613/// `apply_focused_node_changed`.
614fn apply_magnified_node_changed(
615    mstore: &Store,
616    tab_id: &str,
617    node_id: &str,
618) -> Result<(), Box<dyn std::error::Error>> {
619    let Some(tab) = mstore.get::<Tab>(tab_id)? else {
620        return Ok(());
621    };
622    if tab.layoutstate.is_empty() {
623        return Ok(());
624    }
625    let Some(mut layout) = mstore.get::<PersistedLayoutState>(&tab.layoutstate)? else {
626        return Ok(());
627    };
628    if layout.magnifiednodeid == node_id {
629        return Ok(());
630    }
631    layout.magnifiednodeid = node_id.to_string();
632    mstore.update(&mut layout)?;
633    Ok(())
634}
635
636/// Focus/magnify ids a tree-only layout event says the reducer cleared.
637#[derive(Clone, Copy)]
638struct FocusClear {
639    focused: bool,
640    magnified: bool,
641}
642
643const NO_FOCUS_CLEAR: FocusClear = FocusClear { focused: false, magnified: false };
644
645/// Phase E.4.B — apply a `LayoutTreeReplaced` event: write the reducer-
646/// supplied tree onto `LayoutState.rootnode`. Mirrors
647/// `reducer::layout::handle_layout_set_tree` — when the new tree is
648/// empty, also clear the focus/magnify ids so they don't dangle at nodes
649/// that no longer exist.
650///
651/// When the event carries `slices` (a seeding `LayoutSetTree`), the rest of
652/// the row is REPLACED: pendingbackendactions is written verbatim (absent =
653/// clear); focus/magnify strings overwrite (empty = clear). `slices: None`
654/// (tree-only events) leaves those fields untouched, except that `clear`
655/// empties a focus/magnify id the reducer dropped with the edit. Idempotent:
656/// no-op (no version bump) when nothing changes.
657fn apply_layout_tree_replaced(
658    mstore: &Store,
659    tab_id: &str,
660    new_tree: &Option<agentmux_common::LayoutNode>,
661    slices: Option<&agentmux_common::LayoutClientSlices>,
662    clear: FocusClear,
663) -> Result<(), Box<dyn std::error::Error>> {
664    let Some(tab) = mstore.get::<Tab>(tab_id)? else {
665        return Ok(());
666    };
667    if tab.layoutstate.is_empty() {
668        return Ok(());
669    }
670    let Some(mut layout) = mstore.get::<PersistedLayoutState>(&tab.layoutstate)? else {
671        return Ok(());
672    };
673    let clears = new_tree.is_none();
674
675    // Compute the candidate values for every column this event owns, then
676    // write once only if something actually changed (idempotency contract:
677    // a double-apply — sync from the RPC handler, again from broadcast —
678    // must not churn the version).
679    let new_focused = match (slices, clears) {
680        (_, true) => String::new(),
681        (Some(s), false) => s.focused_node_id.clone(),
682        (None, false) if clear.focused => String::new(),
683        (None, false) => layout.focusednodeid.clone(),
684    };
685    let new_magnified = match (slices, clears) {
686        (_, true) => String::new(),
687        (Some(s), false) => s.magnified_node_id.clone(),
688        (None, false) if clear.magnified => String::new(),
689        (None, false) => layout.magnifiednodeid.clone(),
690    };
691    let new_pending: Option<Vec<LayoutActionData>> = match slices {
692        // The pending queue is frontend-acked state, not tree geometry —
693        // an empty-tree `LayoutSetTree` still replaces it (unlike focus,
694        // which dangles without a tree).
695        Some(s) => match &s.pending_backend_actions {
696            Some(v) if !v.is_null() => Some(serde_json::from_value(v.clone())?),
697            _ => None,
698        },
699        None => layout_queue::without_stale(layout.pendingbackendactions.clone()),
700    };
701
702    let already = layout.rootnode == *new_tree
703        && layout.focusednodeid == new_focused
704        && layout.magnifiednodeid == new_magnified
705        && layout.pendingbackendactions == new_pending;
706    if already {
707        return Ok(());
708    }
709    layout.rootnode = new_tree.clone();
710    layout.focusednodeid = new_focused;
711    layout.magnifiednodeid = new_magnified;
712    layout.pendingbackendactions = new_pending;
713    mstore.update(&mut layout)?;
714    Ok(())
715}
716
717/// Phase E.5.3 — apply a meta-patch to a workspace's `meta` map.
718/// Reducer doesn't track meta in `WorkspaceRecord`; this subscriber
719/// is the sole authority that mutates persisted meta. Patch is a
720/// JSON object that merges shallow-key-by-shallow-key on top of the
721/// existing meta. `null` values in the patch delete the key.
722fn apply_workspace_meta_updated(
723    mstore: &Store,
724    workspace_id: &str,
725    meta_patch: &serde_json::Value,
726) -> Result<(), Box<dyn std::error::Error>> {
727    let Some(mut ws) = mstore.get::<Workspace>(workspace_id)? else {
728        return Ok(());
729    };
730    if merge_meta_patch(&mut ws.meta, meta_patch) {
731        mstore.update(&mut ws)?;
732    }
733    Ok(())
734}
735
736/// Phase E.5.x (issue #855) — apply a meta-patch to a window's `meta`
737/// map. Same shape as `apply_workspace_meta_updated`. Silent no-op if
738/// the window doesn't exist in mstore (preserves the idempotency
739/// contract — duplicate or stale events fold to no-op).
740fn apply_window_meta_updated(
741    mstore: &Store,
742    window_id: &str,
743    meta_patch: &serde_json::Value,
744) -> Result<(), Box<dyn std::error::Error>> {
745    let Some(mut window) = mstore.get::<Window>(window_id)? else {
746        return Ok(());
747    };
748    if merge_meta_patch(&mut window.meta, meta_patch) {
749        mstore.update(&mut window)?;
750    }
751    Ok(())
752}
753
754/// Phase E.5.3 — apply a meta-patch to a tab's `meta` map.
755fn apply_tab_meta_updated(
756    mstore: &Store,
757    tab_id: &str,
758    meta_patch: &serde_json::Value,
759) -> Result<(), Box<dyn std::error::Error>> {
760    let Some(mut tab) = mstore.get::<Tab>(tab_id)? else {
761        return Ok(());
762    };
763    if merge_meta_patch(&mut tab.meta, meta_patch) {
764        mstore.update(&mut tab)?;
765    }
766    Ok(())
767}
768
769/// Phase E.5.3 — apply a meta-patch to a block's `meta` map.
770fn apply_block_meta_updated(
771    mstore: &Store,
772    block_id: &str,
773    meta_patch: &serde_json::Value,
774) -> Result<(), Box<dyn std::error::Error>> {
775    let Some(mut block) = mstore.get::<Block>(block_id)? else {
776        return Ok(());
777    };
778    if merge_meta_patch(&mut block.meta, meta_patch) {
779        mstore.update(&mut block)?;
780    }
781    Ok(())
782}
783
784/// Phase E.5.5 — apply a `TabMoved` event to SQLite.
785/// Idempotent: detects already-moved state (tab in dst, not in src)
786/// and returns `Ok(())` without re-mutating.
787///
788/// What this writes:
789/// * Removes `tab_id` from `src_workspace.tabids` (and `pinnedtabids`
790///   for legacy rows — bootstrap merges them into reducer state, so
791///   any leftover here is a stray legacy entry that should be drained).
792/// * Updates `src_workspace.activetabid` to `new_src_active_tab_id`
793///   (which may be empty when the source emptied).
794/// * Inserts `tab_id` at `dst_index` in `dst_workspace.tabids`,
795///   clamping to the dst list length.
796/// * Updates the `Tab` row's parent ref so loaders find it under
797///   the new workspace.
798fn apply_tab_moved(
799    mstore: &Store,
800    tab_id: &str,
801    src_workspace_id: &str,
802    dst_workspace_id: &str,
803    dst_index: u32,
804    new_src_active_tab_id: Option<&str>,
805    new_dst_active_tab_id: Option<&str>,
806) -> Result<(), Box<dyn std::error::Error>> {
807    // F1.A — both workspaces' updates wrapped in one tx so a partial
808    // failure can't leave the tab in both src.tabids and dst.tabids
809    // simultaneously, or in neither.
810    mstore.with_tx(|tx| {
811        // Source workspace: remove the tab and update activetabid.
812        if let Some(mut src_ws) = tx.get::<Workspace>(src_workspace_id)? {
813            let len_before_tabids = src_ws.tabids.len();
814            let len_before_pinned = src_ws.pinnedtabids.len();
815            src_ws.tabids.retain(|id| id != tab_id);
816            src_ws.pinnedtabids.retain(|id| id != tab_id);
817            let new_active = new_src_active_tab_id.unwrap_or("").to_string();
818            let active_changed = src_ws.activetabid != new_active;
819            if src_ws.tabids.len() != len_before_tabids
820                || src_ws.pinnedtabids.len() != len_before_pinned
821                || active_changed
822            {
823                src_ws.activetabid = new_active;
824                tx.update(&mut src_ws)?;
825            }
826        }
827
828        // Dest workspace: insert at clamped index + update
829        // active_tab_id if the event carries one (codex P2 #621).
830        // Skip insert if the tab is already present (idempotent on
831        // duplicate delivery).
832        if let Some(mut dst_ws) = tx.get::<Workspace>(dst_workspace_id)? {
833            // `dst_index` counts the legacy pinned tabs too (tab_order.rs).
834            let mut changed = tab_order::fold_pinned_into_tabids(&mut dst_ws);
835            if !dst_ws.tabids.iter().any(|id| id == tab_id) {
836                let clamped = (dst_index as usize).min(dst_ws.tabids.len());
837                dst_ws.tabids.insert(clamped, tab_id.to_string());
838                changed = true;
839            }
840            if let Some(new_active) = new_dst_active_tab_id {
841                if dst_ws.activetabid != new_active {
842                    dst_ws.activetabid = new_active.to_string();
843                    changed = true;
844                }
845            }
846            if changed {
847                tx.update(&mut dst_ws)?;
848            }
849        }
850
851        // No per-Tab parent ref to update — the workspace owns the
852        // parentage relationship via its `tabids` list.
853        Ok(())
854    })?;
855    Ok(())
856}
857
858/// Phase E.5.5 — apply a `BlockMoved` event to SQLite.
859/// Handles both cross-tab moves and intra-tab repositioning.
860/// Idempotent on re-delivery (checks current parent before mutating).
861fn apply_block_moved(
862    mstore: &Store,
863    block_id: &str,
864    src_tab_id: &str,
865    dst_tab_id: &str,
866    dst_index: u32,
867) -> Result<(), Box<dyn std::error::Error>> {
868    // F1.A — src.blockids + dst.blockids + block.parentoref updates
869    // wrapped in one tx so a partial failure can't leave the block in
870    // both tabs' blockids or with parentoref pointing at the wrong
871    // tab.
872    mstore.with_tx(|tx| {
873        if src_tab_id == dst_tab_id {
874            // Intra-tab reposition: remove + re-insert in the same tab.
875            if let Some(mut tab) = tx.get::<Tab>(src_tab_id)? {
876                tab.blockids.retain(|id| id != block_id);
877                let clamped = (dst_index as usize).min(tab.blockids.len());
878                tab.blockids.insert(clamped, block_id.to_string());
879                tx.update(&mut tab)?;
880            }
881            return Ok(());
882        }
883
884        // Cross-tab: remove from src.
885        if let Some(mut src_tab) = tx.get::<Tab>(src_tab_id)? {
886            let before = src_tab.blockids.len();
887            src_tab.blockids.retain(|id| id != block_id);
888            if src_tab.blockids.len() != before {
889                tx.update(&mut src_tab)?;
890            }
891        }
892
893        // Insert into dst (skip if already there).
894        if let Some(mut dst_tab) = tx.get::<Tab>(dst_tab_id)? {
895            if !dst_tab.blockids.iter().any(|id| id == block_id) {
896                let clamped = (dst_index as usize).min(dst_tab.blockids.len());
897                dst_tab.blockids.insert(clamped, block_id.to_string());
898                tx.update(&mut dst_tab)?;
899            }
900        }
901
902        // Block row: update parent.
903        if let Some(mut block) = tx.get::<Block>(block_id)? {
904            let new_parent = format!("tab:{}", dst_tab_id);
905            if block.parentoref != new_parent {
906                block.parentoref = new_parent;
907                tx.update(&mut block)?;
908            }
909        }
910
911        Ok(())
912    })?;
913    Ok(())
914}
915
916/// Phase E.5.3 — shallow merge a JSON object patch into a
917/// `MetaMapType`. Mirrors `backend::obj::merge_meta` semantics so
918/// `UpdateObjectMeta` keeps behaving the same way after the reducer
919/// migration:
920/// - Keys ending in `:*` with a `true` value clear all keys with
921///   that prefix (e.g. `{"term:*": true}` removes every `term*`
922///   key) before regular merging.
923/// - `null` patch values delete the corresponding key.
924/// - Other values replace the key.
925/// Returns `true` if anything actually changed.
926fn merge_meta_patch(
927    meta: &mut crate::backend::obj::MetaMapType,
928    patch: &serde_json::Value,
929) -> bool {
930    let serde_json::Value::Object(patch_map) = patch else {
931        return false;
932    };
933    let mut changed = false;
934    // First pass: section-clear keys (`prefix:*` with `true`).
935    for (k, v) in patch_map {
936        if !k.ends_with(":*") {
937            continue;
938        }
939        if !matches!(v, serde_json::Value::Bool(true)) {
940            continue;
941        }
942        let prefix = k.trim_end_matches(":*");
943        if prefix.is_empty() {
944            continue;
945        }
946        let prefix_colon = format!("{prefix}:");
947        let before = meta.len();
948        meta.retain(|k2, _| k2 != prefix && !k2.starts_with(&prefix_colon));
949        if meta.len() != before {
950            changed = true;
951        }
952    }
953    // Second pass: regular merges and null deletes.
954    for (k, v) in patch_map {
955        if k.ends_with(":*") {
956            continue;
957        }
958        if v.is_null() {
959            if meta.remove(k).is_some() {
960                changed = true;
961            }
962            continue;
963        }
964        match meta.get(k) {
965            Some(existing) if existing == v => {}
966            _ => {
967                meta.insert(k.clone(), v.clone());
968                changed = true;
969            }
970        }
971    }
972    changed
973}
974
975/// Compact textual identifier for an event (debug logging only).
976fn event_kind(event: &Event) -> &'static str {
977    match event {
978        Event::WorkspaceCreated { .. } => "WorkspaceCreated",
979        Event::WorkspaceDeleted { .. } => "WorkspaceDeleted",
980        Event::TabCreated { .. } => "TabCreated",
981        Event::TabDeleted { .. } => "TabDeleted",
982        Event::ActiveTabChanged { .. } => "ActiveTabChanged",
983        Event::TabReordered { .. } => "TabReordered",
984        Event::SrvWindowOpened { .. } => "SrvWindowOpened",
985        Event::SrvWindowClosed { .. } => "SrvWindowClosed",
986        Event::SrvWindowWorkspaceChanged { .. } => "SrvWindowWorkspaceChanged",
987        Event::TabsReorderedBulk { .. } => "TabsReorderedBulk",
988        Event::WorkspaceRenamed { .. } => "WorkspaceRenamed",
989        Event::TabRenamed { .. } => "TabRenamed",
990        Event::WorkspaceMetaUpdated { .. } => "WorkspaceMetaUpdated",
991        Event::WindowMetaUpdated { .. } => "WindowMetaUpdated",
992        Event::TabMetaUpdated { .. } => "TabMetaUpdated",
993        Event::BlockMetaUpdated { .. } => "BlockMetaUpdated",
994        Event::TabMoved { .. } => "TabMoved",
995        Event::BlockMoved { .. } => "BlockMoved",
996        Event::BlockCreated { .. } => "BlockCreated",
997        Event::BlockDeleted { .. } => "BlockDeleted",
998        Event::FocusedNodeChanged { .. } => "FocusedNodeChanged",
999        Event::MagnifiedNodeChanged { .. } => "MagnifiedNodeChanged",
1000        _ => "Other",
1001    }
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use super::*;
1007    use crate::backend::storage::store::Store;
1008
1009    fn store() -> Arc<Store> {
1010        // In-memory SQLite for tests (matches existing mstore test pattern).
1011        let store = Store::open_in_memory().expect("in-memory mstore");
1012        Arc::new(store)
1013    }
1014
1015    #[test]
1016    fn workspace_created_inserts_row() {
1017        let s = store();
1018        apply_event_to_mstore(
1019            &Event::WorkspaceCreated {
1020                workspace_id: "ws-1".into(),
1021                name: "Alpha".into(),
1022                version: 1,
1023            },
1024            &s,
1025        )
1026        .unwrap();
1027        let ws = s.get::<Workspace>("ws-1").unwrap().unwrap();
1028        assert_eq!(ws.name, "Alpha");
1029    }
1030
1031    #[test]
1032    fn workspace_created_idempotent_on_duplicate() {
1033        let s = store();
1034        let ev = Event::WorkspaceCreated {
1035            workspace_id: "ws-1".into(),
1036            name: "Alpha".into(),
1037            version: 1,
1038        };
1039        apply_event_to_mstore(&ev, &s).unwrap();
1040        // Second application should not error.
1041        apply_event_to_mstore(&ev, &s).unwrap();
1042        // Original name preserved (no overwrite).
1043        let ws = s.get::<Workspace>("ws-1").unwrap().unwrap();
1044        assert_eq!(ws.name, "Alpha");
1045    }
1046
1047    #[test]
1048    fn workspace_deleted_silent_when_missing() {
1049        let s = store();
1050        apply_event_to_mstore(
1051            &Event::WorkspaceDeleted {
1052                workspace_id: "ghost".into(),
1053                block_ids: Vec::new(),
1054                version: 1,
1055            },
1056            &s,
1057        )
1058        .unwrap();
1059    }
1060
1061    #[test]
1062    fn tab_created_links_into_workspace() {
1063        let s = store();
1064        apply_event_to_mstore(
1065            &Event::WorkspaceCreated {
1066                workspace_id: "ws-1".into(),
1067                name: "Alpha".into(),
1068                version: 1,
1069            },
1070            &s,
1071        )
1072        .unwrap();
1073        apply_event_to_mstore(
1074            &Event::TabCreated {
1075                workspace_id: "ws-1".into(),
1076                tab_id: "tab-1".into(),
1077                name: "Tab".into(),
1078                version: 2,
1079            },
1080            &s,
1081        )
1082        .unwrap();
1083        let ws = s.get::<Workspace>("ws-1").unwrap().unwrap();
1084        assert_eq!(ws.tabids, vec!["tab-1".to_string()]);
1085        let tab = s.get::<Tab>("tab-1").unwrap().unwrap();
1086        assert_eq!(tab.name, "Tab");
1087    }
1088
1089    #[test]
1090    fn tab_created_idempotent_on_duplicate_link() {
1091        let s = store();
1092        apply_event_to_mstore(
1093            &Event::WorkspaceCreated {
1094                workspace_id: "ws-1".into(),
1095                name: "Alpha".into(),
1096                version: 1,
1097            },
1098            &s,
1099        )
1100        .unwrap();
1101        let ev = Event::TabCreated {
1102            workspace_id: "ws-1".into(),
1103            tab_id: "tab-1".into(),
1104            name: "Tab".into(),
1105            version: 2,
1106        };
1107        apply_event_to_mstore(&ev, &s).unwrap();
1108        apply_event_to_mstore(&ev, &s).unwrap();
1109        let ws = s.get::<Workspace>("ws-1").unwrap().unwrap();
1110        assert_eq!(ws.tabids.len(), 1);
1111    }
1112
1113    #[test]
1114    fn active_tab_changed_updates_workspace() {
1115        let s = store();
1116        apply_event_to_mstore(
1117            &Event::WorkspaceCreated {
1118                workspace_id: "ws-1".into(),
1119                name: "Alpha".into(),
1120                version: 1,
1121            },
1122            &s,
1123        )
1124        .unwrap();
1125        apply_event_to_mstore(
1126            &Event::TabCreated {
1127                workspace_id: "ws-1".into(),
1128                tab_id: "tab-1".into(),
1129                name: "Tab".into(),
1130                version: 2,
1131            },
1132            &s,
1133        )
1134        .unwrap();
1135        apply_event_to_mstore(
1136            &Event::ActiveTabChanged {
1137                workspace_id: "ws-1".into(),
1138                tab_id: Some("tab-1".into()),
1139                version: 3,
1140            },
1141            &s,
1142        )
1143        .unwrap();
1144        let ws = s.get::<Workspace>("ws-1").unwrap().unwrap();
1145        assert_eq!(ws.activetabid, "tab-1");
1146    }
1147
1148    #[test]
1149    fn active_tab_changed_to_none_clears_activetabid() {
1150        let s = store();
1151        apply_event_to_mstore(
1152            &Event::WorkspaceCreated {
1153                workspace_id: "ws-1".into(),
1154                name: "Alpha".into(),
1155                version: 1,
1156            },
1157            &s,
1158        )
1159        .unwrap();
1160        apply_event_to_mstore(
1161            &Event::TabCreated {
1162                workspace_id: "ws-1".into(),
1163                tab_id: "tab-1".into(),
1164                name: "Tab".into(),
1165                version: 2,
1166            },
1167            &s,
1168        )
1169        .unwrap();
1170        apply_event_to_mstore(
1171            &Event::ActiveTabChanged {
1172                workspace_id: "ws-1".into(),
1173                tab_id: Some("tab-1".into()),
1174                version: 3,
1175            },
1176            &s,
1177        )
1178        .unwrap();
1179        apply_event_to_mstore(
1180            &Event::ActiveTabChanged {
1181                workspace_id: "ws-1".into(),
1182                tab_id: None,
1183                version: 4,
1184            },
1185            &s,
1186        )
1187        .unwrap();
1188        let ws = s.get::<Workspace>("ws-1").unwrap().unwrap();
1189        assert_eq!(ws.activetabid, "");
1190    }
1191
1192    #[test]
1193    fn tab_created_provisions_layoutstate() {
1194        let s = store();
1195        apply_event_to_mstore(
1196            &Event::WorkspaceCreated {
1197                workspace_id: "ws-1".into(),
1198                name: "Alpha".into(),
1199                version: 1,
1200            },
1201            &s,
1202        )
1203        .unwrap();
1204        apply_event_to_mstore(
1205            &Event::TabCreated {
1206                workspace_id: "ws-1".into(),
1207                tab_id: "tab-1".into(),
1208                name: "Tab".into(),
1209                version: 2,
1210            },
1211            &s,
1212        )
1213        .unwrap();
1214        let tab = s.get::<Tab>("tab-1").unwrap().unwrap();
1215        // codex P2 #614: tab must reference a real LayoutState row,
1216        // not be left with empty layoutstate.
1217        assert!(!tab.layoutstate.is_empty());
1218        let layout = s
1219            .get::<PersistedLayoutState>(&tab.layoutstate)
1220            .unwrap()
1221            .expect("layout row must exist");
1222        assert_eq!(layout.oid, tab.layoutstate);
1223    }
1224
1225    // ── Layout-tree persistence (Phase E.4.B) ───────────────────────────
1226    fn leaf(id: &str, block: &str) -> agentmux_common::LayoutNode {
1227        agentmux_common::LayoutNode {
1228            id: id.into(),
1229            data: Some(agentmux_common::LayoutNodeData {
1230                block_id: block.into(),
1231                ..Default::default()
1232            }),
1233            ..Default::default()
1234        }
1235    }
1236
1237    /// Create ws-1 + tab-1 (which provisions a real LayoutState row) and
1238    /// return the tab id.
1239    fn ws_tab(s: &Store) -> String {
1240        apply_event_to_mstore(
1241            &Event::WorkspaceCreated {
1242                workspace_id: "ws-1".into(),
1243                name: "A".into(),
1244                version: 1,
1245            },
1246            s,
1247        )
1248        .unwrap();
1249        apply_event_to_mstore(
1250            &Event::TabCreated {
1251                workspace_id: "ws-1".into(),
1252                tab_id: "tab-1".into(),
1253                name: "T".into(),
1254                version: 2,
1255            },
1256            s,
1257        )
1258        .unwrap();
1259        "tab-1".to_string()
1260    }
1261
1262    fn layout_of(s: &Store, tab_id: &str) -> PersistedLayoutState {
1263        let tab = s.get::<Tab>(tab_id).unwrap().unwrap();
1264        s.get::<PersistedLayoutState>(&tab.layoutstate)
1265            .unwrap()
1266            .unwrap()
1267    }
1268
1269    #[test]
1270    fn layout_tree_replaced_persists_rootnode() {
1271        let s = store();
1272        let tab = ws_tab(&s);
1273        apply_event_to_mstore(
1274            &Event::LayoutTreeReplaced {
1275                tab_id: tab.clone(),
1276                new_tree: Some(leaf("n1", "b1")),
1277                correlation_id: "c1".into(),
1278                slices: None,
1279                version: 3,
1280            },
1281            &s,
1282        )
1283        .unwrap();
1284        let root = layout_of(&s, &tab).rootnode.expect("rootnode set");
1285        assert_eq!(root.id, "n1");
1286        assert_eq!(root.data.unwrap().block_id, "b1");
1287    }
1288
1289
1290
1291    // ── SPEC_864 site #6 — LayoutNodeDeleted persistence ────────────────────
1292
1293    #[test]
1294    fn layout_node_deleted_persists_new_tree() {
1295        let s = store();
1296        let tab = ws_tab(&s);
1297        apply_event_to_mstore(
1298            &Event::LayoutNodeDeleted {
1299                tab_id: tab.clone(),
1300                node_id: "gone".into(),
1301                new_tree: Some(leaf("survivor", "bs")),
1302                tree_cleared: false,
1303                was_focused: false,
1304                was_magnified: false,
1305                correlation_id: "c".into(),
1306                version: 3,
1307            },
1308            &s,
1309        )
1310        .unwrap();
1311        let root = layout_of(&s, &tab)
1312            .rootnode
1313            .expect("delete event persisted the resulting tree");
1314        assert_eq!(root.id, "survivor");
1315    }
1316
1317    #[test]
1318    fn layout_node_deleted_none_without_cleared_is_ignored() {
1319        // A version-skewed LayoutNodeDeleted (pre-site-#6 JSON: no
1320        // new_tree, tree_cleared defaults false) must NOT erase the
1321        // persisted layout.
1322        let s = store();
1323        let tab = ws_tab(&s);
1324        apply_event_to_mstore(
1325            &Event::LayoutTreeReplaced {
1326                tab_id: tab.clone(),
1327                new_tree: Some(leaf("keep", "bk")),
1328                correlation_id: "seed".into(),
1329                slices: None,
1330                version: 2,
1331            },
1332            &s,
1333        )
1334        .unwrap();
1335        apply_event_to_mstore(
1336            &Event::LayoutNodeDeleted {
1337                tab_id: tab.clone(),
1338                node_id: "x".into(),
1339                new_tree: None,
1340                tree_cleared: false, // skewed sender — not a real clear
1341                was_focused: false,
1342                was_magnified: false,
1343                correlation_id: "c".into(),
1344                version: 3,
1345            },
1346            &s,
1347        )
1348        .unwrap();
1349        let root = layout_of(&s, &tab)
1350            .rootnode
1351            .expect("tree preserved — skewed delete event must not clear");
1352        assert_eq!(root.id, "keep");
1353    }
1354
1355    #[test]
1356    fn layout_node_deleted_tree_cleared_erases_tree() {
1357        // Root-orphan delete: new_tree=None + tree_cleared=true is a REAL
1358        // clear (the deleted node was the root) and must wipe rootnode.
1359        let s = store();
1360        let tab = ws_tab(&s);
1361        apply_event_to_mstore(
1362            &Event::LayoutTreeReplaced {
1363                tab_id: tab.clone(),
1364                new_tree: Some(leaf("doomed-root", "bd")),
1365                correlation_id: "seed".into(),
1366                slices: None,
1367                version: 2,
1368            },
1369            &s,
1370        )
1371        .unwrap();
1372        apply_event_to_mstore(
1373            &Event::LayoutNodeDeleted {
1374                tab_id: tab.clone(),
1375                node_id: "doomed-root".into(),
1376                new_tree: None,
1377                tree_cleared: true,
1378                was_focused: true,
1379                was_magnified: false,
1380                correlation_id: "c".into(),
1381                version: 3,
1382            },
1383            &s,
1384        )
1385        .unwrap();
1386        assert!(
1387            layout_of(&s, &tab).rootnode.is_none(),
1388            "tree_cleared delete must wipe the persisted tree"
1389        );
1390    }
1391
1392    #[test]
1393    fn layout_node_deleted_persists_focus_and_magnify_clears() {
1394        let s = store();
1395        let tab = ws_tab(&s);
1396        let seed = |focused: &str, magnified: &str| Event::LayoutTreeReplaced {
1397            tab_id: tab.clone(),
1398            new_tree: Some(leaf("gone", "bg")),
1399            correlation_id: "seed".into(),
1400            slices: Some(slices(focused, magnified, None)),
1401            version: 2,
1402        };
1403        let delete = |was_focused: bool, was_magnified: bool| Event::LayoutNodeDeleted {
1404            tab_id: tab.clone(),
1405            node_id: "gone".into(),
1406            new_tree: Some(leaf("survivor", "bs")),
1407            tree_cleared: false,
1408            was_focused,
1409            was_magnified,
1410            correlation_id: "c".into(),
1411            version: 3,
1412        };
1413
1414        apply_event_to_mstore(&seed("gone", "gone"), &s).unwrap();
1415        apply_event_to_mstore(&delete(true, true), &s).unwrap();
1416        let layout = layout_of(&s, &tab);
1417        assert_eq!(layout.rootnode.unwrap().id, "survivor");
1418        assert_eq!(layout.focusednodeid, "", "reducer cleared focus; the row must too");
1419        assert_eq!(layout.magnifiednodeid, "", "reducer cleared magnify; the row must too");
1420
1421        // Ids the delete didn't touch stay as they were.
1422        apply_event_to_mstore(&seed("survivor", "survivor"), &s).unwrap();
1423        apply_event_to_mstore(&delete(false, false), &s).unwrap();
1424        let layout = layout_of(&s, &tab);
1425        assert_eq!(layout.focusednodeid, "survivor");
1426        assert_eq!(layout.magnifiednodeid, "survivor");
1427    }
1428
1429
1430    #[test]
1431    fn layout_tree_replaced_empty_clears_focus_magnify() {
1432        let s = store();
1433        let tab = ws_tab(&s);
1434        apply_event_to_mstore(
1435            &Event::LayoutTreeReplaced {
1436                tab_id: tab.clone(),
1437                new_tree: Some(leaf("n1", "b1")),
1438                correlation_id: "c".into(),
1439                slices: None,
1440                version: 3,
1441            },
1442            &s,
1443        )
1444        .unwrap();
1445        apply_event_to_mstore(
1446            &Event::FocusedNodeChanged {
1447                tab_id: tab.clone(),
1448                node_id: "n1".into(),
1449                version: 4,
1450            },
1451            &s,
1452        )
1453        .unwrap();
1454        apply_event_to_mstore(
1455            &Event::LayoutTreeReplaced {
1456                tab_id: tab.clone(),
1457                new_tree: None,
1458                correlation_id: "c".into(),
1459                slices: None,
1460                version: 5,
1461            },
1462            &s,
1463        )
1464        .unwrap();
1465        let layout = layout_of(&s, &tab);
1466        assert!(layout.rootnode.is_none());
1467        assert!(layout.focusednodeid.is_empty());
1468        assert!(layout.magnifiednodeid.is_empty());
1469    }
1470
1471    #[test]
1472    fn layout_tree_replaced_idempotent_no_version_churn() {
1473        let s = store();
1474        let tab = ws_tab(&s);
1475        let ev = Event::LayoutTreeReplaced {
1476            tab_id: tab.clone(),
1477            new_tree: Some(leaf("n1", "b1")),
1478            correlation_id: "c".into(),
1479            slices: None,
1480            version: 3,
1481        };
1482        apply_event_to_mstore(&ev, &s).unwrap();
1483        let v1 = layout_of(&s, &tab).version;
1484        apply_event_to_mstore(&ev, &s).unwrap();
1485        let v2 = layout_of(&s, &tab).version;
1486        assert_eq!(v1, v2, "idempotent re-apply must not bump version");
1487    }
1488
1489    // ── SPEC_864 Phase 2 — client slices on LayoutTreeReplaced ─────────
1490
1491    fn slices(
1492        focused: &str,
1493        magnified: &str,
1494        pending: Option<serde_json::Value>,
1495    ) -> agentmux_common::LayoutClientSlices {
1496        agentmux_common::LayoutClientSlices {
1497            focused_node_id: focused.into(),
1498            magnified_node_id: magnified.into(),
1499            pending_backend_actions: pending,
1500        }
1501    }
1502
1503    #[test]
1504    fn layout_tree_replaced_with_slices_writes_full_row() {
1505        let s = store();
1506        let tab = ws_tab(&s);
1507        apply_event_to_mstore(
1508            &Event::LayoutTreeReplaced {
1509                tab_id: tab.clone(),
1510                new_tree: Some(leaf("n1", "b1")),
1511                correlation_id: "c".into(),
1512                slices: Some(slices("n1", "n1", None)),
1513                version: 3,
1514            },
1515            &s,
1516        )
1517        .unwrap();
1518        let layout = layout_of(&s, &tab);
1519        assert_eq!(layout.rootnode.unwrap().id, "n1");
1520        assert_eq!(layout.focusednodeid, "n1");
1521        assert_eq!(layout.magnifiednodeid, "n1");
1522    }
1523
1524    #[test]
1525    fn layout_tree_replaced_slices_ack_clears_pending_actions() {
1526        // Pushing the row without pendingbackendactions is how the frontend
1527        // acks its processed backend-action queue — the slice-carrying write
1528        // must CLEAR the column, not leave it (else actions re-apply on the
1529        // next reload).
1530        let s = store();
1531        let tab = ws_tab(&s);
1532        // Seed a pending action directly (as queue_target_layout_* would).
1533        {
1534            let t = s.get::<Tab>(&tab).unwrap().unwrap();
1535            let mut layout = s
1536                .get::<PersistedLayoutState>(&t.layoutstate)
1537                .unwrap()
1538                .unwrap();
1539            layout.pendingbackendactions = Some(vec![LayoutActionData {
1540                actiontype: "insert".into(),
1541                actionid: "a1".into(),
1542                blockid: "b-new".into(),
1543                nodesize: None,
1544                nodesizefraction: None,
1545                indexarr: None,
1546                focused: true,
1547                magnified: false,
1548                ephemeral: false,
1549                targetblockid: String::new(),
1550                position: String::new(),
1551                ..Default::default()
1552            }]);
1553            s.update(&mut layout).unwrap();
1554        }
1555        apply_event_to_mstore(
1556            &Event::LayoutTreeReplaced {
1557                tab_id: tab.clone(),
1558                new_tree: Some(leaf("n1", "b1")),
1559                correlation_id: "c".into(),
1560                slices: Some(slices("n1", "", None)),
1561                version: 4,
1562            },
1563            &s,
1564        )
1565        .unwrap();
1566        assert!(
1567            layout_of(&s, &tab).pendingbackendactions.is_none(),
1568            "slice write with absent pending queue must clear the column (ack path)"
1569        );
1570    }
1571
1572    #[test]
1573    fn layout_tree_replaced_without_slices_leaves_client_columns_untouched() {
1574        // Tree-only events (pane-tab edits, saga callers) must not clobber
1575        // focus/magnify/pending — only a slice-carrying full-row
1576        // push owns those columns.
1577        let s = store();
1578        let tab = ws_tab(&s);
1579        apply_event_to_mstore(
1580            &Event::LayoutTreeReplaced {
1581                tab_id: tab.clone(),
1582                new_tree: Some(leaf("n1", "b1")),
1583                correlation_id: "seed".into(),
1584                slices: Some(slices(
1585                    "n1",
1586                    "",
1587                    Some(serde_json::json!([{
1588                        "actiontype": "insert",
1589                        "actionid": "a1",
1590                        "blockid": "b2",
1591                        "focused": false,
1592                        "magnified": false,
1593                        "ephemeral": false, "queuedat": agentmux_common::time::now_ms(),
1594                    }])),
1595                )),
1596                version: 3,
1597            },
1598            &s,
1599        )
1600        .unwrap();
1601        // Now a tree-only replace (slices: None) with a different tree.
1602        apply_event_to_mstore(
1603            &Event::LayoutTreeReplaced {
1604                tab_id: tab.clone(),
1605                new_tree: Some(leaf("n2", "b2")),
1606                correlation_id: "c".into(),
1607                slices: None,
1608                version: 4,
1609            },
1610            &s,
1611        )
1612        .unwrap();
1613        let layout = layout_of(&s, &tab);
1614        assert_eq!(layout.rootnode.unwrap().id, "n2", "tree replaced");
1615        assert_eq!(layout.focusednodeid, "n1", "focus untouched");
1616        assert!(
1617            layout.pendingbackendactions.is_some(),
1618            "pending queue untouched by tree-only write"
1619        );
1620    }
1621
1622    #[test]
1623    fn layout_events_silent_when_tab_missing() {
1624        let s = store();
1625        apply_event_to_mstore(
1626            &Event::LayoutTreeReplaced {
1627                tab_id: "ghost".into(),
1628                new_tree: Some(leaf("n", "b")),
1629                correlation_id: "c".into(),
1630                slices: None,
1631                version: 1,
1632            },
1633            &s,
1634        )
1635        .unwrap();
1636    }
1637
1638    #[test]
1639    fn workspace_deleted_cascades_pinned_tabs() {
1640        let s = store();
1641        // Build a workspace with a pinned tab via wcore (the bug
1642        // path: pinned tab created via wcore::create_tab_with_opts).
1643        let ws = wcore::create_workspace(&s, "Alpha").unwrap();
1644        let pinned_tab =
1645            wcore::create_tab_with_opts(&s, &ws.oid, "PinnedTab", true).unwrap();
1646        // Verify pinned tab is in pinnedtabids (sanity).
1647        let ws_loaded = s.get::<Workspace>(&ws.oid).unwrap().unwrap();
1648        assert!(ws_loaded.pinnedtabids.contains(&pinned_tab.oid));
1649        // Delete via the subscriber's WorkspaceDeleted handler.
1650        apply_event_to_mstore(
1651            &Event::WorkspaceDeleted {
1652                workspace_id: ws.oid.clone(),
1653                block_ids: Vec::new(),
1654                version: 1,
1655            },
1656            &s,
1657        )
1658        .unwrap();
1659        // codex P1 #614: pinned tab must be cascade-deleted, not
1660        // orphaned.
1661        assert!(s.get::<Tab>(&pinned_tab.oid).unwrap().is_none());
1662        assert!(s.get::<Workspace>(&ws.oid).unwrap().is_none());
1663    }
1664
1665    #[test]
1666    fn block_created_links_into_tab() {
1667        let s = store();
1668        apply_event_to_mstore(
1669            &Event::WorkspaceCreated {
1670                workspace_id: "ws-1".into(),
1671                name: "Alpha".into(),
1672                version: 1,
1673            },
1674            &s,
1675        )
1676        .unwrap();
1677        apply_event_to_mstore(
1678            &Event::TabCreated {
1679                workspace_id: "ws-1".into(),
1680                tab_id: "tab-1".into(),
1681                name: "Tab".into(),
1682                version: 2,
1683            },
1684            &s,
1685        )
1686        .unwrap();
1687        apply_event_to_mstore(
1688            &Event::BlockCreated { tab_id: "tab-1".into(), block_id: "block-1".into(), meta: serde_json::Value::Null, version: 3 },
1689            &s,
1690        )
1691        .unwrap();
1692        let tab = s.get::<Tab>("tab-1").unwrap().unwrap();
1693        assert_eq!(tab.blockids, vec!["block-1".to_string()]);
1694        let block = s.get::<Block>("block-1").unwrap().unwrap();
1695        assert_eq!(block.parentoref, "tab:tab-1");
1696    }
1697
1698    #[test]
1699    fn block_deleted_unlinks_from_tab() {
1700        let s = store();
1701        apply_event_to_mstore(
1702            &Event::WorkspaceCreated {
1703                workspace_id: "ws-1".into(),
1704                name: "Alpha".into(),
1705                version: 1,
1706            },
1707            &s,
1708        )
1709        .unwrap();
1710        apply_event_to_mstore(
1711            &Event::TabCreated {
1712                workspace_id: "ws-1".into(),
1713                tab_id: "tab-1".into(),
1714                name: "Tab".into(),
1715                version: 2,
1716            },
1717            &s,
1718        )
1719        .unwrap();
1720        apply_event_to_mstore(
1721            &Event::BlockCreated { tab_id: "tab-1".into(), block_id: "block-1".into(), meta: serde_json::Value::Null, version: 3 },
1722            &s,
1723        )
1724        .unwrap();
1725        apply_event_to_mstore(
1726            &Event::BlockDeleted {
1727                tab_id: "tab-1".into(),
1728                block_id: "block-1".into(),
1729                version: 4,
1730            },
1731            &s,
1732        )
1733        .unwrap();
1734        assert!(s.get::<Block>("block-1").unwrap().is_none());
1735        let tab = s.get::<Tab>("tab-1").unwrap().unwrap();
1736        assert!(tab.blockids.is_empty());
1737    }
1738
1739    /// codex P1 #620: a workspace with legacy `pinnedtabids` rows must
1740    /// have those drained the first time `TabsReorderedBulk` writes
1741    /// the workspace; otherwise the UI's
1742    /// `[...pinnedtabids, ...tabids]` combine duplicates the pinned
1743    /// tab IDs once they have been merged into the reducer's
1744    /// `tab_ids` at bootstrap.
1745    #[test]
1746    fn tabs_reordered_bulk_drains_legacy_pinned_tabids() {
1747        let s = store();
1748        let ws = wcore::create_workspace(&s, "Alpha").unwrap();
1749        let pinned_tab =
1750            wcore::create_tab_with_opts(&s, &ws.oid, "Pinned", true).unwrap();
1751        let regular_tab =
1752            wcore::create_tab_with_opts(&s, &ws.oid, "Regular", false).unwrap();
1753        // Sanity: pinned tab is in `pinnedtabids` on disk.
1754        let ws_before = s.get::<Workspace>(&ws.oid).unwrap().unwrap();
1755        assert!(ws_before.pinnedtabids.contains(&pinned_tab.oid));
1756
1757        // Reducer-driven bulk reorder treating the pinned tab as a
1758        // regular tab (mirrors what bootstrap-merge produces).
1759        apply_event_to_mstore(
1760            &Event::TabsReorderedBulk {
1761                workspace_id: ws.oid.clone(),
1762                tab_ids: vec![pinned_tab.oid.clone(), regular_tab.oid.clone()],
1763                version: ws_before.version as u64 + 1,
1764            },
1765            &s,
1766        )
1767        .unwrap();
1768        let ws_after = s.get::<Workspace>(&ws.oid).unwrap().unwrap();
1769        assert_eq!(
1770            ws_after.tabids,
1771            vec![pinned_tab.oid.clone(), regular_tab.oid.clone()]
1772        );
1773        assert!(
1774            ws_after.pinnedtabids.is_empty(),
1775            "pinnedtabids must be drained, was {:?}",
1776            ws_after.pinnedtabids
1777        );
1778    }
1779
1780    /// codex P2 #620: `merge_meta_patch` must honour the existing
1781    /// `section:*` clear-prefix semantics so `UpdateObjectMeta`
1782    /// behaviour stays the same after the reducer migration.
1783    #[test]
1784    fn meta_updated_clears_section_prefix() {
1785        let s = store();
1786        apply_event_to_mstore(
1787            &Event::TabCreated {
1788                workspace_id: "ws-1".into(),
1789                tab_id: "tab-1".into(),
1790                name: "Tab".into(),
1791                version: 1,
1792            },
1793            &s,
1794        )
1795        .unwrap();
1796        apply_event_to_mstore(
1797            &Event::WorkspaceCreated {
1798                workspace_id: "ws-1".into(),
1799                name: "Alpha".into(),
1800                version: 1,
1801            },
1802            &s,
1803        )
1804        .unwrap();
1805        // Seed the tab with grouped meta entries.
1806        let mut tab = s.get::<Tab>("tab-1").unwrap().unwrap();
1807        tab.meta
1808            .insert("term:fontsize".into(), serde_json::json!(14));
1809        tab.meta
1810            .insert("term:theme".into(), serde_json::json!("solarized"));
1811        tab.meta.insert("name".into(), serde_json::json!("keep"));
1812        s.update(&mut tab).unwrap();
1813        // Patch with `term:*` clear plus a single replacement key.
1814        apply_event_to_mstore(
1815            &Event::TabMetaUpdated {
1816                tab_id: "tab-1".into(),
1817                meta_patch: serde_json::json!({
1818                    "term:*": true,
1819                    "term:fontsize": 18,
1820                }),
1821                version: 2,
1822            },
1823            &s,
1824        )
1825        .unwrap();
1826        let after = s.get::<Tab>("tab-1").unwrap().unwrap();
1827        assert!(!after.meta.contains_key("term:theme"),
1828            "term:theme should be cleared by `term:*` patch");
1829        assert_eq!(
1830            after.meta.get("term:fontsize"),
1831            Some(&serde_json::json!(18)),
1832            "term:fontsize replacement must take effect after the section clear"
1833        );
1834        assert_eq!(after.meta.get("name"), Some(&serde_json::json!("keep")));
1835    }
1836
1837    // ---- Phase E.5.5 — TabMoved / BlockMoved subscriber tests ----
1838
1839    #[test]
1840    fn tab_moved_cross_workspace_rewrites_both_tabids() {
1841        let s = store();
1842        // Two workspaces, each pre-existing in SQLite.
1843        for (id, name) in &[("src-ws", "Src"), ("dst-ws", "Dst")] {
1844            apply_event_to_mstore(
1845                &Event::WorkspaceCreated {
1846                    workspace_id: id.to_string(),
1847                    name: name.to_string(),
1848                    version: 1,
1849                },
1850                &s,
1851            )
1852            .unwrap();
1853        }
1854        // Tab in src.
1855        apply_event_to_mstore(
1856            &Event::TabCreated {
1857                workspace_id: "src-ws".into(),
1858                tab_id: "tab-1".into(),
1859                name: "T".into(),
1860                version: 2,
1861            },
1862            &s,
1863        )
1864        .unwrap();
1865        let src = s.get::<Workspace>("src-ws").unwrap().unwrap();
1866        assert_eq!(src.tabids, vec!["tab-1".to_string()]);
1867
1868        // Move it. Set dst active to the moved tab (per reducer
1869        // semantics + codex P2 #621).
1870        apply_event_to_mstore(
1871            &Event::TabMoved {
1872                tab_id: "tab-1".into(),
1873                src_workspace_id: "src-ws".into(),
1874                dst_workspace_id: "dst-ws".into(),
1875                dst_index: 0,
1876                new_src_active_tab_id: None,
1877                new_dst_active_tab_id: Some("tab-1".into()),
1878                version: 3,
1879            },
1880            &s,
1881        )
1882        .unwrap();
1883        let src = s.get::<Workspace>("src-ws").unwrap().unwrap();
1884        let dst = s.get::<Workspace>("dst-ws").unwrap().unwrap();
1885        assert!(src.tabids.is_empty());
1886        assert_eq!(src.activetabid, "");
1887        assert_eq!(dst.tabids, vec!["tab-1".to_string()]);
1888        assert_eq!(dst.activetabid, "tab-1", "dst active should be the moved tab");
1889    }
1890
1891    #[test]
1892    fn tab_moved_idempotent_on_re_delivery() {
1893        let s = store();
1894        for (id, name) in &[("src-ws", "Src"), ("dst-ws", "Dst")] {
1895            apply_event_to_mstore(
1896                &Event::WorkspaceCreated {
1897                    workspace_id: id.to_string(),
1898                    name: name.to_string(),
1899                    version: 1,
1900                },
1901                &s,
1902            )
1903            .unwrap();
1904        }
1905        apply_event_to_mstore(
1906            &Event::TabCreated {
1907                workspace_id: "src-ws".into(),
1908                tab_id: "tab-1".into(),
1909                name: "T".into(),
1910                version: 2,
1911            },
1912            &s,
1913        )
1914        .unwrap();
1915        let ev = Event::TabMoved {
1916            tab_id: "tab-1".into(),
1917            src_workspace_id: "src-ws".into(),
1918            dst_workspace_id: "dst-ws".into(),
1919            dst_index: 0,
1920            new_src_active_tab_id: None,
1921            new_dst_active_tab_id: Some("tab-1".into()),
1922            version: 3,
1923        };
1924        apply_event_to_mstore(&ev, &s).unwrap();
1925        // Re-deliver the same event.
1926        apply_event_to_mstore(&ev, &s).unwrap();
1927        let dst = s.get::<Workspace>("dst-ws").unwrap().unwrap();
1928        // Still exactly one entry — no duplicate insert.
1929        assert_eq!(dst.tabids, vec!["tab-1".to_string()]);
1930    }
1931
1932    #[test]
1933    fn block_moved_cross_tab_updates_block_lists_and_parent() {
1934        let s = store();
1935        let ws = wcore::create_workspace(&s, "W").unwrap();
1936        let src_tab = wcore::create_tab_with_opts(&s, &ws.oid, "src", false).unwrap();
1937        let dst_tab = wcore::create_tab_with_opts(&s, &ws.oid, "dst", false).unwrap();
1938        // Create a block in src via the subscriber path.
1939        apply_event_to_mstore(
1940            &Event::BlockCreated {
1941                tab_id: src_tab.oid.clone(),
1942                block_id: "blk-1".into(),
1943                meta: serde_json::Value::Null,
1944                version: 1,
1945            },
1946            &s,
1947        )
1948        .unwrap();
1949        let src_before = s.get::<Tab>(&src_tab.oid).unwrap().unwrap();
1950        assert_eq!(src_before.blockids, vec!["blk-1".to_string()]);
1951
1952        apply_event_to_mstore(
1953            &Event::BlockMoved {
1954                block_id: "blk-1".into(),
1955                src_tab_id: src_tab.oid.clone(),
1956                dst_tab_id: dst_tab.oid.clone(),
1957                dst_index: 0,
1958                version: 2,
1959            },
1960            &s,
1961        )
1962        .unwrap();
1963        let src_after = s.get::<Tab>(&src_tab.oid).unwrap().unwrap();
1964        let dst_after = s.get::<Tab>(&dst_tab.oid).unwrap().unwrap();
1965        let block = s.get::<Block>("blk-1").unwrap().unwrap();
1966        assert!(src_after.blockids.is_empty());
1967        assert_eq!(dst_after.blockids, vec!["blk-1".to_string()]);
1968        assert_eq!(block.parentoref, format!("tab:{}", dst_tab.oid));
1969    }
1970
1971    #[test]
1972    fn block_moved_intra_tab_repositions() {
1973        let s = store();
1974        let ws = wcore::create_workspace(&s, "W").unwrap();
1975        let tab = wcore::create_tab_with_opts(&s, &ws.oid, "t", false).unwrap();
1976        for id in &["b1", "b2", "b3"] {
1977            apply_event_to_mstore(
1978                &Event::BlockCreated {
1979                    tab_id: tab.oid.clone(),
1980                    block_id: id.to_string(),
1981                    meta: serde_json::Value::Null,
1982                    version: 1,
1983                },
1984                &s,
1985            )
1986            .unwrap();
1987        }
1988        // Move b1 to position 2 (post-removal end).
1989        apply_event_to_mstore(
1990            &Event::BlockMoved {
1991                block_id: "b1".into(),
1992                src_tab_id: tab.oid.clone(),
1993                dst_tab_id: tab.oid.clone(),
1994                dst_index: 2,
1995                version: 2,
1996            },
1997            &s,
1998        )
1999        .unwrap();
2000        let tab_after = s.get::<Tab>(&tab.oid).unwrap().unwrap();
2001        assert_eq!(tab_after.blockids, vec!["b2".to_string(), "b3".to_string(), "b1".to_string()]);
2002    }
2003
2004    // ── SPEC_864 Phase 4 — pendingbackendactions APPEND semantics ──────────
2005
2006    fn action(id: &str, block: &str) -> LayoutActionData {
2007        LayoutActionData {
2008            actiontype: "insert".into(),
2009            actionid: id.into(),
2010            blockid: block.into(),
2011            nodesize: None,
2012            nodesizefraction: None,
2013            indexarr: None,
2014            focused: true,
2015            magnified: false,
2016            ephemeral: false,
2017            targetblockid: String::new(),
2018            position: String::new(),
2019            ..Default::default()
2020        }
2021    }
2022
2023    #[test]
2024    fn layout_backend_actions_queued_appends_not_replaces() {
2025        let s = store();
2026        let tab = ws_tab(&s);
2027        apply_event_to_mstore(
2028            &Event::LayoutBackendActionsQueued {
2029                tab_id: tab.clone(),
2030                actions: serde_json::to_value(vec![action("a1", "b1")]).unwrap(),
2031                correlation_id: "c1".into(),
2032                version: 3,
2033            },
2034            &s,
2035        )
2036        .unwrap();
2037        apply_event_to_mstore(
2038            &Event::LayoutBackendActionsQueued {
2039                tab_id: tab.clone(),
2040                actions: serde_json::to_value(vec![action("a2", "b2")]).unwrap(),
2041                correlation_id: "c2".into(),
2042                version: 4,
2043            },
2044            &s,
2045        )
2046        .unwrap();
2047        let pending = layout_of(&s, &tab).pendingbackendactions.unwrap();
2048        assert_eq!(pending.len(), 2, "second event must APPEND, not replace");
2049        assert_eq!(pending[0].actionid, "a1");
2050        assert_eq!(pending[1].actionid, "a2");
2051    }
2052
2053    #[test]
2054    fn layout_backend_actions_queued_dedupes_on_double_apply() {
2055        // Same event applied twice (sync dispatch + broadcast redelivery)
2056        // must not duplicate the queued action.
2057        let s = store();
2058        let tab = ws_tab(&s);
2059        let ev = Event::LayoutBackendActionsQueued {
2060            tab_id: tab.clone(),
2061            actions: serde_json::to_value(vec![action("a1", "b1")]).unwrap(),
2062            correlation_id: "c1".into(),
2063            version: 3,
2064        };
2065        apply_event_to_mstore(&ev, &s).unwrap();
2066        apply_event_to_mstore(&ev, &s).unwrap();
2067        let pending = layout_of(&s, &tab).pendingbackendactions.unwrap();
2068        assert_eq!(pending.len(), 1, "double-apply must not duplicate by actionid");
2069    }
2070
2071    #[test]
2072    fn layout_backend_actions_queued_silent_when_tab_missing() {
2073        let s = store();
2074        apply_event_to_mstore(
2075            &Event::LayoutBackendActionsQueued {
2076                tab_id: "ghost".into(),
2077                actions: serde_json::to_value(vec![action("a1", "b1")]).unwrap(),
2078                correlation_id: "c1".into(),
2079                version: 1,
2080            },
2081            &s,
2082        )
2083        .unwrap();
2084    }
2085}