surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! `surject migrate loadout`: keeps a Loadout 1.0.x machine working after
//! the rename to Surjection (SPEC 15.3). Idempotent; the CLI and the app
//! run it once at their first start (marker `loadout_migration` in
//! `state/local-settings.toml`), the Windows installer after installing.
//!
//! 1. Data folder: the former default folder is moved (renamed) to the new
//!    default one when that does not exist, and a junction (Windows) or
//!    symbolic link (elsewhere) is left at the old path. A folder named by
//!    `SURJECTION_HOME` or `LOADOUT_HOME` is never moved. A folder in use
//!    (a running Loadout) stops the step; the next start tries again.
//! 2. File names: machine-local files named after Loadout are renamed
//!    ([`versions::rename_legacy_names`], also run by every start).
//! 3. WebView profile: the app's UI preferences, copied from the former
//!    identifier's folder when the new one does not exist.
//! 4. Launchers: owned client entries whose only difference from the
//!    desired entry is the launcher (`loadout`, or an absolute path to
//!    `loadout(.exe)`) are rewritten by the apply engine (owned entries
//!    only, backups, one History commit). Anything else stays pending.
//! 5. Agent skill: the bundled `loadout` skill, when unchanged, is replaced
//!    by the Surjection skill in the same clients ([`agent::swap_legacy`]).

use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::agent::{self, LegacySwap};
use crate::apply::{
    self, ApplyEnv, ApplyRequest, EntryFilter, EntryState, PlanOptions, TargetFilter,
};
use crate::brand;
use crate::env::{Env, KnownFolder, Os};
use crate::error::{CoreError, ErrorCode};
use crate::formats::NativeValue;
use crate::fs::Fs;
use crate::local_settings::LocalSettings;
use crate::model::applied::ApplyTrigger;
use crate::paths::{self, SurjectionHome};
use crate::skills::SkillsEnv;
use crate::store::{CommitId, Operation, Store};
use crate::versions;

/// A step of the migration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StepKind {
    DataFolder,
    FileNames,
    WebviewProfile,
    Launchers,
    AgentSkill,
}

/// What happened in a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StepStatus {
    /// Done in this run.
    Done,
    /// Would be done (dry run).
    Planned,
    /// Nothing to do.
    NotNeeded,
    /// Left alone on purpose (the detail says why).
    Skipped,
    /// Could not be done; the next run tries again.
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Step {
    pub step: StepKind,
    pub status: StepStatus,
    pub detail: String,
    /// Files renamed, entries repaired (`<client> <file>: <name>`).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub items: Vec<String>,
}

impl Step {
    fn new(step: StepKind, status: StepStatus, detail: impl Into<String>) -> Self {
        Self {
            step,
            status,
            detail: detail.into(),
            items: Vec::new(),
        }
    }
}

/// What a run did, step by step.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Report {
    pub dry_run: bool,
    pub steps: Vec<Step>,
    /// The History commit of the launcher repair.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit: Option<String>,
}

impl Report {
    /// Whether any step did (or, in a dry run, would do) something.
    pub fn changed(&self) -> bool {
        self.steps
            .iter()
            .any(|step| matches!(step.status, StepStatus::Done | StepStatus::Planned))
    }

    /// Whether a step failed (the marker is not written then).
    pub fn failed(&self) -> bool {
        self.steps
            .iter()
            .any(|step| step.status == StepStatus::Failed)
    }

    pub fn step(&self, kind: StepKind) -> Option<&Step> {
        self.steps.iter().find(|step| step.step == kind)
    }
}

// ----------------------------------------------------------- data folder

/// Step 1. Runs before the data folder is resolved (the CLI and the app
/// call it first). Never fails: a failure is the step's status.
pub fn data_folder(env: &Env, dry_run: bool) -> Step {
    let kind = StepKind::DataFolder;
    if let Some((name, _)) = paths::home_var(env) {
        return Step::new(
            kind,
            StepStatus::Skipped,
            format!("{name} is set: that folder stays where it is"),
        );
    }
    let new = paths::default_surjection_home(env);
    let old = paths::legacy_default_home(env);
    if is_link(&old) {
        return Step::new(
            kind,
            StepStatus::NotNeeded,
            format!("{} is a link already", old.display()),
        );
    }
    if !old.is_dir() {
        return Step::new(
            kind,
            StepStatus::NotNeeded,
            format!(
                "no {} data folder at {}",
                brand::legacy::PRODUCT_NAME,
                old.display()
            ),
        );
    }
    if new.exists() {
        return Step::new(
            kind,
            StepStatus::Skipped,
            format!(
                "{} exists, so {} is left as it is",
                new.display(),
                old.display()
            ),
        );
    }
    if dry_run {
        return Step::new(
            kind,
            StepStatus::Planned,
            format!(
                "move {} to {} and leave a link at the old path",
                old.display(),
                new.display()
            ),
        );
    }
    if in_use(&old) {
        return in_use_step(&old);
    }
    if let Some(parent) = new.parent()
        && let Err(err) = std::fs::create_dir_all(parent)
    {
        return Step::new(
            kind,
            StepStatus::Failed,
            format!("cannot create {}: {err}", parent.display()),
        );
    }
    if let Err(err) = std::fs::rename(&old, &new) {
        // Another first start won the race: it moved the folder.
        if new.is_dir() && (is_link(&old) || !old.exists()) {
            return Step::new(
                kind,
                StepStatus::NotNeeded,
                format!("{} was moved already", old.display()),
            );
        }
        return if is_sharing_error(&err) {
            in_use_step(&old)
        } else {
            Step::new(
                kind,
                StepStatus::Failed,
                format!("cannot move {} to {}: {err}", old.display(), new.display()),
            )
        };
    }
    let detail = match make_link(&new, &old).or_else(|err| {
        // A link another first start made meanwhile is as good.
        if is_link(&old) { Ok(()) } else { Err(err) }
    }) {
        Ok(()) => format!(
            "moved {} to {}; {} now links to it",
            old.display(),
            new.display(),
            old.display()
        ),
        Err(err) => format!(
            "moved {} to {} (no link left at the old path: {err})",
            old.display(),
            new.display()
        ),
    };
    Step::new(kind, StepStatus::Done, detail)
}

fn in_use_step(old: &Path) -> Step {
    Step::new(
        StepKind::DataFolder,
        StepStatus::Failed,
        format!(
            "{} is in use (is {} running?); close it and run `{} migrate loadout` again (it also \
             runs at the next start)",
            old.display(),
            brand::legacy::PRODUCT_NAME,
            brand::BIN_NAME
        ),
    )
}

/// Whether a running Loadout holds its store lock.
fn in_use(old: &Path) -> bool {
    let lock = old.join("state").join("loadout.lock");
    let Ok(file) = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(&lock)
    else {
        return false;
    };
    matches!(file.try_lock(), Err(std::fs::TryLockError::WouldBlock))
}

/// A rename refused because a file in the folder is open (Windows sharing
/// violation or access denied).
fn is_sharing_error(err: &std::io::Error) -> bool {
    err.kind() == std::io::ErrorKind::PermissionDenied
        || matches!(err.raw_os_error(), Some(5 | 32 | 33))
        || err.kind() == std::io::ErrorKind::ResourceBusy
}

fn is_link(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink())
        || is_junction(path)
}

#[cfg(windows)]
fn is_junction(path: &Path) -> bool {
    junction::exists(path).unwrap_or(false)
}

#[cfg(not(windows))]
fn is_junction(_path: &Path) -> bool {
    false
}

#[cfg(windows)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
    junction::create(target, link)
}

#[cfg(unix)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

// ------------------------------------------------------------ file names

/// Step 2.
pub fn file_names(fs: &dyn Fs, home: &SurjectionHome, dry_run: bool) -> Step {
    let kind = StepKind::FileNames;
    let names = if dry_run {
        versions::legacy_names(fs, home)
    } else {
        versions::rename_legacy_names(fs, home)
    };
    if names.is_empty() {
        return Step::new(
            kind,
            StepStatus::NotNeeded,
            "no file carries the former name",
        );
    }
    let status = if dry_run {
        StepStatus::Planned
    } else {
        StepStatus::Done
    };
    let mut step = Step::new(kind, status, format!("{} file(s) renamed", names.len()));
    step.items = names
        .into_iter()
        .map(|name| format!("{} -> {}", name.from, name.to))
        .collect();
    step
}

// ------------------------------------------------------- WebView profile

/// The folder the desktop app's WebView keeps its profile in for
/// identifier `id` (Tauri's default data directory per OS).
pub fn webview_dir(env: &Env, id: &str) -> PathBuf {
    let base = match env.os() {
        Os::Windows => env
            .known_folder(KnownFolder::LocalAppData)
            .map(Path::to_path_buf)
            .unwrap_or_else(|| env.home().join("AppData").join("Local")),
        Os::Linux => env
            .var("XDG_DATA_HOME")
            .map(PathBuf::from)
            .filter(|path| path.is_absolute())
            .unwrap_or_else(|| env.home().join(".local").join("share")),
        Os::MacOs => env.home().join("Library").join("WebKit"),
    };
    base.join(id)
}

/// Step 3.
pub fn webview_profile(env: &Env, dry_run: bool) -> Step {
    let kind = StepKind::WebviewProfile;
    let old = webview_dir(env, brand::legacy::APP_ID);
    let new = webview_dir(env, brand::APP_ID);
    if !old.is_dir() || is_link(&old) {
        return Step::new(kind, StepStatus::NotNeeded, "no former app profile");
    }
    if new.exists() {
        return Step::new(
            kind,
            StepStatus::NotNeeded,
            format!("{} exists already", new.display()),
        );
    }
    if dry_run {
        return Step::new(
            kind,
            StepStatus::Planned,
            format!("copy {} to {}", old.display(), new.display()),
        );
    }
    // Copied to a temp sibling first, so a failed copy never leaves a
    // half profile at the new path.
    // One temp folder per process: two first starts never share one.
    let temp = new.with_file_name(format!(
        ".{}.copy-{}",
        new.file_name().unwrap_or_default().to_string_lossy(),
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&temp);
    let copied = copy_dir(&old, &temp).and_then(|()| std::fs::rename(&temp, &new));
    match copied {
        // Another first start copied it meanwhile.
        Err(_) if new.is_dir() => {
            let _ = std::fs::remove_dir_all(&temp);
            Step::new(
                kind,
                StepStatus::NotNeeded,
                format!("{} exists already", new.display()),
            )
        }
        Ok(()) => Step::new(
            kind,
            StepStatus::Done,
            format!("copied {} to {}", old.display(), new.display()),
        ),
        Err(err) => {
            let _ = std::fs::remove_dir_all(&temp);
            Step::new(
                kind,
                StepStatus::Failed,
                format!("cannot copy {}: {err}", old.display()),
            )
        }
    }
}

fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(to)?;
    for entry in std::fs::read_dir(from)? {
        let entry = entry?;
        let kind = entry.file_type()?;
        let target = to.join(entry.file_name());
        if kind.is_dir() {
            copy_dir(&entry.path(), &target)?;
        } else if kind.is_file() {
            std::fs::copy(entry.path(), &target)?;
        }
    }
    Ok(())
}

// -------------------------------------------------------------- launchers

/// Whether a launcher token (a whitespace- or quote-separated word) names
/// a binary called `stem` (`stem`, `stem.exe`, or a path ending in one).
fn is_launcher(token: &str, stem: &str) -> bool {
    let name = token.rsplit(['/', '\\']).next().unwrap_or(token);
    let name = name
        .strip_suffix(".exe")
        .or_else(|| name.strip_suffix(".EXE"))
        .unwrap_or(name);
    name.eq_ignore_ascii_case(stem)
}

/// `text` with every launcher token for `stem` replaced by a placeholder.
fn mask_launchers(text: &str, stem: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut word = String::new();
    let flush = |word: &mut String, out: &mut String| {
        if is_launcher(word, stem) {
            out.push('\u{0}');
        } else {
            out.push_str(word);
        }
        word.clear();
    };
    for ch in text.chars() {
        if ch.is_whitespace() || ch == '"' || ch == '\'' {
            flush(&mut word, &mut out);
            out.push(ch);
        } else {
            word.push(ch);
        }
    }
    flush(&mut word, &mut out);
    out
}

/// Whether `observed` equals `desired` once the former launcher in
/// `observed` and the current one in `desired` are set aside, and they
/// differ (so the launcher is the only difference).
pub fn launcher_only(observed: &NativeValue, desired: &NativeValue) -> bool {
    let mut launcher = false;
    same_but_launcher(observed, desired, &mut launcher) && launcher
}

fn same_but_launcher(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
    match (a, b) {
        (NativeValue::String(x), NativeValue::String(y)) => {
            if x == y {
                return true;
            }
            let same =
                mask_launchers(x, brand::legacy::BIN_NAME) == mask_launchers(y, brand::BIN_NAME);
            *launcher |= same;
            same
        }
        (NativeValue::Array(x), NativeValue::Array(y)) => {
            x.len() == y.len()
                && x.iter()
                    .zip(y)
                    .all(|(x, y)| same_but_launcher(x, y, launcher))
        }
        (NativeValue::Object(x), NativeValue::Object(y)) => {
            x.len() == y.len()
                && x.keys().all(|key| {
                    y.get(key)
                        .zip(x.get(key))
                        .is_some_and(|(y, x)| same_but_launcher(x, y, launcher))
                })
        }
        _ => a == b,
    }
}

/// Whether `observed` equals `desired` except that it starts the bare
/// former launcher (`loadout`) where `desired` starts the bare `surject`:
/// how a shared project file Loadout 1.0.x wrote differs. Such an entry is
/// kept as written (teammates may still run 1.0.x).
pub fn legacy_bare_launcher(observed: &NativeValue, desired: &NativeValue) -> bool {
    let mut launcher = false;
    same_but_bare(observed, desired, &mut launcher) && launcher
}

fn mask_bare(text: &str, word: &str) -> String {
    text.split(' ')
        .map(|token| if token == word { "\u{0}" } else { token })
        .collect::<Vec<_>>()
        .join(" ")
}

fn same_but_bare(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
    match (a, b) {
        (NativeValue::String(x), NativeValue::String(y)) => {
            if x == y {
                return true;
            }
            let same = mask_bare(x, brand::legacy::BIN_NAME) == mask_bare(y, brand::BIN_NAME);
            *launcher |= same;
            same
        }
        (NativeValue::Array(x), NativeValue::Array(y)) => {
            x.len() == y.len() && x.iter().zip(y).all(|(x, y)| same_but_bare(x, y, launcher))
        }
        (NativeValue::Object(x), NativeValue::Object(y)) => {
            x.len() == y.len()
                && x.keys().all(|key| {
                    y.get(key)
                        .zip(x.get(key))
                        .is_some_and(|(y, x)| same_but_bare(x, y, launcher))
                })
        }
        _ => a == b,
    }
}

/// One entry to repair.
#[derive(Debug, Clone, PartialEq)]
struct Repair {
    filter: TargetFilter,
    pointer: String,
    name: String,
    label: String,
}

fn filter_of(target: &apply::TargetPlan) -> TargetFilter {
    TargetFilter {
        scope: target.scope,
        project: target.project.clone(),
        file: target.file.clone(),
    }
}

/// The owned entries, unchanged since they were written, whose only
/// difference from the desired entry is the launcher.
fn repairs(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Vec<Repair>, CoreError> {
    let plan = apply::preview(store, ax, &PlanOptions::default())?;
    let mut repairs = Vec::new();
    for target in &plan.targets {
        if target.problem.is_some() || target.read_only.is_some() {
            continue;
        }
        for entry in &target.entries {
            let (Some(observed), Some(desired)) = (&entry.observed, &entry.desired) else {
                continue;
            };
            if entry.state == EntryState::PendingUpdate
                && entry.action == apply::Action::Update
                && launcher_only(observed, desired)
            {
                repairs.push(Repair {
                    filter: filter_of(target),
                    pointer: target.pointer.clone(),
                    name: entry.name.clone(),
                    label: label(target, entry),
                });
            }
        }
    }
    Ok(repairs)
}

fn label(target: &apply::TargetPlan, entry: &apply::EntryPlan) -> String {
    format!(
        "{} {}: {}",
        entry
            .client
            .unwrap_or(target.clients.first().copied().unwrap_or("")),
        target.file.display(),
        entry.name
    )
}

/// The plan of the repairs alone: their files, and in them only their
/// entries (every other entry is held as it is).
fn options(repairs: &[Repair]) -> PlanOptions {
    let mut targets: Vec<TargetFilter> = Vec::new();
    for repair in repairs {
        if !targets.contains(&repair.filter) {
            targets.push(repair.filter.clone());
        }
    }
    PlanOptions {
        targets: Some(targets),
        entries: Some(
            repairs
                .iter()
                .map(|repair| EntryFilter {
                    target: repair.filter.clone(),
                    pointer: repair.pointer.clone(),
                    name: repair.name.clone(),
                })
                .collect(),
        ),
        ..PlanOptions::default()
    }
}

/// Step 4: one apply run (one History commit) over the repairs only.
pub fn launchers(
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
    dry_run: bool,
) -> Result<(Step, Option<CommitId>), CoreError> {
    let kind = StepKind::Launchers;
    let Some(store) = store else {
        return Ok((Step::new(kind, StepStatus::NotNeeded, "no store"), None));
    };
    let repairs = repairs(Some(store), ax)?;
    if repairs.is_empty() {
        return Ok((
            Step::new(
                kind,
                StepStatus::NotNeeded,
                "no entry uses the former launcher",
            ),
            None,
        ));
    }
    let labels: Vec<String> = repairs.iter().map(|repair| repair.label.clone()).collect();
    if dry_run {
        let mut step = Step::new(
            kind,
            StepStatus::Planned,
            format!("{} entr{} to repair", labels.len(), plural_y(labels.len())),
        );
        step.items = labels;
        return Ok((step, None));
    }
    let request = ApplyRequest {
        options: options(&repairs),
        trigger: ApplyTrigger::Review,
    };
    let operation = Operation::new(
        "apply",
        format!(
            "migrate: loadout launchers ({} entr{})",
            labels.len(),
            plural_y(labels.len())
        ),
    );
    let committed = store.transaction(operation, |tx| apply::apply_in(tx, ax, &request))?;
    let report = committed.value;
    let written: Vec<String> = report
        .targets
        .iter()
        .filter(|target| target.written)
        .flat_map(|target| {
            target
                .entries
                .iter()
                .filter(|entry| entry.action == apply::Action::Update)
                .map(move |entry| {
                    format!(
                        "{} {}: {}",
                        entry
                            .client
                            .unwrap_or(target.clients.first().copied().unwrap_or("")),
                        target.file.display(),
                        entry.name
                    )
                })
        })
        .collect();
    let failed = report.targets.iter().any(|target| target.error.is_some());
    let status = if failed {
        StepStatus::Failed
    } else {
        StepStatus::Done
    };
    let mut step = Step::new(
        kind,
        status,
        format!("{} entr{} repaired", written.len(), plural_y(written.len())),
    );
    step.items = written;
    Ok((step, committed.commit))
}

fn plural_y(n: usize) -> &'static str {
    if n == 1 { "y" } else { "ies" }
}

// ------------------------------------------------------------ agent skill

/// Step 5.
pub fn agent_skill(
    store: Option<&Store<'_>>,
    sx: &SkillsEnv<'_>,
    dry_run: bool,
) -> Result<Step, CoreError> {
    let kind = StepKind::AgentSkill;
    let Some(store) = store else {
        return Ok(Step::new(kind, StepStatus::NotNeeded, "no store"));
    };
    let legacy = brand::legacy::SKILL_ID;
    Ok(match agent::swap_legacy(store, sx, dry_run)? {
        LegacySwap::Absent => Step::new(
            kind,
            StepStatus::NotNeeded,
            format!("no {legacy:?} skill in the store"),
        ),
        LegacySwap::Foreign => Step::new(
            kind,
            StepStatus::Skipped,
            format!("the store skill {legacy:?} is your own; it is kept"),
        ),
        LegacySwap::Customized => Step::new(
            kind,
            StepStatus::Skipped,
            format!("the {legacy:?} skill was edited; it is kept as it is"),
        ),
        LegacySwap::Planned => Step::new(
            kind,
            StepStatus::Planned,
            format!(
                "replace the {legacy:?} skill with {:?} for the same clients",
                agent::SKILL_ID
            ),
        ),
        LegacySwap::Swapped { .. } => Step::new(
            kind,
            StepStatus::Done,
            format!(
                "replaced the {legacy:?} skill with {:?} for the same clients",
                agent::SKILL_ID
            ),
        ),
    })
}

// ------------------------------------------------------------------ runs

/// Whether the automatic run at start is done on this machine.
pub fn is_done(fs: &dyn Fs, home: &SurjectionHome) -> bool {
    LocalSettings::load(fs, &home.state_dir())
        .is_ok_and(|settings| settings.loadout_migration.is_some())
}

/// Records the automatic run as done (only in a data folder that exists:
/// a fresh machine gets no state folder from this).
pub fn mark_done(fs: &dyn Fs, home: &SurjectionHome) -> Result<(), CoreError> {
    if !fs.is_dir(&home.state_dir()) {
        return Ok(());
    }
    let state = home.state_dir();
    let mut settings = LocalSettings::load(fs, &state)?;
    if settings.loadout_migration.as_deref() == Some(agent::BUNDLED_VERSION) {
        return Ok(());
    }
    settings.loadout_migration = Some(agent::BUNDLED_VERSION.to_owned());
    settings.save(fs, &state)
}

/// Steps 2 to 5 against a resolved data folder. `early` holds the steps
/// that ran before it was resolved: step 1, and step 3 in the app (before
/// its WebView starts); step 3 runs here when it is not among them.
/// `store` is the opened store, if any.
pub fn run_in_home(
    early: Vec<Step>,
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
    sx: &SkillsEnv<'_>,
    dry_run: bool,
) -> Result<Report, CoreError> {
    let mut report = Report {
        dry_run,
        steps: early,
        commit: None,
    };
    report.steps.push(file_names(ax.fs, ax.home, dry_run));
    if report.step(StepKind::WebviewProfile).is_none() {
        report.steps.push(webview_profile(ax.env, dry_run));
    }
    let (launchers, commit) = launchers(store, ax, dry_run)?;
    report.steps.push(launchers);
    report.commit = commit.map(|commit| commit.to_string());
    report.steps.push(agent_skill(store, sx, dry_run)?);
    if !dry_run && !report.failed() {
        mark_done(ax.fs, ax.home)?;
    }
    Ok(report)
}

/// The error a failed data-folder step is in `--quiet` runs and the app.
pub fn step_error(step: &Step) -> CoreError {
    CoreError::new(ErrorCode::IoError, step.detail.clone())
}