1use std::collections::HashSet;
20use std::path::{Path, PathBuf};
21use std::time::Instant;
22
23use crate::backend::storage::store::Store;
24use crate::registry::{resolve_global_shared_root, resolve_shared_store_path};
25
26use super::{MigrationContext, MigrationScope, REGISTRY};
27
28fn emit(event: &str, id: &str, extra: &str) {
31 if extra.is_empty() {
32 println!("{{\"event\":\"{}\",\"id\":\"{}\"}}", event, id);
33 } else {
34 println!("{{\"event\":\"{}\",\"id\":\"{}\",{}}}", event, id, extra);
35 }
36}
37
38pub(super) fn emit_summary(applied: usize, skipped: usize) {
39 println!(
40 "{{\"event\":\"complete\",\"applied\":{},\"skipped\":{}}}",
41 applied, skipped
42 );
43}
44
45fn resolve_home() -> Option<PathBuf> {
58 resolve_global_shared_root().and_then(|p| p.parent().map(Path::to_path_buf))
59}
60
61pub const VERIFY_FAILED_EXIT_CODE: i32 = 3;
70
71pub fn run_migrate_command(data_dir: &Path, dry_run: bool, list: bool, verify: bool, prepare: bool) -> i32 {
75 let Some(shared_store_path) = resolve_shared_store_path() else {
79 emit_summary(0, 0);
80 return 0;
81 };
82
83 let Some(home) = resolve_home() else {
84 emit_summary(0, 0);
85 return 0;
86 };
87
88 if verify {
94 return cmd_verify(data_dir, &home, &shared_store_path);
95 }
96
97 if let Some(parent) = shared_store_path.parent() {
101 if let Err(e) = std::fs::create_dir_all(parent) {
102 eprintln!("migration: failed to create shared dir {}: {}", parent.display(), e);
103 return 1;
104 }
105 }
106
107 if prepare || !(list || dry_run) {
108 if let Some(code) = crate::registry::shared_guard::claim_for_migrate(data_dir) {
109 return code;
110 }
111 }
112
113 if prepare {
114 return super::prepare::run(data_dir, &home, &shared_store_path);
115 }
116
117 if list || dry_run {
123 let (shared_store, channel_store) = match open_stores_for_preview(&shared_store_path, data_dir) {
124 Ok(pair) => pair,
125 Err(msg) => {
126 eprintln!("migration: {}", msg);
127 return 1;
128 }
129 };
130 if list {
131 return cmd_list(&shared_store, channel_store.as_ref());
132 }
133 let pending = pending_of(REGISTRY, &shared_store, channel_store.as_ref());
134 if pending.is_empty() {
135 emit_summary(0, REGISTRY.len());
136 }
137 for m in &pending {
138 println!("pending: {} — {}", m.id(), m.description());
139 }
140 return 0;
141 }
142
143 let progress = ApplyProgress {
151 on_start: &|id, description| {
152 emit("migration_start", id, &format!("\"description\":\"{}\"", description));
153 },
154 on_done: &|id, ms| emit("migration_done", id, &format!("\"duration_ms\":{}", ms)),
155 };
156 match apply_pending(REGISTRY, &home, &shared_store_path, data_dir, Some(&progress)) {
157 Ok(outcome) => {
158 emit_summary(outcome.applied, outcome.skipped);
159 0
160 }
161 Err(msg) => {
162 write_error_log(&home, &msg);
163 eprintln!("{}", msg);
164 1
165 }
166 }
167}
168
169fn tracking_store<'a>(
172 scope: super::MigrationScope,
173 shared: &'a Store,
174 channel: Option<&'a Store>,
175) -> Option<&'a Store> {
176 match scope {
177 super::MigrationScope::Global => Some(shared),
178 super::MigrationScope::Channel => channel,
179 }
180}
181
182fn cmd_list(shared_store: &Store, channel_store: Option<&Store>) -> i32 {
183 let shared_applied = shared_store.migrations_list_applied().unwrap_or_default();
184 let channel_applied = channel_store
185 .and_then(|s| s.migrations_list_applied().ok())
186 .unwrap_or_default();
187 for m in REGISTRY.iter() {
188 let applied_ids = match m.scope() {
189 super::MigrationScope::Global => &shared_applied,
190 super::MigrationScope::Channel => &channel_applied,
191 };
192 let status = if applied_ids.contains(&m.id().to_string()) { "applied" } else { "pending" };
193 println!("{} [{}] [{}] — {}", m.id(), m.scope().as_str(), status, m.description());
194 }
195 0
196}
197
198pub fn run_pending_migrations(data_dir: &Path) -> Result<usize, String> {
215 let shared_store_path = match resolve_shared_store_path() {
216 Some(p) => p,
217 None => {
218 tracing::info!("run_pending_migrations: shared store path unresolvable — nothing to do");
219 return Ok(0);
220 }
221 };
222
223 let home = match resolve_home() {
224 Some(p) => p,
225 None => return Err("run_pending_migrations: cannot resolve global shared root".to_string()),
226 };
227
228 apply_pending(REGISTRY, &home, &shared_store_path, data_dir, Some(&STDERR_PROGRESS)).map(|o| o.applied)
242}
243
244pub(super) const MIGRATION_LOCK_FILE: &str = "migrations.lock.db";
263
264const MIGRATION_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30 * 60);
268
269pub(super) struct MigrationLock {
271 _conn: rusqlite::Connection,
272}
273
274impl MigrationLock {
275 pub(super) fn acquire(path: &Path, wait: std::time::Duration) -> Result<Self, String> {
279 let conn = rusqlite::Connection::open(path)
280 .map_err(|e| format!("open migration lock {}: {}", path.display(), e))?;
281 conn.busy_timeout(wait)
282 .map_err(|e| format!("migration lock busy_timeout: {}", e))?;
283 conn.execute_batch("CREATE TABLE IF NOT EXISTS lock (id INTEGER PRIMARY KEY); BEGIN IMMEDIATE;")
286 .map_err(|e| format!("acquire migration lock {} (another runner may still hold it): {}", path.display(), e))?;
287 Ok(Self { _conn: conn })
288 }
289}
290
291fn open_stores_for_preview(shared_store_path: &Path, data_dir: &Path) -> Result<(Store, Option<Store>), String> {
295 let shared_store = Store::open_shared(shared_store_path)
296 .map_err(|e| format!("open shared store: {}", e))?;
297 let channel_store_path = data_dir.join("db").join("objects.db");
298 if let Some(parent) = channel_store_path.parent() {
299 std::fs::create_dir_all(parent).map_err(|e| format!("create channel db dir: {}", e))?;
300 }
301 let channel_store = Store::open(&channel_store_path)
312 .map(Some)
313 .map_err(|e| format!("open channel store: {}", e))?;
314 Ok((shared_store, channel_store))
315}
316
317fn pending_of<'r>(
319 regs: &'r [&'r (dyn super::Migration + Sync)],
320 shared: &Store,
321 channel: Option<&Store>,
322) -> Vec<&'r (dyn super::Migration + Sync)> {
323 regs.iter()
324 .copied()
325 .filter(|m| {
326 tracking_store(m.scope(), shared, channel).map_or(false, |s| !s.migration_is_applied(m.id()))
327 })
328 .collect()
329}
330
331pub(super) struct ApplyProgress<'a> {
338 pub on_start: &'a dyn Fn(&str, &str),
339 pub on_done: &'a dyn Fn(&str, u64),
340}
341
342pub(super) const STDERR_PROGRESS: ApplyProgress<'static> = ApplyProgress {
346 on_start: &|id, description| eprintln!("{}", agentmux_common::srv_stderr::migration_begin_line(id, description)),
347 on_done: &|id, ms| eprintln!("{}", agentmux_common::srv_stderr::migration_end_line(id, ms)),
348};
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub(super) struct ApplyOutcome {
353 pub applied: usize,
354 pub skipped: usize,
355}
356
357pub(super) fn apply_pending(
367 regs: &[&(dyn super::Migration + Sync)],
368 home: &Path,
369 shared_store_path: &Path,
370 data_dir: &Path,
371 progress: Option<&ApplyProgress<'_>>,
372) -> Result<ApplyOutcome, String> {
373 super::gate::refuse_on_real_home(regs, shared_store_path, &home.join("shared").join("identity-store.db"))?;
374 if let Some(parent) = shared_store_path.parent() {
375 if let Err(e) = std::fs::create_dir_all(parent) {
376 return Err(format!("run_pending_migrations: create shared dir: {}", e));
377 }
378 }
379
380 let shared_lock_path = shared_store_path
389 .parent()
390 .map(|p| p.join(MIGRATION_LOCK_FILE))
391 .unwrap_or_else(|| PathBuf::from(MIGRATION_LOCK_FILE));
392 let channel_db_dir = data_dir.join("db");
393 let (_shared_lock, _channel_lock) =
395 crate::boot_timing::step_if_slow("migration_lock", "Waiting for other AgentMux", || {
396 let shared = MigrationLock::acquire(&shared_lock_path, MIGRATION_LOCK_WAIT)
397 .map_err(|e| format!("run_pending_migrations: {}", e))?;
398 std::fs::create_dir_all(&channel_db_dir)
399 .map_err(|e| format!("run_pending_migrations: create channel db dir: {}", e))?;
400 let channel = MigrationLock::acquire(&channel_db_dir.join(MIGRATION_LOCK_FILE), MIGRATION_LOCK_WAIT)
401 .map_err(|e| format!("run_pending_migrations: {}", e))?;
402 Ok::<_, String>((shared, channel))
403 })?;
404
405 let channel_store_path = channel_db_dir.join("objects.db");
408 let identity_store_path = home.join("shared").join("identity-store.db");
409 if super::gate::pending_reason(regs, shared_store_path, &channel_store_path, &identity_store_path).is_some() {
410 super::backup::backup_stores(home, shared_store_path, data_dir)
411 .map_err(|e| format!("run_pending_migrations: backup failed: {}", e))?;
412 }
413 let (shared_store, channel_store) = open_stores_for_preview(shared_store_path, data_dir)
414 .map_err(|e| format!("run_pending_migrations: {}", e))?;
415 if identity_store_path.exists() {
417 if let Err(e) = Store::open_identity_store(&identity_store_path) {
418 tracing::warn!(error = %e, "run_pending_migrations: identity store not opened");
419 }
420 }
421
422 let pending = pending_of(regs, &shared_store, channel_store.as_ref());
423 if pending.is_empty() {
424 return Ok(ApplyOutcome { applied: 0, skipped: regs.len() });
425 }
426 let skipped = regs.len() - pending.len();
427
428 let ctx = super::MigrationContext {
429 home: home.to_path_buf(),
430 data_dir: data_dir.to_path_buf(),
431 shared_store_path: shared_store_path.to_path_buf(),
432 channel_store_path: channel_store_path.clone(),
433 };
434
435 let mut applied = 0;
436 for m in &pending {
437 let t = Instant::now();
438 tracing::info!(id = m.id(), description = m.description(), "run_pending_migrations: applying");
439 if let Some(p) = progress {
440 (p.on_start)(m.id(), m.description());
441 }
442 match m.up(&ctx) {
443 Ok(()) => {
444 let ms = t.elapsed().as_millis() as u64;
445 let scope = m.scope().as_str();
446 let tracking = tracking_store(m.scope(), &shared_store, channel_store.as_ref())
447 .ok_or_else(|| format!("run_pending_migrations: no tracking store for {} (channel store missing)", m.id()))?;
448 if let Err(e) = tracking.migration_mark_applied(m.id(), scope, ms) {
449 return Err(format!("run_pending_migrations: failed to record {} as applied: {}", m.id(), e));
450 }
451 tracing::info!(id = m.id(), duration_ms = ms, "run_pending_migrations: applied");
452 if let Some(p) = progress {
453 (p.on_done)(m.id(), ms);
454 }
455 applied += 1;
456 }
457 Err(e) => {
458 return Err(format!("run_pending_migrations: migration {} failed: {}", m.id(), e));
459 }
460 }
461 }
462
463 Ok(ApplyOutcome { applied, skipped })
464}
465
466#[derive(Debug)]
473pub enum PendingCountError {
474 SharedStoreUnresolvable,
477 SharedStoreUnreadable { path: PathBuf, error: String },
479 ChannelStoreUnreadable { path: PathBuf, error: String, global_pending: usize },
484}
485
486impl PendingCountError {
487 pub fn readable_pending(&self) -> usize {
497 match self {
498 Self::ChannelStoreUnreadable { global_pending, .. } => *global_pending,
499 Self::SharedStoreUnresolvable | Self::SharedStoreUnreadable { .. } => 0,
500 }
501 }
502}
503
504impl std::fmt::Display for PendingCountError {
505 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
506 match self {
507 Self::SharedStoreUnresolvable => write!(f, "could not resolve the shared store path"),
508 Self::SharedStoreUnreadable { path, error } => {
509 write!(f, "failed to open the shared store at {}: {}", path.display(), error)
510 }
511 Self::ChannelStoreUnreadable { path, error, .. } => {
512 write!(f, "failed to open the channel store at {}: {}", path.display(), error)
513 }
514 }
515 }
516}
517
518pub fn try_count_pending_migrations(data_dir: &Path) -> Result<usize, PendingCountError> {
535 let shared_store_path =
536 resolve_shared_store_path().ok_or(PendingCountError::SharedStoreUnresolvable)?;
537 let shared_store = Store::open_shared(&shared_store_path).map_err(|e| {
538 PendingCountError::SharedStoreUnreadable {
539 path: shared_store_path.clone(),
540 error: e.to_string(),
541 }
542 })?;
543 let pending_in = |channel: Option<&Store>| pending_of(REGISTRY, &shared_store, channel).len();
544 let channel_store_path = data_dir.join("db").join("objects.db");
545 let channel_store = Store::open(&channel_store_path).map_err(|e| {
546 PendingCountError::ChannelStoreUnreadable {
547 path: channel_store_path.clone(),
548 error: e.to_string(),
549 global_pending: pending_in(None),
552 }
553 })?;
554 Ok(pending_in(Some(&channel_store)))
555}
556
557pub fn count_pending_migrations(data_dir: &Path) -> usize {
568 match try_count_pending_migrations(data_dir) {
569 Ok(n) => n,
570 Err(e) => {
571 let fallback = e.readable_pending();
575 tracing::warn!("count_pending_migrations: {} — reporting {}", e, fallback);
576 fallback
577 }
578 }
579}
580
581pub(super) fn write_error_log(home: &Path, msg: &str) {
584 let log_dir = home.join("logs");
585 let _ = std::fs::create_dir_all(&log_dir);
586 let path = log_dir.join("migration-error.log");
587 let content = format!("{}\n", msg);
588 let _ = std::fs::write(path, content);
589}
590
591#[derive(Debug, Clone, PartialEq, Eq)]
608pub struct VerifyRecord {
609 pub id: &'static str,
610 pub scope: &'static str,
611 pub outcome: super::VerifyOutcome,
612}
613
614pub struct AppliedIds {
624 pub global: Result<HashSet<String>, String>,
625 pub channel: Result<HashSet<String>, String>,
626}
627
628impl AppliedIds {
629 fn for_scope(&self, scope: MigrationScope) -> &Result<HashSet<String>, String> {
630 match scope {
631 MigrationScope::Global => &self.global,
632 MigrationScope::Channel => &self.channel,
633 }
634 }
635}
636
637pub(super) fn open_readonly(path: &Path) -> Result<Option<rusqlite::Connection>, String> {
640 if !path.exists() {
641 return Ok(None);
642 }
643 rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
644 .map(Some)
645 .map_err(|e| format!("open {} read-only: {}", path.display(), e))
646}
647
648pub(super) fn read_applied_ids(path: &Path) -> Result<HashSet<String>, String> {
653 let Some(conn) = open_readonly(path)? else {
654 return Ok(HashSet::new());
655 };
656 let mut stmt = match conn.prepare("SELECT id FROM db_migrations") {
657 Ok(s) => s,
658 Err(rusqlite::Error::SqliteFailure(_, Some(msg))) if msg.contains("no such table") => {
659 return Ok(HashSet::new());
660 }
661 Err(e) => return Err(format!("read db_migrations in {}: {}", path.display(), e)),
662 };
663 stmt.query_map([], |row| row.get::<_, String>(0))
664 .and_then(|rows| rows.collect::<Result<HashSet<String>, _>>())
665 .map_err(|e| format!("read db_migrations in {}: {}", path.display(), e))
666}
667
668pub fn verify_applied(
672 regs: &[&(dyn super::Migration + Sync)],
673 ctx: &MigrationContext,
674 applied: &AppliedIds,
675) -> Vec<VerifyRecord> {
676 let mut out = Vec::new();
677 for m in regs {
678 let outcome = match applied.for_scope(m.scope()) {
679 Err(e) => super::VerifyOutcome::Error(format!("cannot read applied state: {}", e)),
680 Ok(ids) if ids.contains(m.id()) => m.verify(ctx),
681 Ok(_) => continue,
682 };
683 out.push(VerifyRecord { id: m.id(), scope: m.scope().as_str(), outcome });
684 }
685 out
686}
687
688pub fn verify_exit_code(records: &[VerifyRecord]) -> i32 {
691 if records.iter().any(|r| r.outcome.is_failure()) {
692 VERIFY_FAILED_EXIT_CODE
693 } else {
694 0
695 }
696}
697
698fn verify_event_line(r: &VerifyRecord) -> String {
702 let detail = serde_json::to_string(r.outcome.detail()).unwrap_or_else(|_| "\"\"".to_string());
703 format!(
704 "{{\"event\":\"migration_verify\",\"id\":\"{}\",\"scope\":\"{}\",\"status\":\"{}\",\"detail\":{}}}",
705 r.id,
706 r.scope,
707 r.outcome.label(),
708 detail
709 )
710}
711
712#[derive(Debug, Clone, serde::Serialize)]
725pub struct DoctorReport {
726 pub data_dir: String,
727 pub shared_store: String,
728 pub channel_store: String,
729 pub tracking_errors: Vec<String>,
733 pub migrations: Vec<DoctorRow>,
734 pub summary: DoctorSummary,
735 pub exit_code: i32,
738}
739
740#[derive(Debug, Clone, serde::Serialize)]
742pub struct DoctorRow {
743 pub id: &'static str,
744 pub scope: &'static str,
745 pub description: &'static str,
746 pub state: &'static str,
749 #[serde(skip_serializing_if = "Option::is_none")]
753 pub verify: Option<&'static str>,
754 #[serde(skip_serializing_if = "String::is_empty")]
756 pub detail: String,
757}
758
759#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
760pub struct DoctorSummary {
761 pub total: usize,
762 pub applied: usize,
763 pub pending: usize,
764 pub unknown: usize,
765 pub checked: usize,
768 pub ok: usize,
769 pub mismatch: usize,
770 pub error: usize,
771 pub not_verifiable: usize,
772}
773
774fn doctor_inputs(data_dir: &Path, home: &Path, shared_store_path: &Path) -> (MigrationContext, AppliedIds) {
777 let channel_store_path = data_dir.join("db").join("objects.db");
778 let ctx = MigrationContext {
779 home: home.to_path_buf(),
780 data_dir: data_dir.to_path_buf(),
781 shared_store_path: shared_store_path.to_path_buf(),
782 channel_store_path: channel_store_path.clone(),
783 };
784 let applied = AppliedIds {
785 global: read_applied_ids(shared_store_path),
786 channel: read_applied_ids(&channel_store_path),
787 };
788 (ctx, applied)
789}
790
791fn build_doctor_report(
795 regs: &[&(dyn super::Migration + Sync)],
796 ctx: &MigrationContext,
797 applied: &AppliedIds,
798 records: &[VerifyRecord],
799) -> DoctorReport {
800 let mut summary = DoctorSummary { total: regs.len(), ..Default::default() };
801 let mut migrations = Vec::with_capacity(regs.len());
802 for m in regs {
803 let record = records.iter().find(|r| r.id == m.id());
804 let state = match applied.for_scope(m.scope()) {
805 Err(_) => "unknown",
806 Ok(ids) if ids.contains(m.id()) => "applied",
807 Ok(_) => "pending",
808 };
809 match state {
810 "applied" => summary.applied += 1,
811 "pending" => summary.pending += 1,
812 _ => summary.unknown += 1,
813 }
814 let (verify, detail) = match record {
815 Some(r) => {
816 summary.checked += 1;
817 match r.outcome {
818 super::VerifyOutcome::Ok(_) => summary.ok += 1,
819 super::VerifyOutcome::Mismatch(_) => summary.mismatch += 1,
820 super::VerifyOutcome::Error(_) => summary.error += 1,
821 super::VerifyOutcome::NotVerifiable => summary.not_verifiable += 1,
822 }
823 (Some(r.outcome.label()), r.outcome.detail().to_string())
824 }
825 None => (None, String::new()),
826 };
827 migrations.push(DoctorRow {
828 id: m.id(),
829 scope: m.scope().as_str(),
830 description: m.description(),
831 state,
832 verify,
833 detail,
834 });
835 }
836 let tracking_errors = [&applied.global, &applied.channel]
837 .into_iter()
838 .filter_map(|r| r.as_ref().err().cloned())
839 .collect();
840 DoctorReport {
841 data_dir: ctx.data_dir.display().to_string(),
842 shared_store: ctx.shared_store_path.display().to_string(),
843 channel_store: ctx.channel_store_path.display().to_string(),
844 tracking_errors,
845 migrations,
846 summary,
847 exit_code: verify_exit_code(records),
848 }
849}
850
851pub fn doctor_report(
854 regs: &[&(dyn super::Migration + Sync)],
855 data_dir: &Path,
856 home: &Path,
857 shared_store_path: &Path,
858) -> DoctorReport {
859 let (ctx, applied) = doctor_inputs(data_dir, home, shared_store_path);
860 let records = verify_applied(regs, &ctx, &applied);
861 build_doctor_report(regs, &ctx, &applied, &records)
862}
863
864pub fn doctor_report_for_instance(data_dir: &Path) -> Result<DoctorReport, String> {
870 let shared_store_path = resolve_shared_store_path()
871 .ok_or_else(|| "shared store path is unresolvable (AGENTMUX_SHARED_DIR / home not set)".to_string())?;
872 let home = resolve_home().ok_or_else(|| "AgentMux home is unresolvable".to_string())?;
873 Ok(doctor_report(REGISTRY, data_dir, &home, &shared_store_path))
874}
875
876fn cmd_verify(data_dir: &Path, home: &Path, shared_store_path: &Path) -> i32 {
877 let (ctx, applied) = doctor_inputs(data_dir, home, shared_store_path);
878 let records = verify_applied(REGISTRY, &ctx, &applied);
879 for r in &records {
880 let detail = r.outcome.detail();
881 if detail.is_empty() {
882 println!("verify: {} [{}] [{}]", r.id, r.scope, r.outcome.label());
883 } else {
884 println!("verify: {} [{}] [{}] — {}", r.id, r.scope, r.outcome.label(), detail);
885 }
886 println!("{}", verify_event_line(r));
887 }
888 let report = build_doctor_report(REGISTRY, &ctx, &applied, &records);
889 let s = &report.summary;
890 println!(
891 "verify: {} applied checked — {} ok, {} mismatch, {} error, {} not verifiable (data dir {})",
892 s.checked,
893 s.ok,
894 s.mismatch,
895 s.error,
896 s.not_verifiable,
897 data_dir.display()
898 );
899 println!(
900 "{{\"event\":\"verify_complete\",\"checked\":{},\"ok\":{},\"mismatch\":{},\"error\":{},\"not_verifiable\":{}}}",
901 s.checked, s.ok, s.mismatch, s.error, s.not_verifiable
902 );
903 report.exit_code
904}
905
906pub(super) fn table_count(conn: &rusqlite::Connection, table: &str) -> Result<i64, String> {
912 match conn.query_row(&format!("SELECT COUNT(*) FROM {}", table), [], |row| row.get::<_, i64>(0)) {
913 Ok(n) => Ok(n),
914 Err(rusqlite::Error::SqliteFailure(_, Some(msg))) if msg.contains("no such table") => Ok(0),
915 Err(e) => Err(format!("count {}: {}", table, e)),
916 }
917}
918
919#[cfg(test)]
920mod lock_tests {
921 use super::*;
922 use crate::migrations::{Migration, MigrationError};
923 use std::sync::atomic::{AtomicUsize, Ordering};
924
925 #[test]
926 fn lock_is_exclusive_across_connections_and_released_on_drop() {
927 let dir = tempfile::tempdir().unwrap();
928 let path = dir.path().join(MIGRATION_LOCK_FILE);
929 let first = MigrationLock::acquire(&path, std::time::Duration::from_millis(100)).expect("first holder");
930 let err = MigrationLock::acquire(&path, std::time::Duration::from_millis(200))
932 .err()
933 .expect("second acquire must fail while the first is held");
934 assert!(err.contains("another runner may still hold it"), "{}", err);
935 drop(first);
936 MigrationLock::acquire(&path, std::time::Duration::from_millis(100)).expect("free after drop");
937 }
938
939 static UP_RUNS: AtomicUsize = AtomicUsize::new(0);
944 struct SlowOnce;
945 impl Migration for SlowOnce {
946 fn id(&self) -> &'static str { "9900_slow_once" }
947 fn scope(&self) -> MigrationScope { MigrationScope::Global }
948 fn description(&self) -> &'static str { "counts its own runs" }
949 fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> {
950 UP_RUNS.fetch_add(1, Ordering::SeqCst);
951 std::thread::sleep(std::time::Duration::from_millis(300));
952 Ok(())
953 }
954 }
955 static SLOW_ONCE: SlowOnce = SlowOnce;
956
957 static CHANNEL_UP_RUNS: AtomicUsize = AtomicUsize::new(0);
959 struct SlowOnceChannel;
960 impl Migration for SlowOnceChannel {
961 fn id(&self) -> &'static str { "9901_slow_once_channel" }
962 fn scope(&self) -> MigrationScope { MigrationScope::Channel }
963 fn description(&self) -> &'static str { "counts its own runs (channel scope)" }
964 fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> {
965 CHANNEL_UP_RUNS.fetch_add(1, Ordering::SeqCst);
966 std::thread::sleep(std::time::Duration::from_millis(300));
967 Ok(())
968 }
969 }
970 static SLOW_ONCE_CHANNEL: SlowOnceChannel = SlowOnceChannel;
971
972 #[test]
973 fn runners_with_different_shared_stores_but_one_data_dir_still_serialize() {
974 let dir = tempfile::tempdir().unwrap();
979 let home = dir.path().to_path_buf();
980 let data_dir = home.join("data");
981 let shared_a = home.join("iso-a").join("shared").join("store.db");
982 let shared_b = home.join("iso-b").join("shared").join("store.db");
983 CHANNEL_UP_RUNS.store(0, Ordering::SeqCst);
984
985 let results: Vec<Result<ApplyOutcome, String>> = std::thread::scope(|s| {
986 let handles: Vec<_> = [shared_a.clone(), shared_b.clone()]
987 .into_iter()
988 .map(|shared| {
989 let (home, data_dir) = (home.clone(), data_dir.clone());
990 s.spawn(move || {
991 let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE_CHANNEL];
992 apply_pending(®s, &home, &shared, &data_dir, None)
993 })
994 })
995 .collect();
996 handles.into_iter().map(|h| h.join().expect("runner thread")).collect()
997 });
998
999 for r in &results {
1000 assert!(r.is_ok(), "both runners must succeed: {:?}", results);
1001 }
1002 let applied: usize = results.iter().map(|r| r.as_ref().unwrap().applied).sum();
1003 assert_eq!(applied, 1, "exactly one runner applied it: {:?}", results);
1004 assert_eq!(CHANNEL_UP_RUNS.load(Ordering::SeqCst), 1, "channel-scoped up() ran once despite two shared stores");
1005 }
1006
1007 #[test]
1008 fn previews_do_not_wait_on_the_migration_lock() {
1009 let dir = tempfile::tempdir().unwrap();
1013 let shared = dir.path().join("shared").join("store.db");
1014 std::fs::create_dir_all(shared.parent().unwrap()).unwrap();
1015 let data_dir = dir.path().join("data");
1016 let _held = MigrationLock::acquire(&shared.parent().unwrap().join(MIGRATION_LOCK_FILE), std::time::Duration::from_millis(100))
1017 .expect("hold the lock");
1018
1019 let before = UP_RUNS.load(Ordering::SeqCst);
1020 let started = std::time::Instant::now();
1021 let (shared_store, channel_store) = open_stores_for_preview(&shared, &data_dir).expect("preview opens stores");
1022 let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE];
1023 let pending = pending_of(®s, &shared_store, channel_store.as_ref());
1024 assert_eq!(pending.len(), 1, "nothing applied yet, so the fake is pending");
1025 assert!(started.elapsed() < std::time::Duration::from_secs(5), "preview must not block on the lock");
1026 assert_eq!(UP_RUNS.load(Ordering::SeqCst), before, "preview never runs up()");
1027 }
1028
1029 #[test]
1030 fn two_concurrent_runners_on_one_data_dir_apply_a_migration_exactly_once() {
1031 let dir = tempfile::tempdir().unwrap();
1037 let home = dir.path().to_path_buf();
1038 let shared = home.join("shared").join("store.db");
1039 let data_dir = home.join("data");
1040 UP_RUNS.store(0, Ordering::SeqCst);
1041
1042 let results: Vec<Result<usize, String>> = std::thread::scope(|s| {
1043 let handles: Vec<_> = (0..2)
1044 .map(|_| {
1045 let (home, shared, data_dir) = (home.clone(), shared.clone(), data_dir.clone());
1046 s.spawn(move || {
1047 let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE];
1048 apply_pending(®s, &home, &shared, &data_dir, None).map(|o| o.applied)
1049 })
1050 })
1051 .collect();
1052 handles.into_iter().map(|h| h.join().expect("runner thread")).collect()
1053 });
1054
1055 for r in &results {
1056 assert!(r.is_ok(), "both runners must succeed: {:?}", results);
1057 }
1058 let applied: usize = results.iter().map(|r| *r.as_ref().unwrap()).sum();
1059 assert_eq!(applied, 1, "exactly one runner applied it: {:?}", results);
1060 assert_eq!(UP_RUNS.load(Ordering::SeqCst), 1, "up() body must execute exactly once");
1061
1062 let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE];
1064 assert_eq!(apply_pending(®s, &home, &shared, &data_dir, None).map(|o| o.applied).unwrap(), 0);
1065 assert_eq!(UP_RUNS.load(Ordering::SeqCst), 1);
1066 }
1067}
1068
1069#[cfg(test)]
1070mod verify_tests {
1071 use super::*;
1072 use crate::migrations::{Migration, MigrationError, VerifyOutcome};
1073
1074 struct Fake {
1077 id: &'static str,
1078 scope: MigrationScope,
1079 outcome: VerifyOutcome,
1080 }
1081 impl Migration for Fake {
1082 fn id(&self) -> &'static str { self.id }
1083 fn scope(&self) -> MigrationScope { self.scope }
1084 fn description(&self) -> &'static str { "fake" }
1085 fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> { Ok(()) }
1086 fn verify(&self, _ctx: &MigrationContext) -> VerifyOutcome { self.outcome.clone() }
1087 }
1088
1089 struct Silent;
1091 impl Migration for Silent {
1092 fn id(&self) -> &'static str { "9998_silent" }
1093 fn scope(&self) -> MigrationScope { MigrationScope::Global }
1094 fn description(&self) -> &'static str { "no verify impl" }
1095 fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> { Ok(()) }
1096 }
1097
1098 fn ctx_in(dir: &tempfile::TempDir) -> MigrationContext {
1099 MigrationContext {
1100 home: dir.path().to_path_buf(),
1101 data_dir: dir.path().join("data"),
1102 shared_store_path: dir.path().join("shared").join("store.db"),
1103 channel_store_path: dir.path().join("data").join("db").join("objects.db"),
1104 }
1105 }
1106
1107 fn ids(list: &[&str]) -> Result<HashSet<String>, String> {
1108 Ok(list.iter().map(|s| s.to_string()).collect())
1109 }
1110
1111 #[test]
1112 fn only_applied_migrations_are_verified_and_unapplied_are_skipped() {
1113 let dir = tempfile::tempdir().unwrap();
1114 let applied = Fake { id: "9001_applied", scope: MigrationScope::Global, outcome: VerifyOutcome::Ok("fine".into()) };
1115 let pending = Fake { id: "9002_pending", scope: MigrationScope::Global, outcome: VerifyOutcome::Mismatch("would fail".into()) };
1116 let state = AppliedIds { global: ids(&["9001_applied"]), channel: ids(&[]) };
1117
1118 let regs: Vec<&(dyn Migration + Sync)> = vec![&applied, &pending];
1119 let records = verify_applied(®s, &ctx_in(&dir), &state);
1120 assert_eq!(records.len(), 1, "the pending one has nothing to verify yet");
1121 assert_eq!(records[0].id, "9001_applied");
1122 assert_eq!(records[0].outcome, VerifyOutcome::Ok("fine".into()));
1123 assert_eq!(verify_exit_code(&records), 0);
1124 }
1125
1126 #[test]
1127 fn channel_scoped_migrations_consult_the_channel_state_not_the_global_one() {
1128 let dir = tempfile::tempdir().unwrap();
1129 let m = Fake { id: "9003_channel", scope: MigrationScope::Channel, outcome: VerifyOutcome::Ok("ok".into()) };
1130 let regs: Vec<&(dyn Migration + Sync)> = vec![&m];
1131 let wrong = AppliedIds { global: ids(&["9003_channel"]), channel: ids(&[]) };
1134 assert!(verify_applied(®s, &ctx_in(&dir), &wrong).is_empty());
1135 let right = AppliedIds { global: ids(&[]), channel: ids(&["9003_channel"]) };
1136 assert_eq!(verify_applied(®s, &ctx_in(&dir), &right).len(), 1);
1137 }
1138
1139 #[test]
1140 fn unreadable_tracking_state_is_an_error_for_every_migration_of_that_scope() {
1141 let dir = tempfile::tempdir().unwrap();
1144 let g = Fake { id: "9004_global", scope: MigrationScope::Global, outcome: VerifyOutcome::Ok("never reached".into()) };
1145 let c = Fake { id: "9005_channel", scope: MigrationScope::Channel, outcome: VerifyOutcome::Ok("fine".into()) };
1146 let regs: Vec<&(dyn Migration + Sync)> = vec![&g, &c];
1147 let state = AppliedIds { global: Err("file is not a database".into()), channel: ids(&["9005_channel"]) };
1148 let records = verify_applied(®s, &ctx_in(&dir), &state);
1149 assert_eq!(records.len(), 2);
1150 assert!(matches!(&records[0].outcome, VerifyOutcome::Error(e) if e.contains("not a database")));
1151 assert_eq!(records[1].outcome, VerifyOutcome::Ok("fine".into()));
1152 assert_eq!(verify_exit_code(&records), VERIFY_FAILED_EXIT_CODE);
1153 }
1154
1155 #[test]
1156 fn a_migration_without_a_verify_impl_reports_not_verifiable_and_passes() {
1157 let dir = tempfile::tempdir().unwrap();
1158 let regs: Vec<&(dyn Migration + Sync)> = vec![&Silent];
1159 let state = AppliedIds { global: ids(&["9998_silent"]), channel: ids(&[]) };
1160 let records = verify_applied(®s, &ctx_in(&dir), &state);
1161 assert_eq!(records[0].outcome, VerifyOutcome::NotVerifiable);
1162 assert_eq!(verify_exit_code(&records), 0, "not verifiable is honest, not a failure");
1163 }
1164
1165 #[test]
1166 fn mismatch_or_error_fails_the_pass_with_a_code_distinct_from_run_failure_and_clap() {
1167 let mk = |o: VerifyOutcome| VerifyRecord { id: "x", scope: "global", outcome: o };
1168 assert_eq!(verify_exit_code(&[mk(VerifyOutcome::Ok("a".into())), mk(VerifyOutcome::NotVerifiable)]), 0);
1169 assert_eq!(verify_exit_code(&[mk(VerifyOutcome::Ok("a".into())), mk(VerifyOutcome::Mismatch("gone".into()))]), VERIFY_FAILED_EXIT_CODE);
1170 assert_eq!(verify_exit_code(&[mk(VerifyOutcome::Error("locked".into()))]), VERIFY_FAILED_EXIT_CODE);
1171 assert_ne!(VERIFY_FAILED_EXIT_CODE, 1, "1 = a migration run failed");
1172 assert_ne!(VERIFY_FAILED_EXIT_CODE, 2, "2 = clap usage error (bad flag)");
1173 }
1174
1175 #[test]
1176 fn read_applied_ids_reads_real_tracking_state_and_never_creates_a_store() {
1177 let dir = tempfile::tempdir().unwrap();
1178 let path = dir.path().join("shared").join("store.db");
1179 assert_eq!(read_applied_ids(&path).unwrap(), HashSet::new());
1181 assert!(!path.exists(), "verify must never create a database");
1182
1183 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1184 let store = Store::open_shared(&path).expect("open shared");
1185 store.migration_mark_applied("9010_a", "global", 1).unwrap();
1186 store.migration_mark_applied("9011_b", "global", 1).unwrap();
1187 drop(store);
1188 let got = read_applied_ids(&path).unwrap();
1189 assert!(got.contains("9010_a") && got.contains("9011_b"));
1190 assert_eq!(got.len(), 2);
1191 }
1192
1193 #[test]
1194 fn read_applied_ids_errors_on_a_file_that_is_not_a_database() {
1195 let dir = tempfile::tempdir().unwrap();
1196 let path = dir.path().join("objects.db");
1197 std::fs::write(&path, b"definitely not sqlite\n").unwrap();
1198 let err = read_applied_ids(&path).unwrap_err();
1199 assert!(err.contains("objects.db"), "names the store: {}", err);
1200 }
1201
1202 #[test]
1203 fn table_count_treats_a_missing_table_as_zero_rows() {
1204 let dir = tempfile::tempdir().unwrap();
1205 let path = dir.path().join("objects.db");
1206 drop(Store::open(&path).expect("create channel store"));
1207 let conn = open_readonly(&path).unwrap().expect("exists");
1208 assert_eq!(table_count(&conn, "db_table_that_never_existed").unwrap(), 0);
1209 assert!(table_count(&conn, "db_migrations").is_ok());
1210 }
1211
1212 #[test]
1215 fn doctor_report_on_a_fresh_data_dir_lists_everything_pending_and_creates_nothing() {
1216 let dir = tempfile::tempdir().unwrap();
1217 let data_dir = dir.path().join("data");
1218 let shared = dir.path().join("shared").join("store.db");
1219 let report = doctor_report(REGISTRY, &data_dir, dir.path(), &shared);
1220
1221 assert_eq!(report.migrations.len(), REGISTRY.len());
1222 assert!(report.migrations.iter().all(|r| r.state == "pending" && r.verify.is_none()));
1223 assert_eq!(report.summary.total, REGISTRY.len());
1224 assert_eq!(report.summary.pending, REGISTRY.len());
1225 assert_eq!(report.summary.checked, 0);
1226 assert!(report.tracking_errors.is_empty());
1227 assert_eq!(report.exit_code, 0);
1228 assert!(!shared.exists() && !data_dir.exists(), "doctor created files");
1230 let json = serde_json::to_value(&report).unwrap();
1232 assert_eq!(json["summary"]["pending"], REGISTRY.len());
1233 assert!(json["migrations"][0].get("verify").is_none(), "pending rows omit `verify`");
1234 }
1235
1236 #[test]
1237 fn doctor_report_reports_applied_rows_with_their_verdict_and_counts_them() {
1238 let dir = tempfile::tempdir().unwrap();
1239 let data_dir = dir.path().join("data");
1240 let channel = data_dir.join("db").join("objects.db");
1241 std::fs::create_dir_all(channel.parent().unwrap()).unwrap();
1242 let shared = dir.path().join("shared").join("store.db");
1243 {
1244 let store = Store::open(&channel).expect("create channel store");
1247 store.migration_mark_applied("0007_agents_consolidate", "channel", 1).unwrap();
1248 }
1249 let report = doctor_report(REGISTRY, &data_dir, dir.path(), &shared);
1250 let row = report.migrations.iter().find(|r| r.id == "0007_agents_consolidate").unwrap();
1251 assert_eq!(row.state, "applied");
1252 assert_eq!(row.verify, Some("ok"));
1253 assert!(row.detail.contains("no legacy rows"), "{}", row.detail);
1254 assert_eq!(report.summary.applied, 1);
1255 assert_eq!(report.summary.checked, 1);
1256 assert_eq!(report.summary.ok, 1);
1257 assert_eq!(report.summary.pending, REGISTRY.len() - 1);
1258 assert_eq!(report.exit_code, 0);
1259 }
1260
1261 #[test]
1262 fn doctor_report_marks_a_scope_unknown_when_its_tracking_store_is_unreadable_and_exits_3() {
1263 let dir = tempfile::tempdir().unwrap();
1264 let data_dir = dir.path().join("data");
1265 let shared = dir.path().join("shared").join("store.db");
1266 std::fs::create_dir_all(shared.parent().unwrap()).unwrap();
1267 std::fs::write(&shared, b"definitely not sqlite\n").unwrap();
1268 let report = doctor_report(REGISTRY, &data_dir, dir.path(), &shared);
1269
1270 let global_rows: Vec<_> = report.migrations.iter().filter(|r| r.scope == "global").collect();
1271 assert!(!global_rows.is_empty());
1272 assert!(global_rows.iter().all(|r| r.state == "unknown" && r.verify == Some("error")));
1273 assert!(report.migrations.iter().filter(|r| r.scope == "channel").all(|r| r.state == "pending"));
1274 assert_eq!(report.summary.unknown, global_rows.len());
1275 assert_eq!(report.summary.error, global_rows.len());
1276 assert_eq!(report.tracking_errors.len(), 1, "{:?}", report.tracking_errors);
1278 assert!(report.tracking_errors[0].contains("store.db"));
1279 assert_eq!(report.exit_code, VERIFY_FAILED_EXIT_CODE);
1280 }
1281
1282 #[test]
1283 fn verify_event_line_is_valid_json_even_with_control_characters_in_detail() {
1284 let r = VerifyRecord {
1285 id: "9020_x",
1286 scope: "channel",
1287 outcome: VerifyOutcome::Error("line one\nline \"two\"\t\\end".into()),
1288 };
1289 let line = verify_event_line(&r);
1290 let parsed: serde_json::Value = serde_json::from_str(&line).expect("one JSON object per line");
1291 assert_eq!(parsed["event"], "migration_verify");
1292 assert_eq!(parsed["status"], "error");
1293 assert_eq!(parsed["detail"], "line one\nline \"two\"\t\\end");
1294 assert!(!line.contains('\n'), "must stay on one line");
1295 }
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300 use super::*;
1301
1302 use crate::test_support::ISOLATED_AUTH_ENV_LOCK as ENV_LOCK;
1309
1310 fn clear() {
1311 std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
1312 std::env::remove_var("AGENTMUX_SHARED_DIR");
1313 std::env::remove_var("AGENTMUX_ISOLATED_AUTH");
1314 std::env::remove_var("AGENTMUX_INSTANCE_DIR");
1315 std::env::remove_var("AGENTMUX_CHANNEL");
1316 }
1317
1318 #[test]
1321 fn an_unreadable_shared_store_is_an_error_not_a_zero() {
1322 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1327 clear();
1328 let home = tempfile::tempdir().expect("tempdir");
1331 std::env::set_var("AGENTMUX_HOME_OVERRIDE", home.path());
1332 let data_dir = home.path().join("data");
1333
1334 let strict = try_count_pending_migrations(&data_dir);
1335 let lenient = count_pending_migrations(&data_dir);
1336 clear();
1337
1338 match strict {
1339 Err(PendingCountError::SharedStoreUnreadable { .. }) => {}
1340 Err(other) => panic!("expected SharedStoreUnreadable, got {other}"),
1341 Ok(n) => panic!("an unreadable shared store must not read as {n} pending"),
1342 }
1343 assert_eq!(lenient, 0, "the lenient wrapper still reports 0, as it always did");
1344 }
1345
1346 #[test]
1347 fn the_lenient_wrapper_keeps_reporting_the_global_half_it_could_read() {
1348 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1354 clear();
1355 let home = tempfile::tempdir().expect("tempdir");
1356 std::fs::create_dir_all(home.path().join("shared")).expect("shared dir");
1357 std::env::set_var("AGENTMUX_HOME_OVERRIDE", home.path());
1358 let data_dir = home.path().join("no-such-data-dir");
1360
1361 let strict = try_count_pending_migrations(&data_dir);
1362 let lenient = count_pending_migrations(&data_dir);
1363 let global_pending = match &strict {
1364 Err(PendingCountError::ChannelStoreUnreadable { global_pending, .. }) => *global_pending,
1365 other => {
1366 let msg = format!("precondition: expected ChannelStoreUnreadable, got {other:?}");
1367 clear();
1368 panic!("{msg}");
1369 }
1370 };
1371 clear();
1372
1373 assert_eq!(
1374 lenient, global_pending,
1375 "the lenient wrapper must keep reporting the readable global-scope count"
1376 );
1377 }
1378
1379 #[test]
1380 fn readable_pending_keeps_the_global_half_but_claims_nothing_otherwise() {
1381 assert_eq!(
1385 PendingCountError::ChannelStoreUnreadable {
1386 path: std::path::PathBuf::from("/tmp/objects.db"),
1387 error: "locked".into(),
1388 global_pending: 3,
1389 }
1390 .readable_pending(),
1391 3
1392 );
1393 assert_eq!(PendingCountError::SharedStoreUnresolvable.readable_pending(), 0);
1394 assert_eq!(
1395 PendingCountError::SharedStoreUnreadable {
1396 path: std::path::PathBuf::from("/tmp/store.db"),
1397 error: "locked".into(),
1398 }
1399 .readable_pending(),
1400 0
1401 );
1402 }
1403
1404 #[test]
1405 fn a_pending_count_error_says_which_store_and_why() {
1406 let e = PendingCountError::SharedStoreUnreadable {
1410 path: std::path::PathBuf::from("/tmp/store.db"),
1411 error: "disk I/O error".to_string(),
1412 };
1413 let msg = e.to_string();
1414 assert!(msg.contains("store.db"), "{msg}");
1415 assert!(msg.contains("disk I/O error"), "{msg}");
1416 }
1417
1418 #[test]
1427 fn home_is_invariant_to_isolated_auth() {
1428 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1429 clear();
1430 std::env::set_var("AGENTMUX_HOME_OVERRIDE", "/tmp/test-home");
1431
1432 let home_default = resolve_home().unwrap();
1433 assert_eq!(home_default, PathBuf::from("/tmp/test-home"));
1434
1435 let shared_store_path_default = resolve_shared_store_path().unwrap();
1436
1437 std::env::set_var("AGENTMUX_ISOLATED_AUTH", "1");
1438 std::env::set_var("AGENTMUX_INSTANCE_DIR", "/tmp/test-home/dev/some-branch");
1439 let home_isolated = resolve_home().unwrap();
1440 let shared_store_path_isolated = resolve_shared_store_path().unwrap();
1441
1442 assert_eq!(
1443 home_default, home_isolated,
1444 "resolve_home() must be invariant to AGENTMUX_ISOLATED_AUTH/AGENTMUX_INSTANCE_DIR"
1445 );
1446 assert_ne!(
1450 shared_store_path_default, shared_store_path_isolated,
1451 "resolve_shared_store_path() must actually change under isolation"
1452 );
1453
1454 clear();
1455 }
1456
1457 #[test]
1462 fn home_and_store_are_invariant_to_the_channel_when_auth_is_shared() {
1463 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1464 clear();
1465 std::env::set_var("AGENTMUX_HOME_OVERRIDE", "/tmp/test-home");
1466
1467 let home_default = resolve_home().unwrap();
1468 let shared_store_path_default = resolve_shared_store_path().unwrap();
1469
1470 std::env::set_var("AGENTMUX_CHANNEL", "dev-some-branch");
1472 std::env::set_var("AGENTMUX_INSTANCE_DIR", "/tmp/test-home/dev/some-branch");
1473 let home_isolated = resolve_home().unwrap();
1474 let shared_store_path_isolated = resolve_shared_store_path().unwrap();
1475
1476 assert_eq!(
1477 home_default, home_isolated,
1478 "resolve_home() must not depend on the channel"
1479 );
1480 assert_eq!(
1481 shared_store_path_default, shared_store_path_isolated,
1482 "a non-stable channel alone must not move the shared store"
1483 );
1484
1485 std::env::set_var("AGENTMUX_ISOLATED_AUTH", "1");
1487 assert_eq!(resolve_home().unwrap(), home_default);
1488 assert_ne!(resolve_shared_store_path().unwrap(), shared_store_path_default);
1489
1490 clear();
1491 }
1492}