Skip to main content

memstead_base/engine/
conflicts.rs

1//! Merge-conflict resolution for folder mems.
2//!
3//! A hand-committed folder mem lives inside the user's own git
4//! repository, so an ordinary merge can write conflict markers into
5//! entity files. At that moment every other door is locked by design:
6//! the loader refuses the file (naming this operation as the remedy),
7//! and the guards correctly block git verbs and raw edits against mem
8//! content. This module is the one sanctioned door — the agent judges
9//! each conflict on its content and the engine is the pair of hands:
10//! the chosen side is validated as an entity BEFORE it lands (a broken
11//! ours side never launders into the mem), and the resolution commits
12//! as an attributed, note-carrying mutation like any other write.
13//!
14//! Scope is deliberately narrow: per-entity, two sides (ours/theirs),
15//! folder backend only, and one merged mode for what the engine itself
16//! stamped. A merged-content resolution of a body conflict is out of
17//! scope by design: that is a content judgement, made by choosing a side
18//! as the base and then editing through the normal mutation surface,
19//! which preserves validation and provenance; the operation's note is
20//! the designated place to record "base for a manual merge; discarded
21//! side: <which>". The one exception is `merged`: when every conflict
22//! block covers only the engine-stamped `last_modified` key, git's merge
23//! of the rest is kept and the later timestamp wins
24//! ([`extract_timestamp_only_merge`]).
25//! The git-branch backend's mem-repo is engine-managed and cannot
26//! acquire merge conflicts through supported use, so it refuses typed
27//! rather than pretending applicability.
28
29use std::path::Path;
30
31use crate::entity::id::file_path_to_id;
32use crate::entity::{EntityId, loader, parser, source::EntitySource};
33use crate::provenance::{Provenance, ProvenanceKind};
34use crate::vcs::{Actor, ClientId};
35use crate::workspace::{MountCapability, MountStorage};
36
37use super::{Engine, EngineError};
38
39/// Which side of a git merge conflict to keep.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum ConflictSide {
42    Ours,
43    Theirs,
44    /// Keep git's merged file, valid only when every conflict block lies
45    /// in the frontmatter and covers the engine-stamped `last_modified`
46    /// key alone; the later value wins.
47    Merged,
48}
49
50impl ConflictSide {
51    /// Parse the wire token (`"ours"` / `"theirs"`). `None` for an
52    /// unrecognized token so the calling surface raises a typed error
53    /// naming the bad value.
54    pub fn from_wire(s: &str) -> Option<Self> {
55        match s {
56            "ours" => Some(Self::Ours),
57            "theirs" => Some(Self::Theirs),
58            "merged" => Some(Self::Merged),
59            _ => None,
60        }
61    }
62
63    /// The wire token for this side.
64    pub fn as_wire(self) -> &'static str {
65        match self {
66            Self::Ours => "ours",
67            Self::Theirs => "theirs",
68            Self::Merged => "merged",
69        }
70    }
71}
72
73/// One conflicted entity file found in a folder mem.
74#[derive(Debug, Clone, serde::Serialize)]
75pub struct ConflictedEntity {
76    /// The entity id the file's path derives to — the handle
77    /// `resolve_merge_conflict` accepts.
78    pub id: EntityId,
79    pub mem: String,
80    /// Mem-relative file path, for human orientation.
81    pub file_path: String,
82}
83
84/// Outcome of a successful [`Engine::resolve_merge_conflict`].
85#[derive(Debug, Clone, serde::Serialize)]
86pub struct ResolveConflictOutcome {
87    pub id: EntityId,
88    /// The side that was kept (`"ours"` / `"theirs"`).
89    pub side: &'static str,
90    pub write_id: String,
91    /// Carries `CONFIG_WRITE_INTERVENED` when the mutation version stamp this
92    /// resolution triggered merged over another writer's config change.
93    /// Empty on the ordinary path.
94    #[serde(default, skip_serializing_if = "Vec::is_empty")]
95    pub warnings: Vec<crate::ops::WarningHint>,
96}
97
98/// Extract one side of a git merge conflict from raw file content.
99///
100/// Handles the standard two-way marker layout and the diff3 variant
101/// (`|||||||` base section, dropped from both sides). Operates on raw
102/// lines exactly as git wrote them — git places markers at line starts
103/// without regard for markdown structure. `Err` carries a description
104/// of the malformation (e.g. a start marker with no closing marker).
105pub fn extract_conflict_side(content: &str, side: ConflictSide) -> Result<String, String> {
106    #[derive(PartialEq)]
107    enum State {
108        Normal,
109        Ours,
110        Base,
111        Theirs,
112    }
113    let mut state = State::Normal;
114    let mut out: Vec<&str> = Vec::new();
115    for (n, line) in content.lines().enumerate() {
116        match state {
117            State::Normal => {
118                if line.starts_with("<<<<<<< ") {
119                    state = State::Ours;
120                } else {
121                    out.push(line);
122                }
123            }
124            State::Ours => {
125                if line.starts_with("|||||||") {
126                    state = State::Base;
127                } else if line.trim_end() == "=======" {
128                    state = State::Theirs;
129                } else if line.starts_with(">>>>>>> ") {
130                    return Err(format!(
131                        "line {}: end marker before `=======` separator",
132                        n + 1
133                    ));
134                } else if side == ConflictSide::Ours {
135                    out.push(line);
136                }
137            }
138            State::Base => {
139                if line.trim_end() == "=======" {
140                    state = State::Theirs;
141                }
142                // base-section lines belong to neither side
143            }
144            State::Theirs => {
145                if line.starts_with(">>>>>>> ") {
146                    state = State::Normal;
147                } else if side == ConflictSide::Theirs {
148                    out.push(line);
149                }
150            }
151        }
152    }
153    if state != State::Normal {
154        return Err("unterminated conflict block (no `>>>>>>> ` end marker)".to_string());
155    }
156    let mut resolved = out.join("\n");
157    if content.ends_with('\n') && !resolved.ends_with('\n') {
158        resolved.push('\n');
159    }
160    Ok(resolved)
161}
162
163/// Why a file cannot take the `merged` resolution.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub enum MergedRefusal {
166    /// The markers themselves are malformed.
167    Malformed(String),
168    /// A conflict block covers something other than `last_modified`:
169    /// the frontmatter key it names, or the body section it sits in.
170    NotTimestampOnly {
171        key: Option<String>,
172        section: Option<String>,
173    },
174}
175
176/// The `merged` resolution of `content`: git's merged file with each
177/// conflict block replaced by the later of its two `last_modified`
178/// values. Every block must lie inside the frontmatter, and each of its
179/// sides must be exactly one `last_modified:` line; anything else is
180/// [`MergedRefusal::NotTimestampOnly`] naming the block's key (in the
181/// frontmatter) or its section (in the body). The values are the
182/// engine's own ISO-8601 stamps, which order as strings.
183pub fn extract_timestamp_only_merge(content: &str) -> Result<String, MergedRefusal> {
184    #[derive(PartialEq)]
185    enum State {
186        Normal,
187        Ours,
188        Base,
189        Theirs,
190    }
191    let key_of = |line: &str| -> Option<String> {
192        let (key, _) = line.split_once(':')?;
193        let key = key.trim();
194        (!key.is_empty() && !key.contains(' ')).then(|| key.to_string())
195    };
196    let mut state = State::Normal;
197    let mut out: Vec<String> = Vec::new();
198    // Frontmatter: the lines between an opening `---` on line 1 and the
199    // next `---`.
200    let mut fence_count = 0usize;
201    let mut section: Option<String> = None;
202    let mut ours: Vec<&str> = Vec::new();
203    let mut theirs: Vec<&str> = Vec::new();
204    for (n, line) in content.lines().enumerate() {
205        let in_frontmatter = fence_count == 1;
206        match state {
207            State::Normal => {
208                if line.starts_with("<<<<<<< ") {
209                    state = State::Ours;
210                    ours.clear();
211                    theirs.clear();
212                    continue;
213                }
214                if line.trim_end() == "---" && (n == 0 || fence_count == 1) {
215                    fence_count += 1;
216                } else if fence_count >= 2
217                    && let Some(heading) = line.strip_prefix("## ")
218                {
219                    section = Some(heading.trim().to_string());
220                }
221                out.push(line.to_string());
222            }
223            State::Ours => {
224                if line.starts_with("|||||||") {
225                    state = State::Base;
226                } else if line.trim_end() == "=======" {
227                    state = State::Theirs;
228                } else if line.starts_with(">>>>>>> ") {
229                    return Err(MergedRefusal::Malformed(format!(
230                        "line {}: end marker before `=======` separator",
231                        n + 1
232                    )));
233                } else {
234                    ours.push(line);
235                }
236            }
237            State::Base => {
238                if line.trim_end() == "=======" {
239                    state = State::Theirs;
240                }
241            }
242            State::Theirs => {
243                if !line.starts_with(">>>>>>> ") {
244                    theirs.push(line);
245                    continue;
246                }
247                state = State::Normal;
248                let refuse = |lines: &[&str]| {
249                    let key = lines
250                        .iter()
251                        .find_map(|l| key_of(l).filter(|k| k != "last_modified"));
252                    if in_frontmatter {
253                        MergedRefusal::NotTimestampOnly {
254                            key: key.or_else(|| Some("last_modified".to_string())),
255                            section: None,
256                        }
257                    } else {
258                        MergedRefusal::NotTimestampOnly {
259                            key: None,
260                            section: section.clone().or_else(|| Some("(title)".to_string())),
261                        }
262                    }
263                };
264                let both: Vec<&str> = ours.iter().chain(theirs.iter()).copied().collect();
265                let stamp = |lines: &[&str]| -> Option<String> {
266                    match lines {
267                        [one] if key_of(one).as_deref() == Some("last_modified") => {
268                            Some(one.split_once(':')?.1.trim().to_string())
269                        }
270                        _ => None,
271                    }
272                };
273                let (Some(a), Some(b), true) = (stamp(&ours), stamp(&theirs), in_frontmatter)
274                else {
275                    return Err(refuse(&both));
276                };
277                let later = if a >= b { a } else { b };
278                out.push(format!("last_modified: {later}"));
279            }
280        }
281    }
282    if state != State::Normal {
283        return Err(MergedRefusal::Malformed(
284            "unterminated conflict block (no `>>>>>>> ` end marker)".to_string(),
285        ));
286    }
287    let mut resolved = out.join("\n");
288    if content.ends_with('\n') && !resolved.ends_with('\n') {
289        resolved.push('\n');
290    }
291    Ok(resolved)
292}
293
294impl Engine {
295    /// Resolve a mem name to its writable FOLDER mount. The visibility
296    /// gate mirrors `search`'s (quarantined or invisible → the same
297    /// `UNKNOWN_MEM` refusal); a visible non-folder mem refuses
298    /// `CONFLICT_RESOLVE_UNSUPPORTED_BACKEND`.
299    fn folder_mount(&self, mem: &str) -> Result<(usize, std::path::PathBuf), EngineError> {
300        let mount_idx = self
301            .mounts
302            .iter()
303            .position(|m| m.mount.mem == mem)
304            .ok_or_else(|| self.unknown_mem_error(mem))?;
305        if self.quarantine_reason(mem).is_some() {
306            return Err(self.unknown_mem_error(mem));
307        }
308        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
309            return Err(EngineError::ReadOnlyMount(mem.to_string()));
310        }
311        match &self.mounts[mount_idx].mount.storage {
312            MountStorage::Folder { path } => Ok((mount_idx, path.clone())),
313            _ => Err(EngineError::MergeConflictUnsupportedBackend {
314                mem: mem.to_string(),
315            }),
316        }
317    }
318
319    /// List every entity file carrying git merge-conflict markers.
320    ///
321    /// `mem: Some(name)` scopes to that mem and refuses typed when it
322    /// is unknown or not folder-backed; `None` sweeps every writable
323    /// folder mem (non-folder mounts are simply not applicable and are
324    /// skipped — the unscoped sweep answers "what is conflicted",
325    /// never "which backends exist").
326    pub fn list_merge_conflicts(
327        &self,
328        mem: Option<&str>,
329    ) -> Result<Vec<ConflictedEntity>, EngineError> {
330        let targets: Vec<(String, std::path::PathBuf)> = match mem {
331            Some(name) => {
332                let (_, root) = self.folder_mount(name)?;
333                vec![(name.to_string(), root)]
334            }
335            None => self
336                .mounts
337                .iter()
338                .filter(|m| m.mount.capability == MountCapability::Write)
339                .filter_map(|m| match &m.mount.storage {
340                    MountStorage::Folder { path } => Some((m.mount.mem.clone(), path.clone())),
341                    _ => None,
342                })
343                .collect(),
344        };
345        let mut out = Vec::new();
346        for (mem_name, root) in targets {
347            let (entries, _read_errors) = EntitySource::Directory { root }
348                .read_all()
349                .map_err(|e| EngineError::InvalidInput(format!("read mem directory: {e}")))?;
350            for entry in entries {
351                if parser::has_merge_conflict_markers(&entry.content) {
352                    out.push(ConflictedEntity {
353                        id: file_path_to_id(&entry.relative_path, &mem_name),
354                        mem: mem_name.clone(),
355                        file_path: entry.relative_path,
356                    });
357                }
358            }
359        }
360        out.sort_by(|a, b| a.id.0.cmp(&b.id.0));
361        Ok(out)
362    }
363
364    /// Resolve one conflicted entity to the chosen side.
365    ///
366    /// The chosen side must parse as a valid entity against the mem's
367    /// schema BEFORE anything is written — resolution never launders an
368    /// invalid entity into the mem. On success the resolved content is
369    /// written through the mem's backend, committed with an attributed
370    /// [`CommitContext`] (note included when given) together with its
371    /// provenance record, and the mem is reloaded so the entity reads
372    /// validly and the conflict load-error clears. The mem's write lock
373    /// is held throughout.
374    pub fn resolve_merge_conflict(
375        &mut self,
376        id: &EntityId,
377        side: ConflictSide,
378        actor: Actor,
379        client: Option<&ClientId>,
380        note: Option<&str>,
381    ) -> Result<ResolveConflictOutcome, EngineError> {
382        let mem = id.mem().to_string();
383        // The write lock is held from before the conflicted file is
384        // read until its resolution is committed, like any other
385        // write: a second process cannot change the file in between.
386        // The side it writes can hold relationship rows and links into
387        // any mem, so it holds every mem's lock: a delete or a rename
388        // of something the resolved entity refers to cannot run beside
389        // it.
390        let (_write_lock, mut warnings) = self.lock_workspace_for_write_if(true)?;
391        let (mount_idx, root) = self.folder_mount(&mem)?;
392
393        // Locate the file whose path derives to the requested id. The
394        // conflicted entity is NOT in the store (its file refused to
395        // load), so the lookup goes over the source files directly.
396        let (entries, _read_errors) = EntitySource::Directory { root }
397            .read_all()
398            .map_err(|e| EngineError::InvalidInput(format!("read mem directory: {e}")))?;
399        let Some(entry) = entries
400            .into_iter()
401            .find(|e| file_path_to_id(&e.relative_path, &mem) == *id)
402        else {
403            return Err(self.not_found(id.as_ref()));
404        };
405        if !parser::has_merge_conflict_markers(&entry.content) {
406            return Err(EngineError::NotConflicted { id: id.to_string() });
407        }
408
409        let malformed = |m: String| {
410            EngineError::InvalidInput(format!(
411                "malformed conflict markers in {}: {m}",
412                entry.relative_path
413            ))
414        };
415        let resolved = match side {
416            ConflictSide::Merged => {
417                extract_timestamp_only_merge(&entry.content).map_err(|r| match r {
418                    MergedRefusal::Malformed(m) => malformed(m),
419                    MergedRefusal::NotTimestampOnly { key, section } => {
420                        EngineError::ConflictNotTimestampOnly {
421                            id: id.to_string(),
422                            key,
423                            section,
424                        }
425                    }
426                })?
427            }
428            _ => extract_conflict_side(&entry.content, side).map_err(malformed)?,
429        };
430
431        // Validate the chosen side as an entity BEFORE any write —
432        // resolution never launders an invalid entity into the mem.
433        // Load-grade first: the chosen side must itself be free of
434        // conflict markers (a nested conflict from a recursive merge
435        // leaves residue in one side), or the mem would refuse to load
436        // it right back. Then write-grade: the tolerant parser accepts
437        // nearly anything, so the schema checks the mutation surface
438        // applies to section shape run here too — unknown section keys
439        // and content-format violations refuse with the same typed
440        // validation errors a write would raise. Missing required
441        // sections stay soft on purpose, matching `memstead_update`'s
442        // permissive posture: resolution is an update-kind mutation on
443        // an entity that already exists, and refusing here could leave
444        // BOTH sides unresolvable — a locked door again.
445        if parser::has_merge_conflict_markers(&resolved) {
446            return Err(EngineError::InvalidInput(format!(
447                "the {} side of {} still carries conflict markers (nested conflict) — \
448                 refusing to write it; resolve the other side or repair upstream first",
449                side.as_wire(),
450                entry.relative_path
451            )));
452        }
453        let schema = self
454            .schemas
455            .get(&mem)
456            .cloned()
457            .ok_or_else(|| self.unknown_mem_error(&mem))?;
458        let resolved_type = loader::resolve_type_for_entry(&schema, &resolved);
459        let parsed = parser::parse_markdown(
460            &resolved,
461            &entry.relative_path,
462            resolved_type.as_ref(),
463            &mem,
464        )?;
465        crate::runtime_validator::validate_section_keys(
466            parsed.entity.sections.keys().map(String::as_str),
467            resolved_type.as_ref(),
468        )?;
469        let mut heading_buf: Vec<&str> = Vec::new();
470        let catch_all =
471            crate::runtime_validator::catch_all_context(resolved_type.as_ref(), &mut heading_buf);
472        crate::runtime_validator::validate_section_content(
473            parsed
474                .entity
475                .sections
476                .iter()
477                .map(|(k, v)| (k.as_str(), v.as_str())),
478            catch_all,
479        )?;
480
481        // The chosen side is written as the engine writes any entity:
482        // a link in its body gets its relationship row, and every row
483        // passes the checks a declared write passes (target grammar,
484        // relationship type and endpoint shape, a cycle on an acyclic
485        // relationship). The cycle walk reads every mem, so all are
486        // loaded first; the workspace lock is held. A side that fails
487        // refuses with the declared write's code and stays in conflict;
488        // the other side stays resolvable.
489        self.ensure_mems_loaded(None);
490        let mut entity = parsed.entity;
491        let resolved = match crate::engine::mutation::synthesise_alias_relations(
492            self,
493            &std::collections::HashSet::new(),
494            &mut entity,
495        )? {
496            outcome if !outcome.emitted.is_empty() => {
497                crate::engine::mutation::render_for_write(&entity, resolved_type.as_ref())?
498            }
499            _ => resolved,
500        };
501        for rel in &entity.relationships {
502            crate::engine::mutation::validate_relation_target_grammar(&rel.target)?;
503            let to_type = self.store.get(&rel.target).map(|t| t.entity_type.clone());
504            crate::engine::mutation::route_edge_validation(
505                self,
506                &rel.rel_type,
507                &entity.entity_type,
508                to_type.as_deref(),
509                &mem,
510                rel.target.mem(),
511                &entity.id,
512                &rel.target,
513                true,
514            )?;
515            crate::engine::mutation::validate_edge_acyclicity(
516                &self.store,
517                &schema,
518                &entity.id,
519                &entity.entity_type,
520                &rel.target,
521                &rel.rel_type,
522            )?;
523        }
524
525        // A gated value lands here as on any other write: the conflicted
526        // file is not in the store, so the resolved side enters every
527        // gated value it holds. A self-check gate commits only on a fresh
528        // independent record naming the resolved bytes' own hash (content
529        // checked before it entered conflict); a checks gate commits when
530        // its related entities meet it. Only the transition forms are
531        // read: the other constraints stay as soft as the missing
532        // required sections above, so a resolution stays possible.
533        {
534            let def: &memstead_schema::TypeDefinition = resolved_type.as_ref();
535            let check_provider = self.check_standing_provider();
536            entity.content_hash = parser::compute_hash(&resolved);
537            let transition_forms: Vec<_> = crate::ops::health::unsatisfied_constraints(
538                &self.store,
539                &entity,
540                def,
541                Some(&entity.id),
542                Some(&check_provider),
543            )
544            .into_iter()
545            .filter(|v| {
546                matches!(
547                    v,
548                    crate::ops::health::UnsatisfiedConstraint::TransitionRequiresChecks { .. }
549                )
550            })
551            .collect();
552            let content_hash = entity.content_hash.clone();
553            let (violated, _) =
554                self.gate_transition_forms(None, &entity, &content_hash, def, transition_forms);
555            let blocked: Vec<_> = violated
556                .into_iter()
557                .filter(|v| v.severity() == memstead_schema::ConstraintSeverity::Block)
558                .collect();
559            if !blocked.is_empty() {
560                return Err(EngineError::ConstraintUnsatisfied {
561                    entity_type: entity.entity_type.clone(),
562                    entity_id: entity.id.to_string(),
563                    violations: blocked,
564                });
565            }
566        }
567
568        let backend = self.mounts[mount_idx].backend.as_ref();
569        backend.write_entity(Path::new(&entry.relative_path), resolved.as_bytes())?;
570        let ctx = self.commit_context(
571            Some("resolve_conflict"),
572            actor,
573            client.cloned(),
574            note.map(String::from),
575        );
576        // The record lands with the commit, through the one commit call.
577        let record = Provenance::new(
578            std::time::SystemTime::now(),
579            ProvenanceKind::Update,
580            Some(id.to_string()),
581            actor,
582            client.cloned(),
583            note.map(String::from),
584        )
585        .with_role(self.current_role)
586        .with_identity(self.current_identity.clone());
587        let landed = self.commit_staged(
588            mount_idx,
589            &format!("memstead: resolve-conflict {id} (side: {})", side.as_wire()),
590            &ctx,
591            std::slice::from_ref(&record),
592        )?;
593        let write_id = landed.write_id;
594        warnings.extend(landed.warnings);
595        self.record_self_write(mount_idx, &write_id);
596        warnings.extend(self.stamp_mutation_versions(mount_idx));
597
598        // Reload so the resolved entity enters the store and the
599        // conflict load-error clears — the caller's next read sees a
600        // clean mem, not a stale refusal.
601        self.reload_each_writable_mem()?;
602
603        Ok(ResolveConflictOutcome {
604            warnings,
605            id: id.clone(),
606            side: side.as_wire(),
607            write_id,
608        })
609    }
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615
616    const CONFLICTED: &str = "---\ntype: spec\n---\n# Torn\n\n## Identity\n\n\
617<<<<<<< HEAD\nours line\n||||||| base\nbase line\n=======\ntheirs line\n\
618>>>>>>> feature\n\n## Purpose\n\nshared tail\n";
619
620    /// Build a booted folder workspace with one mem (`specs`) whose
621    /// files are exactly `files`. Returns `(tempdir, engine)`.
622    fn folder_workspace(files: &[(&str, &str)]) -> (tempfile::TempDir, Engine) {
623        use crate::workspace::{Mount, MountLifecycle};
624        use crate::workspace_store::WorkspaceStoreAdapter;
625
626        let tmp = tempfile::TempDir::new().unwrap();
627        let mem_dir = tmp.path().join("specs");
628        std::fs::create_dir_all(&mem_dir).unwrap();
629        for (name, content) in files {
630            std::fs::write(mem_dir.join(name), content).unwrap();
631        }
632        let memstead = tmp.path().join(".memstead");
633        std::fs::create_dir_all(&memstead).unwrap();
634        std::fs::write(
635            memstead.join("workspace.toml"),
636            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
637        )
638        .unwrap();
639        let mount = Mount {
640            mem: "specs".to_string(),
641            schema: Some(memstead_schema::SchemaRef::new(
642                "default",
643                semver::Version::new(1, 0, 0),
644            )),
645            storage: MountStorage::Folder { path: mem_dir },
646            capability: MountCapability::Write,
647            lifecycle: MountLifecycle::Eager,
648            cross_linkable: true,
649            migration_target: None,
650        };
651        crate::FileWorkspaceStore::new()
652            .save_state(
653                tmp.path(),
654                &crate::workspace::Workspace {
655                    mounts: vec![mount],
656                    settings: crate::workspace::WorkspaceSettings::default(),
657                },
658            )
659            .unwrap();
660        let engine = Engine::from_workspace_root(tmp.path()).expect("workspace boots");
661        (tmp, engine)
662    }
663
664    const CLEAN: &str = "---\ntype: spec\n---\n# Fine\n\n## Identity\n\nis\n\n## Purpose\n\nok\n";
665
666    /// On a live folder workspace: the load
667    /// refusal names the resolve remedy, the conflicted entity lists,
668    /// resolving to theirs makes the mem load clean with the entity
669    /// valid, and the resolution lands in the provenance ledger with
670    /// its note. Complements: resolving the already-clean entity
671    /// refuses `NOT_CONFLICTED`; a missing id refuses not-found.
672    #[test]
673    fn conflicted_folder_entity_lists_resolves_and_reads_clean() {
674        let (tmp, mut engine) = folder_workspace(&[("torn.md", CONFLICTED), ("fine.md", CLEAN)]);
675
676        // The parse failure an agent hits names the remedy.
677        let errors = engine.load_errors();
678        assert_eq!(errors.len(), 1, "exactly the conflicted file refuses");
679        assert!(
680            errors[0].1.contains("memstead conflicts resolve"),
681            "load error names the resolve operation: {}",
682            errors[0].1
683        );
684
685        // The conflicted entity is identified; the clean one is not.
686        let listed = engine.list_merge_conflicts(None).unwrap();
687        assert_eq!(listed.len(), 1);
688        assert_eq!(listed[0].id.as_ref(), "specs--torn");
689        assert_eq!(listed[0].file_path, "torn.md");
690
691        // Resolve to theirs.
692        let id = EntityId("specs--torn".into());
693        let outcome = engine
694            .resolve_merge_conflict(
695                &id,
696                ConflictSide::Theirs,
697                Actor::Cli,
698                None,
699                Some("keeping upstream wording"),
700            )
701            .expect("resolution succeeds");
702        assert_eq!(outcome.side, "theirs");
703
704        // The mem loads clean and the entity reads validly.
705        assert!(
706            engine.load_errors().is_empty(),
707            "{:?}",
708            engine.load_errors()
709        );
710        let entity = engine.get_entity(&id).expect("resolved entity is loaded");
711        assert!(!entity.stub);
712        assert!(
713            entity
714                .sections
715                .get("identity")
716                .unwrap()
717                .contains("theirs line"),
718            "the kept side's content is live: {:?}",
719            entity.sections.get("identity")
720        );
721        let on_disk = std::fs::read_to_string(tmp.path().join("specs").join("torn.md")).unwrap();
722        assert!(!on_disk.contains("<<<<<<<") && !on_disk.contains("ours line"));
723
724        // Provenance: the resolution is an attributed ledger entry
725        // carrying the note — never an untracked file swap.
726        let ledger = std::fs::read_to_string(
727            tmp.path()
728                .join("specs")
729                .join(".memstead")
730                .join("changes.jsonl"),
731        )
732        .expect("folder provenance ledger exists");
733        assert!(
734            ledger.contains("specs--torn") && ledger.contains("keeping upstream wording"),
735            "ledger records the resolution with its note: {ledger}"
736        );
737
738        // Complements: already-clean refuses NOT_CONFLICTED; unknown
739        // id refuses not-found.
740        let err = engine
741            .resolve_merge_conflict(&id, ConflictSide::Ours, Actor::Cli, None, None)
742            .unwrap_err();
743        assert_eq!(err.code(), "NOT_CONFLICTED");
744        let err = engine
745            .resolve_merge_conflict(
746                &EntityId("specs--absent".into()),
747                ConflictSide::Ours,
748                Actor::Cli,
749                None,
750                None,
751            )
752            .unwrap_err();
753        assert_eq!(err.code(), "ENTITY_NOT_FOUND");
754    }
755
756    /// Complement: a fenced code example DOCUMENTING conflict markers
757    /// is legal content — it loads without a conflict refusal and does
758    /// not list as conflicted (the detector evaluates masked content).
759    #[test]
760    fn fenced_marker_example_is_not_a_conflict() {
761        let doc = "---\ntype: spec\n---\n# Git Lore\n\n## Identity\n\n\
762```text\n<<<<<<< HEAD\nexample\n=======\nexample\n>>>>>>> branch\n```\n\n\
763## Purpose\n\nteaching\n";
764        let (_tmp, engine) = folder_workspace(&[("lore.md", doc)]);
765        assert!(
766            engine.load_errors().is_empty(),
767            "{:?}",
768            engine.load_errors()
769        );
770        assert!(engine.list_merge_conflicts(None).unwrap().is_empty());
771        assert!(engine.get_entity(&EntityId("specs--lore".into())).is_some());
772    }
773
774    /// A chosen side that fails entity validation
775    /// refuses with the validation error and writes nothing. The
776    /// fixture is a nested conflict (recursive-merge shape): the
777    /// theirs side still carries marker residue after extraction, so
778    /// writing it would put the mem right back into the unloadable
779    /// state — resolution refuses; the clean ours side resolves.
780    #[test]
781    fn invalid_chosen_side_refuses_and_writes_nothing() {
782        let nested = "---\ntype: spec\n---\n# Nested\n\n## Identity\n\n\
783<<<<<<< HEAD\nours\n=======\n<<<<<<< inner\ntheirs-a\n=======\ntheirs-b\n\
784>>>>>>> inner\n>>>>>>> outer\n\n## Purpose\n\np\n";
785        let (tmp, mut engine) = folder_workspace(&[("nested.md", nested)]);
786
787        let id = EntityId("specs--nested".into());
788        let err = engine
789            .resolve_merge_conflict(&id, ConflictSide::Theirs, Actor::Cli, None, None)
790            .unwrap_err();
791        assert_eq!(err.code(), "INVALID_INPUT", "got: {err}");
792        assert!(
793            err.to_string().contains("still carries conflict markers"),
794            "refusal names the residue: {err}"
795        );
796        // Nothing was written: the original markers are still on disk.
797        let on_disk = std::fs::read_to_string(tmp.path().join("specs").join("nested.md")).unwrap();
798        assert!(
799            on_disk.contains("<<<<<<< HEAD"),
800            "file untouched on refusal"
801        );
802
803        // The ours side is clean and resolves fine.
804        engine
805            .resolve_merge_conflict(&id, ConflictSide::Ours, Actor::Cli, None, None)
806            .expect("clean side resolves");
807        assert!(engine.load_errors().is_empty());
808    }
809
810    /// A folder workspace mounting one mem on a fixture schema: types
811    /// `thing` and `other`; `LINKS` joins a `thing` to an `other` only;
812    /// body wiki-links are `REFERENCES` rows, and `REFERENCES` is acyclic.
813    fn edge_fixture(files: &[(&str, &str)]) -> (tempfile::TempDir, Engine) {
814        let (tmp, engine) = folder_workspace(files);
815        drop(engine);
816        let dir = tmp
817            .path()
818            .join(".memstead")
819            .join("schemas")
820            .join("cx@0.1.0");
821        std::fs::create_dir_all(dir.join("types")).unwrap();
822        std::fs::write(
823            dir.join("schema.yaml"),
824            "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",
825        )
826        .unwrap();
827        for ty in ["thing", "other"] {
828            std::fs::write(
829                dir.join("types").join(format!("{ty}.yaml")),
830                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"),
831            )
832            .unwrap();
833        }
834        {
835            use crate::workspace_store::WorkspaceStoreAdapter;
836            let mount = crate::workspace::Mount {
837                mem: "specs".to_string(),
838                schema: Some(memstead_schema::SchemaRef::new(
839                    "cx",
840                    semver::Version::new(0, 1, 0),
841                )),
842                storage: MountStorage::Folder {
843                    path: tmp.path().join("specs"),
844                },
845                capability: MountCapability::Write,
846                lifecycle: crate::workspace::MountLifecycle::Eager,
847                cross_linkable: true,
848                migration_target: None,
849            };
850            crate::FileWorkspaceStore::new()
851                .save_state(
852                    tmp.path(),
853                    &crate::workspace::Workspace {
854                        mounts: vec![mount],
855                        settings: crate::workspace::WorkspaceSettings::default(),
856                    },
857                )
858                .unwrap();
859        }
860        let engine = Engine::from_workspace_root(tmp.path()).expect("workspace boots");
861        (tmp, engine)
862    }
863
864    fn conflicted(ty: &str, title: &str, theirs: &str) -> String {
865        format!(
866            "---\ntype: {ty}\n---\n# {title}\n\n## Body\n\n<<<<<<< HEAD\nkept as it was\n=======\n{theirs}\n>>>>>>> theirs\n"
867        )
868    }
869
870    /// The chosen side's rows pass the declared-edge checks: an
871    /// undeclared relationship type, an endpoint the schema forbids and
872    /// a body link closing a cycle on an acyclic relationship each
873    /// refuse with the code the declared write raises, the file stays in
874    /// conflict, and the other side resolves.
875    #[test]
876    fn a_resolution_lands_only_rows_a_declared_write_could_land() {
877        let target = "---\ntype: other\n---\n# Target\n\n## Body\n\nsee [[specs--loop]]\n\n## Relationships\n\n- **REFERENCES**: [[specs--loop]]\n";
878        let peer = "---\ntype: thing\n---\n# Peer\n\n## Body\n\nplain\n";
879        let cases = [
880            (
881                "thing",
882                "Undeclared",
883                "a\n\n## Relationships\n\n- **BOGUS**: [[specs--target]]".to_string(),
884                "INVALID_REL_TYPE",
885            ),
886            (
887                "thing",
888                "Shape",
889                "a\n\n## Relationships\n\n- **LINKS**: [[specs--peer]]".to_string(),
890                "INVALID_REL_SHAPE",
891            ),
892            (
893                "thing",
894                "Loop",
895                "closes the loop: [[specs--target]]".to_string(),
896                "RELATIONSHIP_CYCLE",
897            ),
898        ];
899        for (ty, title, theirs, code) in cases {
900            let slug = title.to_lowercase();
901            let file = format!("{slug}.md");
902            let body = conflicted(ty, title, &theirs);
903            let (tmp, mut engine) =
904                edge_fixture(&[("target.md", target), ("peer.md", peer), (&file, &body)]);
905            let id = EntityId(format!("specs--{slug}"));
906            let err = engine
907                .resolve_merge_conflict(&id, ConflictSide::Theirs, Actor::Cli, None, None)
908                .unwrap_err();
909            assert_eq!(err.code(), code, "{title}: {err}");
910            let on_disk = std::fs::read_to_string(tmp.path().join("specs").join(&file)).unwrap();
911            assert!(
912                on_disk.contains("<<<<<<< HEAD"),
913                "{title}: still in conflict"
914            );
915            engine
916                .resolve_merge_conflict(&id, ConflictSide::Ours, Actor::Cli, None, None)
917                .unwrap_or_else(|e| panic!("{title}: ours resolves: {e}"));
918        }
919    }
920
921    #[test]
922    fn extract_sides_and_diff3_base_drops() {
923        let ours = extract_conflict_side(CONFLICTED, ConflictSide::Ours).unwrap();
924        assert!(ours.contains("ours line"));
925        assert!(!ours.contains("theirs line") && !ours.contains("base line"));
926        assert!(ours.contains("shared tail"));
927        let theirs = extract_conflict_side(CONFLICTED, ConflictSide::Theirs).unwrap();
928        assert!(theirs.contains("theirs line"));
929        assert!(!theirs.contains("ours line") && !theirs.contains("base line"));
930        assert!(!theirs.contains("<<<<<<<") && !theirs.contains(">>>>>>>"));
931    }
932
933    #[test]
934    fn malformed_markers_refuse() {
935        let unterminated = "a\n<<<<<<< HEAD\nours\n=======\ntheirs\n";
936        assert!(extract_conflict_side(unterminated, ConflictSide::Ours).is_err());
937        let inverted = "a\n<<<<<<< HEAD\nours\n>>>>>>> feature\n";
938        assert!(extract_conflict_side(inverted, ConflictSide::Ours).is_err());
939    }
940
941    /// A file after a rebase whose only conflict is the two stamped
942    /// `last_modified` lines, with both sides' body additions merged by
943    /// git: `merged` keeps git's file and the later stamp, and the entity
944    /// validates.
945    const STAMP_ONLY: &str = "---\ntype: spec\ncreated_date: 2026-01-01\n\
946<<<<<<< HEAD\nlast_modified: 2026-03-02T10:00:00Z\n=======\nlast_modified: 2026-03-04T09:00:00Z\n\
947>>>>>>> feature\n---\n# Torn\n\n## Identity\n\nidentity body\nours addition\n\n\
948## Purpose\n\npurpose body\ntheirs addition\n";
949
950    #[test]
951    fn a_timestamp_only_conflict_resolves_merged_with_both_additions_and_the_later_stamp() {
952        let (tmp, mut engine) = folder_workspace(&[("torn.md", STAMP_ONLY)]);
953        let id = EntityId::new("specs", "torn");
954        let outcome = engine
955            .resolve_merge_conflict(&id, ConflictSide::Merged, Actor::Cli, None, Some("stamp"))
956            .expect("a stamp-only conflict resolves merged");
957        assert_eq!(outcome.side, "merged");
958        let written = std::fs::read_to_string(tmp.path().join("specs/torn.md")).unwrap();
959        assert!(!parser::has_merge_conflict_markers(&written), "{written}");
960        assert!(written.contains("ours addition"), "{written}");
961        assert!(written.contains("theirs addition"), "{written}");
962        assert!(
963            written.contains("last_modified: 2026-03-04T09:00:00Z"),
964            "{written}"
965        );
966        assert!(!written.contains("2026-03-02T10:00:00Z"), "{written}");
967        let entity = engine.get_entity(&id).expect("the entity loads");
968        assert!(!entity.stub);
969    }
970
971    /// A conflict block on anything but `last_modified` refuses
972    /// `CONFLICT_NOT_TIMESTAMP_ONLY` naming its key or section, and the
973    /// file stays in conflict.
974    #[test]
975    fn a_conflict_beyond_the_timestamp_refuses_merged_naming_where() {
976        let body = "---\ntype: spec\nlast_modified: 2026-03-02T10:00:00Z\n---\n# Torn\n\n\
977## Identity\n\n<<<<<<< HEAD\nours line\n=======\ntheirs line\n>>>>>>> feature\n\n\
978## Purpose\n\ntail\n";
979        let created = "---\ntype: spec\n<<<<<<< HEAD\ncreated_date: 2026-01-01\n=======\n\
980created_date: 2026-01-02\n>>>>>>> feature\nlast_modified: 2026-03-02T10:00:00Z\n---\n# Torn\n\n\
981## Identity\n\nx\n";
982        let stamp_and_more = "---\ntype: spec\n<<<<<<< HEAD\nlast_modified: 2026-03-02T10:00:00Z\n\
983level: M0\n=======\nlast_modified: 2026-03-04T09:00:00Z\nlevel: M1\n>>>>>>> feature\n---\n\
984# Torn\n\n## Identity\n\nx\n";
985        for (content, key, section) in [
986            (body, None, Some("Identity")),
987            (created, Some("created_date"), None),
988            (stamp_and_more, Some("level"), None),
989        ] {
990            let (tmp, mut engine) = folder_workspace(&[("torn.md", content)]);
991            let id = EntityId::new("specs", "torn");
992            let err = engine
993                .resolve_merge_conflict(&id, ConflictSide::Merged, Actor::Cli, None, None)
994                .expect_err("not a stamp-only conflict");
995            assert_eq!(err.code(), "CONFLICT_NOT_TIMESTAMP_ONLY", "{err}");
996            let d = err.details();
997            assert_eq!(d["key"].as_str(), key, "{d}");
998            assert_eq!(d["section"].as_str(), section, "{d}");
999            let still = std::fs::read_to_string(tmp.path().join("specs/torn.md")).unwrap();
1000            assert_eq!(still, content, "the file stays in conflict");
1001        }
1002    }
1003}