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