Skip to main content

agentmux_srv_core/backend/
agent_bundle_sidecar.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which bundle is an agent's own bundle (its ABF bundle), across channels
5//! (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.6, phase M4).
6//!
7//! `db_agents.default_memory_id` lives in each channel's object store, so
8//! migration m0021 minted a **new** bundle for an agent in every channel it
9//! ran in — "Name — ABF", "Name — ABF (2)", … in the one shared store. The
10//! id belongs with the agent, but not in `DefinitionRecordV1`: that would
11//! need a schema bump older builds reject. So it goes in a sidecar zone in
12//! the global store, `agent-uid:<uid>:bundle`, holding `{memory_id}`. It was
13//! written when the agent's bundle was provisioned; a new agent has no bundle
14//! now, so this is only read: m0021 binds a recorded bundle (m0047 then moves it into
15//! the agent's picks), and m0046 keeps every recorded bundle when it removes the empty ones
16//! nothing points at.
17
18use serde::{Deserialize, Serialize};
19
20use crate::backend::storage::error::StoreError;
21use crate::backend::storage::filestore::FileStore;
22
23const FILE: &str = "bundle.json";
24
25#[derive(Debug, Default, Serialize, Deserialize)]
26struct Sidecar {
27    #[serde(default)]
28    memory_id: String,
29    #[serde(flatten)]
30    extra: serde_json::Map<String, serde_json::Value>,
31}
32
33fn zone(uid: &str) -> Option<String> {
34    crate::backend::agent_session::is_valid_definition_id(uid).then(|| format!("agent-uid:{uid}:bundle"))
35}
36
37/// The agent's recorded bundle id, if any.
38pub(crate) fn get(fs: &FileStore, uid: &str) -> Result<Option<String>, StoreError> {
39    let Some(zone) = zone(uid) else { return Ok(None) };
40    let Some(bytes) = fs.read_files_consistent(&zone, &[FILE])?.pop().flatten() else { return Ok(None) };
41    let s: Sidecar = serde_json::from_slice(&bytes).map_err(|e| StoreError::Other(format!("bundle sidecar unreadable: {e}")))?;
42    Ok(Some(s.memory_id).filter(|m| !m.is_empty()))
43}
44
45/// Record `memory_id` as the agent's bundle unless one is recorded already, and return the id now
46/// recorded. Nothing records a bundle any more (a new agent has none); the tests use this to set one up.
47#[cfg(test)]
48pub(crate) fn claim(fs: &FileStore, uid: &str, memory_id: &str) -> Result<String, StoreError> {
49    let Some(zone) = zone(uid) else { return Ok(memory_id.to_string()) };
50    fs.zone_txn(&zone, |z| {
51        let mut s: Sidecar = match z.read(FILE)? {
52            Some(b) => serde_json::from_slice(&b).map_err(|e| StoreError::Other(format!("bundle sidecar unreadable: {e}")))?,
53            None => Sidecar::default(),
54        };
55        if s.memory_id.is_empty() {
56            s.memory_id = memory_id.to_string();
57            z.put(FILE, &serde_json::to_vec(&s).map_err(|e| StoreError::Other(e.to_string()))?)?;
58        }
59        Ok(s.memory_id)
60    })
61}
62
63/// The global store, opened directly — for migrations, which run before
64/// srv attaches it. `None` when it can't be resolved or opened.
65pub(crate) fn open_global() -> Option<FileStore> {
66    let dir = crate::registry::resolve_shared_transcripts_dir()?;
67    std::fs::create_dir_all(&dir).ok()?;
68    FileStore::open_global_transcripts(&dir.join("filestore.db")).ok()
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn the_first_recorded_bundle_wins() {
77        let fs = FileStore::open_in_memory().unwrap();
78        assert_eq!(get(&fs, "agent-a").unwrap(), None);
79        assert_eq!(claim(&fs, "agent-a", "b1").unwrap(), "b1");
80        assert_eq!(claim(&fs, "agent-a", "b2").unwrap(), "b1", "another channel's later bundle doesn't replace it");
81        assert_eq!(get(&fs, "agent-a").unwrap().as_deref(), Some("b1"));
82        assert_eq!(get(&fs, "agent-b").unwrap(), None);
83    }
84}