Skip to main content

memstead_base/engine/
review.rs

1//! Review marks — one per-mem pointer to the last human-approved
2//! state (the operator's review model: diffs accumulate against it,
3//! approving moves it, ignoring it entirely is first-class).
4//!
5//! The mark's value vocabulary is deliberately the existing
6//! backend-opaque `changes_since` cursor (git-branch: commit SHA;
7//! folder: changelog RFC3339-millis timestamp) — no second
8//! state-naming scheme. Storage is mem-repo state via
9//! `MemConfig.review_mark` (the `sync_state` precedent): it rides
10//! reloads, survives cache wipes, is visible to every sibling process
11//! opening the workspace, and is stripped from published archives by
12//! the `PublishedMemConfig` allowlist.
13//!
14//! Marks never gate: no mutation path consults them. `set` takes an
15//! explicit target only — never an implicit "now", because writers may
16//! have advanced the mem mid-review.
17
18use serde::Serialize;
19
20use super::{Engine, EngineError};
21
22/// One mem's review-mark status, alongside its current head so a
23/// single list call answers "what has un-reviewed changes".
24#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
25pub struct ReviewMarkStatus {
26    pub mem: String,
27    /// The last human-approved state; `None` is the ordinary markless
28    /// state.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub mark: Option<String>,
31    /// Current head cursor (`None` for backends without one).
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub head: Option<String>,
34    /// Whether the mem is writable (marks on read-only mounts are
35    /// visible but not settable).
36    pub writable: bool,
37}
38
39/// Successful outcome of [`Engine::set_review_mark`].
40#[derive(Debug, Clone, Serialize)]
41pub struct SetReviewMarkOutcome {
42    pub mem: String,
43    /// The mark after this call (`None` = cleared).
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub mark: Option<String>,
46    /// The mark before this call.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub previous: Option<String>,
49    /// Typed non-fatal issues (NOTE_MISSING under require-notes,
50    /// MEM_RELOADED from the pre-write drift probe).
51    pub warnings: Vec<crate::ops::WarningHint>,
52}
53
54impl Engine {
55    /// Every mem's review mark (or its absence) with the current head.
56    /// Markless mems are ordinary entries, never errors.
57    pub fn review_marks(&self) -> Vec<ReviewMarkStatus> {
58        self.mounts
59            .iter()
60            .map(|m| ReviewMarkStatus {
61                mem: m.mount.mem.clone(),
62                mark: m.mem_config.as_ref().and_then(|c| c.review_mark.clone()),
63                head: m.backend.current_head().ok().flatten(),
64                writable: m.mount.capability == crate::workspace::MountCapability::Write,
65            })
66            .collect()
67    }
68
69    /// Set (or clear, with `target: None`) a mem's review mark to an
70    /// explicitly named state. The target is validated against the
71    /// backend's cursor vocabulary before anything is written —
72    /// git-branch cursors must resolve to a known commit, folder
73    /// cursors must parse as the changelog's RFC3339 timestamp shape —
74    /// and an invalid target refuses with `INVALID_CURSOR`, leaving
75    /// the mark untouched. Provenance (note gating, warn-and-commit)
76    /// mirrors `set_mem_sync_state`; the config write commits with
77    /// the caller's note.
78    pub fn set_review_mark(
79        &mut self,
80        mem_name: &str,
81        target: Option<&str>,
82        note: Option<&str>,
83    ) -> Result<SetReviewMarkOutcome, EngineError> {
84        let mount_idx = self
85            .mounts
86            .iter()
87            .position(|m| m.mount.mem == mem_name)
88            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
89        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
90            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
91        }
92
93        // Validate the explicit target against the backend's cursor
94        // vocabulary BEFORE any write. Clearing needs no validation.
95        if let Some(target) = target {
96            self.validate_review_cursor(mount_idx, mem_name, target)?;
97        }
98
99        // Same posture as every other commit-producing mutation.
100        let (_write_lock, mut warnings) = self.lock_for_write(true, &[mem_name])?;
101        warnings.extend(self.reload_if_stale_content_only(Some(mem_name)));
102        let mount_idx = self.writable_mount_index(mem_name)?;
103        if let Some(w) = self.note_missing_warning("set_review_mark", note) {
104            warnings.push(w);
105        }
106
107        // `previous` comes from the config this write lands on, not the
108        // cache: a sibling reviewer may have moved the mark since boot, and
109        // reporting the cached value would name a mark nobody is at.
110        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
111        let target_owned = target.map(str::to_string);
112        let (_, intervened) = self.write_mem_config_merged(
113            mount_idx,
114            mem_name,
115            "set_review_mark",
116            note,
117            &|c: &mut memstead_schema::config::MemConfig| {
118                *seen.borrow_mut() = c.review_mark.clone();
119                c.review_mark = target_owned.clone();
120            },
121        )?;
122        let previous = seen.into_inner();
123        if !intervened.is_empty() {
124            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
125                mem: mem_name.to_string(),
126                fields: intervened,
127            });
128        }
129
130        Ok(SetReviewMarkOutcome {
131            mem: mem_name.to_string(),
132            mark: target.map(str::to_string),
133            previous,
134            warnings,
135        })
136    }
137
138    /// The accumulated per-entity delta from the mem's review mark to
139    /// its current head — exactly the envelopes `changes_since`
140    /// reports for the mark's cursor. A markless mem refuses with
141    /// `REVIEW_MARK_NOT_SET` (marklessness is known from the roster; a
142    /// silent empty answer would equate "no mark" with "no changes").
143    pub fn review_mark_diff(
144        &self,
145        mem_name: &str,
146        rename_similarity: Option<f32>,
147    ) -> Result<crate::ops::ChangesReport, EngineError> {
148        let mount = self
149            .mounts
150            .iter()
151            .find(|m| m.mount.mem == mem_name)
152            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
153        let mark = mount
154            .mem_config
155            .as_ref()
156            .and_then(|c| c.review_mark.clone())
157            .ok_or_else(|| EngineError::ReviewMarkNotSet {
158                mem: mem_name.to_string(),
159            })?;
160        self.changes_since(mem_name, &mark, rename_similarity)
161    }
162
163    /// Backend-vocabulary validation for an explicit mark target.
164    fn validate_review_cursor(
165        &self,
166        mount_idx: usize,
167        mem_name: &str,
168        target: &str,
169    ) -> Result<(), EngineError> {
170        use crate::workspace::MountStorage;
171        let invalid = || EngineError::InvalidChangesCursor {
172            mem: mem_name.to_string(),
173            since: target.to_string(),
174        };
175        match &self.mounts[mount_idx].mount.storage {
176            MountStorage::Folder { .. } => {
177                // Folder cursors are the changelog's RFC3339-millis
178                // timestamps; format-level validation (existence is not
179                // required — any parseable instant is a legal `since`).
180                if crate::filesystem::changelog::parse_rfc3339_utc(target).is_none() {
181                    return Err(invalid());
182                }
183                Ok(())
184            }
185            MountStorage::GitBranch { .. } => {
186                // A git-branch cursor must resolve to a known commit —
187                // `changes_since` is the authoritative resolver and
188                // already refuses unknown SHAs with INVALID_CURSOR.
189                self.changes_since(mem_name, target, None).map(|_| ())
190            }
191            MountStorage::Archive { .. } | MountStorage::InMemory => {
192                // Unreachable through set (capability gate refuses
193                // first); refuse defensively for direct callers.
194                Err(invalid())
195            }
196        }
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use crate::backend::MemBackend;
203
204    const SEED: &str = "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Seed\n\n## Identity\n\nSeed.\n";
205
206    fn folder_engine(tmp: &tempfile::TempDir) -> crate::Engine {
207        let dir = tmp.path().join("specs");
208        if !dir.exists() {
209            std::fs::create_dir_all(&dir).unwrap();
210            let writer = crate::storage::FilesystemBackend::new(dir.clone());
211            MemBackend::write_entity(&writer, std::path::Path::new("seed.md"), SEED.as_bytes())
212                .unwrap();
213            MemBackend::commit(&writer, "seed", &crate::vcs::CommitContext::internal()).unwrap();
214            crate::backend::MemBackend::append_provenance(
215                &writer,
216                &crate::provenance::Provenance::new(
217                    std::time::SystemTime::now(),
218                    crate::provenance::ProvenanceKind::Create,
219                    Some("specs--seed".into()),
220                    crate::vcs::Actor::Cli,
221                    None,
222                    None,
223                ),
224            )
225            .unwrap();
226            // A config file so set_review_mark has a MemConfig to carry
227            // the mark (mirrors an initialized mem).
228            let config = memstead_schema::config::MemConfig {
229                format: None,
230                name: None,
231                title: None,
232                subject: None,
233                version: None,
234                description: None,
235                authors: None,
236                schema: Some("default@1.0.0".parse().unwrap()),
237                write_guidance: Default::default(),
238                process_mem: None,
239                rules: None,
240                publish: None,
241                language: None,
242                read_mems: Default::default(),
243                community: None,
244                vcs: None,
245                unregistered_at: None,
246                renaming_from: None,
247                sync_state: Default::default(),
248                review_mark: None,
249                mutation_stamp: None,
250                forked_from: None,
251                extra: Default::default(),
252            };
253            let meta = dir.join(memstead_schema::MEM_META_DIR);
254            std::fs::create_dir_all(&meta).unwrap();
255            std::fs::write(
256                meta.join("config.json"),
257                serde_json::to_vec_pretty(&config).unwrap(),
258            )
259            .unwrap();
260        }
261        let mount = crate::Mount {
262            mem: "specs".to_string(),
263            schema: Some(memstead_schema::SchemaRef::new(
264                "default",
265                semver::Version::new(1, 0, 0),
266            )),
267            storage: crate::MountStorage::Folder { path: dir.clone() },
268            capability: crate::MountCapability::Write,
269            lifecycle: crate::MountLifecycle::Eager,
270            cross_linkable: false,
271            migration_target: None,
272        };
273        let backend =
274            Box::new(crate::storage::FilesystemBackend::new(dir)) as Box<dyn crate::MemBackend>;
275        crate::Engine::from_mounts(vec![(mount, backend)]).unwrap()
276    }
277
278    fn head(engine: &crate::Engine) -> String {
279        engine
280            .review_marks()
281            .into_iter()
282            .find(|s| s.mem == "specs")
283            .and_then(|s| s.head)
284            .expect("folder head cursor")
285    }
286
287    #[test]
288    fn mark_lifecycle_persists_validates_and_never_gates() {
289        let tmp = tempfile::TempDir::new().unwrap();
290        let mut engine = folder_engine(&tmp);
291
292        // Markless start: ordinary state, listed as such.
293        let status = &engine.review_marks()[0];
294        assert_eq!(status.mem, "specs");
295        assert!(status.mark.is_none());
296        assert!(status.writable);
297
298        // Invalid cursor refuses typed, mark untouched.
299        let err = engine
300            .set_review_mark("specs", Some("not-a-timestamp"), None)
301            .unwrap_err();
302        assert_eq!(err.code(), "INVALID_CURSOR");
303        assert!(engine.review_marks()[0].mark.is_none());
304        // Unknown mem refuses typed.
305        let err = engine.set_review_mark("ghost", None, None).unwrap_err();
306        assert_eq!(err.code(), "UNKNOWN_MEM");
307
308        // Markless diff refuses typed — never a silent empty answer.
309        let err = engine.review_mark_diff("specs", None).unwrap_err();
310        assert_eq!(err.code(), "REVIEW_MARK_NOT_SET");
311
312        // Set to the reviewed head; diff-since is now empty.
313        let reviewed = head(&engine);
314        let outcome = engine
315            .set_review_mark("specs", Some(&reviewed), Some("reviewed everything"))
316            .unwrap();
317        assert_eq!(outcome.mark.as_deref(), Some(reviewed.as_str()));
318        assert!(outcome.previous.is_none());
319        let diff = engine.review_mark_diff("specs", None).unwrap();
320        assert!(diff.changes.is_empty(), "reviewed head → empty: {diff:?}");
321
322        // A mutation past the mark succeeds with no mark-related
323        // warning (marks never gate) — and diff-since accumulates it,
324        // matching changes_since for the mark's cursor.
325        let outcome = engine
326            .create_entity(
327                crate::CreateEntityArgs {
328                    mem: "specs".to_string(),
329                    title: "Past The Mark".to_string(),
330                    entity_type: "spec".to_string(),
331                    sections: [
332                        ("identity".to_string(), "x".to_string()),
333                        ("purpose".to_string(), "y".to_string()),
334                    ]
335                    .into_iter()
336                    .collect(),
337                    metadata: Default::default(),
338                    relations: Vec::new(),
339                    anchors: Vec::new(),
340                    dry_run: false,
341                },
342                crate::vcs::Actor::App,
343                None,
344                Some("agent work"),
345            )
346            .unwrap();
347        assert!(
348            outcome
349                .warnings
350                .iter()
351                .all(|w| !format!("{w:?}").to_lowercase().contains("mark")),
352            "marks never gate or warn: {:?}",
353            outcome.warnings
354        );
355        let diff = engine.review_mark_diff("specs", None).unwrap();
356        assert_eq!(diff.changes.len(), 1, "{diff:?}");
357        let direct = engine.changes_since("specs", &reviewed, None).unwrap();
358        assert_eq!(
359            serde_json::to_value(&diff.changes).unwrap(),
360            serde_json::to_value(&direct.changes).unwrap(),
361            "diff-since must equal changes_since at the mark"
362        );
363
364        // Persistence across engine restarts (separate instance, same
365        // workspace) — the sibling-visibility half.
366        drop(engine);
367        let mut second = folder_engine(&tmp);
368        assert_eq!(
369            second.review_marks()[0].mark.as_deref(),
370            Some(reviewed.as_str()),
371            "the mark is mem-repo state"
372        );
373
374        // Clear returns to markless.
375        let outcome = second.set_review_mark("specs", None, None).unwrap();
376        assert_eq!(outcome.previous.as_deref(), Some(reviewed.as_str()));
377        assert!(second.review_marks()[0].mark.is_none());
378    }
379
380    #[test]
381    fn noteless_set_under_require_notes_warns_and_commits() {
382        let tmp = tempfile::TempDir::new().unwrap();
383        let mut engine = folder_engine(&tmp);
384        engine.set_settings(crate::WorkspaceSettings {
385            mutations: crate::workspace::MutationsSection {
386                require_notes: Some(true),
387            },
388            ..Default::default()
389        });
390        let reviewed = head(&engine);
391        let outcome = engine
392            .set_review_mark("specs", Some(&reviewed), None)
393            .unwrap();
394        assert!(
395            outcome.warnings.iter().any(
396                |w| matches!(w, crate::ops::WarningHint::NoteMissing { tool } if tool == "set_review_mark")
397            ),
398            "warn-and-commit: {:?}",
399            outcome.warnings
400        );
401        assert_eq!(outcome.mark.as_deref(), Some(reviewed.as_str()));
402    }
403
404    #[test]
405    fn published_projection_strips_the_mark() {
406        // The PublishedMemConfig allowlist strips everything it does
407        // not name — pin that the mark stays out (the
408        // structural half; the export round-trip rides the exporter's
409        // own tests).
410        let mut config = memstead_schema::config::MemConfig {
411            format: None,
412            name: None,
413            title: None,
414            subject: None,
415            version: Some(semver::Version::new(1, 0, 0)),
416            description: None,
417            authors: None,
418            schema: Some("default@1.0.0".parse().unwrap()),
419            write_guidance: Default::default(),
420            process_mem: None,
421            rules: None,
422            publish: None,
423            language: None,
424            read_mems: Default::default(),
425            community: None,
426            vcs: None,
427            unregistered_at: None,
428            renaming_from: None,
429            sync_state: Default::default(),
430            review_mark: None,
431            mutation_stamp: None,
432            forked_from: None,
433            extra: Default::default(),
434        };
435        config.review_mark = Some("deadbeef".to_string());
436        let published = memstead_schema::config::published_config_from(&config, "specs").unwrap();
437        let json = serde_json::to_string(&published).unwrap();
438        assert!(
439            !json.contains("reviewMark") && !json.contains("deadbeef"),
440            "published config must strip the mark: {json}"
441        );
442    }
443
444    #[test]
445    fn overview_roster_carries_the_mark_and_its_indicator() {
446        // The agents' cold-start read (overview `## Mems`) is a
447        // per-mem summary surface: a set mark rides it with the
448        // mark≠head indicator, a markless mem stays unmarked (ordinary
449        // state, never flagged).
450        let tmp = tempfile::TempDir::new().unwrap();
451        let mut engine = folder_engine(&tmp);
452        let overview_md = |engine: &mut crate::Engine| {
453            crate::overview::compose_overview(
454                engine,
455                crate::overview::OverviewArgs {
456                    include: &[],
457                    mem: None,
458                    rebuild: false,
459                    token_budget: 8000,
460                    operator_mode: false,
461                    suppress_lifecycle: false,
462                },
463                crate::overview::Surface::Mcp,
464            )
465            .unwrap()
466            .markdown
467        };
468
469        // Markless: no mark line anywhere.
470        let md = overview_md(&mut engine);
471        assert!(
472            !md.contains("Review mark"),
473            "markless roster must not mention marks: {md}"
474        );
475
476        // Mark at head: the line appears, indicator says at-mark.
477        let reviewed = head(&engine);
478        engine
479            .set_review_mark("specs", Some(&reviewed), Some("reviewed"))
480            .unwrap();
481        let md = overview_md(&mut engine);
482        assert!(
483            md.contains(&format!("**Review mark:** `{reviewed}`")),
484            "roster must carry the mark value: {md}"
485        );
486        assert!(
487            md.contains("head is at the mark"),
488            "at-mark indicator missing: {md}"
489        );
490
491        // Head moves past the mark: the indicator flips and names the
492        // composition path (changes_since with the mark's cursor).
493        engine
494            .create_entity(
495                crate::CreateEntityArgs {
496                    mem: "specs".to_string(),
497                    title: "Past The Mark Roster".to_string(),
498                    entity_type: "spec".to_string(),
499                    sections: [
500                        ("identity".to_string(), "x".to_string()),
501                        ("purpose".to_string(), "y".to_string()),
502                    ]
503                    .into_iter()
504                    .collect(),
505                    metadata: Default::default(),
506                    relations: Vec::new(),
507                    anchors: Vec::new(),
508                    dry_run: false,
509                },
510                crate::vcs::Actor::App,
511                None,
512                Some("agent work"),
513            )
514            .unwrap();
515        let md = overview_md(&mut engine);
516        assert!(
517            md.contains("head has moved past the mark") && md.contains("changes_since"),
518            "unreviewed indicator missing: {md}"
519        );
520    }
521}