surjection-core 1.2.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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! Schema versions of the data folder (SPEC 5.0): which files carry a
//! `schema` number, refusing a data folder a newer Surjection wrote, and
//! migrating files an older Surjection wrote.
//!
//! The store has one version for all of its files ([`SCHEMA_VERSION`]): a
//! pull merges whole trees between machines, so "this store is schema N"
//! must mean one thing on every machine, and bumping it migrates every
//! store file in one commit. State files are machine-local and owned by one
//! module each, so each kind keeps its own version and migrates on its own.
//!
//! [`prepare`] runs before a command touches the data folder (the CLI
//! before any command, the app at startup). A file newer than this build
//! fails it with `unsupported_schema` and nothing is written. Files older
//! than this build are migrated under the store lock, after a second look
//! (another process may have migrated them meanwhile): state files first,
//! each original copied to `backups/schema/<timestamp>/state/`, then the
//! store files as one commit (git history keeps the old versions). A file
//! at the current version is never rewritten, so running it again does
//! nothing.
//!
//! One migration exists: the ledger's 1 -> 2 of the rename to Surjection
//! (no change in the file; it makes Loadout 1.0.x refuse the folder).
//! [`Registry::with_step`] adds a step; it is how a real migration is added
//! and how tests exercise the runner.

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

use toml_edit::{DocumentMut, Item};

use crate::apply::backup::timestamp;
use crate::apply::journal::{APPLIES_DIR, JOURNAL_DIR};
use crate::apply::ledger::LEDGER_FILE;
use crate::apply::unmanaged::SEEN_FILE;
use crate::apply::write_atomic;
use crate::brand;
use crate::eject::EJECT_FILE;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::layering::trust::TRUST_FILE;
use crate::local_settings::LOCAL_SETTINGS_FILE;
use crate::model::{SCHEMA_VERSION, StoreFile};
use crate::paths::SurjectionHome;
use crate::remote::config::REMOTES_FILE;
use crate::remote::sync::STATUS_FILE;
use crate::scan::RULES_OVERRIDE_FILE;
use crate::store::merge::{Files, MERGE_STATE};
use crate::store::{
    CommitId, IDENTITY_FILE, LOCK_TIMEOUT, MACHINE_FILE, Operation, Store, StoreLock,
};

#[cfg(test)]
mod tests;

/// Every kind starts at this version.
const FIRST: i64 = 1;
/// Below `backups/`: one folder per migration with the state files it
/// rewrote, as they were.
pub const BACKUP_DIR: &str = "schema";
const BOM: char = '\u{feff}';

/// Where a file lives in the data folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Area {
    /// `<SURJECTION_HOME>/store`, versioned and synced.
    Store,
    /// `<SURJECTION_HOME>/state`, machine-local.
    State,
}

impl Area {
    /// The folder below the data folder.
    pub fn dir(self) -> &'static str {
        match self {
            Area::Store => "store",
            Area::State => "state",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    Toml,
    Json,
}

/// A file being migrated, parsed. TOML keeps its formatting and comments.
#[derive(Debug, Clone)]
pub enum Doc {
    Toml(DocumentMut),
    Json(serde_json::Value),
}

/// Upgrades one file by one version. Gets the area-relative path and the
/// parsed file; the runner sets `schema` afterwards.
pub type Rewrite = fn(&str, &mut Doc) -> Result<(), CoreError>;

/// One migration step `N -> N + 1` of a kind.
#[derive(Debug, Clone, Copy)]
pub struct Step {
    pub rewrite: Rewrite,
}

/// A kind of versioned file.
#[derive(Debug, Clone)]
pub struct Kind {
    pub name: &'static str,
    pub area: Area,
    pub format: Format,
    /// `steps[i]` upgrades version `1 + i` to `2 + i`.
    steps: Vec<Step>,
    /// Whether an area-relative path (`/`-separated) is of this kind.
    matches: fn(&str) -> bool,
}

impl Kind {
    fn new(name: &'static str, area: Area, format: Format, matches: fn(&str) -> bool) -> Self {
        Self {
            name,
            area,
            format,
            steps: Vec::new(),
            matches,
        }
    }

    /// The highest version this build reads and writes.
    pub fn current(&self) -> i64 {
        FIRST + i64::try_from(self.steps.len()).unwrap_or(i64::MAX - FIRST)
    }
}

/// Runs between a migration's store commit and its working-tree writes
/// (test hook, see [`Registry::with_after_commit`]).
pub type AfterCommit = fn() -> Result<(), CoreError>;

/// Every versioned kind with its migration steps.
#[derive(Debug, Clone)]
pub struct Registry {
    kinds: Vec<Kind>,
    after_commit: Option<AfterCommit>,
}

impl Registry {
    /// The kinds of this build (M56 inventory). Each kind's current version
    /// equals the constant its module reads and writes (checked by a test).
    pub fn builtin() -> Self {
        use Area::{State, Store};
        use Format::{Json, Toml};
        Self {
            kinds: vec![
                Kind::new("store", Store, Toml, is_store_schema_file),
                Kind::new("machine", State, Toml, |p| p == MACHINE_FILE),
                Kind::new("local-settings", State, Toml, |p| p == LOCAL_SETTINGS_FILE),
                Kind::new("remotes", State, Toml, |p| p == REMOTES_FILE),
                Kind::new("remote-status", State, Toml, |p| p == STATUS_FILE),
                Kind::new("scan-rules", State, Toml, |p| p == RULES_OVERRIDE_FILE),
                Kind::new("ledger", State, Json, |p| p == LEDGER_FILE),
                Kind::new("trust", State, Json, |p| p == TRUST_FILE),
                Kind::new("unmanaged-seen", State, Json, |p| p == SEEN_FILE),
                Kind::new("merge-state", State, Json, is_merge_state),
                Kind::new("journal", State, Json, is_journal),
                Kind::new("eject", State, Json, |p| p == EJECT_FILE),
            ],
            after_commit: None,
        }
        // Ledger 1 -> 2 (Surjection 1.1.0): no change in the file. Its only
        // purpose is the version: a Loadout 1.0.x binary that still reaches
        // this data folder (through the link `surject migrate loadout`
        // leaves) refuses it with `unsupported_schema` instead of changing
        // it, while its `exec` and `secret` hooks, which never survey the
        // folder, keep working.
        .with_step("ledger", Step { rewrite: renamed })
    }

    /// Appends a migration step to kind `name`, raising its current version
    /// by one. Panics on an unknown kind (a programming error).
    #[must_use]
    pub fn with_step(mut self, name: &str, step: Step) -> Self {
        let kind = self
            .kinds
            .iter_mut()
            .find(|kind| kind.name == name)
            .unwrap_or_else(|| panic!("unknown file kind {name:?}"));
        kind.steps.push(step);
        self
    }

    /// Test hook: `hook` runs after a migration's store commit and before
    /// its working-tree writes, so a test can stop the migration in its
    /// worst place and check that the next run converges.
    #[must_use]
    pub fn with_after_commit(mut self, hook: AfterCommit) -> Self {
        self.after_commit = Some(hook);
        self
    }

    pub fn kinds(&self) -> &[Kind] {
        &self.kinds
    }

    pub fn kind(&self, name: &str) -> Option<&Kind> {
        self.kinds.iter().find(|kind| kind.name == name)
    }

    fn kind_of(&self, area: Area, relative: &str) -> Option<&Kind> {
        self.kinds
            .iter()
            .find(|kind| kind.area == area && (kind.matches)(relative))
    }
}

/// `loadout.toml` and every store file with a schema (SPEC 4.5).
pub(crate) fn is_store_schema_file(relative: &str) -> bool {
    relative == IDENTITY_FILE || StoreFile::classify(Path::new(relative)).is_some()
}

/// The ledger step of the rename to Surjection: nothing to rewrite.
fn renamed(_: &str, _: &mut Doc) -> Result<(), CoreError> {
    Ok(())
}

fn is_merge_state(relative: &str) -> bool {
    relative
        .strip_prefix("merge/")
        .is_some_and(|name| name == MERGE_STATE)
}

fn is_journal(relative: &str) -> bool {
    [JOURNAL_DIR, APPLIES_DIR].into_iter().any(|dir| {
        relative
            .strip_prefix(dir)
            .and_then(|rest| rest.strip_prefix('/'))
            .is_some_and(|name| !name.contains('/') && name.ends_with(".json"))
    })
}

/// A versioned file found in the data folder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Found {
    pub kind: &'static str,
    pub area: Area,
    /// Below the area's folder, `/`-separated.
    pub relative: String,
    pub version: i64,
}

impl Found {
    /// Relative to the data folder (`store/servers/github.toml`).
    pub fn file(&self) -> String {
        format!("{}/{}", self.area.dir(), self.relative)
    }
}

/// Every versioned file of the data folder with the version it says. The
/// store is read only when it is a repository (as [`Store::open`] does);
/// skill content and `.git` are not walked. Files that do not parse or have
/// no integer `schema` are left out: their readers report them.
///
/// `journal/` and `applies/` hold up to 200 files of one kind, named by
/// ULID, so in time order. While that kind has no migration step only the
/// newest file of each folder is read: a newer Surjection that wrote any of
/// them wrote the newest one last, which is all the refusal needs; a step
/// to run makes every file count again.
pub fn survey(
    fs: &dyn Fs,
    home: &SurjectionHome,
    registry: &Registry,
) -> Result<Vec<Found>, CoreError> {
    let mut found = Vec::new();
    let store = home.store_dir();
    if fs.exists(&store.join(".git")) {
        let mut dirs: Vec<String> = ["", "servers", "skill-meta", "machines"]
            .into_iter()
            .map(str::to_owned)
            .collect();
        for project in list_dirs(fs, &store.join("projects"))? {
            dirs.push(format!("projects/{project}"));
        }
        collect(fs, &store, Area::Store, &dirs, registry, false, &mut found)?;
    }
    let state = home.state_dir();
    let dirs = [String::new(), "merge".to_owned()];
    collect(fs, &state, Area::State, &dirs, registry, false, &mut found)?;
    let newest_only = registry
        .kind("journal")
        .is_some_and(|kind| kind.steps.is_empty());
    let dirs = [JOURNAL_DIR.to_owned(), APPLIES_DIR.to_owned()];
    collect(
        fs,
        &state,
        Area::State,
        &dirs,
        registry,
        newest_only,
        &mut found,
    )?;
    Ok(found)
}

fn collect(
    fs: &dyn Fs,
    root: &Path,
    area: Area,
    dirs: &[String],
    registry: &Registry,
    newest_only: bool,
    found: &mut Vec<Found>,
) -> Result<(), CoreError> {
    for dir in dirs {
        let mut files: Vec<(String, &Kind)> = list_files(fs, &join(root, dir))?
            .into_iter()
            .filter_map(|name| {
                let relative = if dir.is_empty() {
                    name
                } else {
                    format!("{dir}/{name}")
                };
                let kind = registry.kind_of(area, &relative)?;
                Some((relative, kind))
            })
            .collect();
        if newest_only {
            files = files.pop().into_iter().collect();
        }
        for (relative, kind) in files {
            // A file removed or locked meanwhile is someone else's problem.
            let Ok(text) = fs.read_to_string(&join(root, &relative)) else {
                continue;
            };
            if let Some(version) = read_version(kind.format, &text) {
                found.push(Found {
                    kind: kind.name,
                    area,
                    relative,
                    version,
                });
            }
        }
    }
    Ok(())
}

/// Names of the files directly in `dir`, sorted; empty when it is absent.
fn list_files(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
    list(fs, dir, false)
}

fn list_dirs(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
    list(fs, dir, true)
}

fn list(fs: &dyn Fs, dir: &Path, dirs: bool) -> Result<Vec<String>, CoreError> {
    if !fs.is_dir(dir) {
        return Ok(Vec::new());
    }
    let entries = fs.read_dir(dir).map_err(|err| {
        CoreError::new(ErrorCode::IoError, format!("cannot list directory: {err}")).with_path(dir)
    })?;
    let mut names: Vec<String> = entries
        .iter()
        .filter(|entry| fs.is_dir(entry) == dirs)
        .filter_map(|entry| entry.file_name()?.to_str().map(str::to_owned))
        .collect();
    names.sort();
    Ok(names)
}

/// `root` joined with a `/`-separated relative path.
fn join(root: &Path, relative: &str) -> PathBuf {
    relative
        .split('/')
        .filter(|part| !part.is_empty())
        .fold(root.to_path_buf(), |path, part| path.join(part))
}

/// Only the `schema` key; every other key is skipped, not kept.
#[derive(serde::Deserialize)]
struct SchemaField {
    #[serde(default)]
    schema: Option<i64>,
}

/// The top-level integer `schema` of a file's text.
pub fn read_version(format: Format, text: &str) -> Option<i64> {
    let text = text.strip_prefix(BOM).unwrap_or(text);
    let field: SchemaField = match format {
        Format::Toml => toml::from_str(text).ok()?,
        Format::Json => serde_json::from_str(text).ok()?,
    };
    field.schema
}

/// Whether the file at `path` says a `schema` above `supported`: a newer
/// Surjection wrote it (possibly while this process runs), so it must not be
/// overwritten. Absent or unreadable files are not.
pub fn written_by_newer(fs: &dyn Fs, path: &Path, format: Format, supported: i64) -> bool {
    fs.read_to_string(path)
        .ok()
        .and_then(|text| read_version(format, &text))
        .is_some_and(|found| found > supported)
}

/// A file a newer Surjection wrote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewerData {
    pub kind: &'static str,
    /// Relative to the data folder (`store/servers/github.toml`).
    pub file: String,
    pub found: i64,
    pub supported: i64,
}

impl NewerData {
    pub fn message(&self) -> String {
        newer_message("This data folder was", self.found, self.supported)
    }

    /// `unsupported_schema` with [`Self::message`] and the file's path.
    pub fn to_error(&self, home: &SurjectionHome) -> CoreError {
        CoreError::new(ErrorCode::UnsupportedSchema, self.message())
            .with_path(join(&home.path, &self.file))
    }
}

fn newer_message(subject: &str, found: i64, supported: i64) -> String {
    let product = brand::PRODUCT_NAME;
    format!(
        "{subject} written by a newer {product} (schema {found}; this version reads up to \
         {supported}). Update {product}."
    )
}

/// The first file of `found` newer than its kind's current version.
fn first_newer(found: &[Found], registry: &Registry) -> Option<NewerData> {
    found.iter().find_map(|file| {
        let supported = registry.kind(file.kind)?.current();
        (file.version > supported).then(|| NewerData {
            kind: file.kind,
            file: file.file(),
            found: file.version,
            supported,
        })
    })
}

/// One file a migration rewrote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Migrated {
    pub kind: &'static str,
    /// Relative to the data folder.
    pub file: String,
    pub from: i64,
    pub to: i64,
}

/// What a migration did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Migration {
    pub files: Vec<Migrated>,
    /// The store commit holding the migrated store files.
    pub commit: Option<CommitId>,
    /// Copies of the state files as they were.
    pub backup: Option<PathBuf>,
}

/// What [`prepare`] found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Prepared {
    /// The folder can be used; `Some` when files were migrated first.
    Ready(Option<Migration>),
    /// A newer Surjection wrote this file; nothing was written.
    Newer(NewerData),
}

impl Prepared {
    /// [`Prepared::Newer`] as its `unsupported_schema` error.
    pub fn into_result(self, home: &SurjectionHome) -> Result<Option<Migration>, CoreError> {
        match self {
            Prepared::Ready(migration) => Ok(migration),
            Prepared::Newer(newer) => Err(newer.to_error(home)),
        }
    }
}

/// [`prepare_with`] over [`Registry::builtin`].
pub fn prepare(
    env: &Env,
    fs: &dyn Fs,
    home: &SurjectionHome,
    client: &str,
) -> Result<Prepared, CoreError> {
    prepare_with(env, fs, home, client, &Registry::builtin())
}

/// Surveys the data folder once: a file a newer Surjection wrote is returned
/// as [`Prepared::Newer`] and nothing is written; files an older one wrote
/// are migrated. `client` names the program for the store commit's
/// `Surjection-Client` trailer. An error is a failed survey or migration.
pub fn prepare_with(
    env: &Env,
    fs: &dyn Fs,
    home: &SurjectionHome,
    client: &str,
    registry: &Registry,
) -> Result<Prepared, CoreError> {
    let found = survey(fs, home, registry)?;
    if let Some(newer) = first_newer(&found, registry) {
        return Ok(Prepared::Newer(newer));
    }
    rename_legacy_names(fs, home);
    if pending(&found, registry).next().is_none() {
        return Ok(Prepared::Ready(None));
    }
    let _lock = StoreLock::acquire(fs, &home.state_dir(), LOCK_TIMEOUT)?;
    // Another process may have migrated, or a newer one written, meanwhile.
    let found = survey(fs, home, registry)?;
    if let Some(newer) = first_newer(&found, registry) {
        return Ok(Prepared::Newer(newer));
    }
    let pending: Vec<&Found> = pending(&found, registry).collect();
    if pending.is_empty() {
        return Ok(Prepared::Ready(None));
    }
    migrate(env, fs, home, client, registry, &pending).map(|m| Prepared::Ready(Some(m)))
}

/// Files below their kind's current version. A version below the first one
/// (0 or negative) is no version Surjection wrote: left to the file's reader.
fn pending<'f>(found: &'f [Found], registry: &'f Registry) -> impl Iterator<Item = &'f Found> + 'f {
    found.iter().filter(|file| {
        registry
            .kind(file.kind)
            .is_some_and(|kind| (FIRST..kind.current()).contains(&file.version))
    })
}

/// Migrates `pending` (the caller holds the lock): state files first, so
/// `state/machine.toml` is current before the store commit reads it, then
/// the store.
fn migrate(
    env: &Env,
    fs: &dyn Fs,
    home: &SurjectionHome,
    client: &str,
    registry: &Registry,
    pending: &[&Found],
) -> Result<Migration, CoreError> {
    let mut migration = Migration {
        files: Vec::new(),
        commit: None,
        backup: None,
    };
    let state = home.state_dir();
    let backup = home
        .backups_dir()
        .join(BACKUP_DIR)
        .join(timestamp(env.now()));
    for file in pending.iter().filter(|file| file.area == Area::State) {
        let kind = registry.kind(file.kind).expect("surveyed kinds exist");
        let path = join(&state, &file.relative);
        let bytes = fs
            .read(&path)
            .map_err(|err| io_error("cannot read file", &path, &err))?;
        let text = upgrade(kind, &file.relative, &bytes, file.version)
            .map_err(|err| err.with_path(&path))?;
        let copy = join(&backup.join(Area::State.dir()), &file.relative);
        let parent = copy.parent().unwrap_or(&backup);
        fs.create_private_dir_all(&backup)
            .and_then(|()| fs.create_dir_all(parent))
            .map_err(|err| io_error("cannot create directory", parent, &err))?;
        fs.write(&copy, &bytes)
            .map_err(|err| io_error("cannot write file", &copy, &err))?;
        write_atomic(fs, &path, text.as_bytes())?;
        migration.backup = Some(backup.clone());
        migration
            .files
            .push(migrated(&file.file(), file.version, kind));
    }
    let store_pending: Vec<&Found> = pending
        .iter()
        .copied()
        .filter(|file| file.area == Area::Store)
        .collect();
    if !store_pending.is_empty() {
        migrate_store(
            env,
            fs,
            home,
            client,
            registry,
            &store_pending,
            &mut migration,
        )?;
    }
    Ok(migration)
}

/// The store part of a migration. HEAD's blobs are upgraded and committed
/// first, without touching the working tree; then the working tree is
/// written. A working-tree file with the same bytes as HEAD gets the
/// committed bytes; one that differs (hand edits, or a file a crash left
/// at the old version after the commit) is upgraded on its own and stays
/// as it is relative to HEAD (uncommitted). Every upgrade is computed
/// before anything is written, so a working-tree file that cannot be
/// upgraded fails the migration with nothing committed.
fn migrate_store(
    env: &Env,
    fs: &dyn Fs,
    home: &SurjectionHome,
    client: &str,
    registry: &Registry,
    pending: &[&Found],
    migration: &mut Migration,
) -> Result<(), CoreError> {
    let kind = registry.kind("store").expect("the store kind exists");
    let to = kind.current();
    let store = Store::open_raw(env, fs, home, client)?.ok_or_else(|| {
        CoreError::new(ErrorCode::NotFound, "the store is not a repository")
            .with_path(home.store_dir())
    })?;
    let revision = store.revision(&store.head()?)?;
    let mut committed = Files::new();
    let mut old_head = Files::new();
    let mut from = to;
    for relative in revision.files()? {
        if !is_store_schema_file(&relative) {
            continue;
        }
        let Some(bytes) = revision.read_bytes(&relative)? else {
            continue;
        };
        let Some(version) = std::str::from_utf8(&bytes)
            .ok()
            .and_then(|text| read_version(Format::Toml, text))
        else {
            continue;
        };
        if !(FIRST..to).contains(&version) {
            continue;
        }
        let text = upgrade(kind, &relative, &bytes, version)
            .map_err(|err| err.with_path(store.path(&relative).unwrap_or_default()))?;
        from = from.min(version);
        committed.insert(relative.clone(), text.into_bytes());
        old_head.insert(relative, bytes);
    }

    let mut worktree = Vec::new();
    for file in pending {
        let path = store.path(&file.relative)?;
        let bytes = fs
            .read(&path)
            .map_err(|err| io_error("cannot read file", &path, &err))?;
        let new = match (old_head.get(&file.relative), committed.get(&file.relative)) {
            (Some(old), Some(new)) if *old == bytes => new.clone(),
            _ => upgrade(kind, &file.relative, &bytes, file.version)
                .map_err(|err| {
                    CoreError::new(
                        err.code(),
                        format!(
                            "store/{} has changes that are not committed and cannot be \
                             upgraded to schema {to}: {}. Fix or remove them by hand, then run \
                             {} again.",
                            file.relative,
                            err.message(),
                            brand::PRODUCT_NAME
                        ),
                    )
                    .with_path(&path)
                })?
                .into_bytes(),
        };
        worktree.push((path, new));
    }
    for relative in committed.keys() {
        if !pending.iter().any(|file| &file.relative == relative) {
            let old = &old_head[relative];
            let version = std::str::from_utf8(old)
                .ok()
                .and_then(|text| read_version(Format::Toml, text))
                .unwrap_or(FIRST);
            migration
                .files
                .push(migrated(&format!("store/{relative}"), version, kind));
        }
    }
    for file in pending {
        migration
            .files
            .push(migrated(&file.file(), file.version, kind));
    }

    if !committed.is_empty() {
        let count = committed.len();
        let noun = if count == 1 { "file" } else { "files" };
        let operation = Operation::new(
            "store.migrate",
            format!("migrate: store schema {from} -> {to} ({count} {noun})"),
        );
        migration.commit = store.commit_migration(&operation, committed, to == SCHEMA_VERSION)?;
    }
    if let Some(hook) = registry.after_commit {
        hook()?;
    }
    for (path, bytes) in worktree {
        write_atomic(fs, &path, &bytes)?;
    }
    Ok(())
}

fn migrated(file: &str, from: i64, kind: &Kind) -> Migrated {
    Migrated {
        kind: kind.name,
        file: file.to_owned(),
        from,
        to: kind.current(),
    }
}

/// `bytes` (a file of `kind` at version `from`) upgraded to the kind's
/// current version. Keeps a UTF-8 BOM, CRLF line endings and, for TOML,
/// comments and formatting.
fn upgrade(kind: &Kind, relative: &str, bytes: &[u8], from: i64) -> Result<String, CoreError> {
    let text = std::str::from_utf8(bytes)
        .map_err(|_| CoreError::new(ErrorCode::ParseError, "the file is not UTF-8"))?;
    let bom = text.starts_with(BOM);
    let text = text.strip_prefix(BOM).unwrap_or(text);
    let crlf = text.find('\n').is_some_and(|i| text[..i].ends_with('\r'));
    let text = if crlf {
        text.replace("\r\n", "\n")
    } else {
        text.to_owned()
    };
    let final_newline = text.ends_with('\n');
    let mut doc = match kind.format {
        Format::Toml => Doc::Toml(
            text.parse::<DocumentMut>()
                .map_err(|err| CoreError::new(ErrorCode::ParseError, err.message().to_owned()))?,
        ),
        Format::Json => Doc::Json(
            serde_json::from_str(&text)
                .map_err(|err| CoreError::new(ErrorCode::ParseError, err.to_string()))?,
        ),
    };
    for version in from..kind.current() {
        let index = usize::try_from(version - FIRST).map_err(|_| {
            CoreError::new(
                ErrorCode::UnsupportedSchema,
                format!("schema {version} is older than any version this build migrates"),
            )
        })?;
        let step = kind.steps.get(index).ok_or_else(|| {
            CoreError::new(
                ErrorCode::UnsupportedSchema,
                format!("no migration from schema {version} for {}", kind.name),
            )
        })?;
        (step.rewrite)(relative, &mut doc)?;
        set_version(&mut doc, version + 1);
    }
    let mut out = match &doc {
        Doc::Toml(doc) => doc.to_string(),
        Doc::Json(value) => {
            let mut out = serde_json::to_string_pretty(value).map_err(|err| {
                CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
            })?;
            if final_newline {
                out.push('\n');
            }
            out
        }
    };
    if crlf {
        out = out.replace('\n', "\r\n");
    }
    if bom {
        out.insert(0, BOM);
    }
    Ok(out)
}

/// Sets the top-level `schema`, keeping the TOML key's comments.
fn set_version(doc: &mut Doc, version: i64) {
    match doc {
        Doc::Toml(doc) => match doc.get_mut("schema").and_then(Item::as_value_mut) {
            Some(value) => {
                let decor = value.decor().clone();
                *value = toml_edit::Value::from(version);
                *value.decor_mut() = decor;
            }
            None => {
                doc.insert("schema", toml_edit::value(version));
            }
        },
        Doc::Json(value) => {
            if let Some(object) = value.as_object_mut() {
                object.insert("schema".to_owned(), serde_json::Value::from(version));
            }
        }
    }
}

/// [`check_store_files_with`] over [`Registry::builtin`].
pub fn check_store_files<'f>(
    files: impl IntoIterator<Item = (&'f str, &'f [u8])>,
    origin: &str,
) -> Result<(), CoreError> {
    check_store_files_with(files, origin, &Registry::builtin())
}

/// Refuses an incoming store (an incoming commit, an export or a restore
/// source; store-relative paths and bytes) whose files are at another
/// store version than this build's, with `unsupported_schema`. Newer:
/// update Surjection here. Older (after a version bump, from a machine that
/// still runs an older Surjection): its files cannot be merged field by field
/// into migrated ones, so the other machine has to be updated and push
/// again. Versions below the first one are left to the readers. `origin`
/// starts the message (`The remote "backup"`).
pub fn check_store_files_with<'f>(
    files: impl IntoIterator<Item = (&'f str, &'f [u8])>,
    origin: &str,
    registry: &Registry,
) -> Result<(), CoreError> {
    let current = registry.kind("store").map_or(SCHEMA_VERSION, Kind::current);
    let product = brand::PRODUCT_NAME;
    for (relative, bytes) in files {
        if !is_store_schema_file(relative) {
            continue;
        }
        let Some(found) = std::str::from_utf8(bytes)
            .ok()
            .and_then(|text| read_version(Format::Toml, text))
        else {
            continue;
        };
        let message = if found > current {
            newer_message(&format!("{origin} holds data"), found, current)
        } else if (FIRST..current).contains(&found) {
            format!(
                "{origin} holds data written by an older {product} (schema {found}; this version \
                 reads {current}). Update {product} on that machine and push again."
            )
        } else {
            continue;
        };
        return Err(CoreError::new(ErrorCode::UnsupportedSchema, message).with_path(relative));
    }
    Ok(())
}

impl Store<'_> {
    /// [`Store::check_incoming_with`] over [`Registry::builtin`].
    pub fn check_incoming(&self, id: &CommitId, origin: &str) -> Result<(), CoreError> {
        self.check_incoming_with(id, origin, &Registry::builtin())
    }

    /// [`check_store_files_with`] over commit `id`'s tree (its objects are
    /// in the store already): run before a pull or restore tags or merges
    /// it, so a refused source leaves HEAD, the working tree and the tags
    /// as they were.
    pub fn check_incoming_with(
        &self,
        id: &CommitId,
        origin: &str,
        registry: &Registry,
    ) -> Result<(), CoreError> {
        let revision = self.revision(id)?;
        let mut files = Files::new();
        for relative in revision.files()? {
            if is_store_schema_file(&relative)
                && let Some(bytes) = revision.read_bytes(&relative)?
            {
                files.insert(relative, bytes);
            }
        }
        check_store_files_with(
            files
                .iter()
                .map(|(path, bytes)| (path.as_str(), bytes.as_slice())),
            origin,
            registry,
        )
    }
}

fn io_error(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
}

/// The machine-local file names Loadout 1.0.x gave its own files, by
/// folder below the data folder: `(folder, old prefix, new prefix)`. A
/// file is renamed when its name is the old prefix or starts with it
/// followed by `.` (`loadout.log.1`, `loadout.log.lock`).
/// `state/loadout.lock` keeps its name: the store lock holds it too
/// ([`crate::store::StoreLock`]).
const LEGACY_NAMES: [(&str, &str, &str); 1] =
    [("logs", "loadout.log", crate::diagnostics::log::LOG_FILE)];

/// A machine-local file that still carries the former product name and
/// what it becomes (relative to the data folder, `/`-separated).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegacyName {
    pub from: String,
    pub to: String,
}

/// The machine-local files of `home` that Loadout 1.0.x named after itself
/// and that [`rename_legacy_names`] would rename. Reads only. The synced
/// store keeps its names (`store/loadout.toml`, `store/.loadout-allow`):
/// renaming them would need a store schema bump, which would refuse pulls
/// from 1.0.x machines and restores of 1.0.x backups.
pub fn legacy_names(fs: &dyn Fs, home: &SurjectionHome) -> Vec<LegacyName> {
    let mut found = Vec::new();
    for (folder, old, new) in LEGACY_NAMES {
        let dir = home.path.join(folder);
        let Ok(entries) = fs.read_dir(&dir) else {
            continue;
        };
        for path in entries {
            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
                continue;
            };
            let Some(rest) = name.strip_prefix(old) else {
                continue;
            };
            if !(rest.is_empty() || rest.starts_with('.')) || !fs.is_regular_file(&path) {
                continue;
            }
            found.push(LegacyName {
                from: format!("{folder}/{name}"),
                to: format!("{folder}/{new}{rest}"),
            });
        }
    }
    found.sort_by(|a, b| a.from.cmp(&b.from));
    found
}

/// Renames the files [`legacy_names`] lists (M56 data-folder names, run
/// before anything opens them). A file whose new name exists already is
/// left alone. Idempotent. Returns what was renamed.
pub fn rename_legacy_names(fs: &dyn Fs, home: &SurjectionHome) -> Vec<LegacyName> {
    let mut done = Vec::new();
    for name in legacy_names(fs, home) {
        let from = join(&home.path, &name.from);
        let to = join(&home.path, &name.to);
        if fs.exists(&to) {
            continue;
        }
        if fs.replace(&from, &to).is_ok() {
            done.push(name);
        }
    }
    done
}