Skip to main content

agentmux_srv_core/backend/storage/
bundle_scope.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which Global Memory entries follow the fleet
5//! (task #12439, "agents operate other machines", section 4.6).
6//!
7//! An entry's scope is `fleet` (pushed to every proven machine, last write
8//! wins) or `machine` (this machine only). Rows live in `db_bundle_scope`,
9//! beside `db_bundles`, created on first use without a schema bump (like
10//! `db_skill_optout`). An entry with no row is `fleet`, so every new entry
11//! follows the fleet by default.
12//!
13//! The first time the table is created, every entry that exists then gets a
14//! `machine` row: those entries were copied by hand between machines and may
15//! differ on purpose, so a push does not overwrite them silently. Such a row is
16//! a default, not a choice: `chosen` is 0 on it, and 1 on a row an owner set
17//! with [`Store::bundle_scope_set`]. A newer write from the fleet replaces an
18//! entry whose `machine` row was only the default (and the entry then follows
19//! the fleet); a `machine` row an owner chose is never overwritten.
20
21use rusqlite::{params, OptionalExtension};
22
23use crate::migrations::table_exists;
24
25use super::error::StoreError;
26use super::store::Store;
27
28pub const SCOPE_FLEET: &str = "fleet";
29pub const SCOPE_MACHINE: &str = "machine";
30
31const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS db_bundle_scope (
32        bundle_id TEXT PRIMARY KEY,
33        scope TEXT NOT NULL,
34        chosen INTEGER NOT NULL DEFAULT 0
35    );";
36
37/// Create the table if it is missing, marking the entries that already exist as
38/// `machine`, and add the `chosen` column to a table made before it. A no-op
39/// once both are there. Rows that exist when the column is added count as
40/// defaults: only a row set after this build is known to be an owner's choice.
41fn ensure(conn: &rusqlite::Connection) -> Result<(), StoreError> {
42    if table_exists(conn, "db_bundle_scope")? {
43        let has_chosen: i64 =
44            conn.query_row("SELECT COUNT(*) FROM pragma_table_info('db_bundle_scope') WHERE name = 'chosen'", [], |r| r.get(0))?;
45        if has_chosen == 0 {
46            conn.execute_batch("ALTER TABLE db_bundle_scope ADD COLUMN chosen INTEGER NOT NULL DEFAULT 0;")?;
47        }
48        return Ok(());
49    }
50    let tx = conn.unchecked_transaction()?;
51    tx.execute_batch(SCHEMA)?;
52    if table_exists(&tx, "db_bundles")? {
53        tx.execute("INSERT OR IGNORE INTO db_bundle_scope (bundle_id, scope) SELECT id, ?1 FROM db_bundles", params![SCOPE_MACHINE])?;
54    }
55    tx.commit()?;
56    Ok(())
57}
58
59impl Store {
60    /// Create the scope table now, so the entries that exist before this build
61    /// are the ones marked `machine` and not the first ones written after it.
62    /// Call once when the identity store is opened.
63    pub fn bundle_scope_ensure(&self) -> Result<(), StoreError> {
64        let conn = self.conn.lock().unwrap();
65        ensure(&conn)
66    }
67
68    /// The entry's scope: its row, or `fleet` when it has none.
69    pub fn bundle_scope_get(&self, id: &str) -> Result<String, StoreError> {
70        let conn = self.conn.lock().unwrap();
71        ensure(&conn)?;
72        let row: Option<String> = conn
73            .query_row("SELECT scope FROM db_bundle_scope WHERE bundle_id = ?1", params![id], |r| r.get(0))
74            .optional()?;
75        Ok(row.unwrap_or_else(|| SCOPE_FLEET.to_string()))
76    }
77
78    /// The ids of the entries that stay on this machine.
79    pub fn bundle_scope_machine_ids(&self) -> Result<std::collections::HashSet<String>, StoreError> {
80        let conn = self.conn.lock().unwrap();
81        ensure(&conn)?;
82        let mut stmt = conn.prepare("SELECT bundle_id FROM db_bundle_scope WHERE scope = ?1")?;
83        let rows = stmt.query_map(params![SCOPE_MACHINE], |r| r.get::<_, String>(0))?;
84        Ok(rows.collect::<Result<_, _>>()?)
85    }
86
87    /// Set an entry's scope to `fleet` or `machine`, as its owner's choice.
88    pub fn bundle_scope_set(&self, id: &str, scope: &str) -> Result<(), StoreError> {
89        if scope != SCOPE_FLEET && scope != SCOPE_MACHINE {
90            return Err(StoreError::Other(format!("scope must be \"{SCOPE_FLEET}\" or \"{SCOPE_MACHINE}\", not \"{scope}\"")));
91        }
92        let conn = self.conn.lock().unwrap();
93        ensure(&conn)?;
94        conn.execute(
95            "INSERT INTO db_bundle_scope (bundle_id, scope, chosen) VALUES (?1, ?2, 1)
96             ON CONFLICT(bundle_id) DO UPDATE SET scope = excluded.scope, chosen = 1",
97            params![id, scope],
98        )?;
99        Ok(())
100    }
101
102    /// Whether the entry is `machine` only because the scope table was created while it existed,
103    /// and no owner has set it since.
104    pub fn bundle_scope_is_default_machine(&self, id: &str) -> Result<bool, StoreError> {
105        let conn = self.conn.lock().unwrap();
106        ensure(&conn)?;
107        let row: Option<(String, i64)> = conn
108            .query_row("SELECT scope, chosen FROM db_bundle_scope WHERE bundle_id = ?1", params![id], |r| Ok((r.get(0)?, r.get(1)?)))
109            .optional()?;
110        Ok(matches!(row, Some((scope, 0)) if scope == SCOPE_MACHINE))
111    }
112
113    /// Make an entry follow the fleet, without recording it as an owner's choice: the way a
114    /// default `machine` row is lifted when the fleet's newer write replaces the entry.
115    pub fn bundle_scope_follow_fleet(&self, id: &str) -> Result<(), StoreError> {
116        let conn = self.conn.lock().unwrap();
117        ensure(&conn)?;
118        conn.execute(
119            "INSERT INTO db_bundle_scope (bundle_id, scope, chosen) VALUES (?1, ?2, 0)
120             ON CONFLICT(bundle_id) DO UPDATE SET scope = excluded.scope, chosen = 0",
121            params![id, SCOPE_FLEET],
122        )?;
123        Ok(())
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::backend::storage::store::Bundle;
131
132    fn bundle(id: &str) -> Bundle {
133        serde_json::from_value(serde_json::json!({
134            "id": id, "name": id, "instructions": "x", "is_global": true, "mcp_servers": "[]", "skills": "[]",
135        }))
136        .unwrap()
137    }
138
139    #[test]
140    fn entries_that_exist_when_the_table_is_created_stay_on_this_machine_and_new_ones_follow_the_fleet() {
141        let store = Store::open_in_memory().unwrap();
142        store.bundle_upsert(&bundle("old")).unwrap();
143        store.bundle_scope_ensure().unwrap();
144        store.bundle_upsert(&bundle("new")).unwrap();
145
146        assert_eq!(store.bundle_scope_get("old").unwrap(), SCOPE_MACHINE);
147        assert_eq!(store.bundle_scope_get("new").unwrap(), SCOPE_FLEET);
148        assert_eq!(store.bundle_scope_get("never-written").unwrap(), SCOPE_FLEET);
149    }
150
151    #[test]
152    fn ensure_marks_the_existing_entries_once() {
153        let store = Store::open_in_memory().unwrap();
154        store.bundle_scope_ensure().unwrap();
155        store.bundle_upsert(&bundle("later")).unwrap();
156        store.bundle_scope_ensure().unwrap();
157        assert_eq!(store.bundle_scope_get("later").unwrap(), SCOPE_FLEET, "a second ensure must not mark it");
158    }
159
160    #[test]
161    fn a_machine_row_made_by_the_migration_is_a_default_and_one_an_owner_sets_is_a_choice() {
162        let store = Store::open_in_memory().unwrap();
163        store.bundle_upsert(&bundle("old")).unwrap();
164        store.bundle_upsert(&bundle("kept")).unwrap();
165        store.bundle_scope_ensure().unwrap();
166        store.bundle_scope_set("kept", SCOPE_MACHINE).unwrap();
167
168        assert!(store.bundle_scope_is_default_machine("old").unwrap());
169        assert!(!store.bundle_scope_is_default_machine("kept").unwrap(), "the owner chose it");
170        assert!(!store.bundle_scope_is_default_machine("never-written").unwrap(), "no row is fleet, not a default machine row");
171
172        store.bundle_scope_follow_fleet("old").unwrap();
173        assert_eq!(store.bundle_scope_get("old").unwrap(), SCOPE_FLEET);
174        assert!(!store.bundle_scope_is_default_machine("old").unwrap());
175    }
176
177    #[test]
178    fn a_table_made_before_the_chosen_column_gets_it_and_its_rows_count_as_defaults() {
179        let store = Store::open_in_memory().unwrap();
180        {
181            let conn = store.conn.lock().unwrap();
182            conn.execute_batch(
183                "CREATE TABLE db_bundle_scope (bundle_id TEXT PRIMARY KEY, scope TEXT NOT NULL);
184                 INSERT INTO db_bundle_scope VALUES ('a', 'machine'), ('b', 'fleet');",
185            )
186            .unwrap();
187        }
188        assert!(store.bundle_scope_is_default_machine("a").unwrap());
189        assert_eq!(store.bundle_scope_get("b").unwrap(), SCOPE_FLEET);
190        store.bundle_scope_set("a", SCOPE_MACHINE).unwrap();
191        assert!(!store.bundle_scope_is_default_machine("a").unwrap());
192    }
193
194    #[test]
195    fn the_scope_can_be_flipped_and_only_two_values_are_accepted() {
196        let store = Store::open_in_memory().unwrap();
197        store.bundle_upsert(&bundle("a")).unwrap();
198        store.bundle_scope_set("a", SCOPE_MACHINE).unwrap();
199        assert_eq!(store.bundle_scope_get("a").unwrap(), SCOPE_MACHINE);
200        store.bundle_scope_set("a", SCOPE_FLEET).unwrap();
201        assert_eq!(store.bundle_scope_get("a").unwrap(), SCOPE_FLEET);
202        assert!(store.bundle_scope_set("a", "everywhere").is_err());
203    }
204}