agentmux_srv_core/backend/storage/
bundle_scope.rs1use 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
37fn 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 pub fn bundle_scope_ensure(&self) -> Result<(), StoreError> {
64 let conn = self.conn.lock().unwrap();
65 ensure(&conn)
66 }
67
68 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 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 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 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 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}