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 mut warnings = self.reload_if_stale(Some(mem_name));
101        if let Some(w) = self.note_missing_warning("set_review_mark", note) {
102            warnings.push(w);
103        }
104
105        // `previous` comes from the config this write lands on, not the
106        // cache: a sibling reviewer may have moved the mark since boot, and
107        // reporting the cached value would name a mark nobody is at.
108        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
109        let target_owned = target.map(str::to_string);
110        let (_, intervened) = self.write_mem_config_merged(
111            mount_idx,
112            mem_name,
113            "set_review_mark",
114            note,
115            &|c: &mut memstead_schema::config::MemConfig| {
116                *seen.borrow_mut() = c.review_mark.clone();
117                c.review_mark = target_owned.clone();
118            },
119        )?;
120        let previous = seen.into_inner();
121        if !intervened.is_empty() {
122            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
123                mem: mem_name.to_string(),
124                fields: intervened,
125            });
126        }
127
128        Ok(SetReviewMarkOutcome {
129            mem: mem_name.to_string(),
130            mark: target.map(str::to_string),
131            previous,
132            warnings,
133        })
134    }
135
136    /// The accumulated per-entity delta from the mem's review mark to
137    /// its current head — exactly the envelopes `changes_since`
138    /// reports for the mark's cursor. A markless mem refuses with
139    /// `REVIEW_MARK_NOT_SET` (marklessness is known from the roster; a
140    /// silent empty answer would equate "no mark" with "no changes").
141    pub fn review_mark_diff(
142        &self,
143        mem_name: &str,
144        rename_similarity: Option<f32>,
145    ) -> Result<crate::ops::ChangesReport, EngineError> {
146        let mount = self
147            .mounts
148            .iter()
149            .find(|m| m.mount.mem == mem_name)
150            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
151        let mark = mount
152            .mem_config
153            .as_ref()
154            .and_then(|c| c.review_mark.clone())
155            .ok_or_else(|| EngineError::ReviewMarkNotSet {
156                mem: mem_name.to_string(),
157            })?;
158        self.changes_since(mem_name, &mark, rename_similarity)
159    }
160
161    /// Backend-vocabulary validation for an explicit mark target.
162    fn validate_review_cursor(
163        &self,
164        mount_idx: usize,
165        mem_name: &str,
166        target: &str,
167    ) -> Result<(), EngineError> {
168        use crate::workspace::MountStorage;
169        let invalid = || EngineError::InvalidChangesCursor {
170            mem: mem_name.to_string(),
171            since: target.to_string(),
172        };
173        match &self.mounts[mount_idx].mount.storage {
174            MountStorage::Folder { .. } => {
175                // Folder cursors are the changelog's RFC3339-millis
176                // timestamps; format-level validation (existence is not
177                // required — any parseable instant is a legal `since`).
178                if crate::filesystem::changelog::parse_rfc3339_utc(target).is_none() {
179                    return Err(invalid());
180                }
181                Ok(())
182            }
183            MountStorage::GitBranch { .. } => {
184                // A git-branch cursor must resolve to a known commit —
185                // `changes_since` is the authoritative resolver and
186                // already refuses unknown SHAs with INVALID_CURSOR.
187                self.changes_since(mem_name, target, None).map(|_| ())
188            }
189            MountStorage::Archive { .. } | MountStorage::InMemory => {
190                // Unreachable through set (capability gate refuses
191                // first); refuse defensively for direct callers.
192                Err(invalid())
193            }
194        }
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use crate::backend::MemBackend;
201
202    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";
203
204    fn folder_engine(tmp: &tempfile::TempDir) -> crate::Engine {
205        let dir = tmp.path().join("specs");
206        if !dir.exists() {
207            std::fs::create_dir_all(&dir).unwrap();
208            let writer = crate::storage::FilesystemBackend::new(dir.clone());
209            MemBackend::write_entity(&writer, std::path::Path::new("seed.md"), SEED.as_bytes())
210                .unwrap();
211            MemBackend::commit(&writer, "seed", &crate::vcs::CommitContext::internal()).unwrap();
212            crate::backend::MemBackend::append_provenance(
213                &writer,
214                &crate::provenance::Provenance::new(
215                    std::time::SystemTime::now(),
216                    crate::provenance::ProvenanceKind::Create,
217                    Some("specs--seed".into()),
218                    crate::vcs::Actor::Cli,
219                    None,
220                    None,
221                ),
222            )
223            .unwrap();
224            // A config file so set_review_mark has a MemConfig to carry
225            // the mark (mirrors an initialized mem).
226            let config = memstead_schema::config::MemConfig {
227                format: None,
228                name: None,
229                title: None,
230                subject: None,
231                version: None,
232                description: None,
233                authors: None,
234                schema: Some("default@1.0.0".parse().unwrap()),
235                write_guidance: Default::default(),
236                process_mem: None,
237                rules: None,
238                publish: None,
239                language: None,
240                read_mems: Default::default(),
241                community: None,
242                vcs: None,
243                unregistered_at: None,
244                sync_state: Default::default(),
245                review_mark: None,
246                mutation_stamp: None,
247                forked_from: None,
248                extra: Default::default(),
249            };
250            let meta = dir.join(memstead_schema::MEM_META_DIR);
251            std::fs::create_dir_all(&meta).unwrap();
252            std::fs::write(
253                meta.join("config.json"),
254                serde_json::to_vec_pretty(&config).unwrap(),
255            )
256            .unwrap();
257        }
258        let mount = crate::Mount {
259            mem: "specs".to_string(),
260            schema: Some(memstead_schema::SchemaRef::new(
261                "default",
262                semver::Version::new(1, 0, 0),
263            )),
264            storage: crate::MountStorage::Folder { path: dir.clone() },
265            capability: crate::MountCapability::Write,
266            lifecycle: crate::MountLifecycle::Eager,
267            cross_linkable: false,
268            migration_target: None,
269        };
270        let backend =
271            Box::new(crate::storage::FilesystemBackend::new(dir)) as Box<dyn crate::MemBackend>;
272        crate::Engine::from_mounts(vec![(mount, backend)]).unwrap()
273    }
274
275    fn head(engine: &crate::Engine) -> String {
276        engine
277            .review_marks()
278            .into_iter()
279            .find(|s| s.mem == "specs")
280            .and_then(|s| s.head)
281            .expect("folder head cursor")
282    }
283
284    #[test]
285    fn mark_lifecycle_persists_validates_and_never_gates() {
286        let tmp = tempfile::TempDir::new().unwrap();
287        let mut engine = folder_engine(&tmp);
288
289        // Markless start: ordinary state, listed as such.
290        let status = &engine.review_marks()[0];
291        assert_eq!(status.mem, "specs");
292        assert!(status.mark.is_none());
293        assert!(status.writable);
294
295        // Invalid cursor refuses typed, mark untouched.
296        let err = engine
297            .set_review_mark("specs", Some("not-a-timestamp"), None)
298            .unwrap_err();
299        assert_eq!(err.code(), "INVALID_CURSOR");
300        assert!(engine.review_marks()[0].mark.is_none());
301        // Unknown mem refuses typed.
302        let err = engine.set_review_mark("ghost", None, None).unwrap_err();
303        assert_eq!(err.code(), "UNKNOWN_MEM");
304
305        // Markless diff refuses typed — never a silent empty answer.
306        let err = engine.review_mark_diff("specs", None).unwrap_err();
307        assert_eq!(err.code(), "REVIEW_MARK_NOT_SET");
308
309        // Set to the reviewed head; diff-since is now empty.
310        let reviewed = head(&engine);
311        let outcome = engine
312            .set_review_mark("specs", Some(&reviewed), Some("reviewed everything"))
313            .unwrap();
314        assert_eq!(outcome.mark.as_deref(), Some(reviewed.as_str()));
315        assert!(outcome.previous.is_none());
316        let diff = engine.review_mark_diff("specs", None).unwrap();
317        assert!(diff.changes.is_empty(), "reviewed head → empty: {diff:?}");
318
319        // A mutation past the mark succeeds with no mark-related
320        // warning (marks never gate) — and diff-since accumulates it,
321        // matching changes_since for the mark's cursor.
322        let outcome = engine
323            .create_entity(
324                crate::CreateEntityArgs {
325                    mem: "specs".to_string(),
326                    title: "Past The Mark".to_string(),
327                    entity_type: "spec".to_string(),
328                    sections: [
329                        ("identity".to_string(), "x".to_string()),
330                        ("purpose".to_string(), "y".to_string()),
331                    ]
332                    .into_iter()
333                    .collect(),
334                    metadata: Default::default(),
335                    relations: Vec::new(),
336                    anchors: Vec::new(),
337                    dry_run: false,
338                },
339                crate::vcs::Actor::App,
340                None,
341                Some("agent work"),
342            )
343            .unwrap();
344        assert!(
345            outcome
346                .warnings
347                .iter()
348                .all(|w| !format!("{w:?}").to_lowercase().contains("mark")),
349            "marks never gate or warn: {:?}",
350            outcome.warnings
351        );
352        let diff = engine.review_mark_diff("specs", None).unwrap();
353        assert_eq!(diff.changes.len(), 1, "{diff:?}");
354        let direct = engine.changes_since("specs", &reviewed, None).unwrap();
355        assert_eq!(
356            serde_json::to_value(&diff.changes).unwrap(),
357            serde_json::to_value(&direct.changes).unwrap(),
358            "diff-since must equal changes_since at the mark"
359        );
360
361        // Persistence across engine restarts (separate instance, same
362        // workspace) — the sibling-visibility half.
363        drop(engine);
364        let mut second = folder_engine(&tmp);
365        assert_eq!(
366            second.review_marks()[0].mark.as_deref(),
367            Some(reviewed.as_str()),
368            "the mark is mem-repo state"
369        );
370
371        // Clear returns to markless.
372        let outcome = second.set_review_mark("specs", None, None).unwrap();
373        assert_eq!(outcome.previous.as_deref(), Some(reviewed.as_str()));
374        assert!(second.review_marks()[0].mark.is_none());
375    }
376
377    #[test]
378    fn noteless_set_under_require_notes_warns_and_commits() {
379        let tmp = tempfile::TempDir::new().unwrap();
380        let mut engine = folder_engine(&tmp);
381        engine.set_settings(crate::WorkspaceSettings {
382            mutations: crate::workspace::MutationsSection {
383                require_notes: Some(true),
384            },
385            ..Default::default()
386        });
387        let reviewed = head(&engine);
388        let outcome = engine
389            .set_review_mark("specs", Some(&reviewed), None)
390            .unwrap();
391        assert!(
392            outcome.warnings.iter().any(
393                |w| matches!(w, crate::ops::WarningHint::NoteMissing { tool } if tool == "set_review_mark")
394            ),
395            "warn-and-commit: {:?}",
396            outcome.warnings
397        );
398        assert_eq!(outcome.mark.as_deref(), Some(reviewed.as_str()));
399    }
400
401    #[test]
402    fn published_projection_strips_the_mark() {
403        // The PublishedMemConfig allowlist strips everything it does
404        // not name — pin that the mark stays out (the
405        // structural half; the export round-trip rides the exporter's
406        // own tests).
407        let mut config = memstead_schema::config::MemConfig {
408            format: None,
409            name: None,
410            title: None,
411            subject: None,
412            version: Some(semver::Version::new(1, 0, 0)),
413            description: None,
414            authors: None,
415            schema: Some("default@1.0.0".parse().unwrap()),
416            write_guidance: Default::default(),
417            process_mem: None,
418            rules: None,
419            publish: None,
420            language: None,
421            read_mems: Default::default(),
422            community: None,
423            vcs: None,
424            unregistered_at: None,
425            sync_state: Default::default(),
426            review_mark: None,
427            mutation_stamp: None,
428            forked_from: None,
429            extra: Default::default(),
430        };
431        config.review_mark = Some("deadbeef".to_string());
432        let published = memstead_schema::config::published_config_from(&config, "specs").unwrap();
433        let json = serde_json::to_string(&published).unwrap();
434        assert!(
435            !json.contains("reviewMark") && !json.contains("deadbeef"),
436            "published config must strip the mark: {json}"
437        );
438    }
439
440    #[test]
441    fn overview_roster_carries_the_mark_and_its_indicator() {
442        // The agents' cold-start read (overview `## Mems`) is a
443        // per-mem summary surface: a set mark rides it with the
444        // mark≠head indicator, a markless mem stays unmarked (ordinary
445        // state, never flagged).
446        let tmp = tempfile::TempDir::new().unwrap();
447        let mut engine = folder_engine(&tmp);
448        let overview_md = |engine: &mut crate::Engine| {
449            crate::overview::compose_overview(
450                engine,
451                crate::overview::OverviewArgs {
452                    include: &[],
453                    mem: None,
454                    rebuild: false,
455                    token_budget: 8000,
456                    operator_mode: false,
457                    suppress_lifecycle: false,
458                },
459                crate::overview::Surface::Mcp,
460            )
461            .unwrap()
462            .markdown
463        };
464
465        // Markless: no mark line anywhere.
466        let md = overview_md(&mut engine);
467        assert!(
468            !md.contains("Review mark"),
469            "markless roster must not mention marks: {md}"
470        );
471
472        // Mark at head: the line appears, indicator says at-mark.
473        let reviewed = head(&engine);
474        engine
475            .set_review_mark("specs", Some(&reviewed), Some("reviewed"))
476            .unwrap();
477        let md = overview_md(&mut engine);
478        assert!(
479            md.contains(&format!("**Review mark:** `{reviewed}`")),
480            "roster must carry the mark value: {md}"
481        );
482        assert!(
483            md.contains("head is at the mark"),
484            "at-mark indicator missing: {md}"
485        );
486
487        // Head moves past the mark: the indicator flips and names the
488        // composition path (changes_since with the mark's cursor).
489        engine
490            .create_entity(
491                crate::CreateEntityArgs {
492                    mem: "specs".to_string(),
493                    title: "Past The Mark Roster".to_string(),
494                    entity_type: "spec".to_string(),
495                    sections: [
496                        ("identity".to_string(), "x".to_string()),
497                        ("purpose".to_string(), "y".to_string()),
498                    ]
499                    .into_iter()
500                    .collect(),
501                    metadata: Default::default(),
502                    relations: Vec::new(),
503                    anchors: Vec::new(),
504                    dry_run: false,
505                },
506                crate::vcs::Actor::App,
507                None,
508                Some("agent work"),
509            )
510            .unwrap();
511        let md = overview_md(&mut engine);
512        assert!(
513            md.contains("head has moved past the mark") && md.contains("changes_since"),
514            "unreviewed indicator missing: {md}"
515        );
516    }
517}