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
//! Pull merges (SPEC 9.9): an incoming head that is an ancestor of HEAD
//! changes nothing, a descendant fast-forwards, anything else merges per
//! entity against the merge base.
//!
//! - TOML files merge per field (tables flattened to key paths, arrays as
//!   one value): changed on one side takes that side, changed identically
//!   takes it, changed differently is a conflict for that field.
//! - Other text (skill content, `.gitattributes`) merges per line through
//!   git's file merge; binary content changed on both sides conflicts.
//! - A file deleted on one side and changed on the other conflicts.
//! - `sources.toml` merges per record (#24): a lapse gives way to the
//!   user's decision on the other side (untrust wins), two lapses keep the
//!   earlier, other records both sides changed conflict whole.
//! - `machines/<id>.toml` and `machines/<id>.applied.toml` are single
//!   writer: this machine's own files keep ours; another machine's come
//!   from the side whose history touched them last. Never a conflict.
//!
//! Nothing is resolved in favor of local silently. With a conflict HEAD
//! stays as it is and the caller records the conflicts.

use std::collections::BTreeMap;
use std::path::Path;
use std::time::SystemTime;

use git2::{MergeFileInput, Oid, Sort};
use toml_edit::{DocumentMut, Item, Table};

use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::sources::SOURCES_FILE;
use crate::store::transaction::Changes;
use crate::store::{
    CommitId, LOCK_TIMEOUT, Machine, Operation, Store, StoreLock, git_error, io_error,
};

/// File contents by store-relative path.
pub type Files = BTreeMap<String, Vec<u8>>;

/// One side of a merge.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Ours,
    Theirs,
}

/// One field (or a whole file, `field: None`) both sides changed
/// differently. Values are TOML text or file text; `None` is absent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Conflict {
    pub file: String,
    pub field: Option<String>,
    pub base: Option<String>,
    pub ours: Option<String>,
    pub theirs: Option<String>,
}

/// The merged files, or the conflicts that prevent them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Merged {
    pub files: Files,
    pub conflicts: Vec<Conflict>,
}

/// What decides the single-writer files.
pub struct MergePolicy<'a> {
    /// This machine: its `machines/<id>*` files always keep ours.
    pub machine_id: &'a str,
    /// For another machine's file both sides changed: the side whose
    /// history touched it last.
    pub newer: &'a dyn Fn(&str) -> Side,
}

/// Merges `ours` and `theirs` against `base` (SPEC 9.9 step 3).
pub fn merge_trees(base: &Files, ours: &Files, theirs: &Files, policy: &MergePolicy<'_>) -> Merged {
    let mut paths: Vec<&String> = base
        .keys()
        .chain(ours.keys())
        .chain(theirs.keys())
        .collect();
    paths.sort();
    paths.dedup();
    let mut files = Files::new();
    let mut conflicts = Vec::new();
    for path in paths {
        let (b, o, t) = (base.get(path), ours.get(path), theirs.get(path));
        let pick = |side: Option<&Vec<u8>>, files: &mut Files| {
            if let Some(bytes) = side {
                files.insert(path.clone(), bytes.clone());
            }
        };
        if o == t || t == b {
            pick(o, &mut files);
            continue;
        }
        if o == b {
            pick(t, &mut files);
            continue;
        }
        if let Some(owner) = machine_file_owner(path) {
            let side = if owner == policy.machine_id {
                Side::Ours
            } else {
                (policy.newer)(path)
            };
            pick(if side == Side::Ours { o } else { t }, &mut files);
            continue;
        }
        let (Some(o), Some(t)) = (o, t) else {
            conflicts.push(Conflict {
                file: path.clone(),
                field: None,
                base: b.map(|bytes| text(bytes)),
                ours: o.map(|bytes| text(bytes)),
                theirs: t.map(|bytes| text(bytes)),
            });
            continue;
        };
        let merged = if path == SOURCES_FILE {
            merge_sources(path, b, o, t)
        } else if path.ends_with(".toml") {
            merge_toml(path, b, o, t)
        } else {
            merge_text(path, b, o, t)
        };
        match merged {
            Ok(bytes) => {
                files.insert(path.clone(), bytes);
            }
            Err(found) => conflicts.extend(found),
        }
    }
    Merged { files, conflicts }
}

/// `sources.toml` (#24) merges per record, so a merge never leaves a
/// half record: a record changed on one side takes that side whole; a
/// lapse (only `lapsed` changed, or a new record that carries one: the
/// automatic kind) gives way to the user's decision on the other side
/// (untrust, block, trust again), and two lapses of one record keep the
/// earlier. Any other record both sides changed is a conflict of that
/// record. The rest of the file merges per field.
fn merge_sources(
    path: &str,
    b: Option<&Vec<u8>>,
    o: &[u8],
    t: &[u8],
) -> Result<Vec<u8>, Vec<Conflict>> {
    let parse = |bytes: &[u8]| std::str::from_utf8(bytes).ok()?.parse::<toml::Table>().ok();
    let base = match b {
        Some(bytes) => parse(bytes),
        None => Some(toml::Table::new()),
    };
    let (Some(mut base), Some(ours), Some(mut theirs)) = (base, parse(o), parse(t)) else {
        return Err(whole_file(path, b, o, t));
    };
    let records = |table: &toml::Table| match table.get("sources") {
        None => Some(toml::Table::new()),
        Some(toml::Value::Table(records)) => Some(records.clone()),
        Some(_) => None,
    };
    let (Some(base_records), Some(our_records), Some(their_records)) =
        (records(&base), records(&ours), records(&theirs))
    else {
        return merge_toml(path, b, o, t);
    };
    let mut keys: Vec<&String> = base_records
        .keys()
        .chain(our_records.keys())
        .chain(their_records.keys())
        .collect();
    keys.sort();
    keys.dedup();
    // The field merge below then takes the chosen side of each record
    // whole: the base gets ours (so theirs is the only change), and theirs
    // gets ours too where ours wins.
    let mut new_base = base_records.clone();
    let mut new_theirs = their_records.clone();
    let mut conflicts = Vec::new();
    for key in keys {
        let (bv, ov, tv) = (
            base_records.get(key),
            our_records.get(key),
            their_records.get(key),
        );
        if ov == tv || tv == bv || ov == bv {
            continue;
        }
        let Some(side) = settle_record(bv, ov, tv) else {
            conflicts.push(Conflict {
                file: path.to_owned(),
                field: Some(dotted(&["sources".to_owned(), key.clone()])),
                base: bv.map(ToString::to_string),
                ours: ov.map(ToString::to_string),
                theirs: tv.map(ToString::to_string),
            });
            continue;
        };
        let put = |table: &mut toml::Table| match ov {
            Some(value) => table.insert(key.clone(), value.clone()),
            None => table.remove(key),
        };
        put(&mut new_base);
        if side == Side::Ours {
            put(&mut new_theirs);
        }
    }
    if !conflicts.is_empty() {
        return Err(conflicts);
    }
    let text = |table: &mut toml::Table, records: toml::Table| {
        if records.is_empty() {
            table.remove("sources");
        } else {
            table.insert("sources".to_owned(), toml::Value::Table(records));
        }
        toml::to_string(table).ok().map(String::into_bytes)
    };
    let (Some(base), Some(theirs)) = (text(&mut base, new_base), text(&mut theirs, new_theirs))
    else {
        return Err(whole_file(path, b, o, t));
    };
    merge_toml(path, Some(&base), o, &theirs)
}

/// Which side of a `sources.toml` record both sides changed wins, if a
/// rule decides (see [`merge_sources`]).
fn settle_record(
    b: Option<&toml::Value>,
    o: Option<&toml::Value>,
    t: Option<&toml::Value>,
) -> Option<Side> {
    fn lapse(side: Option<&toml::Value>) -> Option<&toml::Value> {
        side.and_then(|record| record.get("lapsed"))
    }
    let decision = |side: Option<&toml::Value>| {
        side.map(|record| {
            let mut record = record.clone();
            if let toml::Value::Table(table) = &mut record {
                table.remove("lapsed");
            }
            record
        })
    };
    // Only the automatic lapse changed: the decision is the base's, or a
    // new record that carries a lapse (a repository trusted through its
    // owner or host gets its own lapsed record).
    let lapse_only = |side: Option<&toml::Value>| {
        lapse(side).is_some() && (b.is_none() || decision(side) == decision(b))
    };
    match (lapse_only(o), lapse_only(t)) {
        (true, true) if decision(o) == decision(t) => {
            let at = |side| {
                lapse(side)
                    .and_then(|lapsed| lapsed.get("at"))
                    .map(ToString::to_string)
            };
            Some(if at(t) < at(o) {
                Side::Theirs
            } else {
                Side::Ours
            })
        }
        (true, false) => Some(Side::Theirs),
        (false, true) => Some(Side::Ours),
        _ => None,
    }
}

/// The machine id of a `machines/<id>.toml` or `machines/<id>.applied.toml`.
fn machine_file_owner(path: &str) -> Option<&str> {
    let name = path.strip_prefix("machines/")?;
    name.strip_suffix(".applied.toml")
        .or_else(|| name.strip_suffix(".toml"))
        .filter(|id| !id.contains('/'))
}

fn text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).into_owned()
}

fn whole_file(path: &str, b: Option<&Vec<u8>>, o: &[u8], t: &[u8]) -> Vec<Conflict> {
    vec![Conflict {
        file: path.to_owned(),
        field: None,
        base: b.map(|bytes| text(bytes)),
        ours: Some(text(o)),
        theirs: Some(text(t)),
    }]
}

/// Per-line 3-way merge of text; binary or overlapping changes conflict.
fn merge_text(
    path: &str,
    b: Option<&Vec<u8>>,
    o: &[u8],
    t: &[u8],
) -> Result<Vec<u8>, Vec<Conflict>> {
    let binary = |bytes: &[u8]| std::str::from_utf8(bytes).is_err() || bytes.contains(&0);
    if binary(o) || binary(t) || b.is_some_and(|b| binary(b)) {
        return Err(whole_file(path, b, o, t));
    }
    let empty = Vec::new();
    let mut ancestor = MergeFileInput::new();
    ancestor.content(b.unwrap_or(&empty)).path(path);
    let mut ours = MergeFileInput::new();
    ours.content(o).path(path);
    let mut theirs = MergeFileInput::new();
    theirs.content(t).path(path);
    // `git2::merge_file` does not initialize libgit2 itself (it fails with
    // "no error" before any other git2 call in the process); hashing the
    // base initializes it.
    let _ = git2::Oid::hash_object(git2::ObjectType::Blob, b.unwrap_or(&empty));
    match git2::merge_file(&ancestor, &ours, &theirs, None) {
        Ok(result) if result.is_automergeable() => Ok(result.content().to_vec()),
        _ => Err(whole_file(path, b, o, t)),
    }
}

type Fields = BTreeMap<Vec<String>, toml::Value>;

/// Leaves of a TOML table by key path; arrays and inline values are leaves.
fn flatten(table: &toml::Table) -> Fields {
    fn walk(prefix: &mut Vec<String>, table: &toml::Table, out: &mut Fields) {
        for (key, value) in table {
            prefix.push(key.clone());
            match value {
                toml::Value::Table(inner) => walk(prefix, inner, out),
                other => {
                    out.insert(prefix.clone(), other.clone());
                }
            }
            prefix.pop();
        }
    }
    let mut out = Fields::new();
    walk(&mut Vec::new(), table, &mut out);
    out
}

fn dotted(path: &[String]) -> String {
    path.iter()
        .map(|key| {
            let bare = !key.is_empty()
                && key
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
            if bare {
                key.clone()
            } else {
                toml::Value::String(key.clone()).to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(".")
}

/// Per-field 3-way merge of a TOML file, written into ours so its layout
/// and comments stay.
fn merge_toml(
    path: &str,
    b: Option<&Vec<u8>>,
    o: &[u8],
    t: &[u8],
) -> Result<Vec<u8>, Vec<Conflict>> {
    let parse = |bytes: &[u8]| -> Option<Fields> {
        std::str::from_utf8(bytes)
            .ok()?
            .parse::<toml::Table>()
            .ok()
            .map(|table| flatten(&table))
    };
    let base = match b {
        Some(bytes) => parse(bytes),
        None => Some(Fields::new()),
    };
    let (Some(base), Some(ours), Some(theirs)) = (base, parse(o), parse(t)) else {
        return Err(whole_file(path, b, o, t));
    };
    let mut keys: Vec<&Vec<String>> = base
        .keys()
        .chain(ours.keys())
        .chain(theirs.keys())
        .collect();
    keys.sort();
    keys.dedup();
    let mut conflicts = Vec::new();
    let mut edits: Vec<(&Vec<String>, Option<&toml::Value>)> = Vec::new();
    for key in keys {
        let (bv, ov, tv) = (base.get(key), ours.get(key), theirs.get(key));
        if ov == tv || tv == bv {
            continue;
        }
        if ov == bv {
            edits.push((key, tv));
            continue;
        }
        conflicts.push(Conflict {
            file: path.to_owned(),
            field: Some(dotted(key)),
            base: bv.map(ToString::to_string),
            ours: ov.map(ToString::to_string),
            theirs: tv.map(ToString::to_string),
        });
    }
    if !conflicts.is_empty() {
        return Err(conflicts);
    }
    let text = std::str::from_utf8(o).expect("parsed above");
    let mut doc: DocumentMut = text.parse().map_err(|_| whole_file(path, b, o, t))?;
    for (key, value) in edits {
        let applied = match value {
            Some(value) => set_path(&mut doc, key, value),
            None => remove_path(&mut doc, key),
        };
        if !applied {
            return Err(whole_file(path, b, o, t));
        }
    }
    let merged = doc.to_string().into_bytes();
    // The result must read back as exactly the merged fields.
    let mut expected = ours.clone();
    for key in base.keys().chain(theirs.keys()) {
        let (bv, ov, tv) = (base.get(key), ours.get(key), theirs.get(key));
        if ov == bv && tv != bv {
            match tv {
                Some(value) => expected.insert(key.clone(), value.clone()),
                None => expected.remove(key),
            };
        }
    }
    match parse(&merged) {
        Some(fields) if fields == expected => Ok(merged),
        _ => Err(whole_file(path, b, o, t)),
    }
}

fn set_path(doc: &mut DocumentMut, path: &[String], value: &toml::Value) -> bool {
    let Some((last, parents)) = path.split_last() else {
        return false;
    };
    let Ok(value) = value.to_string().parse::<toml_edit::Value>() else {
        return false;
    };
    let mut table: &mut dyn toml_edit::TableLike = doc.as_table_mut();
    for key in parents {
        let item = table.entry(key).or_insert_with(|| {
            let mut created = Table::new();
            created.set_implicit(true);
            Item::Table(created)
        });
        match item.as_table_like_mut() {
            Some(inner) => table = inner,
            None => return false,
        }
    }
    match table.get_mut(last) {
        Some(item) if item.is_value() => {
            if let Some(old) = item.as_value() {
                let decor = old.decor().clone();
                let mut value = value;
                *value.decor_mut() = decor;
                *item = Item::Value(value);
            }
        }
        Some(_) => return false,
        None => {
            table.insert(last, Item::Value(value));
        }
    }
    true
}

fn remove_path(doc: &mut DocumentMut, path: &[String]) -> bool {
    fn remove(table: &mut dyn toml_edit::TableLike, path: &[String]) -> bool {
        match path {
            [] => false,
            [last] => table.remove(last).is_some(),
            [first, rest @ ..] => {
                let Some(inner) = table.get_mut(first).and_then(Item::as_table_like_mut) else {
                    return false;
                };
                let removed = remove(inner, rest);
                if removed && inner.is_empty() {
                    table.remove(first);
                }
                removed
            }
        }
    }
    remove(doc.as_table_mut(), path)
}

/// What merging one incoming head did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergeOutcome {
    /// The incoming head is already in HEAD's history.
    UpToDate,
    /// HEAD moved forward to the incoming head.
    FastForward(CommitId),
    /// A merge commit with both parents.
    Merged(CommitId),
    /// Fields both sides changed differently; HEAD is unchanged.
    Conflicts {
        base: Option<CommitId>,
        conflicts: Vec<Conflict>,
    },
}

impl Store<'_> {
    /// Merges `incoming` (whose objects are in the store already) into
    /// HEAD; `label` names it in the merge commit (`merge: <label>`).
    pub fn merge_incoming(
        &self,
        incoming: &CommitId,
        label: &str,
    ) -> Result<MergeOutcome, CoreError> {
        let theirs_oid = Oid::from_str(incoming.as_str()).map_err(git_error)?;
        self.repo.find_commit(theirs_oid).map_err(|_| {
            CoreError::new(
                ErrorCode::RemoteIncomplete,
                format!("commit {} is not in the store", incoming.short()),
            )
        })?;
        let _lock = StoreLock::acquire(self.fs, &self.state_dir, LOCK_TIMEOUT)?;
        let machine = Machine::load_or_create(&self.env, self.fs, &self.state_dir)?;
        let head = self.head()?;
        let ours_oid = Oid::from_str(head.as_str()).map_err(git_error)?;
        if ours_oid == theirs_oid
            || self
                .repo
                .graph_descendant_of(ours_oid, theirs_oid)
                .map_err(git_error)?
        {
            return Ok(MergeOutcome::UpToDate);
        }
        if self
            .repo
            .graph_descendant_of(theirs_oid, ours_oid)
            .map_err(git_error)?
        {
            self.fast_forward(&head, incoming)?;
            return Ok(MergeOutcome::FastForward(incoming.clone()));
        }
        let base = self.repo.merge_base(ours_oid, theirs_oid).ok();
        let base_files = match base {
            Some(base) => self.files_at(&CommitId::from_oid(base))?,
            None => Files::new(),
        };
        let ours = self.files_at(&head)?;
        let theirs = self.files_at(incoming)?;
        let newer = |path: &str| {
            let ours_time = self.last_touch(ours_oid, path);
            let theirs_time = self.last_touch(theirs_oid, path);
            if ours_time > theirs_time {
                Side::Ours
            } else {
                Side::Theirs
            }
        };
        let merged = merge_trees(
            &base_files,
            &ours,
            &theirs,
            &MergePolicy {
                machine_id: &machine.id,
                newer: &newer,
            },
        );
        if !merged.conflicts.is_empty() {
            return Ok(MergeOutcome::Conflicts {
                base: base.map(CommitId::from_oid),
                conflicts: merged.conflicts,
            });
        }
        let mut changes = Changes::new();
        for path in ours.keys().chain(merged.files.keys()) {
            if ours.get(path) != merged.files.get(path) {
                changes.insert(path.clone(), merged.files.get(path).cloned());
            }
        }
        let operation = Operation::new("store.merge", format!("merge: {label}"));
        let commit = self.commit_merge(&machine, &operation, changes, theirs_oid)?;
        Ok(MergeOutcome::Merged(commit))
    }

    /// Every file of a commit with its bytes.
    pub(crate) fn files_at(&self, id: &CommitId) -> Result<Files, CoreError> {
        let revision = self.revision(id)?;
        let mut files = Files::new();
        for file in revision.files()? {
            if let Some(bytes) = revision.read_bytes(&file)? {
                files.insert(file, bytes);
            }
        }
        Ok(files)
    }

    /// When the history from `start` last changed `path`.
    fn last_touch(&self, start: Oid, path: &str) -> Option<SystemTime> {
        let mut walk = self.repo.revwalk().ok()?;
        walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME).ok()?;
        walk.push(start).ok()?;
        let paths = [path.to_owned()];
        for oid in walk.flatten() {
            let commit = self.repo.find_commit(oid).ok()?;
            if crate::store::log::touches(&commit, &paths).ok()? {
                return Some(crate::store::log::commit_time(&commit));
            }
        }
        None
    }

    /// Moves `main` from `from` to its descendant `to`, updating the
    /// working tree and the index. The caller holds the lock.
    fn fast_forward(&self, from: &CommitId, to: &CommitId) -> Result<(), CoreError> {
        let old = self.files_at(from)?;
        let new = self.files_at(to)?;
        let mut changes = Changes::new();
        for path in old.keys().chain(new.keys()) {
            if old.get(path) != new.get(path) {
                changes.insert(path.clone(), new.get(path).cloned());
            }
        }
        self.write_worktree(&changes)?;
        let oid = Oid::from_str(to.as_str()).map_err(git_error)?;
        let tree = self
            .repo
            .find_commit(oid)
            .and_then(|commit| commit.tree())
            .map_err(git_error)?;
        let mut index = self.repo.index().map_err(git_error)?;
        index.read_tree(&tree).map_err(git_error)?;
        index.write().map_err(git_error)?;
        self.repo
            .reference(
                &format!("refs/heads/{}", crate::store::BRANCH),
                oid,
                true,
                &format!("fast-forward to {}", to.short()),
            )
            .map_err(git_error)?;
        Ok(())
    }
}

/// `state/merge/MERGE_STATE.json`: the conflicts of the latest merge of
/// each source, local only (never in the store), so a sync tool never
/// loops on them.
pub const MERGE_STATE: &str = "MERGE_STATE.json";
/// Version of [`MERGE_STATE`].
pub(crate) const MERGE_STATE_SCHEMA: u32 = 1;

/// One incoming head that did not merge.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PendingMerge {
    /// `<remote>/<machine-id>` (folder), `<remote>` (git) or
    /// `restore/<source>`.
    pub source: String,
    pub incoming: String,
    pub base: Option<String>,
    pub conflicts: Vec<RecordedConflict>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RecordedConflict {
    pub file: String,
    pub field: Option<String>,
    pub base: Option<String>,
    pub ours: Option<String>,
    pub theirs: Option<String>,
}

impl From<&Conflict> for RecordedConflict {
    fn from(conflict: &Conflict) -> Self {
        Self {
            file: conflict.file.clone(),
            field: conflict.field.clone(),
            base: conflict.base.clone(),
            ours: conflict.ours.clone(),
            theirs: conflict.theirs.clone(),
        }
    }
}

/// The merges recorded in `state/merge/`; none when the file is absent or
/// unreadable.
pub fn read_merge_state(fs: &dyn Fs, state_dir: &Path) -> Vec<PendingMerge> {
    #[derive(serde::Deserialize)]
    struct State {
        merges: Vec<PendingMerge>,
    }
    fs.read_to_string(&state_dir.join("merge").join(MERGE_STATE))
        .ok()
        .and_then(|text| serde_json::from_str::<State>(&text).ok())
        .map(|state| state.merges)
        .unwrap_or_default()
}

/// Records the outcome of merging from the sources in `attempted`: their
/// earlier entries are replaced by `pending` (the ones that conflicted
/// this time); entries of other sources stay. The file is removed when no
/// entry is left. A file a newer Surjection wrote is left alone (neither
/// rewritten nor removed).
pub fn write_merge_state(
    fs: &dyn Fs,
    state_dir: &Path,
    attempted: &[String],
    pending: &[PendingMerge],
) -> Result<(), CoreError> {
    let path = state_dir.join("merge").join(MERGE_STATE);
    if crate::versions::written_by_newer(
        fs,
        &path,
        crate::versions::Format::Json,
        i64::from(MERGE_STATE_SCHEMA),
    ) {
        return Ok(());
    }
    let mut merges = read_merge_state(fs, state_dir);
    merges.retain(|merge| !attempted.contains(&merge.source));
    merges.extend(pending.iter().cloned());
    if merges.is_empty() {
        if fs.exists(&path) {
            fs.remove_file(&path)
                .map_err(|err| io_error("cannot remove file", &path, &err))?;
        }
        return Ok(());
    }
    let text = serde_json::to_string_pretty(&serde_json::json!({
        "schema": MERGE_STATE_SCHEMA,
        "merges": merges,
    }))
    .expect("merge state serializes");
    crate::apply::write_atomic(fs, &path, text.as_bytes())
}