Skip to main content

agentmux_srv/bootstrap/
store_attach.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of [`open_stores_and_migrate`](super::open_stores_and_migrate) that attach the
5//! registries and open each store, one function each, in the order they ran. Moved out of that
6//! function without a change in behaviour.
7
8use super::stores::restore_repaired_history;
9use super::*;
10use crate::backend::memory::global_record::Recorder;
11
12/// Attaches the cross-version named-agent registry, and the catch-up pass over its records.
13pub(super) fn attach_agent_registry(mstore_raw: &Store) {
14    // Attach the cross-version named-agent registry. Falls back to a
15    // disabled registry when the shared home can't be resolved (CI,
16    // unusual envs); mutations still hit SQLite, just don't mirror.
17    // See docs/specs/SPEC_SHARED_AGENT_REGISTRY_2026_05_12.md.
18    if let Some(root) = registry::resolve_shared_registry_dir() {
19        match crate::boot_timing::time("open_agent_registry", || {
20            registry::Registry::open(root.clone())
21        }) {
22            Ok(reg) => {
23                tracing::info!(root = %root.display(), "registry: shared agent registry attached");
24                // Best-effort catch-up pass, run every startup: fills
25                // session_id for any agent record that still lacks one, e.g.
26                // one named after the one-shot migration that once did this
27                // ran. Idempotent — skips records that already carry
28                // a non-empty session_id. Without this, an agent created
29                // after the migration ran would never get a resumable
30                // session_id in the registry, so a cross-tab/cross-restart
31                // open would silently orphan its conversation (the still-open
32                // half of docs/retro/retro-cross-channel-conversation-continuity-regression-2026-06-16.md).
33                if let Some(shared_dir) = root.parent().and_then(|p| p.parent()) {
34                    let filled = crate::boot_timing::time("registry_session_backfill", || {
35                        backend::session_backfill::backfill_session_ids(&reg, shared_dir)
36                    });
37                    if filled > 0 {
38                        tracing::info!(filled, "registry: backfilled session_id for cross-channel resume (startup pass)");
39                    }
40                }
41                mstore_raw.set_registry(Arc::new(reg));
42                if let Some(base) = std::env::var_os("AGENTMUX_AGENTS_DIR") {
43                    if !base.is_empty() {
44                        mstore_raw.set_registry_agents_base(std::path::PathBuf::from(base));
45                    }
46                }
47            }
48            Err(e) => tracing::warn!(
49                root = %root.display(),
50                error = %e,
51                "registry: failed to open shared agent registry — SQLite remains authoritative"
52            ),
53        }
54    } else {
55        tracing::warn!("registry: could not resolve shared registry dir — mirror disabled");
56    }
57}
58
59/// Attaches the global agent-definition store and returns the ids of the active user agents, for the
60/// transcript backfill.
61pub(super) fn attach_definition_store(mstore_raw: &Store) -> Vec<String> {
62    // Attach the GLOBAL (cross-channel) agent-definition store. Sibling of the
63    // instance registry above — since P0.3b both live under ~/.agentmux/shared/
64    // (definitions/ and registry/), so user agents created in one channel are
65    // visible in every channel. Best-effort: disabled when the shared dir can't
66    // be resolved. See SPEC_CROSS_CHANNEL_AGENT_PERSISTENCE_2026-06-13.md (P0.2/P0.3).
67    // Captured for the transcript backfill below (after the global transcript
68    // store opens): the user-agent definition ids to seed conversations for.
69    let mut backfill_def_ids: Vec<String> = Vec::new();
70    if let Some(def_dir) = registry::resolve_shared_definitions_dir() {
71        match crate::boot_timing::time("open_definition_store", || {
72            registry::DefinitionStore::open(def_dir.clone())
73        }) {
74            Ok(def_store) => {
75                // Capture user-agent ids for the transcript backfill (below).
76                backfill_def_ids = crate::boot_timing::time("def_store_list_active", || {
77                    def_store
78                        .list_active()
79                        .map(|v| v.into_iter().map(|r| r.data.id).collect())
80                        .unwrap_or_default()
81                });
82                mstore_raw.set_def_registry(Arc::new(def_store));
83                tracing::info!(dir = %def_dir.display(), "def registry: global definition store attached");
84                // New slugs are checked against every channel's and version's
85                // objects.db too, the root the fork slug migration reads.
86                match backend::slug_migration::Home::from_env() {
87                    Ok(home) => mstore_raw.set_slug_home(home),
88                    Err(e) => {
89                        tracing::warn!(error = %e, "agent slugs: other channels' agents can't be checked; only the shared definitions are")
90                    }
91                }
92                // This channel's copy of every agent's former slugs, in step
93                // with the shared records (SPEC_FORK_SLUG_MIGRATION_2026_10_22.md Phase 1).
94                if let Err(e) = mstore_raw.agent_former_slugs_sync_from_shared() {
95                    tracing::warn!(error = %e, "former slugs: not copied from the shared definitions");
96                }
97            }
98            Err(e) => tracing::warn!(
99                dir = %def_dir.display(),
100                error = %e,
101                "def registry: failed to open global definition store — definitions stay channel-local"
102            ),
103        }
104    } else {
105        tracing::warn!(
106            "def registry: could not resolve shared definitions dir — global definitions disabled"
107        );
108    }
109    backfill_def_ids
110}
111
112/// Reconciles the two host-global registries against each other.
113pub(super) fn reconcile_registries(mstore_raw: &Store) {
114    // Both host-global trees are attached now, so they can be reconciled
115    // against each other. Best-effort catch-up pass run every startup, same
116    // shape as the session_id backfill above: drops instance records whose
117    // definition is tombstoned, which the picker would otherwise keep
118    // rendering as an iconless "(missing definition)" row — a deleted agent
119    // whose card never went away. New deletes sweep the registry themselves
120    // (`Store::agent_def_delete`); this is for the orphans already on disk.
121    if let (Some(reg), Some(defs)) = (
122        mstore_raw.shared_agent_registry(),
123        mstore_raw.shared_def_registry(),
124    ) {
125        let pruned = backend::registry_reconcile::prune_tombstoned_instance_records(&reg, &defs);
126        if pruned > 0 {
127            tracing::info!(
128                pruned,
129                "registry: dropped instance records for deleted agents (startup pass)"
130            );
131        }
132    }
133}
134
135/// Attaches the agent token index and the channel-wide WAN identity store.
136pub(super) fn attach_token_index_and_wan_identity(mstore_raw: &Store) {
137    // Identity M4a: token → UID for request attribution, on this channel's
138    // object store only (spec §6.5.3).
139    match crate::boot_timing::time("attach_token_index", || mstore_raw.attach_token_index()) {
140        Ok(_) => tracing::info!("identity: agent token index attached"),
141        Err(e) => {
142            tracing::warn!(error = %e, "identity: agent token index unavailable — requests stay unattributed")
143        }
144    }
145    // W3-S (SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md §2.2): the channel-wide
146    // WAN identity store. Opened and its instance minted here, once, so srv
147    // signs every WAN jekt as the same instance. Best-effort and never
148    // redirected: if the file can't be opened or the instance can't be
149    // minted, WAN signing is simply off for this process, and its WAN jekts
150    // go unsigned (`TRUST=network-claimed` at the receiver).
151    match backend::storage::wan_identity::resolve_wan_identity_path() {
152        Some(path) => match crate::boot_timing::time("open_wan_db", || {
153            backend::storage::wan_identity::WanIdentityStore::open(&path)
154        })
155        .and_then(|store| {
156            let instance =
157                store.instance_ensure(&crate::backend::reactive::registry::local_host_label())?;
158            Ok((store, instance))
159        }) {
160            Ok((store, instance)) => {
161                tracing::info!(
162                    path = %path.display(),
163                    instance = %instance.instance_id,
164                    host_hint = %instance.host_hint,
165                    "wan identity: store attached"
166                );
167                let store = Arc::new(store);
168                backend::storage::wan_identity::install_global(store.clone());
169                mstore_raw.set_wan_identity(store);
170            }
171            Err(e) => tracing::warn!(
172                path = %path.display(),
173                error = %e,
174                "wan identity: store unavailable — WAN jekt signing is off for this process"
175            ),
176        },
177        None => tracing::warn!(
178            "wan identity: channel dir unresolved — WAN jekt signing is off for this process"
179        ),
180    }
181}
182
183/// Opens this channel's file store.
184pub(super) fn open_filestore(db_dir: &std::path::Path) -> Arc<FileStore> {
185    Arc::new(
186        crate::boot_timing::time("open_filestore_db", || {
187            FileStore::open(&db_dir.join("filestore.db"))
188        })
189        .unwrap_or_else(|e| {
190            tracing::error!("Failed to open file store: {}", e);
191            std::process::exit(1);
192        }),
193    )
194}
195
196/// Opens the global transcript store; `None` falls back to the per-channel store.
197pub(super) fn open_global_transcripts() -> Option<Arc<FileStore>> {
198    // GLOBAL transcript store — backs the `agent:<defId>:current` zone so a
199    // conversation loads when the agent is opened from any build/channel
200    // (finishes the cross-channel arc #1387–#1396). A second FileStore over an
201    // independent SQLite/WAL file is safe alongside the per-channel one. This is
202    // best-effort: if the shared root can't be resolved, or the store can't be
203    // opened, we log and fall back to the per-channel `filestore` (global
204    // transcripts disabled) — never fatal, unlike the per-channel store above.
205    // See `docs/analysis/ANALYSIS_CROSS_CHANNEL_CONVERSATION_HISTORY_2026_06_14.md`.
206    match registry::resolve_shared_transcripts_dir() {
207        Some(dir) => {
208            if let Err(e) = std::fs::create_dir_all(&dir) {
209                tracing::warn!(dir = %dir.display(), error = %e, "global transcripts: failed to create dir — disabled, falling back to per-channel store");
210                None
211            } else {
212                let path = dir.join("filestore.db");
213                // The one copy of a conversation: only its owner may open the folder and what is in it, as it was
214                // left by an earlier version too (SPEC_HISTORY_COMPACT_FORM_ONLY §7). Again after the open below,
215                // for the log files the database makes.
216                crate::backend::storage::filestore::at_rest::secure_at_start(&dir);
217                // Give freed space back, if the Storage view asked and no other srv
218                // runs (SPEC_HISTORY_STORE_RECLAIM_SPACE_2026_10_23 §4), then hold the
219                // gate shared while opening, so an srv starting meanwhile waits. The
220                // rewrite takes longer than a supervisor's ESTART wait (about 40 s for
221                // 3.6 GB), so it says so first, as a migration does, and the splash
222                // shows it as a step.
223                {
224                    use crate::backend::storage::filestore::{reclaim, repair};
225                    reclaim::recover_if_alone(&reclaim::Paths::for_db(&path));
226                    // A store the last run found damaged is rebuilt first, from what reads, if no
227                    // other srv runs; the damaged file is kept beside it.
228                    if repair::needs_start(&path) {
229                        eprintln!(
230                            "{}",
231                            agentmux_common::srv_stderr::migrating_line("repairing-history", 1)
232                        );
233                        crate::boot_timing::step(
234                            "repair-history",
235                            "Repairing the history database",
236                            || {
237                                repair::run_at_start(
238                                    &path,
239                                    crate::backend::transcript::framer::other_srv,
240                                    restore_repaired_history,
241                                    agentmux_common::time::now_ms_u64(),
242                                )
243                            },
244                        );
245                    }
246                    if reclaim::requested(&path) {
247                        eprintln!(
248                            "{}",
249                            agentmux_common::srv_stderr::migrating_line("reclaiming-history", 1)
250                        );
251                        crate::boot_timing::step(
252                            "reclaim-history",
253                            "Giving back history disk space",
254                            || {
255                                reclaim::run_at_start(
256                                    &path,
257                                    crate::backend::transcript::framer::other_srv,
258                                    agentmux_common::time::now_ms_u64(),
259                                )
260                            },
261                        );
262                    }
263                }
264                let gate = crate::backend::storage::filestore::reclaim::gate_shared(&path);
265                let opened = crate::boot_timing::time("open_transcripts_db", || {
266                    FileStore::open_global_transcripts(&path)
267                        .inspect_err(super::shared_guard::note_open_failure)
268                });
269                drop(gate);
270                match opened {
271                    Ok(fs) => {
272                        crate::backend::storage::filestore::at_rest::secure_at_start(&dir);
273                        tracing::info!(dir = %dir.display(), "global transcripts: store attached");
274                        // This srv reads compressed frames (transcript::framer).
275                        crate::backend::transcript::framer::mark_reader(&dir);
276                        ask_for_the_rewrite_if_wanted(&path, &fs);
277                        Some(Arc::new(fs))
278                    }
279                    Err(e) => {
280                        tracing::warn!(dir = %dir.display(), error = %e, "global transcripts: failed to open store — disabled, falling back to per-channel store");
281                        None
282                    }
283                }
284            }
285        }
286        None => {
287            tracing::warn!("global transcripts: could not resolve shared transcripts dir — disabled, falling back to per-channel store");
288            None
289        }
290    }
291}
292
293/// Opens the global shared store; `None` when it cannot be resolved or opened.
294pub(super) fn open_shared_store() -> Option<Arc<Store>> {
295    // GLOBAL shared store — accounts, bundles, drone
296    // definitions, MuxBus credentials. Best-effort: disabled when the shared
297    // root can't be resolved. Falls back to mstore so behavior is unchanged
298    // from today. See SPEC_GLOBAL_IDENTITY_MEMORY_DRONE_2026_06_24.md.
299    match registry::resolve_shared_store_path() {
300        Some(path) => {
301            // Ensure the parent dir (shared/) exists before opening.
302            let parent = path.parent().unwrap_or(path.as_path());
303            if let Err(e) = std::fs::create_dir_all(parent) {
304                tracing::warn!(path = %path.display(), error = %e, "shared store: failed to create dir — disabled");
305                None
306            } else {
307                match crate::boot_timing::time("open_shared_store", || {
308                    Store::open_shared(&path).inspect_err(super::shared_guard::note_open_failure)
309                }) {
310                    Ok(s) => {
311                        let reason = agentmux_common::isolated_auth_reason();
312                        if reason.is_isolated() {
313                            tracing::info!(path = %path.display(), reason = reason.as_str(), "shared store: attached (ISOLATED — channel-scoped)");
314                        } else {
315                            tracing::info!(path = %path.display(), reason = reason.as_str(), "shared store: attached");
316                        }
317                        Some(Arc::new(s))
318                    }
319                    Err(e) => {
320                        tracing::warn!(path = %path.display(), error = %e, "shared store: failed to open — identity/memory/drone/muxbus stay per-channel");
321                        None
322                    }
323                }
324            }
325        }
326        None => {
327            tracing::warn!("shared store: could not resolve shared store path — disabled");
328            None
329        }
330    }
331}
332
333/// Chooses where identity, memory, drone and muxbus operations go.
334pub(super) fn pick_id_store(shared_store: &Option<Arc<Store>>, mstore: &Arc<Store>) -> Arc<Store> {
335    // id_store: routes identity/memory/drone/muxbus ops to the shared store when
336    // available AND the shared-store backfill migration has been applied.
337    // Checking the specific migration (not a coarse migration_ok flag) avoids
338    // a split-brain when 0011 succeeded but a later migration failed: the shared
339    // store is already backfilled, so using per-channel would strand writes made
340    // this session once the later migration succeeds on next boot.
341    match shared_store.as_ref() {
342        Some(ss) if ss.migration_is_applied("0011_shared_store_backfill") => ss.clone(),
343        Some(_) => {
344            tracing::warn!(
345                "id_store: 0011_shared_store_backfill not yet applied — using per-channel store"
346            );
347            mstore.clone()
348        }
349        None => mstore.clone(),
350    }
351}
352
353/// Carries what earlier per-channel builds kept to themselves into the shared store.
354pub(super) fn adopt_earlier_auth(shared_store: &Option<Arc<Store>>, id_store: &Arc<Store>) {
355    // Shared auth: carry what earlier per-channel (isolated) builds kept to
356    // themselves into the shared store, once and without touching the sources
357    // (SPEC_SHARED_AUTH_ACROSS_CHANNELS_2026_10_03.md). Only when this channel
358    // really runs on the shared store; an isolated one never reads another's.
359    if !agentmux_common::isolated_auth_enabled() {
360        if let (Some(ss), Some(path)) =
361            (shared_store.as_ref(), registry::resolve_shared_store_path())
362        {
363            if Arc::ptr_eq(ss, id_store) {
364                crate::boot_timing::time("adoption_scan", || {
365                    crate::adoption::run_at_boot(ss, &path)
366                });
367            }
368        }
369    }
370}
371
372/// Opens the permanently-global identity store; falls back to the per-channel store.
373pub(super) fn open_identity_store(mstore: &Arc<Store>) -> Arc<Store> {
374    // Permanently-global identity store (agent→account links, memory
375    // bundles, drone definitions, muxbus/agent M2M credentials, native
376    // memory, cron jobs) — see
377    // docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md. Deliberately NOT
378    // gated by isolated_auth_enabled() at all, unlike shared_store above:
379    // none of this store's tables have a legitimate per-channel-isolation
380    // use case. Best-effort, same fallback-to-mstore terms as id_store —
381    // a resolution/open failure degrades to today's per-channel behavior
382    // rather than being fatal.
383    match registry::resolve_identity_store_path() {
384        Some(path) => {
385            let parent = path.parent().unwrap_or(path.as_path());
386            if let Err(e) = std::fs::create_dir_all(parent) {
387                tracing::warn!(path = %path.display(), error = %e, "identity store: failed to create dir — falling back to per-channel store");
388                mstore.clone()
389            } else {
390                match crate::boot_timing::time("open_identity_store", || {
391                    Store::open_identity_store(&path)
392                        .inspect_err(super::shared_guard::note_open_failure)
393                }) {
394                    Ok(s) => {
395                        tracing::info!(path = %path.display(), "identity store: attached (always global)");
396                        // An agent's LAN signing key is the host's, not this channel's: a channel switch
397                        // must not change the key LAN peers have pinned.
398                        match backend::storage::host_lan_keys::HostLanKeys::open(&path) {
399                            Ok(keys) => mstore.set_host_lan_keys(Arc::new(keys)),
400                            Err(e) => {
401                                tracing::warn!(error = %e, "LAN keys: the host key table did not open, this channel keeps its own keys")
402                            }
403                        }
404                        Arc::new(s)
405                    }
406                    Err(e) => {
407                        tracing::warn!(path = %path.display(), error = %e, "identity store: failed to open — falling back to per-channel store");
408                        mstore.clone()
409                    }
410                }
411            }
412        }
413        None => {
414            tracing::warn!(
415                "identity store: could not resolve path — falling back to per-channel store"
416            );
417            mstore.clone()
418        }
419    }
420}
421
422/// Attaches Global Memory's record and heals the global transcript snapshots; returns the recorder.
423pub(super) fn attach_global_memory(
424    id_store: &Arc<Store>,
425    global_transcript_store: &Option<Arc<FileStore>>,
426    backfill_def_ids: &[String],
427) -> Option<Recorder> {
428    // Install the process-global handle so the block-controller stdout-reader
429    // hot path can mirror agent `output` into the global zone without threading
430    // the store through `resync_controller` and every controller constructor.
431    // Which Global Memory entries follow the fleet (task #12439, section 4.6): the
432    // entries that exist now stay on this machine, so create the table before anything new is written.
433    if let Err(e) = id_store.bundle_scope_ensure() {
434        tracing::warn!(error = %e, "Global Memory scope table: could not create it");
435    }
436    // Global Memory's own record (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md
437    // §2.1.6): write-through from id_store, attached before this start's
438    // seeding so seeded entries keep their seeder's attribution.
439    let global_memory_recorder = global_transcript_store
440        .as_ref()
441        .map(|fs| crate::backend::memory::global_record::attach(fs.clone(), id_store.clone()));
442    if let Some(ref fs) = global_transcript_store {
443        crate::backend::agent_session::set_global_transcript_store(fs.clone());
444        // Heal global snapshots poisoned before the normalize-on-mirror fix: a
445        // channel-local `sourceBlockId` mirrored into the global zone makes a
446        // cross-channel open render empty (the read fallback can't anchor a block
447        // that doesn't exist in the opening channel). Idempotent + cheap. See
448        // docs/retro/retro-legacy-agent-history-cross-channel-2026-06-16.md.
449        let healed = crate::boot_timing::time("transcript_snapshot_heal", || {
450            backend::agent_session::heal_global_snapshot_source_block_ids(fs, backfill_def_ids)
451        });
452        if healed > 0 {
453            tracing::info!(
454                healed,
455                "global transcripts: healed poisoned snapshot sourceBlockIds"
456            );
457        }
458    }
459    global_memory_recorder
460}
461
462/// Opens the saga log and reads the saga id to seed the allocator from.
463pub(super) fn open_saga_log(db_dir: &std::path::Path) -> (Arc<crate::sagas::log::SagaLog>, u64) {
464    // Saga durability — see SPEC_SAGA_DURABILITY_2026-05-01.md.
465    // Backed by its own SQLite file (`sagas.db`) so saga writes
466    // commit independently of the mstore connection. Failure here
467    // is fatal: without the log, a srv crash mid-saga leaves
468    // unrecoverable state divergence.
469    let saga_log = Arc::new(
470        crate::boot_timing::time("open_sagas_db", || {
471            crate::sagas::log::SagaLog::open(&db_dir.join("sagas.db"))
472        })
473        .unwrap_or_else(|e| {
474            tracing::error!("Failed to open saga log: {}", e);
475            std::process::exit(1);
476        }),
477    );
478    // Seed `saga_id_alloc` from the highest persisted saga_id so
479    // restarts don't reuse IDs from prior runs (reagent P1 + codex
480    // P1 PR #631). With this seed + the plain INSERT (no OR REPLACE)
481    // in `start_saga`, ID collisions become impossible by
482    // construction.
483    let saga_id_seed = crate::boot_timing::time("saga_id_seed_scan", || saga_log.max_saga_id()).unwrap_or_else(|e| {
484        tracing::warn!(
485            "[saga] failed to read MAX(saga_id) for allocator seed: {} — defaulting to 0; ID collisions on restart possible until next successful query",
486            e
487        );
488        0
489    });
490    if saga_id_seed > 0 {
491        tracing::info!(
492            "[saga] seeded saga_id_alloc from durable log: next saga_id = {}",
493            saga_id_seed + 1
494        );
495    }
496    (saga_log, saga_id_seed)
497}
498
499/// A store that is not incremental keeps the pages compression frees: ask for the one-time rewrite, which runs at the next
500/// start with no other srv running (reclaim spec §4).
501fn ask_for_the_rewrite_if_wanted(path: &std::path::Path, fs: &FileStore) {
502    let Ok(stats) = fs.page_stats() else { return };
503    if crate::backend::storage::filestore::reclaim::request_if_wanted(path, stats, agentmux_common::time::now_ms_u64()) {
504        tracing::info!("history store: the one-time rewrite that gives free space back is asked for at the next start");
505    }
506}