Skip to main content

agentmux_srv_core/backend/storage/
bundle_versions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Append-only version history for Global Memory entry content — mirrors
5//! `agent_native_memory_versions.rs`'s shape exactly, adapted for a single
6//! `bundle_id` key instead of that table's composite `(agent_id, filename)`
7//! (a Bundle's identity is already a single id). See
8//! `docs/specs/SPEC_AGENT_FACING_GLOBAL_MEMORY_API_2026_09_15.md` Phase 0 —
9//! Global Memory (`db_bundles`) previously had no audit trail at all, only
10//! `updated_at`; this exists specifically because Global Memory is about to
11//! gain a write path an agent, not just a human in Memory, can reach.
12//!
13//! The WRITE side (`bundle_version_insert`, called via
14//! `Store::bundle_upsert_with_version` in `bundles.rs` on every
15//! `globalmemory.write` AND Memory → Global's own `upsertmemory` save path)
16//! and the READ side (`bundle_version_list`/`bundle_version_get`, called by
17//! `global_memory_history_impl`/`global_memory_diff_impl`/
18//! `global_memory_revert_impl` in `app_api/mod.rs`, backing the
19//! `GlobalMemoryHistory`/`GlobalMemoryDiff`/`GlobalMemoryRevert` MCP tools)
20//! are both wired into the agent-facing MCP surface now — see
21//! `docs/specs/SPEC_AGENT_FACING_GLOBAL_MEMORY_API_2026_09_15.md`. No
22//! Memory pane surface for this yet — that remains out of scope (MCP/REST
23//! only, per that spec's own non-goals).
24
25use rusqlite::params;
26use sha2::{Digest, Sha256};
27
28use super::error::StoreError;
29use super::store::Store;
30
31/// One version of one bundle's Global Memory content, including its full
32/// `name`/`instructions`. Deliberately no serde derives, same as
33/// `NativeMemoryVersion` — a wire type belongs in `rpc_types`, not here.
34#[derive(Debug, Clone, PartialEq)]
35pub struct BundleVersion {
36    pub id: String,
37    pub bundle_id: String,
38    pub name: String,
39    pub instructions: String,
40    pub content_hash: String,
41    pub parent_version_id: Option<String>,
42    pub source: String,
43    pub source_detail: String,
44    /// The TRUSTED writer identity — an agent's own `AGENTMUX_AGENT_ID`
45    /// (unforgeable, stamped server-side by the caller of
46    /// `bundle_upsert_with_version`, never read from caller-supplied
47    /// `source`/`source_detail`) or `"armory-ui"` for a write through the
48    /// human-facing Memory editor. Distinct from `source` on purpose
49    /// (codex P2, PR #3237): `source` is free-form annotation the caller
50    /// can say anything in (an agent could label its own write
51    /// `source: "human"`), so it alone cannot answer "who actually made
52    /// this change" — this field is what a reviewer should trust for that.
53    pub written_by: String,
54    /// Identity M4c-1 (SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md
55    /// §6.5.9): the writer's UID beside `written_by`, taken from the
56    /// request's `Caller` — its `X-Agent-Token` — never from a body field.
57    /// Empty = unknown: an Unattributed write, the Memory pane, a seeder.
58    /// Dual-written; nothing branches on it.
59    pub written_by_uid: String,
60    pub created_at: i64,
61}
62
63/// A version's metadata without its full `name`/`instructions` — the
64/// list-view shape.
65#[derive(Debug, Clone, PartialEq)]
66pub struct BundleVersionSummary {
67    pub id: String,
68    pub content_hash: String,
69    pub parent_version_id: Option<String>,
70    pub source: String,
71    pub source_detail: String,
72    pub written_by: String,
73    /// See [`BundleVersion::written_by_uid`].
74    pub written_by_uid: String,
75    pub created_at: i64,
76    /// The version's instructions' size and estimated tokens
77    /// (`agentmux_common::tokens`); the summary doesn't carry the text.
78    pub size_bytes: u64,
79    pub tokens_est: u64,
80}
81
82use agentmux_common::time::now_ms;
83
84/// Hashes `name` + `instructions` together (not `instructions` alone) —
85/// unlike native memory, where a version's whole identity IS its content, a
86/// bundle's `name` is content too (renaming a Global Memory entry without
87/// touching its body is a real, meaningful edit an operator or agent might
88/// make, and should still produce a new version + a changed hash).
89pub fn content_hash(name: &str, instructions: &str) -> String {
90    let mut hasher = Sha256::new();
91    hasher.update(name.as_bytes());
92    hasher.update(b"\0");
93    hasher.update(instructions.as_bytes());
94    hex::encode(hasher.finalize())
95}
96
97/// Appends a version row within an ALREADY-OPEN transaction — the shared
98/// implementation both `Store::bundle_version_insert` below (opens its own
99/// transaction) and `Store::bundle_upsert_with_version` (`bundles.rs`,
100/// reuses the SAME transaction as its own `db_bundles` write, so the bundle
101/// row and its version can never observably diverge under a concurrent
102/// writer — codex P2, PR #3237) call, rather than duplicating the
103/// parent-chain-lookup + INSERT SQL in two places. `pub(crate)`, not
104/// private: `bundles.rs` is a sibling module in this same crate, not this
105/// one.
106#[allow(clippy::too_many_arguments)]
107pub(crate) fn bundle_version_insert_tx(
108    tx: &rusqlite::Transaction,
109    bundle_id: &str,
110    name: &str,
111    instructions: &str,
112    source: &str,
113    source_detail: &str,
114    written_by: &str,
115    written_by_uid: &str,
116) -> Result<BundleVersion, StoreError> {
117    let id = uuid::Uuid::new_v4().to_string();
118    let hash = content_hash(name, instructions);
119    let created_at = now_ms();
120    let parent_version_id: Option<String> = {
121        let mut stmt = tx.prepare(
122            "SELECT id FROM db_bundle_versions
123             WHERE bundle_id = ?1
124             ORDER BY created_at DESC, rowid DESC
125             LIMIT 1",
126        )?;
127        match stmt.query_row(params![bundle_id], |row| row.get::<_, String>(0)) {
128            Ok(id) => Some(id),
129            Err(rusqlite::Error::QueryReturnedNoRows) => None,
130            Err(e) => return Err(e.into()),
131        }
132    };
133    tx.execute(
134        "INSERT INTO db_bundle_versions
135             (id, bundle_id, name, instructions, content_hash, parent_version_id, source, source_detail, written_by, created_at, written_by_uid)
136         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
137        params![
138            id,
139            bundle_id,
140            name,
141            instructions,
142            hash,
143            parent_version_id,
144            source,
145            source_detail,
146            written_by,
147            created_at,
148            written_by_uid,
149        ],
150    )?;
151
152    Ok(BundleVersion {
153        id,
154        bundle_id: bundle_id.to_string(),
155        name: name.to_string(),
156        instructions: instructions.to_string(),
157        content_hash: hash,
158        parent_version_id,
159        source: source.to_string(),
160        source_detail: source_detail.to_string(),
161        written_by: written_by.to_string(),
162        written_by_uid: written_by_uid.to_string(),
163        created_at,
164    })
165}
166
167impl Store {
168    /// Records a new version for `bundle_id`, chained onto whatever the
169    /// current latest version for this bundle is (`None` for a brand-new
170    /// bundle's first version). Every call records a version, even if
171    /// content is byte-identical to the previous one — same "simplicity
172    /// over cleverness, no dedup-by-hash" posture as
173    /// `agent_native_memory_version_insert`. `BEGIN IMMEDIATE` for the same
174    /// cross-process reason that function's own doc comment gives.
175    ///
176    /// Standalone (not composed with a `db_bundles` write) — kept for
177    /// direct testing and any future caller that only needs to append a
178    /// version without also touching the bundle row itself. Production
179    /// write paths use `Store::bundle_upsert_with_version` (`bundles.rs`)
180    /// instead, which keeps the bundle row and its version atomic.
181    #[cfg(any(test, feature = "test-support"))]
182    pub fn bundle_version_insert(
183        &self,
184        bundle_id: &str,
185        name: &str,
186        instructions: &str,
187        source: &str,
188        source_detail: &str,
189        written_by: &str,
190    ) -> Result<BundleVersion, StoreError> {
191        let mut conn = self.conn.lock().unwrap();
192        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
193        // No `Caller` reaches this standalone path, so no writer UID.
194        let version = bundle_version_insert_tx(&tx, bundle_id, name, instructions, source, source_detail, written_by, "")?;
195        tx.commit()?;
196        Ok(version)
197    }
198
199    /// History for one bundle, newest first — metadata only, no content
200    /// (mirrors `agent_native_memory_version_list`). Not called by the
201    /// Operator Config reseed path — `Store::bundle_reseed_system_if_owned`
202    /// (`bundles.rs`) performs its own inline `SELECT written_by,
203    /// content_hash, source_detail ... LIMIT 1` query instead, so its
204    /// ownership check and the write it gates happen in one transaction
205    /// (see that method's own doc comment for why). Backs the
206    /// `GlobalMemoryHistory` MCP tool (`global_memory_history_impl`,
207    /// `server/app_api/mod.rs`) as of
208    /// SPEC_AGENT_FACING_GLOBAL_MEMORY_API_2026_09_15.md's Phase-3
209    /// follow-up — also still exercised directly by this file's own tests.
210    pub fn bundle_version_list(&self, bundle_id: &str) -> Result<Vec<BundleVersionSummary>, StoreError> {
211        self.bundle_versions_newest_first(bundle_id, -1)
212    }
213
214    /// The newest version of `bundle_id`, if any: one row, for a caller that
215    /// needs only that (Global Memory's write record), not the history's text.
216    pub fn bundle_version_latest(&self, bundle_id: &str) -> Result<Option<BundleVersionSummary>, StoreError> {
217        Ok(self.bundle_versions_newest_first(bundle_id, 1)?.into_iter().next())
218    }
219
220    /// Up to `limit` versions, newest first (`-1`: all of them).
221    fn bundle_versions_newest_first(&self, bundle_id: &str, limit: i64) -> Result<Vec<BundleVersionSummary>, StoreError> {
222        let conn = self.conn.lock().unwrap();
223        let mut stmt = conn.prepare(
224            "SELECT id, content_hash, parent_version_id, source, source_detail, written_by, created_at, written_by_uid, instructions
225             FROM db_bundle_versions
226             WHERE bundle_id = ?1
227             ORDER BY created_at DESC, rowid DESC
228             LIMIT ?2",
229        )?;
230        let rows = stmt
231            .query_map(params![bundle_id, limit], |row| {
232                Ok(BundleVersionSummary {
233                    id: row.get(0)?,
234                    content_hash: row.get(1)?,
235                    parent_version_id: row.get(2)?,
236                    source: row.get(3)?,
237                    source_detail: row.get(4)?,
238                    written_by: row.get(5)?,
239                    created_at: row.get(6)?,
240                    written_by_uid: row.get(7)?,
241                    size_bytes: row.get_ref(8)?.as_str().map_or(0, |c| c.len() as u64),
242                    tokens_est: row.get_ref(8)?.as_str().map_or(0, agentmux_common::tokens::estimate_tokens),
243                })
244            })?
245            .collect::<Result<Vec<_>, _>>()?;
246        Ok(rows)
247    }
248
249    /// One version by id, full content included — the lookup `diff`/`revert`
250    /// build on (mirrors `agent_native_memory_version_get`). Called by
251    /// `global_memory_diff_impl`/`global_memory_revert_impl`
252    /// (`app_api/mod.rs`), which back the `GlobalMemoryDiff`/
253    /// `GlobalMemoryRevert` MCP tools.
254    pub fn bundle_version_get(&self, version_id: &str) -> Result<Option<BundleVersion>, StoreError> {
255        let conn = self.conn.lock().unwrap();
256        let mut stmt = conn.prepare(
257            "SELECT id, bundle_id, name, instructions, content_hash, parent_version_id, source, source_detail, written_by, created_at, written_by_uid
258             FROM db_bundle_versions
259             WHERE id = ?1",
260        )?;
261        match stmt.query_row(params![version_id], |row| {
262            Ok(BundleVersion {
263                id: row.get(0)?,
264                bundle_id: row.get(1)?,
265                name: row.get(2)?,
266                instructions: row.get(3)?,
267                content_hash: row.get(4)?,
268                parent_version_id: row.get(5)?,
269                source: row.get(6)?,
270                source_detail: row.get(7)?,
271                written_by: row.get(8)?,
272                created_at: row.get(9)?,
273                written_by_uid: row.get(10)?,
274            })
275        }) {
276            Ok(v) => Ok(Some(v)),
277            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
278            Err(e) => Err(e.into()),
279        }
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    fn test_store() -> Store {
288        Store::open_shared(std::path::Path::new(":memory:")).unwrap()
289    }
290
291    #[test]
292    fn insert_chains_parent_version_id() {
293        let store = test_store();
294        let v1 = store
295            .bundle_version_insert("bundle-1", "Coding Standards", "use tabs", "agent_inferred", "{}", "agent-1")
296            .unwrap();
297        assert!(v1.parent_version_id.is_none());
298
299        let v2 = store
300            .bundle_version_insert("bundle-1", "Coding Standards", "use spaces", "agent_inferred", "{}", "agent-1")
301            .unwrap();
302        assert_eq!(v2.parent_version_id, Some(v1.id.clone()));
303        assert_ne!(v1.content_hash, v2.content_hash);
304    }
305
306    #[test]
307    fn list_is_newest_first_and_scoped_to_one_bundle() {
308        let store = test_store();
309        store
310            .bundle_version_insert("bundle-a", "A", "content 1", "agent_inferred", "{}", "agent-1")
311            .unwrap();
312        let a2 = store
313            .bundle_version_insert("bundle-a", "A", "content 2", "agent_inferred", "{}", "agent-1")
314            .unwrap();
315        store
316            .bundle_version_insert("bundle-b", "B", "unrelated", "agent_inferred", "{}", "agent-1")
317            .unwrap();
318
319        let history = store.bundle_version_list("bundle-a").unwrap();
320        assert_eq!(history.len(), 2);
321        assert_eq!(history[0].id, a2.id, "newest first");
322    }
323
324    #[test]
325    fn get_returns_full_content_by_id() {
326        let store = test_store();
327        let v = store
328            .bundle_version_insert("bundle-1", "Name", "the body", "human", "{}", "armory-ui")
329            .unwrap();
330        let fetched = store.bundle_version_get(&v.id).unwrap().expect("version exists");
331        assert_eq!(fetched.instructions, "the body");
332        assert_eq!(fetched.bundle_id, "bundle-1");
333        assert_eq!(fetched.written_by, "armory-ui");
334    }
335
336    #[test]
337    fn get_returns_none_for_unknown_id() {
338        let store = test_store();
339        assert!(store.bundle_version_get("does-not-exist").unwrap().is_none());
340    }
341
342    #[test]
343    fn renaming_without_changing_instructions_still_changes_the_hash() {
344        let store = test_store();
345        let v1 = store
346            .bundle_version_insert("bundle-1", "Old Name", "same body", "agent_inferred", "{}", "agent-1")
347            .unwrap();
348        let v2 = store
349            .bundle_version_insert("bundle-1", "New Name", "same body", "agent_inferred", "{}", "agent-1")
350            .unwrap();
351        assert_ne!(v1.content_hash, v2.content_hash, "renaming is a real edit, not a no-op");
352    }
353
354    /// codex P2, PR #3237: `written_by` must reflect the TRUSTED caller
355    /// identity, independent of whatever the caller claims via
356    /// `source`/`source_detail` — an agent could otherwise claim
357    /// `source: "human"` with nothing to contradict it.
358    #[test]
359    fn written_by_is_independent_of_the_caller_supplied_source() {
360        let store = test_store();
361        let v = store
362            .bundle_version_insert("bundle-1", "Name", "body", "human", "{}", "agent-should-not-be-trusted-as-human")
363            .unwrap();
364        assert_eq!(v.source, "human", "source is caller-supplied annotation, kept as-is");
365        assert_eq!(v.written_by, "agent-should-not-be-trusted-as-human", "written_by is the real, separate identity field");
366    }
367}