memstead-base 0.26.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! Merge-conflict resolution for folder mems.
//!
//! A hand-committed folder mem lives inside the user's own git
//! repository, so an ordinary merge can write conflict markers into
//! entity files. At that moment every other door is locked by design:
//! the loader refuses the file (naming this operation as the remedy),
//! and the guards correctly block git verbs and raw edits against mem
//! content. This module is the one sanctioned door — the agent judges
//! each conflict on its content and the engine is the pair of hands:
//! the chosen side is validated as an entity BEFORE it lands (a broken
//! ours side never launders into the mem), and the resolution commits
//! as an attributed, note-carrying mutation like any other write.
//!
//! Scope is deliberately narrow: per-entity, two sides (ours/theirs),
//! folder backend only, and one merged mode for what the engine itself
//! stamped. A merged-content resolution of a body conflict is out of
//! scope by design: that is a content judgement, made by choosing a side
//! as the base and then editing through the normal mutation surface,
//! which preserves validation and provenance; the operation's note is
//! the designated place to record "base for a manual merge; discarded
//! side: <which>". The one exception is `merged`: when every conflict
//! block covers only the engine-stamped `last_modified` key, git's merge
//! of the rest is kept and the later timestamp wins
//! ([`extract_timestamp_only_merge`]).
//! The git-branch backend's mem-repo is engine-managed and cannot
//! acquire merge conflicts through supported use, so it refuses typed
//! rather than pretending applicability.

use std::path::Path;

use crate::entity::id::file_path_to_id;
use crate::entity::{EntityId, loader, parser, source::EntitySource};
use crate::provenance::{Provenance, ProvenanceKind};
use crate::vcs::{Actor, ClientId};
use crate::workspace::{MountCapability, MountStorage};

use super::{Engine, EngineError};

/// Which side of a git merge conflict to keep.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictSide {
    Ours,
    Theirs,
    /// Keep git's merged file, valid only when every conflict block lies
    /// in the frontmatter and covers the engine-stamped `last_modified`
    /// key alone; the later value wins.
    Merged,
}

impl ConflictSide {
    /// Parse the wire token (`"ours"` / `"theirs"`). `None` for an
    /// unrecognized token so the calling surface raises a typed error
    /// naming the bad value.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "ours" => Some(Self::Ours),
            "theirs" => Some(Self::Theirs),
            "merged" => Some(Self::Merged),
            _ => None,
        }
    }

    /// The wire token for this side.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Ours => "ours",
            Self::Theirs => "theirs",
            Self::Merged => "merged",
        }
    }
}

/// One conflicted entity file found in a folder mem.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ConflictedEntity {
    /// The entity id the file's path derives to — the handle
    /// `resolve_merge_conflict` accepts.
    pub id: EntityId,
    pub mem: String,
    /// Mem-relative file path, for human orientation.
    pub file_path: String,
}

/// Outcome of a successful [`Engine::resolve_merge_conflict`].
#[derive(Debug, Clone, serde::Serialize)]
pub struct ResolveConflictOutcome {
    pub id: EntityId,
    /// The side that was kept (`"ours"` / `"theirs"`).
    pub side: &'static str,
    pub write_id: String,
    /// Carries `CONFIG_WRITE_INTERVENED` when the mutation version stamp this
    /// resolution triggered merged over another writer's config change.
    /// Empty on the ordinary path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<crate::ops::WarningHint>,
}

/// Extract one side of a git merge conflict from raw file content.
///
/// Handles the standard two-way marker layout and the diff3 variant
/// (`|||||||` base section, dropped from both sides). Operates on raw
/// lines exactly as git wrote them — git places markers at line starts
/// without regard for markdown structure. `Err` carries a description
/// of the malformation (e.g. a start marker with no closing marker).
pub fn extract_conflict_side(content: &str, side: ConflictSide) -> Result<String, String> {
    #[derive(PartialEq)]
    enum State {
        Normal,
        Ours,
        Base,
        Theirs,
    }
    let mut state = State::Normal;
    let mut out: Vec<&str> = Vec::new();
    for (n, line) in content.lines().enumerate() {
        match state {
            State::Normal => {
                if line.starts_with("<<<<<<< ") {
                    state = State::Ours;
                } else {
                    out.push(line);
                }
            }
            State::Ours => {
                if line.starts_with("|||||||") {
                    state = State::Base;
                } else if line.trim_end() == "=======" {
                    state = State::Theirs;
                } else if line.starts_with(">>>>>>> ") {
                    return Err(format!(
                        "line {}: end marker before `=======` separator",
                        n + 1
                    ));
                } else if side == ConflictSide::Ours {
                    out.push(line);
                }
            }
            State::Base => {
                if line.trim_end() == "=======" {
                    state = State::Theirs;
                }
                // base-section lines belong to neither side
            }
            State::Theirs => {
                if line.starts_with(">>>>>>> ") {
                    state = State::Normal;
                } else if side == ConflictSide::Theirs {
                    out.push(line);
                }
            }
        }
    }
    if state != State::Normal {
        return Err("unterminated conflict block (no `>>>>>>> ` end marker)".to_string());
    }
    let mut resolved = out.join("\n");
    if content.ends_with('\n') && !resolved.ends_with('\n') {
        resolved.push('\n');
    }
    Ok(resolved)
}

/// Why a file cannot take the `merged` resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergedRefusal {
    /// The markers themselves are malformed.
    Malformed(String),
    /// A conflict block covers something other than `last_modified`:
    /// the frontmatter key it names, or the body section it sits in.
    NotTimestampOnly {
        key: Option<String>,
        section: Option<String>,
    },
}

/// The `merged` resolution of `content`: git's merged file with each
/// conflict block replaced by the later of its two `last_modified`
/// values. Every block must lie inside the frontmatter, and each of its
/// sides must be exactly one `last_modified:` line; anything else is
/// [`MergedRefusal::NotTimestampOnly`] naming the block's key (in the
/// frontmatter) or its section (in the body). The values are the
/// engine's own ISO-8601 stamps, which order as strings.
pub fn extract_timestamp_only_merge(content: &str) -> Result<String, MergedRefusal> {
    #[derive(PartialEq)]
    enum State {
        Normal,
        Ours,
        Base,
        Theirs,
    }
    let key_of = |line: &str| -> Option<String> {
        let (key, _) = line.split_once(':')?;
        let key = key.trim();
        (!key.is_empty() && !key.contains(' ')).then(|| key.to_string())
    };
    let mut state = State::Normal;
    let mut out: Vec<String> = Vec::new();
    // Frontmatter: the lines between an opening `---` on line 1 and the
    // next `---`.
    let mut fence_count = 0usize;
    let mut section: Option<String> = None;
    let mut ours: Vec<&str> = Vec::new();
    let mut theirs: Vec<&str> = Vec::new();
    for (n, line) in content.lines().enumerate() {
        let in_frontmatter = fence_count == 1;
        match state {
            State::Normal => {
                if line.starts_with("<<<<<<< ") {
                    state = State::Ours;
                    ours.clear();
                    theirs.clear();
                    continue;
                }
                if line.trim_end() == "---" && (n == 0 || fence_count == 1) {
                    fence_count += 1;
                } else if fence_count >= 2
                    && let Some(heading) = line.strip_prefix("## ")
                {
                    section = Some(heading.trim().to_string());
                }
                out.push(line.to_string());
            }
            State::Ours => {
                if line.starts_with("|||||||") {
                    state = State::Base;
                } else if line.trim_end() == "=======" {
                    state = State::Theirs;
                } else if line.starts_with(">>>>>>> ") {
                    return Err(MergedRefusal::Malformed(format!(
                        "line {}: end marker before `=======` separator",
                        n + 1
                    )));
                } else {
                    ours.push(line);
                }
            }
            State::Base => {
                if line.trim_end() == "=======" {
                    state = State::Theirs;
                }
            }
            State::Theirs => {
                if !line.starts_with(">>>>>>> ") {
                    theirs.push(line);
                    continue;
                }
                state = State::Normal;
                let refuse = |lines: &[&str]| {
                    let key = lines
                        .iter()
                        .find_map(|l| key_of(l).filter(|k| k != "last_modified"));
                    if in_frontmatter {
                        MergedRefusal::NotTimestampOnly {
                            key: key.or_else(|| Some("last_modified".to_string())),
                            section: None,
                        }
                    } else {
                        MergedRefusal::NotTimestampOnly {
                            key: None,
                            section: section.clone().or_else(|| Some("(title)".to_string())),
                        }
                    }
                };
                let both: Vec<&str> = ours.iter().chain(theirs.iter()).copied().collect();
                let stamp = |lines: &[&str]| -> Option<String> {
                    match lines {
                        [one] if key_of(one).as_deref() == Some("last_modified") => {
                            Some(one.split_once(':')?.1.trim().to_string())
                        }
                        _ => None,
                    }
                };
                let (Some(a), Some(b), true) = (stamp(&ours), stamp(&theirs), in_frontmatter)
                else {
                    return Err(refuse(&both));
                };
                let later = if a >= b { a } else { b };
                out.push(format!("last_modified: {later}"));
            }
        }
    }
    if state != State::Normal {
        return Err(MergedRefusal::Malformed(
            "unterminated conflict block (no `>>>>>>> ` end marker)".to_string(),
        ));
    }
    let mut resolved = out.join("\n");
    if content.ends_with('\n') && !resolved.ends_with('\n') {
        resolved.push('\n');
    }
    Ok(resolved)
}

impl Engine {
    /// Resolve a mem name to its writable FOLDER mount. The visibility
    /// gate mirrors `search`'s (quarantined or invisible → the same
    /// `UNKNOWN_MEM` refusal); a visible non-folder mem refuses
    /// `CONFLICT_RESOLVE_UNSUPPORTED_BACKEND`.
    fn folder_mount(&self, mem: &str) -> Result<(usize, std::path::PathBuf), EngineError> {
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem)
            .ok_or_else(|| self.unknown_mem_error(mem))?;
        if self.quarantine_reason(mem).is_some() {
            return Err(self.unknown_mem_error(mem));
        }
        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem.to_string()));
        }
        match &self.mounts[mount_idx].mount.storage {
            MountStorage::Folder { path } => Ok((mount_idx, path.clone())),
            _ => Err(EngineError::MergeConflictUnsupportedBackend {
                mem: mem.to_string(),
            }),
        }
    }

    /// List every entity file carrying git merge-conflict markers.
    ///
    /// `mem: Some(name)` scopes to that mem and refuses typed when it
    /// is unknown or not folder-backed; `None` sweeps every writable
    /// folder mem (non-folder mounts are simply not applicable and are
    /// skipped — the unscoped sweep answers "what is conflicted",
    /// never "which backends exist").
    pub fn list_merge_conflicts(
        &self,
        mem: Option<&str>,
    ) -> Result<Vec<ConflictedEntity>, EngineError> {
        let targets: Vec<(String, std::path::PathBuf)> = match mem {
            Some(name) => {
                let (_, root) = self.folder_mount(name)?;
                vec![(name.to_string(), root)]
            }
            None => self
                .mounts
                .iter()
                .filter(|m| m.mount.capability == MountCapability::Write)
                .filter_map(|m| match &m.mount.storage {
                    MountStorage::Folder { path } => Some((m.mount.mem.clone(), path.clone())),
                    _ => None,
                })
                .collect(),
        };
        let mut out = Vec::new();
        for (mem_name, root) in targets {
            let (entries, _read_errors) = EntitySource::Directory { root }
                .read_all()
                .map_err(|e| EngineError::InvalidInput(format!("read mem directory: {e}")))?;
            for entry in entries {
                if parser::has_merge_conflict_markers(&entry.content) {
                    out.push(ConflictedEntity {
                        id: file_path_to_id(&entry.relative_path, &mem_name),
                        mem: mem_name.clone(),
                        file_path: entry.relative_path,
                    });
                }
            }
        }
        out.sort_by(|a, b| a.id.0.cmp(&b.id.0));
        Ok(out)
    }

    /// Resolve one conflicted entity to the chosen side.
    ///
    /// The chosen side must parse as a valid entity against the mem's
    /// schema BEFORE anything is written — resolution never launders an
    /// invalid entity into the mem. On success the resolved content is
    /// written through the mem's backend, committed with an attributed
    /// [`CommitContext`] (note included when given) together with its
    /// provenance record, and the mem is reloaded so the entity reads
    /// validly and the conflict load-error clears. The mem's write lock
    /// is held throughout.
    pub fn resolve_merge_conflict(
        &mut self,
        id: &EntityId,
        side: ConflictSide,
        actor: Actor,
        client: Option<&ClientId>,
        note: Option<&str>,
    ) -> Result<ResolveConflictOutcome, EngineError> {
        let mem = id.mem().to_string();
        // The write lock is held from before the conflicted file is
        // read until its resolution is committed, like any other
        // write: a second process cannot change the file in between.
        // The side it writes can hold relationship rows and links into
        // any mem, so it holds every mem's lock: a delete or a rename
        // of something the resolved entity refers to cannot run beside
        // it.
        let (_write_lock, mut warnings) = self.lock_workspace_for_write_if(true)?;
        let (mount_idx, root) = self.folder_mount(&mem)?;

        // Locate the file whose path derives to the requested id. The
        // conflicted entity is NOT in the store (its file refused to
        // load), so the lookup goes over the source files directly.
        let (entries, _read_errors) = EntitySource::Directory { root }
            .read_all()
            .map_err(|e| EngineError::InvalidInput(format!("read mem directory: {e}")))?;
        let Some(entry) = entries
            .into_iter()
            .find(|e| file_path_to_id(&e.relative_path, &mem) == *id)
        else {
            return Err(self.not_found(id.as_ref()));
        };
        if !parser::has_merge_conflict_markers(&entry.content) {
            return Err(EngineError::NotConflicted { id: id.to_string() });
        }

        let malformed = |m: String| {
            EngineError::InvalidInput(format!(
                "malformed conflict markers in {}: {m}",
                entry.relative_path
            ))
        };
        let resolved = match side {
            ConflictSide::Merged => {
                extract_timestamp_only_merge(&entry.content).map_err(|r| match r {
                    MergedRefusal::Malformed(m) => malformed(m),
                    MergedRefusal::NotTimestampOnly { key, section } => {
                        EngineError::ConflictNotTimestampOnly {
                            id: id.to_string(),
                            key,
                            section,
                        }
                    }
                })?
            }
            _ => extract_conflict_side(&entry.content, side).map_err(malformed)?,
        };

        // Validate the chosen side as an entity BEFORE any write —
        // resolution never launders an invalid entity into the mem.
        // Load-grade first: the chosen side must itself be free of
        // conflict markers (a nested conflict from a recursive merge
        // leaves residue in one side), or the mem would refuse to load
        // it right back. Then write-grade: the tolerant parser accepts
        // nearly anything, so the schema checks the mutation surface
        // applies to section shape run here too — unknown section keys
        // and content-format violations refuse with the same typed
        // validation errors a write would raise. Missing required
        // sections stay soft on purpose, matching `memstead_update`'s
        // permissive posture: resolution is an update-kind mutation on
        // an entity that already exists, and refusing here could leave
        // BOTH sides unresolvable — a locked door again.
        if parser::has_merge_conflict_markers(&resolved) {
            return Err(EngineError::InvalidInput(format!(
                "the {} side of {} still carries conflict markers (nested conflict) — \
                 refusing to write it; resolve the other side or repair upstream first",
                side.as_wire(),
                entry.relative_path
            )));
        }
        let schema = self
            .schemas
            .get(&mem)
            .cloned()
            .ok_or_else(|| self.unknown_mem_error(&mem))?;
        let resolved_type = loader::resolve_type_for_entry(&schema, &resolved);
        let parsed = parser::parse_markdown(
            &resolved,
            &entry.relative_path,
            resolved_type.as_ref(),
            &mem,
        )?;
        crate::runtime_validator::validate_section_keys(
            parsed.entity.sections.keys().map(String::as_str),
            resolved_type.as_ref(),
        )?;
        let mut heading_buf: Vec<&str> = Vec::new();
        let catch_all =
            crate::runtime_validator::catch_all_context(resolved_type.as_ref(), &mut heading_buf);
        crate::runtime_validator::validate_section_content(
            parsed
                .entity
                .sections
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str())),
            catch_all,
        )?;

        // The chosen side is written as the engine writes any entity:
        // a link in its body gets its relationship row, and every row
        // passes the checks a declared write passes (target grammar,
        // relationship type and endpoint shape, a cycle on an acyclic
        // relationship). The cycle walk reads every mem, so all are
        // loaded first; the workspace lock is held. A side that fails
        // refuses with the declared write's code and stays in conflict;
        // the other side stays resolvable.
        self.ensure_mems_loaded(None);
        let mut entity = parsed.entity;
        let resolved = match crate::engine::mutation::synthesise_alias_relations(
            self,
            &std::collections::HashSet::new(),
            &mut entity,
        )? {
            outcome if !outcome.emitted.is_empty() => {
                crate::engine::mutation::render_for_write(&entity, resolved_type.as_ref())?
            }
            _ => resolved,
        };
        for rel in &entity.relationships {
            crate::engine::mutation::validate_relation_target_grammar(&rel.target)?;
            let to_type = self.store.get(&rel.target).map(|t| t.entity_type.clone());
            crate::engine::mutation::route_edge_validation(
                self,
                &rel.rel_type,
                &entity.entity_type,
                to_type.as_deref(),
                &mem,
                rel.target.mem(),
                &entity.id,
                &rel.target,
                true,
            )?;
            crate::engine::mutation::validate_edge_acyclicity(
                &self.store,
                &schema,
                &entity.id,
                &entity.entity_type,
                &rel.target,
                &rel.rel_type,
            )?;
        }

        // A gated value lands here as on any other write: the conflicted
        // file is not in the store, so the resolved side enters every
        // gated value it holds. A self-check gate commits only on a fresh
        // independent record naming the resolved bytes' own hash (content
        // checked before it entered conflict); a checks gate commits when
        // its related entities meet it. Only the transition forms are
        // read: the other constraints stay as soft as the missing
        // required sections above, so a resolution stays possible.
        {
            let def: &memstead_schema::TypeDefinition = resolved_type.as_ref();
            let check_provider = self.check_standing_provider();
            entity.content_hash = parser::compute_hash(&resolved);
            let transition_forms: Vec<_> = crate::ops::health::unsatisfied_constraints(
                &self.store,
                &entity,
                def,
                Some(&entity.id),
                Some(&check_provider),
            )
            .into_iter()
            .filter(|v| {
                matches!(
                    v,
                    crate::ops::health::UnsatisfiedConstraint::TransitionRequiresChecks { .. }
                )
            })
            .collect();
            let content_hash = entity.content_hash.clone();
            let (violated, _) =
                self.gate_transition_forms(None, &entity, &content_hash, def, transition_forms);
            let blocked: Vec<_> = violated
                .into_iter()
                .filter(|v| v.severity() == memstead_schema::ConstraintSeverity::Block)
                .collect();
            if !blocked.is_empty() {
                return Err(EngineError::ConstraintUnsatisfied {
                    entity_type: entity.entity_type.clone(),
                    entity_id: entity.id.to_string(),
                    violations: blocked,
                });
            }
        }

        let backend = self.mounts[mount_idx].backend.as_ref();
        backend.write_entity(Path::new(&entry.relative_path), resolved.as_bytes())?;
        let ctx = self.commit_context(
            Some("resolve_conflict"),
            actor,
            client.cloned(),
            note.map(String::from),
        );
        // The record lands with the commit, through the one commit call.
        let record = Provenance::new(
            std::time::SystemTime::now(),
            ProvenanceKind::Update,
            Some(id.to_string()),
            actor,
            client.cloned(),
            note.map(String::from),
        )
        .with_role(self.current_role)
        .with_identity(self.current_identity.clone());
        let landed = self.commit_staged(
            mount_idx,
            &format!("memstead: resolve-conflict {id} (side: {})", side.as_wire()),
            &ctx,
            std::slice::from_ref(&record),
        )?;
        let write_id = landed.write_id;
        warnings.extend(landed.warnings);
        self.record_self_write(mount_idx, &write_id);
        warnings.extend(self.stamp_mutation_versions(mount_idx));

        // Reload so the resolved entity enters the store and the
        // conflict load-error clears — the caller's next read sees a
        // clean mem, not a stale refusal.
        self.reload_each_writable_mem()?;

        Ok(ResolveConflictOutcome {
            warnings,
            id: id.clone(),
            side: side.as_wire(),
            write_id,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const CONFLICTED: &str = "---\ntype: spec\n---\n# Torn\n\n## Identity\n\n\
<<<<<<< HEAD\nours line\n||||||| base\nbase line\n=======\ntheirs line\n\
>>>>>>> feature\n\n## Purpose\n\nshared tail\n";

    /// Build a booted folder workspace with one mem (`specs`) whose
    /// files are exactly `files`. Returns `(tempdir, engine)`.
    fn folder_workspace(files: &[(&str, &str)]) -> (tempfile::TempDir, Engine) {
        use crate::workspace::{Mount, MountLifecycle};
        use crate::workspace_store::WorkspaceStoreAdapter;

        let tmp = tempfile::TempDir::new().unwrap();
        let mem_dir = tmp.path().join("specs");
        std::fs::create_dir_all(&mem_dir).unwrap();
        for (name, content) in files {
            std::fs::write(mem_dir.join(name), content).unwrap();
        }
        let memstead = tmp.path().join(".memstead");
        std::fs::create_dir_all(&memstead).unwrap();
        std::fs::write(
            memstead.join("workspace.toml"),
            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
        )
        .unwrap();
        let mount = Mount {
            mem: "specs".to_string(),
            schema: Some(memstead_schema::SchemaRef::new(
                "default",
                semver::Version::new(1, 0, 0),
            )),
            storage: MountStorage::Folder { path: mem_dir },
            capability: MountCapability::Write,
            lifecycle: MountLifecycle::Eager,
            cross_linkable: true,
            migration_target: None,
        };
        crate::FileWorkspaceStore::new()
            .save_state(
                tmp.path(),
                &crate::workspace::Workspace {
                    mounts: vec![mount],
                    settings: crate::workspace::WorkspaceSettings::default(),
                },
            )
            .unwrap();
        let engine = Engine::from_workspace_root(tmp.path()).expect("workspace boots");
        (tmp, engine)
    }

    const CLEAN: &str = "---\ntype: spec\n---\n# Fine\n\n## Identity\n\nis\n\n## Purpose\n\nok\n";

    /// On a live folder workspace: the load
    /// refusal names the resolve remedy, the conflicted entity lists,
    /// resolving to theirs makes the mem load clean with the entity
    /// valid, and the resolution lands in the provenance ledger with
    /// its note. Complements: resolving the already-clean entity
    /// refuses `NOT_CONFLICTED`; a missing id refuses not-found.
    #[test]
    fn conflicted_folder_entity_lists_resolves_and_reads_clean() {
        let (tmp, mut engine) = folder_workspace(&[("torn.md", CONFLICTED), ("fine.md", CLEAN)]);

        // The parse failure an agent hits names the remedy.
        let errors = engine.load_errors();
        assert_eq!(errors.len(), 1, "exactly the conflicted file refuses");
        assert!(
            errors[0].1.contains("memstead conflicts resolve"),
            "load error names the resolve operation: {}",
            errors[0].1
        );

        // The conflicted entity is identified; the clean one is not.
        let listed = engine.list_merge_conflicts(None).unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].id.as_ref(), "specs--torn");
        assert_eq!(listed[0].file_path, "torn.md");

        // Resolve to theirs.
        let id = EntityId("specs--torn".into());
        let outcome = engine
            .resolve_merge_conflict(
                &id,
                ConflictSide::Theirs,
                Actor::Cli,
                None,
                Some("keeping upstream wording"),
            )
            .expect("resolution succeeds");
        assert_eq!(outcome.side, "theirs");

        // The mem loads clean and the entity reads validly.
        assert!(
            engine.load_errors().is_empty(),
            "{:?}",
            engine.load_errors()
        );
        let entity = engine.get_entity(&id).expect("resolved entity is loaded");
        assert!(!entity.stub);
        assert!(
            entity
                .sections
                .get("identity")
                .unwrap()
                .contains("theirs line"),
            "the kept side's content is live: {:?}",
            entity.sections.get("identity")
        );
        let on_disk = std::fs::read_to_string(tmp.path().join("specs").join("torn.md")).unwrap();
        assert!(!on_disk.contains("<<<<<<<") && !on_disk.contains("ours line"));

        // Provenance: the resolution is an attributed ledger entry
        // carrying the note — never an untracked file swap.
        let ledger = std::fs::read_to_string(
            tmp.path()
                .join("specs")
                .join(".memstead")
                .join("changes.jsonl"),
        )
        .expect("folder provenance ledger exists");
        assert!(
            ledger.contains("specs--torn") && ledger.contains("keeping upstream wording"),
            "ledger records the resolution with its note: {ledger}"
        );

        // Complements: already-clean refuses NOT_CONFLICTED; unknown
        // id refuses not-found.
        let err = engine
            .resolve_merge_conflict(&id, ConflictSide::Ours, Actor::Cli, None, None)
            .unwrap_err();
        assert_eq!(err.code(), "NOT_CONFLICTED");
        let err = engine
            .resolve_merge_conflict(
                &EntityId("specs--absent".into()),
                ConflictSide::Ours,
                Actor::Cli,
                None,
                None,
            )
            .unwrap_err();
        assert_eq!(err.code(), "ENTITY_NOT_FOUND");
    }

    /// Complement: a fenced code example DOCUMENTING conflict markers
    /// is legal content — it loads without a conflict refusal and does
    /// not list as conflicted (the detector evaluates masked content).
    #[test]
    fn fenced_marker_example_is_not_a_conflict() {
        let doc = "---\ntype: spec\n---\n# Git Lore\n\n## Identity\n\n\
```text\n<<<<<<< HEAD\nexample\n=======\nexample\n>>>>>>> branch\n```\n\n\
## Purpose\n\nteaching\n";
        let (_tmp, engine) = folder_workspace(&[("lore.md", doc)]);
        assert!(
            engine.load_errors().is_empty(),
            "{:?}",
            engine.load_errors()
        );
        assert!(engine.list_merge_conflicts(None).unwrap().is_empty());
        assert!(engine.get_entity(&EntityId("specs--lore".into())).is_some());
    }

    /// A chosen side that fails entity validation
    /// refuses with the validation error and writes nothing. The
    /// fixture is a nested conflict (recursive-merge shape): the
    /// theirs side still carries marker residue after extraction, so
    /// writing it would put the mem right back into the unloadable
    /// state — resolution refuses; the clean ours side resolves.
    #[test]
    fn invalid_chosen_side_refuses_and_writes_nothing() {
        let nested = "---\ntype: spec\n---\n# Nested\n\n## Identity\n\n\
<<<<<<< HEAD\nours\n=======\n<<<<<<< inner\ntheirs-a\n=======\ntheirs-b\n\
>>>>>>> inner\n>>>>>>> outer\n\n## Purpose\n\np\n";
        let (tmp, mut engine) = folder_workspace(&[("nested.md", nested)]);

        let id = EntityId("specs--nested".into());
        let err = engine
            .resolve_merge_conflict(&id, ConflictSide::Theirs, Actor::Cli, None, None)
            .unwrap_err();
        assert_eq!(err.code(), "INVALID_INPUT", "got: {err}");
        assert!(
            err.to_string().contains("still carries conflict markers"),
            "refusal names the residue: {err}"
        );
        // Nothing was written: the original markers are still on disk.
        let on_disk = std::fs::read_to_string(tmp.path().join("specs").join("nested.md")).unwrap();
        assert!(
            on_disk.contains("<<<<<<< HEAD"),
            "file untouched on refusal"
        );

        // The ours side is clean and resolves fine.
        engine
            .resolve_merge_conflict(&id, ConflictSide::Ours, Actor::Cli, None, None)
            .expect("clean side resolves");
        assert!(engine.load_errors().is_empty());
    }

    /// A folder workspace mounting one mem on a fixture schema: types
    /// `thing` and `other`; `LINKS` joins a `thing` to an `other` only;
    /// body wiki-links are `REFERENCES` rows, and `REFERENCES` is acyclic.
    fn edge_fixture(files: &[(&str, &str)]) -> (tempfile::TempDir, Engine) {
        let (tmp, engine) = folder_workspace(files);
        drop(engine);
        let dir = tmp
            .path()
            .join(".memstead")
            .join("schemas")
            .join("cx@0.1.0");
        std::fs::create_dir_all(dir.join("types")).unwrap();
        std::fs::write(
            dir.join("schema.yaml"),
            "name: cx\nversion: 0.1.0\ndescription: d\nwhen_to_use: t\ntypes:\n  - thing\n  - other\nrelationships:\n  mode: strict\n  definitions:\n    - name: LINKS\n      description: l\n      default_weight: 1.0\n      source_types: [thing]\n      target_types: [other]\n    - name: REFERENCES\n      description: r\n      default_weight: 1.0\n      acyclic: true\n    - name: _default\n      description: f\n      default_weight: 1.0\nalias_target_rel_type: REFERENCES\ncommunity:\n  resolution: 1.0\n  seed: 42\n",
        )
        .unwrap();
        for ty in ["thing", "other"] {
            std::fs::write(
                dir.join("types").join(format!("{ty}.yaml")),
                format!("name: {ty}\ndescription: t\nwhen_to_use: Here\nsections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: _default\nno_self_loop_relationships: []\nupdatable_fields:\n  - title\n  - body\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\n"),
            )
            .unwrap();
        }
        {
            use crate::workspace_store::WorkspaceStoreAdapter;
            let mount = crate::workspace::Mount {
                mem: "specs".to_string(),
                schema: Some(memstead_schema::SchemaRef::new(
                    "cx",
                    semver::Version::new(0, 1, 0),
                )),
                storage: MountStorage::Folder {
                    path: tmp.path().join("specs"),
                },
                capability: MountCapability::Write,
                lifecycle: crate::workspace::MountLifecycle::Eager,
                cross_linkable: true,
                migration_target: None,
            };
            crate::FileWorkspaceStore::new()
                .save_state(
                    tmp.path(),
                    &crate::workspace::Workspace {
                        mounts: vec![mount],
                        settings: crate::workspace::WorkspaceSettings::default(),
                    },
                )
                .unwrap();
        }
        let engine = Engine::from_workspace_root(tmp.path()).expect("workspace boots");
        (tmp, engine)
    }

    fn conflicted(ty: &str, title: &str, theirs: &str) -> String {
        format!(
            "---\ntype: {ty}\n---\n# {title}\n\n## Body\n\n<<<<<<< HEAD\nkept as it was\n=======\n{theirs}\n>>>>>>> theirs\n"
        )
    }

    /// The chosen side's rows pass the declared-edge checks: an
    /// undeclared relationship type, an endpoint the schema forbids and
    /// a body link closing a cycle on an acyclic relationship each
    /// refuse with the code the declared write raises, the file stays in
    /// conflict, and the other side resolves.
    #[test]
    fn a_resolution_lands_only_rows_a_declared_write_could_land() {
        let target = "---\ntype: other\n---\n# Target\n\n## Body\n\nsee [[specs--loop]]\n\n## Relationships\n\n- **REFERENCES**: [[specs--loop]]\n";
        let peer = "---\ntype: thing\n---\n# Peer\n\n## Body\n\nplain\n";
        let cases = [
            (
                "thing",
                "Undeclared",
                "a\n\n## Relationships\n\n- **BOGUS**: [[specs--target]]".to_string(),
                "INVALID_REL_TYPE",
            ),
            (
                "thing",
                "Shape",
                "a\n\n## Relationships\n\n- **LINKS**: [[specs--peer]]".to_string(),
                "INVALID_REL_SHAPE",
            ),
            (
                "thing",
                "Loop",
                "closes the loop: [[specs--target]]".to_string(),
                "RELATIONSHIP_CYCLE",
            ),
        ];
        for (ty, title, theirs, code) in cases {
            let slug = title.to_lowercase();
            let file = format!("{slug}.md");
            let body = conflicted(ty, title, &theirs);
            let (tmp, mut engine) =
                edge_fixture(&[("target.md", target), ("peer.md", peer), (&file, &body)]);
            let id = EntityId(format!("specs--{slug}"));
            let err = engine
                .resolve_merge_conflict(&id, ConflictSide::Theirs, Actor::Cli, None, None)
                .unwrap_err();
            assert_eq!(err.code(), code, "{title}: {err}");
            let on_disk = std::fs::read_to_string(tmp.path().join("specs").join(&file)).unwrap();
            assert!(
                on_disk.contains("<<<<<<< HEAD"),
                "{title}: still in conflict"
            );
            engine
                .resolve_merge_conflict(&id, ConflictSide::Ours, Actor::Cli, None, None)
                .unwrap_or_else(|e| panic!("{title}: ours resolves: {e}"));
        }
    }

    #[test]
    fn extract_sides_and_diff3_base_drops() {
        let ours = extract_conflict_side(CONFLICTED, ConflictSide::Ours).unwrap();
        assert!(ours.contains("ours line"));
        assert!(!ours.contains("theirs line") && !ours.contains("base line"));
        assert!(ours.contains("shared tail"));
        let theirs = extract_conflict_side(CONFLICTED, ConflictSide::Theirs).unwrap();
        assert!(theirs.contains("theirs line"));
        assert!(!theirs.contains("ours line") && !theirs.contains("base line"));
        assert!(!theirs.contains("<<<<<<<") && !theirs.contains(">>>>>>>"));
    }

    #[test]
    fn malformed_markers_refuse() {
        let unterminated = "a\n<<<<<<< HEAD\nours\n=======\ntheirs\n";
        assert!(extract_conflict_side(unterminated, ConflictSide::Ours).is_err());
        let inverted = "a\n<<<<<<< HEAD\nours\n>>>>>>> feature\n";
        assert!(extract_conflict_side(inverted, ConflictSide::Ours).is_err());
    }

    /// A file after a rebase whose only conflict is the two stamped
    /// `last_modified` lines, with both sides' body additions merged by
    /// git: `merged` keeps git's file and the later stamp, and the entity
    /// validates.
    const STAMP_ONLY: &str = "---\ntype: spec\ncreated_date: 2026-01-01\n\
<<<<<<< HEAD\nlast_modified: 2026-03-02T10:00:00Z\n=======\nlast_modified: 2026-03-04T09:00:00Z\n\
>>>>>>> feature\n---\n# Torn\n\n## Identity\n\nidentity body\nours addition\n\n\
## Purpose\n\npurpose body\ntheirs addition\n";

    #[test]
    fn a_timestamp_only_conflict_resolves_merged_with_both_additions_and_the_later_stamp() {
        let (tmp, mut engine) = folder_workspace(&[("torn.md", STAMP_ONLY)]);
        let id = EntityId::new("specs", "torn");
        let outcome = engine
            .resolve_merge_conflict(&id, ConflictSide::Merged, Actor::Cli, None, Some("stamp"))
            .expect("a stamp-only conflict resolves merged");
        assert_eq!(outcome.side, "merged");
        let written = std::fs::read_to_string(tmp.path().join("specs/torn.md")).unwrap();
        assert!(!parser::has_merge_conflict_markers(&written), "{written}");
        assert!(written.contains("ours addition"), "{written}");
        assert!(written.contains("theirs addition"), "{written}");
        assert!(
            written.contains("last_modified: 2026-03-04T09:00:00Z"),
            "{written}"
        );
        assert!(!written.contains("2026-03-02T10:00:00Z"), "{written}");
        let entity = engine.get_entity(&id).expect("the entity loads");
        assert!(!entity.stub);
    }

    /// A conflict block on anything but `last_modified` refuses
    /// `CONFLICT_NOT_TIMESTAMP_ONLY` naming its key or section, and the
    /// file stays in conflict.
    #[test]
    fn a_conflict_beyond_the_timestamp_refuses_merged_naming_where() {
        let body = "---\ntype: spec\nlast_modified: 2026-03-02T10:00:00Z\n---\n# Torn\n\n\
## Identity\n\n<<<<<<< HEAD\nours line\n=======\ntheirs line\n>>>>>>> feature\n\n\
## Purpose\n\ntail\n";
        let created = "---\ntype: spec\n<<<<<<< HEAD\ncreated_date: 2026-01-01\n=======\n\
created_date: 2026-01-02\n>>>>>>> feature\nlast_modified: 2026-03-02T10:00:00Z\n---\n# Torn\n\n\
## Identity\n\nx\n";
        let stamp_and_more = "---\ntype: spec\n<<<<<<< HEAD\nlast_modified: 2026-03-02T10:00:00Z\n\
level: M0\n=======\nlast_modified: 2026-03-04T09:00:00Z\nlevel: M1\n>>>>>>> feature\n---\n\
# Torn\n\n## Identity\n\nx\n";
        for (content, key, section) in [
            (body, None, Some("Identity")),
            (created, Some("created_date"), None),
            (stamp_and_more, Some("level"), None),
        ] {
            let (tmp, mut engine) = folder_workspace(&[("torn.md", content)]);
            let id = EntityId::new("specs", "torn");
            let err = engine
                .resolve_merge_conflict(&id, ConflictSide::Merged, Actor::Cli, None, None)
                .expect_err("not a stamp-only conflict");
            assert_eq!(err.code(), "CONFLICT_NOT_TIMESTAMP_ONLY", "{err}");
            let d = err.details();
            assert_eq!(d["key"].as_str(), key, "{d}");
            assert_eq!(d["section"].as_str(), section, "{d}");
            let still = std::fs::read_to_string(tmp.path().join("specs/torn.md")).unwrap();
            assert_eq!(still, content, "the file stays in conflict");
        }
    }
}