Skip to main content

agentmux_srv_core/backend/slug_migration/
run.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A run: plan, preconditions, backup, then each agent's steps through the
5//! journal and its verification, agent by agent (ยง5.2); and the two ways
6//! back, journal mode and restore mode.
7
8use std::path::{Path, PathBuf};
9
10use super::backup::{self, BackupList};
11use super::home::{fold, Home};
12use super::journal::{journals, Journal, Record, Step, STEPS};
13use super::preconditions;
14use super::steps::{self, Agent, Ctx};
15use super::{steps_files, verify};
16use crate::backend::rpc_types::{ForkSlugCandidate, ForkSlugChoice, ForkSlugMigrated, ForkSlugReport};
17
18/// Where a test stops a run, as a crash would.
19#[cfg(any(test, feature = "test-support"))]
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub(super) enum Crash {
22    /// After the step's change, before its result is recorded.
23    BeforeDone(Step),
24    /// After its result is recorded.
25    AfterDone(Step),
26}
27
28#[derive(Default)]
29pub(super) struct Options {
30    #[cfg(any(test, feature = "test-support"))]
31    pub crash: Option<(String, Crash)>,
32    /// Runs just before an agent's target is checked again, as another
33    /// channel creating an agent during the backup would.
34    #[cfg(any(test, feature = "test-support"))]
35    pub before_recheck: Option<Box<dyn Fn()>>,
36}
37
38pub(super) const CRASHED: &str = "crashed (test)";
39
40fn agents(candidates: &[ForkSlugCandidate]) -> Vec<Agent> {
41    candidates
42        .iter()
43        .filter(|c| c.refused.is_none())
44        .map(|c| Agent { uid: c.uid.clone(), name: c.name.clone(), old: c.old_slug.clone(), new: c.new_slug.clone() })
45        .collect()
46}
47
48/// The latest run that neither finished nor was rolled back: the one an
49/// apply resumes.
50fn unfinished(home: &Home) -> Result<Option<Journal>, String> {
51    for path in journals(&home.backups()) {
52        // A journal whose header a crash tore holds no run to resume, and
53        // must not block new ones (#5342).
54        let j = match Journal::read(&path) {
55            Ok(j) => j,
56            Err(e) => {
57                tracing::warn!(journal = %path.display(), error = %e, "fork slug migration: skipped a journal it can't read");
58                continue;
59            }
60        };
61        if j.finished().is_none() && !j.rolled_back() {
62            return Journal::open(&path).map(Some);
63        }
64    }
65    Ok(None)
66}
67
68/// Every file a run of `agents` may change, for the backup. S8's moves
69/// (`gh-<slug>`, the bashwrap cwd file) need none: they are moved back.
70pub(super) fn backup_list(ctx: &Ctx, agents: &[Agent]) -> Result<BackupList, String> {
71    let mut list = BackupList { databases: ctx.objects_dbs(), files: Vec::new() };
72    list.databases.extend(ctx.wan_dbs());
73    list.databases.extend(ctx.host_stores());
74    for a in agents {
75        list.files.push(steps_files::def_path(ctx.home, &a.uid));
76        list.files.extend(steps_files::mcp_files(ctx, a)?);
77        list.files.extend(steps_files::stale_registrations(ctx, a));
78    }
79    list.files.retain(|f| f.is_file());
80    list.files.dedup();
81    Ok(list)
82}
83
84fn new_run_dir(home: &Home) -> PathBuf {
85    let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%S%.3fZ");
86    home.backups().join(format!("slug-migration-{stamp}"))
87}
88
89/// Migrate every candidate the plan doesn't refuse, or resume the run that
90/// stopped. Refuses before any write when a precondition fails.
91pub(super) fn apply(home: &Home, opts: &Options) -> Result<ForkSlugReport, String> {
92    apply_choosing(home, opts, &[])
93}
94
95/// [`apply`], giving the agents in `choices` the id the user picked. A run being resumed
96/// already has its ids (its journal holds the plan), so a pick can't change them: finish it first.
97pub(super) fn apply_choosing(home: &Home, opts: &Options, choices: &[ForkSlugChoice]) -> Result<ForkSlugReport, String> {
98    let _lock = preconditions::take_lock(home)?;
99    let installs = home.installs()?;
100    let mut journal = match unfinished(home)? {
101        Some(_) if !choices.is_empty() => {
102            return Err("an update that stopped halfway has to finish before an id can be chosen: run it again first".into());
103        }
104        Some(j) => {
105            let pending: Vec<ForkSlugCandidate> =
106                j.header().1.candidates.iter().filter(|c| !j.verified(&c.uid)).cloned().collect();
107            let mut refusals = Vec::new();
108            for c in pending.iter().filter(|c| c.refused.is_none()) {
109                let def = super::plan::load_defs(home)?.0.into_iter().find(|d| d.uid == c.uid);
110                if let Some(def) = def {
111                    for r in super::running::running(home, &installs, &def)? {
112                        refusals.push(format!("{} is running ({}): stop it first", c.name, r.how));
113                    }
114                }
115            }
116            refusals.extend(preconditions::old_instances(home, &installs));
117            if !refusals.is_empty() {
118                return Err(format!("not resuming the run in {}: {}", j.dir().display(), refusals.join("; ")));
119            }
120            j
121        }
122        None => {
123            let plan = super::plan::plan_with(home, false, false, choices)?;
124            if !plan.blockers.is_empty() {
125                let why: Vec<&str> = plan.blockers.iter().map(|b| b.message.as_str()).collect();
126                return Err(format!("not migrating: {}", why.join("; ")));
127            }
128            let ready = agents(&plan.candidates);
129            if ready.is_empty() {
130                return Ok(ForkSlugReport { notes: vec![plan.summary.clone()], ..Default::default() });
131            }
132            let dir = new_run_dir(home);
133            let ctx = Ctx { home, installs: &installs, run_dir: dir.clone(), backups: &[], retired_at: 0 };
134            let entries = backup::take(&dir, &backup_list(&ctx, &ready)?)?;
135            let now = agentmux_common::time::now_ms();
136            Journal::create(&dir, now, now, plan, entries)?
137        }
138    };
139    let (retired_at, plan, backups) = journal.header();
140    let (plan, backups) = (plan.clone(), backups.to_vec());
141    let ctx = Ctx { home, installs: &installs, run_dir: journal.dir(), backups: &backups, retired_at };
142    for a in agents(&plan.candidates) {
143        if journal.verified(&a.uid) || journal.skipped(&a.uid).is_some() {
144            continue;
145        }
146        if let Err(e) = run_agent_reserved(&ctx, &mut journal, &a, opts) {
147            if e != CRASHED {
148                journal.append(Record::Failed { uid: a.uid.clone(), error: e.clone() })?;
149            }
150            return Err(e);
151        }
152        if journal.skipped(&a.uid).is_some() {
153            continue;
154        }
155        let problems = verify::verify(&ctx, &a)?;
156        if !problems.is_empty() {
157            let error = format!("{} didn't verify: {}", a.name, problems.join("; "));
158            journal.append(Record::Failed { uid: a.uid.clone(), error: error.clone() })?;
159            return Ok(report(&journal, &plan, Some(error)));
160        }
161        journal.append(Record::Verified { uid: a.uid.clone() })?;
162    }
163    // Only files: restore mode compares them, and takes databases back row
164    // by row without a digest.
165    let mut after = Vec::new();
166    for b in backups.iter().filter(|b| !b.database) {
167        after.push(backup::fingerprint(Path::new(&b.original), false)?);
168    }
169    journal.append(Record::Finished { at: agentmux_common::time::now_ms(), after })?;
170    Ok(report(&journal, &plan, None))
171}
172
173/// One agent's steps. Before its first write, its new id is checked again
174/// under the host-wide slug allocation lock, the one every channel creating
175/// an agent holds while it picks and publishes a slug: the plan was made
176/// before the backup, which can take a while, and another channel may have
177/// handed the id out since. The lock is held through S1 and S2, which
178/// publish the new id in the shared definition and every `objects.db`, and
179/// released before the rest. A target taken in the meantime leaves the agent
180/// out of the run with nothing written for it (`Record::Skipped`).
181///
182/// Only a finished S1 reserves the id, so a resume checks again until S1 is
183/// done; a target taken meanwhile stops the run for a rollback (#5342).
184fn run_agent_reserved(ctx: &Ctx, journal: &mut Journal, a: &Agent, opts: &Options) -> Result<(), String> {
185    if journal.done(&a.uid, Step::S1) {
186        return run_agent(ctx, journal, a, opts, &STEPS);
187    }
188    #[cfg(any(test, feature = "test-support"))]
189    if let Some(hook) = &opts.before_recheck {
190        hook();
191    }
192    let store = crate::registry::DefinitionStore::open(ctx.home.definitions()).map_err(|e| e.to_string())?;
193    let allocation = store.lock_slug_allocation().map_err(|e| e.to_string())?;
194    let (defs, unreadable) = super::plan::load_defs(ctx.home)?;
195    let holder = if unreadable.is_empty() {
196        super::plan::holder_of(ctx.home, ctx.installs, &defs, &Default::default(), &a.uid, &a.new)?
197    } else {
198        Some(format!("the shared definitions can't all be read ({})", unreadable.join("; ")))
199    };
200    if let Some(holder) = holder {
201        if journal.intent(&a.uid, Step::S1).is_some() {
202            return Err(format!(
203                "{}: {} was taken while the run was interrupted ({holder}); roll this run back from its journal",
204                a.name, a.new
205            ));
206        }
207        let reason = format!("{} wasn't updated: {} was taken after the plan ({holder})", a.name, a.new);
208        tracing::warn!(uid = %a.uid, target = %a.new, %holder, "fork slug migration: target taken since the plan; agent left out");
209        journal.append(Record::Skipped { uid: a.uid.clone(), reason })?;
210        return Ok(());
211    }
212    run_agent(ctx, journal, a, opts, &STEPS[..2])?;
213    drop(allocation);
214    run_agent(ctx, journal, a, opts, &STEPS[2..])
215}
216
217/// `steps` of one agent, each recorded before and after it runs.
218fn run_agent(ctx: &Ctx, journal: &mut Journal, a: &Agent, opts: &Options, steps: &[Step]) -> Result<(), String> {
219    let _ = opts;
220    for &step in steps {
221        if journal.done(&a.uid, step) {
222            continue;
223        }
224        let before = match journal.intent(&a.uid, step) {
225            Some(b) => b.clone(),
226            None => {
227                let b = steps::before(ctx, a, step)?;
228                journal.append(Record::Intent { uid: a.uid.clone(), step, before: b.clone() })?;
229                b
230            }
231        };
232        let changes = steps::apply(ctx, a, step, &before).map_err(|e| format!("{} {step:?}: {e}", a.name))?;
233        #[cfg(any(test, feature = "test-support"))]
234        if opts.crash == Some((a.uid.clone(), Crash::BeforeDone(step))) {
235            return Err(CRASHED.into());
236        }
237        journal.append(Record::Done { uid: a.uid.clone(), step, changes })?;
238        #[cfg(any(test, feature = "test-support"))]
239        if opts.crash == Some((a.uid.clone(), Crash::AfterDone(step))) {
240            return Err(CRASHED.into());
241        }
242    }
243    Ok(())
244}
245
246fn report(journal: &Journal, plan: &crate::backend::rpc_types::ForkSlugPlan, failed: Option<String>) -> ForkSlugReport {
247    let migrated: Vec<ForkSlugMigrated> = plan
248        .candidates
249        .iter()
250        .filter(|c| journal.verified(&c.uid))
251        .map(|c| ForkSlugMigrated {
252            uid: c.uid.clone(),
253            name: c.name.clone(),
254            old_slug: c.old_slug.clone(),
255            new_slug: c.new_slug.clone(),
256            changes: journal.changes(&c.uid),
257        })
258        .collect();
259    let pr_searches = migrated
260        .iter()
261        .map(|m| format!("gh-agent pr list --state open --search \"agentmux:agent_id={} in:body\"", fold(&m.old_slug)))
262        .collect();
263    let mut notes: Vec<String> = plan.candidates.iter().filter_map(|c| journal.skipped(&c.uid).map(str::to_string)).collect();
264    if !migrated.is_empty() {
265        notes.extend([
266            "Relaunch each migrated agent: it takes its new id, fresh signing keys and a new WAN key publication at its next spawn.".to_string(),
267            "Run each search in every repository the agent opens PRs in, and change agentmux:agent_id in each body with gh-agent pr edit; for 30 days the old id still receives review notices.".to_string(),
268            "The old id's WAN key record stays in the account's key directory: nothing on this side can remove it, and no key here signs under that name any more.".to_string(),
269            "LAN peers pin the new id's key on first use; other agents' notes and memory that mention the old id are theirs to update.".to_string(),
270            format!(
271                "The backup in {} holds copies of the databases, signing keys and credentials included: delete it once you won't roll back.",
272                journal.dir().display()
273            ),
274        ]);
275    }
276    ForkSlugReport {
277        journal: journal.path.display().to_string(),
278        backup_dir: journal.dir().display().to_string(),
279        migrated,
280        failed: failed.or_else(|| journal.last_failure()),
281        pr_searches,
282        notes,
283    }
284}
285
286/// The journal to roll back: `path`, or the latest run.
287fn pick(home: &Home, path: Option<&str>) -> Result<Journal, String> {
288    match path {
289        Some(p) => Journal::open(Path::new(p)),
290        None => {
291            let latest = journals(&home.backups()).into_iter().next().ok_or("no fork slug migration has run here")?;
292            Journal::open(&latest)
293        }
294    }
295}
296
297/// Refuse to undo `journal`'s run while any agent it touched runs anywhere
298/// on this host, under its old id or its new one (a relaunch takes the new
299/// one), or while an AgentMux too old for former slugs runs: either would
300/// keep using, or write back, what the undo changes. The caller holds the
301/// migration lock.
302fn refuse_undo_while_running(home: &Home, installs: &[super::home::Install], journal: &Journal) -> Result<(), String> {
303    let (defs, _) = super::plan::load_defs(home)?;
304    let touched: std::collections::HashSet<String> = journal.intents().into_iter().map(|(uid, _, _)| uid).collect();
305    let mut why = Vec::new();
306    for c in journal.header().1.candidates.iter().filter(|c| touched.contains(&c.uid)) {
307        let mut def = defs.iter().find(|d| d.uid == c.uid).cloned().unwrap_or_else(|| super::plan::Def {
308            uid: c.uid.clone(),
309            name: c.name.clone(),
310            slug: c.new_slug.clone(),
311            ..Default::default()
312        });
313        def.former.extend([c.old_slug.clone(), c.new_slug.clone()]);
314        for r in super::running::running(home, installs, &def)? {
315            let at = if r.channel.is_empty() { String::new() } else { format!(" in {}", r.channel) };
316            why.push(format!("{} is running{at} ({}): stop it first", c.name, r.how));
317        }
318    }
319    why.extend(preconditions::old_instances(home, installs));
320    if why.is_empty() {
321        Ok(())
322    } else {
323        Err(format!("not rolling back: {}", why.join("; ")))
324    }
325}
326
327/// Journal mode: undo every step that has an intent, newest first, each
328/// from its before-image. Resumable: a step already undone is skipped.
329pub(super) fn rollback(home: &Home, path: Option<&str>) -> Result<ForkSlugReport, String> {
330    let _lock = preconditions::take_lock(home)?;
331    let mut journal = pick(home, path)?;
332    if journal.rolled_back() {
333        return Ok(ForkSlugReport {
334            journal: journal.path.display().to_string(),
335            backup_dir: journal.dir().display().to_string(),
336            notes: vec!["this run was already rolled back".into()],
337            ..Default::default()
338        });
339    }
340    let installs = home.installs()?;
341    refuse_undo_while_running(home, &installs, &journal)?;
342    let (retired_at, plan, backups) = journal.header();
343    let (plan, backups) = (plan.clone(), backups.to_vec());
344    let ctx = Ctx { home, installs: &installs, run_dir: journal.dir(), backups: &backups, retired_at };
345    let mut notes = Vec::new();
346    for (uid, step, before) in journal.intents().into_iter().rev() {
347        if journal.undone(&uid, step) {
348            continue;
349        }
350        let Some(c) = plan.candidates.iter().find(|c| c.uid == uid) else { continue };
351        let a = Agent { uid: uid.clone(), name: c.name.clone(), old: c.old_slug.clone(), new: c.new_slug.clone() };
352        journal.append(Record::Undo { uid: uid.clone(), step })?;
353        let changes = steps::undo(&ctx, &a, step, &before).map_err(|e| format!("{} {step:?} undo: {e}", a.name))?;
354        notes.extend(changes.iter().map(|c| format!("{} {step:?}: {c}", a.name)));
355        journal.append(Record::Undone { uid, step, changes })?;
356    }
357    journal.append(Record::RolledBack { at: agentmux_common::time::now_ms(), mode: "journal".into() })?;
358    Ok(ForkSlugReport {
359        journal: journal.path.display().to_string(),
360        backup_dir: journal.dir().display().to_string(),
361        notes,
362        ..Default::default()
363    })
364}
365
366/// Restore mode: put the backed-up files back as they were, only while every
367/// one the run left is unchanged since it finished (its bytes and
368/// modification time); the moved folders go back through the journal.
369///
370/// Databases go back row by row through journal mode's database undos, never
371/// as a whole copy, which would drop other panes' writes since (#5342).
372pub(super) fn restore(home: &Home, path: Option<&str>) -> Result<ForkSlugReport, String> {
373    let _lock = preconditions::take_lock(home)?;
374    let mut journal = pick(home, path)?;
375    if journal.rolled_back() {
376        return Err("this run was already rolled back".into());
377    }
378    let after = journal.finished().ok_or("this run didn't finish: roll it back from its journal instead")?.to_vec();
379    refuse_undo_while_running(home, &home.installs()?, &journal)?;
380    let mut changed = Vec::new();
381    for f in after.iter().filter(|f| !is_database(&journal, &f.path)) {
382        let now = backup::fingerprint(Path::new(&f.path), false)?;
383        if now.digest != f.digest || now.mtime_ms != f.mtime_ms {
384            changed.push(f.path.clone());
385        }
386    }
387    if !changed.is_empty() {
388        return Err(format!("written since the run, so the backup can't be put back: {}; roll back from the journal instead", changed.join(", ")));
389    }
390    let (retired_at, plan, backups) = journal.header();
391    let (plan, backups) = (plan.clone(), backups.to_vec());
392    let dir = journal.dir();
393    let mut notes = Vec::new();
394    for b in backups.iter().filter(|b| !b.database) {
395        let copy = backup::copy_of(&dir, &backups, Path::new(&b.original))?;
396        let bytes = std::fs::read(&copy).map_err(|e| e.to_string())?;
397        super::home::write_file(Path::new(&b.original), &bytes)?;
398        notes.push(format!("restored {}", b.original));
399    }
400    let installs = home.installs()?;
401    let ctx = Ctx { home, installs: &installs, run_dir: dir.clone(), backups: &backups, retired_at };
402    for (uid, step, before) in journal.intents().into_iter().rev() {
403        let Some(c) = plan.candidates.iter().find(|c| c.uid == uid) else { continue };
404        let a = Agent { uid: uid.clone(), name: c.name.clone(), old: c.old_slug.clone(), new: c.new_slug.clone() };
405        let changes = match step {
406            // S1's file came back with the others above; S5 changes nothing.
407            Step::S1 | Step::S5 => continue,
408            Step::S2 | Step::S3 | Step::S4 | Step::S6 | Step::S8 => steps::undo(&ctx, &a, step, &before)?,
409            // Its `.mcp.json` files came back above; its rows go back here.
410            Step::S7 => super::steps_db::s7_undo(&a, &before)?,
411        };
412        notes.extend(changes.iter().map(|c| format!("{} {step:?}: {c}", a.name)));
413    }
414    journal.append(Record::RolledBack { at: agentmux_common::time::now_ms(), mode: "restore".into() })?;
415    Ok(ForkSlugReport { journal: journal.path.display().to_string(), backup_dir: dir.display().to_string(), notes, ..Default::default() })
416}
417
418fn is_database(journal: &Journal, path: &str) -> bool {
419    journal.header().2.iter().any(|b| b.original == path && b.database)
420}