agentmux_srv_core/migrations/
m0021_backfill_agent_bundles.rs1use 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
31pub(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;