agentmux_srv_core/migrations/
m0007_agents_consolidate.rs1use std::sync::Arc;
5use crate::backend::storage::agents_consolidate::consolidate_looks_incomplete;
6use crate::backend::storage::store::Store;
7use super::{Migration, MigrationContext, MigrationError, MigrationScope, VerifyOutcome};
8
9pub struct M0007AgentsConsolidate;
10
11impl Migration for M0007AgentsConsolidate {
12 fn id(&self) -> &'static str { "0007_agents_consolidate" }
13 fn scope(&self) -> MigrationScope { MigrationScope::Channel }
14 fn description(&self) -> &'static str { "Consolidate db_agent_definitions + db_agent_instances into db_agents" }
15
16 fn up(&self, ctx: &MigrationContext) -> Result<(), MigrationError> {
17 if !ctx.channel_store_path.exists() {
18 return Ok(());
19 }
20 let mstore = Arc::new(
21 Store::open(&ctx.channel_store_path)
22 .map_err(|e| MigrationError(format!("agents_consolidate: open mstore: {}", e)))?,
23 );
24 let stats = mstore
25 .run_agents_consolidate(Some(&ctx.data_dir))
26 .map_err(|e| MigrationError(format!("agents_consolidate: {}", e)))?;
27 tracing::info!(
33 already_done = stats.already_done,
34 templates_inserted = stats.templates_inserted,
35 user_defs_inserted = stats.user_defs_inserted,
36 instances_as_clone_inserted = stats.instances_as_clone_inserted,
37 instances_folded_into_def = stats.instances_folded_into_def,
38 "m0007_agents_consolidate: outcome",
39 );
40 Ok(())
41 }
42
43 fn verify(&self, ctx: &MigrationContext) -> VerifyOutcome {
53 let conn = match super::runner::open_readonly(&ctx.channel_store_path) {
54 Ok(Some(c)) => c,
55 Ok(None) => return VerifyOutcome::Ok("no channel store on this data dir; nothing to consolidate".into()),
56 Err(e) => return VerifyOutcome::Error(e),
57 };
58 let incomplete = match consolidate_looks_incomplete(&conn) {
59 Ok(b) => b,
60 Err(e) => return VerifyOutcome::Error(format!("consolidate check: {}", e)),
63 };
64 let count = |t: &str| super::runner::table_count(&conn, t);
65 match (count("db_agent_definitions"), count("db_agent_instances"), count("db_agents")) {
66 (Ok(defs), Ok(instances), Ok(agents)) => consolidate_report(incomplete, defs, instances, agents),
67 (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => VerifyOutcome::Error(e),
68 }
69 }
70}
71
72pub(super) fn consolidate_report(incomplete: bool, defs: i64, instances: i64, agents: i64) -> VerifyOutcome {
75 if incomplete {
76 return VerifyOutcome::Mismatch(format!(
77 "db_agent_definitions={} db_agent_instances={} but db_agents={} — recorded applied, wrote nothing",
78 defs, instances, agents
79 ));
80 }
81 if defs + instances == 0 {
82 return VerifyOutcome::Ok(format!("no legacy rows to consolidate (db_agents={})", agents));
83 }
84 VerifyOutcome::Ok(format!(
85 "db_agents={} (legacy: definitions={}, instances={})",
86 agents, defs, instances
87 ))
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 use crate::backend::storage::store::Store;
94
95 #[test]
96 fn incomplete_verdict_reports_the_incident_shape_with_counts() {
97 match consolidate_report(true, 3, 2, 0) {
98 VerifyOutcome::Mismatch(m) => {
99 assert!(m.contains("db_agent_definitions=3"));
100 assert!(m.contains("db_agents=0"));
101 }
102 other => panic!("expected Mismatch, got {:?}", other),
103 }
104 }
105
106 #[test]
107 fn complete_verdicts_pass_and_carry_counts() {
108 assert!(matches!(consolidate_report(false, 0, 0, 0), VerifyOutcome::Ok(_)));
109 match consolidate_report(false, 4, 1, 5) {
110 VerifyOutcome::Ok(s) => assert!(s.contains("db_agents=5")),
111 other => panic!("expected Ok, got {:?}", other),
112 }
113 }
114
115 #[test]
116 fn verify_on_a_fresh_channel_store_passes_and_on_no_store_passes_without_creating_one() {
117 let dir = tempfile::tempdir().unwrap();
118 let data_dir = dir.path().join("data");
119 let path = data_dir.join("db").join("objects.db");
120 let ctx = MigrationContext {
121 home: dir.path().to_path_buf(),
122 data_dir: data_dir.clone(),
123 shared_store_path: dir.path().join("shared").join("store.db"),
124 channel_store_path: path.clone(),
125 };
126 assert!(matches!(M0007AgentsConsolidate.verify(&ctx), VerifyOutcome::Ok(_)));
128 assert!(!path.exists());
129
130 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
132 drop(Store::open(&path).expect("create channel store"));
133 match M0007AgentsConsolidate.verify(&ctx) {
134 VerifyOutcome::Ok(s) => assert!(s.contains("no legacy rows"), "{}", s),
135 other => panic!("expected Ok, got {:?}", other),
136 }
137 }
138}