Skip to main content

surjection_core/migrate/
loadout.rs

1//! `surject migrate loadout`: keeps a Loadout 1.0.x machine working after
2//! the rename to Surjection (SPEC 15.3). Idempotent; the CLI and the app
3//! run it once at their first start (marker `loadout_migration` in
4//! `state/local-settings.toml`), the Windows installer after installing.
5//!
6//! 1. Data folder: the former default folder is moved (renamed) to the new
7//!    default one when that does not exist, and a junction (Windows) or
8//!    symbolic link (elsewhere) is left at the old path. A folder named by
9//!    `SURJECTION_HOME` or `LOADOUT_HOME` is never moved. A folder in use
10//!    (a running Loadout) stops the step; the next start tries again.
11//! 2. File names: machine-local files named after Loadout are renamed
12//!    ([`versions::rename_legacy_names`], also run by every start).
13//! 3. WebView profile: the app's UI preferences, copied from the former
14//!    identifier's folder when the new one does not exist.
15//! 4. Launchers: owned client entries whose only difference from the
16//!    desired entry is the launcher (`loadout`, or an absolute path to
17//!    `loadout(.exe)`) are rewritten by the apply engine (owned entries
18//!    only, backups, one History commit). Anything else stays pending.
19//! 5. Agent skill: the bundled `loadout` skill, when unchanged, is replaced
20//!    by the Surjection skill in the same clients ([`agent::swap_legacy`]).
21
22use std::path::{Path, PathBuf};
23
24use serde::Serialize;
25
26use crate::agent::{self, LegacySwap};
27use crate::apply::{
28    self, ApplyEnv, ApplyRequest, EntryFilter, EntryState, PlanOptions, TargetFilter,
29};
30use crate::brand;
31use crate::env::{Env, KnownFolder, Os};
32use crate::error::{CoreError, ErrorCode};
33use crate::formats::NativeValue;
34use crate::fs::Fs;
35use crate::local_settings::LocalSettings;
36use crate::model::applied::ApplyTrigger;
37use crate::paths::{self, SurjectionHome};
38use crate::skills::SkillsEnv;
39use crate::store::{CommitId, Operation, Store};
40use crate::versions;
41
42/// A step of the migration.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
44#[serde(rename_all = "snake_case")]
45pub enum StepKind {
46    DataFolder,
47    FileNames,
48    WebviewProfile,
49    Launchers,
50    AgentSkill,
51}
52
53/// What happened in a step.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
55#[serde(rename_all = "snake_case")]
56pub enum StepStatus {
57    /// Done in this run.
58    Done,
59    /// Would be done (dry run).
60    Planned,
61    /// Nothing to do.
62    NotNeeded,
63    /// Left alone on purpose (the detail says why).
64    Skipped,
65    /// Could not be done; the next run tries again.
66    Failed,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
70pub struct Step {
71    pub step: StepKind,
72    pub status: StepStatus,
73    pub detail: String,
74    /// Files renamed, entries repaired (`<client> <file>: <name>`).
75    #[serde(skip_serializing_if = "Vec::is_empty")]
76    pub items: Vec<String>,
77}
78
79impl Step {
80    fn new(step: StepKind, status: StepStatus, detail: impl Into<String>) -> Self {
81        Self {
82            step,
83            status,
84            detail: detail.into(),
85            items: Vec::new(),
86        }
87    }
88}
89
90/// What a run did, step by step.
91#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
92pub struct Report {
93    pub dry_run: bool,
94    pub steps: Vec<Step>,
95    /// The History commit of the launcher repair.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub commit: Option<String>,
98}
99
100impl Report {
101    /// Whether any step did (or, in a dry run, would do) something.
102    pub fn changed(&self) -> bool {
103        self.steps
104            .iter()
105            .any(|step| matches!(step.status, StepStatus::Done | StepStatus::Planned))
106    }
107
108    /// Whether a step failed (the marker is not written then).
109    pub fn failed(&self) -> bool {
110        self.steps
111            .iter()
112            .any(|step| step.status == StepStatus::Failed)
113    }
114
115    pub fn step(&self, kind: StepKind) -> Option<&Step> {
116        self.steps.iter().find(|step| step.step == kind)
117    }
118}
119
120// ----------------------------------------------------------- data folder
121
122/// Step 1. Runs before the data folder is resolved (the CLI and the app
123/// call it first). Never fails: a failure is the step's status.
124pub fn data_folder(env: &Env, dry_run: bool) -> Step {
125    let kind = StepKind::DataFolder;
126    if let Some((name, _)) = paths::home_var(env) {
127        return Step::new(
128            kind,
129            StepStatus::Skipped,
130            format!("{name} is set: that folder stays where it is"),
131        );
132    }
133    let new = paths::default_surjection_home(env);
134    let old = paths::legacy_default_home(env);
135    if is_link(&old) {
136        return Step::new(
137            kind,
138            StepStatus::NotNeeded,
139            format!("{} is a link already", old.display()),
140        );
141    }
142    if !old.is_dir() {
143        return Step::new(
144            kind,
145            StepStatus::NotNeeded,
146            format!(
147                "no {} data folder at {}",
148                brand::legacy::PRODUCT_NAME,
149                old.display()
150            ),
151        );
152    }
153    if new.exists() {
154        return Step::new(
155            kind,
156            StepStatus::Skipped,
157            format!(
158                "{} exists, so {} is left as it is",
159                new.display(),
160                old.display()
161            ),
162        );
163    }
164    if dry_run {
165        return Step::new(
166            kind,
167            StepStatus::Planned,
168            format!(
169                "move {} to {} and leave a link at the old path",
170                old.display(),
171                new.display()
172            ),
173        );
174    }
175    if in_use(&old) {
176        return in_use_step(&old);
177    }
178    if let Some(parent) = new.parent()
179        && let Err(err) = std::fs::create_dir_all(parent)
180    {
181        return Step::new(
182            kind,
183            StepStatus::Failed,
184            format!("cannot create {}: {err}", parent.display()),
185        );
186    }
187    if let Err(err) = std::fs::rename(&old, &new) {
188        // Another first start won the race: it moved the folder.
189        if new.is_dir() && (is_link(&old) || !old.exists()) {
190            return Step::new(
191                kind,
192                StepStatus::NotNeeded,
193                format!("{} was moved already", old.display()),
194            );
195        }
196        return if is_sharing_error(&err) {
197            in_use_step(&old)
198        } else {
199            Step::new(
200                kind,
201                StepStatus::Failed,
202                format!("cannot move {} to {}: {err}", old.display(), new.display()),
203            )
204        };
205    }
206    let detail = match make_link(&new, &old).or_else(|err| {
207        // A link another first start made meanwhile is as good.
208        if is_link(&old) { Ok(()) } else { Err(err) }
209    }) {
210        Ok(()) => format!(
211            "moved {} to {}; {} now links to it",
212            old.display(),
213            new.display(),
214            old.display()
215        ),
216        Err(err) => format!(
217            "moved {} to {} (no link left at the old path: {err})",
218            old.display(),
219            new.display()
220        ),
221    };
222    Step::new(kind, StepStatus::Done, detail)
223}
224
225fn in_use_step(old: &Path) -> Step {
226    Step::new(
227        StepKind::DataFolder,
228        StepStatus::Failed,
229        format!(
230            "{} is in use (is {} running?); close it and run `{} migrate loadout` again (it also \
231             runs at the next start)",
232            old.display(),
233            brand::legacy::PRODUCT_NAME,
234            brand::BIN_NAME
235        ),
236    )
237}
238
239/// Whether a running Loadout holds its store lock.
240fn in_use(old: &Path) -> bool {
241    let lock = old.join("state").join("loadout.lock");
242    let Ok(file) = std::fs::OpenOptions::new()
243        .read(true)
244        .write(true)
245        .open(&lock)
246    else {
247        return false;
248    };
249    matches!(file.try_lock(), Err(std::fs::TryLockError::WouldBlock))
250}
251
252/// A rename refused because a file in the folder is open (Windows sharing
253/// violation or access denied).
254fn is_sharing_error(err: &std::io::Error) -> bool {
255    err.kind() == std::io::ErrorKind::PermissionDenied
256        || matches!(err.raw_os_error(), Some(5 | 32 | 33))
257        || err.kind() == std::io::ErrorKind::ResourceBusy
258}
259
260fn is_link(path: &Path) -> bool {
261    std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink())
262        || is_junction(path)
263}
264
265#[cfg(windows)]
266fn is_junction(path: &Path) -> bool {
267    junction::exists(path).unwrap_or(false)
268}
269
270#[cfg(not(windows))]
271fn is_junction(_path: &Path) -> bool {
272    false
273}
274
275#[cfg(windows)]
276fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
277    junction::create(target, link)
278}
279
280#[cfg(unix)]
281fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
282    std::os::unix::fs::symlink(target, link)
283}
284
285// ------------------------------------------------------------ file names
286
287/// Step 2.
288pub fn file_names(fs: &dyn Fs, home: &SurjectionHome, dry_run: bool) -> Step {
289    let kind = StepKind::FileNames;
290    let names = if dry_run {
291        versions::legacy_names(fs, home)
292    } else {
293        versions::rename_legacy_names(fs, home)
294    };
295    if names.is_empty() {
296        return Step::new(
297            kind,
298            StepStatus::NotNeeded,
299            "no file carries the former name",
300        );
301    }
302    let status = if dry_run {
303        StepStatus::Planned
304    } else {
305        StepStatus::Done
306    };
307    let mut step = Step::new(kind, status, format!("{} file(s) renamed", names.len()));
308    step.items = names
309        .into_iter()
310        .map(|name| format!("{} -> {}", name.from, name.to))
311        .collect();
312    step
313}
314
315// ------------------------------------------------------- WebView profile
316
317/// The folder the desktop app's WebView keeps its profile in for
318/// identifier `id` (Tauri's default data directory per OS).
319pub fn webview_dir(env: &Env, id: &str) -> PathBuf {
320    let base = match env.os() {
321        Os::Windows => env
322            .known_folder(KnownFolder::LocalAppData)
323            .map(Path::to_path_buf)
324            .unwrap_or_else(|| env.home().join("AppData").join("Local")),
325        Os::Linux => env
326            .var("XDG_DATA_HOME")
327            .map(PathBuf::from)
328            .filter(|path| path.is_absolute())
329            .unwrap_or_else(|| env.home().join(".local").join("share")),
330        Os::MacOs => env.home().join("Library").join("WebKit"),
331    };
332    base.join(id)
333}
334
335/// Step 3.
336pub fn webview_profile(env: &Env, dry_run: bool) -> Step {
337    let kind = StepKind::WebviewProfile;
338    let old = webview_dir(env, brand::legacy::APP_ID);
339    let new = webview_dir(env, brand::APP_ID);
340    if !old.is_dir() || is_link(&old) {
341        return Step::new(kind, StepStatus::NotNeeded, "no former app profile");
342    }
343    if new.exists() {
344        return Step::new(
345            kind,
346            StepStatus::NotNeeded,
347            format!("{} exists already", new.display()),
348        );
349    }
350    if dry_run {
351        return Step::new(
352            kind,
353            StepStatus::Planned,
354            format!("copy {} to {}", old.display(), new.display()),
355        );
356    }
357    // Copied to a temp sibling first, so a failed copy never leaves a
358    // half profile at the new path.
359    // One temp folder per process: two first starts never share one.
360    let temp = new.with_file_name(format!(
361        ".{}.copy-{}",
362        new.file_name().unwrap_or_default().to_string_lossy(),
363        std::process::id()
364    ));
365    let _ = std::fs::remove_dir_all(&temp);
366    let copied = copy_dir(&old, &temp).and_then(|()| std::fs::rename(&temp, &new));
367    match copied {
368        // Another first start copied it meanwhile.
369        Err(_) if new.is_dir() => {
370            let _ = std::fs::remove_dir_all(&temp);
371            Step::new(
372                kind,
373                StepStatus::NotNeeded,
374                format!("{} exists already", new.display()),
375            )
376        }
377        Ok(()) => Step::new(
378            kind,
379            StepStatus::Done,
380            format!("copied {} to {}", old.display(), new.display()),
381        ),
382        Err(err) => {
383            let _ = std::fs::remove_dir_all(&temp);
384            Step::new(
385                kind,
386                StepStatus::Failed,
387                format!("cannot copy {}: {err}", old.display()),
388            )
389        }
390    }
391}
392
393fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
394    std::fs::create_dir_all(to)?;
395    for entry in std::fs::read_dir(from)? {
396        let entry = entry?;
397        let kind = entry.file_type()?;
398        let target = to.join(entry.file_name());
399        if kind.is_dir() {
400            copy_dir(&entry.path(), &target)?;
401        } else if kind.is_file() {
402            std::fs::copy(entry.path(), &target)?;
403        }
404    }
405    Ok(())
406}
407
408// -------------------------------------------------------------- launchers
409
410/// Whether a launcher token (a whitespace- or quote-separated word) names
411/// a binary called `stem` (`stem`, `stem.exe`, or a path ending in one).
412fn is_launcher(token: &str, stem: &str) -> bool {
413    let name = token.rsplit(['/', '\\']).next().unwrap_or(token);
414    let name = name
415        .strip_suffix(".exe")
416        .or_else(|| name.strip_suffix(".EXE"))
417        .unwrap_or(name);
418    name.eq_ignore_ascii_case(stem)
419}
420
421/// `text` with every launcher token for `stem` replaced by a placeholder.
422fn mask_launchers(text: &str, stem: &str) -> String {
423    let mut out = String::with_capacity(text.len());
424    let mut word = String::new();
425    let flush = |word: &mut String, out: &mut String| {
426        if is_launcher(word, stem) {
427            out.push('\u{0}');
428        } else {
429            out.push_str(word);
430        }
431        word.clear();
432    };
433    for ch in text.chars() {
434        if ch.is_whitespace() || ch == '"' || ch == '\'' {
435            flush(&mut word, &mut out);
436            out.push(ch);
437        } else {
438            word.push(ch);
439        }
440    }
441    flush(&mut word, &mut out);
442    out
443}
444
445/// Whether `observed` equals `desired` once the former launcher in
446/// `observed` and the current one in `desired` are set aside, and they
447/// differ (so the launcher is the only difference).
448pub fn launcher_only(observed: &NativeValue, desired: &NativeValue) -> bool {
449    let mut launcher = false;
450    same_but_launcher(observed, desired, &mut launcher) && launcher
451}
452
453fn same_but_launcher(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
454    match (a, b) {
455        (NativeValue::String(x), NativeValue::String(y)) => {
456            if x == y {
457                return true;
458            }
459            let same =
460                mask_launchers(x, brand::legacy::BIN_NAME) == mask_launchers(y, brand::BIN_NAME);
461            *launcher |= same;
462            same
463        }
464        (NativeValue::Array(x), NativeValue::Array(y)) => {
465            x.len() == y.len()
466                && x.iter()
467                    .zip(y)
468                    .all(|(x, y)| same_but_launcher(x, y, launcher))
469        }
470        (NativeValue::Object(x), NativeValue::Object(y)) => {
471            x.len() == y.len()
472                && x.keys().all(|key| {
473                    y.get(key)
474                        .zip(x.get(key))
475                        .is_some_and(|(y, x)| same_but_launcher(x, y, launcher))
476                })
477        }
478        _ => a == b,
479    }
480}
481
482/// Whether `observed` equals `desired` except that it starts the bare
483/// former launcher (`loadout`) where `desired` starts the bare `surject`:
484/// how a shared project file Loadout 1.0.x wrote differs. Such an entry is
485/// kept as written (teammates may still run 1.0.x).
486pub fn legacy_bare_launcher(observed: &NativeValue, desired: &NativeValue) -> bool {
487    let mut launcher = false;
488    same_but_bare(observed, desired, &mut launcher) && launcher
489}
490
491fn mask_bare(text: &str, word: &str) -> String {
492    text.split(' ')
493        .map(|token| if token == word { "\u{0}" } else { token })
494        .collect::<Vec<_>>()
495        .join(" ")
496}
497
498fn same_but_bare(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
499    match (a, b) {
500        (NativeValue::String(x), NativeValue::String(y)) => {
501            if x == y {
502                return true;
503            }
504            let same = mask_bare(x, brand::legacy::BIN_NAME) == mask_bare(y, brand::BIN_NAME);
505            *launcher |= same;
506            same
507        }
508        (NativeValue::Array(x), NativeValue::Array(y)) => {
509            x.len() == y.len() && x.iter().zip(y).all(|(x, y)| same_but_bare(x, y, launcher))
510        }
511        (NativeValue::Object(x), NativeValue::Object(y)) => {
512            x.len() == y.len()
513                && x.keys().all(|key| {
514                    y.get(key)
515                        .zip(x.get(key))
516                        .is_some_and(|(y, x)| same_but_bare(x, y, launcher))
517                })
518        }
519        _ => a == b,
520    }
521}
522
523/// One entry to repair.
524#[derive(Debug, Clone, PartialEq)]
525struct Repair {
526    filter: TargetFilter,
527    pointer: String,
528    name: String,
529    label: String,
530}
531
532fn filter_of(target: &apply::TargetPlan) -> TargetFilter {
533    TargetFilter {
534        scope: target.scope,
535        project: target.project.clone(),
536        file: target.file.clone(),
537    }
538}
539
540/// The owned entries, unchanged since they were written, whose only
541/// difference from the desired entry is the launcher.
542fn repairs(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Vec<Repair>, CoreError> {
543    let plan = apply::preview(store, ax, &PlanOptions::default())?;
544    let mut repairs = Vec::new();
545    for target in &plan.targets {
546        if target.problem.is_some() || target.read_only.is_some() {
547            continue;
548        }
549        for entry in &target.entries {
550            let (Some(observed), Some(desired)) = (&entry.observed, &entry.desired) else {
551                continue;
552            };
553            if entry.state == EntryState::PendingUpdate
554                && entry.action == apply::Action::Update
555                && launcher_only(observed, desired)
556            {
557                repairs.push(Repair {
558                    filter: filter_of(target),
559                    pointer: target.pointer.clone(),
560                    name: entry.name.clone(),
561                    label: label(target, entry),
562                });
563            }
564        }
565    }
566    Ok(repairs)
567}
568
569fn label(target: &apply::TargetPlan, entry: &apply::EntryPlan) -> String {
570    format!(
571        "{} {}: {}",
572        entry
573            .client
574            .unwrap_or(target.clients.first().copied().unwrap_or("")),
575        target.file.display(),
576        entry.name
577    )
578}
579
580/// The plan of the repairs alone: their files, and in them only their
581/// entries (every other entry is held as it is).
582fn options(repairs: &[Repair]) -> PlanOptions {
583    let mut targets: Vec<TargetFilter> = Vec::new();
584    for repair in repairs {
585        if !targets.contains(&repair.filter) {
586            targets.push(repair.filter.clone());
587        }
588    }
589    PlanOptions {
590        targets: Some(targets),
591        entries: Some(
592            repairs
593                .iter()
594                .map(|repair| EntryFilter {
595                    target: repair.filter.clone(),
596                    pointer: repair.pointer.clone(),
597                    name: repair.name.clone(),
598                })
599                .collect(),
600        ),
601        ..PlanOptions::default()
602    }
603}
604
605/// Step 4: one apply run (one History commit) over the repairs only.
606pub fn launchers(
607    store: Option<&Store<'_>>,
608    ax: &ApplyEnv<'_>,
609    dry_run: bool,
610) -> Result<(Step, Option<CommitId>), CoreError> {
611    let kind = StepKind::Launchers;
612    let Some(store) = store else {
613        return Ok((Step::new(kind, StepStatus::NotNeeded, "no store"), None));
614    };
615    let repairs = repairs(Some(store), ax)?;
616    if repairs.is_empty() {
617        return Ok((
618            Step::new(
619                kind,
620                StepStatus::NotNeeded,
621                "no entry uses the former launcher",
622            ),
623            None,
624        ));
625    }
626    let labels: Vec<String> = repairs.iter().map(|repair| repair.label.clone()).collect();
627    if dry_run {
628        let mut step = Step::new(
629            kind,
630            StepStatus::Planned,
631            format!("{} entr{} to repair", labels.len(), plural_y(labels.len())),
632        );
633        step.items = labels;
634        return Ok((step, None));
635    }
636    let request = ApplyRequest {
637        options: options(&repairs),
638        trigger: ApplyTrigger::Review,
639    };
640    let operation = Operation::new(
641        "apply",
642        format!(
643            "migrate: loadout launchers ({} entr{})",
644            labels.len(),
645            plural_y(labels.len())
646        ),
647    );
648    let committed = store.transaction(operation, |tx| apply::apply_in(tx, ax, &request))?;
649    let report = committed.value;
650    let written: Vec<String> = report
651        .targets
652        .iter()
653        .filter(|target| target.written)
654        .flat_map(|target| {
655            target
656                .entries
657                .iter()
658                .filter(|entry| entry.action == apply::Action::Update)
659                .map(move |entry| {
660                    format!(
661                        "{} {}: {}",
662                        entry
663                            .client
664                            .unwrap_or(target.clients.first().copied().unwrap_or("")),
665                        target.file.display(),
666                        entry.name
667                    )
668                })
669        })
670        .collect();
671    let failed = report.targets.iter().any(|target| target.error.is_some());
672    let status = if failed {
673        StepStatus::Failed
674    } else {
675        StepStatus::Done
676    };
677    let mut step = Step::new(
678        kind,
679        status,
680        format!("{} entr{} repaired", written.len(), plural_y(written.len())),
681    );
682    step.items = written;
683    Ok((step, committed.commit))
684}
685
686fn plural_y(n: usize) -> &'static str {
687    if n == 1 { "y" } else { "ies" }
688}
689
690// ------------------------------------------------------------ agent skill
691
692/// Step 5.
693pub fn agent_skill(
694    store: Option<&Store<'_>>,
695    sx: &SkillsEnv<'_>,
696    dry_run: bool,
697) -> Result<Step, CoreError> {
698    let kind = StepKind::AgentSkill;
699    let Some(store) = store else {
700        return Ok(Step::new(kind, StepStatus::NotNeeded, "no store"));
701    };
702    let legacy = brand::legacy::SKILL_ID;
703    Ok(match agent::swap_legacy(store, sx, dry_run)? {
704        LegacySwap::Absent => Step::new(
705            kind,
706            StepStatus::NotNeeded,
707            format!("no {legacy:?} skill in the store"),
708        ),
709        LegacySwap::Foreign => Step::new(
710            kind,
711            StepStatus::Skipped,
712            format!("the store skill {legacy:?} is your own; it is kept"),
713        ),
714        LegacySwap::Customized => Step::new(
715            kind,
716            StepStatus::Skipped,
717            format!("the {legacy:?} skill was edited; it is kept as it is"),
718        ),
719        LegacySwap::Planned => Step::new(
720            kind,
721            StepStatus::Planned,
722            format!(
723                "replace the {legacy:?} skill with {:?} for the same clients",
724                agent::SKILL_ID
725            ),
726        ),
727        LegacySwap::Swapped { .. } => Step::new(
728            kind,
729            StepStatus::Done,
730            format!(
731                "replaced the {legacy:?} skill with {:?} for the same clients",
732                agent::SKILL_ID
733            ),
734        ),
735    })
736}
737
738// ------------------------------------------------------------------ runs
739
740/// Whether the automatic run at start is done on this machine.
741pub fn is_done(fs: &dyn Fs, home: &SurjectionHome) -> bool {
742    LocalSettings::load(fs, &home.state_dir())
743        .is_ok_and(|settings| settings.loadout_migration.is_some())
744}
745
746/// Records the automatic run as done (only in a data folder that exists:
747/// a fresh machine gets no state folder from this).
748pub fn mark_done(fs: &dyn Fs, home: &SurjectionHome) -> Result<(), CoreError> {
749    if !fs.is_dir(&home.state_dir()) {
750        return Ok(());
751    }
752    let state = home.state_dir();
753    let mut settings = LocalSettings::load(fs, &state)?;
754    if settings.loadout_migration.as_deref() == Some(agent::BUNDLED_VERSION) {
755        return Ok(());
756    }
757    settings.loadout_migration = Some(agent::BUNDLED_VERSION.to_owned());
758    settings.save(fs, &state)
759}
760
761/// Steps 2 to 5 against a resolved data folder. `early` holds the steps
762/// that ran before it was resolved: step 1, and step 3 in the app (before
763/// its WebView starts); step 3 runs here when it is not among them.
764/// `store` is the opened store, if any.
765pub fn run_in_home(
766    early: Vec<Step>,
767    store: Option<&Store<'_>>,
768    ax: &ApplyEnv<'_>,
769    sx: &SkillsEnv<'_>,
770    dry_run: bool,
771) -> Result<Report, CoreError> {
772    let mut report = Report {
773        dry_run,
774        steps: early,
775        commit: None,
776    };
777    report.steps.push(file_names(ax.fs, ax.home, dry_run));
778    if report.step(StepKind::WebviewProfile).is_none() {
779        report.steps.push(webview_profile(ax.env, dry_run));
780    }
781    let (launchers, commit) = launchers(store, ax, dry_run)?;
782    report.steps.push(launchers);
783    report.commit = commit.map(|commit| commit.to_string());
784    report.steps.push(agent_skill(store, sx, dry_run)?);
785    if !dry_run && !report.failed() {
786        mark_done(ax.fs, ax.home)?;
787    }
788    Ok(report)
789}
790
791/// The error a failed data-folder step is in `--quiet` runs and the app.
792pub fn step_error(step: &Step) -> CoreError {
793    CoreError::new(ErrorCode::IoError, step.detail.clone())
794}