Skip to main content

agentmux_srv_core/migrations/
m0021_backfill_agent_bundles.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bind an agent definition to the bundle another channel already recorded for it
5//! (`docs/specs/SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md` §2.1.6).
6//!
7//! This migration used to mint a dedicated, empty "<Name> — ABF" bundle for every definition
8//! without one (`docs/specs/ARCHITECTURE_MANDATORY_ABF_RETHINK_2026_08_14.md`). It no longer does:
9//! a new agent has no bundle of its own, and a fresh channel must not fill the shared store with an
10//! empty one per agent (`docs/reports/REPORT_AGENT_BUNDLES_REFINE_OR_DROP_2026_11_03.md`: 881 of
11//! 926 bundles on one machine were empty and unreferenced). The record other channels wrote
12//! (`agent_bundle_sidecar`) is still bound, so an agent that already has a bundle keeps it in every
13//! channel; `m0046` removes the empty ones nothing points at.
14//!
15//! Local-channel only: `DefinitionRecordV1` doesn't carry `memory_id`, so a definition that exists
16//! only in the global registry has no row here to bind to. The registry is still attached so the
17//! agents it lists are seen.
18//!
19//! Idempotent: only a definition still at `memory_id=''` is touched, and
20//! `agent_def_set_memory_id_if_empty` refuses to overwrite a binding.
21
22use std::sync::Arc;
23
24use crate::backend::storage::store::Store;
25use crate::registry::{resolve_shared_definitions_dir, DefinitionStore};
26
27use super::{Migration, MigrationContext, MigrationError, MigrationScope};
28
29pub struct M0021BackfillAgentBundles;
30
31/// The store bundles live in: the shared store when it opens, else the channel store, as
32/// `AppState.id_store` does. Never a hard failure: an unusable shared store means "not today".
33pub(super) fn resolve_bundle_store(ctx: &MigrationContext, mstore: &Arc<Store>) -> Arc<Store> {
34    match Store::open_shared(&ctx.shared_store_path) {
35        Ok(shared) => Arc::new(shared),
36        Err(e) => {
37            tracing::warn!(
38                error = %e,
39                path = %ctx.shared_store_path.display(),
40                "backfill_agent_bundles: shared store unavailable, falling back to channel store for bundle reads"
41            );
42            mstore.clone()
43        }
44    }
45}
46
47impl Migration for M0021BackfillAgentBundles {
48    fn id(&self) -> &'static str { "0021_backfill_agent_bundles" }
49    fn scope(&self) -> MigrationScope { MigrationScope::Channel }
50    fn description(&self) -> &'static str {
51        "Bind each agent definition to the bundle another channel recorded for it"
52    }
53
54    fn up(&self, ctx: &MigrationContext) -> Result<(), MigrationError> {
55        if !ctx.channel_store_path.exists() {
56            return Ok(());
57        }
58        let mstore = Arc::new(
59            Store::open(&ctx.channel_store_path)
60                .map_err(|e| MigrationError(format!("backfill_agent_bundles: open mstore: {}", e)))?,
61        );
62        if let Some(def_dir) = resolve_shared_definitions_dir() {
63            match DefinitionStore::open(def_dir) {
64                Ok(def_store) => mstore.set_def_registry(Arc::new(def_store)),
65                Err(e) => tracing::warn!(error = %e, "backfill_agent_bundles: failed to open global def registry, using local definitions only"),
66            }
67        } else {
68            tracing::warn!("backfill_agent_bundles: could not resolve global def registry dir, using local definitions only");
69        }
70        let bundle_store = resolve_bundle_store(ctx, &mstore);
71        let Some(sidecar) = crate::backend::agent_bundle_sidecar::open_global() else { return Ok(()) };
72
73        let defs = mstore
74            .agent_def_list()
75            .map_err(|e| MigrationError(format!("backfill_agent_bundles: list defs: {}", e)))?;
76        for def in defs.into_iter().filter(|d| d.memory_id.is_empty()) {
77            let local = mstore
78                .agent_def_has_local_row(&def.id)
79                .map_err(|e| MigrationError(format!("backfill_agent_bundles: look up {}: {}", def.id, e)))?;
80            if !local {
81                tracing::debug!(agent_id = %def.id, "backfill_agent_bundles: definition only in the global registry; nothing here to bind a bundle to");
82                continue;
83            }
84            let recorded = crate::backend::agent_bundle_sidecar::get(&sidecar, &def.id).ok().flatten();
85            if let Some(existing) = recorded.filter(|id| matches!(bundle_store.bundle_get(id), Ok(Some(_)))) {
86                mstore
87                    .agent_def_set_memory_id_if_empty(&def.id, &existing)
88                    .map_err(|e| MigrationError(format!("backfill_agent_bundles: bind {}: {}", def.id, e)))?;
89            }
90        }
91        Ok(())
92    }
93}
94
95#[cfg(test)]
96#[path = "m0021_backfill_agent_bundles_tests.rs"]
97mod tests;