Skip to main content

agentmux_srv_core/backend/storage/
agent_bundles.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's Bundles list: the bundles picked for it, in order
5//! (`SPEC_RENAME_KNOWLEDGE_TO_MEMORY_2026_10_06.md` ยง3.6).
6//!
7//! This list is all an agent has: there is no bundle of its own in front of
8//! it (`REPORT_AGENT_BUNDLES_REFINE_OR_DROP_2026_11_03.md`; `m0047` moved
9//! any that existed into the picks). The table is per channel (#3148);
10//! bundles themselves live in the identity store, so a listed id can name a
11//! bundle deleted elsewhere, and readers skip it.
12//!
13//! The Stash's old Startup tab stored one bundle as `startup_bundle_id`
14//! agent content. Reading the list folds that pick in and removes it, which
15//! covers existing agents and one an older build writes later.
16
17use rusqlite::params;
18
19use super::bundles::{Bundle, GLOBAL_SECTION_SEPARATOR};
20use super::error::StoreError;
21use super::store::Store;
22
23/// The agent content type the old Startup tab stored its one bundle under.
24pub const STARTUP_BUNDLE_CONTENT_TYPE: &str = "startup_bundle_id";
25
26impl Store {
27    /// The bundles picked for `agent_id`, in order.
28    pub fn agent_bundle_ids(&self, agent_id: &str) -> Result<Vec<String>, StoreError> {
29        self.agent_bundles_fold_startup_pick(agent_id);
30        self.agent_bundle_ids_stored(agent_id)
31    }
32
33    /// Append an old Startup-tab pick to the list, then remove it. Best
34    /// effort: on a failure the pick stays, to be folded on a later read.
35    fn agent_bundles_fold_startup_pick(&self, agent_id: &str) {
36        let Ok(Some(content)) = self.agent_content_get(agent_id, STARTUP_BUNDLE_CONTENT_TYPE) else {
37            return;
38        };
39        let pick = content.content.trim().to_string();
40        if !pick.is_empty() {
41            let mut ids = self.agent_bundle_ids_stored(agent_id).unwrap_or_default();
42            if !ids.contains(&pick) {
43                ids.push(pick);
44                if let Err(e) = self.agent_bundles_set(agent_id, &ids) {
45                    tracing::warn!(agent_id, error = %e, "agent bundles: Startup pick not folded in");
46                    return;
47                }
48            }
49        }
50        let _ = self.agent_content_delete(agent_id, STARTUP_BUNDLE_CONTENT_TYPE);
51    }
52
53    fn agent_bundle_ids_stored(&self, agent_id: &str) -> Result<Vec<String>, StoreError> {
54        let conn = self.conn.lock().unwrap();
55        let mut stmt = conn.prepare(
56            "SELECT bundle_id FROM db_agent_bundles WHERE agent_id = ?1 ORDER BY position",
57        )?;
58        let rows = stmt.query_map(params![agent_id], |row| row.get::<_, String>(0))?;
59        Ok(rows.collect::<Result<_, _>>()?)
60    }
61
62    /// Replace `agent_id`'s picks with `bundle_ids`, in that order. Blank ids
63    /// and repeats are dropped. Returns what was stored.
64    pub fn agent_bundles_set(
65        &self,
66        agent_id: &str,
67        bundle_ids: &[String],
68    ) -> Result<Vec<String>, StoreError> {
69        let mut picks: Vec<String> = Vec::new();
70        for id in bundle_ids.iter().map(|id| id.trim()) {
71            if !id.is_empty() && !picks.iter().any(|p| p == id) {
72                picks.push(id.to_string());
73            }
74        }
75        let mut conn = self.conn.lock().unwrap();
76        let tx = conn.transaction()?;
77        tx.execute("DELETE FROM db_agent_bundles WHERE agent_id = ?1", params![agent_id])?;
78        for (position, id) in picks.iter().enumerate() {
79            tx.execute(
80                "INSERT INTO db_agent_bundles (agent_id, bundle_id, position) VALUES (?1, ?2, ?3)",
81                params![agent_id, id, position as i64],
82            )?;
83        }
84        tx.commit()?;
85        Ok(picks)
86    }
87
88    /// Take a deleted bundle out of every agent's list. Returns the rows removed.
89    pub fn agent_bundles_forget_bundle(&self, bundle_id: &str) -> Result<usize, StoreError> {
90        let conn = self.conn.lock().unwrap();
91        Ok(conn.execute("DELETE FROM db_agent_bundles WHERE bundle_id = ?1", params![bundle_id])?)
92    }
93}
94
95/// The picked bundles' part of the startup file: one `# [Bundle] <name>`
96/// section per bundle with instructions, in list order, joined by the rule
97/// Global Memory uses. `bundles` are the picks as found (a deleted one is
98/// already missing). Empty when none has instructions.
99pub fn format_agent_bundle_block(bundles: &[Bundle]) -> String {
100    bundles
101        .iter()
102        .filter(|b| !b.instructions.trim().is_empty())
103        .map(|b| format!("# [Bundle] {}\n\n{}", b.name, b.instructions))
104        .collect::<Vec<_>>()
105        .join(GLOBAL_SECTION_SEPARATOR)
106}
107
108/// The bundles picked for `agent_id` (from `mstore`), looked up in
109/// `bundle_store`, in list order. A bundle that no longer exists is skipped.
110pub fn agent_picked_bundles(mstore: &Store, bundle_store: &Store, agent_id: &str) -> Vec<Bundle> {
111    mstore
112        .agent_bundle_ids(agent_id)
113        .unwrap_or_default()
114        .iter()
115        .filter_map(|id| match bundle_store.bundle_get(id) {
116            Ok(Some(bundle)) => Some(bundle),
117            Ok(None) => {
118                tracing::debug!(agent_id, bundle_id = %id, "agent bundles: skipping a bundle that no longer exists");
119                None
120            }
121            Err(e) => {
122                tracing::warn!(agent_id, bundle_id = %id, error = %e, "agent bundles: bundle lookup failed");
123                None
124            }
125        })
126        .collect()
127}
128
129/// The text launch puts after `# Memory` in the startup file: Global Memory,
130/// then the agent's picked bundles, each part only when it has content.
131pub fn join_startup_blocks(global_block: &str, agent_block: &str) -> String {
132    [global_block, agent_block]
133        .into_iter()
134        .filter(|b| !b.is_empty())
135        .collect::<Vec<_>>()
136        .join(GLOBAL_SECTION_SEPARATOR)
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::backend::storage::agents::test_agent_def;
143
144    fn bundle(id: &str, name: &str, instructions: &str) -> Bundle {
145        Bundle {
146            id: id.into(),
147            name: name.into(),
148            description: String::new(),
149            is_blank: false,
150            is_global: false,
151            provider: String::new(),
152            model: String::new(),
153            instructions: instructions.into(),
154            instructions_by_provider: "{}".into(),
155            context_files: "[]".into(),
156            mcp_servers: "[]".into(),
157            skills: "[]".into(),
158            sort_order: 0,
159            created_at: 0,
160            updated_at: 0,
161            is_system: false,
162        }
163    }
164
165    fn store_with_agent() -> Store {
166        let s = Store::open_in_memory().unwrap();
167        let mut def = test_agent_def("a1", "a1", "claude", "agent", 1, "");
168        s.agent_def_insert(&mut def).unwrap();
169        s
170    }
171
172    fn ids(v: &[&str]) -> Vec<String> {
173        v.iter().map(|s| s.to_string()).collect()
174    }
175
176    #[test]
177    fn set_keeps_order_and_drops_blanks_and_repeats() {
178        let s = store_with_agent();
179        let stored = s.agent_bundles_set("a1", &ids(&["b2", "", "b1", "b2", " b3 "])).unwrap();
180        assert_eq!(stored, ids(&["b2", "b1", "b3"]));
181        assert_eq!(s.agent_bundle_ids("a1").unwrap(), stored);
182        // Replacing, not appending.
183        s.agent_bundles_set("a1", &ids(&["b1"])).unwrap();
184        assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["b1"]));
185        assert!(s.agent_bundle_ids("nobody").unwrap().is_empty());
186    }
187
188    fn set_startup_pick(s: &Store, id: &str) {
189        s.agent_content_set(&crate::backend::storage::content::AgentContent {
190            agent_id: "a1".into(),
191            content_type: STARTUP_BUNDLE_CONTENT_TYPE.into(),
192            content: id.into(),
193            updated_at: 1,
194        })
195        .unwrap();
196    }
197
198    #[test]
199    fn an_old_startup_pick_is_folded_into_the_list_once() {
200        let s = store_with_agent();
201        s.agent_bundles_set("a1", &ids(&["b1"])).unwrap();
202        set_startup_pick(&s, "b2");
203        assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["b1", "b2"]));
204        assert!(s.agent_content_get("a1", STARTUP_BUNDLE_CONTENT_TYPE).unwrap().is_none());
205        // Removing it afterwards sticks: the pick is gone, not re-folded.
206        s.agent_bundles_set("a1", &ids(&["b1"])).unwrap();
207        assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["b1"]));
208        // Already listed, or blank: nothing added.
209        for pick in ["b1", " "] {
210            set_startup_pick(&s, pick);
211            assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["b1"]), "pick {pick:?}");
212            assert!(s.agent_content_get("a1", STARTUP_BUNDLE_CONTENT_TYPE).unwrap().is_none());
213        }
214        // The launch path reads through the fold too.
215        set_startup_pick(&s, "b3");
216        assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["b1", "b3"]));
217    }
218
219    /// `agentdefcreatefromtemplate`'s order: the definition is inserted, then
220    /// its picks are stored, and every pick stays listed (#4434).
221    #[test]
222    fn a_new_agents_picks_stay_listed() {
223        let s = Store::open_in_memory().unwrap();
224        s.bundle_upsert(&bundle("shared", "Shared", "shared rules")).unwrap();
225        let mut def = test_agent_def("a1", "a1", "claude", "agent", 1, "");
226        s.agent_def_insert(&mut def).unwrap();
227        s.agent_bundles_set("a1", &ids(&["shared"])).unwrap();
228        assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["shared"]));
229    }
230
231    #[test]
232    fn a_deleted_bundle_leaves_every_list() {
233        let s = store_with_agent();
234        let mut other = test_agent_def("a2", "a2", "claude", "agent", 1, "");
235        s.agent_def_insert(&mut other).unwrap();
236        s.agent_bundles_set("a1", &ids(&["gone", "b1"])).unwrap();
237        s.agent_bundles_set("a2", &ids(&["gone"])).unwrap();
238        assert_eq!(s.agent_bundles_forget_bundle("gone").unwrap(), 2);
239        assert_eq!(s.agent_bundle_ids("a1").unwrap(), ids(&["b1"]));
240        assert!(s.agent_bundle_ids("a2").unwrap().is_empty());
241    }
242
243    #[test]
244    fn deleting_the_agent_deletes_its_list() {
245        let s = store_with_agent();
246        s.agent_bundles_set("a1", &ids(&["b1"])).unwrap();
247        assert!(s.agent_def_delete("a1").unwrap());
248        assert!(s.agent_bundle_ids("a1").unwrap().is_empty());
249    }
250
251    #[test]
252    fn picked_bundles_skip_a_missing_one_and_keep_order() {
253        let s = store_with_agent();
254        s.bundle_upsert(&bundle("b1", "One", "first")).unwrap();
255        s.bundle_upsert(&bundle("b2", "Two", "second")).unwrap();
256        s.agent_bundles_set("a1", &ids(&["b2", "gone", "b1"])).unwrap();
257        let names: Vec<String> = agent_picked_bundles(&s, &s, "a1").into_iter().map(|b| b.name).collect();
258        assert_eq!(names, ids(&["Two", "One"]));
259    }
260
261    #[test]
262    fn the_block_has_one_section_per_bundle_with_instructions() {
263        let block = format_agent_bundle_block(&[
264            bundle("b1", "One", "first"),
265            bundle("b2", "Empty", "  "),
266            bundle("b3", "Three", "third"),
267        ]);
268        assert_eq!(block, "# [Bundle] One\n\nfirst\n\n---\n\n# [Bundle] Three\n\nthird");
269        assert!(format_agent_bundle_block(&[bundle("b2", "Empty", "")]).is_empty());
270    }
271
272    #[test]
273    fn startup_blocks_join_only_what_has_content() {
274        assert_eq!(join_startup_blocks("G", "B"), "G\n\n---\n\nB");
275        assert_eq!(join_startup_blocks("", "B"), "B");
276        assert_eq!(join_startup_blocks("G", ""), "G");
277        assert_eq!(join_startup_blocks("", ""), "");
278    }
279}