Skip to main content

agentmux_srv_core/backend/storage/
store.rs

1// Copyright 2025, Command Line Inc.
2// Copyright 2025-2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! Store: generic OID-based CRUD for StoreObj types.
6//! Port of Go's pkg/mstore/mstore_dbops.go + mstore_dbsetup.go.
7//!
8//! Uses `Mutex<Connection>` matching Go's `MaxOpenConns(1)`.
9//! SQLite WAL mode + 5s busy timeout (same as Go).
10
11
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex};
14
15use rusqlite::{params, Connection};
16
17use crate::backend::obj::{mux_obj_from_json, mux_obj_to_json, StoreObj};
18use crate::registry::{DefinitionStore, Registry};
19
20use super::error::StoreError;
21use super::migrations::{
22    check_schema_compat, run_identity_store_schema, run_object_schema, run_shared_store_schema,
23    stamp_version, IDENTITY_STORE_SCHEMA_VERSION, OBJECT_SCHEMA_VERSION,
24    SHARED_STORE_SCHEMA_VERSION,
25};
26
27/// SQLite-backed object store for StoreObj types.
28pub struct Store {
29    /// `pub(super)` so sibling subsystem modules (e.g. `bundles`)
30    /// can take the lock. Each per-subsystem file adds methods to `Store`
31    /// via `impl Store {}` and needs the connection.
32    pub(super) conn: super::timed_mutex::TimedMutex<Connection>,
33    /// Cross-version named-agent registry. `None` for in-memory test
34    /// stores; `Some` for production srv. Mutations to
35    /// `db_agent_instances` parallel-write to this registry when set.
36    /// See `docs/specs/SPEC_SHARED_AGENT_REGISTRY_2026_05_12.md`.
37    registry: Mutex<Option<Arc<Registry>>>,
38    /// GLOBAL (cross-channel) agent-definition store. `None` for in-memory
39    /// test stores and when the shared dir can't be resolved; `Some` for
40    /// production srv. Definition mutations mirror to it so an agent created
41    /// in one channel is visible in every channel (cross-channel agent
42    /// persistence, `docs/specs/SPEC_CROSS_CHANNEL_AGENT_PERSISTENCE_2026-06-13.md`).
43    def_registry: Mutex<Option<Arc<DefinitionStore>>>,
44    /// The AgentMux root whose every `objects.db` and live registration a
45    /// new agent's slug is also checked against
46    /// (`slug_migration::HostSlugs`). `None` except on the channel's object
47    /// store at runtime, and in tests that ask for it.
48    slug_home: Mutex<Option<Arc<crate::backend::slug_migration::Home>>>,
49    /// Every former slug this channel can see, cached so a sender or target
50    /// that isn't one costs no store read (`agents/former_slugs.rs`).
51    pub(super) former_slugs: super::agents::FormerSlugSet,
52    /// token → UID for attributing requests (identity M4a). `None` except on
53    /// the channel's object store at runtime; see `attach_token_index`.
54    pub(super) token_index: Mutex<Option<Arc<super::agent_tokens::TokenIndex>>>,
55    /// The channel-wide WAN identity store (`wan-identity/wan.db`). `None`
56    /// except on the channel's object store at runtime, and when the file
57    /// couldn't be opened — WAN signing is then off. See `wan_identity.rs`.
58    wan_identity: Mutex<Option<Arc<super::wan_identity::WanIdentityStore>>>,
59    /// Base directory that named-instance `working_directory` values are
60    /// expressed **relative to** in the instance registry (write side:
61    /// `registry_mirror`; read side: the `listnamedagents` handler).
62    ///
63    /// This is the **current channel's** agents dir (`channels/<ch>/agents`,
64    /// i.e. `AGENTMUX_AGENTS_DIR`). It must be tracked separately from the
65    /// registry's own file location because P0.3 re-roots the registry to the
66    /// global `~/.agentmux/shared/agents/registry/` — once the registry no
67    /// longer sits under `channels/<ch>/agents/`, its parent (`agents_root()`)
68    /// stops coinciding with the channel agents dir, and using it to strip /
69    /// re-join `working_directory` would drop every live instance.
70    ///
71    /// In production it is wired from `AGENTMUX_AGENTS_DIR` in `main.rs`
72    /// (P0.3b), atomically with the re-root to the global shared registry —
73    /// which is why the wiring waited for the re-root: setting it earlier would
74    /// diverge in dev mode, where `AGENTMUX_AGENTS_DIR` ≠ the (then
75    /// channel-local) registry parent. `None` only for in-memory test stores
76    /// and odd envs where the var is unset; the accessor then falls back to the
77    /// registry's parent (which equals the channel agents dir in the pre-re-root
78    /// layout), so existing mirror tests are unchanged. When set, it is passed
79    /// in explicitly — never read from ambient env inside the Store — so tests
80    /// running inside an AgentMux pane don't pick up the host's
81    /// `AGENTMUX_AGENTS_DIR`. See
82    /// `docs/specs/SPEC_CROSS_CHANNEL_AGENT_PERSISTENCE_2026-06-13.md` (P0.3).
83    registry_agents_base: Mutex<Option<PathBuf>>,
84    /// The host's LAN signing keys (`host_lan_keys.rs`): the key an agent signs with on this machine
85    /// whatever channel runs it. `None` for in-memory test stores, and when the shared identity store
86    /// did not open, which leaves each channel on its own keys.
87    host_lan_keys: Mutex<Option<Arc<super::host_lan_keys::HostLanKeys>>>,
88    /// Serializes `muxbus_save` end-to-end (keychain read, keychain write,
89    /// SQL write, and any rollback) — reagent P1 on #2260: two concurrent
90    /// `muxbus_save` calls (the `muxbus.login` RPC handler and the broker's
91    /// registered refresh closure can each call it independently) would
92    /// otherwise race on the keychain's "previous state" snapshot; if the
93    /// second call's SQL write then failed, its rollback could restore a
94    /// stale pre-first-call blob, silently reverting a credential the first
95    /// call already committed. `self.conn`'s own lock only covers the SQL
96    /// portion, not the keychain read/write either side of it, so a
97    /// dedicated lock is needed rather than reusing that one. `pub(super)`
98    /// like `conn` — `muxbus.rs` is a sibling module under `backend::storage`.
99    pub(super) muxbus_save_lock: Mutex<()>,
100    /// Told about every change to a Global Memory entry or its order, after
101    /// it commits — the Global Memory record's write-through
102    /// (`backend::memory::global_record`,
103    /// SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.6). `None` except on
104    /// the channel's Global Memory store at runtime.
105    global_memory_observer: Mutex<Option<GlobalMemoryObserver>>,
106    /// Writes to the objects a user workspace is saved from, counted so the
107    /// workspace saver knows when something changed (`user_workspaces.rs`).
108    pub(super) layout_writes: super::user_workspaces::LayoutWrites,
109}
110
111/// A change to Global Memory, for [`Store::set_global_memory_observer`].
112#[derive(Debug, Clone, PartialEq, Eq, Hash)]
113pub enum GlobalMemoryChange {
114    /// The bundle with this id was written or deleted (it may or may not be
115    /// global, before or after).
116    Entry(String),
117    /// Global Memory was reordered.
118    Order,
119}
120
121/// Must not block or call back into the store: it runs where the change was
122/// made. The record's observer only queues the change for a worker.
123pub type GlobalMemoryObserver = Arc<dyn Fn(GlobalMemoryChange) + Send + Sync>;
124
125impl Store {
126    /// Open a Store backed by a file on disk.
127    /// Configures WAL mode and 5s busy timeout (matching Go).
128    pub fn open(path: &Path) -> Result<Self, StoreError> {
129        let conn = Connection::open(path)?;
130        Self::configure_and_migrate(conn)
131    }
132
133    /// Open an existing store **read-only**: `SQLITE_OPEN_READ_ONLY`, no
134    /// WAL/journal pragma, no schema setup, no version stamp — nothing that
135    /// could write. For doctor checks (`migrate --verify`, `muxspect
136    /// migrations`) that need the typed read API against a store they must
137    /// not touch, including one on a read-only backup (codex P2 on #3070).
138    /// Any read of a table the store predates simply errors. Fails if the
139    /// file does not exist — a doctor must never conjure a store.
140    pub fn open_read_only(path: &Path) -> Result<Self, StoreError> {
141        let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
142        conn.execute_batch("PRAGMA busy_timeout=5000;")?;
143        Ok(Self {
144            conn: super::timed_mutex::TimedMutex::new(conn, "objects"),
145            registry: Mutex::new(None),
146            def_registry: Mutex::new(None),
147            slug_home: Mutex::new(None),
148            former_slugs: Default::default(),
149            token_index: Mutex::new(None),
150            wan_identity: Mutex::new(None),
151            registry_agents_base: Mutex::new(None),
152            host_lan_keys: Mutex::new(None),
153            muxbus_save_lock: Mutex::new(()),
154            global_memory_observer: Mutex::new(None),
155            layout_writes: Default::default(),
156        })
157    }
158
159    /// Open an in-memory Store for testing.
160    #[allow(dead_code)]
161    pub fn open_in_memory() -> Result<Self, StoreError> {
162        let conn = Connection::open_in_memory()?;
163        Self::configure_and_migrate(conn)
164    }
165
166    /// Which store this is, stable for its lifetime: the database file, or —
167    /// for an in-memory store — its address. Lets a record written into a
168    /// machine-wide zone say which channel's store wrote it.
169    pub fn origin_id(&self) -> String {
170        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
171        match conn.path() {
172            Some(p) if !p.is_empty() => p.to_string(),
173            _ => format!("memory:{:p}", self),
174        }
175    }
176
177    /// TEST-ONLY: the connection's lock, held for as long as the guard lives: a store another thread has busy.
178    #[cfg(any(test, feature = "test-support"))]
179    pub fn hold_for_tests(&self) -> super::timed_mutex::TimedGuard<'_, Connection> {
180        self.conn.lock().unwrap_or_else(|e| e.into_inner())
181    }
182
183    /// TEST-ONLY: additionally install the **identity-store** schema on this
184    /// store, on top of whatever schema it already carries.
185    ///
186    /// `server::tests::test_state` deliberately aliases `mstore`, `id_store`
187    /// and `identity_store` to ONE in-memory store so a test can seed data
188    /// through any of them — a lot of existing setup code depends on that.
189    /// The cost is that the single store carried only the object schema, so a
190    /// handler touching a table that exists ONLY in the global identity store
191    /// (`db_work_queue`) failed with a bare "no such table" 500 in tests while
192    /// being correct in production — the harness silently answered a different
193    /// question than the one under test.
194    ///
195    /// Every statement in that schema is `CREATE TABLE/INDEX IF NOT EXISTS`,
196    /// so tables already present from the object schema are left untouched;
197    /// this only fills in the ones that are missing.
198    #[cfg(any(test, feature = "test-support"))]
199    pub fn apply_identity_schema_for_tests(&self) -> Result<(), StoreError> {
200        let conn = self.conn.lock().unwrap();
201        run_identity_store_schema(&conn)?;
202        conn.execute_batch(super::work_claims::SCHEMA)?;
203        conn.execute_batch(super::coord_posts::SCHEMA)?;
204        conn.execute_batch(super::bulletins::SCHEMA)?;
205        super::work_schema::apply(&conn)?;
206        super::work_boards::seed_main(&conn)?;
207        super::job_runs::apply_schema(&conn)?;
208        super::dreams::apply_schema(&conn)?;
209        Ok(conn.execute_batch(super::google_grants::SCHEMA)?)
210    }
211
212    /// Open the GLOBAL shared store at `path` (`~/.agentmux/shared/store.db`).
213    ///
214    /// Uses the same WAL + busy-timeout config as `open()` but runs
215    /// `run_shared_store_schema` instead of `run_object_schema` so only
216    /// the durable-user-content tables are created (identity, memory, drone
217    /// definitions, muxbus creds). Per-channel session tables are intentionally
218    /// absent — calling per-channel CRUD methods on this store will error.
219    pub fn open_shared(path: &Path) -> Result<Self, StoreError> {
220        let conn = Connection::open(path)?;
221        conn.execute_batch(
222            "PRAGMA journal_mode=WAL;
223             PRAGMA busy_timeout=5000;
224             PRAGMA foreign_keys=ON;
225             PRAGMA synchronous=NORMAL;
226             PRAGMA cache_size=-8000;
227             PRAGMA mmap_size=268435456;
228             PRAGMA temp_store=MEMORY;",
229        )?;
230        check_schema_compat(&conn, SHARED_STORE_SCHEMA_VERSION, "store.db")?;
231        run_shared_store_schema(&conn)?;
232        // The record of memory passes is read through `id_store`, which is this store (or the channel's own).
233        super::dreams::apply_schema(&conn)?;
234        stamp_version(&conn, SHARED_STORE_SCHEMA_VERSION)?;
235        Ok(Self {
236            conn: super::timed_mutex::TimedMutex::new(conn, "objects"),
237            registry: Mutex::new(None),
238            def_registry: Mutex::new(None),
239            slug_home: Mutex::new(None),
240            former_slugs: Default::default(),
241            token_index: Mutex::new(None),
242            wan_identity: Mutex::new(None),
243            registry_agents_base: Mutex::new(None),
244            host_lan_keys: Mutex::new(None),
245            muxbus_save_lock: Mutex::new(()),
246            global_memory_observer: Mutex::new(None),
247            layout_writes: Default::default(),
248        })
249    }
250
251    /// Open the permanently-global identity store at `path`
252    /// (`~/.agentmux/shared/identity-store.db`) — see
253    /// `docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md`.
254    ///
255    /// Same WAL + busy-timeout config as [`open_shared`](Self::open_shared),
256    /// but runs [`run_identity_store_schema`] — a strict subset of
257    /// [`open_shared`](Self::open_shared)'s tables (everything except
258    /// `db_accounts`) — instead of `run_shared_store_schema`. Crucially,
259    /// this store's PATH is never gated by `isolated_auth_enabled()` (see
260    /// its resolver, `registry::resolve_identity_store_path`): unlike
261    /// `open_shared`, there is no isolated/per-channel variant of this
262    /// store at all.
263    pub fn open_identity_store(path: &Path) -> Result<Self, StoreError> {
264        let conn = Connection::open(path)?;
265        conn.execute_batch(
266            "PRAGMA journal_mode=WAL;
267             PRAGMA busy_timeout=5000;
268             PRAGMA foreign_keys=ON;
269             PRAGMA synchronous=NORMAL;
270             PRAGMA cache_size=-8000;
271             PRAGMA mmap_size=268435456;
272             PRAGMA temp_store=MEMORY;",
273        )?;
274        check_schema_compat(&conn, IDENTITY_STORE_SCHEMA_VERSION, "identity-store.db")?;
275        // The Kanban's tables have their own version in the same file: refuse a newer shape before
276        // anything here writes (see work_schema's module doc for why it is not this store's number).
277        super::work_schema::check_before_open(&conn)?;
278        run_identity_store_schema(&conn)?;
279        conn.execute_batch(super::work_claims::SCHEMA)?;
280        conn.execute_batch(super::coord_posts::SCHEMA)?;
281        conn.execute_batch(super::bulletins::SCHEMA)?;
282        super::work_schema::apply(&conn)?;
283        super::work_boards::seed_main(&conn)?;
284        super::job_runs::apply_schema(&conn)?;
285        super::dreams::apply_schema(&conn)?;
286        conn.execute_batch(super::google_grants::SCHEMA)?;
287        stamp_version(&conn, IDENTITY_STORE_SCHEMA_VERSION)?;
288        Ok(Self {
289            conn: super::timed_mutex::TimedMutex::new(conn, "objects"),
290            registry: Mutex::new(None),
291            def_registry: Mutex::new(None),
292            slug_home: Mutex::new(None),
293            former_slugs: Default::default(),
294            token_index: Mutex::new(None),
295            wan_identity: Mutex::new(None),
296            registry_agents_base: Mutex::new(None),
297            host_lan_keys: Mutex::new(None),
298            muxbus_save_lock: Mutex::new(()),
299            global_memory_observer: Mutex::new(None),
300            layout_writes: Default::default(),
301        })
302    }
303
304    /// Open a sibling `objects.db` file for read-only backfill access.
305    ///
306    /// Does NOT run schema migrations or stamp a version — the source DB is
307    /// never modified (spec §3.1). WAL mode is not set either: the file is
308    /// opened with `SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_NO_MUTEX` so concurrent
309    /// writers on the same DB are unaffected. Tables absent in older schemas
310    /// (e.g. `db_drone_definitions`) return empty results via the normal
311    /// `StoreError` path; callers use `.unwrap_or_default()`.
312    pub fn open_source_readonly(path: &Path) -> Result<Self, StoreError> {
313        use rusqlite::OpenFlags;
314        let conn = Connection::open_with_flags(
315            path,
316            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
317        )?;
318        conn.busy_timeout(std::time::Duration::from_millis(500))?;
319        Ok(Self {
320            conn: super::timed_mutex::TimedMutex::new(conn, "objects"),
321            registry: Mutex::new(None),
322            def_registry: Mutex::new(None),
323            slug_home: Mutex::new(None),
324            former_slugs: Default::default(),
325            token_index: Mutex::new(None),
326            wan_identity: Mutex::new(None),
327            registry_agents_base: Mutex::new(None),
328            host_lan_keys: Mutex::new(None),
329            muxbus_save_lock: Mutex::new(()),
330            global_memory_observer: Mutex::new(None),
331            layout_writes: Default::default(),
332        })
333    }
334
335    /// Crate-internal accessor for sibling modules that maintain their
336    /// own per-table CRUD via the `DroneStore` extension trait
337    /// pattern (see `crates/srv-core/src/backend/storage/drone_store.rs`). Outside
338    /// callers must use the typed methods on this impl.
339    pub fn conn(&self) -> &super::timed_mutex::TimedMutex<Connection> {
340        &self.conn
341    }
342
343    /// Run the `db_agents` consolidation backfill under the mstore's
344    /// exclusive connection lock. Idempotent — gated by a marker file in
345    /// `data_dir` (skip with `None` for tests).
346    pub fn run_agents_consolidate(
347        &self,
348        data_dir: Option<&Path>,
349    ) -> Result<super::agents_consolidate::ConsolidateStats, StoreError> {
350        let mut conn = self.conn.lock().unwrap();
351        super::agents_consolidate::run_consolidate_migration(&mut conn, data_dir)
352    }
353
354    /// Run `PRAGMA wal_checkpoint(TRUNCATE)` to fold the WAL back into the
355    /// main DB file. Called periodically and on clean shutdown. The 5s
356    /// `busy_timeout` set at open handles transient reader contention — if it
357    /// can't fully truncate it returns partial progress (safe; picked up on
358    /// the next pass).
359    pub fn checkpoint(&self) -> Result<(), StoreError> {
360        self.conn()
361            .lock()
362            .unwrap()
363            .execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
364        Ok(())
365    }
366
367    fn configure_and_migrate(conn: Connection) -> Result<Self, StoreError> {
368        conn.execute_batch(
369            // `foreign_keys=ON` is per-connection and defaults to OFF in
370            // SQLite. The v6 schema (`db_agent_identity_links`,
371            // `db_agent_instances`) relies on `ON DELETE CASCADE` to clean
372            // up junction rows and instances when a parent agent or
373            // identity is removed. Without this pragma on the production
374            // connection, cascades silently no-op; migration tests set it
375            // explicitly, which would have masked the gap.
376            "PRAGMA journal_mode=WAL;
377             PRAGMA busy_timeout=5000;
378             PRAGMA foreign_keys=ON;
379             PRAGMA synchronous=NORMAL;
380             PRAGMA cache_size=-8000;
381             PRAGMA mmap_size=268435456;
382             PRAGMA temp_store=MEMORY;",
383        )?;
384        // Safety lock BEFORE any migration side effects — the legacy-
385        // table rename + seed-insert steps in `run_object_schema` are
386        // mutating, so we must refuse to open a newer-schema DB before
387        // we touch it. (codex P1 on #1029 — fixes the original PR's
388        // check-after-migrate order that let a downgraded binary
389        // partially mutate a newer DB before the error fired.)
390        check_schema_compat(&conn, OBJECT_SCHEMA_VERSION, "objects.db")?;
391        run_object_schema(&conn)?;
392        conn.execute_batch(super::user_workspaces::SCHEMA)?;
393        // `id_store` is this store when there is no shared one, and the record of memory passes is read through it.
394        super::dreams::apply_schema(&conn)?;
395        stamp_version(&conn, OBJECT_SCHEMA_VERSION)?;
396        Ok(Self {
397            conn: super::timed_mutex::TimedMutex::new(conn, "objects"),
398            registry: Mutex::new(None),
399            def_registry: Mutex::new(None),
400            slug_home: Mutex::new(None),
401            former_slugs: Default::default(),
402            token_index: Mutex::new(None),
403            wan_identity: Mutex::new(None),
404            registry_agents_base: Mutex::new(None),
405            host_lan_keys: Mutex::new(None),
406            muxbus_save_lock: Mutex::new(()),
407            global_memory_observer: Mutex::new(None),
408            layout_writes: Default::default(),
409        })
410    }
411
412    /// Attach a shared cross-version agent registry. Called once on
413    /// srv startup after `Store::open` and before the store is
414    /// wrapped in `Arc`. Mutations to `db_agent_instances` will then
415    /// parallel-write to the registry; the SQLite table remains the
416    /// authoritative read path for PR A.
417    pub fn set_registry(&self, registry: Arc<Registry>) {
418        *self.registry.lock().unwrap_or_else(|e| e.into_inner()) = Some(registry);
419    }
420
421    /// Attach the Global Memory record's observer (see the field).
422    pub fn set_global_memory_observer(&self, observer: GlobalMemoryObserver) {
423        *self.global_memory_observer.lock().unwrap_or_else(|e| e.into_inner()) = Some(observer);
424    }
425
426    /// Tell the observer, if any, about a committed change. Callers invoke it
427    /// once their connection lock is released.
428    pub(super) fn notify_global_memory(&self, change: GlobalMemoryChange) {
429        let observer = self.global_memory_observer.lock().unwrap_or_else(|e| e.into_inner()).clone();
430        if let Some(o) = observer {
431            o(change);
432        }
433    }
434
435    pub(super) fn registry(&self) -> Option<Arc<Registry>> {
436        self.registry
437            .lock()
438            .unwrap_or_else(|e| e.into_inner())
439            .clone()
440    }
441
442    /// Attach the host's LAN key table: from then on this store's LAN keys follow it.
443    pub fn set_host_lan_keys(&self, keys: Arc<super::host_lan_keys::HostLanKeys>) {
444        *self.host_lan_keys.lock().unwrap_or_else(|e| e.into_inner()) = Some(keys);
445    }
446
447    pub(super) fn host_lan_keys(&self) -> Option<Arc<super::host_lan_keys::HostLanKeys>> {
448        self.host_lan_keys.lock().unwrap_or_else(|e| e.into_inner()).clone()
449    }
450
451    /// Set the channel agents dir that instance `working_directory` values
452    /// are stored relative to (see the `registry_agents_base` field). Wired
453    /// from `AGENTMUX_AGENTS_DIR` in `main.rs` in P0.3b (atomically with the
454    /// registry re-root); until then it is exercised only by tests.
455    pub fn set_registry_agents_base(&self, base: PathBuf) {
456        *self
457            .registry_agents_base
458            .lock()
459            .unwrap_or_else(|e| e.into_inner()) = Some(base);
460    }
461
462    /// The base dir for instance `working_directory` relative paths.
463    ///
464    /// Returns the explicitly-set channel agents dir
465    /// ([`set_registry_agents_base`]) when present; otherwise falls back to
466    /// the registry's parent (`agents_root()`), which equals the channel
467    /// agents dir in the pre-re-root layout. Used symmetrically by the write
468    /// mirror and the read handler so the two never disagree on the anchor.
469    pub fn registry_agents_base(&self) -> Option<PathBuf> {
470        if let Some(base) = self
471            .registry_agents_base
472            .lock()
473            .unwrap_or_else(|e| e.into_inner())
474            .clone()
475        {
476            return Some(base);
477        }
478        self.registry()
479            .and_then(|r| r.agents_root().map(|p| p.to_path_buf()))
480    }
481
482    /// Public accessor for the cross-version named-agent registry.
483    /// Returns `None` when the registry couldn't be resolved at
484    /// startup (CI / unusual envs); callers must handle the absent
485    /// case by falling back to SQLite.
486    pub fn shared_agent_registry(&self) -> Option<Arc<Registry>> {
487        self.registry()
488    }
489
490    /// Attach the GLOBAL (cross-channel) agent-definition store. Called
491    /// once on srv startup after `Store::open`, before the store is
492    /// wrapped in `Arc`. Definition mutations then mirror to it.
493    pub fn set_wan_identity(&self, wan_identity: Arc<super::wan_identity::WanIdentityStore>) {
494        *self.wan_identity.lock().unwrap_or_else(|e| e.into_inner()) = Some(wan_identity);
495    }
496
497    /// The channel-wide WAN identity store, if attached. `None` means WAN
498    /// signing is off for this process — never fall back to another store.
499    pub fn wan_identity(&self) -> Option<Arc<super::wan_identity::WanIdentityStore>> {
500        self.wan_identity.lock().unwrap_or_else(|e| e.into_inner()).clone()
501    }
502
503    pub fn set_def_registry(&self, def_registry: Arc<DefinitionStore>) {
504        *self.def_registry.lock().unwrap_or_else(|e| e.into_inner()) = Some(def_registry);
505        self.former_slugs.invalidate();
506    }
507
508    /// Check new slugs against every `objects.db` and live registration
509    /// under `home` too, not only this channel's rows and the shared
510    /// definitions.
511    pub fn set_slug_home(&self, home: crate::backend::slug_migration::Home) {
512        *self.slug_home.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(home));
513    }
514
515    pub(super) fn slug_home(&self) -> Option<Arc<crate::backend::slug_migration::Home>> {
516        self.slug_home.lock().unwrap_or_else(|e| e.into_inner()).clone()
517    }
518
519    /// Public accessor for the global agent-definition store. `None` when
520    /// it couldn't be resolved at startup (CI / unusual envs / in-memory
521    /// tests); callers fall back to SQLite.
522    pub fn shared_def_registry(&self) -> Option<Arc<DefinitionStore>> {
523        self.def_registry
524            .lock()
525            .unwrap_or_else(|e| e.into_inner())
526            .clone()
527    }
528
529    /// Table name for a StoreObj type: `db_<otype>`.
530    fn table_name<T: StoreObj>() -> String {
531        format!("db_{}", T::get_otype())
532    }
533
534    /// Get a single object by OID. Returns `None` if not found.
535    pub fn get<T: StoreObj>(&self, oid: &str) -> Result<Option<T>, StoreError> {
536        let conn = self.conn.lock().unwrap();
537        let table = Self::table_name::<T>();
538        let mut stmt =
539            conn.prepare(&format!("SELECT version, data FROM {table} WHERE oid = ?1"))?;
540
541        let result = stmt.query_row(params![oid], |row| {
542            let version: i64 = row.get(0)?;
543            let data: Vec<u8> = row.get(1)?;
544            Ok((version, data))
545        });
546
547        match result {
548            Ok((version, data)) => {
549                let mut obj: T = mux_obj_from_json(&data)?;
550                obj.set_version(version);
551                Ok(Some(obj))
552            }
553            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
554            Err(e) => Err(StoreError::Sqlite(e)),
555        }
556    }
557
558    /// Get a single object, returning `StoreError::NotFound` if missing.
559    pub fn must_get<T: StoreObj>(&self, oid: &str) -> Result<T, StoreError> {
560        self.get::<T>(oid)?.ok_or(StoreError::NotFound)
561    }
562
563    /// Get a single object as raw JSON Value by otype and OID.
564    /// Used by GetObject/GetObjects to return data without strict struct deserialization.
565    pub fn get_raw(&self, otype: &str, oid: &str) -> Result<Option<serde_json::Value>, StoreError> {
566        let conn = self.conn.lock().unwrap();
567        let table = format!("db_{}", otype);
568        let mut stmt =
569            conn.prepare(&format!("SELECT version, data FROM {table} WHERE oid = ?1"))?;
570
571        let result = stmt.query_row(params![oid], |row| {
572            let version: i64 = row.get(0)?;
573            let data: Vec<u8> = row.get(1)?;
574            Ok((version, data))
575        });
576
577        match result {
578            Ok((version, data)) => {
579                let mut val: serde_json::Value = serde_json::from_slice(&data)
580                    .map_err(|e| StoreError::Json(e))?;
581                if let Some(obj) = val.as_object_mut() {
582                    obj.insert("version".to_string(), serde_json::json!(version));
583                    obj.insert("otype".to_string(), serde_json::json!(otype));
584                }
585                Ok(Some(val))
586            }
587            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
588            Err(e) => Err(StoreError::Sqlite(e)),
589        }
590    }
591
592    /// Check if an object exists (by otype and OID).
593    #[allow(dead_code)]
594    pub fn exists_raw(&self, otype: &str, oid: &str) -> Result<bool, StoreError> {
595        let conn = self.conn.lock().unwrap();
596        let table = format!("db_{}", otype);
597        let count: i64 = conn.query_row(
598            &format!("SELECT COUNT(*) FROM {table} WHERE oid = ?1"),
599            params![oid],
600            |row| row.get(0),
601        )?;
602        Ok(count > 0)
603    }
604
605    /// Insert a new object. Sets version to 1.
606    pub fn insert<T: StoreObj>(&self, obj: &mut T) -> Result<(), StoreError> {
607        let oid = obj.get_oid().to_string();
608        if oid.is_empty() {
609            return Err(StoreError::EmptyOID);
610        }
611
612        obj.set_version(1);
613        let data = mux_obj_to_json(obj)?;
614
615        let conn = self.conn.lock().unwrap();
616        let table = Self::table_name::<T>();
617        conn.execute(
618            &format!("INSERT INTO {table} (oid, version, data) VALUES (?1, 1, ?2)"),
619            params![oid, data],
620        )?;
621        self.layout_writes.wrote(T::get_otype());
622
623        Ok(())
624    }
625
626    /// Update an existing object. Increments version atomically.
627    /// Returns the new version number.
628    pub fn update<T: StoreObj>(&self, obj: &mut T) -> Result<i64, StoreError> {
629        let oid = obj.get_oid().to_string();
630        if oid.is_empty() {
631            return Err(StoreError::EmptyOID);
632        }
633
634        let data = mux_obj_to_json(obj)?;
635
636        let conn = self.conn.lock().unwrap();
637        let table = Self::table_name::<T>();
638
639        // Optimistic locking: increment version and return new value.
640        // Matches Go: `UPDATE ... SET version = version+1 ... RETURNING version`
641        let new_version: i64 = conn.query_row(
642            &format!(
643                "UPDATE {table} SET data = ?1, version = version + 1 WHERE oid = ?2 RETURNING version"
644            ),
645            params![data, oid],
646            |row| row.get(0),
647        )?;
648        self.layout_writes.wrote(T::get_otype());
649
650        obj.set_version(new_version);
651        Ok(new_version)
652    }
653
654    /// Update an object using raw JSON (bypasses struct deserialization).
655    /// Used by UpdateObject where the frontend sends the full replacement object.
656    /// This matches Go's generic map-based UpdateObject behavior.
657    pub fn update_raw(&self, otype: &str, oid: &str, value: &serde_json::Value) -> Result<i64, StoreError> {
658        if oid.is_empty() {
659            return Err(StoreError::EmptyOID);
660        }
661        let data = serde_json::to_vec(value)?;
662        let conn = self.conn.lock().unwrap();
663        let table = format!("db_{}", otype);
664        let new_version: i64 = conn.query_row(
665            &format!(
666                "UPDATE {table} SET data = ?1, version = version + 1 WHERE oid = ?2 RETURNING version"
667            ),
668            params![data, oid],
669            |row| row.get(0),
670        )?;
671        self.layout_writes.wrote(otype);
672        Ok(new_version)
673    }
674
675    /// Delete an object by OID.
676    #[allow(dead_code)]
677    pub fn delete<T: StoreObj>(&self, oid: &str) -> Result<(), StoreError> {
678        let conn = self.conn.lock().unwrap();
679        let table = Self::table_name::<T>();
680        conn.execute(
681            &format!("DELETE FROM {table} WHERE oid = ?1"),
682            params![oid],
683        )?;
684        self.layout_writes.wrote(T::get_otype());
685        Ok(())
686    }
687
688    /// Delete by otype string and OID (for dynamic dispatch).
689    /// Validates `otype` against `VALID_OTYPES` to prevent SQL injection.
690    #[allow(dead_code)]
691    pub fn delete_by_otype(&self, otype: &str, oid: &str) -> Result<(), StoreError> {
692        if !crate::backend::obj::VALID_OTYPES.contains(&otype) {
693            return Err(StoreError::Other(format!("unknown otype: {otype:?}")));
694        }
695        let conn = self.conn.lock().unwrap();
696        let table = format!("db_{otype}");
697        conn.execute(
698            &format!("DELETE FROM {table} WHERE oid = ?1"),
699            params![oid],
700        )?;
701        self.layout_writes.wrote(otype);
702        Ok(())
703    }
704
705    /// Get all objects of a given type.
706    pub fn get_all<T: StoreObj>(&self) -> Result<Vec<T>, StoreError> {
707        let conn = self.conn.lock().unwrap();
708        let table = Self::table_name::<T>();
709        let mut stmt = conn.prepare(&format!("SELECT oid, version, data FROM {table}"))?;
710        let rows = stmt.query_map([], |row| {
711            let version: i64 = row.get(1)?;
712            let data: Vec<u8> = row.get(2)?;
713            Ok((version, data))
714        })?;
715
716        let mut result = Vec::new();
717        for row in rows {
718            let (version, data) = row?;
719            let mut obj: T = mux_obj_from_json(&data)?;
720            obj.set_version(version);
721            result.push(obj);
722        }
723        Ok(result)
724    }
725
726    /// Count objects of a given type.
727    #[allow(dead_code)]
728    pub fn count<T: StoreObj>(&self) -> Result<i64, StoreError> {
729        let conn = self.conn.lock().unwrap();
730        let table = Self::table_name::<T>();
731        let count: i64 =
732            conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |row| {
733                row.get(0)
734            })?;
735        Ok(count)
736    }
737
738    /// Execute multiple operations in a single SQLite transaction.
739    /// Acquires the Mutex once, wraps all operations in BEGIN/COMMIT.
740    /// On error, rolls back and returns the error.
741    ///
742    /// This is the key performance primitive — reduces N lock acquisitions
743    /// and N fsyncs to 1 each.
744    pub fn with_tx<F, R>(&self, f: F) -> Result<R, StoreError>
745    where
746        F: FnOnce(&StoreTx) -> Result<R, StoreError>,
747    {
748        let conn = self.conn.lock().unwrap();
749        conn.execute_batch("BEGIN")?;
750        let tx = StoreTx { conn: &conn, layout_writes: &self.layout_writes };
751        match f(&tx) {
752            Ok(result) => {
753                conn.execute_batch("COMMIT")?;
754                Ok(result)
755            }
756            Err(e) => {
757                let _ = conn.execute_batch("ROLLBACK");
758                Err(e)
759            }
760        }
761    }
762
763    // ── Migration state (db_migrations — shared store only) ──────────────
764
765    pub fn migration_is_applied(&self, id: &str) -> bool {
766        let conn = self.conn.lock().unwrap();
767        conn.query_row(
768            "SELECT 1 FROM db_migrations WHERE id = ?1",
769            [id],
770            |_| Ok(true),
771        )
772        .unwrap_or(false)
773    }
774
775    pub fn migration_mark_applied(
776        &self,
777        id: &str,
778        scope: &str,
779        duration_ms: u64,
780    ) -> Result<(), StoreError> {
781        let now = chrono::Utc::now().to_rfc3339();
782        let conn = self.conn.lock().unwrap();
783        conn.execute(
784            "INSERT OR REPLACE INTO db_migrations (id, applied_at, duration_ms, scope)
785             VALUES (?1, ?2, ?3, ?4)",
786            params![id, now, duration_ms as i64, scope],
787        )?;
788        Ok(())
789    }
790
791    pub fn migrations_list_applied(&self) -> Result<Vec<String>, StoreError> {
792        let conn = self.conn.lock().unwrap();
793        let mut stmt =
794            conn.prepare("SELECT id FROM db_migrations ORDER BY id")?;
795        let ids = stmt
796            .query_map([], |row| row.get(0))?
797            .collect::<Result<Vec<String>, _>>()?;
798        Ok(ids)
799    }
800}
801
802/// A borrowed connection handle for use inside [`Store::with_tx`].
803/// Provides the same CRUD methods as `Store` but operates on the
804/// already-locked connection without additional Mutex acquisition.
805pub struct StoreTx<'a> {
806    conn: &'a Connection,
807    layout_writes: &'a super::user_workspaces::LayoutWrites,
808}
809
810impl<'a> StoreTx<'a> {
811    fn table_name<T: StoreObj>() -> String {
812        format!("db_{}", T::get_otype())
813    }
814
815    /// The locked connection, for sibling modules' own tables
816    /// (`user_workspaces`), written in the same transaction.
817    pub(super) fn raw_conn(&self) -> &Connection {
818        self.conn
819    }
820
821    pub fn get<T: StoreObj>(&self, oid: &str) -> Result<Option<T>, StoreError> {
822        let table = Self::table_name::<T>();
823        let mut stmt =
824            self.conn.prepare(&format!("SELECT version, data FROM {table} WHERE oid = ?1"))?;
825
826        let result = stmt.query_row(params![oid], |row| {
827            let version: i64 = row.get(0)?;
828            let data: Vec<u8> = row.get(1)?;
829            Ok((version, data))
830        });
831
832        match result {
833            Ok((version, data)) => {
834                let mut obj: T = mux_obj_from_json(&data)?;
835                obj.set_version(version);
836                Ok(Some(obj))
837            }
838            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
839            Err(e) => Err(StoreError::Sqlite(e)),
840        }
841    }
842
843    pub fn must_get<T: StoreObj>(&self, oid: &str) -> Result<T, StoreError> {
844        self.get::<T>(oid)?.ok_or(StoreError::NotFound)
845    }
846
847    pub fn insert<T: StoreObj>(&self, obj: &mut T) -> Result<(), StoreError> {
848        let oid = obj.get_oid().to_string();
849        if oid.is_empty() {
850            return Err(StoreError::EmptyOID);
851        }
852
853        obj.set_version(1);
854        let data = mux_obj_to_json(obj)?;
855
856        let table = Self::table_name::<T>();
857        self.conn.execute(
858            &format!("INSERT INTO {table} (oid, version, data) VALUES (?1, 1, ?2)"),
859            params![oid, data],
860        )?;
861        self.layout_writes.wrote(T::get_otype());
862
863        Ok(())
864    }
865
866    pub fn update<T: StoreObj>(&self, obj: &mut T) -> Result<i64, StoreError> {
867        let oid = obj.get_oid().to_string();
868        if oid.is_empty() {
869            return Err(StoreError::EmptyOID);
870        }
871
872        let data = mux_obj_to_json(obj)?;
873
874        let table = Self::table_name::<T>();
875        let new_version: i64 = self.conn.query_row(
876            &format!(
877                "UPDATE {table} SET data = ?1, version = version + 1 WHERE oid = ?2 RETURNING version"
878            ),
879            params![data, oid],
880            |row| row.get(0),
881        )?;
882        self.layout_writes.wrote(T::get_otype());
883
884        obj.set_version(new_version);
885        Ok(new_version)
886    }
887
888    pub fn get_all<T: StoreObj>(&self) -> Result<Vec<T>, StoreError> {
889        let table = Self::table_name::<T>();
890        let mut stmt = self.conn.prepare(&format!("SELECT oid, version, data FROM {table}"))?;
891        let rows = stmt.query_map([], |row| {
892            let version: i64 = row.get(1)?;
893            let data: Vec<u8> = row.get(2)?;
894            Ok((version, data))
895        })?;
896
897        let mut result = Vec::new();
898        for row in rows {
899            let (version, data) = row?;
900            let mut obj: T = mux_obj_from_json(&data)?;
901            obj.set_version(version);
902            result.push(obj);
903        }
904        Ok(result)
905    }
906
907    #[allow(dead_code)]
908    pub fn delete<T: StoreObj>(&self, oid: &str) -> Result<(), StoreError> {
909        let table = Self::table_name::<T>();
910        self.conn.execute(
911            &format!("DELETE FROM {table} WHERE oid = ?1"),
912            params![oid],
913        )?;
914        self.layout_writes.wrote(T::get_otype());
915        Ok(())
916    }
917}
918
919// Re-exports so existing `storage::store::*` imports keep working.
920pub use super::agents::{derive_slug, AgentDefinition, AgentInstance, InstanceStatus};
921pub use super::bundles::Bundle;
922pub use super::content::AgentContent;
923pub use super::skills::AgentSkill;
924
925// Identity system types.
926pub use super::identities::{AgentIdentityLink, IdentityAccount, SecretRef};
927
928
929
930
931// ====================================================================
932// Tests
933// ====================================================================
934
935#[cfg(test)]
936mod tests;