Skip to main content

agentmux_srv_core/backend/storage/
bundles.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bundles — the agent's personality and capability stack
5//! (provider, model, instructions, context files, MCP servers, skills).
6//!
7//! Extracted from `store.rs` in Phase R.3 of the storage
8//! modularization plan
9//! (`docs/specs/SPEC_STORE_MODULARIZATION_2026_05_27.md`). The
10//! method surface is unchanged — `Store::bundle_*` still
11//! lives on `Store` via this `impl` block; callers stay on
12//! `storage::store::Bundle` thanks to the re-export.
13
14use rusqlite::{params, OptionalExtension};
15use serde::{Deserialize, Serialize};
16
17use super::bundle_versions::{bundle_version_insert_tx, BundleVersion};
18use super::error::StoreError;
19use super::store::Store;
20
21/// A Bundle — the agent's personality and capability stack.
22/// Provider, model, instructions, and JSON-encoded arrays of context
23/// files / MCP servers / skills. Agent definitions shadow-migrate into this
24/// table during the v7 migration.
25#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
26#[ts(export, export_to = "../../../frontend/types/rpc/")]
27pub struct Bundle {
28    pub id: String,
29    pub name: String,
30    #[serde(default)]
31    pub description: String,
32    #[serde(default)]
33    pub is_blank: bool,
34    /// Global bundles are injected into every agent's CLAUDE.md at launch,
35    /// regardless of per-agent memory selection. Managed in Memory → Global.
36    /// Seeded from workspace-wide rule sets.
37    #[serde(default)]
38    pub is_global: bool,
39    /// "claude" | "codex" | "gemini" | empty string
40    #[serde(default)]
41    pub provider: String,
42    #[serde(default)]
43    pub model: String,
44    #[serde(default)]
45    pub instructions: String,
46    /// JSON-encoded object of `{provider_id: content}` — additive,
47    /// harness-scoped instruction variants alongside the flat
48    /// `instructions` column above (which keeps meaning "default"). ABF v0.2
49    /// §2.2; see SPEC_ABF_V0_2_PROVIDER_AWARE_COMPONENTS_AND_NATIVE_MEMORY_2026_08_10.md.
50    #[serde(default = "default_json_object_string")]
51    pub instructions_by_provider: String,
52    /// JSON-encoded array; the renderer types it as `[{path, content}]`.
53    #[serde(default = "default_json_array_string")]
54    pub context_files: String,
55    /// Always `"[]"`: a bundle carries no MCP servers
56    /// (`SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md` §3.1). Kept on
57    /// the wire for older clients; see [`NO_INLINE_MCP_SERVERS`].
58    #[serde(default = "default_json_array_string")]
59    pub mcp_servers: String,
60    /// JSON-encoded array of skill IDs.
61    #[serde(default = "default_json_array_string")]
62    pub skills: String,
63    /// Explicit ordering within Memory → Global. Lower sorts
64    /// first; this is the order sections inject into CLAUDE.md at launch.
65    /// Only meaningful for `is_global` bundles; 0 for the rest. Owned by the
66    /// `reorderglobalbrain` RPC — `bundle_upsert` never overwrites it
67    /// on conflict, so editing a bundle via the regular form keeps its place.
68    #[serde(default)]
69    #[ts(type = "number")]
70    pub sort_order: i64,
71    /// AgentMux-controlled, highest-priority Global Bundle tier — always
72    /// also `is_global`, injected first in `format_global_bundle_block`'s
73    /// output with explicit override wording. Writable ONLY through
74    /// `bundle_upsert_system`/`bundle_delete_system` — the
75    /// generic `bundle_upsert`/`_delete`/`_reorder` all refuse to
76    /// touch a row with this set. See
77    /// docs/specs/SPEC_GLOBAL_MEMORY_SYSTEM_TIER_2026_08_24.md.
78    #[serde(default)]
79    pub is_system: bool,
80    // created_at / updated_at are server-owned: the upsert handler stamps
81    // created_at = now when 0 and always overwrites updated_at with now. They
82    // default on input so partial upserts (e.g. a "new section" that only
83    // sends id/name/instructions) deserialize cleanly. (reagent P0 on #1608)
84    #[serde(default)]
85    #[ts(type = "number")]
86    pub created_at: i64,
87    #[serde(default)]
88    #[ts(type = "number")]
89    pub updated_at: i64,
90}
91
92fn default_json_array_string() -> String {
93    "[]".to_string()
94}
95
96/// The one statement that writes a user-tier row, for every method that does: on the caller's
97/// connection or inside its transaction, after the caller's own guard.
98///
99/// `sort_order` is deliberately NOT in the ON CONFLICT update set: it is owned by
100/// `bundle_reorder`, so editing a bundle through the regular Bundle form never disturbs its
101/// position in the global bundles. `is_system` is hardcoded to 0 on insert (this path can never
102/// CREATE a system row) and omitted from the update set entirely (an existing row's tier, always
103/// 0 given the callers' guard, is never touched here either).
104fn write_user_row(conn: &rusqlite::Connection, memory: &Bundle) -> rusqlite::Result<usize> {
105    conn.execute(
106        "INSERT INTO db_bundles
107            (id, name, description, is_blank, is_global, provider, model, instructions,
108             context_files, mcp_servers, skills, sort_order, created_at, updated_at,
109             instructions_by_provider, is_system)
110         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, 0)
111         ON CONFLICT(id) DO UPDATE SET
112            name = excluded.name,
113            description = excluded.description,
114            is_global = excluded.is_global,
115            provider = excluded.provider,
116            model = excluded.model,
117            instructions = excluded.instructions,
118            context_files = excluded.context_files,
119            mcp_servers = excluded.mcp_servers,
120            skills = excluded.skills,
121            updated_at = excluded.updated_at,
122            instructions_by_provider = excluded.instructions_by_provider",
123        params![
124            memory.id,
125            memory.name,
126            memory.description,
127            memory.is_blank as i64,
128            memory.is_global as i64,
129            memory.provider,
130            memory.model,
131            memory.instructions,
132            memory.context_files,
133            NO_INLINE_MCP_SERVERS,
134            memory.skills,
135            memory.sort_order,
136            memory.created_at,
137            memory.updated_at,
138            memory.instructions_by_provider,
139        ],
140    )
141}
142
143/// The one statement that writes a system-tier row, for every method that does: on the caller's
144/// connection or inside its transaction, after the caller's own guard. The row is global, system
145/// and not blank whatever `memory` says, on insert and on update.
146fn write_system_row(conn: &rusqlite::Connection, memory: &Bundle) -> rusqlite::Result<usize> {
147    conn.execute(
148        "INSERT INTO db_bundles
149            (id, name, description, is_blank, is_global, provider, model, instructions,
150             context_files, mcp_servers, skills, sort_order, created_at, updated_at,
151             instructions_by_provider, is_system)
152         VALUES (?1, ?2, ?3, 0, 1, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, 1)
153         ON CONFLICT(id) DO UPDATE SET
154            name = excluded.name,
155            description = excluded.description,
156            is_global = 1,
157            is_system = 1,
158            provider = excluded.provider,
159            model = excluded.model,
160            instructions = excluded.instructions,
161            context_files = excluded.context_files,
162            mcp_servers = excluded.mcp_servers,
163            skills = excluded.skills,
164            updated_at = excluded.updated_at,
165            instructions_by_provider = excluded.instructions_by_provider",
166        params![
167            memory.id,
168            memory.name,
169            memory.description,
170            memory.provider,
171            memory.model,
172            memory.instructions,
173            memory.context_files,
174            NO_INLINE_MCP_SERVERS,
175            memory.skills,
176            memory.sort_order,
177            memory.created_at,
178            memory.updated_at,
179            memory.instructions_by_provider,
180        ],
181    )
182}
183
184/// The base check behind `bundle_upsert_with_version_based` /
185/// `bundle_upsert_system_if_changed_based`, run inside the caller's own
186/// transaction so nothing can land between the check and the write.
187fn check_bundle_base_tx(tx: &rusqlite::Transaction, id: &str, base: &str) -> Result<(), StoreError> {
188    let current: Option<(String, String)> = tx
189        .query_row(
190            "SELECT name, instructions FROM db_bundles WHERE id = ?1",
191            params![id],
192            |r| Ok((r.get(0)?, r.get(1)?)),
193        )
194        .optional()?;
195    match current {
196        None => Err(StoreError::Conflict(format!(
197            "Global Memory entry {id} no longer exists (your edit was based on {base}); not saved"
198        ))),
199        Some((name, instructions)) => {
200            let current_hash = super::bundle_versions::content_hash(&name, &instructions);
201            if current_hash.eq_ignore_ascii_case(base) {
202                Ok(())
203            } else {
204                Err(StoreError::Conflict(format!(
205                    "Global Memory entry {id} changed since your edit began (base {base}, current {current_hash}); not saved"
206                )))
207            }
208        }
209    }
210}
211
212/// Outcome of `Store::bundle_reseed_system_if_owned` — see that method's own
213/// doc comment for what each variant means and why the decision is made
214/// atomically rather than by the caller.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub enum BundleReseedOutcome {
217    Created,
218    Updated,
219    Unchanged,
220    SkippedLocalEdit,
221    /// This write's manifest generation (see `manifest_generation_from_
222    /// source_detail`) is older than the generation already recorded for
223    /// this row — an older AgentMux process must never downgrade a newer
224    /// seed. See `bundle_reseed_system_if_owned`'s own doc comment.
225    SkippedOlderGeneration,
226    /// The row doesn't exist, but a retirement tombstone (`RETIREMENT_
227    /// TOMBSTONE_SOURCE`) recorded by a newer manifest generation says it
228    /// was deliberately pruned — this caller's own (older) manifest must
229    /// not resurrect it. See `bundle_reseed_system_if_owned`'s own doc
230    /// comment.
231    SkippedRetired,
232}
233
234/// The `source` sentinel `bundle_delete_system_if_owned` stamps on the
235/// tombstone version row it appends after deleting a row — distinguishes a
236/// deliberate, generation-aware retirement (pruned because a manifest no
237/// longer lists this id) from an ordinary human delete in Memory
238/// (`bundle_delete_system`, which records no version at all). `bundle_
239/// reseed_system_if_owned`'s missing-row branch checks for this sentinel
240/// specifically — see that method's own doc comment.
241const RETIREMENT_TOMBSTONE_SOURCE: &str = "operator_config_seed_retired";
242
243/// The `source` of the version an entry gets when it leaves Global Memory: the
244/// content it held and the writer who removed it, so history can show the
245/// removal and a revert can bring the entry back.
246pub const REMOVE_SOURCE: &str = "remove";
247
248/// Extracts a `{"manifest_version": N}` field from a version row's
249/// `source_detail` JSON, defaulting to `0` when absent or unparseable — so a
250/// pre-existing row seeded before this field existed is always treated as
251/// generation 0, never blocking a real (>=1) manifest generation from
252/// writing over it. Shared convention between `bundle_reseed_system_if_
253/// owned`'s own generation guard and any seeder populating `source_detail`
254/// (see `operator_config_seed.rs`).
255fn manifest_generation_from_source_detail(source_detail: &str) -> u64 {
256    serde_json::from_str::<serde_json::Value>(source_detail)
257        .ok()
258        .and_then(|v| v.get("manifest_version").and_then(|g| g.as_u64()))
259        .unwrap_or(0)
260}
261
262fn default_json_object_string() -> String {
263    "{}".to_string()
264}
265
266/// Format global bundles into the block injected into an agent's
267/// CLAUDE.md. `is_system` sections (see `Bundle::is_system`) are split out
268/// and rendered FIRST, wrapped in explicit override wording, so they
269/// outrank every ordinary `# [Workspace] <name>` section that follows —
270/// see docs/specs/SPEC_GLOBAL_MEMORY_SYSTEM_TIER_2026_08_24.md §3.4. Bundles
271/// arrive already ordered by `bundle_list_global` (is_system DESC,
272/// sort_order, name), so this only needs to partition, not re-sort.
273/// Sections are separated by a `---` rule ([`GLOBAL_SECTION_SEPARATOR`]).
274/// Returns an empty string when no section has instructions.
275///
276/// Exactly [`global_bundle_sections`] joined by the separator: memory
277/// reinjection sends those same sections, so what it re-delivers is this
278/// block byte for byte (SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P1).
279pub fn format_global_bundle_block(bundles: &[Bundle]) -> String {
280    global_bundle_sections(bundles)
281        .into_iter()
282        .map(|s| s.text)
283        .collect::<Vec<_>>()
284        .join(GLOBAL_SECTION_SEPARATOR)
285}
286
287/// The rule between two sections of the Global Memory block.
288pub const GLOBAL_SECTION_SEPARATOR: &str = "\n\n---\n\n";
289
290/// The override wording that opens the system (`is_system`) part of the block.
291const SYSTEM_TIER_PREAMBLE: &str = "IMPORTANT: The following AgentMux-controlled instructions take \
292     the HIGHEST PRIORITY of any content in this file. They OVERRIDE \
293     any default behavior, any other section below, and any \
294     conflicting instruction elsewhere — you MUST follow them \
295     exactly as written.";
296
297/// One section of the Global Memory block: one global bundle with
298/// instructions, rendered as the startup file carries it.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
300#[ts(export, export_to = "../../../frontend/types/rpc/")]
301pub struct GlobalMemorySection {
302    /// The Global Memory entry's id (the bundle id).
303    pub id: String,
304    pub name: String,
305    pub is_system: bool,
306    /// `# [AgentMux System] <name>` or `# [Workspace] <name>`, a blank line,
307    /// then the instructions. The first system section also opens with the
308    /// override preamble.
309    pub text: String,
310    /// `text`'s length in bytes: what this section adds to an injection.
311    #[ts(type = "number")]
312    pub size_bytes: u64,
313    /// `text`'s estimated tokens (`agentmux_common::tokens`).
314    #[ts(type = "number")]
315    pub tokens_est: u64,
316}
317
318/// The sections of the Global Memory block, system (`is_system`) first, each
319/// in the order `bundle_list_global` returns them. Bundles with no
320/// instructions are skipped.
321pub fn global_bundle_sections(bundles: &[Bundle]) -> Vec<GlobalMemorySection> {
322    let non_empty = bundles.iter().filter(|b| !b.instructions.trim().is_empty());
323    let (system, ordinary): (Vec<&Bundle>, Vec<&Bundle>) = non_empty.partition(|b| b.is_system);
324    let section = |b: &Bundle, text: String| GlobalMemorySection {
325        id: b.id.clone(),
326        name: b.name.clone(),
327        is_system: b.is_system,
328        size_bytes: text.len() as u64,
329        tokens_est: agentmux_common::tokens::estimate_tokens(&text),
330        text,
331    };
332    let system = system.into_iter().enumerate().map(|(i, b)| {
333        let body = format!("# [AgentMux System] {}\n\n{}", b.name, b.instructions);
334        section(b, if i == 0 { format!("{SYSTEM_TIER_PREAMBLE}\n\n{body}") } else { body })
335    });
336    let ordinary = ordinary
337        .into_iter()
338        .map(|b| section(b, format!("# [Workspace] {}\n\n{}", b.name, b.instructions)));
339    system.chain(ordinary).collect()
340}
341
342impl Store {
343    pub fn bundle_list(&self) -> Result<Vec<Bundle>, StoreError> {
344        let conn = self.conn.lock().unwrap();
345        let mut stmt = conn.prepare(
346            "SELECT id, name, description, is_blank, is_global, provider, model, instructions,
347                    context_files, mcp_servers, skills, sort_order, created_at, updated_at,
348                    instructions_by_provider, is_system
349             FROM db_bundles
350             ORDER BY is_blank ASC, is_global DESC, updated_at DESC",
351        )?;
352        let iter = stmt.query_map([], map_memory_row)?;
353        let mut out = Vec::new();
354        for r in iter {
355            out.push(r?);
356        }
357        Ok(out)
358    }
359
360    /// Returns only the global bundles (`is_global = 1`), `is_system` rows
361    /// first (regardless of `sort_order` — see
362    /// docs/specs/SPEC_GLOBAL_MEMORY_SYSTEM_TIER_2026_08_24.md), then by
363    /// explicit `sort_order` (then name as a stable tiebreak). Called at
364    /// agent launch to inject workspace-wide rules into every agent in the
365    /// order the user arranged them in Memory → Global.
366    pub fn bundle_list_global(&self) -> Result<Vec<Bundle>, StoreError> {
367        let conn = self.conn.lock().unwrap();
368        let mut stmt = conn.prepare(
369            "SELECT id, name, description, is_blank, is_global, provider, model, instructions,
370                    context_files, mcp_servers, skills, sort_order, created_at, updated_at,
371                    instructions_by_provider, is_system
372             FROM db_bundles
373             WHERE is_global = 1
374             ORDER BY is_system DESC, sort_order ASC, name ASC",
375        )?;
376        let iter = stmt.query_map([], map_memory_row)?;
377        let mut out = Vec::new();
378        for r in iter {
379            out.push(r?);
380        }
381        Ok(out)
382    }
383
384    /// Ordinary entries that were removed from Global Memory and can be
385    /// restored: not global now, and their newest version is a
386    /// [`REMOVE_SOURCE`] one. A private bundle that was never Global Memory
387    /// has no versions and never appears. Most recently removed first.
388    pub fn bundle_list_removed_global(&self) -> Result<Vec<Bundle>, StoreError> {
389        let conn = self.conn.lock().unwrap();
390        let mut stmt = conn.prepare(
391            "SELECT b.id, b.name, b.description, b.is_blank, b.is_global, b.provider, b.model, b.instructions,
392                    b.context_files, b.mcp_servers, b.skills, b.sort_order, b.created_at, b.updated_at,
393                    b.instructions_by_provider, b.is_system
394             FROM db_bundles b
395             WHERE b.is_global = 0 AND b.is_system = 0 AND b.is_blank = 0 AND b.id != 'blank'
396               AND (SELECT v.source FROM db_bundle_versions v WHERE v.bundle_id = b.id
397                    ORDER BY v.created_at DESC, v.rowid DESC LIMIT 1) = ?1
398             ORDER BY b.updated_at DESC",
399        )?;
400        let iter = stmt.query_map(params![REMOVE_SOURCE], map_memory_row)?;
401        let mut out = Vec::new();
402        for r in iter {
403            out.push(r?);
404        }
405        Ok(out)
406    }
407
408    /// Whether `id` was removed from Global Memory and not restored since: its
409    /// newest version is a [`REMOVE_SOURCE`] one.
410    pub fn bundle_is_removed_global(&self, id: &str) -> Result<bool, StoreError> {
411        Ok(self.bundle_version_latest(id)?.is_some_and(|v| v.source == REMOVE_SOURCE))
412    }
413
414    pub fn bundle_get(&self, id: &str) -> Result<Option<Bundle>, StoreError> {
415        let conn = self.conn.lock().unwrap();
416        let mut stmt = conn.prepare(
417            "SELECT id, name, description, is_blank, is_global, provider, model, instructions,
418                    context_files, mcp_servers, skills, sort_order, created_at, updated_at,
419                    instructions_by_provider, is_system
420             FROM db_bundles WHERE id = ?1",
421        )?;
422        let result = stmt.query_row(params![id], map_memory_row);
423        match result {
424            Ok(m) => Ok(Some(m)),
425            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
426            Err(e) => Err(e.into()),
427        }
428    }
429
430    /// The bundle that holds `name` (it is `UNIQUE`: at most one), whatever kind it is: a live or a
431    /// removed Global Memory entry, or an agent's bundle.
432    pub fn bundle_get_by_name(&self, name: &str) -> Result<Option<Bundle>, StoreError> {
433        let conn = self.conn.lock().unwrap();
434        let mut stmt = conn.prepare(
435            "SELECT id, name, description, is_blank, is_global, provider, model, instructions,
436                    context_files, mcp_servers, skills, sort_order, created_at, updated_at,
437                    instructions_by_provider, is_system
438             FROM db_bundles WHERE name = ?1",
439        )?;
440        match stmt.query_row(params![name], map_memory_row) {
441            Ok(m) => Ok(Some(m)),
442            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
443            Err(e) => Err(e.into()),
444        }
445    }
446
447    /// Give a removed Global Memory entry another name, so its old one is free for a live entry. Only
448    /// a row that is not global and not a system one; no version is recorded, so it stays removed.
449    pub fn bundle_rename_removed(&self, id: &str, new_name: &str) -> Result<(), StoreError> {
450        let conn = self.conn.lock().unwrap();
451        conn.execute("UPDATE db_bundles SET name = ?2 WHERE id = ?1 AND is_global = 0 AND is_system = 0", params![id, new_name])?;
452        Ok(())
453    }
454
455    /// Look up just the `is_system` flag for `id`, without decoding a full
456    /// `Bundle` row. Shared by every guard in this file that needs to know
457    /// "is the EXISTING row (if any) a system entry" before deciding
458    /// whether to allow a write through the generic path.
459    fn bundle_is_system(&self, conn: &rusqlite::Connection, id: &str) -> Result<Option<bool>, StoreError> {
460        let existing: Option<i64> = conn
461            .query_row(
462                "SELECT is_system FROM db_bundles WHERE id = ?1",
463                params![id],
464                |r| r.get(0),
465            )
466            .optional()?;
467        Ok(existing.map(|v| v != 0))
468    }
469
470    /// [`Self::bundle_upsert_unobserved`], then tell the Global Memory record's
471    /// observer (`GlobalMemoryChange`).
472    pub fn bundle_upsert(&self, memory: &Bundle) -> Result<(), StoreError> {
473        let r = self.bundle_upsert_unobserved(memory);
474        if r.is_ok() {
475            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(memory.id.clone()));
476        }
477        r
478    }
479
480    /// Generic Global Bundle upsert — used by the ordinary Memory editor,
481    /// the per-agent Bundle editor, ABF import, and internal seeding.
482    /// Refuses outright to touch an existing `is_system=1` row (content
483    /// included, not just the flag) — see
484    /// docs/specs/SPEC_GLOBAL_MEMORY_SYSTEM_TIER_2026_08_24.md §3.2. Use
485    /// `bundle_upsert_system` to create/edit a system entry.
486    fn bundle_upsert_unobserved(&self, memory: &Bundle) -> Result<(), StoreError> {
487        let conn = self.conn.lock().unwrap();
488        if self.bundle_is_system(&conn, &memory.id)? == Some(true) {
489            return Err(StoreError::Other(
490                "cannot modify a system Global Memory entry via the generic bundle upsert path"
491                    .to_string(),
492            ));
493        }
494        write_user_row(&conn, memory)?;
495        Ok(())
496    }
497
498    /// Same as `bundle_upsert`, but when `memory.is_global` is true, also
499    /// appends a `db_bundle_versions` row for it — atomically, in the SAME
500    /// transaction as the `db_bundles` write, not as two separate calls.
501    /// codex P2, PR #3237: two separate lock/transaction acquisitions (the
502    /// original shape — call `bundle_upsert`, then separately call
503    /// `bundle_version_insert`) let a concurrent writer interleave between
504    /// them: writer A upserts, writer B upserts AND versions, then A's own
505    /// (now-stale) version-insert lands last — the history would then claim
506    /// A's content is current while the live row actually holds B's. One
507    /// transaction makes that interleaving impossible.
508    ///
509    /// `written_by` is the caller's own TRUSTED identity (an agent's real
510    /// `AGENTMUX_AGENT_ID`, or `"armory-ui"` for the human-facing Memory
511    /// editor) — see `BundleVersion::written_by`'s own doc comment for why
512    /// this is a separate field from `source`/`source_detail`.
513    /// `written_by_uid` is the writer's UID from the request's `Caller`
514    /// (identity M4c-1, spec §6.5.9) — `""` when Unattributed, and for the
515    /// Memory pane. Returns
516    /// `None` (no version recorded) when `memory.is_global` is false —
517    /// versioning is scoped to Global Memory specifically, matching this
518    /// table's whole purpose; a private, per-agent bundle upsert still
519    /// writes normally but has nothing to audit here.
520    ///
521    /// Shares `bundle_upsert`'s exact guard (refuses an existing
522    /// `is_system=1` row), written out here too, and its statement
523    /// (`write_user_row`). It does not call `bundle_upsert`: `self.conn`
524    /// is a plain (non-reentrant) `Mutex`, so a call that takes its own
525    /// lock from inside a transaction already holding that same lock would
526    /// deadlock.
527    pub fn bundle_upsert_with_version(
528        &self,
529        memory: &Bundle,
530        written_by: &str,
531        written_by_uid: &str,
532        source: &str,
533        source_detail: &str,
534    ) -> Result<Option<BundleVersion>, StoreError> {
535        self.bundle_upsert_with_version_based(memory, written_by, written_by_uid, source, source_detail, None)
536    }
537
538    /// [`Self::bundle_upsert_with_version_based_unobserved`], then tell the Global Memory record's
539    /// observer (`GlobalMemoryChange`).
540    pub fn bundle_upsert_with_version_based(&self, memory: &Bundle, written_by: &str, written_by_uid: &str, source: &str, source_detail: &str, base_sha256: Option<&str>) -> Result<Option<BundleVersion>, StoreError> {
541        let r = self.bundle_upsert_with_version_based_unobserved(memory, written_by, written_by_uid, source, source_detail, base_sha256);
542        if r.is_ok() {
543            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(memory.id.clone()));
544        }
545        r
546    }
547
548    /// `bundle_upsert_with_version` with an optional base: when
549    /// `base_sha256` is `Some`, the row's CURRENT `name` + `instructions`
550    /// must still hash to it (`bundle_versions::content_hash` — the same
551    /// value as the latest version's `content_hash`), checked inside the
552    /// same `IMMEDIATE` transaction as the write, else `StoreError::Conflict`
553    /// and nothing is written. A missing row is a conflict too. `None`
554    /// behaves exactly like `bundle_upsert_with_version`. Memory →
555    /// Global's editor sends it (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.4).
556    fn bundle_upsert_with_version_based_unobserved(
557        &self,
558        memory: &Bundle,
559        written_by: &str,
560        written_by_uid: &str,
561        source: &str,
562        source_detail: &str,
563        base_sha256: Option<&str>,
564    ) -> Result<Option<BundleVersion>, StoreError> {
565        let mut conn = self.conn.lock().unwrap();
566        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
567
568        if let Some(base) = base_sha256 {
569            check_bundle_base_tx(&tx, &memory.id, base)?;
570        }
571
572        let existing: Option<(i64, i64, String, String)> = tx
573            .query_row(
574                "SELECT is_system, is_global, name, instructions FROM db_bundles WHERE id = ?1",
575                params![memory.id],
576                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
577            )
578            .optional()?;
579        if matches!(existing, Some((1, ..))) {
580            return Err(StoreError::Other(
581                "cannot modify a system Global Memory entry via the generic bundle upsert path"
582                    .to_string(),
583            ));
584        }
585        // An entry leaving Global Memory keeps a trail: the content it held and
586        // who removed it, so it can be restored (`Store::bundle_list_removed_global`).
587        let removed_content = match existing {
588            Some((_, 1, name, instructions)) if !memory.is_global => Some((name, instructions)),
589            _ => None,
590        };
591
592        write_user_row(&tx, memory)?;
593
594        let version = if let Some((name, instructions)) = removed_content {
595            Some(bundle_version_insert_tx(
596                &tx,
597                &memory.id,
598                &name,
599                &instructions,
600                REMOVE_SOURCE,
601                source_detail,
602                written_by,
603                written_by_uid,
604            )?)
605        } else if memory.is_global {
606            Some(bundle_version_insert_tx(
607                &tx,
608                &memory.id,
609                &memory.name,
610                &memory.instructions,
611                source,
612                source_detail,
613                written_by,
614                written_by_uid,
615            )?)
616        } else {
617            None
618        };
619
620        tx.commit()?;
621        Ok(version)
622    }
623
624    /// [`Self::bundle_upsert_system_unobserved`], then tell the Global Memory record's
625    /// observer (`GlobalMemoryChange`).
626    #[cfg(any(test, feature = "test-support"))]
627    pub fn bundle_upsert_system(&self, memory: &Bundle) -> Result<(), StoreError> {
628        let r = self.bundle_upsert_system_unobserved(memory);
629        if r.is_ok() {
630            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(memory.id.clone()));
631        }
632        r
633    }
634
635    /// The ONLY path that can write `is_system=1`. Refuses the mirror-image
636    /// case of `bundle_upsert`'s guard: converting an EXISTING
637    /// non-system row into a system one by id collision is not allowed —
638    /// `id` must be either brand new or already a system entry.
639    /// `is_blank`/`is_global`/`is_system` are hardcoded (not read from
640    /// `memory`) so this method can never produce anything other than a
641    /// well-formed system row regardless of what the caller passed in.
642    #[cfg(any(test, feature = "test-support"))]
643    fn bundle_upsert_system_unobserved(&self, memory: &Bundle) -> Result<(), StoreError> {
644        let conn = self.conn.lock().unwrap();
645        if self.bundle_is_system(&conn, &memory.id)? == Some(false) {
646            return Err(StoreError::Other(
647                "cannot convert an existing non-system Global Memory entry into a system entry"
648                    .to_string(),
649            ));
650        }
651        write_system_row(&conn, memory)?;
652        Ok(())
653    }
654
655    /// [`Self::bundle_upsert_system_with_version_unobserved`], then tell the Global Memory record's
656    /// observer (`GlobalMemoryChange`).
657    #[cfg(test)]
658    pub fn bundle_upsert_system_with_version(&self, memory: &Bundle, written_by: &str, source: &str, source_detail: &str) -> Result<BundleVersion, StoreError> {
659        let r = self.bundle_upsert_system_with_version_unobserved(memory, written_by, source, source_detail);
660        if r.is_ok() {
661            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(memory.id.clone()));
662        }
663        r
664    }
665
666    /// Same as `bundle_upsert_system`, but also appends a `db_bundle_versions`
667    /// row in the SAME transaction — the system-tier counterpart of
668    /// `bundle_upsert_with_version`, for the same atomicity reason (codex P2,
669    /// PR #3237). Always records a version (unlike the ordinary method, this
670    /// one never returns `None`): a system row is unconditionally
671    /// `is_global=1`, so there is never a case where versioning would not
672    /// apply. See docs/specs/SPEC_SYSTEM_TIER_GLOBAL_MEMORY_SEEDING_2026_09_15.md
673    /// — this is what lets `operator_config_seed`'s startup reseed tell "did
674    /// AgentMux's own seeder write this last, or did a human edit it in
675    /// Memory" apart, via the returned/stored `written_by`.
676    ///
677    /// Shares `bundle_upsert_system`'s exact guard, written out here too
678    /// for the non-reentrant-`Mutex` reason `bundle_upsert_with_version`
679    /// documents on itself, and its statement (`write_system_row`).
680    #[cfg(test)]
681    fn bundle_upsert_system_with_version_unobserved(
682        &self,
683        memory: &Bundle,
684        written_by: &str,
685        source: &str,
686        source_detail: &str,
687    ) -> Result<BundleVersion, StoreError> {
688        let mut conn = self.conn.lock().unwrap();
689        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
690
691        let existing_is_system: Option<i64> = tx
692            .query_row(
693                "SELECT is_system FROM db_bundles WHERE id = ?1",
694                params![memory.id],
695                |r| r.get(0),
696            )
697            .optional()?;
698        if existing_is_system == Some(0) {
699            return Err(StoreError::Other(
700                "cannot convert an existing non-system Global Memory entry into a system entry"
701                    .to_string(),
702            ));
703        }
704
705        write_system_row(&tx, memory)?;
706
707        let version = bundle_version_insert_tx(
708            &tx,
709            &memory.id,
710            &memory.name,
711            &memory.instructions,
712            source,
713            source_detail,
714            written_by,
715            "", // the system tier is written by seeders, never a Caller
716        )?;
717
718        tx.commit()?;
719        Ok(version)
720    }
721
722    /// Same as `bundle_upsert_system_with_version`, but skips recording a
723    /// version when the write is byte-identical (`name` + `instructions`) to
724    /// what's already stored — the case where an operator opens a seeded
725    /// Operator Config entry in Memory and clicks Save without
726    /// changing anything (the UI does not suppress this request). Recording
727    /// a version for a true no-op would permanently mark the row as
728    /// human-owned even though nothing actually changed, breaking `bundle_
729    /// reseed_system_if_owned`'s ownership signal for no reason (Codex P2,
730    /// PR #3244).
731    ///
732    /// The existing-content comparison happens in the SAME transaction as
733    /// the resulting write, for the identical check-then-act reason `bundle_
734    /// reseed_system_if_owned` documents on itself — an earlier revision of
735    /// `upsertsystemmemory` (`bundle.rs`) composed this from a separate
736    /// `bundle_get` call plus a conditional branch, which raced a concurrent
737    /// writer between the read and the write (ReAgent P2, PR #3244).
738    ///
739    /// Returns `Ok(None)` when the save was a no-op (still refreshes every
740    /// other field via the plain upsert; just records no version); `Ok(Some(
741    /// version))` otherwise, including for a brand-new row (never a no-op).
742    pub fn bundle_upsert_system_if_changed(
743        &self,
744        memory: &Bundle,
745        written_by: &str,
746        source: &str,
747        source_detail: &str,
748    ) -> Result<Option<BundleVersion>, StoreError> {
749        self.bundle_upsert_system_if_changed_based(memory, written_by, source, source_detail, None)
750    }
751
752    /// [`Self::bundle_upsert_system_if_changed_based_unobserved`], then tell the Global Memory record's
753    /// observer (`GlobalMemoryChange`).
754    pub fn bundle_upsert_system_if_changed_based(&self, memory: &Bundle, written_by: &str, source: &str, source_detail: &str, base_sha256: Option<&str>) -> Result<Option<BundleVersion>, StoreError> {
755        let r = self.bundle_upsert_system_if_changed_based_unobserved(memory, written_by, source, source_detail, base_sha256);
756        if r.is_ok() {
757            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(memory.id.clone()));
758        }
759        r
760    }
761
762    /// `bundle_upsert_system_if_changed` with the same optional base check
763    /// `bundle_upsert_with_version_based` documents — the system-tier half
764    /// of Memory → Global's conditional save.
765    fn bundle_upsert_system_if_changed_based_unobserved(
766        &self,
767        memory: &Bundle,
768        written_by: &str,
769        source: &str,
770        source_detail: &str,
771        base_sha256: Option<&str>,
772    ) -> Result<Option<BundleVersion>, StoreError> {
773        let mut conn = self.conn.lock().unwrap();
774        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
775
776        if let Some(base) = base_sha256 {
777            check_bundle_base_tx(&tx, &memory.id, base)?;
778        }
779
780        let existing: Option<(String, String, i64)> = tx
781            .query_row(
782                "SELECT name, instructions, is_system FROM db_bundles WHERE id = ?1",
783                params![memory.id],
784                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
785            )
786            .optional()?;
787
788        if let Some((_, _, is_system)) = &existing {
789            if *is_system == 0 {
790                return Err(StoreError::Other(
791                    "cannot convert an existing non-system Global Memory entry into a system entry"
792                        .to_string(),
793                ));
794            }
795        }
796
797        let is_noop = existing
798            .as_ref()
799            .is_some_and(|(name, instructions, _)| *name == memory.name && *instructions == memory.instructions);
800
801        write_system_row(&tx, memory)?;
802
803        let version = if is_noop {
804            None
805        } else {
806            Some(bundle_version_insert_tx(
807                &tx,
808                &memory.id,
809                &memory.name,
810                &memory.instructions,
811                source,
812                source_detail,
813                written_by,
814                "", // the system tier is written by seeders, never a Caller
815            )?)
816        };
817
818        tx.commit()?;
819        Ok(version)
820    }
821
822    /// [`Self::bundle_reseed_system_if_owned_unobserved`], then tell the Global Memory record's
823    /// observer (`GlobalMemoryChange`).
824    pub fn bundle_reseed_system_if_owned(&self, memory: &Bundle, seeder_identity: &str, source: &str, source_detail: &str) -> Result<BundleReseedOutcome, StoreError> {
825        let r = self.bundle_reseed_system_if_owned_unobserved(memory, seeder_identity, source, source_detail);
826        if r.is_ok() {
827            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(memory.id.clone()));
828        }
829        r
830    }
831
832    /// Atomically decide-and-apply an Operator Config reseed for one system
833    /// row — the ownership check (is this row still owned by AgentMux's own
834    /// seeder, or has a human/another writer claimed it) and the resulting
835    /// write happen inside the SAME transaction, not as two separate `Store`
836    /// calls composed by the caller. A caller-composed version (read latest
837    /// version via `bundle_version_list`, decide, then separately call
838    /// `bundle_upsert_system_with_version`) is a check-then-act race: a
839    /// concurrent writer — a human editing this row in Memory, or
840    /// another AgentMux instance's own startup reseed, since multiple
841    /// instances can run in parallel by design — could land a new version
842    /// between the read and the write, and the caller's decision would be
843    /// based on data that was already stale by the time it acted (muxreview
844    /// P1, PR #3244).
845    ///
846    /// `seeder_identity` is the reserved `written_by` value that marks a row
847    /// as still owned by the seeder (see `operator_config_seed::WRITTEN_BY`)
848    /// — a latest version written by anything else means a human (or some
849    /// other writer) has claimed this row, and it is left alone.
850    ///
851    /// - No existing `db_bundles` row at all -> (re)create, UNLESS the
852    ///   latest version for this id is a `RETIREMENT_TOMBSTONE_SOURCE`
853    ///   marker whose recorded generation is newer than `source_detail`'s
854    ///   own (`SkippedRetired` in that case) — see `bundle_delete_system_
855    ///   if_owned`'s own doc comment for why the tombstone exists: without
856    ///   it, an older AgentMux build (or a rollback) sharing this store.db
857    ///   would read "no row" as "never existed" and resurrect content a
858    ///   newer build's prune deliberately retired (ReAgent/Codex P2, PR
859    ///   #3244). An ordinary human delete (`bundle_delete_system`, which
860    ///   records no version at all) leaves no tombstone, so a manually
861    ///   deleted entry still comes back exactly as before — only a
862    ///   generation-aware prune leaves a tombstone behind.
863    /// - Existing row, latest version's `written_by != seeder_identity` ->
864    ///   `SkippedLocalEdit`, no write at all.
865    /// - Existing row, latest version's `content_hash` already matches the
866    ///   target (`name`+`instructions`) -> `Unchanged`, no write.
867    /// - Otherwise -> upsert + version insert, `Updated`.
868    fn bundle_reseed_system_if_owned_unobserved(
869        &self,
870        memory: &Bundle,
871        seeder_identity: &str,
872        source: &str,
873        source_detail: &str,
874    ) -> Result<BundleReseedOutcome, StoreError> {
875        let mut conn = self.conn.lock().unwrap();
876        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
877
878        let existing: Option<(i64, String, String)> = tx
879            .query_row(
880                "SELECT is_system, name, instructions FROM db_bundles WHERE id = ?1",
881                params![memory.id],
882                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
883            )
884            .optional()?;
885        let row_exists = existing.is_some();
886
887        if let Some((0, _, _)) = existing {
888            return Err(StoreError::Other(
889                "cannot convert an existing non-system Global Memory entry into a system entry"
890                    .to_string(),
891            ));
892        }
893
894        if let Some((_, live_name, live_instructions)) = &existing {
895            // Ordered by rowid (insertion sequence), NOT created_at: unlike
896            // bundle_version_list's own history ordering (a display
897            // concern, where wall-clock order is what a human expects to
898            // see), this ownership decision has a real behavioral
899            // consequence if it picks the wrong "latest" row. A backward
900            // system-clock jump (e.g. correcting a VM whose clock was
901            // ahead) between two writes to the same bundle_id would give
902            // the chronologically-later write a SMALLER created_at, so
903            // `ORDER BY created_at DESC` could keep selecting the older
904            // row as "latest" — silently defeating the ownership
905            // guarantee this whole method exists for. rowid is monotonic
906            // per insert regardless of wall-clock time. Codex P2, PR #3244.
907            let latest: Option<(String, String, String)> = tx
908                .query_row(
909                    "SELECT written_by, content_hash, source_detail FROM db_bundle_versions
910                     WHERE bundle_id = ?1
911                     ORDER BY rowid DESC
912                     LIMIT 1",
913                    params![memory.id],
914                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
915                )
916                .optional()?;
917            if let Some((written_by, content_hash, stored_source_detail)) = latest {
918                // The live db_bundles row must match what the latest
919                // version CLAIMS is there before `written_by` can be
920                // trusted at all — a compatible-schema OLDER build sharing
921                // this store might still run a pre-PR-#3244
922                // `upsertsystemmemory` handler that calls the unversioned
923                // `bundle_upsert_system` directly, changing the live row
924                // without ever touching `db_bundle_versions`. In that case
925                // the latest version would still (wrongly) show the seeder
926                // as the last writer, even though a human's edit is
927                // sitting live and unrecorded. Codex P2, PR #3244.
928                let live_hash = super::bundle_versions::content_hash(live_name, live_instructions);
929                if live_hash != content_hash {
930                    return Ok(BundleReseedOutcome::SkippedLocalEdit);
931                }
932                if written_by != seeder_identity {
933                    return Ok(BundleReseedOutcome::SkippedLocalEdit);
934                }
935                let target_hash = super::bundle_versions::content_hash(&memory.name, &memory.instructions);
936                let stored_generation = manifest_generation_from_source_detail(&stored_source_detail);
937                let target_generation = manifest_generation_from_source_detail(source_detail);
938                if content_hash == target_hash {
939                    // Content is identical, but if THIS call's own manifest
940                    // generation is strictly newer than what's recorded,
941                    // that fact must still be persisted — otherwise a
942                    // concurrently-running build on a LOWER generation
943                    // (still not "older" than the stale recorded one) could
944                    // later see its own differing content as valid to write
945                    // and downgrade content a newer generation already
946                    // confirmed as current. E.g. generation 3's text
947                    // happens to match generation 1's (a revert); without
948                    // this, a generation-2 build's own different text would
949                    // still pass the generation check against the
950                    // never-advanced "1" and overwrite generation 3's
951                    // result. Codex P2, PR #3244.
952                    if target_generation > stored_generation {
953                        bundle_version_insert_tx(
954                            &tx,
955                            &memory.id,
956                            &memory.name,
957                            &memory.instructions,
958                            source,
959                            source_detail,
960                            seeder_identity,
961                            "",
962                        )?;
963                        // Returning without an explicit commit drops `tx`,
964                        // which rolls back — harmless for every OTHER early
965                        // return in this method (they make no writes), but
966                        // this one just did. Must commit explicitly before
967                        // returning.
968                        tx.commit()?;
969                    }
970                    return Ok(BundleReseedOutcome::Unchanged);
971                }
972                // Content differs, but only from THIS process's point of
973                // view — on a machine sharing store.db across multiple
974                // AgentMux builds/versions (a supported configuration; see
975                // "Multiple Instances Run in Parallel" in this repo's own
976                // CLAUDE.md), an older build's own (older) manifest must
977                // never overwrite a newer build's already-seeded content
978                // just because both processes use the same seeder_identity.
979                // Codex P2, PR #3244.
980                if target_generation < stored_generation {
981                    return Ok(BundleReseedOutcome::SkippedOlderGeneration);
982                }
983            } else {
984                // Row exists but has ZERO version history (possible via the
985                // still-present unversioned bundle_upsert_system, or data
986                // that predates this tier having versioning at all) —
987                // conservatively treated as NOT owned by the seeder and
988                // left alone, same policy `bundle_delete_system_if_owned`
989                // already documents and implements for the identical edge
990                // case. Falling through to the unconditional upsert below
991                // would silently overwrite a row this method has no basis
992                // to claim is safe to touch. ReAgent P2, PR #3244.
993                return Ok(BundleReseedOutcome::SkippedLocalEdit);
994            }
995        } else {
996            // No db_bundles row — but check for a retirement tombstone
997            // before assuming that means "never existed, safe to create."
998            // See this method's own doc comment and `bundle_delete_system_
999            // if_owned`'s. rowid DESC for the same reason as the row_exists
1000            // branch above.
1001            let tombstone: Option<(String, String)> = tx
1002                .query_row(
1003                    "SELECT source, source_detail FROM db_bundle_versions
1004                     WHERE bundle_id = ?1
1005                     ORDER BY rowid DESC
1006                     LIMIT 1",
1007                    params![memory.id],
1008                    |r| Ok((r.get(0)?, r.get(1)?)),
1009                )
1010                .optional()?;
1011            if let Some((last_source, last_source_detail)) = tombstone {
1012                if last_source == RETIREMENT_TOMBSTONE_SOURCE {
1013                    let retired_generation = manifest_generation_from_source_detail(&last_source_detail);
1014                    let target_generation = manifest_generation_from_source_detail(source_detail);
1015                    if target_generation < retired_generation {
1016                        return Ok(BundleReseedOutcome::SkippedRetired);
1017                    }
1018                }
1019            }
1020        }
1021
1022        write_system_row(&tx, memory)?;
1023
1024        bundle_version_insert_tx(
1025            &tx,
1026            &memory.id,
1027            &memory.name,
1028            &memory.instructions,
1029            source,
1030            source_detail,
1031            seeder_identity,
1032            "",
1033        )?;
1034
1035        tx.commit()?;
1036        Ok(if row_exists {
1037            BundleReseedOutcome::Updated
1038        } else {
1039            BundleReseedOutcome::Created
1040        })
1041    }
1042
1043    /// [`Self::bundle_delete_unobserved`], then tell the Global Memory record's
1044    /// observer (`GlobalMemoryChange`).
1045    pub fn bundle_delete(&self, id: &str) -> Result<bool, StoreError> {
1046        let r = self.bundle_delete_unobserved(id);
1047        if r.is_ok() {
1048            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(id.to_string()));
1049        }
1050        r
1051    }
1052
1053    /// Delete a Bundle. Refuses to delete the blank singleton, a
1054    /// seeded bundle, or (new) a system entry — use
1055    /// `bundle_delete_system` for the last case.
1056    fn bundle_delete_unobserved(&self, id: &str) -> Result<bool, StoreError> {
1057        if id == "blank" {
1058            return Err(StoreError::Other(
1059                "cannot delete the blank bundle".to_string(),
1060            ));
1061        }
1062        // Seeded bundles (IDs prefixed "seed-") are workspace defaults that
1063        // re-seed on every startup; blocking deletion is cleaner than a
1064        // tombstone table and avoids the re-creation loop.
1065        if id.starts_with("seed-") {
1066            return Err(StoreError::Other(
1067                "cannot delete a seeded bundle; toggle is_global or clear its instructions instead".to_string(),
1068            ));
1069        }
1070        let conn = self.conn.lock().unwrap();
1071        if self.bundle_is_system(&conn, id)? == Some(true) {
1072            return Err(StoreError::Other(
1073                "cannot delete a system Global Memory entry via the generic delete path; use bundle_delete_system".to_string(),
1074            ));
1075        }
1076        let rows = conn.execute("DELETE FROM db_bundles WHERE id = ?1", params![id])?;
1077        Ok(rows > 0)
1078    }
1079
1080    /// [`Self::bundle_delete_system_unobserved`], then tell the Global Memory record's
1081    /// observer (`GlobalMemoryChange`).
1082    pub fn bundle_delete_system(&self, id: &str) -> Result<bool, StoreError> {
1083        let r = self.bundle_delete_system_unobserved(id);
1084        if r.is_ok() {
1085            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(id.to_string()));
1086        }
1087        r
1088    }
1089
1090    /// The ONLY path that can remove an `is_system=1` row — structurally
1091    /// incapable of deleting anything else, even if misused.
1092    fn bundle_delete_system_unobserved(&self, id: &str) -> Result<bool, StoreError> {
1093        let conn = self.conn.lock().unwrap();
1094        let rows = conn.execute(
1095            "DELETE FROM db_bundles WHERE id = ?1 AND is_system = 1",
1096            params![id],
1097        )?;
1098        Ok(rows > 0)
1099    }
1100
1101    /// All `is_system=1` row ids — the full universe `operator_config_seed`'s
1102    /// startup prune pass checks its manifest against, to find rows for an
1103    /// entry AgentMux itself removed or renamed in a later release (Codex
1104    /// P2, PR #3244). Ids only, not full `Bundle`s: the prune pass needs
1105    /// nothing else before deciding whether a given id is still in the
1106    /// manifest.
1107    pub fn bundle_list_system_ids(&self) -> Result<Vec<String>, StoreError> {
1108        let conn = self.conn.lock().unwrap();
1109        let mut stmt = conn.prepare("SELECT id FROM db_bundles WHERE is_system = 1")?;
1110        let rows = stmt
1111            .query_map([], |r| r.get::<_, String>(0))?
1112            .collect::<Result<Vec<_>, _>>()?;
1113        Ok(rows)
1114    }
1115
1116    /// [`Self::bundle_delete_system_if_owned_unobserved`], then tell the Global Memory record's
1117    /// observer (`GlobalMemoryChange`).
1118    pub fn bundle_delete_system_if_owned(&self, id: &str, seeder_identity: &str, caller_manifest_version: u32) -> Result<bool, StoreError> {
1119        let r = self.bundle_delete_system_if_owned_unobserved(id, seeder_identity, caller_manifest_version);
1120        if r.is_ok() {
1121            self.notify_global_memory(super::store::GlobalMemoryChange::Entry(id.to_string()));
1122        }
1123        r
1124    }
1125
1126    /// Atomically deletes an `is_system=1` row ONLY if its latest version is
1127    /// still owned by `seeder_identity` AND that version's own recorded
1128    /// manifest generation is `<= caller_manifest_version` — the delete-side
1129    /// counterpart of `bundle_reseed_system_if_owned`'s ownership check,
1130    /// used to prune a row whose manifest entry AgentMux itself removed in a
1131    /// later release.
1132    ///
1133    /// The generation gate exists for the same reason `bundle_reseed_
1134    /// system_if_owned` has one: on a machine sharing `store.db` across
1135    /// multiple AgentMux builds/versions, an OLDER build's own manifest
1136    /// simply doesn't mention an entry a NEWER build already added — that
1137    /// absence means "I don't know about this yet," not "this was removed."
1138    /// Without gating on generation, an older build's prune pass would
1139    /// delete a newer build's own addition on every one of its startups.
1140    /// Only a row whose generation this process's OWN manifest has already
1141    /// caught up to (or exceeds) is eligible for pruning at all.
1142    ///
1143    /// A row a human has edited (`written_by` on the latest version is
1144    /// anything else) is left in place — same "never clobber a local edit"
1145    /// posture as the reseed path; an orphaned-but-human-owned entry is a
1146    /// human's to clean up, not this seeder's. A row with NO version
1147    /// history at all (should not normally happen — every write path that
1148    /// can create an `is_system` row also records one) is conservatively
1149    /// treated as NOT owned by the seeder and left alone, rather than
1150    /// guessing. Returns `true` only when a deletion actually happened.
1151    ///
1152    /// Also appends a `RETIREMENT_TOMBSTONE_SOURCE`-marked version row in
1153    /// the SAME transaction as the delete — without it, an older AgentMux
1154    /// build (or a rollback to one) sharing this store.db, whose own
1155    /// manifest still lists this id, would see no `db_bundles` row and
1156    /// treat that as "never existed, safe to create," silently resurrecting
1157    /// content this deletion deliberately retired. `bundle_reseed_system_
1158    /// if_owned`'s missing-row branch checks for this tombstone before
1159    /// recreating anything (ReAgent/Codex P2, PR #3244).
1160    ///
1161    /// Also validates the LIVE row's content against what the latest
1162    /// version claims before trusting `written_by` at all — the delete-side
1163    /// mirror of the same check `bundle_reseed_system_if_owned` gained
1164    /// earlier in this PR. Without it, a compatible-schema OLDER build's
1165    /// unversioned write (still possible during a rolling upgrade — see
1166    /// that method's own doc comment) would leave `written_by` stale at
1167    /// the seeder's identity, and this method would DELETE the unrecorded
1168    /// edit outright — strictly worse than the overwrite the reseed-path
1169    /// fix was built to prevent, since deletion cannot be undone from
1170    /// `db_bundles` alone. ReAgent P1, PR #3244.
1171    fn bundle_delete_system_if_owned_unobserved(
1172        &self,
1173        id: &str,
1174        seeder_identity: &str,
1175        caller_manifest_version: u32,
1176    ) -> Result<bool, StoreError> {
1177        let mut conn = self.conn.lock().unwrap();
1178        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
1179
1180        let live: Option<(String, String)> = tx
1181            .query_row(
1182                "SELECT name, instructions FROM db_bundles WHERE id = ?1 AND is_system = 1",
1183                params![id],
1184                |r| Ok((r.get(0)?, r.get(1)?)),
1185            )
1186            .optional()?;
1187        let Some((live_name, live_instructions)) = live else {
1188            return Ok(false);
1189        };
1190
1191        // rowid, not created_at — see bundle_reseed_system_if_owned's own
1192        // comment on the same ordering choice.
1193        let latest: Option<(String, String, String)> = tx
1194            .query_row(
1195                "SELECT written_by, content_hash, source_detail FROM db_bundle_versions
1196                 WHERE bundle_id = ?1
1197                 ORDER BY rowid DESC
1198                 LIMIT 1",
1199                params![id],
1200                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
1201            )
1202            .optional()?;
1203
1204        let Some((written_by, content_hash, source_detail)) = latest else {
1205            return Ok(false);
1206        };
1207        let live_hash = super::bundle_versions::content_hash(&live_name, &live_instructions);
1208        if live_hash != content_hash {
1209            return Ok(false);
1210        }
1211        if written_by != seeder_identity {
1212            return Ok(false);
1213        }
1214        let row_generation = manifest_generation_from_source_detail(&source_detail);
1215        if row_generation > caller_manifest_version as u64 {
1216            return Ok(false);
1217        }
1218
1219        let rows = tx.execute("DELETE FROM db_bundles WHERE id = ?1 AND is_system = 1", params![id])?;
1220        if rows > 0 {
1221            let tombstone_detail = format!(r#"{{"manifest_version":{caller_manifest_version}}}"#);
1222            bundle_version_insert_tx(&tx, id, "", "", RETIREMENT_TOMBSTONE_SOURCE, &tombstone_detail, seeder_identity, "")?;
1223        }
1224        tx.commit()?;
1225        Ok(rows > 0)
1226    }
1227
1228    /// [`Self::bundle_reorder_unobserved`], then tell the Global Memory record's
1229    /// observer (`GlobalMemoryChange`).
1230    pub fn bundle_reorder(&self, ordered_ids: &[String]) -> Result<usize, StoreError> {
1231        let r = self.bundle_reorder_unobserved(ordered_ids);
1232        if r.is_ok() {
1233            self.notify_global_memory(super::store::GlobalMemoryChange::Order);
1234        }
1235        r
1236    }
1237
1238    /// Assign `sort_order` to the given bundle ids in the order supplied
1239    /// (position 0, 1, 2, …). Drives the Memory → Global ordering,
1240    /// which in turn controls CLAUDE.md injection order. Ids not present in
1241    /// the table, OR present but `is_system=1`, are skipped silently — a
1242    /// system row's position is fixed (always first, see
1243    /// `bundle_list_global`) and never disturbed by the generic
1244    /// reorder command. Runs in a single transaction so a partial reorder
1245    /// never lands. Returns the number of rows updated.
1246    fn bundle_reorder_unobserved(&self, ordered_ids: &[String]) -> Result<usize, StoreError> {
1247        let mut conn = self.conn.lock().unwrap();
1248        let tx = conn.transaction()?;
1249        let mut updated = 0usize;
1250        {
1251            let mut stmt =
1252                tx.prepare("UPDATE db_bundles SET sort_order = ?1 WHERE id = ?2 AND is_system = 0")?;
1253            for (idx, id) in ordered_ids.iter().enumerate() {
1254                updated += stmt.execute(params![idx as i64, id])?;
1255            }
1256        }
1257        tx.commit()?;
1258        Ok(updated)
1259    }
1260}
1261
1262/// What every bundle write stores in `db_bundles.mcp_servers`, and what every
1263/// read returns, whatever the caller sent or an older build wrote. A bundle
1264/// carries no MCP servers (`SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md`
1265/// §3.1), and the column held server configs, credentials included:
1266/// `m0036_drop_bundle_mcp` clears it once, and this keeps it clear and
1267/// unreadable from this build on, whichever client writes.
1268pub(crate) const NO_INLINE_MCP_SERVERS: &str = "[]";
1269
1270fn map_memory_row(row: &rusqlite::Row) -> rusqlite::Result<Bundle> {
1271    Ok(Bundle {
1272        id: row.get(0)?,
1273        name: row.get(1)?,
1274        description: row.get(2)?,
1275        is_blank: row.get::<_, i64>(3)? != 0,
1276        is_global: row.get::<_, i64>(4)? != 0,
1277        provider: row.get(5)?,
1278        model: row.get(6)?,
1279        instructions: row.get(7)?,
1280        context_files: row.get(8)?,
1281        // Column 9 is never read back; see NO_INLINE_MCP_SERVERS.
1282        mcp_servers: NO_INLINE_MCP_SERVERS.to_string(),
1283        skills: row.get(10)?,
1284        sort_order: row.get(11)?,
1285        created_at: row.get(12)?,
1286        updated_at: row.get(13)?,
1287        instructions_by_provider: row.get(14)?,
1288        is_system: row.get::<_, i64>(15)? != 0,
1289    })
1290}
1291
1292#[cfg(test)]
1293#[path = "bundles_tests.rs"]
1294mod tests;