agentmux_srv/bootstrap/store_boot.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 prepare the data
5//! folder, seed the first launch and install the key resolvers. Moved out of that function without
6//! a change in behaviour.
7
8use super::stores::prepare_in_process;
9use super::*;
10use crate::backend::memory::global_record::Recorder;
11
12/// Sets the data folder up: environment, locks, the stamp and the startup diagnostics.
13pub(super) fn prepare_data_dir(config: &config::Config, version: &str) {
14 // Before anything is created: a data folder of its own must not mean the real shared folder.
15 super::shared_root::guard_shared_folder(&config.data_home, version);
16
17 // Set up data directory (uses AGENTMUX_DATA_HOME or default)
18 if !config.data_home.as_os_str().is_empty() {
19 std::env::set_var("AGENTMUX_DATA_HOME", &config.data_home);
20 }
21 if !config.config_home.as_os_str().is_empty() {
22 std::env::set_var("AGENTMUX_CONFIG_HOME", &config.config_home);
23 }
24 if !config.app_path.is_empty() {
25 std::env::set_var("AGENTMUX_APP_PATH", &config.app_path);
26 }
27
28 base::ensure_mux_data_dir().unwrap_or_else(|e| {
29 tracing::error!("Failed to ensure data dir: {}", e);
30 std::process::exit(1);
31 });
32 // One srv per set of databases, however it was started (headless already
33 // took this in `headless::prepare_env`; that makes this a no-op). A second srv exits with the code
34 // the launcher reads, so the person is told another AgentMux already runs here rather than seeing
35 // a bare failed start (task #49109).
36 if let Err(e) = base::acquire_data_dir_lock(&base::get_mux_data_dir()) {
37 tracing::error!("{e}");
38 eprintln!("agentmux-srv: {e}");
39 let code = match &e {
40 base::DataDirLockError::Held { .. } => agentmux_common::srv_stderr::DATA_DIR_HELD_EXIT,
41 base::DataDirLockError::Failed { .. } => 1,
42 };
43 std::process::exit(code);
44 }
45 base::ensure_mux_db_dir().unwrap_or_else(|e| {
46 tracing::error!("Failed to ensure db dir: {}", e);
47 std::process::exit(1);
48 });
49 // What this srv can do, beside the lock that names its pid, for a fork
50 // slug migration's precondition (`slug_migration::stamp`).
51 crate::backend::slug_migration::stamp::write(&base::get_mux_data_dir());
52
53 // Startup diagnostics. `home` is the folder this instance's whole data lives under: the real
54 // ~/.agentmux unless `AGENTMUX_HOME_OVERRIDE` names another (`task dev` always does).
55 let home_override = std::env::var_os("AGENTMUX_HOME_OVERRIDE").filter(|v| !v.is_empty());
56 tracing::info!(
57 data_dir = %base::get_mux_data_dir().display(),
58 db_dir = %base::get_mux_db_dir().display(),
59 app_path = %config.app_path,
60 instance_id = %config.instance_id,
61 secret_store = crate::identity::secret_store::backend_name(),
62 home = %home_override.as_ref().map(|h| h.to_string_lossy().into_owned()).unwrap_or_else(|| {
63 agentmux_common::data_paths::agentmux_root().map(|p| p.display().to_string()).unwrap_or_default()
64 }),
65 home_isolated = home_override.is_some(),
66 "backend directories initialized"
67 );
68}
69
70/// Runs the read-only data gate under a supervisor, or prepares the data in this process.
71pub(super) fn gate_or_prepare_data(mux_data_dir: &std::path::Path, db_dir: &std::path::Path) {
72 // Apply any pending migrations in-process before opening stores.
73 // This ensures 0011_shared_store_backfill (and any future Global migrations)
74 // have run before id_store binds to the shared store — avoiding apparent data
75 // loss on first boot after an upgrade. Fast-path: no-op when already current.
76 //
77 // id_store binding below checks shared_store.migration_is_applied("0011_shared_store_backfill")
78 // directly rather than a coarse migration_ok flag: if an early migration (e.g.
79 // 0011) succeeds but a later one fails, the shared store is already backfilled
80 // and safe to use — falling back to per-channel would strand writes made this
81 // session when the later migration succeeds on next boot.
82
83 let code_version =
84 std::env::var("AGENTMUX_VERSION").unwrap_or_else(|_| env!("CARGO_PKG_VERSION").to_string());
85 // Under a supervisor that prepares data (the launcher sets
86 // AGENTMUX_SUPERVISOR_PREPARES=1), srv never copies, snapshots or migrates
87 // at boot (SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15
88 // §10, S1c). A read-only check runs before anything writes the stores; if
89 // the data needs preparing, srv says why and exits, and the launcher runs
90 // `migrate --prepare` and starts it again. Elsewhere (headless srv,
91 // `task dev:standalone`) srv still prepares in-process.
92 let supervised =
93 std::env::var(agentmux_common::srv_stderr::SUPERVISOR_PREPARES_ENV).as_deref() == Ok("1");
94 if supervised {
95 if let Some(reason) = crate::boot_timing::time("data_gate", || {
96 migrations::data_needs_preparing(mux_data_dir, &code_version)
97 }) {
98 tracing::info!("startup: data needs preparing, exiting for the launcher: {reason}");
99 eprintln!(
100 "{}",
101 agentmux_common::srv_stderr::needs_prepare_line(&reason)
102 );
103 std::process::exit(agentmux_common::srv_stderr::NEEDS_PREPARE_EXIT);
104 }
105 } else {
106 prepare_in_process(mux_data_dir, db_dir, &code_version);
107 }
108}
109
110/// Opens the per-channel object store.
111pub(super) fn open_objects_db(db_dir: &std::path::Path) -> Store {
112 crate::boot_timing::time("open_objects_db", || {
113 Store::open(&db_dir.join("objects.db"))
114 })
115 .unwrap_or_else(|e| {
116 tracing::error!("Failed to open object store: {}", e);
117 std::process::exit(1);
118 })
119}
120
121/// Creates the first launch's workspace and initial data.
122pub(super) fn ensure_initial_data(mstore: &Arc<Store>) {
123 // The user's workspace (SPEC_WORKSPACES_2026_10_23.md §4.2): Default
124 // Workspace, or a new version's copy of the previous version's. Before the
125 // initial data, which a copied workspace with windows replaces.
126 let opened_workspace = crate::server::service::user_workspace::prepare_at_startup(
127 mstore,
128 crate::server::service::session_other_builds::ScanRoots::live().as_ref(),
129 );
130 // Bootstrap data (creates Client/Window/Workspace/Tab on first launch)
131 let first_launch = wcore::ensure_initial_data(mstore).unwrap_or_else(|e| {
132 tracing::error!("Failed to ensure initial data: {}", e);
133 std::process::exit(1);
134 });
135 if first_launch {
136 tracing::info!("First launch: created initial data");
137 // Its window may offer a layout another build saved.
138 crate::server::service::session_other_builds::remember_first_launch_default(mstore);
139 }
140 // A window whose close a quit outran: the session record restores it.
141 crate::server::service::forget_windows_left_by_quit(mstore);
142 crate::server::service::user_workspace::adopt_current(mstore, opened_workspace);
143
144 // Seed ~/.agentmux/.gitignore so accidental git operations inside the
145 // data directory (e.g. an agent running `git init` or `git clone` in its
146 // cwd) don't stage anything by default. Idempotent — written once per
147 // install; we don't overwrite an existing user-customized file.
148 if let Some(home) = dirs::home_dir() {
149 let data_dir = home.join(".agentmux");
150 if data_dir.is_dir() {
151 let gitignore = data_dir.join(".gitignore");
152 if !gitignore.exists() {
153 let _ = std::fs::write(&gitignore, "*\n!.gitignore\n");
154 }
155 }
156 }
157}
158
159/// Flags interrupted sessions and runs the startup seeds.
160pub(super) fn recover_and_seed(
161 mstore: &Arc<Store>,
162 id_store: &Arc<Store>,
163 identity_store: &Arc<Store>,
164 global_memory_recorder: &Option<Recorder>,
165) {
166 // Session recovery (Phase 4.2): scan for agent blocks that still have
167 // `session:active_pid` from a previous run — those sessions were killed
168 // by a crash/reboot. Transfer to `session:was_interrupted` so the
169 // frontend can show a reconnect banner.
170 let orphan_count = backend::blockcontroller::session_recovery::scan_orphans(mstore);
171 if orphan_count > 0 {
172 tracing::info!(
173 orphan_count = orphan_count,
174 "session_recovery: flagged {} interrupted sessions for user reconnect",
175 orphan_count
176 );
177 backend::blockcontroller::session_recovery::note_interrupted(
178 &base::get_mux_data_dir(),
179 orphan_count,
180 std::env::var(agentmux_common::incidents::RESTART_ID_ENV)
181 .ok()
182 .as_deref(),
183 );
184 }
185
186 // Auto-seed agent definitions on first launch (or empty DB)
187 crate::boot_timing::time("agent_auto_seed", || {
188 backend::agent_seed::auto_seed_on_startup(mstore)
189 });
190
191 // Keep AgentMux's own Operator Config (is_system=1 Global Memory) in
192 // sync with the shipped manifest on every startup — not a one-time
193 // seed, since stale Operator Config content would mislead an agent
194 // rather than merely being absent. See
195 // docs/specs/SPEC_SYSTEM_TIER_GLOBAL_MEMORY_SEEDING_2026_09_15.md.
196 //
197 // Seeded into id_store, NOT mstore: Global Memory reads/writes
198 // (agent_open.rs's bundle_list_global, bundle.rs's handlers via
199 // state.id_store) all route through id_store, which points at the
200 // shared store once 0011_shared_store_backfill has run and only falls
201 // back to mstore before that. Seeding mstore directly would leave these
202 // rows invisible under the normal shared-store configuration once that
203 // migration has applied. Codex P1, PR #3244.
204 backend::operator_config_seed::auto_seed_on_startup(id_store);
205 // Then record whatever the record doesn't have yet: the baseline the
206 // first time, and what older builds changed since.
207 if let Some(ref recorder) = global_memory_recorder {
208 recorder.sync_all();
209 }
210
211 // No starter Skills are seeded: the migration that did is retired, and
212 // 0041 removed the ones it had left in existing catalogs.
213 // The skills AgentMux ships are a different thing: a few, each created once and then the
214 // user's (`backend::builtin_skills`).
215 backend::builtin_skills::seed_on_startup(identity_store);
216
217 // Gap-repair (backfilling a db_agent_definitions row missing its
218 // db_agents mirror) is gone as of the definition flip: every
219 // agent_def_* write lands on db_agents directly now, so that gap can no
220 // longer open. Removing the per-boot pass was required, not optional —
221 // once agent_def_delete/instance_delete stopped also clearing
222 // db_agent_definitions, a repair pass still reading it would have
223 // resurrected every deleted agent on the next boot.
224}
225
226/// Lets the cross-instance agent registry publish each agent's public key.
227pub(super) fn install_key_resolvers(mstore: &Arc<Store>) {
228 // Let the cross-instance agent registry publish each agent's Ed25519
229 // PUBLIC key alongside its entry, so a peer instance in a *different
230 // channel* can verify that agent's jekts — the one same-machine tier that
231 // had no verification path at all before
232 // `SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md`. Host-tier's HMAC key is
233 // symmetric and deliberately NOT published (spec §5).
234 //
235 // Installed here rather than next to `init_local_auth_key` in
236 // `load_config` because that runs before any store is open, and this is a
237 // per-agent lookup rather than a process constant. Registry writes before
238 // this point simply publish an empty key, which readers treat as "cannot
239 // check."
240 crate::backend::reactive::registry::init_jekt_public_key_resolver({
241 let mstore = mstore.clone();
242 move |agent_id| mstore.agent_lan_public_key_load(agent_id).ok().flatten()
243 });
244 // Identity M4d-5: the block's agent UID and that UID's public key, beside
245 // the name-keyed one.
246 crate::backend::reactive::registry::init_uid_key_resolver({
247 let mstore = mstore.clone();
248 move |block_id| {
249 let uid = mstore
250 .instance_get_active_for_block(block_id)
251 .ok()
252 .flatten()?
253 .id;
254 let key = mstore.agent_uid_lan_public_key_load(&uid).ok().flatten()?;
255 Some((uid, key))
256 }
257 });
258}