Skip to main content

agentmux_srv_core/backend/slug_migration/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The fork slug migration (`docs/specs/SPEC_FORK_SLUG_MIGRATION_2026_10_22.md`
5//! §4 Phase 2): an operation the operator starts, never a boot step, that
6//! gives each pre-fix fork the id `fork_slug` gives (`loap-loap-2` →
7//! `loap-2`) and keeps the old one as a former slug, which Phase 1 already
8//! routes and reserves.
9//!
10//! - **Plan** (`plan.rs`, the default): candidates by §5.1, a collision check
11//!   across every definition, every `objects.db` on disk and every live
12//!   registration, and every place the old slug is stored. Changes nothing.
13//!   It also reports slugs two agents hold (`duplicates.rs`), with a proposed
14//!   id for the later one, and renames neither.
15//! - **Holders** (`holders.rs`): the same stores read in one pass, which a new
16//!   agent's slug is picked against too (`Store::agent_def_insert`).
17//! - **Preconditions** (`preconditions.rs`): the agents run nowhere on this
18//!   host, every running AgentMux understands former slugs (`stamp.rs`), and
19//!   the host-wide lock `shared/locks/slug-migration.lock` is taken.
20//! - **Backup** (`backup.rs`) into `shared/backups/slug-migration-<ts>/`.
21//! - **Apply** (`run.rs`, `steps*.rs`): S1–S8 per agent, parent first, each
22//!   recorded in the write-ahead journal (`journal.rs`) before and after it
23//!   runs; then **verify** (`verify.rs`) before the next agent.
24//! - **Roll back**: from the journal, step by step, or by restoring the
25//!   backup while nothing has changed since.
26//!
27//! It works on the disk, not on this instance's stores, so it covers
28//! every channel and version and runs the same from the CLI
29//! (`agentmux-srv migrate-fork-slugs`) and from `agents.migrateForkSlugs`.
30
31pub mod backup;
32pub mod duplicates;
33pub mod holders;
34pub mod home;
35pub mod journal;
36pub mod locations;
37pub mod plan;
38pub mod preconditions;
39pub mod run;
40pub mod running;
41pub mod stamp;
42pub mod steps;
43pub mod steps_db;
44pub mod steps_files;
45pub mod verify;
46
47#[cfg(test)]
48mod tests;
49
50pub use holders::HostSlugs;
51pub use home::Home;
52
53use crate::backend::rpc_types::{ForkSlugChoice, ForkSlugMigrationMode, ForkSlugPlan, ForkSlugReport, MigrateForkSlugsResult};
54
55/// The plan for `home`; `quick` finds the candidates only.
56pub fn plan(home: &Home, quick: bool) -> Result<ForkSlugPlan, String> {
57    plan::plan(home, quick)
58}
59
60/// `plan`, `apply`, `rollback` or `restore` on `home`. `stop` needs the
61/// running instance and is the RPC's.
62pub fn run(home: &Home, mode: ForkSlugMigrationMode, journal: Option<&str>, quick: bool) -> Result<MigrateForkSlugsResult, String> {
63    run_choosing(home, mode, journal, quick, &[])
64}
65
66/// The plan for `home` with ids the user picked for some agents (`choices`).
67pub fn plan_choosing(home: &Home, quick: bool, choices: &[ForkSlugChoice]) -> Result<ForkSlugPlan, String> {
68    plan::plan_choosing(home, quick, choices)
69}
70
71/// [`run`] with ids the user picked for some agents; `plan` and `apply` take them, the
72/// other modes ignore them.
73pub fn run_choosing(
74    home: &Home,
75    mode: ForkSlugMigrationMode,
76    journal: Option<&str>,
77    quick: bool,
78    choices: &[ForkSlugChoice],
79) -> Result<MigrateForkSlugsResult, String> {
80    let result = |plan: Option<ForkSlugPlan>, report: Option<ForkSlugReport>| {
81        let summary = match (&plan, &report) {
82            (Some(p), _) => p.summary.clone(),
83            (_, Some(r)) => report_summary(r),
84            _ => String::new(),
85        };
86        MigrateForkSlugsResult { mode, plan, report, pending: Vec::new(), wait_ms: 0, summary }
87    };
88    match mode {
89        ForkSlugMigrationMode::Plan => Ok(result(Some(plan::plan_choosing(home, quick, choices)?), None)),
90        ForkSlugMigrationMode::Apply => Ok(result(None, Some(run::apply_choosing(home, &run::Options::default(), choices)?))),
91        ForkSlugMigrationMode::Rollback => Ok(result(None, Some(run::rollback(home, journal)?))),
92        ForkSlugMigrationMode::Restore => Ok(result(None, Some(run::restore(home, journal)?))),
93        ForkSlugMigrationMode::Stop => Err("stop runs in the app, through agents.migrateForkSlugs".into()),
94    }
95}
96
97/// A report as text: what changed, what is left, and the searches to run.
98pub fn report_summary(r: &ForkSlugReport) -> String {
99    let mut lines = Vec::new();
100    for m in &r.migrated {
101        lines.push(format!("{}: {} -> {}", m.name, m.old_slug, m.new_slug));
102        lines.extend(m.changes.iter().map(|c| format!("  {c}")));
103    }
104    if let Some(f) = &r.failed {
105        lines.push(format!("Stopped: {f}"));
106    }
107    if !r.pr_searches.is_empty() {
108        lines.push("Open PRs that may still carry an old id:".into());
109        lines.extend(r.pr_searches.iter().map(|s| format!("  {s}")));
110    }
111    lines.extend(r.notes.iter().cloned());
112    if !r.journal.is_empty() {
113        lines.push(format!("Journal: {}", r.journal));
114    }
115    lines.join("\n")
116}
117
118/// `agentmux-srv migrate-fork-slugs`: print the result's summary and its
119/// JSON; exit 0 on success, 1 on a refusal or an error.
120pub fn run_cli(mode: ForkSlugMigrationMode, journal: Option<&str>) -> i32 {
121    let outcome = Home::from_env().and_then(|home| run(&home, mode, journal, false));
122    match outcome {
123        Ok(result) => {
124            eprintln!("{}", result.summary);
125            match serde_json::to_string_pretty(&result) {
126                Ok(json) => println!("{json}"),
127                Err(e) => eprintln!("migrate-fork-slugs: {e}"),
128            }
129            i32::from(result.report.as_ref().is_some_and(|r| r.failed.is_some()))
130        }
131        Err(e) => {
132            eprintln!("migrate-fork-slugs: {e}");
133            1
134        }
135    }
136}