memstead-base 0.10.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, 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
//! Merge-conflict resolution for folder mems (backlog-sweep plan 07,
//! decision 20).
//!
//! 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. A merged-content resolution is out of scope by
//! design — an agent wanting a merge resolves to one side as the base
//! and then edits 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 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, CommitContext};
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,
}

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),
            _ => None,
        }
    }

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

/// 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 commit_sha: String,
}

/// 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)
}

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), recorded in the
    /// provenance ledger, and the mem is reloaded so the entity reads
    /// validly and the conflict load-error clears.
    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();
        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(EngineError::NotFound { id: id.to_string() });
        };
        if !parser::has_merge_conflict_markers(&entry.content) {
            return Err(EngineError::NotConflicted { id: id.to_string() });
        }

        let resolved = extract_conflict_side(&entry.content, side).map_err(|m| {
            EngineError::InvalidInput(format!(
                "malformed conflict markers in {}: {m}",
                entry.relative_path
            ))
        })?;

        // 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(),
        )?;
        crate::runtime_validator::validate_section_content(
            parsed
                .entity
                .sections
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str())),
        )?;

        let backend = self.mounts[mount_idx].backend.as_ref();
        backend.write_entity(Path::new(&entry.relative_path), resolved.as_bytes())?;
        let ctx = CommitContext {
            actor,
            client: client.cloned(),
            tool: Some("resolve_conflict"),
            note: note.map(String::from),
            role: self.current_role,
            logical_operation_id: None,
            entity_ids: None,
        };
        let commit_sha = backend.commit(
            &format!("memstead: resolve-conflict {id} (side: {})", side.as_wire()),
            &ctx,
        )?;
        backend.append_provenance(
            &Provenance::new(
                std::time::SystemTime::now(),
                ProvenanceKind::Update,
                Some(id.to_string()),
                actor,
                client.cloned(),
                note.map(String::from),
            )
            .with_role(self.current_role),
        )?;
        self.record_self_write(mount_idx, &commit_sha);
        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 {
            id: id.clone(),
            side: side.as_wire(),
            commit_sha,
        })
    }
}

#[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";

    /// Plan 07 criteria 1/3/4 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());
    }

    /// Plan 07 criterion 2: 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());
    }

    #[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());
    }
}